Beispiel #1
0
 public function encoding($text)
 {
     // encoding para ISO 8859-1
     return $text;
     if (strrpos(Run::ENCODING, "utf") != "") {
         return Encoding::toUTF8($text);
     } else {
         return Encoding::toLatin1($text);
     }
 }
 static function toSlug($string, $space = "-")
 {
     $string = Encoding::fixUTF8(Encoding::toUTF8($string));
     $string = self::mb_strtolower(self::mb_trim($string));
     $string = self::cleanTextHtml($string);
     if (function_exists('iconv')) {
         $string = @iconv('UTF-8', 'ASCII//TRANSLIT', $string);
     }
     $string = preg_replace('/[^a-z0-9 _.-]/', '', $string);
     $string = preg_replace('/[\\s\\-_]+/', $space, $string);
     $string = str_replace(' ', $space, $string);
     return $string;
 }
 function cumulus_update($file)
 {
     $infile = fopen($file, 'r');
     $firstLine = fgetcsv($infile);
     $csvArray = array();
     while (!feof($infile)) {
         $assoc = array();
         $line = fgetcsv($infile);
         if ($line[0]) {
             foreach ($line as $index => $value) {
                 $assoc[$firstLine[$index]] = $value ? Encoding::toUTF8($value) : NULL;
             }
             $csvArray[] = $assoc;
         }
     }
     fclose($infile);
     print_r($csvArray);
 }
/**
 * @see https://github.com/FerreroJeremy/DBNary-PHP-Interface
 */
require_once 'DBNaryInterface.php';
/**
 * @see https://github.com/neitanod/forceutf8
 */
require_once 'Encoding.php';
$db = new DBNaryInterface();
$encode = new Encoding();
$db->setLanguageFrom('french');
$db->setLanguageTo('english');
$db->connect();
$words = extractLinesFromFile('dicos/dico_295065.txt');
foreach ($words as $word) {
    $word = $encode->toUTF8(trim($word));
    $word = getFirstWord(trim($word));
    $db->getTranslations(trim($word));
    $availableTranslations = $db->getResultInList();
    if (!empty($availableTranslations)) {
        foreach ($availableTranslations as $translation) {
            writeInFile('dico_from_dbnary.txt', trim($word) . ' @ ' . trim($translation) . chr(10));
        }
    }
}
/* * ***********************
 *      FUNCTIONS
 * *********************** */
/**
 * Return the first token of a string.
 * @param   string  $text   Text.
 private function parseDelimitedText()
 {
     $array = array();
     $handle = fopen($this->filename, 'r');
     while (!feof($handle)) {
         if ($this->delimiter == 'tab') {
             $line = fgetcsv($handle, 0, "\t");
         } elseif ($this->delimiter == 'comma') {
             $line = fgetcsv($handle);
         }
         $array[] = array('fromNode' => trim(str_replace(array(':', '.'), '', $line[0])), 'leadText' => Encoding::toUTF8(trim($line[1])), 'toNode' => Encoding::toUTF8(trim($line[2])));
     }
     // Get the items
     foreach ($array as $row) {
         $goto = $row['toNode'];
         if ($row && !is_numeric($row['toNode'])) {
             $this->items[] = array('id' => $goto, 'name' => $goto, 'icon' => NULL, 'url' => NULL);
             $this->itemIDs[] = $goto;
         }
     }
     // Id of the first step
     $this->firstStepID = $array[0]['fromNode'];
     // Get all the leads
     foreach ($array as $index => $row) {
         $goto = $row['toNode'];
         $this->stepIDs[] = $row['fromNode'];
         $this->leads[] = array('stepid' => $row['fromNode'], 'leadid' => $index + 1, 'goto' => $goto, 'icon' => NULL, 'leadtext' => $row['leadText']);
     }
 }
Beispiel #6
0
 private function createImageRecord($row)
 {
     $rec = new ImageRecord();
     $rec->CumulusRecordID = $row['CumulusRecordID'];
     $rec->CumulusRecordName = $row['CumulusRecordName'];
     $rec->CumulusCatalogue = $row['CumulusCatalog'];
     $rec->Title = $row['dcterms:title'];
     $rec->Source = $row['dc:source'];
     $rec->Modified = $row['dcterms:modified'];
     $rec->DCType = $row['dcterms:type'];
     $rec->Subtype = $row['ac:subtype'] == 'Illustration' ? 'Illustration' : 'Photograph';
     $rec->Caption = substr($row['ac:caption'], -1) == '.' ? $row['ac:caption'] : $row['ac:caption'] . '.';
     $rec->SubjectCategory = $row['iptc:CVTerm'];
     $rec->SubjectPart = $row['ac:subjectPart'];
     $rec->SubjectOrientation = $row['ac:subjectOrientation'];
     $rec->CreateDate = $row['xmp:CreateDate'];
     $rec->DigitizationDate = $row['ac:digitizationDate'];
     $rec->Creator = $row['dcterms:creator'];
     $rec->RightsHolder = $row['dcterms:rightsHolder'];
     $rec->License = $row['dcterms:license'];
     $rec->Rights = $row['dc:rights'];
     $rec->ScientificName = Encoding::toUTF8($row['dwc:scientificName']);
     $rec->CatalogNumber = $row['dwc:catalogNumber'];
     $rec->RecordedBy = $row['dwc:recordedBy'];
     $rec->RecordNumber = $row['dwc:recordNumber'];
     $rec->Country = $row['dwc:country'];
     $rec->CountryCode = $row['dwc:countryCode'];
     $rec->StateProvince = $row['dwc:stateProvince'];
     $rec->Locality = $row['dwc:locality'];
     $rec->Latitude = $row['dwc:decimalLatitude'];
     $rec->Longitude = $row['dwc:decimalLongitude'];
     $rec->PixelXDimension = $row['exif:PixelXDimension'];
     $rec->PixelYDimension = $row['exif:PixelYDimension'];
     $rec->HeroImage = $row['HeroImage'];
     $rec->Rating = $row['xmp:Rating'];
     $rec->ThumbnailUrlEnabled = isset($row['ThumbnailUrlEnabled']) && strtolower($row['ThumbnailUrlEnabled']) == 'true' ? TRUE : FALSE;
     $rec->PreviewUrlEnabled = isset($row['PreviewUrlEnabled']) && strtolower($row['PreviewUrlEnabled']) == 'true' ? TRUE : FALSE;
     $tax = $this->findTaxon(Encoding::toUTF8($row['dwc:scientificName']));
     if ($tax) {
         $rec->TaxonID = $tax->TaxonID;
         $rec->AcceptedID = $tax->AcceptedID;
     }
     return $rec;
 }
Beispiel #7
0
function nvweb_content_date_format($format = "", $ts)
{
    global $website;
    global $session;
    $out = '';
    setlocale(LC_ALL, $website->languages[$session['lang']]['system_locale']);
    if (empty($format)) {
        $out = date($website->date_format, $ts);
    } else {
        if (strpos($format, '%day') !== false || strpos($format, '%month') !== false || strpos($format, '%year4')) {
            // deprecated: used until Navigate CMS 1.6.7; to be removed in Navigate CMS 2.0
            $out = str_replace('%br', '<br />', $format);
            $out = str_replace('%day', date("d", $ts), $out);
            $out = str_replace('%month_abr', Encoding::toUTF8(strtoupper(strftime("%b", $ts))), $out);
            $out = str_replace('%month', date("m", $ts), $out);
            $out = str_replace('%year4', date("Y", $ts), $out);
        } else {
            if (!empty($ts)) {
                $out = Encoding::toUTF8(strftime($format, intval($ts)));
            }
        }
    }
    return $out;
}
/**
 * Recursively encode array (or string) as UTF8 text
 *
 * @param mixed $pm_input Array or string to encode
 * @return mixed Encoded array or string
 */
function caEncodeUTF8Deep(&$pm_input)
{
    if (is_string($pm_input)) {
        $pm_input = Encoding::toUTF8($pm_input);
    } else {
        if (is_array($pm_input)) {
            foreach ($pm_input as &$vm_value) {
                caEncodeUTF8Deep($vm_value);
            }
            unset($vm_value);
        } else {
            if (is_object($pm_input)) {
                $va_keys = array_keys(get_object_vars($pm_input));
                foreach ($va_keys as $vs_key) {
                    caEncodeUTF8Deep($pm_input->{$vs_key});
                }
            }
        }
    }
    return $pm_input;
}
 function encodeData()
 {
     $encoding = mb_detect_encoding($this->data, "ISO-8859-15, ISO-8859-1, UTF-8, ASCII, auto");
     if ($encoding && $encoding != 'UTF-8') {
         $this->data = Encoding::toUTF8($this->data);
     }
 }
