コード例 #1
1
ファイル: MatchesManager.php プロジェクト: ilivanoff/www
 /**
  * Регистрирует решение задачи
  * 
  * @return bool - признак, был ли ответ привязан к авторизованному пользователю
  */
 public function registerSolution($taskIdent, $matchesStr)
 {
     $task = $this->taskByIdent($taskIdent);
     $matchesStr = normalize_string($matchesStr, true);
     $mCnt = $task['m'];
     $sCnt = $task['s'];
     $cols = $task['c'];
     $rows = $task['r'];
     $excluded = $this->strToArray($matchesStr, $mCnt, $cols, $rows);
     ksort($excluded);
     //Вычисляем оставшиеся спички (пробегаем по всем точкам и берём правую и верхнюю спичку)
     $matches = array();
     for ($x = 0; $x <= $cols; $x++) {
         for ($y = 0; $y <= $rows; $y++) {
             $matchId = $this->matchId($x, $y, $x + 1, $y);
             if (!array_key_exists($matchId, $excluded) && $x + 1 <= $cols) {
                 $matches[$matchId] = true;
             }
             $matchId = $this->matchId($x, $y, $x, $y + 1);
             if (!array_key_exists($matchId, $excluded) && $y + 1 <= $rows) {
                 $matches[$matchId] = true;
             }
         }
     }
     $sqCnt = 0;
     //Скопируем массив
     $badMatches = $matches;
     //Вычисляем координаты всех квадратов
     for ($x = 0; $x < $cols; $x++) {
         for ($y = 0; $y < $rows; $y++) {
             //Проверяем точку
             $endX = $x;
             $endY = $y;
             while (++$endX <= $cols && ++$endY <= $rows) {
                 $bounds = $this->isFullSquare($x, $y, $endX, $endY, $matches);
                 if ($bounds) {
                     ++$sqCnt;
                     foreach ($bounds as $key => $val) {
                         unset($badMatches[$key]);
                     }
                 }
             }
         }
     }
     $badMatches = empty($badMatches) ? false : concat(array_keys($badMatches));
     check_condition(!$badMatches, "Bad matches left: [{$badMatches}]");
     check_condition($sqCnt == $sCnt, "Invalid squares cnt: [{$sqCnt}], required: [{$sCnt}].");
     //Сохраняем в базу
     $userId = AuthManager::getUserIdOrNull();
     //Склеим строку из отсартированных спичек
     $matchesStr = $this->arrToStr($excluded);
     //Регистрируем ответ пользователя
     $ansBindedToUser = MatchesBean::inst()->registerAnswer($taskIdent, $matchesStr, $userId);
     //Если зарегистрировали, попробуем дать очки
     if ($ansBindedToUser && $userId) {
         PL_matches::inst()->givePoints(PsUser::inst());
     }
     //Возвратим признак выданных очков
     return $ansBindedToUser;
 }
コード例 #2
0
ファイル: TexTools.php プロジェクト: ilivanoff/www
 /**
  * Метод удаляет всё лишнее из формулы, добавляя пробелы вокруг специальных символов.
  * Это сделано потому, что интерпретатор TeX`а считает одинаковыми последовательности:
  * [<][ <][< ][ < ], мы же должны защититься от повторного построения формул.
  * 
  * На вход принимается "чистая" формула, без всяких макросов в начале и конце: 
  * \sqrt{x} \pm 2
  */
 public static function safeFormula($TeX)
 {
     $TeX = str_replace('<', ' < ', $TeX);
     $TeX = str_replace('>', ' > ', $TeX);
     $TeX = str_replace('&', ' & ', $TeX);
     return normalize_string($TeX);
 }
コード例 #3
0
ファイル: PSDB.php プロジェクト: ilivanoff/www
 /** @return ADORecordSet */
 private static function executeQuery($query, $params = false, &$queryFinal = null, array &$paramsFinal = null)
 {
     $queryFinal = $query instanceof Query ? $query->build($params) : $query;
     $queryFinal = normalize_string($queryFinal);
     $paramsFinal = to_array($params);
     $LOGGER = PsLogger::inst(__CLASS__);
     $PROFILER = PsProfiler::inst(__CLASS__);
     $PROFILER->start(strtolower($queryFinal));
     try {
         if ($LOGGER->isEnabled()) {
             $LOGGER->info("[{$queryFinal}]" . ($paramsFinal ? ', PARAMS: ' . array_to_string($paramsFinal) : ''));
         }
         $rs = PsConnectionPool::conn()->execute($queryFinal, $paramsFinal);
         if (is_object($rs)) {
             $PROFILER->stop();
             return $rs;
         }
         $error = PsConnectionPool::conn()->ErrorMsg();
         $LOGGER->info('ERROR: {}', $error);
         throw new DBException($error, DBException::ERROR_NOT_CLASSIFIED, $queryFinal, $paramsFinal);
     } catch (Exception $ex) {
         $PROFILER->stop(false);
         if ($ex instanceof DBException) {
             ExceptionHandler::dumpError($ex);
         }
         throw $ex;
     }
 }
