/**
  * Reademails
  * @return type
  */
 public function readmails(Emails $emails, Email $settings_email, System $system)
 {
     $path_url = $system->first()->url;
     if ($settings_email->first()->email_fetching == 1) {
         if ($settings_email->first()->all_emails == 1) {
             $helptopic = $this->TicketController->default_helptopic();
             $sla = $this->TicketController->default_sla();
             $email = $emails->get();
             foreach ($email as $e_mail) {
                 $dept = $e_mail->department;
                 $host = $e_mail->fetching_host;
                 $port = $e_mail->fetching_port;
                 $protocol = $e_mail->mailbox_protocol;
                 $imap_config = '{' . $host . ':' . $port . $protocol . '}INBOX';
                 $password = Crypt::decrypt($e_mail->password);
                 $mailbox = new ImapMailbox($imap_config, $e_mail->user_name, $password, __DIR__);
                 $mails = array();
                 $mailsIds = $mailbox->searchMailBox('SINCE ' . date('d-M-Y', strtotime("-1 day")));
                 if (!$mailsIds) {
                     die('Mailbox is empty');
                 }
                 // dd($mailsIds);
                 foreach ($mailsIds as $mailId) {
                     $overview = $mailbox->get_overview($mailId);
                     $var = $overview[0]->seen ? 'read' : 'unread';
                     if ($var == 'unread') {
                         $mail = $mailbox->getMail($mailId);
                         if ($settings_email->email_collaborator == 1) {
                             $collaborator = $mail->cc;
                         } else {
                             $collaborator = null;
                         }
                         $body = $mail->textHtml;
                         // dd($mailId);
                         if ($body == null) {
                             $body = $mailbox->backup_getmail($mailId);
                             $body = str_replace('\\r\\n', '<br/>', $body);
                             // var_dump($body);
                         }
                         // dd($body);
                         $date = $mail->date;
                         $datetime = $overview[0]->date;
                         $date_time = explode(" ", $datetime);
                         $date = $date_time[1] . "-" . $date_time[2] . "-" . $date_time[3] . " " . $date_time[4];
                         $date = date('Y-m-d H:i:s', strtotime($date));
                         if (isset($mail->subject)) {
                             $subject = $mail->subject;
                         } else {
                             $subject = "No Subject";
                         }
                         $fromname = $mail->fromName;
                         $fromaddress = $mail->fromAddress;
                         $source = "2";
                         $phone = "";
                         $priority = '1';
                         $assign = "";
                         $form_data = null;
                         if ($this->TicketController->create_user($fromaddress, $fromname, $subject, $body, $phone, $helptopic, $sla, $priority, $source, $collaborator, $dept, $assign, $form_data) == true) {
                             $thread_id = Ticket_Thread::whereRaw('id = (select max(`id`) from ticket_thread)')->first();
                             $thread_id = $thread_id->id;
                             foreach ($mail->getAttachments() as $attachment) {
                                 $support = "support";
                                 // echo $_SERVER['DOCUMENT_ROOT'];
                                 $dir_img_paths = __DIR__;
                                 $dir_img_path = explode('/code', $dir_img_paths);
                                 $filepath = explode('../../../../../../public/', $attachment->filePath);
                                 // dd($filepath);
                                 // $path = $dir_img_path[0]."/public/".$filepath[1];
                                 $path = public_path() . '/' . $filepath[1];
                                 // dd($path);
                                 $filesize = filesize($path);
                                 $file_data = file_get_contents($path);
                                 $ext = pathinfo($attachment->filePath, PATHINFO_EXTENSION);
                                 $imageid = $attachment->id;
                                 $string = str_replace('-', '', $attachment->name);
                                 $filename = explode('src', $attachment->filePath);
                                 $filename = str_replace('\\', '', $filename);
                                 $body = str_replace("cid:" . $imageid, $filepath[1], $body);
                                 $pos = strpos($body, $filepath[1]);
                                 if ($pos == false) {
                                     if ($settings_email->first()->attachment == 1) {
                                         $upload = new Ticket_attachments();
                                         $upload->file = $file_data;
                                         $upload->thread_id = $thread_id;
                                         $upload->name = $filepath[1];
                                         $upload->type = $ext;
                                         $upload->size = $filesize;
                                         $upload->poster = "ATTACHMENT";
                                         $upload->save();
                                     }
                                 } else {
                                     $upload = new Ticket_attachments();
                                     $upload->file = $file_data;
                                     $upload->thread_id = $thread_id;
                                     $upload->name = $filepath[1];
                                     $upload->type = $ext;
                                     $upload->size = $filesize;
                                     $upload->poster = "INLINE";
                                     $upload->save();
                                 }
                                 unlink($path);
                             }
                             $body = Encoding::fixUTF8($body);
                             $thread = Ticket_Thread::where('id', '=', $thread_id)->first();
                             $thread->body = $this->separate_reply($body);
                             $thread->save();
                         }
                     }
                 }
             }
         }
     }
 }