Beispiel #10
0
 public function actualitza($courseYear, $date = NULL)
 {
     $this->logger = sfContext::getInstance()->getLogger();
     $this->courseYear = $courseYear;
     $this->sessions = array();
     $timetableDOM = new simple_html_dom();
     //echo $this->courseYear."<br>";
     //echo $timetableDOM->load_file($courseYear->getUrlHorari())."<br>";
     $timetableDOM = file_get_html($courseYear->getUrlHorari());
     if (!($timetableDOM && is_object($timetableDOM) && isset($timetableDOM->nodes))) {
         $this->logger->debug("La pàgina HTML és invàlida: " . $this->courseYear);
         return -1;
     }
     // Date of first week is in the first table, second row, second cell.
     $firstWeek = $timetableDOM->find('table', 0)->find('tr', 1)->find('td', 1)->plaintext;
     $currWeekNum = $this->calculateCurrentWeek($firstWeek, $date);
     $this->logger->info('Current week number is ' . $currWeekNum);
     $currWeekDOM = $timetableDOM->find('table', $currWeekNum);
     if ($date) {
         $currWeekStartDate = $this->weekStartDate(new DateTime($date));
     } else {
         $currWeekStartDate = $this->weekStartDate(new DateTime());
     }
     $this->deleteWeekSessions($currWeekStartDate->format('d.m.Y H:i:s'));
     $this->logger->info("Current week start date is " . $currWeekStartDate->format('d.m.Y H:i:s'));
     //echo "////// /////// /////// Current week start date is ". $currWeekStartDate->format('d.m.Y H:i:s');
     // Create sessions for each period in the timetable and save them to the database.
     $rows = $currWeekDOM->find('tr');
     for ($row = 0; $row < sizeof($rows); $row++) {
         if ($row > 1) {
             $cells = $rows[$row]->find('div');
             $period = new Period($cells[0]->plaintext);
             $period->setCourseYear($this->courseYear);
             $this->logger->info("Start time is " . $period->getStart()->format("H:i:s") . ". End time is " . $period->getEnd()->format("H:i:s"));
             for ($cell = 0; $cell < sizeof($cells); $cell++) {
                 if ($cell > 0) {
                     // Parse the start/end times for this row's period.
                     if (trim($cells[$cell]->plaintext) === '') {
                         $this->logger->debug("Skipping cell [" . $row . "][" . $cell . "], it's empty.");
                         continue;
                     }
                     // Session start date is the week's start date + current day of week. Time is provided in the first cell of each row
                     $sessionStartDateTime = new DateTime($currWeekStartDate->format('d.m.Y'));
                     $sessionStartDateTime->add(new DateInterval('P' . strval($cell - 1) . 'D'));
                     $sessionStartDateTime->setTime($period->getStart()->format('H'), $period->getStart()->format('i'));
                     $period->setStart($sessionStartDateTime);
                     $this->logger->debug('SessionStartDateTime is: ' . $sessionStartDateTime->format('d.m.Y H:i:s'));
                     // Agafem el timestamp de l'hora que acaba la classe i la guardem a la variable period
                     $sessionEndDateTime = new DateTime($currWeekStartDate->format('d.m.Y'));
                     $sessionEndDateTime->add(new DateInterval('P' . strval($cell - 1) . 'D'));
                     $sessionEndDateTime = $sessionEndDateTime->setTime($period->getEnd()->format('H'), $period->getEnd()->format('i'));
                     $period->setEnd($sessionEndDateTime);
                     $this->logger->debug('SessionEndDateTime is: ' . $sessionEndDateTime->format('d.m.Y H:i:s'));
                     //echo "*******LA PRUEBA DEL DELITO: ".$cells[$cell]->plaintext."**********<br>";
                     // Get the plaintext for the period and insert each line into an array.
                     $this->logger->debug("Periodinfoarray is: " . var_export($cells[$cell]->plaintext, true), 'err');
                     $periodInfo = html_entity_decode($cells[$cell]->plaintext, ENT_QUOTES, 'UTF-8');
                     $periodInfo = Encoding::toUTF8($periodInfo);
                     $periodInfoArray = explode("\n", $periodInfo);
                     foreach ($periodInfoArray as $i => $value) {
                         unset($periodInfoArray[$i]);
                         $periodInfoArray[] = trim($value);
                     }
                     // Re-index the array starting from zero.
                     $period->setDetails(array_values($periodInfoArray));
                     $this->logger->debug("Trimmed periodinfoarray is: " . var_export($period->getDetails(), true));
                     //echo "parsejant<br />";
                     $this->parseSession($period);
                 }
             }
             unset($period);
         }
     }
 }
