Beispiel #1
0
function upperCaseAuthors($xml)
{
    do {
        $aut = getContent('author', $xml);
        if (strlen($aut) > 0) {
            $names = explode(',', $aut);
            $upperCaseAuthorsXML = '<AUTHOR key="' . $aut . '" SEARCH="' . str_replace(',', ',+', strtoupper(removeAccent(str_replace(' ', '+', $aut)))) . '"><NAME>' . $names[1] . '</NAME><SURNAME>' . $names[0] . '</SURNAME><UPP_NAME>' . strtoupper($names[1]) . '</UPP_NAME><UPP_SURNAME>' . strtoupper($names[0]) . '</UPP_SURNAME></AUTHOR>';
            $xml = str_replace('<author>' . $aut . '</author>', $upperCaseAuthorsXML, $xml);
        }
    } while (strlen($aut) > 0);
    return $xml;
}
function removeTitle($string, $keyReplace = "/")
{
    $string = removeAccent($string);
    $string = trim(preg_replace("/[^A-Za-z0-9]/i", " ", $string));
    // khong dau
    $string = str_replace(" ", "-", $string);
    $string = str_replace("--", "-", $string);
    $string = str_replace("--", "-", $string);
    $string = str_replace("--", "-", $string);
    $string = str_replace("--", "-", $string);
    $string = str_replace("--", "-", $string);
    $string = str_replace("--", "-", $string);
    $string = str_replace("--", "-", $string);
    $string = str_replace($keyReplace, "-", $string);
    return strtolower($string);
}
Beispiel #3
0
 function add_Field_Seach($field_name, $arrayField = array())
 {
     $temp = '';
     if (count($arrayField) > 0) {
         foreach ($arrayField as $key => $value) {
             if (intval($value) == 0) {
                 if (isset($_POST[$key])) {
                     $temp .= $_POST[$key] . ' ';
                 }
             }
             if (intval($value) == 1) {
                 $temp_var = $key;
                 global ${$temp_var};
                 $temp .= ${$temp_var} . ' ';
             }
         }
     }
     $temp = str_replace("\\'", "'", $temp);
     $temp = str_replace("'", "''", $temp);
     $temp = $this->removeTagHtml($temp);
     $temp = mb_strtolower($temp, "UTF-8");
     $temp = str_replace(chr(13), "", $temp);
     $temp = str_replace("  ", " ", $temp);
     $temp = str_replace("  ", " ", $temp);
     $temp = str_replace("  ", " ", $temp);
     $temp = str_replace("  ", " ", $temp);
     $temp = str_replace("  ", " ", $temp);
     $temp = str_replace("  ", " ", $temp);
     $temp = $temp . ' ' . removeAccent($temp);
     $this->number_of_field++;
     $this->array_data_field[$this->number_of_field] = $field_name;
     $this->array_data_value[$this->number_of_field] = 'not from post';
     $this->array_data_type[$this->number_of_field] = 0;
     $this->array_data_store[$this->number_of_field] = 0;
     $this->array_data_default_value[$this->number_of_field] = $temp;
     $this->array_data_require[$field_name] = 0;
     $this->array_data_error_message[$this->number_of_field] = "";
     $this->array_data_unique[$this->number_of_field] = 0;
     $this->array_data_error_message2[$this->number_of_field] = "";
     unset($temp);
 }