Example #2
0
 protected function _prepareDomainsTable()
 {
     $table = new Table();
     $table->addClass('table', 'table-striped', 'tablesorter');
     $row = new TableRow();
     $row->setContent([TableHeading::create('Domain'), TableHeading::create('Price'), TableHeading::create('Source'), TableHeading::create('Month'), TableHeading::create('Year'), TableHeading::create('Status')]);
     $thead = new TableHead();
     $thead->setContent($row);
     $tbody = new TableBody();
     foreach ($this->_domains as $item) {
         $month = $item->month;
         $domain = strtolower(trim($item->domain, ''));
         if (is_numeric($item->month)) {
             $dateObj = \DateTime::createFromFormat('!m', (int) ltrim($item->month, 0));
             $month = $dateObj->format('F');
         }
         $whois = Span::create('Check')->addClass('btn', 'btn-success', 'btn-xs');
         $whois->setAttribute('data-sendretrieve', '/domains/whois/' . $domain);
         $domainLink = new Link('http://www.' . $domain, $domain);
         $row = TableRow::create();
         $row->appendContent([TableCell::create($domainLink), TableCell::create(Encoding::toUTF8($item->price)), TableCell::create($this->_filterSource($item->source)), TableCell::create($month), TableCell::create($item->year), TableCell::create($whois)]);
         $tbody->appendContent($row);
     }
     $table->prependContent($thead);
     $table->appendContent($tbody);
     return Div::create([GoogleAdsense::leaderboard(), $table]);
 }
Example #3
0
 /**
  * Return entities by document
  * @param string $document
  * @return array
  * @throws OpenCalaisException
  */
 public function getEntities($document)
 {
     $ch = curl_init();
     curl_setopt($ch, CURLOPT_URL, $this->api_url);
     curl_setopt($ch, CURLOPT_HTTPHEADER, array('X-AG-Access-Token: ' . $this->api_token, 'Content-Type: ' . $this->contentType, 'outputFormat: ' . $this->outputFormat));
     curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
     curl_setopt($ch, CURLOPT_HEADER, 0);
     curl_setopt($ch, CURLOPT_POST, 1);
     curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
     curl_setopt($ch, CURLOPT_POSTFIELDS, $document);
     $response = curl_exec($ch);
     $response = Encoding::fixUTF8($response);
     $object = json_decode($response);
     if (empty($object)) {
         throw new OpenCalaisException('No response was received from the API.');
     } elseif (isset($object->fault)) {
         throw new OpenCalaisException('OpenCalais Error:' . $object->fault->faultstring);
     }
     foreach ($object as $item) {
         if (!empty($item->_typeGroup) && !empty($item->name)) {
             if (!empty($item->_type)) {
                 $this->entities[$item->_typeGroup][$item->_type][] = trim($item->name);
             } else {
                 $this->entities[$item->_typeGroup][] = trim($item->name);
             }
         }
     }
     return $this->entities;
 }
Example #4
0
 /**
  * @return bool
  */
 public function hasNext()
 {
     if (count($this->_rowBuffer) >= DBIterator::RECORD_BUFFER) {
         return true;
     } else {
         if (is_null($this->_rs)) {
             return count($this->_rowBuffer) > 0;
         } else {
             if ($row = $this->_rs->fetch(PDO::FETCH_ASSOC)) {
                 foreach ($row as $key => $value) {
                     if (is_null($value)) {
                         $row[$key] = "";
                     } elseif (is_object($value)) {
                         $row[$key] = "[OBJECT]";
                     } else {
                         $row[$key] = Encoding::toUTF8($value);
                     }
                 }
                 $sr = new SingleRow($row);
                 // Enfileira o registo
                 array_push($this->_rowBuffer, $sr);
                 // Traz novos até encher o Buffer
                 if (count($this->_rowBuffer) < DBIterator::RECORD_BUFFER) {
                     $this->hasNext();
                 }
                 return true;
             } else {
                 $this->_rs->closeCursor();
                 $this->_rs = null;
                 return count($this->_rowBuffer) > 0;
             }
         }
     }
 }
Example #5
0
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     //get formatter
     $formatter = $this->getHelper('formatter');
     $file = $input->getArgument('csv-file');
     //check if file exists
     if (!file_exists($file)) {
         $output->writeln($formatter->formatBlock(['[Error]', 'File ' . $file . ' not found.'], 'error', true));
         return;
     }
     //get options
     $delimiter = $input->getOption('delimiter');
     $enclosure = $input->getOption('enclosure');
     $escape = $input->getOption('escape');
     //get content and fix encoding
     $content = file_get_contents($file);
     //remove windows line breaks
     $content = str_replace("\r", '', $content);
     //split lines
     $lines = explode("\n", $content);
     //output
     $columns = [];
     //loop over all lines and put them into columns
     foreach ($lines as $line) {
         $csv = str_getcsv($line, $delimiter, $enclosure, $escape);
         foreach ($csv as $key => $field) {
             $field = trim($field);
             $columns[$key][] = $field;
         }
     }
     $rows = [];
     //loop over columns
     foreach ($columns as $columnKey => $column) {
         //row id
         $rowId = 0;
         //get max strlen
         $max = StringUtil::maxStrlen($column) + 1;
         //make columns equal length
         foreach ($column as $fieldKey => $field) {
             $rows[$rowId][$columnKey] = ' ' . str_pad($field, $max, ' ', STR_PAD_RIGHT);
             $rowId++;
         }
     }
     $table = '';
     //loop over rows
     foreach ($rows as $row) {
         $line = '|' . implode(' | ', $row) . '|';
         if ($table == '') {
             $headers = [];
             foreach ($row as $field) {
                 $headers[] = str_repeat('-', strlen($field));
             }
             $line .= "\n|" . implode(' | ', $headers) . '|';
         }
         $table .= $line . "\n";
     }
     echo Encoding::toUTF8($table);
 }
Example #6
0
 public function onMessage(Bucket $bucket)
 {
     $data = $bucket->getData();
     if ($data['isAction']) {
         $format = '* %s %s';
     } else {
         $format = '<%s> %s';
     }
     $this->log(sprintf($format, $data['from']['nick'], \ForceUTF8\Encoding::fixUTF8($data['message'])), $data['channel']);
 }