コード例 #4
0
ファイル: PageNormalizer.php プロジェクト: ilivanoff/www
 protected function doFinalize($PAGE_CONTENT)
 {
     //Сначала выделим то, что не должно попасть под нормализацию
     $this->addReplaces($PAGE_CONTENT);
     /*
      * Далее:
      * 1. Заменяем контент на макросы
      * 2. Проводим нормализацию
      * 3. Заменяем обратно макросы на контент
      */
     $hasReplaces = !empty($this->REPLACES);
     $replaceMacroses = array_to_string($this->REPLACES);
     if ($hasReplaces) {
         foreach ($this->REPLACES as $content => $replace) {
             $PAGE_CONTENT = str_replace($content, $replace, $PAGE_CONTENT);
         }
     }
     if ($hasReplaces && $this->LOGGER->isEnabled()) {
         $this->LOGGER->infoBox('PAGE WITH REPLACES ' . $replaceMacroses, $PAGE_CONTENT);
     }
     $PAGE_CONTENT = normalize_string($PAGE_CONTENT);
     if ($hasReplaces && $this->LOGGER->isEnabled()) {
         $this->LOGGER->infoBox('NORMALIZED PAGE WITH REPLACES ' . $replaceMacroses, $PAGE_CONTENT);
     }
     if ($hasReplaces) {
         foreach ($this->REPLACES as $content => $replace) {
             $PAGE_CONTENT = str_replace($replace, $content, $PAGE_CONTENT);
         }
     }
     if ($hasReplaces && $this->LOGGER->isEnabled()) {
         $this->LOGGER->infoBox('PAGE AFTER BACKREPLACE ' . $replaceMacroses, $PAGE_CONTENT);
     }
     return $PAGE_CONTENT;
 }
コード例 #5
0
ファイル: findwords.php プロジェクト: ilivanoff/ps-sdk-dev
 public function getPluginContent($content, ArrayAdapter $params, PluginFetchingContext $ctxt)
 {
     $content = normalize_string($content);
     $strings = explode(' ', $content);
     $data['findwords'] = $strings;
     return new PluginContent($this->getFoldedEntity()->fetchTpl($data));
 }
コード例 #6
0
ファイル: block.chessboard.php プロジェクト: ilivanoff/www
function smarty_block_chessboard($params, $content, Smarty_Internal_Template &$template)
{
    if (!$content) {
        return;
    }
    $content = normalize_string($content, true);
    $content = strtolower($content);
    $arr = explode(',', $content);
    $sets = array();
    foreach ($arr as $value) {
        if (strlen($value) >= 4) {
            $fig = substr($value, 0, 2);
            $pos = substr($value, 2, 2);
            $sets[$pos] = $fig;
            $colNum = false;
            $rowNum = $pos[1];
            switch ($pos[0]) {
                case 'a':
                    $colNum = 1;
                    break;
                case 'b':
                    $colNum = 2;
                    break;
                case 'c':
                    $colNum = 3;
                    break;
                case 'd':
                    $colNum = 4;
                    break;
                case 'e':
                    $colNum = 5;
                    break;
                case 'f':
                    $colNum = 6;
                    break;
                case 'g':
                    $colNum = 7;
                    break;
                case 'h':
                    $colNum = 8;
                    break;
                default:
                    return PsHtml::spanErr("Bad chess board position: [{$value}]");
            }
            if ($colNum) {
                $sets[$colNum . $rowNum] = $fig;
            }
        }
    }
    /* @var $chessBoardTpl Smarty_Internal_Template */
    $chessBoardTpl = $template->smarty->createTemplate('common/chessboard.tpl');
    $chessBoardTpl->assign('figures', $sets);
    $chessBoardTpl->assign('small', array_key_exists('small', $params));
    $chessBoardTpl->display();
}
コード例 #7
0
ファイル: snippetTest.php プロジェクト: crecorn/assetmanager
 /**
  * Seems that you have to force the Snippet to be cached before this will work.
  */
 public function testSecure()
 {
     global $modx;
     $modx = self::$modx;
     $props = array();
     $props['input'] = '29.99';
     $props['options'] = '';
     $actual = $modx->runSnippet('scale2w', $props);
     $expected = '';
     $this->assertEquals(normalize_string($expected), normalize_string($actual));
 }
コード例 #8
0
ファイル: UserInputTools.php プロジェクト: ilivanoff/www
 public static function safeLongText($string)
 {
     check_condition($string, 'Пустое сообщение');
     $texExtractor = TexExtractor::inst($string, true);
     $string = $texExtractor->getMaskedText();
     $string = htmlspecialchars($string);
     $string = nl2brr($string);
     $string = $texExtractor->restoreMasks($string);
     /*
      * Удалим двойные пробелы, т.к. к этом моменту уже все переносы 
      * строк заменены на <br />
      */
     return normalize_string($string);
 }