Beispiel #11
0
function nvweb_properties_render($property, $vars)
{
    global $website;
    global $current;
    global $DB;
    global $session;
    global $theme;
    global $structure;
    $out = '';
    setlocale(LC_ALL, $website->languages[$session['lang']]['system_locale']);
    // if this property is null (no value assigned (null), (empty) is a value!)
    // get the default value
    if (!isset($property->value)) {
        $property->value = $property->dvalue;
    }
    // check multilanguage properties, where the value can be saved in a language but may be (null) in another language
    if (in_array($property->type, array("text", "textarea", "rich_textarea", "link")) || $property->multilanguage == 'true') {
        // cast variable as array
        if (is_object($property->value)) {
            $property->value = (array) $property->value;
        }
        if (!isset($property->value) || !isset($property->value[$current['lang']])) {
            if (isset($property->dvalue->{$current['lang']})) {
                $property->value[$current['lang']] = $property->dvalue->{$current['lang']};
            } else {
                if (!is_array($property->value)) {
                    $property->value = array();
                }
                $property->value[$current['lang']] = $property->dvalue;
            }
        }
    }
    switch ($property->type) {
        case 'value':
            $out = $property->value;
            break;
        case 'decimal':
            $out = $property->value;
            if (isset($vars['precision'])) {
                $out = number_format($property->value, $vars['precision']);
            }
            break;
        case 'boolean':
            $out = $property->value;
            break;
        case 'option':
            $options = mb_unserialize($property->options);
            $options = (array) $options;
            switch (@$vars['return']) {
                case 'value':
                    $out = $property->value;
                    break;
                default:
                    $out = $theme->t($options[$property->value]);
            }
            break;
        case 'moption':
            $options = mb_unserialize($property->options);
            $selected = explode(",", $property->value);
            switch (@$vars['return']) {
                case 'value':
                case 'values':
                    $out = $property->value;
                    break;
                default:
                    $buffer = array();
                    foreach ($selected as $seloption) {
                        $buffer[] = '<span>' . $theme->t($options[$seloption]) . '</span>';
                    }
                    $out .= implode(', ', $buffer);
            }
            break;
        case 'text':
            $out = htmlspecialchars($property->value[$current['lang']]);
            break;
        case 'textarea':
            $out = nl2br(htmlspecialchars($property->value[$current['lang']]));
            break;
        case 'rich_textarea':
            $out = $property->value[$current['lang']];
            break;
        case 'source_code':
            if (@$property->multilanguage == 'true' || $property->multilanguage == '1') {
                $out = $property->value[$current['lang']];
            } else {
                $out = $property->value;
            }
            break;
        case 'date':
            if (!empty($vars['format'])) {
                $out = Encoding::toUTF8(strftime($vars['format'], $property->value));
            } else {
                $out = date($website->date_format, $property->value);
            }
            break;
        case 'datetime':
            if (!empty($vars['format'])) {
                $out = Encoding::toUTF8(strftime($vars['format'], $property->value));
            } else {
                $out = date($website->date_format . ' H:i', $property->value);
            }
            break;
        case 'link':
            // split title and link
            $link = explode('##', $property->value[$current['lang']]);
            if (is_array($link)) {
                $target = @$link[2];
                $title = @$link[1];
                $link = $link[0];
                if (empty($title)) {
                    $title = $link;
                }
            } else {
                $title = $property->value[$current['lang']];
                $link = $property->value[$current['lang']];
                $target = '_self';
            }
            if (strpos($link, '://') === false) {
                $link = $website->absolute_path() . $link;
            }
            if ($vars['link'] === 'false') {
                $out = $link;
            } else {
                if (isset($vars['return'])) {
                    if ($vars['return'] == 'title') {
                        $out = $title;
                    } else {
                        if ($vars['return'] == 'link' || $vars['return'] == 'url') {
                            $out = $link;
                        } else {
                            if ($vars['return'] == 'target') {
                                $out = $target;
                            }
                        }
                    }
                } else {
                    $out = '<a href="' . $link . '" target="' . $target . '">' . $title . '</a>';
                }
            }
            break;
        case 'image':
            $add = '';
            $extra = '';
            if (@$property->multilanguage == 'true' || $property->multilanguage == '1') {
                $image_id = $property->value[$session['lang']];
            } else {
                $image_id = $property->value;
            }
            if (isset($vars['width'])) {
                $add .= ' width="' . $vars['width'] . '" ';
                $extra .= '&width=' . $vars['width'];
            }
            if (isset($vars['height'])) {
                $add .= ' height="' . $vars['height'] . '" ';
                $extra .= '&height=' . $vars['height'];
            }
            if (isset($vars['border'])) {
                $extra .= '&border=' . $vars['border'];
            }
            if (isset($vars['quality'])) {
                $extra .= '&quality=' . $vars['quality'];
            }
            $img_url = NVWEB_OBJECT . '?type=image&id=' . $image_id . $extra;
            if (empty($image_id)) {
                $out = '';
            } else {
                if ($vars['return'] == 'url') {
                    $out = $img_url;
                } else {
                    // retrieve additional info (title/alt), if available
                    if (is_numeric($image_id)) {
                        $f = new file();
                        $f->load($image_id);
                        $ftitle = $f->title[$current['lang']];
                        $falt = $f->description[$current['lang']];
                        if (!empty($ftitle)) {
                            $add .= ' title="' . $ftitle . '" ';
                        }
                        if (!empty($falt)) {
                            $add .= ' alt="' . $falt . '" ';
                        }
                    }
                    $out = '<img class="' . $vars['class'] . '" src="' . $img_url . '" ' . $add . ' />';
                }
            }
            break;
        case 'file':
            if (!empty($property->value)) {
                $file = $DB->query_single('name', 'nv_files', ' id = ' . protect($property->value) . ' AND website = ' . $website->id);
                if ($vars['return'] == 'url' || $vars['return'] == 'url-download') {
                    $out = NVWEB_OBJECT . '?type=file&id=' . $property->value . '&disposition=attachment';
                } else {
                    if ($vars['return'] == 'url-inline') {
                        $out = NVWEB_OBJECT . '?type=file&id=' . $property->value . '&disposition=inline';
                    } else {
                        $out = '<a href="' . NVWEB_OBJECT . '?type=file&id=' . $property->value . '&disposition=attachment">' . $file . '</a>';
                    }
                }
            }
            break;
        case 'comment':
            $out = $property->value;
            break;
        case 'coordinates':
            $coordinates = explode('#', $property->value);
            $out = implode(',', $coordinates);
            break;
        case 'rating':
            // half stars are always enabled (ratings fixed to 0..10)
            $out = $property->value;
            // we want nearest integer down
            if ($vars['option'] == 'floor') {
                $out = floor($out / 2);
            }
            break;
        case 'color':
            $out = $property->value;
            break;
        case 'video':
            // value may be a numeric file ID or a provider#id structure, f.e. youtube#3MteSlpxCpo
            // compatible providers: file,youtube,vimeo
            if (@$property->multilanguage == 'true' || $property->multilanguage == '1') {
                $video_id = $property->value[$session['lang']];
            } else {
                $video_id = $property->value;
            }
            $provider = '';
            $reference = '';
            $add = '';
            if (isset($vars['width'])) {
                $add .= ' width="' . $vars['width'] . '" ';
            }
            if (isset($vars['height'])) {
                $add .= ' height="' . $vars['height'] . '" ';
            }
            $url_add = '&type=image';
            if (isset($vars['width'])) {
                $url_add .= '&width=' . $vars['width'] . '';
            }
            if (isset($vars['height'])) {
                $url_add .= '&height=' . $vars['height'] . '';
            }
            if (isset($vars['border'])) {
                $url_add .= '&border=' . $vars['border'] . '';
            }
            if (strpos($video_id, '#') !== false) {
                list($provider, $reference) = explode("#", $video_id);
            }
            if ($provider == 'file') {
                $video_id = $reference;
            }
            $file = new file();
            if (is_numeric($video_id)) {
                $file->load($video_id);
                $embed = file::embed('file', $file, $add);
            } else {
                if ($provider == 'youtube') {
                    $embed = file::embed('youtube', $reference, $add);
                    if (!empty($vars['part']) || $vars['part'] != 'embed') {
                        $file->load_from_youtube($reference);
                    }
                } else {
                    if ($provider == 'vimeo') {
                        $embed = file::embed('vimeo', $reference, $add);
                        if (!empty($vars['part']) || $vars['part'] != 'embed') {
                            $file->load_from_vimeo($reference);
                        }
                    }
                }
            }
            switch (@$vars['return']) {
                case 'title':
                    $out = $file->title;
                    break;
                case 'mime':
                    $out = $file->mime;
                    break;
                case 'author':
                    if (is_numeric($file->uploaded_by)) {
                        $out = $website->name;
                    } else {
                        $out = $file->uploaded_by;
                    }
                    break;
                case 'path':
                case 'url':
                    $out = $file->extra['link'];
                    break;
                case 'thumbnail_url':
                    $out = file::file_url($file->extra['thumbnail_cache']) . $url_add;
                    break;
                case 'thumbnail':
                    $out = '<img src="' . file::file_url($file->extra['thumbnail_cache']) . $url_add . '" class="' . $vars['class'] . '" ' . $add . ' />';
                    break;
                case 'reference':
                    $out = $reference;
                    break;
                case 'provider':
                    $out = $provider;
                    break;
                case 'embed':
                default:
                    $out = $embed;
            }
            break;
        case 'article':
            // TO DO
            break;
        case 'category':
            $return = @$vars['return'];
            switch ($return) {
                case 'title':
                case 'name':
                    nvweb_menu_load_dictionary();
                    $out = $structure['dictionary'][$property->value];
                    break;
                case 'url':
                case 'link':
                    $out = nvweb_source_url('structure', $property->value);
                    break;
                default:
                    $out = $property->value;
            }
            break;
        case 'categories':
            $return = @$vars['return'];
            $value = explode(",", $property->value);
            $position = intval(@vars['position']) + 0;
            switch ($return) {
                case 'title':
                case 'name':
                    nvweb_menu_load_dictionary();
                    $out = $structure['dictionary'][$value[$position]];
                    break;
                case 'url':
                case 'link':
                    $out = nvweb_source_url('structure', $value[$position]);
                    break;
                default:
                    $out = $property->value;
            }
            break;
        case 'country':
            $return = @$vars['return'];
            switch ($return) {
                case 'name':
                    $countries = property::countries();
                    $out = $countries[$property->value];
                    break;
                case 'id':
                case 'code':
                default:
                    $out = $property->value;
                    break;
            }
            break;
        case 'elements':
            $out = $property->value;
            break;
        case 'element':
        case 'item':
            // deprecated
            $return = @$vars['return'];
            switch ($return) {
                case 'title':
                    $item = new item();
                    $item->load($property->value);
                    $out = $item->dictionary[$current['lang']]['title'];
                    break;
                case 'url':
                case 'path':
                    $out = nvweb_source_url('item', $property->value, $current['lang']);
                    break;
                case 'section':
                    $item = new item();
                    $item->load($property->value);
                    $out = $item->dictionary[$current['lang']]['section-' . $vars['section']];
                    break;
                case 'property':
                    $params = array();
                    foreach ($vars as $attr_name => $attr_value) {
                        if (strpos($attr_name, 'element-property-') === 0) {
                            $attr_name = str_replace('element-property-', '', $attr_name);
                            $params[$attr_name] = $attr_value;
                        } else {
                            if ($attr_name == 'element-property') {
                                $params['property'] = $attr_value;
                            }
                        }
                    }
                    //  default parameters
                    $params['mode'] = 'item';
                    $params['id'] = $property->value;
                    $out = nvweb_properties($params);
                    break;
                case 'id':
                default:
                    $out = $property->value;
                    break;
            }
            break;
        default:
    }
    return $out;
}
Beispiel #12
0
function nvweb_comments($vars = array())
{
    global $website;
    global $DB;
    global $current;
    global $webgets;
    global $dictionary;
    global $webuser;
    global $theme;
    global $events;
    global $session;
    $webget = 'comments';
    if (!isset($webgets[$webget])) {
        $webgets[$webget] = array();
        global $lang;
        if (empty($lang)) {
            $lang = new language();
            $lang->load($current['lang']);
        }
        // default translations
        $webgets[$webget]['translations'] = array('post_a_comment' => t(379, 'Post a comment'), 'name' => t(159, 'Name'), 'email' => t(44, 'E-Mail'), 'website' => t(177, 'Website'), 'message' => t(380, 'Message'), 'email_will_not_be_published' => t(381, 'E-Mail will not be published'), 'submit' => t(382, 'Submit'), 'sign_in_or_sign_up_to_post_a_comment' => t(383, 'Sign in or Sign up to post a comment'), 'comments_on_this_entry_are_closed' => t(384, 'Comments on this entry are closed'), 'please_dont_leave_any_field_blank' => t(385, 'Please don\'t leave any field blank'), 'your_comment_has_been_received_and_will_be_published_shortly' => t(386, 'Your comment has been received and will be published shortly'), 'new_comment' => t(387, 'New comment'), 'review_comments' => t(388, 'Review comments'));
        // theme translations
        // if the web theme has custom translations for this string subtypes, use it (for the user selected language)
        /* just add the following translations to your json theme dictionary:
        
        			"post_a_comment": "Post a comment",
        			"name": "Name",
        			"email": "E-Mail",
        			"website": "Website",
        			"message": "Message",
        			"email_will_not_be_published": "E-Mail will not be published",
        			"submit": "Submit",
        			"sign_in_or_sign_up_to_post_a_comment": "Sign in or Sign up to post a comment",
        			"comments_on_this_entry_are_closed": "Comments on this entry are closed",
        			"please_dont_leave_any_field_blank": "Please don't leave any field blank",
        			"your_comment_has_been_received_and_will_be_published_shortly": "Your comment has been received and will be published shortly",
        			"new_comment": "New comment",
        			"review_comments": "Review comments"
        		*/
        if (!empty($website->theme) && method_exists($theme, 't')) {
            foreach ($webgets[$webget]['translations'] as $code => $text) {
                $theme_translation = $theme->t($code);
                if (!empty($theme_translation) && $theme_translation != $code) {
                    $webgets[$webget]['translations'][$code] = $theme_translation;
                }
            }
        }
    }
    // set default callback
    if (empty($vars['callback'])) {
        $vars['callback'] = 'alert';
    }
    // check callback attributes
    $callback = $vars['callback'];
    if (!empty($vars['alert_callback'])) {
        $callback = $vars['alert_callback'];
    } else {
        if (!empty($vars['callback_alert'])) {
            $callback = $vars['callback_alert'];
        }
    }
    $callback_error = $callback;
    if (!empty($vars['error_callback'])) {
        $callback_error = $vars['error_callback'];
    } else {
        if (!empty($vars['callback_error'])) {
            $callback_error = $vars['callback_error'];
        }
    }
    $out = '';
    // if the current page belongs to a structure entry
    // we need to get the associated elements to retrieve and post its comments
    // (because structure entry pages can't have associated comments)
    // so, ONLY the FIRST element associated to a category can have comments in a structure entry page
    // (of course if the element has its own page, it can have its own comments)
    $element = $current['object'];
    if ($current['type'] == 'structure') {
        if (empty($current['structure_elements'])) {
            $current['structure_elements'] = $element->elements();
        }
        $element = $current['structure_elements'][0];
    }
    switch (@$vars['mode']) {
        case 'process':
            if (isset($_GET['nv_approve_comment'])) {
                // process 1-click comment approval
                $comment = new comment();
                $comment->load($_GET['id']);
                if (!empty($comment->id) && $comment->status == -1) {
                    $hash = $_GET['hash'];
                    if ($hash == sha1($comment->id . $comment->email . APP_UNIQUE . serialize($website->contact_emails))) {
                        // hash check passed
                        $comment->status = 0;
                        $comment->save();
                        $response = t(555, "Item has been successfully published.");
                        if ($vars['notify'] == 'inline' || $callback == 'inline') {
                            $out = '<div class="comment-success">' . $response . '</div>';
                        } else {
                            if (!isset($vars['notify']) || $vars['notify'] == 'callback') {
                                nvweb_after_body("js", $callback . '("' . $response . '");');
                            }
                        }
                    } else {
                        $response = t(344, "Security error");
                        if ($vars['notify'] == 'inline' || $callback_error == 'inline') {
                            $out = '<div class="comment-error">' . $response . '</div>';
                        } else {
                            if (!isset($vars['notify']) || $vars['notify'] == 'callback') {
                                nvweb_after_body("js", $callback_error . '("' . $response . '");');
                            }
                        }
                    }
                } else {
                    $response = t(56, "Unexpected error");
                    if ($vars['notify'] == 'inline' || $callback_error == 'inline') {
                        $out = '<div class="comment-error">' . $response . '</div>';
                    } else {
                        if (!isset($vars['notify']) || $vars['notify'] == 'callback') {
                            nvweb_after_body("js", $callback_error . '("' . $response . '");');
                        }
                    }
                }
            }
            if (isset($_GET['nv_remove_comment'])) {
                // process 1-click comment removal
                $comment = new comment();
                $comment->load($_GET['id']);
                if (!empty($comment->id) && $comment->status == -1) {
                    $hash = $_GET['hash'];
                    if ($hash == sha1($comment->id . $comment->email . APP_UNIQUE . serialize($website->contact_emails))) {
                        // hash check passed
                        $comment->delete();
                        $response = t(55, "Item successfully deleted");
                        if ($vars['notify'] == 'inline' || $callback == 'inline') {
                            $out = '<div class="comment-success">' . $response . '</div>';
                        } else {
                            if (!isset($vars['notify']) || $vars['notify'] == 'callback') {
                                nvweb_after_body("js", $callback . '("' . $response . '");');
                            }
                        }
                    } else {
                        $response = t(344, "Security error");
                        if ($vars['notify'] == 'inline' || $callback_error == 'inline') {
                            $out = '<div class="comment-error">' . $response . '</div>';
                        } else {
                            if (!isset($vars['notify']) || $vars['notify'] == 'callback') {
                                nvweb_after_body("js", $callback_error . '("' . $response . '");');
                            }
                        }
                    }
                } else {
                    $response = t(56, "Unexpected error");
                    if ($vars['notify'] == 'inline' || $callback_error == 'inline') {
                        $out = '<div class="comment-error">' . $response . '</div>';
                    } else {
                        if (!isset($vars['notify']) || $vars['notify'] == 'callback') {
                            nvweb_after_body("js", $callback_error . '("' . $response . '");');
                        }
                    }
                }
            }
            if ($_REQUEST['form-type'] == 'comment-reply' || isset($_POST[$vars['field-message']])) {
                // add comment
                if (empty($vars['field-name'])) {
                    $vars['field-name'] = 'reply-name';
                }
                if (empty($vars['field-email'])) {
                    $vars['field-email'] = 'reply-email';
                }
                if (empty($vars['field-url'])) {
                    $vars['field-url'] = 'reply-url';
                }
                if (empty($vars['field-message'])) {
                    $vars['field-message'] = 'reply-message';
                }
                if (!empty($vars['element'])) {
                    $element = $vars['element'];
                }
                $comment_name = @$_REQUEST[$vars['field-name']];
                $comment_email = @$_REQUEST[$vars['field-email']];
                $comment_url = @$_REQUEST[$vars['field-url']];
                $comment_message = @$_REQUEST[$vars['field-message']];
                if ((empty($comment_name) || empty($comment_email)) && empty($webuser->id) || empty($comment_message)) {
                    $response = $webgets[$webget]['translations']['please_dont_leave_any_field_blank'];
                    if ($vars['notify'] == 'inline' || $callback_error == 'inline') {
                        $out = '<div class="comment-error">' . $response . '</div>';
                    } else {
                        if (!isset($vars['notify']) || $vars['notify'] == 'callback') {
                            nvweb_after_body("js", $callback_error . '("' . $response . '");');
                        }
                    }
                    return $out;
                }
                $status = -1;
                // new comment, not approved
                if (empty($element->comments_moderator)) {
                    $status = 0;
                }
                // all comments auto-approved
                // remove any <nv /> or {{nv}} tag
                $comment_name = core_remove_nvtags($comment_name);
                $comment_name = strip_tags($comment_name);
                $comment_message = core_remove_nvtags($comment_message);
                $comment = new comment();
                $comment->id = 0;
                $comment->website = $website->id;
                $comment->item = $element->id;
                $comment->user = empty($webuser->id) ? 0 : $webuser->id;
                $comment->name = $comment_name;
                $comment->email = filter_var($comment_email, FILTER_SANITIZE_EMAIL);
                $comment->url = filter_var($comment_url, FILTER_SANITIZE_URL);
                $comment->ip = core_ip();
                $comment->date_created = core_time();
                $comment->date_modified = 0;
                $comment->status = $status;
                $comment->message = $comment_message;
                $properties = array();
                // check if there are comment properties values
                if (isset($vars['field-properties-prefix'])) {
                    // check every possible property
                    $e_properties = property::elements($element->template, 'comment');
                    for ($ep = 0; $ep < count($e_properties); $ep++) {
                        if (isset($_POST[$vars['field-properties-prefix'] . $e_properties[$ep]->id])) {
                            $properties[$e_properties[$ep]->id] = $_POST[$vars['field-properties-prefix'] . $e_properties[$ep]->id];
                        }
                    }
                }
                // trigger the "new_comment" event through the extensions system before inserting it!
                $extensions_messages = $events->trigger('comment', 'before_insert', array('comment' => $comment, 'properties' => $properties));
                foreach ($extensions_messages as $ext_name => $ext_result) {
                    if (isset($ext_result['error'])) {
                        $response = $ext_result['error'];
                        if ($vars['notify'] == 'inline' || $callback_error == 'inline') {
                            $out = '<div class="comment-error">' . $response . '</div>';
                        } else {
                            if (!isset($vars['notify']) || $vars['notify'] == 'callback') {
                                nvweb_after_body("js", $callback_error . '("' . $response . '");');
                            }
                        }
                        return $out;
                    }
                }
                $comment->insert();
                if (!empty($properties)) {
                    property::save_properties_from_array('comment', $comment->id, $element->template, $properties);
                }
                // reload the element to retrieve the new comments
                $element = new item();
                $element->load($comment->item);
                if ($current['type'] == 'item' && !isset($vars['element'])) {
                    $current['object'] = $element;
                }
                // trigger the "new_comment" event through the extensions system
                $events->trigger('comment', 'after_insert', array('comment' => &$comment, 'properties' => $properties));
                if (!empty($comment->id)) {
                    if ($status == -1) {
                        $response = $webgets[$webget]['translations']['your_comment_has_been_received_and_will_be_published_shortly'];
                        if ($vars['notify'] == 'inline' || $callback_error == 'inline') {
                            $out = '<div class="comment-success">' . $response . '</div>';
                        } else {
                            if (!isset($vars['notify']) || $vars['notify'] == 'callback') {
                                nvweb_after_body("js", $callback . '("' . $response . '");');
                            }
                        }
                    } else {
                        $response = $webgets[$webget]['translations']['your_comment_has_been_received_and_will_be_published_shortly'];
                        if ($vars['notify'] == 'inline' || $callback_error == 'inline') {
                            $out = '<div class="comment-success">' . $response . '</div>';
                        } else {
                            if (!isset($vars['notify']) || $vars['notify'] == 'callback') {
                                nvweb_after_body("js", $callback . '("' . $response . '");');
                            }
                        }
                    }
                }
                $notify_addresses = $website->contact_emails;
                if (!empty($element->comments_moderator)) {
                    $notify_addresses[] = user::email_of($element->comments_moderator);
                }
                $hash = sha1($comment->id . $comment->email . APP_UNIQUE . serialize($website->contact_emails));
                $base_url = nvweb_source_url('element', $element->id);
                // default colors
                $background_color = '#E5F1FF';
                $text_color = '#595959';
                $title_color = '#595959';
                $background_color_db = $DB->query_single('value', 'nv_permissions', 'name = ' . protect("nvweb.comments.background_color") . ' AND website = ' . protect($website->id), 'id DESC');
                $text_color_db = $DB->query_single('value', 'nv_permissions', 'name = ' . protect("nvweb.comments.text_color") . ' AND website = ' . protect($website->id), 'id DESC');
                $title_color_db = $DB->query_single('value', 'nv_permissions', 'name = ' . protect("nvweb.comments.titles_color") . ' AND website = ' . protect($website->id), 'id DESC');
                if (!empty($background_color_db)) {
                    $background_color = str_replace('"', '', $background_color_db);
                }
                if (!empty($text_color_db)) {
                    $text_color = str_replace('"', '', $text_color_db);
                }
                if (!empty($title_color_db)) {
                    $title_color = str_replace('"', '', $title_color_db);
                }
                $message = navigate_compose_email(array(array('title' => t(9, 'Content'), 'content' => $element->dictionary[$current['lang']]['title']), array('title' => $webgets[$webget]['translations']['name'], 'content' => $comment_name . @$webuser->username), array('title' => $webgets[$webget]['translations']['email'], 'content' => $comment_email . @$webuser->email), array('title' => $webgets[$webget]['translations']['website'], 'content' => $comment_url . @$webuser->social_website), array('title' => $webgets[$webget]['translations']['message'], 'content' => nl2br($comment_message)), array('footer' => '<a href="' . NAVIGATE_URL . '/' . NAVIGATE_MAIN . '?wid=' . $website->id . '&fid=10&act=2&tab=5&id=' . $element->id . '"><strong>' . $webgets[$webget]['translations']['review_comments'] . '</strong></a>' . '&nbsp;&nbsp;|&nbsp;&nbsp;' . '<a style=" color: #008830" href="' . $base_url . '?nv_approve_comment&id=' . $comment->id . '&hash=' . $hash . '">' . t(258, "Publish") . '</a>' . '&nbsp;&nbsp;|&nbsp;&nbsp;' . '<a style=" color: #FF0090" href="' . $base_url . '?nv_remove_comment&id=' . $comment->id . '&hash=' . $hash . '">' . t(525, "Remove comment (without confirmation)") . '</a>')), array('background' => $background_color, 'title-color' => $title_color, 'content-color' => $text_color));
                // trying to implement One-Click actions (used in Google GMail)
                // You need to be registered with Google first: https://developers.google.com/gmail/markup/registering-with-google
                $one_click_actions = '
                    <script type="application/ld+json">
                    {
                        "@context": "http://schema.org",
                        "@type": "EmailMessage",
                        "potentialAction":
                        {
                            "@type": "ViewAction",
                            "name": "' . $webgets[$webget]['translations']['review_comments'] . '",
                            "url": "' . NAVIGATE_URL . '/' . NAVIGATE_MAIN . '?wid=' . $website->id . '&fid=10&act=2&tab=5&id=' . $element->id . '"
                        }
                    }
                    </script>
				';
                $message = '<html><head>' . $one_click_actions . '</head><body>' . $message . '</body></html>';
                foreach ($website->contact_emails as $contact_address) {
                    @nvweb_send_email($website->name . ' | ' . $webgets[$webget]['translations']['new_comment'], $message, $contact_address, null, true);
                }
            }
            break;
        case 'reply':
            if ($element->comments_enabled_to == 2 && empty($webuser->id)) {
                // Post a comment form (unsigned users)
                $out = '
					<div class="comments-reply">
						<div><div class="comments-reply-info">' . $webgets[$webget]['translations']['post_a_comment'] . '</div></div>
						<br />
						<form action="' . NVWEB_ABSOLUTE . '/' . $current['route'] . '" method="post">
							<input type="hidden" name="form-type" value="comment-reply" />
							<div class="comments-reply-field"><label>' . $webgets[$webget]['translations']['name'] . '</label> <input type="text" name="reply-name" value="" /></div>
							<div class="comments-reply-field"><label>' . $webgets[$webget]['translations']['email'] . ' *</label> <input type="text" name="reply-email" value="" /></div>
							<div class="comments-reply-field"><label>' . $webgets[$webget]['translations']['message'] . '</label> <textarea name="reply-message"></textarea></div>
							<!-- {{navigate-comments-reply-extra-fields-placeholder}} -->
							<div class="comments-reply-field comments-reply-field-info-email"><label>&nbsp;</label> * ' . $webgets[$webget]['translations']['email_will_not_be_published'] . '</div>
							<div class="comments-reply-field comments-reply-field-submit"><input class="comments-reply-submit" type="submit" value="' . $webgets[$webget]['translations']['submit'] . '" /></div>
						</form>
					</div>
				';
                $extensions_messages = $events->trigger('comment', 'reply_extra_fields', array('html' => &$out));
                // add any extra field generated
                if (!empty($extensions_messages)) {
                    $extra_fields = array_map(function ($v) {
                        return $v;
                    }, array_values($extensions_messages));
                    $out = str_replace('<!-- {{navigate-comments-reply-extra-fields-placeholder}} -->', implode("\n", $extra_fields), $out);
                }
            } else {
                if ($element->comments_enabled_to > 0 && !empty($webuser->id)) {
                    // Post a comment form (signed in users)
                    if (empty($vars['avatar_size'])) {
                        $vars['avatar_size'] = 32;
                    }
                    $avatar_url = NVWEB_OBJECT . '?type=blank';
                    if (!empty($webuser->avatar)) {
                        $avatar_url = NVWEB_OBJECT . '?wid=' . $website->id . '&id=' . $webuser->avatar . '&amp;disposition=inline&width=' . $vars['avatar_size'] . '&height=' . $vars['avatar_size'];
                    }
                    $out = '
					<div class="comments-reply">
						<div><div class="comments-reply-info">' . $webgets[$webget]['translations']['post_a_comment'] . '</div></div>
						<br />
						<form action="' . NVWEB_ABSOLUTE . '/' . $current['route'] . '" method="post">
							<input type="hidden" name="form-type" value="comment-reply" />
							<div class="comments-reply-field"><label style="display: none;">&nbsp;</label> <img src="' . $avatar_url . '" width="' . $vars['avatar_size'] . '" height="' . $vars['avatar_size'] . '" align="absmiddle" /> <span class="comments-reply-username">' . $webuser->username . '</span><a class="comments-reply-signout" href="?webuser_signout">(x)</a></div>
							<br />
							<div class="comments-reply-field"><label>' . $webgets[$webget]['translations']['message'] . '</label> <textarea name="reply-message"></textarea></div>
							<!-- {{navigate-comments-reply-extra-fields-placeholder}} -->
							<div class="comments-reply-field-submit"><input class="comments-reply-submit" type="submit" value="' . $webgets[$webget]['translations']['submit'] . '" /></div>
						</form>
					</div>
				';
                    $extensions_messages = $events->trigger('comment', 'reply_extra_fields', array('html' => $out));
                    // add any extra field generated
                    if (!empty($extensions_messages)) {
                        $extra_fields = array_map(function ($v) {
                            return $v;
                        }, array_values($extensions_messages));
                        $out = str_replace('<!-- {{navigate-comments-reply-extra-fields-placeholder}} -->', implode("\n", $extra_fields), $out);
                    }
                } else {
                    if ($element->comments_enabled_to == 1) {
                        $out = '<div class="comments-reply">
                            <div class="comments-reply-info">' . $webgets[$webget]['translations']['sign_in_or_sign_up_to_post_a_comment'] . '</div>
                        </div>';
                    } else {
                        $out = '<div class="comments-reply">
                            <div class="comments-reply-info">' . $webgets[$webget]['translations']['comments_on_this_entry_are_closed'] . '</div>
                        </div>';
                    }
                }
            }
            break;
        case 'comments':
            setlocale(LC_ALL, $website->languages[$session['lang']]['system_locale']);
            list($comments, $comments_total) = nvweb_comments_list(0, NULL, NULL, $vars['order']);
            // get all comments of the current entry
            if (empty($vars['avatar_size'])) {
                $vars['avatar_size'] = '48';
            }
            if (empty($vars['date_format'])) {
                $vars['date_format'] = '%d %B %Y %H:%M';
            }
            for ($c = 0; $c < $comments_total; $c++) {
                $avatar = $comments[$c]->avatar;
                if (!empty($avatar)) {
                    $avatar = '<img src="' . NVWEB_OBJECT . '?type=image&id=' . $avatar . '" width="' . $vars['avatar_size'] . 'px" height="' . $vars['avatar_size'] . 'px"/>';
                } else {
                    $avatar = '<img src="data:image/gif;base64,R0lGODlhAQABAPAAAP///wAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw==" width="' . $vars['avatar_size'] . 'px" height="' . $vars['avatar_size'] . 'px"/>';
                }
                $comment = new comment();
                $comment->load_from_resultset(array($comments[$c]));
                $depth = 'data-depth="' . $comment->depth() . '"';
                $out .= '
					<div class="comment"' . $depth . '>
						<div class="comment-avatar">' . $avatar . '</div>
						<div class="comment-username">' . (!empty($comments[$c]->username) ? $comments[$c]->username : $comments[$c]->name) . '</div>
						<div class="comment-date">' . Encoding::toUTF8(strftime($vars['date_format'], $comments[$c]->date_created)) . '</div>
						<div class="comment-message">' . nl2br($comments[$c]->message) . '</div>
						<div style="clear:both"></div>
					</div>
				';
            }
            break;
    }
    return $out;
}
Beispiel #13
0
 public function retrieveContent()
 {
     // convert page to utf-8
     $this->setOriginal(Encoding::toUTF8(Utils::get_external_file($this->getUrl(), 15)));
     return $this->getOriginal() != null and strlen($this->getOriginal()) > 0;
 }