Example #7
0
function clean($s)
{
    // TODO Replace with preg_replace
    $s = str_replace('“', '"', $s);
    $s = str_replace('”', '"', $s);
    $s = str_replace('‘', '\'', $s);
    $s = str_replace('’', '\'', $s);
    $s = str_replace('–', '-', $s);
    $s = str_replace('—', '-', $s);
    //by the way these are 2 different dashes
    $s = str_replace('…', '...', $s);
    $s = trim(htmlspecialchars(Encoding::toUTF8($s), ENT_QUOTES));
    return $s;
}
 /**
  * Disabled temporary (test takes a lot of time)
  */
 public function testEncDec()
 {
     $pc = new PayloadCypher();
     $keyDir = __DIR__ . '/../../var/test/keys';
     $dataDir = __DIR__ . '/../../var/test/data';
     // Test different key sizes
     for ($x = 1; $x < 4; $x++) {
         $cmd = 'openssl genrsa -out ' . $keyDir . '/private.pem ' . $x * 1024;
         system($cmd);
         $cmd = 'openssl rsa -in ' . $keyDir . '/private.pem -outform PEM -pubout -out ' . $keyDir . '/public.pem';
         system($cmd);
         $pc->setOnPublicKeyLoad(function () use($keyDir) {
             return array(rand(1000, 2000) => file_get_contents($keyDir . '/public.pem'));
         });
         $pc->setOnPrivateKeyLoad(function ($keyName) use($keyDir) {
             return array($keyName => file_get_contents($keyDir . '/private.pem'));
         });
         $utf8Text = file_get_contents($dataDir . '/utf8.txt');
         for ($i = 1; $i < 10; $i++) {
             $payload = $utf8Text . openssl_random_pseudo_bytes(rand(1, 200));
             $cypherText = $pc->encryptString($payload);
             $decrypted = $pc->decryptString($cypherText);
             $this->assertEquals($decrypted, $payload);
         }
         for ($i = 1; $i < 10; $i++) {
             $obj = new stdClass();
             $obj->test0 = 'hallo';
             $obj->test1 = true;
             $obj->test2 = 1.12 * $i;
             $obj->test3 = array(1, 2, 3);
             $obj->utf8 = $utf8Text;
             // Entry to reproduce UTF8 encoding bug like:
             // http://stackoverflow.com/questions/10205722/json-encode-invalid-utf-8-sequence-in-argument
             $obj->invalidUtf8 = Encoding::toUTF8(pack("H*", 'c32e'));
             $cypherText = $pc->objectToEncryptedJson($obj);
             $decrypted = $pc->encryptedJsonToObject($cypherText);
             $this->assertEquals($obj, $decrypted);
         }
         for ($i = 1; $i < 10; $i++) {
             $arr = array('test1' => 123, 'test2' => 10.1, 'utf8' => file_get_contents($dataDir . '/utf8.txt'));
             $cypherText = $pc->arrayToEncryptedJson($arr);
             $decrypted = $pc->encryptedJsonToArray($cypherText);
             $this->assertEquals($arr, $decrypted);
         }
     }
     unlink($keyDir . '/private.pem');
     unlink($keyDir . '/public.pem');
 }
Example #9
0
 public function loadXmlString($html)
 {
     // log output often uses garbled ISO-8859-1 and UTF-8 encodings
     $html = \ForceUTF8\Encoding::toUTF8($html);
     // fix invalid markup of outdated ViewVC versions
     // - help link in footer not terminated
     // - selected branch/tag in CVS "sticky tag" dropdown has not attribute value
     // - self closing elements with no trailing slash
     // - remove navheader because of its often incomplete form tags
     $html = str_replace('Help</strong></td>', 'Help</a></strong></td>', $html);
     $html = str_replace('selected>', 'selected="selected">', $html);
     $html = preg_replace('#<((?:input|br|hr|img)[^\\/\\>]*)>#', '<$1 />', $html);
     $html = preg_replace('#\\<div class\\=\\"vc_navheader\\"\\>.*?\\<\\/div\\>#s', '', $html);
     // replace named HTML entities with their UTF-8 value
     $html = str_replace(array_values($this->entities), array_keys($this->entities), $html);
     // clean up namespace declaration
     $html = str_replace('xmlns="', 'ns="', $html);
     return new SimpleXMLElement($html);
 }