コード例 #9
0
ファイル: xlsx_reader.php プロジェクト: amoryver/ws-converter
function read_excel($out, $in_file, $options = array())
{
    if (!isset($options["calculated"])) {
        $options["calculated"] = false;
    }
    $calculated = $options["calculated"];
    // キャッシュを/tmpに変更する。
    $cacheMethod = PHPExcel_CachedObjectStorageFactory::cache_to_discISAM;
    $cacheSettings = array("dir" => "/tmp");
    PHPExcel_Settings::setCacheStorageMethod($cacheMethod, $cacheSettings);
    // EXCELオブジェクトを読む
    $xls_reader = PHPExcel_IOFactory::createReader("Excel2007");
    $xls_reader->setReadDataOnly(true);
    $xls_object = $xls_reader->load($in_file);
    $num_sheets = $xls_object->getSheetCount();
    // シートを読む
    for ($sheet = 0; $sheet < $num_sheets; $sheet++) {
        $xls_object->setActiveSheetIndex($sheet);
        $xls_sheet = $xls_object->getActiveSheet();
        $worksheet_name = $xls_sheet->getTitle();
        $headers = explode(":", "^:" . $options["inheader"] . ":\$");
        // ワークシートの先頭行に "# ファイル名" を出力する。
        fputs($out, "# {$worksheet_name}\n");
        // 行番号は1から始まるのでHighestRowは総行数と同じ。
        $num_rows = $xls_sheet->getHighestRow();
        // columnIndexFromStringは1から始まる(columnIndexFromString('0')==1)のでHighestColumnは総列数と同じ。
        $num_cols = PHPExcel_Cell::columnIndexFromString($xls_sheet->getHighestColumn());
        // 行を読む
        for ($row = 0; $row < $num_rows; $row++) {
            // 列を読む
            $csv_record = array();
            for ($col = 0; $col < $num_cols; $col++) {
                // getCellByColumnAndRowの列番号は0から始まり、行番号は1から始まる。
                if ($calculated) {
                    $value = (string) $xls_sheet->getCellByColumnAndRow($col, $row + 1)->getCalculatedValue();
                } else {
                    $value = (string) $xls_sheet->getCellByColumnAndRow($col, $row + 1)->getValue();
                    // if (substr($value, 0, 1) == "=") $value = "E";	// buggy for expression?
                }
                $csv_record[$col] = trim(normalize_string($value));
            }
            // 行を出力する。
            if (($header = array_shift($headers)) !== null) {
                // ヘッダを出力する。
                if ($header == "^") {
                    $num_cols = count($csv_record);
                    $fields = array_fill(0, $num_cols, "");
                    $types = array_fill(0, $num_cols, "text");
                    $params = array_fill(0, $num_cols, "");
                    $titles = array_fill(0, $num_cols, "");
                    $header = array_shift($headers);
                }
                if ($header == "F") {
                    $fields = array_replace($fields, $csv_record);
                } else {
                    if ($header == "C") {
                        $types = array_replace($types, $csv_record);
                    } else {
                        if ($header == "P") {
                            $params = array_replace($params, $csv_record);
                        } else {
                            if ($header == "T") {
                                $titles = array_replace($titles, $csv_record);
                            } else {
                                if ($header == "N") {
                                } else {
                                    if ($header == "\$") {
                                        for ($i = 0; $i < count($fields); $i++) {
                                            if ($fields[$i] == "") {
                                                $fields[$i] = $titles[$i];
                                            }
                                            if ($fields[$i] == "") {
                                                $fields[$i] = "f{$i}";
                                                $titles[$i] = "f{$i}";
                                            }
                                        }
                                        array_unshift($fields, "fields");
                                        fputcsv($out, $fields, ",", '"');
                                        array_unshift($types, "types");
                                        fputcsv($out, $types, ",", '"');
                                        array_unshift($params, "params");
                                        fputcsv($out, $params, ",", '"');
                                        array_unshift($titles, "titles");
                                        fputcsv($out, $titles, ",", '"');
                                        $headers = array();
                                        // (最初の)データを出力する。
                                        array_unshift($csv_record, "record");
                                        fputcsv($out, $csv_record, ",", '"');
                                    }
                                }
                            }
                        }
                    }
                }
            } else {
                // データを出力する。
                array_unshift($csv_record, "record");
                fputcsv($out, $csv_record, ",", '"');
            }
        }
        // ワークシートの最終行に空行を出力する。
        fputs($out, "\n");
    }
    $xls_object->disconnectWorksheets();
    unset($xls_object);
    return;
}
コード例 #10
0
function validate_line($line)
{
    $line = trim($line);
    if ($line === '' || $line === '<?php' || $line === '?>') {
        return $line;
    }
    // don't treat empty lines as malicious
    $ok = preg_match('/^\\s*\\$wb\\[(["\'])(.*?)\\1\\]\\s*=\\s*(["\'])(.*?)\\3\\s*;\\s*$/', $line, $matches);
    if (!$ok) {
        return false;
    }
    // this line has invalid form and could lead to malfunction
    $keyquote = $matches[1];
    // ' or "
    $key = $matches[2];
    if (strpos($key, '"') !== false || strpos($key, "'") !== false) {
        return false;
    }
    $textquote = $matches[3];
    // ' or "
    $text = $matches[4];
    $new_line = '$wb[\'';
    // validate the language key
    $key = normalize_string($key, $keyquote);
    $new_line .= $key . '\'] = \'';
    // validate this text to avoid code injection
    $text = normalize_string($text, $textquote, true);
    $new_line .= $text . '\';';
    return $new_line;
}
コード例 #11
0
ファイル: PsUser.php プロジェクト: ilivanoff/www
 /**
  * Строит содержимое для id-card
  */
 public function getIdCardContent()
 {
     return normalize_string(PSSmarty::template('idcard/content.tpl', array('user' => $this))->fetch());
 }