Beispiel #14
0
 public function parseEntriesCSV($fp)
 {
     //$lines = explode("\r\n", $txt);
     // assumes that the first line is the header
     //$lines[0] = trim($lines[0], ',');
     try {
         $headers = fgetcsv($fp);
         //$this->parseCSVLine($lines[0]);
     } catch (Exception $err) {
         throw new Exception(str_replace('xx', '0', $err->getMessage()));
     }
     $vals = array();
     $ents = array();
     $fields = array_keys($this->fields);
     $x = 0;
     while ($vals = fgetcsv($fp)) {
         $entry = new EcEntry($this);
         $vars = array_keys(get_object_vars($entry));
         $varLen = count($vars);
         $ent = array_combine($headers, $vals);
         for ($v = 0; $v < $varLen; ++$v) {
             if (array_key_exists($vars[$v], $ent)) {
                 $entry->{$vars}[$v] = $ent[$vars[$v]];
             }
         }
         $ttl = count($fields);
         for ($f = 0; $f < $ttl; ++$f) {
             if ($this->fields[$fields[$f]]->type == 'location' || $this->fields[$fields[$f]]->type == 'gps') {
                 $lat = sprintf('%s_lattitude', $fields[$f]);
                 $lon = sprintf('%s_longitude', $fields[$f]);
                 $alt = sprintf('%s_alttitude', $fields[$f]);
                 $acc = sprintf('%s_accuarcy', $fields[$f]);
                 $src = sprintf('%s_provider', $fields[$f]);
                 $bearing = sprintf('%s_bearing', $fields[$f]);
                 $entry->values[$fields[$f]] = array('latitude' => getValIfExists($ent, $lat), 'longitude' => getValIfExists($ent, $lon), 'altitude' => getValIfExists($ent, $alt), 'accuracy' => getValIfExists($ent, $acc), 'provider' => getValIfExists($ent, $src), 'bearing' => getValIfExists($ent, $bearing));
             } elseif (($this->fields[$fields[$f]]->type == "photo" || $this->fields[$fields[$f]]->type == "video" || $this->fields[$fields[$f]]->type == "audio") && preg_match('/^https?:\\/\\//', $ent[$fields[$f]])) {
                 $newfn = sprintf('%s_%s_%s', $this->projectName, $this->name, $ent[$this->key]);
                 $entry->values[$fields[$f]] = str_replace('~tn', '', $newfn);
                 /*$mqueue->writeMessage('getFile', array($ent[$fields[$f]], $newfn));*/
             } else {
                 if (array_key_exists($fields[$f], $ent)) {
                     $entry->values[$fields[$f]] = Encoding::toUTF8($ent[$fields[$f]]);
                 }
             }
         }
         if (!preg_match('/^[0-9]+$/', $entry->created)) {
             $date = false;
             try {
                 $date = new DateTime($entry->created, new DateTimeZone('UTC'));
             } catch (Exception $ex) {
                 $date = new DateTime('now', new DateTimeZone('UTC'));
             }
             $entry->created = $date->getTimestamp();
         }
         $entry->deviceId = 'web upload';
         array_push($ents, $entry);
         if (++$x % 100 == 0) {
             $entry->postEntries($ents);
             unset($ents);
             $ents = array();
         }
     }
     if (count($ents) > 0) {
         $entry->postEntries($ents);
     }
     return true;
 }
 public function fixEncoding($string = '')
 {
     if (class_exists("Encoding")) {
         try {
             $string1 = Encoding::toUTF8($string);
             return Encoding::fixUTF8($string1);
         } catch (Exception $e) {
             return $string;
         }
     } else {
         return $string;
     }
 }