Example #10
0
function clean($s)
{
    if (is_array($s)) {
        foreach ($s as $key => $val) {
            $s[$key] = clean($s[$key]);
        }
        return $s;
    }
    // TODO Replace with preg_replace
    $s = str_replace('“', '"', $s);
    $s = str_replace('”', '"', $s);
    $s = str_replace('‘', '\'', $s);
    $s = str_replace('’', '\'', $s);
    $s = str_replace('–', '-', $s);
    $s = str_replace('—', '-', $s);
    //by the way these are 2 different dashes
    $s = str_replace('…', '...', $s);
    $s = trim(htmlspecialchars(Encoding::toUTF8($s), ENT_QUOTES));
    return $s;
}
Example #11
0
function getStoryAttributes($xpath, $story)
{
    $parsedUrl = parse_url($story["story_url"]);
    $host = explode('.', $parsedUrl['host']);
    $subdomain = $host[0];
    $cookies = "HasVisited=bypass page next time; path=/; domain={$subdomain}.adult-fanfiction.org";
    $story_author = $xpath->query("//tr[5]/td[2]");
    $story_title = $xpath->query("//html/head/title");
    $story_chapters = $xpath->query("//select[@name='chapnav']/option");
    // ========== GET STORY PROPERTIES ========== //
    foreach ($story_title as $title) {
        $story["title"] = str_replace("Story: ", '', stripAccents(trim($title->nodeValue)));
    }
    foreach ($story_author as $author) {
        $story["author"] = str_replace("Author: ", '', str_replace("\t", '', str_replace("\n", '', $author->nodeValue)));
    }
    if (!isset($story["author"]) || !isset($story["title"])) {
        throw new WrongFormatException("Data received contained invalid format. Author: {$story['author']}, Title: {$story['title']}");
    }
    $story["desc"] = "";
    $story["numChapter"] = 1;
    $story["chapters"] = array();
    $story["chapters"]["title"] = array();
    $story["chapters"]["content"] = array();
    foreach ($story_chapters as $chapter) {
        $new_url = $story["story_url"] . "&chapter=" . $story["numChapter"];
        $title = trim($chapter->nodeValue);
        if (startsWith($title, $story["numChapter"] . ".")) {
            $title = str_replace($story["numChapter"] . ". ", "", $title);
            array_push($story["chapters"]["title"], $title);
            array_push($story["chapters"]["content"], \ForceUTF8\Encoding::fixUTF8(getChapter($new_url, $story["debug"], $cookies, $story["uniqid"])));
        } else {
            break;
        }
        $story["numChapter"]++;
    }
    return $story;
}
 $enc = mb_detect_encoding($text, mb_list_encodings(), true);
 //overwrite ASCII
 if ($enc === false) {
     $enc = "UNKWN";
     $textToSend = $text;
     $saveToOpen = false;
 } elseif ($enc !== "UTF-8") {
     //$text = mb_convert_encoding($text, 'UTF-8', $enc);
     /*  
                    if(function_exists('incov'))
                    {
     $text = incov($enc,'UTF-8',$text);       
                    }
                    else {
     */
     $textToSend = \ForceUTF8\Encoding::fixUTF8(\ForceUTF8\Encoding::toUTF8($text));
     $test = mb_convert_encoding($textToSend, $enc, 'UTF-8');
     if ($test != $text) {
         $saveToOpen = false;
     } else {
         $saveToOpen = true;
     }
     //}
 } else {
     $textToSend = $text;
     $saveToOpen = true;
 }
 if ($enc === 'ASCII' && mb_check_encoding($text, 'UTF-8')) {
     $enc = 'UTF-8';
 }
 $json = new \stdClass();
 /**
  * 
  * @param string $s
  * @return string
  */
 protected function CustomEncode($s)
 {
     return \ForceUTF8\Encoding::toUTF8($s);
     //return \ForceUTF8\Encoding::fixUTF8(($s));
 }
 private function cleanup_text($text)
 {
     $text = trim(preg_replace('/(\\s\\s+|\\t|\\n)/', ' ', $text));
     return Encoding::fixUTF8($text);
 }
Example #15
0
 /**
  * generate doc
  * @var array $params
  */
 public function generateDoc($params)
 {
     Yii::$app->user->identity = \app\models\User::findIdentityByAccessToken($params['template']['key']);
     header("Content-Description: File Transfer");
     header('Content-Transfer-Encoding: binary');
     header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
     header('Expires: 0');
     switch ($params['template']['format']) {
         case 'PDF':
             $file = Yii::$app->user->id . '_temp.pdf';
             $writeFormat = 'PDF';
             PhpWordSettings::setPdfRendererPath(dirname(__DIR__) . '/../../../vendor/tecnickcom/tcpdf');
             PhpWordSettings::setPdfRendererName('TCPDF');
             header('Content-Type: application/pdf');
             break;
         case 'Word2013':
             $file = Yii::$app->user->id . '_temp.docx';
             $writeFormat = 'Word2013';
             header('Content-Type: application/vnd.openxmlformats-officedocument.wordprocessingml.document');
             break;
         default:
             $file = Yii::$app->user->id . '_temp.doc';
             $writeFormat = 'Word2007';
             header('Content-Type: application/vnd.openxmlformats-officedocument.wordprocessingml.document');
             break;
     }
     header('Content-Disposition: attachment; filename="' . $file . '"');
     $document = new TemplateProcessor(dirname(__DIR__) . '/../../../files/' . $this->id . '/' . $this->template_file);
     /**
      * process the fields, that have been send through the rest interface
      */
     foreach ($params['template']['fields'] as $field) {
         foreach ($field as $key => $value) {
             $document->setValue($key, UTF8encoding::fixUTF8($value));
         }
     }
     /**
      * process the tables, that have been send through the rest interface
      */
     foreach ($params['template']['tables'] as $tables) {
         foreach ($tables as $name => $rows) {
             //first we create a clone for the master row
             $document->cloneRow($name, count($rows));
             //our walking variable for the table
             $ii = 1;
             foreach ($rows as $row) {
                 foreach ($row as $cell) {
                     $document->setValue(key($cell) . '#' . $ii, current($cell));
                 }
                 $ii++;
             }
         }
     }
     // save as a random file in temp file
     $temp_file = tempnam(sys_get_temp_dir(), $file);
     $document->saveAs($temp_file);
     switch ($params['template']['format']) {
         case 'PDF':
             $phpWord = IOFactory::load($temp_file);
             $xmlWriter = IOFactory::createWriter($phpWord, $writeFormat);
             $xmlWriter->save("php://output");
             break;
         case 'Word2007':
             $phpWord = IOFactory::load($temp_file);
             $xmlWriter = IOFactory::createWriter($phpWord, $writeFormat);
             $xmlWriter->save("php://output");
             break;
         default:
             readfile($temp_file);
             break;
     }
     unlink($temp_file);
     $LogEvent = new TemplateEvent();
     $LogEvent->aTemplateCreated(Yii::$app->user->identity->username, $this->id);
     \Yii::$app->end();
 }