コード例 #12
0
ファイル: PsMathRebus.php プロジェクト: ilivanoff/ps-sdk-dev
 public function normalize($rebus)
 {
     return mb_strtolower(normalize_string($rebus, true), 'UTF-8');
 }
コード例 #13
0
ファイル: csv_reader.php プロジェクト: amoryver/ws-converter
function read_csv($out, $in_file, $options = array())
{
    if (!isset($options["enclosure"])) {
        $options["enclosure"] = '"';
    }
    $enclosure = $options["enclosure"];
    $delimiter = $options["delimiter"];
    // CSVファイルを正規化する。
    $tmp = tmpfile();
    if (($in = fopen($in_file, "r")) === false) {
        fputs(STDERR, "Error[{$in_file}]: Failed to open the file.\n");
        return;
    }
    while (($line = fgets($in)) !== false) {
        // UTF-8にする。
        $line = normalize_encoding($line);
        // 全角カタカナ、半角英数字、PHP_EOL、NFCにする。
        $line = normalize_string($line);
        fputs($tmp, $line);
    }
    fclose($in);
    fflush($tmp);
    rewind($tmp);
    // ワークシートの先頭行に "# ファイル名" を出力する。
    $filename = pathinfo($in_file, PATHINFO_FILENAME);
    $ext = pathinfo($in_file, PATHINFO_EXTENSION);
    $filename_fragments = explode(".", $filename);
    $worksheet_name = $filename_fragments[count($filename_fragments) - 1];
    fputs($out, "# {$worksheet_name}\n");
    $headers = explode(":", "^:" . $options["inheader"] . ":\$");
    while (($csv_record = fgetcsv($tmp, 65536, $delimiter, $enclosure)) !== FALSE) {
        for ($i = 0; $i < count($csv_record); $i++) {
            $csv_record[$i] = trim($csv_record[$i]);
        }
        if (($header = array_shift($headers)) !== null) {
            if ($header == "^") {
                $num_cols = count($csv_record);
                $fields = array_fill(0, $num_cols, "");
                $types = array_fill(0, $num_cols, "text");
                $params = array_fill(0, $num_cols, "");
                $titles = array_fill(0, $num_cols, "");
                $header = array_shift($headers);
            }
            if ($header == "F") {
                $fields = array_replace($fields, $csv_record);
            } else {
                if ($header == "C") {
                    $types = array_replace($types, $csv_record);
                } else {
                    if ($header == "P") {
                        $params = array_replace($params, $csv_record);
                    } else {
                        if ($header == "T") {
                            $titles = array_replace($titles, $csv_record);
                        } else {
                            if ($header == "N") {
                            } else {
                                if ($header == "\$") {
                                    for ($i = 0; $i < count($fields); $i++) {
                                        if ($fields[$i] == "") {
                                            $fields[$i] = $titles[$i];
                                        }
                                        if ($fields[$i] == "") {
                                            $fields[$i] = "f{$i}";
                                            $titles[$i] = "f{$i}";
                                        }
                                    }
                                    array_unshift($fields, "fields");
                                    fputcsv($out, $fields, ",", '"');
                                    array_unshift($types, "types");
                                    fputcsv($out, $types, ",", '"');
                                    array_unshift($params, "params");
                                    fputcsv($out, $params, ",", '"');
                                    array_unshift($titles, "titles");
                                    fputcsv($out, $titles, ",", '"');
                                    $headers = array();
                                    // (最初の)データを出力する。
                                    array_unshift($csv_record, "record");
                                    fputcsv($out, $csv_record, ",", '"');
                                }
                            }
                        }
                    }
                }
            }
        } else {
            // データを出力する。
            array_unshift($csv_record, "record");
            fputcsv($out, $csv_record, ",", '"');
        }
    }
    // ワークシートの最終行に空行を出力する。
    fputs($out, "\n");
    fclose($tmp);
    return;
}
コード例 #14
0
ファイル: PsGallery.php プロジェクト: ilivanoff/www
 /**
  * Метод собирает всю необходимую информацию о галерее и кеширует её для быстрого доступа.
  */
 private function getSnapshot()
 {
     $DATA = PSCache::GALLERY()->getFromCache($this->gallery, PsUtil::getClassConsts($this, 'PARAM_'));
     if (is_array($DATA)) {
         return $DATA;
         //---
     }
     $DATA = array();
     /*
      * Информация о галерее (из базы)
      */
     $galleryInfo = GalleryBean::inst()->getGalleryInfo($this->gallery);
     //name
     $gallName = $galleryInfo ? trim($galleryInfo['v_name']) : '';
     $gallName = $gallName ? $gallName : 'Галерея';
     /*
      * Картинки, входящие в галерею (те, для которых есть запись в БД и b_show=1).
      * Мы также сразу отсеим те картинки, для которых нет файла на файловой системе,
      * чтобы потом клиент не делал лишний запрос на наш сервер.
      */
     $galleryImages = GalleryBean::inst()->getGalleryItems($this->gallery, false, $this->getDirectoryImgNames());
     //Проведём фетчинг необходимых представлений галереи
     $SmartyParams['id'] = $this->gallery;
     $SmartyParams['name'] = $gallName;
     $SmartyParams['images'] = $galleryImages;
     //.box_images - блок картинок, который будет преобразован в галерею с помощью js.
     $imagesHtml = PSSmarty::template('mmedia/gallery/box_images.tpl', $SmartyParams)->fetch();
     $imagesHtml = normalize_string($imagesHtml);
     //.as_list - для отображения списка картинок в popup окне
     $asListHtml = PSSmarty::template('mmedia/gallery/as_list.tpl', $SmartyParams)->fetch();
     $asListHtml = normalize_string($asListHtml);
     //Все сложим в файл и сохраним в кеш
     $DATA[self::PARAM_CNT] = count($galleryImages);
     $DATA[self::PARAM_NAME] = $gallName;
     $DATA[self::PARAM_ASLIST] = $asListHtml;
     $DATA[self::PARAM_BOXIMGS] = $imagesHtml;
     return PSCache::GALLERY()->saveToCache($DATA, $this->gallery);
 }