Beispiel #16
0
<?php

require_once "../autoload.php";
function is($desc, $a, $b)
{
    if ($a === $b) {
        echo '<span style="background-color: green;">&nbsp;Pass&nbsp;</span> ' . $desc . "<br/>\n";
    } else {
        echo '<span style="background-color: red;">&nbsp;Failed&nbsp;</span> ' . $desc . "<br/>\n";
    }
    return $a === $b;
}
$orig = "αšΓ‘šÑőαιν";
is("Encoding::toUTF8() convierte a UTF-8 todos los caracteres que no son ya UTF-8, teniendo en cuenta los que son Windows-1252, pero dejando sin cambios a los que ya son UTF-8", Encoding::toUTF8($orig), "ÑőњÑőÑéí");
$utf8_from_iso = "Β€ΒΒ‚ΒƒΒ„Β…Β†Β‡ΒˆΒ‰ΒŠΒ‹ΒŒΒΒŽΒΒΒ‘Β’Β“Β”Β•Β–Β—Β˜Β™ΒšΒ›ΒœΒΒžΒŸ";
$utf8_from_win = "β‚¬Ββ€šΖ’β€žβ€¦β€ β€‘Λ†β€°Ε β€ΉΕ’ΒΕ½ΒΒβ€˜β€™β€œβ€β€’β€“β€”Λœβ„’Ε‘β€ΊΕ“ΒΕΎΕΈ";
is("Encoding::UTF8FixWin1252Chars() convierte UTF-8 a UTF-8 corrigiendo caracteres especiales de Windows-1252", Encoding::UTF8FixWin1252Chars($utf8_from_iso), $utf8_from_win);
is("Encoding::toLatin1() convierte los UTF-8 a Windows-1252", Encoding::toLatin1($orig), "αšαšαšαιν");
is("Encoding::toLatin1() convierte los UTF-8 con caracteres convertidos desde Windows-1252 a Windows-1252", Encoding::toLatin1($utf8_from_win), "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ");
is("Encoding::toLatin1() convierte los UTF-8 con caracteres convertidos desde ISO8859-1 a Windows-1252", Encoding::toLatin1($utf8_from_iso), "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ");
is("Encoding::toWin1252() convierte los UTF-8 a Windows-1252", Encoding::toWin1252($orig), "αšαšαšαιν");
is("Encoding::toWin1252() convierte los UTF-8 con caracteres convertidos desde Windows-1252 a Windows-1252", Encoding::toWin1252($utf8_from_win), "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ");
is("Encoding::toWin1252() convierte los UTF-8 con caracteres convertidos desde ISO8859-1 a Windows-1252", Encoding::toWin1252($utf8_from_iso), "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ");
is("Encoding::fixUTF8() corrige UTF-8 convertido repetidamente", Encoding::fixUTF8(utf8_encode(utf8_encode(utf8_encode($orig)))), "ÑőÑőÑőÑéí");
 public static function encode($encodingLabel, $text)
 {
     $encodingLabel = self::normalizeEncoding($encodingLabel);
     if ($encodingLabel == 'UTF-8') {
         return Encoding::toUTF8($text);
     }
     if ($encodingLabel == 'ISO-8859-1') {
         return Encoding::toLatin1($text);
     }
 }
 $xml_content = simplexml_load_file($dir . basename($file));
 $authors = $xml_content->feature[0]['authors'];
 $title = $xml_content->feature[0]['title'];
 for ($i = 2; $i < count($xml_content); $i++) {
     $type = (string) $xml_content->feature[$i]['type'];
     $obfuscation = (string) $xml_content->feature[$i]['manual_obfuscation'];
     $this_lang = (string) $xml_content->feature[$i]['this_language'];
     $src_lang = (string) $xml_content->feature[$i]['source_language'];
     $this_offset = intval($xml_content->feature[$i]['this_offset']);
     $this_lenght = intval($xml_content->feature[$i]['this_length']);
     $src_offset = intval($xml_content->feature[$i]['source_offset']);
     $src_lenght = intval($xml_content->feature[$i]['source_length']);
     $src_txt = (string) $xml_content->feature[$i]['source_reference'];
     $src_ref = (string) basename($src_txt, '.txt');
     $src_content = loadFile($src_dir . $src_txt);
     $this_feature_content = $encode->toUTF8(substr($encode->toLatin1($this_content), $this_offset, $this_lenght));
     $src_feature_content = $encode->toUTF8(substr($encode->toLatin1($src_content), $src_offset + 1, $src_lenght + 1));
     writeFile($this_lang . '/SUSP_' . $j . '_' . ($i - 2) . '.txt', $this_feature_content);
     writeFile($src_lang . '/SRC_' . $j . '_' . ($i - 2) . '.txt', $src_feature_content);
     $noiseNumber = substr_count($this_feature_content, ' vna ');
     $noiseNumber += substr_count($this_feature_content, ' vn ');
     $noiseNumber += substr_count($this_feature_content, ' i ');
     $noise = $noiseNumber >= 5 ? 'true' : 'false';
     $textualEquivalent = new TextualEquivalent($name, $this_lang, $this_offset, $this_lenght, $this_feature_content, $src_ref, $src_lang, $src_offset, $src_lenght, $src_feature_content, $type, $obfuscation, $noise);
     $string = '<?xml version="1.0" encoding="UTF-8"?>' . chr(10);
     $string .= '<info>' . chr(10);
     $string .= '<sourceIDDoc>' . $src_ref . '</sourceIDDoc>' . chr(10);
     $string .= '<sourceTextLanguage>' . $src_lang . '</sourceTextLanguage>' . chr(10);
     $string .= '<sourceTextOffset>' . $src_offset . '</sourceTextOffset>' . chr(10);
     $string .= '<sourceTextLength>' . $src_lenght . '</sourceTextLength>' . chr(10);
     $string .= '<sourceTextContent>' . $src_feature_content . '</sourceTextContent>' . chr(10);
 * This work is licensed under a Creative Commons Attribution-ShareAlike 4.0 International License.
 * For more information, see http://creativecommons.org/licenses/by-sa/4.0/
 */
set_time_limit(100000);
ini_set('display_errors', 1);
error_reporting(E_ALL);
/**
 * @see https://github.com/neitanod/forceutf8
 */
require_once 'Encoding.php';
/**
 * @see https://github.com/boudinfl/taln-archives
 */
$path = './input_taln_file.bib';
$encode = new Encoding();
$content = $encode->toUTF8(loadFile($path));
$articles = parseBibTex($content);
foreach ($articles as $article) {
    $authors = parseAuthors($article);
    $url = parseUrl($article);
    $ScholarUrlsResult = getLinksOfScholarResult(googleScholarResearch($authors));
    $SERPUrlsResult = getLinksOfGoogleResult(launchGoogleRequestAndGetResults($authors));
    writeFile(basename($path), $url, $ScholarUrlsResult, $SERPUrlsResult);
}
/* * ***********************
 *      FUNCTIONS
 * *********************** */
function googleScholarResearch($authors)
{
    $url = 'https://scholar.google.fr/scholar?hl=fr&q=' . rawurlencode($authors);
    $content = file_get_contents($url);
 private function previousIdentifications($unit)
 {
     $dets = array();
     $date = array();
     $list = $unit->getElementsByTagName('Identification');
     if ($list->length > 1) {
         // This skips all Units that have a single Identification
         // (which is assumed to be the current identification).
         foreach ($list as $item) {
             $preferredflag = $item->getElementsByTagName('PreferredFlag');
             if ($preferredflag->length > 0 && in_array($preferredflag->item(0)->nodeValue, array('0', 'FALSE', 'false'))) {
                 // There is a preferred flag and it resolves to FALSE.
                 $det = array();
                 $nlist = $item->getElementsByTagName('FullScientificNameString');
                 $det['FullScientificNameString'] = $nlist->length > 0 ? $nlist->item(0)->nodeValue : FALSE;
                 $nlist = $item->getElementsByTagName('IdentificationQualifier');
                 if ($nlist->length > 0) {
                     $det['IdentificationQualifier'] = $nlist->item(0)->nodeValue;
                     $det['IdentificationQualifierInsertionPoint'] = $nlist->item(0)->getAttribute('insertionpoint');
                 } else {
                     $det['IdentificationQualifier'] = FALSE;
                     $det['IdentificationQualifierInsertionPoint'] = FALSE;
                 }
                 $nlist = $item->getElementsByTagName('NameAddendum');
                 $det['NameAddendum'] = $nlist->length > 0 ? $nlist->item(0)->nodeValue : FALSE;
                 $nlist = $item->getElementsByTagName('HybridFlag');
                 if ($nlist->length > 0) {
                     $det['HybridFlag'] = $nlist->item(0)->nodeValue;
                     $det['HybridFlagInsertionPoint'] = $nlist->item(0)->getAttribute('insertionpoint');
                 } else {
                     $det['HybridFlag'] = FALSE;
                     $det['HybridFlagInsertionPoint'] = FALSE;
                 }
                 $nlist = $item->getElementsByTagName('IdentifierRole');
                 $det['IdentifierRole'] = $nlist->length > 0 ? $nlist->item(0)->nodeValue : FALSE;
                 $nlist = $item->getElementsByTagName('IdentifiersText');
                 $det['IdentifiersText'] = $nlist->length > 0 ? $nlist->item(0)->nodeValue : FALSE;
                 $nlist = $item->getElementsByTagName('ISODateTimeBegin');
                 $det['IdentificationDate'] = $nlist->length > 0 ? $nlist->item(0)->nodeValue : FALSE;
                 $date[] = $nlist->length > 0 ? $nlist->item(0)->nodeValue : 'ZZZZ';
                 $nlist = $item->getElementsByTagName('Notes');
                 $det['IdentificationNotes'] = $nlist->length > 0 ? $nlist->item(0)->nodeValue : FALSE;
                 $dets[] = $det;
             }
         }
         // previous identifications are sorted by identification date
         array_multisort($date, SORT_ASC, $dets);
         $previousDets = array();
         foreach ($dets as $index => $det) {
             $prev = '';
             // Scientific name
             $sciname = $det['FullScientificNameString'];
             $scinameBits = explode(' ', $sciname);
             if ($det['HybridFlag'] && $det['HybridFlagInsertionPoint']) {
                 $scinameBits = explode(' ', $sciname);
                 $scinameBits[$det['HybridFlagInsertionPoint'] - 1] = Encoding::toUTF8('×') . $scinameBits[$det['HybridFlagInsertionPoint'] - 1];
                 $sciname = implode(' ', $scinameBits);
             }
             if ($det['IdentificationQualifier'] && $det['IdentificationQualifierInsertionPoint']) {
                 $scinameBits = explode(' ', $sciname);
                 $spacer = $det['IdentificationQualifier'] == '?' ? '' : ' ';
                 $scinameBits[$det['IdentificationQualifierInsertionPoint'] - 1] = $det['IdentificationQualifier'] . $spacer . $scinameBits[$det['IdentificationQualifierInsertionPoint'] - 1];
                 $sciname = implode(' ', $scinameBits);
             }
             if ($det['NameAddendum']) {
                 $sciname .= ' ' . $det['NameAddendum'];
             }
             $prev .= $sciname;
             // Determiner
             if ($det['IdentifiersText']) {
                 $prev .= ', ';
                 $prev .= $det['IdentifierRole'] == 'conf.' ? 'conf. ' : 'det. ';
                 $identifiers = explode(';', $det['IdentifiersText']);
                 $identifier = explode(',', $identifiers[0]);
                 $prev .= count($identifier) > 1 ? trim($identifier[1]) . ' ' . trim($identifier[0]) : trim($identifier[0]);
                 if (count($identifiers) == 2) {
                     $identifier = explode(',', $identifiers[1]);
                     $prev .= ' & ';
                     $prev .= count($identifier) > 1 ? trim($identifier[1]) . ' ' . trim($identifier[0]) : trim($identifier[0]);
                 } elseif (count($identifiers) > 2) {
                     $prev .= ' et al.';
                 }
             }
             // Determination date
             if ($det['IdentificationDate']) {
                 $dateBits = explode('-', $det['IdentificationDate']);
                 $date = '';
                 $day = isset($dateBits[2]) ? $dateBits[2] : FALSE;
                 $month = FALSE;
                 if (isset($dateBits[1])) {
                     switch ($dateBits[1]) {
                         case '01':
                             $month = 'i';
                             break;
                         case '02':
                             $month = 'ii';
                             break;
                         case '03':
                             $month = 'iii';
                             break;
                         case '04':
                             $month = 'iv';
                             break;
                         case '05':
                             $month = 'v';
                             break;
                         case '06':
                             $month = 'vi';
                             break;
                         case '07':
                             $month = 'vii';
                             break;
                         case '08':
                             $month = 'viii';
                             break;
                         case '09':
                             $month = 'ix';
                             break;
                         case '10':
                             $month = 'x';
                             break;
                         case '11':
                             $month = 'xi';
                             break;
                         case '12':
                             $month = 'xii';
                             break;
                         default:
                             break;
                     }
                 }
                 $year = $dateBits[0];
                 if ($day) {
                     $date = "{$day}.{$month}.{$year}";
                 } elseif ($month) {
                     $date = "{$month}.{$year}";
                 } else {
                     $date = $year;
                 }
                 $prev .= ', ' . $date;
             }
             if ($det['IdentificationNotes']) {
                 $prev .= ' (' . $det['IdentificationNotes'] . ')';
             }
             $previousDets[] = $prev;
         }
         $previousDets = implode('; ', $previousDets);
         if (substr($previousDets, strlen($previousDets) - 1, 1) != '.') {
             $previousDets .= '.';
         }
         $ret = array('column' => 'previousIdentifications', 'value' => $previousDets);
         return $ret;
     }
 }
Beispiel #21
0
 public function updateDocument($id)
 {
     $updateQuery = $this->client->createUpdate();
     $this->doc = $updateQuery->createDocument();
     $select = "SELECT n.GUID AS scientificNameID,\n                n.NameID,\n                n.FullName AS scientificName,\n                n.Author AS scientificNameAuthorship,\n                n.name_type,\n                r.GUID AS namePublishedInID,\n                r.Title AS namePublishedIn,\n                r.PublicationYear AS namePublishedInYear,\n                t.Sensu,\n                pub.Publication AS nameAccordingTo,\n                LOWER(td.Name) AS taxonRank,\n                LOWER(t.TaxonomicStatus) AS taxonomicStatus,\n                t.OccurrenceStatus AS occurrenceStatus,\n                t.EstablishmentMeans AS establishmentMeans,\n                t.Remarks AS taxonRemarks,\n                pt.GUID AS parentNameUsageID,\n                pn.FullName AS parentNameUsage,\n                at.GUID AS acceptedNameUsageID,\n                an.FullName AS acceptedNameUsage,\n                an.Author AS acceptedNameUsageAuthorship,\n                LOWER(atd.Name) AS acceptedNameUsageTaxonRank,\n                tt.NodeNumber,\n                att.NodeNumber AS AcceptedNodeNumber,\n                t.RankID,\n                at.RankID AS AcceptedRankID,\n                c.CommonName AS vernacularName\n              FROM vicflora_taxon t\n              JOIN vicflora_name n ON t.NameID=n.NameID\n              LEFT JOIN vicflora_taxontreedefitem td ON t.TaxonTreeDefItemID=td.TaxonTreeDefItemID\n              LEFT JOIN vicflora_reference r ON n.ProtologueID=r.ReferenceID\n              LEFT JOIN vicflora_taxon pt ON t.ParentID=pt.TaxonID\n              LEFT JOIN vicflora_name pn ON pt.NameID=pn.NameID\n              LEFT JOIN vicflora_taxon at ON t.AcceptedID=at.TaxonID\n              LEFT JOIN vicflora_name an ON at.NameID=an.NameID\n              LEFT JOIN vicflora_taxontreedefitem atd ON at.TaxonTreeDefItemID=atd.TaxonTreeDefItemID\n              LEFT JOIN vicflora_publication pub ON t.SourceID=pub.PublicationID\n              LEFT JOIN vicflora_taxontree tt ON t.TaxonID=tt.TaxonID AND t.TaxonomicStatus='accepted'\n              LEFT JOIN vicflora_taxontree att ON t.AcceptedID=att.TaxonID AND !(t.TaxonomicStatus='accepted')\n              LEFT JOIN vicflora_commonname c ON t.TaxonID=c.TaxonID AND t.TaxonomicStatus='accepted' AND c.IsPreferred=1\n              WHERE t.GUID='{$id}'";
     $query = $this->db->query($select);
     $row = $query->row();
     $this->doc->project = array('VicFlora');
     $this->doc->id = $id;
     $this->doc->scientific_name_id = $row->scientificNameID;
     $this->doc->scientific_name = Encoding::toUTF8($row->scientificName);
     $this->doc->scientific_name_authorship = $row->scientificNameAuthorship;
     $this->doc->name_type = $row->name_type;
     $this->doc->name_published_in_id = $row->namePublishedInID;
     $this->doc->name_published_in = $row->namePublishedIn;
     $this->doc->name_published_in_year = $row->namePublishedInYear;
     $this->doc->sensu = $row->Sensu;
     $this->doc->name_according_to = $row->nameAccordingTo;
     $this->doc->taxon_rank = $row->taxonRank;
     $this->doc->taxonomic_status = in_array($row->taxonomicStatus, array('homotypic synonym', 'heterotypic synonym')) ? 'synonym' : $row->taxonomicStatus;
     $occurrenceStatus = array();
     if ($row->occurrenceStatus == 'endemic') {
         $occurrenceStatus[] = 'present';
     }
     $occurrenceStatus[] = $row->occurrenceStatus;
     $this->doc->occurrence_status = $occurrenceStatus;
     $this->doc->establishment_means = $this->establishmentMeans($row->establishmentMeans);
     $this->doc->taxon_remarks = $row->taxonRemarks;
     $this->doc->parent_name_usage_id = $row->parentNameUsageID;
     $this->doc->parent_name_usage = $row->parentNameUsage;
     $this->doc->accepted_name_usage_id = $row->acceptedNameUsageID;
     $this->doc->accepted_name_usage = $row->acceptedNameUsage;
     $this->doc->accepted_name_usage_authorship = $row->acceptedNameUsageAuthorship;
     $this->doc->accepted_name_usage_taxon_rank = $row->acceptedNameUsageTaxonRank;
     if ($row->taxonomicStatus == 'accepted') {
         $description = $this->description($id);
         if ($description) {
             $this->doc->profile = $description;
         }
         $this->doc->media = $this->media($id);
         if ($row->AcceptedRankID == 220) {
             $this->doc->species_id = $row->acceptedNameUsageID;
         } elseif ($row->AcceptedRankID > 220) {
             $this->doc->species_id = $this->getSpeciesID($row->acceptedNameUsageID);
         }
     }
     $this->doc->vernacular_name = $row->vernacularName;
     if ($row->NodeNumber) {
         $this->doc->end_or_higher_taxon = $this->endTaxon($id);
         $this->higherClassification($row->NodeNumber, $row->RankID);
     } elseif ($row->AcceptedNodeNumber) {
         $this->doc->end_or_higher_taxon = $this->endTaxon($row->acceptedNameUsageID);
         $this->higherClassification($row->AcceptedNodeNumber, $row->AcceptedRankID);
     }
     $this->doc->ibra_7_subregion = $this->distribution($id, 'subregion', $row->RankID);
     $this->doc->ibra_7_subregion = $this->distribution($id, 'subregion', $row->RankID);
     if ($row->RankID >= 180) {
         $this->doc->nrm_region = $this->NrmRegions($id);
     }
     // Threat status
     $threatStatus = array();
     $epbc = $this->taxonAttribute($id, 'EPBC (Jan. 2014)');
     if ($epbc) {
         $threatStatus[] = 'EPBC_' . $epbc;
     }
     $vrot = $this->taxonAttribute($id, 'VROT');
     if ($vrot) {
         $threatStatus[] = 'VROT_' . $vrot;
     }
     $ffg = $this->taxonAttribute($id, 'FFG');
     if ($ffg) {
         $threatStatus[] = 'FFG listed';
     }
     if ($threatStatus) {
         $this->doc->threat_status = $threatStatus;
     }
     $apni = $this->apniMatch($row->NameID);
     if ($apni) {
         $this->doc->apni_match_type = $apni['apni_match_type'];
         $this->doc->apni_match_verification_status = $apni['apni_match_verification_status'];
     }
     $this->doc->last_modified = date('Y-m-d\\TH:i:s\\Z');
     $updateQuery->addDocuments(array($this->doc), $overwrite = true);
     $updateQuery->addCommit();
     $this->client->update($updateQuery);
 }
Beispiel #22
0
function woo_pi_encode_transient($var = null)
{
    // Check that the Encoding class by Sebastián Grignoli exists
    if (file_exists(WOO_PI_PATH . 'classes/Encoding.php')) {
        include_once WOO_PI_PATH . 'classes/Encoding.php';
        if (class_exists('Encoding')) {
            $encoding = new Encoding();
            return $encoding->toUTF8($var);
        }
    } else {
        return $var;
    }
}
Beispiel #23
0
function nvweb_archive_render($type, $dataset, $archive_url, $categories)
{
    global $website;
    global $session;
    $out = array();
    setlocale(LC_ALL, $website->languages[$session['lang']]['system_locale']);
    if ($type == 'year' || $type == 'year-collapsed') {
        $year_months = array();
        $year_stats = array();
        foreach ($dataset as $row) {
            $year_months[$row->year][] = '<div>
                    <a href="' . $archive_url . '?archive=' . $row->year . '-' . $row->month . '-' . implode(',', $categories) . '">' . Encoding::toUTF8(ucfirst(strftime('%B', mktime(0, 0, 0, $row->month, 1, 2000)))) . ' (' . $row->total . ')
                    </a>
                 </div>';
            $year_stats[$row->year]['total'] += $row->total;
        }
        $first = '';
        // default: show months of the first year in the list
        if ($type == 'year-collapsed') {
            // alternative: hide months for the first year, too
            $first = 'display: none;';
        }
        foreach ($year_months as $year => $months) {
            $out[] = '<div class="nv-year"><a href="#" style=" display: block;" onclick=" return false; ">&raquo; ' . $year . ' (' . $year_stats[$year]['total'] . ')</a></div>';
            $out[] = '<div style="' . $first . ' margin-left: 20px;" class="nv-year-months">';
            $out[] = implode("\n", $months);
            $out[] = '</div>';
            $first = 'display: none;';
        }
        nvweb_after_body('js', '
            jQuery(".nv-year").on("click", function() { $(this).next().toggle() });
        ');
    } else {
        if ($type == 'month') {
            foreach ($dataset as $row) {
                $out[] = '<div>
                    <a href="' . $archive_url . '?archive=' . $row->year . '-' . $row->month . '-' . implode(',', $categories) . '">' . Encoding::toUTF8(ucfirst(strftime('%B', mktime(0, 0, 0, $row->month, 1, 2000)))) . ' ' . $row->year . ' (' . $row->total . ')
                    </a>
                 </div>';
            }
        }
    }
    $out = implode("\n", $out);
    return $out;
}