Example #16
0
 /**
  * @param $element
  * @return $this
  */
 public function setDataFromElement($element)
 {
     $this->data = null;
     $this->id = new Data\Id($element);
     $this->fullPath = $element->getRealFullPath();
     $this->creationDate = $element->getCreationDate();
     $this->modificationDate = $element->getModificationDate();
     $this->userModification = $element->getUserModification();
     $this->userOwner = $element->getUserOwner();
     $this->type = $element->getType();
     if ($element instanceof Object\Concrete) {
         $this->subtype = $element->getClassName();
     } else {
         $this->subtype = $this->type;
     }
     $this->properties = "";
     $properties = $element->getProperties();
     if (is_array($properties)) {
         foreach ($properties as $nextProperty) {
             $pData = (string) $nextProperty->getData();
             if ($nextProperty->getName() == "bool") {
                 $pData = $pData ? "true" : "false";
             }
             $this->properties .= $nextProperty->getName() . ":" . $pData . " ";
         }
     }
     $this->data = "";
     if ($element instanceof Document) {
         if ($element instanceof Document\Folder) {
             $this->data = $element->getKey();
             $this->published = true;
         } elseif ($element instanceof Document\Link) {
             $this->published = $element->isPublished();
             $this->data = $element->getTitle() . " " . $element->getHref();
         } elseif ($element instanceof Document\PageSnippet) {
             $this->published = $element->isPublished();
             $elements = $element->getElements();
             if (is_array($elements) && !empty($elements)) {
                 foreach ($elements as $tag) {
                     if ($tag instanceof Document\Tag\TagInterface) {
                         ob_start();
                         $this->data .= strip_tags($tag->frontend()) . " ";
                         $this->data .= ob_get_clean();
                     }
                 }
             }
             if ($element instanceof Document\Page) {
                 $this->published = $element->isPublished();
                 $this->data .= " " . $element->getTitle() . " " . $element->getDescription() . " " . $element->getPrettyUrl();
             }
         }
     } elseif ($element instanceof Asset) {
         $this->data = $element->getFilename();
         $elementMetadata = $element->getMetadata();
         if (is_array($elementMetadata)) {
             foreach ($elementMetadata as $md) {
                 if (is_scalar($md['data'])) {
                     $this->data .= " " . $md["name"] . ":" . $md["data"];
                 }
             }
         }
         if ($element instanceof Asset\Document && \Pimcore\Document::isAvailable()) {
             if (\Pimcore\Document::isFileTypeSupported($element->getFilename())) {
                 try {
                     $contentText = $element->getText();
                     $contentText = Encoding::toUTF8($contentText);
                     $contentText = str_replace(["\r\n", "\r", "\n", "\t", "\f"], " ", $contentText);
                     $contentText = preg_replace("/[ ]+/", " ", $contentText);
                     $this->data .= " " . $contentText;
                 } catch (\Exception $e) {
                     Logger::error($e);
                 }
             }
         } elseif ($element instanceof Asset\Text) {
             try {
                 $contentText = $element->getData();
                 $contentText = Encoding::toUTF8($contentText);
                 $this->data .= " " . $contentText;
             } catch (\Exception $e) {
                 Logger::error($e);
             }
         } elseif ($element instanceof Asset\Image) {
             try {
                 $metaData = array_merge($element->getEXIFData(), $element->getIPTCData());
                 foreach ($metaData as $key => $value) {
                     $this->data .= " " . $key . " : " . $value;
                 }
             } catch (\Exception $e) {
                 Logger::error($e);
             }
         }
         $this->published = true;
     } elseif ($element instanceof Object\AbstractObject) {
         if ($element instanceof Object\Concrete) {
             $getInheritedValues = Object\AbstractObject::doGetInheritedValues();
             Object\AbstractObject::setGetInheritedValues(true);
             $this->published = $element->isPublished();
             foreach ($element->getClass()->getFieldDefinitions() as $key => $value) {
                 $this->data .= $value->getDataForSearchIndex($element) . " ";
             }
             Object\AbstractObject::setGetInheritedValues($getInheritedValues);
         } elseif ($element instanceof Object\Folder) {
             $this->data = $element->getKey();
             $this->published = true;
         }
     } else {
         Logger::crit("Search\\Backend\\Data received an unknown element!");
     }
     if ($element instanceof Element\ElementInterface) {
         $this->data = "ID: " . $element->getId() . "  \nPath: " . $this->getFullPath() . "  \n" . $this->cleanupData($this->data);
     }
     return $this;
 }
Example #17
0
 /**
  * Converts a string to UTF-8
  * 
  * @param unknown $string            
  * @return Ambigous <unknown, string>
  */
 public function toUtf8($string)
 {
     return ForceUtf8::fixUTF8($string);
 }
 public function genStatusIcon($res, $tt = null)
 {
     $glyphs = array("ok" => "glyphicon-ok text-success", "warning" => "glyphicon-warning-sign text-warning", "error" => "glyphicon-remove text-danger", "unknown" => "glyphicon-question-sign text-info", "info" => "glyphicon-info-sign text-info", "critical" => "glyphicon-fire text-danger");
     // Are we being asked for an alert we actually know about?
     if (!isset($glyphs[$res])) {
         return array('type' => 'unknown', "tooltip" => "Don't know what {$res} is", "glyph-class" => $glyphs['unknown']);
     }
     if ($tt === null) {
         // No Tooltip
         return array('type' => $res, "tooltip" => null, "glyph-class" => $glyphs[$res]);
     } else {
         // Generate a tooltip
         $html = '';
         if (is_array($tt)) {
             foreach ($tt as $line) {
                 $html .= htmlentities(\ForceUTF8\Encoding::fixUTF8($line), ENT_QUOTES, "UTF-8") . "\n";
             }
         } else {
             $html .= htmlentities(\ForceUTF8\Encoding::fixUTF8($tt), ENT_QUOTES, "UTF-8");
         }
         return array('type' => $res, "tooltip" => $html, "glyph-class" => $glyphs[$res]);
     }
     return '';
 }