コード例 #15
0
ファイル: PsProfiler.php プロジェクト: ilivanoff/ps-sdk-dev
 /**
  * Преобразует коллекцию секундомеров в строрку, пригодную для сохранения в файл, и записывает её
  */
 private function saveToFile(DirItem $item, array $secundomers, $rewrite = false)
 {
     $string = '';
     /* @var $secundomer Secundomer */
     foreach ($secundomers as $ident => $secundomer) {
         //Обязательно нужно удалить переносы строк из идентификатора, чтобы наш файл "не поехал"
         $ident = normalize_string($ident);
         if (!$ident || $secundomer->isStarted()) {
             continue;
         }
         $string .= $ident . '|' . $secundomer->getCount() . '|' . $secundomer->getTotalTime() . "\n";
     }
     $item->writeToFile($string, $rewrite);
     return $string;
 }
コード例 #16
0
ファイル: yaml_reader.php プロジェクト: amoryver/ws-converter
function read_yaml($out, $in_file, $options = array())
{
    // YAMLオブジェクトを読む。
    $contents = file_get_contents($in_file);
    $contents = normalize_encoding($contents);
    $contents = normalize_string($contents);
    // parse yaml, '0' for the first document
    if (($dataset = yaml_parse($contents, 0)) === FALSE) {
        fputs(STDERR, "Error[{$in_file}]: The file is not valid format.\n");
        return;
    }
    if (!is_array($dataset)) {
        fputs(STDERR, "Error[{$in_file}]: The 1st level is not an object.\n");
    }
    foreach ($dataset as $worksheet_name => $worksheet) {
        if (!is_array($worksheet)) {
            fputs(STDERR, "Error[{$in_file}]: The 2nd level is not an array.\n");
            return;
        }
        // Pass1: ヘッダとフィールド名を収集する。
        $fields = array();
        $titles = array();
        $types = array();
        $params = array();
        $records = array();
        $num_cols = 0;
        if ($worksheet["titles"] !== null) {
            $titles = array_values($worksheet["titles"]);
            $fields += array_keys($worksheet["titles"]);
        }
        if ($worksheet["types"] !== null) {
            $types = array_values($worksheet["types"]);
            $fields += array_keys($worksheet["types"]);
        }
        if ($worksheet["params"] !== null) {
            $params = array_values($worksheet["params"]);
            $fields += array_keys($worksheet["params"]);
        }
        if ($worksheet["records"] !== null) {
            $records = array_values($worksheet["records"]);
            for ($row = 0; $row < count($records); $row++) {
                $fields += array_keys($records[$row]);
            }
        }
        if (($num_cols = count($fields)) == 0) {
            fputs(STDERR, "Error[{$in_file}]: No field specidied.\n");
            return;
        }
        // Pass2: 内部形式CSVを出力する。
        // 先頭行に "# ファイル名" を出力する。
        fputs($out, "# {$worksheet_name}\n");
        // ヘッダ行を出力する。
        $fields = array_pad($fields, $num_cols, "");
        array_unshift($fields, "fields");
        fputcsv($out, $fields, ",", '"');
        $types = array_pad($types, $num_cols, "text");
        array_unshift($types, "types");
        fputcsv($out, $types, ",", '"');
        $params = array_pad($params, $num_cols, "");
        array_unshift($params, "params");
        fputcsv($out, $params, ",", '"');
        $titles = array_pad($titles, $num_cols, "");
        array_unshift($titles, "titles");
        fputcsv($out, $titles, ",", '"');
        // データ行を出力する。
        for ($row = 0; $row < count($records); $row++) {
            $record = $records[$row];
            $csv_record = array();
            // $fields は上で unshift しているので 1 から開始する。
            for ($col = 1; $col < count($fields); $col++) {
                $csv_record[$col] = $record[$fields[$col]];
            }
            array_unshift($csv_record, "record");
            fputcsv($out, $csv_record, ",", '"');
        }
        // 最終行に空行を出力する。
        fputs($out, "\n");
    }
    return;
}
コード例 #17
0
function search_images_by_term($term = 'доктор')
{
    global $path;
    // find ID of uniques normal term
    $term = normalize_string($term, $path);
    $id_list = "";
    //pokazh($term,"Ищем слово");
    $first_id = true;
    $sql = "select id, exclude from terms_normal where term_normal='" . $term . "' and exclude != 1";
    $result = mysql_query($sql);
    while ($row = mysql_fetch_array($result)) {
        $id = $row['id'];
    }
    // find image ids linked to normal term id
    if ($id == '') {
        echo 'ничего не найдено';
        return;
    } else {
        echo "<div><h1>Рисунки со словом '" . $term . "'</h1></div>";
    }
    $sql = "select image_id from term_to_image where term_id='" . $id . "'";
    $result = mysql_query($sql);
    while ($row = mysql_fetch_array($result)) {
        if ($first_id) {
            $id_list = $row['image_id'] . " ";
        } else {
            $id_list = $id_list . ", " . $row['image_id'];
        }
        $first_id = false;
    }
    // output image previews
    $sql = "select image, name, description, additional_description from wp_product_list where id in (" . $id_list . ")";
    $result = mysql_query($sql);
    if (!$result) {
        die("ничего не найдено");
    }
    $description_set = "";
    while ($row = mysql_fetch_array($result)) {
        echo "<table width='140' style='float:left;font-size:.8em;'><tr><td>";
        echo "<img src='http://cartoonbank.ru/wp-content/plugins/wp-shopping-cart/images/" . $row['image'] . "'>";
        echo "</td></tr><tr><td><div class='descr'>";
        $descr = highlight_term($term, mb_strtolower($row['name'], 'utf-8') . "<br>" . mb_strtolower($row['description'], 'utf-8') . "<br>" . mb_strtolower($row['additional_description'], 'utf-8'));
        echo $descr . "";
        echo "</div></td></tr></table>";
        $description_set = $description_set . $row['name'] . " " . $row['description'] . " " . $row['additional_description'] . " ";
    }
    echo "<br style='clear:both;'>";
    return $description_set;
}
コード例 #18
0
ファイル: StringUtils.php プロジェクト: ilivanoff/www
 public static function getCharsCount($str)
 {
     $str = ps_strtoupper(normalize_string($str, true));
     if ($str && !array_key_exists($str, self::$COUNT_CHARS_CACHE)) {
         self::$COUNT_CHARS_CACHE[$str] = self::getCountCharsImpl($str);
     }
     return array_get_value($str, self::$COUNT_CHARS_CACHE, array());
 }