function removeTitle($string,$keyReplace){
	$string		= html_entity_decode($string, ENT_COMPAT, 'UTF-8');
	$string		= mb_strtolower($string, 'UTF-8');
	$string		= removeAccent($string);
	//neu muon de co dau
	//$string 	=  trim(preg_replace("/[^A-Za-z0-9àáạảãâầấậẩẫăằắặẳẵèéẹẻẽêềếệểễìíịỉĩòóọỏõôồốộổỗơờớợởỡùúụủũưừứựửữỳýỵỷỹđÀÁẠẢÃÂẦẤẬẨẪĂẰẮẶẲẴÈÉẸẺẼÊỀẾỆỂỄÌÍỊỈĨÒÓỌỎÕÔỒỐỘỔỖƠỜỚỢỞỠÙÚỤỦŨƯỪỨỰỬỮỲÝỴỶỸ]/i"," ",$string));

	$string 	= trim(preg_replace("/[^A-Za-z0-9]/i"," ",$string)); // khong dau
	$string 	= str_replace(" ","-",$string);
	$string		= str_replace("--","-",$string);
	$string		= str_replace("--","-",$string);
	$string		= str_replace("--","-",$string);
	$string		= str_replace($keyReplace,"-",$string);
	return $string;
}
Beispiel #5
0
 $myform->add('cdi_doi_tuong', 'cdi_doi_tuong', 0, 1, '');
 $cdi_theo_mua = getValue('cdi_theo_mua', 'arr', 'POST', array());
 $cdi_theo_mua = array_unique($cdi_theo_mua);
 $cdi_theo_mua = implode(',', $cdi_theo_mua);
 $myform->add('cdi_theo_mua', 'cdi_theo_mua', 0, 1, '');
 //update trường keyword search
 $cdi_search = '';
 $field_search = getValue('cdi_name', 'str', 'POST', '', 3);
 $cdi_search .= $field_search;
 $field_search = getValue('cdi_name_alias', 'str', 'POST', '', 3);
 $cdi_search .= $field_search;
 $field_search = getValue('cdi_tag', 'str', 'POST', '', 3);
 $cdi_search .= $field_search;
 $cdi_search = mb_strtolower($cdi_search, 'utf8');
 $cdi_search = removeSpecialChar($cdi_search);
 $cdi_search = $cdi_search . ' ' . removeAccent($cdi_search);
 $myform->add('cdi_search', 'cdi_search', 0, 1, '');
 //Count word và count char từ trường tên
 $cdi_name = getValue('cdi_name', 'str', 'POST', '', 3);
 $cdi_count_word = count(explode(' ', $cdi_name));
 $cdi_count_char = strlen($cdi_name);
 $myform->add('cdi_count_word', 'cdi_count_word', 1, 1, 0);
 $myform->add('cdi_count_char', 'cdi_count_char', 1, 1, 0);
 if (!$bg_errorMsg) {
     $db_update = new db_execute($myform->generate_update_SQL($id_field, $record_id));
     unset($db_update);
     /**
      * something code here
      */
     //update to disease_section
     $array_sec = getValue('cdi_sec_id', 'arr', 'POST', array());
Beispiel #6
0
 public function configReportProfile($type = 'pdf', $options = false, $config)
 {
     set_time_limit(3200);
     $columns = $this->getColumns();
     /**
      * Configuração do estilos padrão
      */
     $dnsEmpresas = array();
     $dnsEmpresas['tanet.com.br'] = 'TA';
     $dnsEmpresas['talog.com.br'] = 'TAL';
     $dnsEmpresas['taexpress.com.br'] = 'TAE';
     $dnsEmpresas['windexpress.com.br'] = 'TAE';
     $dnsEmpresas['tawind.com.br'] = 'TAE';
     $domain = ZendT_Url::getDomain();
     $empresa = 'TA';
     if (isset($dnsEmpresas[$domain])) {
         $empresa = $dnsEmpresas[$domain];
     }
     $nameReport = $config['title'];
     $nameReport = removeAccent($nameReport);
     $nameReport = trim(str_replace(' ', '-', $nameReport));
     $default = array('title' => array('fontSize' => 10, 'bold' => true, 'width' => 160, 'align' => 'center', 'value' => utf8_decode($config['title'])), 'default' => array('fontSize' => 7, 'bold' => false, 'fontName' => 'Arial'), 'cellsTitle' => array('fontSize' => 7, 'bold' => true, 'align' => 'center'), 'empresa' => $empresa, 'maxPerLine' => 4, 'orientation' => 'P');
     if (is_array($options)) {
         $options = ZendT_Functions::array_merge_recursive_distinct($default, $options);
     } else {
         $options = $default;
     }
     if (is_array($options['title'])) {
         $options['title'] = new ZendT_Report_Cell($options['title']);
         $options['title']->setStyleName('title');
     }
     if (is_array($options['footer'])) {
         $options['footer'] = new ZendT_Report_Cell($options['footer']);
         $options['footer']->setStyleName('footer');
     }
     /**
      * Tratamento para buscar os dados no banco de dados
      */
     $logReport = new ZendT_Log_Report($mapperView, $config['title']);
     $medida = array();
     $cols = $config['cols-detail']['fields'];
     $filters = $config['cols-filter']['fields'];
     foreach ($columns as $column) {
         $name = $column->getName();
         if (isset($cols[$name])) {
             if ($cols[$name]['align']) {
                 $column->setAlign($cols[$name]['align']);
             }
             if ($cols[$name]['label']) {
                 $column->setLabel($cols[$name]['label']);
             }
             if ($cols[$name]['width']) {
                 $column->setWidth($cols[$name]['width']);
             }
         }
     }
     /**
      * Recupera todas as sumarizações e quebras de processo para os breakers informados
      */
     foreach ($config['cols-break']['fields'] as $colBreak => $configBreak) {
         if ($config['break-header-' . $colBreak]) {
             $break['header'][$colBreak] = $config['break-header-' . $colBreak]['fields'];
         }
         if ($config['break-measure-' . $colBreak]) {
             $break['measure'][$colBreak] = $config['break-measure-' . $colBreak]['fields'];
         }
     }
     /**
      * Monta o Filtro com Base no Profile
      */
     $postData = $this->getRequest()->getParams();
     $postData['page'] = false;
     $postData['count'] = false;
     if ($filters) {
         $this->getRequest()->setParam('_search', 'true');
         $postData = $this->getRequest()->getParams();
         /**
          * @todo Enviar o nome correto das colunas para o formulário, desde que o formulário aceite pontuações na nomenclatura das colunas
          */
         foreach ($columns as $column) {
             if ($postData[$column->getName()]) {
                 $field = str_replace('.', '-', $column->getIndex());
                 $value = $postData[$column->getName()];
                 $this->getRequest()->setParam($field, $value);
                 unset($postData[$column->getName()]);
             }
         }
     }
     $whereGroup = $this->getWherePostData();
     if ($this->_mapper instanceof ZendT_Db_View) {
         $dataGrid = $this->getMapper()->getDataGrid($whereGroup, $postData);
     } else {
         $dataGrid = $this->getModel()->getDataGrid($whereGroup, $postData);
     }
     /**
      * Instancia do objeto de relatório
      */
     $report = ZendT_Report::factory($type, $options);
     $report->addPage();
     /**
      * Recupera a estrutura do GRID
      */
     $row = $dataGrid->getRow();
     $logReport->finishDb();
     if (!$row) {
         throw new ZendT_Exception_Alert('Dados não encontrados!');
     }
     /**
      * Recupera o valor de Quebra inicial
      */
     $breaker = array();
     foreach ($row as $alias => $val) {
         if (in_array($alias, array_keys($break['header']))) {
             $breaker[$alias] = $row[$alias]->toPhp();
         }
     }
     $keysBreaker = array_keys($breaker);
     /**
      * Configuração da coluna de título
      */
     $celulas = array();
     /**
      * Colunas Breaker
      */
     $colsBreaker = array();
     foreach ($columns as $column) {
         $key = $column->getName();
         if (in_array($key, $keysBreaker)) {
             $colsBreaker[] = $column;
         }
     }
     /**
      * Colunas Detalhes
      */
     $colsDetail = array();
     $celulas = array();
     foreach ($columns as $column) {
         if (!$column->getHidden()) {
             $key = $column->getName();
             if (!in_array($key, array_keys($cols))) {
                 $column->setHidden(true);
                 continue;
             } else {
                 $column->setHeaderTitle($cols[$key]['label']);
             }
             $colsDetail[] = $column;
         }
     }
     /**
      * Impressão dos registros detalhe
      */
     $callStylesRow = method_exists($this->getMapper(), 'getStylesRow');
     $celulas = array();
     /**
      * Preenche as células com os valores da consulta
      */
     $this->setReportHeader($colsBreaker, $breaker, $colsDetail, $report, $options);
     $numRows = 0;
     do {
         $stylesRow = array();
         if ($callStylesRow) {
             $stylesRow = $this->getMapper()->getStylesRow($row);
         }
         foreach ($keysBreaker as $alias) {
             if ($breaker[$alias] != $row[$alias]->toPhp()) {
                 /**
                  *  Imprimir Sumarizações
                  */
                 foreach ($columns as $column) {
                     if ($column->getHidden()) {
                         continue;
                     }
                     $key = $column->getName();
                     if (!isset($cell[$key])) {
                         $cell[$key] = new ZendT_Report_Cell($options['cellsTitle']);
                         $cell[$key]->setTextAlign($column->getAlign())->setWidth($column->getWidth())->setType($row[$alias]->getType())->setStyleName('cellsTitle-' . $key);
                     }
                     if (isset($medida[$alias][$key]['value'])) {
                         $value = number_format($medida[$alias][$key]['value'], 2, ',', '.');
                         $cell[$key]->setValue($value);
                     } else {
                         $cell[$key]->setValue('');
                     }
                     $report->addCell($cell[$key]);
                     $medida[$alias][$key]['value'] = '';
                     $medida[$alias][$key]['sum'] = 0;
                     $medida[$alias][$key]['count'] = 0;
                 }
                 /**
                  * Atualiza o Breaker atual
                  */
                 $breaker[$alias] = $row[$alias]->toPhp();
                 /**
                  * Renderiza os dados
                  */
                 $report->drawLine();
                 $report->printCells();
                 $report->ln();
                 $this->setReportHeader($colsBreaker, $breaker, $colsDetail, $report, $options);
             }
         }
         foreach ($columns as $column) {
             if (!$column->getHidden()) {
                 $key = $column->getName();
                 $cellOptions = $column->getOptions();
                 /**
                  * Sumarizações
                  */
                 foreach ($keysBreaker as $alias) {
                     if ($break['measure'][$alias][$key] != '') {
                         if ($break['measure'][$alias][$key]['tipo'] == 'count') {
                             $medida[$alias][$key]['value'] += 1;
                         }
                         if ($break['measure'][$alias][$key]['tipo'] == 'sum') {
                             $medida[$alias][$key]['value'] += $row[strtolower($key)]->toPhp();
                         }
                         if ($break['measure'][$alias][$key]['tipo'] == 'avg') {
                             $medida[$alias][$key]['sum'] += $row[strtolower($key)]->toPhp();
                             $medida[$alias][$key]['count'] += 1;
                             $medida[$alias][$key]['value'] = $medida[$alias][$key]['sum'] / $medida[$alias][$key]['count'];
                         }
                     }
                 }
                 if ($dataGrid->getType()) {
                     $value = $row[strtolower($key)];
                     $type = $value->getType();
                     if (isset($cellOptions['expandTree'])) {
                         $newValue = $value->get();
                         $newValue = str_repeat(' ', $row['tree_level']->toPhp() * 4) . $newValue;
                         $value->set($newValue);
                     }
                 } elseif ($dataGrid->isRowFormated()) {
                     $value = $row[strtolower($key)];
                     $type = $column->getSorttype();
                 } else {
                     $value = $column->format($row[strtolower($key)]);
                     $type = $column->getSorttype();
                 }
                 $celName = $key;
                 if (isset($stylesRow[$key])) {
                     if (!$stylesRow[$key]['suffix']) {
                         $stylesRow[$key]['suffix'] = 'plus';
                     }
                     $celName .= '-' . $stylesRow[$key]['suffix'];
                 }
                 if (!isset($celulas[$celName])) {
                     $celulas[$celName] = new ZendT_Report_Cell($options['default']);
                     $celulas[$celName]->setTextAlign($column->getAlign())->setWidth($column->getWidth())->setType($type);
                     $celulas[$celName]->setStyleName('default-' . $celName);
                     if (isset($stylesRow[$key])) {
                         $celulas[$celName]->setStyles($stylesRow[$key]);
                     }
                 }
                 $celulas[$celName]->setValue($value);
                 $report->addCell($celulas[$celName]);
             }
         }
         $report->printCells();
         $numRows++;
     } while ($row = $dataGrid->getRow());
     /**
      * @author marquesini
      * @todo Renderizar apenas se o último breaker não foi sumarizado
      */
     foreach ($keysBreaker as $alias) {
         /**
          *  Imprimir Sumarizações
          */
         foreach ($columns as $column) {
             if ($column->getHidden()) {
                 continue;
             }
             $key = $column->getName();
             if (isset($cell[$key])) {
                 if ($medida[$alias][$key]['value'] != '') {
                     $value = number_format($medida[$alias][$key]['value'], 2, ',', '.');
                     $cell[$key]->setValue($value);
                 } else {
                     $cell[$key]->setValue('');
                 }
                 $report->addCell($cell[$key]);
             }
         }
         /**
          * Renderiza os dados
          */
         $report->drawLine();
         $report->printCells();
         $report->ln();
     }
     $report->printCells();
     $logReport->finish($numRows);
     /**
      * Impressão/Saída do relatório
      */
     return array('name' => $nameReport, 'content' => $report->output($nameReport, 'S'));
 }
Beispiel #7
0
 public function generate($limit = 10, $min_word = 1)
 {
     $keywords = $this->extract_keywords();
     $bad_words = explode(',', self::BAD_WORDS);
     $bad_words = array_map('trim', $bad_words);
     $keywords = array_slice($keywords, 0, $limit);
     $keywords = $this->google_trends($keywords);
     foreach ($keywords as $key => $keyword) {
         //$keyword_lower = mb_strtolower($keyword);
         foreach ($bad_words as $bad_word) {
             $keyword_lower = removeAccent($keyword);
             $keyword_lower = strtolower($keyword_lower);
             $bad_word = removeAccent($bad_word);
             if (strpos(' ' . $keyword_lower . ' ', $bad_word)) {
                 unset($keywords[$key]);
                 break;
             }
         }
         //Lọc các từ có bao nhiêu ký tự
         if ($min_word >= 2) {
             $count_word = explode(' ', $keyword);
             if (count($count_word) < $min_word) {
                 unset($keywords[$key]);
             }
         }
     }
     if ($keywords && !empty($keywords)) {
         $keywords = array_unique($keywords);
         $keywords = $this->sort_keywords($keywords);
         $keywords = array_filter($keywords);
         return array_slice($keywords, 0, $limit);
     }
     return array();
 }
Beispiel #8
0
function editEntrySubmit()
{
    global $separator, $newPostFile, $newFullPostNumber, $config, $debugMode, $authors, $authorsPass;
    global $optionValue, $lang, $theme_main, $SHP, $public_data, $blogPath;
    $theme_main['content'] = "";
    if ($debugMode == "on") {
        $theme_main['content'] .= "Inside editEntrySubmit .." . $_POST['fileName'] . "<br>";
    }
    $theme_main['content'] .= "<h3>" . $lang['pageEdit'] . "...</h3>";
    unset($GLOBALS['$public_data']);
    $public_data['entryName'] = $entryName = $_POST['fileName'];
    $public_data['postTitle'] = $postTitle = htmlentities(sqlite_escape_string(str_replace("\\", "", $_POST["title"])));
    $public_data['postContent'] = $postContent = htmlentities(sqlite_escape_string(str_replace("\\", "", $_POST["posts"])));
    $public_data['postDate'] = $postDate = date("Y-m-d H:i:s");
    $public_data['isPage'] = $isPage = isset($_POST["isPage"]) ? $_POST["isPage"] : 0;
    $public_data['stick'] = $stick = isset($_POST["isSticky"]) ? $_POST["isSticky"] : "no";
    $public_data['status'] = $status = isset($_POST["isDraft"]) ? $_POST["isDraft"] : 1;
    $public_data['allowComments'] = $allowComments = isset($_POST["allowComments"]) ? $_POST["allowComments"] : "no";
    $public_data['visits'] = $visits = isset($_POST["visits"]) ? $_POST["visits"] : 0;
    $public_data['postCategory'] = $postCategory = htmlentities(sqlite_escape_string(removeAccent(strtolower($_POST["category"]))));
    $public_data['thisAuthor'] = $thisAuthor = $_POST['author'];
    $thisPass = $_POST['pass'];
    $do = 1;
    unset($listcats);
    foreach (explode(",", $postCategory) as $singlecat) {
        $listcats[$singlecat] = "1";
    }
    $catsep = "";
    $postCategory = "";
    foreach ($listcats as $catkey => $catvalue) {
        $postCategory .= $catsep . trim($catkey);
        $catsep = ",";
    }
    if ($SHP->hooks_exist('hook-editsubmit-before')) {
        $SHP->execute_hooks('hook-editsubmit-before');
    }
    if (trim($postTitle) == '' || trim($postContent) == '' || trim($postCategory) == '' || strstr($postCategory, '.')) {
        $theme_main['content'] .= $lang['errorAllFields'] . '.<br>';
        $theme_main['content'] .= $lang['errorCatName'] . '<br>';
        $do = 0;
    }
    if ($do == 1) {
        if ($isPage == 1) {
            $public_data['postType'] = $postType = "page";
        } else {
            $public_data['postType'] = $postType = "post";
        }
        if ($debugMode == "on") {
            echo "Writing to " . $fileName;
        }
        $errorMessage = '<br><span style="color: rgb(204, 0, 51);">' . $lang['errornewPostFile'] . '<br>';
        $errorMessage = $errorMessage . '<br>' . $lang['errorReportBug'] . '<br>';
        if ($_SESSION['logged_in']) {
            if ($SHP->hooks_exist('hook-editsubmit-validate')) {
                $SHP->execute_hooks('hook-editsubmit-validate', $public_data);
            }
            $postCategory = str_replace(" ", "_", $postCategory);
            $content = $postTitle . $separator . str_replace("\\", "", $postContent) . $separator . $postDate . $separator . $entryName . $separator . $postCategory . $separator . $postType . $separator . $allowComments . $separator . $visits . $separator . $thisAuthor;
            sqlite_query($config['db'], "UPDATE posts SET title='{$postTitle}', content='{$postContent}', category='{$postCategory}', type='{$postType}', stick='{$stick}', status = '{$status}', allowcomments='{$allowComments}', visits='{$visits}', author='{$thisAuthor}' WHERE postid='{$entryName}';");
            $theme_main['content'] .= $lang['msgEditSuccess'] . ' .. <a href="' . $_SESSION['referrer'] . '">' . $lang['msgGoBack'] . '</a> .. <a href="' . $blogPath . '">' . $lang['msgGoHome'] . '</a>';
            if ($SHP->hooks_exist('hook-editsubmit-after')) {
                $SHP->execute_hooks('hook-editsubmit-after');
            }
        } else {
            $theme_main['content'] .= $lang['errorNotAuthorized'] . ' .. <br>';
        }
    } else {
        $theme_main['content'] .= $lang['errorPleaseGoBack'];
    }
}
Beispiel #9
0
 private function _getConfigDashboard($row)
 {
     //$_mapper = $this->_loadMapper($row['objeto']->get());
     $_profile = new ZendT_Profile();
     $profiles = $_profile->listProfile($row['objeto']->get());
     $columns = array();
     foreach ($profiles as $id => $profile) {
         $name = 'view-' . $id . '-' . str_replace(' ', '_', strtolower(removeAccent($profile['nome'])));
         if ($profile['tipo'] != 'B') {
             $columns[$name]['label'] = $profile['nome'];
             $columns[$name]['width'] = 300;
             $columns[$name]['order'] = null;
             $columns[$name]['align'] = 'left';
             $columns[$name]['column'] = $id;
             $columns[$name]['id'] = $id;
             $columns[$name]['type'] = null;
         }
     }
     $config = unserialize(html_entity_decode($row['config']->get()));
     /**
      * 
      */
     if (!isset($config['cols-panel'])) {
         $config = array('cols-panel' => array('name' => 'cols-panel', 'label' => 'Painel de Visões', 'draggable' => 0, 'fields' => array()), 'cols-filter' => array('name' => 'cols-filter', 'label' => 'Painel de Filtros', 'draggable' => 1, 'fields' => array()));
     }
     /**
      * Ordena as colunas 
      */
     if ($config) {
         foreach ($config as $key => $value) {
             unset($columns[$key]);
         }
     }
     /**
      * Adiciona as novas colunas ou as que não foram configuradas
      */
     foreach ($columns as $name => $column) {
         if ($columns[$name]['label']) {
             $column['hidden'] = 1;
             $config['ini']['fields'][$name] = $column;
         }
     }
     return $config;
 }
Beispiel #10
0
 public function pluploadAction()
 {
     $this->_helper->layout->disableLayout();
     $this->_helper->viewRenderer->setNoRender(true);
     $json = new ZendT_Json_Result();
     try {
         $targetDir = ZendT_Lib::getTmpDir() . '/files/' . DIRECTORY_SEPARATOR . "plupload";
         // Create target dir
         if (!file_exists($targetDir)) {
             @($result = mkdir($targetDir));
             if (!$result) {
                 throw new ZendT_Exception_Error('Não foi possível criar o diretório "$targetDir".', 1001);
             }
         }
         if (!file_exists($targetDir)) {
             @($result = mkdir($targetDir));
             if (!$result) {
                 throw new ZendT_Exception_Error('Não foi possível criar o diretório "$targetDir".', 1001);
             }
         }
         //$targetDir = 'uploads';
         $cleanupTargetDir = true;
         // Remove old files
         $maxFileAge = 1 * 3600;
         // Temp file age in seconds
         // 5 minutes execution time
         @set_time_limit(5 * 60);
         // Uncomment this one to fake upload time
         // usleep(5000);
         // Get parameters
         $chunk = isset($_REQUEST["chunk"]) ? intval($_REQUEST["chunk"]) : 0;
         $chunks = isset($_REQUEST["chunks"]) ? intval($_REQUEST["chunks"]) : 0;
         $fileName = isset($_REQUEST["name"]) ? $_REQUEST["name"] : '';
         // Clean the fileName for security reasons
         $fileName = removeAccent(trim($fileName));
         $fileName = preg_replace('/[^\\w\\._]+/', '_', $fileName);
         $fileName = str_replace(' ', '_', $fileName);
         // Make sure the fileName is unique but only if chunking is disabled
         if ($chunks < 2 && file_exists($targetDir . DIRECTORY_SEPARATOR . $fileName)) {
             $ext = strrpos($fileName, '.');
             $fileName_a = substr($fileName, 0, $ext);
             $fileName_b = substr($fileName, $ext);
             $count = 1;
             while (file_exists($targetDir . DIRECTORY_SEPARATOR . $fileName_a . '_' . $count . $fileName_b)) {
                 $count++;
             }
             $fileName = $fileName_a . '_' . $count . $fileName_b;
         }
         $filePath = $targetDir . DIRECTORY_SEPARATOR . $fileName;
         // Remove old temp files
         if ($cleanupTargetDir && is_dir($targetDir) && ($dir = opendir($targetDir))) {
             while (($file = readdir($dir)) !== false) {
                 $tmpfilePath = $targetDir . DIRECTORY_SEPARATOR . $file;
                 // Remove temp file if it is older than the max age and is not the current file
                 if (preg_match('/\\.part$/', $file) && filemtime($tmpfilePath) < time() - $maxFileAge && $tmpfilePath != "{$filePath}.part") {
                     @unlink($tmpfilePath);
                 }
             }
             closedir($dir);
         } else {
             throw new ZendT_Exception_Error('Failed to open temp directory.', 100);
         }
         // Look for the content type header
         if (isset($_SERVER["HTTP_CONTENT_TYPE"])) {
             $contentType = $_SERVER["HTTP_CONTENT_TYPE"];
         }
         if (isset($_SERVER["CONTENT_TYPE"])) {
             $contentType = $_SERVER["CONTENT_TYPE"];
         }
         // Handle non multipart uploads older WebKit versions didn't support multipart in HTML5
         if (strpos($contentType, "multipart") !== false) {
             if (isset($_FILES['file']['tmp_name']) && is_uploaded_file($_FILES['file']['tmp_name'])) {
                 // Open temp file
                 $out = fopen("{$filePath}.part", $chunk == 0 ? "wb" : "ab");
                 if ($out) {
                     // Read binary input stream and append it to temp file
                     $in = fopen($_FILES['file']['tmp_name'], "rb");
                     if ($in) {
                         while ($buff = fread($in, 4096)) {
                             fwrite($out, $buff);
                         }
                     } else {
                         throw new ZendT_Exception_Error('Failed to open input stream.', 101);
                     }
                     fclose($in);
                     fclose($out);
                     @unlink($_FILES['file']['tmp_name']);
                 } else {
                     throw new ZendT_Exception_Error('Failed to open output stream.', 102);
                 }
             } else {
                 throw new ZendT_Exception_Error('Failed to move uploaded file.', 103);
             }
         } else {
             // Open temp file
             $out = fopen("{$filePath}.part", $chunk == 0 ? "wb" : "ab");
             if ($out) {
                 // Read binary input stream and append it to temp file
                 $in = fopen("php://input", "rb");
                 if ($in) {
                     while ($buff = fread($in, 4096)) {
                         fwrite($out, $buff);
                     }
                 } else {
                     throw new ZendT_Exception_Error('Failed to open input stream.', 104);
                 }
                 fclose($in);
                 fclose($out);
             } else {
                 throw new ZendT_Exception_Error('Failed to open output stream.', 105);
             }
         }
         // Check if file has been uploaded
         if (!$chunks || $chunk == $chunks - 1) {
             // Strip the temp .part suffix off
             @($result = rename("{$filePath}.part", $filePath));
             if (!$result) {
                 throw new ZendT_Exception_Error('Não foi possível renomear o arquivo.', 1002);
             }
         }
         if ($this->getRequest()->getParam('platform')) {
             $_file = new ZendT_File($fileName, file_get_contents($filePath), $_FILES['file']['type']);
             if (file_exists($filePath)) {
                 unlink($filePath);
             }
             $infoFile = $_file->toArrayJson();
             $infoFile['size'] = $_FILES['file']['size'];
             $infoFile['type'] = $_FILES['file']['type'];
             $json->setResult($infoFile);
         } else {
             $json->setResult(base64_encode($filePath));
         }
     } catch (Exception $Ex) {
         $json->setException($Ex);
     }
     echo $json->toRpc();
 }