Example #19
0
 /**
  * Converts BB-Code
  *
  * @param string WoWBB-BB-Code
  * @return string MyBB-BB-Code
  */
 public function bb2my($input)
 {
     /**
      * Force UTF-8
      * @see Encoding.php
      */
     $input = \ForceUTF8\Encoding::fixUTF8($input);
     /**
      * HTML to Specialchar
      */
     $input = html_entity_decode($input, ENT_QUOTES | ENT_HTML5, 'UTF-8');
     /**
      * Regexes from WowBB
      */
     $input = preg_replace('/\\[\\s*(\\/*)\\s*(\\S*)\\s*(=*)\\s*("?)(.*)("?)\\s*\\]/isU', '[\\1\\2\\3\\4\\5\\6]', $input);
     $input = preg_replace('/\\[([\\/=*a-z0-9]+):[a-z0-9]*(=".+")?\\]/iU', '[\\1\\2]', $input);
     $input = preg_replace('/(?<!http:\\/\\/|\\/)(www\\.\\S+)\\b/isU', 'http://\\1', $input);
     $input = preg_replace('/(?<!\\]|=|")http(s?):\\/\\/([^\\s<\\[]+)/is', '[url]http\\1://\\2[/url]', $input);
     /**
      * Own Replace
      */
     $input = str_replace("&nbsp;", " ", $input);
     $input = str_replace("[line]", '[hr]', $input);
     $input = str_replace("[/*]", "", $input);
     $input = preg_replace('/\\[([^\\]"]+)="([^\\]]+)"\\]/is', '[\\1=\\2]', $input);
     $input = preg_replace('/\\[(\\/?)indent\\]/i', '[\\1quote]', $input);
     $input = preg_replace('/\\[(\\/?)php\\]/i', '[\\1code]', $input);
     /**
      * [user=...]...[/user]-Convert
      */
     $input = preg_replace_callback('/\\[user="******"?\\](.*?)\\[\\/user\\]/si', function ($matches) {
         $my_uid = $this->uid2my($matches[1], 0);
         if (!$my_uid) {
             return $matches[2];
         } else {
             return "[user="******"]" . $matches[2] . "[/user]";
         }
     }, $input);
     /**
      * Convert Sizes from HTML3-font-tag
      */
     $input = preg_replace_callback('/\\[size="?([+-]?[0-9]+)"?\\]/is', function ($matches) {
         $ret = "[size=";
         switch ($matches[1]) {
             case "-9":
             case "-8":
             case "-7":
             case "-6":
             case "-5":
             case "-4":
             case "-3":
             case "-2":
                 $ret .= "62.5%";
                 break;
             case "-1":
                 $ret .= "smaller";
                 break;
             case "-0":
             case "+0":
                 $ret .= "100%";
                 break;
             case "0":
                 $ret .= "xx-small";
                 break;
             case "1":
                 $ret .= "x-small";
                 break;
             case "2":
                 $ret .= "small";
                 break;
             case "3":
                 $ret .= "medium";
                 break;
             case "4":
                 $ret .= "large";
                 break;
             case "5":
                 $ret .= "x-large";
                 break;
             case "6":
                 $ret .= "xx-large";
                 break;
             case "7":
             case "8":
             case "9":
                 $ret .= "48px";
                 break;
             case "+1":
                 $ret .= "larger";
                 break;
             case "+2":
                 $ret .= "150%";
                 break;
             case "+3":
                 $ret .= "200%";
                 break;
             case "+4":
             case "+5":
             case "+6":
             case "+7":
             case "+8":
             case "+9":
                 $ret .= "300%";
                 break;
             default:
                 $ret .= (int) $matches[1] . "px";
         }
         $ret .= "]";
         return $ret;
     }, $input);
     /**
      * Not supported => delete
      */
     $input = preg_replace('/\\[(sound|real|quicktime|media|fl|flash)[^\\]]*\\].*?\\[\\/\\1\\]/si', "", $input);
     $input = preg_replace('/\\[\\/?(?:blur|glow)\\]/i', "", $input);
     $input = preg_replace('/\\[\\/?(?:shadow|move(?:up|[ldr])?|scroll)[^\\]]*\\]/i', "", $input);
     return $input;
 }