コード例 #19
0
 /**
  * Метод обрабатывает блочные формулы, заключённые в {f}...{/f}, 
  * но не являющиеся формулами TeX (не \[...\]).
  */
 public static function processBlockFormula($content)
 {
     return PsHtml::div(array('class' => 'block_formula'), normalize_string($content));
 }
コード例 #20
0
ファイル: PageFinaliserRegExp.php プロジェクト: ilivanoff/www
 protected function doFinalize($html)
 {
     /*
      * ИНИЦИАЛИЗАЦИЯ
      */
     $this->OBFUSCATABLE[] = DirManager::resources()->relDirPath('folded');
     $this->OBFUSCATABLE[] = DirManager::resources()->relDirPath('scripts/ps');
     //Расширим для предотвращения PREG_BACKTRACK_LIMIT_ERROR
     ini_set('pcre.backtrack_limit', 10 * 1000 * 1000);
     /*
      * НАЧАЛО РЫБОТЫ
      */
     /* Удалим комментарии */
     $pattern = "/<!--(.*?)-->/si";
     $html = preg_replace($pattern, '', $html);
     $resources = '';
     /*
      * JAVASCRIPT
      * <script ...>...</script>
      */
     $linked = array();
     $matches = array();
     $pattern = "/<script ([^>]*)>(.*?)<\\/script>/si";
     $cnt = preg_match_all($pattern, $html, $matches, PREG_PATTERN_ORDER);
     $attributes = $matches[1];
     $contents = $matches[2];
     for ($index = 0; $index < $cnt; $index++) {
         $attrs = $this->parseAttributesString($attributes[$index]);
         $content = trim($contents[$index]);
         if ($content) {
             //Есть содержимое, этот тег включаем сразу
             $tmp = PsHtml::linkJs(null, $content, $attrs);
             $resources .= $tmp . "\n";
             $this->LOGGER->info($tmp);
             continue;
         }
         $src = array_get_value('src', $attrs);
         if (!$src || in_array($src, $linked)) {
             //Нет пути или путь уже включён - пропускаем
             continue;
         }
         $linked[] = $src;
         $newSrc = $this->tryReplaceResource($src);
         if (!$newSrc) {
             if ($this->LOGGER->isEnabled()) {
                 $tmp = PsHtml::linkJs(null, null, $attrs);
                 $this->LOGGER->info($tmp . '  [EXCLUDED]');
             }
             continue;
         }
         $replaced = $src != $newSrc;
         if ($replaced) {
             $linked[] = $newSrc;
             $attrs['src'] = $newSrc;
         }
         $tmp = PsHtml::linkJs(null, null, $attrs);
         $resources .= $tmp . "\n";
         if ($this->LOGGER->isEnabled()) {
             $attrs['src'] = $src;
             $this->LOGGER->info(($replaced ? PsHtml::linkJs(null, null, $attrs) . '  [REPLACED]  ' : '') . $tmp);
         }
     }
     $html = preg_replace($pattern, '', $html);
     /*
      * FAVICON, CSS
      * <link .../>
      */
     /* Вырежем css и другие "линки" */
     $matches = array();
     $pattern = "/<link ([^>]*)\\/>/si";
     $cnt = preg_match_all($pattern, $html, $matches, PREG_PATTERN_ORDER);
     $attributes = $matches[1];
     for ($index = 0; $index < $cnt; $index++) {
         $attrs = $this->parseAttributesString($attributes[$index]);
         $src = array_get_value('href', $attrs);
         if (!$src || in_array($src, $linked)) {
             //Нет пути или путь уже включён - пропускаем
             continue;
         }
         $linked[] = $src;
         $newSrc = $this->tryReplaceResource($src);
         if (!$newSrc) {
             if ($this->LOGGER->isEnabled()) {
                 $tmp = PsHtml::linkLink($attrs);
                 $this->LOGGER->info($tmp . '  [EXCLUDED]');
             }
             continue;
         }
         $replaced = $src != $newSrc;
         if ($replaced) {
             $linked[] = $newSrc;
             $attrs['href'] = $newSrc;
         }
         $tmp = PsHtml::linkLink($attrs);
         $resources .= $tmp . "\n";
         if ($this->LOGGER->isEnabled()) {
             $attrs['href'] = $src;
             $this->LOGGER->info(($replaced ? PsHtml::linkLink($attrs) . '  [REPLACED]  ' : '') . $tmp);
         }
     }
     $html = preg_replace($pattern, '', $html);
     $resources = "\n" . trim($resources) . "\n";
     /*
      * Удалим пробелы
      */
     $matches = array();
     $cnt = preg_match("/<head>(.*?)<\\/head>/si", $html, $matches);
     if ($cnt == 1) {
         /**
          * $headOld - ресурсы страницы, находящиеся в блоке <head ...>...</head> и 
          * оставшиеся после вырезания .js и .css. Обычно там остаётся два блока:
          * <meta...>...</meta> и <title>...</title>
          */
         $headOld = $matches[1];
         $headNew = normalize_string($headOld);
         $headNew = "{$headNew} {$resources}";
         $html = str_replace_first($headOld, $headNew, $html);
     } else {
         //Вставляем ресурсы в <head>
         $html = str_replace_first('</head>', $resources . '</head>', $html);
     }
     $this->LOGGER->infoBox('PAGE FINALISED', $html);
     return $html;
 }