function createShittalkRow($text)
{
    if (strlen($text) > 128) {
        $text = substr($text, 0, 128);
        //shorten to source game default length
    }
    $text_to_utf8 = Encoding::toUTF8($text);
    $text = Encoding::fixUTF8($text_to_utf8);
    $text_escaped = mysql_escape_mimic(strip_double_quotes($text));
    $today = mysql_escape_mimic(date("Y-m-d H:i:s"));
    $sql = "INSERT INTO `shittalkDB`\n            (`text`, `date_created`, `custom`)\n            VALUES ('{$text_escaped}', '{$today}', 1);";
    $result = mySqlQuery($sql);
    return $result;
}
 public function fixUtf8($content)
 {
     $content = Encoding::fixUTF8($content);
     $content = str_replace('Â', '', $content);
     return $content;
 }
 /**
  * Formats an array in preparation for dispatch to a STOMP queue
  *
  * @return array Pass this return array to STOMP :)
  *
  * TODO: Stop saying "STOMP".
  */
 protected function getStompTransaction()
 {
     $transaction = array('gateway_txn_id' => $this->getTransactionGatewayTxnID(), 'response' => $this->getTransactionMessage(), 'correlation-id' => $this->getCorrelationID(), 'php-message-class' => 'SmashPig\\CrmLink\\Messages\\DonationInterfaceMessage', 'gateway_account' => $this->account_name);
     // Add the rest of the relevant data
     // FIXME: This is "normalized" data.  We should refer to it as such,
     // and rename the getData_Unstaged_Escaped function.
     $stomp_data = array_intersect_key($this->getData_Unstaged_Escaped(), array_flip($this->dataObj->getMessageFields()));
     // The order here is important, values in $transaction are considered more definitive
     // in case the transaction already had keys with those values
     $transaction = array_merge($stomp_data, $transaction);
     // FIXME: Note that we're not using any existing date or ts fields.  Why is that?
     $transaction['date'] = time();
     // Force any incorrect encoding to UTF-8.
     // FIXME: Move down to the PHP-Queue library
     $transaction = Encoding::toUTF8($transaction);
     return $transaction;
 }
Example #23
0
 /**
  * This function returns an array with key=column-name and value=data.
  */
 private function createValues($columns, $data)
 {
     $result = array();
     foreach ($columns as $column) {
         if (!empty($data[$column['index']]) || is_numeric(@$data[$column['index']])) {
             $result[$column['column_name_alias']] = \ForceUTF8\Encoding::fixUTF8(@$data[$column['index']]);
         } else {
             $index = $column['index'];
             $result[$column['column_name_alias']] = '';
         }
     }
     return $result;
 }
Example #24
0
function sanitizeElement($elem)
{
    $test = false;
    $elem = str_replace("`", "'", $elem);
    $elem = str_replace("‘", "'", $elem);
    if ($test) {
        echo '-3) ' . json_encode($elem) . "\n";
    }
    $elem = str_replace("’", "'", $elem);
    if ($test) {
        echo '-2) ' . json_encode($elem) . "\n";
    }
    $elem = str_replace("“", "\"", $elem);
    if ($test) {
        echo '-1) ' . json_encode($elem) . "\n";
    }
    $elem = str_replace("”", "\"", $elem);
    if ($test) {
        echo '0) ' . json_encode($elem) . "\n";
    }
    $elem = strtolower($elem) == 'na' ? '' : $elem;
    if ($test) {
        echo '1) ' . json_encode($elem) . "\n";
    }
    $elem = strtolower($elem) == 'n/a' ? '' : $elem;
    if ($test) {
        echo '2) ' . json_encode($elem) . "\n";
    }
    $elem = strtolower($elem) == 'test' ? '' : $elem;
    if ($test) {
        echo '3) ' . json_encode($elem) . "\n";
    }
    $elem = strtolower($elem) == 'void' ? '' : $elem;
    if ($test) {
        echo '4) ' . json_encode($elem) . "\n";
    }
    $elem = strtolower($elem) == 'test - void' ? '' : $elem;
    if ($test) {
        echo '5) ' . json_encode($elem) . "\n";
    }
    $elem = strtolower($elem) == 'tba' ? '' : $elem;
    if ($test) {
        echo '6) ' . json_encode($elem) . "\n";
    }
    $elem = strtolower($elem) == 'tbd' ? '' : $elem;
    if ($test) {
        echo '7) ' . json_encode($elem) . "\n";
    }
    $elem = strtolower($elem) == 'unknown' ? '' : $elem;
    if ($test) {
        echo '8) ' . json_encode($elem) . "\n";
    }
    $elem = strtolower($elem) == '1900-01-01' ? '' : $elem;
    if ($test) {
        echo '9) ' . json_encode($elem) . "\n";
    }
    $elem = strtolower($elem) == '1970-01-01' ? '' : $elem;
    if ($test) {
        echo '10) ' . json_encode($elem) . "\n";
    }
    $elem = preg_replace("/[\r]+/", "", $elem);
    if ($test) {
        echo '11) ' . json_encode($elem) . "\n";
    }
    $elem = isHTML($elem) ? preg_replace("/[\n]+/", "", $elem) : preg_replace("/[\n]/", "<br>", $elem);
    if ($test) {
        echo '12) ' . json_encode($elem) . "\n";
    }
    $elem = preg_replace('/[\\x00-\\x1F\\x80-\\xFF]/', '', $elem);
    // removed non-UTF8 chartacters
    if ($test) {
        echo '13) ' . json_encode($elem) . "\n";
    }
    $elem = str_replace('&nbsp;', ' ', $elem);
    // removed html space
    if ($test) {
        echo '14) ' . json_encode($elem) . "\n";
    }
    $elem = preg_replace('!\\s+!', ' ', $elem);
    // removed redundand spaces
    if ($test) {
        echo '15) ' . json_encode($elem) . "\n";
    }
    $elem = preg_replace('/(<br[\\s]?[\\/]?>[\\s]*){3,}/', '<br /><br />', $elem);
    // replace redundant <br>, space ...
    if ($test) {
        echo '16) ' . json_encode($elem) . "\n";
    }
    $elem = preg_replace('/<br[\\s]?[\\/]?>[\\s]*$/', '', $elem);
    // removed br from end post -->
    if ($test) {
        echo '17) ' . json_encode($elem) . "\n";
    }
    $elem = preg_replace('/<img[^>]+\\>/i', '', $elem);
    // remove all image tags
    if ($test) {
        echo '18) ' . json_encode($elem) . "\n";
    }
    $elem = str_replace('&#65533;', ' ', $elem);
    // removed html placeholder
    if ($test) {
        echo '19) ' . json_encode($elem) . "\n";
    }
    $elem = str_replace('&#65535;', '', $elem);
    // removed html placeholder
    if ($test) {
        echo '20) ' . json_encode($elem) . "\n";
    }
    $elem = str_replace('<p></p>', '', $elem);
    // removed html placeholder
    if ($test) {
        echo '21) ' . json_encode($elem) . "\n";
    }
    $elem = Encoding::toUTF8($elem);
    // fixes broken UTF8 characters
    if ($test) {
        echo '23) ' . json_encode($elem) . "\n";
    }
    $elem = str_replace(" dont", " don't", $elem);
    // grammar 1
    if ($test) {
        echo '24) ' . json_encode($elem) . "\n";
    }
    $elem = str_replace(" doesnt ", " doesn't ", $elem);
    // grammar 2
    if ($test) {
        echo '25) ' . json_encode($elem) . "\n";
    }
    $elem = str_replace(" im ", " i'm ", $elem);
    // grammar 3
    if ($test) {
        echo '26) ' . json_encode($elem) . "\n";
    }
    $elem = trim(trim($elem));
    if ($test) {
        echo '29) ' . json_encode($elem) . "\n";
    }
    return $elem;
}
function test_double_encoded_arrays_fix()
{
    $arr1 = array(utf8_encode(file_get_contents(dirname(__FILE__) . "/data/test1Latin.txt")), utf8_encode(file_get_contents(dirname(__FILE__) . "/data/test1.txt")), utf8_encode(file_get_contents(dirname(__FILE__) . "/data/test1Latin.txt")));
    $arr2 = array(file_get_contents(dirname(__FILE__) . "/data/test1.txt"), file_get_contents(dirname(__FILE__) . "/data/test1.txt"), file_get_contents(dirname(__FILE__) . "/data/test1.txt"));
    return Encoding::fixUTF8($arr1) == $arr2;
}
 /**
  * Get all system recordings
  * @return array Array of system recordings
  */
 public function getSystemRecordings()
 {
     $files = $this->getdir($this->path);
     $final = array();
     foreach ($files as &$file) {
         $file = str_replace($this->path . "/", "", $file);
         if (preg_match("/^(\\w{2}_\\w{2}|\\w{2})\\/(.*)\\.([a-z0-9]{2,})/i", $file, $matches)) {
             $lang = $matches[1];
             $name = \ForceUTF8\Encoding::fixUTF8($matches[2]);
             if (substr($name, 0, 1) == "." || preg_match("/^(?:CHANGES|CREDITS|LICENSE)-asterisk-(?:core|extra)-(?:\\w\\w\\_\\w\\w|\\w\\w)-(?:\\d|\\.)*\$/i", $name)) {
                 continue;
             }
             $format = $matches[3];
             if (!isset($final[$name])) {
                 $final[$name] = array("name" => $name, "languages" => array($lang => $lang), "formats" => array($format => $format), "paths" => array($lang => $lang . "/" . $name));
             } else {
                 $final[$name]['languages'][$lang] = $lang;
                 $final[$name]['formats'][$format] = $format;
                 $final[$name]['paths'][$lang] = $lang . "/" . $name;
             }
         }
     }
     ksort($final);
     return $final;
 }
Example #27
0
 /**
  * @param mixed $input string or array
  *
  * @return mixed
  */
 public function filter($input)
 {
     // The Encoding methods are array-aware so we can just drop our input
     // into the conversion method.
     return Encoding::toUTF8($input);
 }
Example #28
0
 /**
  *@desc Check and encode UTF-8 encoding document. Return the checked document converted to UTF-8
  *@param string $document
  *@return string
  */
 public static function fixUTF8($document)
 {
     return Encoding::fixUTF8(Encoding::removeBOM($document), Encoding::WITHOUT_ICONV);
 }
Example #29
0
 /**
  * @param $document
  * @return array|string
  */
 public static function fixUTF8($document)
 {
     return Encoding::fixUTF8(Encoding::removeBOM($document), Encoding::ICONV_TRANSLIT);
 }
Example #30
0
            }
        }
        $i++;
    }
    $IdAlumnibiris = mysql_result($Alumnos, $j, 'id_estu');
    $Observacion = $Querys->Select('*', 'oboletin', "WHERE id_estu='{$IdAlumnibiris}' AND id_peri='{$IdPeriodo}'");
    $Observacion = mysql_result($Observacion, 0, 'obol_obol');
    $PuestoFinal = $Querys->Select('pues_pues', 'puestos', "WHERE id_estu='" . $IdAlumnibiris . "' AND peri_pues='" . $IdPeriodo . "'");
    $PuestoFinal = mysql_result($PuestoFinal, 0, 'pues_pues');
    ?>

			<div id="observacion"><?php 
    echo Encoding::fixUTF8($Observacion);
    ?>
<br /><b>Puesto en el curso:</b> <?php 
    echo Encoding::fixUTF8($PuestoFinal);
    ?>
</div>
			<div id="firma"><img src="firma.png"></div></div>
	</div>
<?php 
    $j++;
}
?>
		<!--<div id="pagina2">
			<div id="materia">
				<div id="nombremateria9" class="absoluto">Matemáticas</div>
				<div id="ih9" class="absoluto">2</div>
				<div id="f9" class="absoluto">2</div>
				<div id="d9" class="absoluto">Superior</div>
				<div id="v19" class="absoluto">9.3</div>