コード例 #21
0
ファイル: xml_reader.php プロジェクト: amoryver/ws-converter
function read_xml($out, $in_file, $options = array())
{
    // XMLオブジェクトを読む。
    $contents = normalize_encoding(file_get_contents($in_file));
    $contents = normalize_string($contents);
    $dom = new DOMDocument("1.0", "UTF-8");
    $dom->loadXML($contents);
    // 第1レベル要素(ルート)を取得する。固定名(dataset)でなくても受理する。
    $node1 = $dom->documentElement;
    for ($i = 0; $i < $node1->childNodes->length; $i++) {
        // 第2レベル要素(ワークシート)を取得する。
        $node2 = $node1->childNodes->item($i);
        if (!$node2 instanceof DOMElement) {
            continue;
        }
        // タグ間の改行は無視する。
        $worksheet_name = (string) $node2->tagName;
        // Pass1: ヘッダとフィールド名を収集する。
        $titles = array();
        $types = array();
        $params = array();
        $records = array();
        for ($j = 0; $j < $node2->childNodes->length; $j++) {
            // 第3レベル要素(オブジェクト)を取得する。
            $node3 = $node2->childNodes->item($j);
            if (!$node3 instanceof DOMElement) {
                continue;
            }
            // タグ間の改行は無視する。
            $object_name = (string) $node3->tagName;
            switch ($object_name) {
                case "titles":
                    for ($k = 0; $k < $node3->childNodes->length; $k++) {
                        // 第4レベル要素(フィールド)を取得する。
                        $node4 = $node3->childNodes->item($k);
                        if (!$node4 instanceof DOMElement) {
                            continue;
                        }
                        // タグ間の改行は無視する。
                        $field = (string) $node4->tagName;
                        $value = (string) $node4->nodeValue;
                        $titles[$field] = $value;
                    }
                    break;
                case "types":
                    for ($k = 0; $k < $node3->childNodes->length; $k++) {
                        // 第4レベル要素(フィールド)を取得する。
                        $node4 = $node3->childNodes->item($k);
                        if (!$node4 instanceof DOMElement) {
                            continue;
                        }
                        // タグ間の改行は無視する。
                        $field = (string) $node4->tagName;
                        $value = (string) $node4->nodeValue;
                        $types[$field] = $value;
                    }
                    break;
                case "params":
                    for ($k = 0; $k < $node3->childNodes->length; $k++) {
                        // 第4レベル要素(フィールド)を取得する。
                        $node4 = $node3->childNodes->item($k);
                        if (!$node4 instanceof DOMElement) {
                            continue;
                        }
                        // タグ間の改行は無視する。
                        $field = (string) $node4->tagName;
                        $value = (string) $node4->nodeValue;
                        $params[$field] = $value;
                    }
                    break;
                case "records":
                    for ($k = 0; $k < $node3->childNodes->length; $k++) {
                        // 第4レベル要素(レコード)を取得する。
                        $node4 = $node3->childNodes->item($k);
                        if (!$node4 instanceof DOMElement) {
                            continue;
                        }
                        // タグ間の改行は無視する。
                        $record = array();
                        for ($l = 0; $l < $node4->childNodes->length; $l++) {
                            // 第5レベル要素(フィールド)を取得する。
                            $node5 = $node4->childNodes->item($l);
                            if (!$node5 instanceof DOMElement) {
                                continue;
                            }
                            // タグ間の改行は無視する。
                            $field = (string) $node5->tagName;
                            $value = (string) $node5->nodeValue;
                            $record[$field] = $value;
                        }
                        $records[] = $record;
                        // $k はインデックスに使わないこと。
                    }
                    break;
            }
        }
        $fields = array();
        $num_cols = 0;
        $fields += array_keys($titles);
        $fields += array_keys($types);
        $fields += array_keys($params);
        for ($row = 0; $row < count($records); $row++) {
            $fields += array_keys($records[$row]);
        }
        if (($num_cols = count($fields)) == 0) {
            fputs(STDERR, "Error[{$in_file}]: no field specidied.\n");
            return;
        }
        // Pass2: 内部形式CSVを出力する。
        // 先頭行に "# ファイル名" を出力する。
        fputs($out, "# {$worksheet_name}\n");
        // ヘッダ行を出力する。
        $fields = array_pad($fields, $num_cols, "");
        array_unshift($fields, "fields");
        fputcsv($out, $fields, ",", '"');
        $types = array_pad($types, $num_cols, "text");
        array_unshift($types, "types");
        fputcsv($out, $types, ",", '"');
        $params = array_pad($params, $num_cols, "");
        array_unshift($params, "params");
        fputcsv($out, $params, ",", '"');
        $titles = array_pad($titles, $num_cols, "");
        array_unshift($titles, "titles");
        fputcsv($out, $titles, ",", '"');
        // データ行を出力する。
        for ($row = 0; $row < count($records); $row++) {
            $record = $records[$row];
            $csv_record = array();
            // $fields は上で unshift しているので 1 から開始する。
            for ($col = 1; $col < count($fields); $col++) {
                $csv_record[$col] = $record[$fields[$col]];
            }
            array_unshift($csv_record, "record");
            fputcsv($out, $csv_record, ",", '"');
        }
        // 最終行に空行を出力する。
        fputs($out, "\n");
    }
    return;
}