예제 #1
0
파일: PsGlobals.php 프로젝트: ilivanoff/www
 /**
  * Загружает глобальные настройки из файла и кеширует их в массиве GLOBALS.
  * Данный метод вызывается ТОЛЬКО при создании экземпляра класса.
  */
 private function load()
 {
     check_condition(!is_array($this->GLOBALS), 'Недопустима повторная загрузка глобальных настроек');
     $this->GLOBALS = array();
     $this->FileMtimeUpdate();
     $comment = array();
     foreach ($this->DI->getFileLines() as $line) {
         $line = trim($line);
         if (!$line || starts_with($line, '/*') || ends_with($line, '*/')) {
             continue;
         }
         if (starts_with($line, '*')) {
             $line = trim(first_char_remove($line));
             if ($line) {
                 $comment[] = $line;
             }
             continue;
         }
         if (starts_with($line, 'define')) {
             $name = trim(array_get_value(1, explode("'", $line, 3)));
             check_condition($name && defined($name), "Ошибка разбора файла глобальных настроек: свойство [{$name}] не определено.");
             $this->GLOBALS[$name] = new PsGlobalProp($name, implode(' ', $comment));
             $comment = array();
             continue;
         }
     }
 }
예제 #2
0
 /**
  * Функция производит финализацию страницы, показываемой пользователю, добавляя к ней элемент с содержащимися в нём ссылками.
  */
 public function appendLibItemsToPageContent($CONTENT)
 {
     $matches = array();
     $data = PsConstJs::BUBBLE_LOADER_FOLDING_DATA;
     $pattern = "/data-{$data}=\"(.+?)\"/si";
     preg_match_all($pattern, $CONTENT, $matches);
     $matches = array_unique(array_get_value(1, $matches, array()));
     $items = array();
     foreach ($matches as $unique) {
         $entity = Handlers::getInstance()->getFoldedEntityByUnique($unique, false);
         if ($entity && $entity->getFolding()->isItByType(LibResources::LIB_FOLDING_TYPE)) {
             $items[$entity->getUnique()] = $entity->getFolding()->getBubble($entity->getIdent());
         }
     }
     $has = count($items) > 0;
     if ($this->LOGGER->isEnabled()) {
         $this->LOGGER->info();
         $this->LOGGER->info('Библиотечные элементы, добавленные на страницу:');
         if ($has) {
             foreach ($items as $unique => $lib) {
                 $this->LOGGER->info("\t{$unique}");
             }
         } else {
             $this->LOGGER->info("\t-- Нет --");
         }
     }
     return $CONTENT . ($has ? PsHtml::div(array('id' => PsConstJs::BUBBLE_LOADER_FOLDING_STORE_ID), implode('', $items)) : '');
 }
예제 #3
0
파일: PsUtil.php 프로젝트: ilivanoff/www
 /**
  * Метод возвращает информацию о первом вызове класса в стеке.
  */
 public static function getClassFirstCall($class)
 {
     check_condition($class, 'Не передан класс для поиска в вызове');
     check_condition($class != __CLASS__, 'Класс ' . __CLASS__ . ' не может быть использован для поиска вызова');
     $found = null;
     foreach (debug_backtrace(0) as $item) {
         $curClass = array_get_value('class', $item);
         if ($curClass == __CLASS__) {
             if (is_array($found)) {
                 break;
                 //--
             }
             continue;
             //---
         }
         if ($curClass == $class) {
             $found = $item;
             continue;
             //---
         }
         if (is_array($found)) {
             break;
             //--
         }
     }
     return check_condition($found, "Класс {$class} не вызывался");
 }
예제 #4
0
 /**
  * Метод вызывается для инициализации окружения:
  * 1. Директория ресурсов окружения будет подключена в Autoload
  * 2. Файл, включающий окружение, будет выполнен
  */
 public static function init()
 {
     if (self::$inited) {
         return;
         //---
     }
     self::$inited = true;
     //---
     /*
      * Проверим, нужно ли подключать окружение
      */
     if (self::isSkipInclude()) {
         return;
         //---
     }
     $env = self::env();
     if (!$env) {
         return;
         //---
     }
     $envDir = array_get_value($env, ConfigIni::environments());
     if (!$envDir) {
         return PsUtil::raise('Environment [{}] not found', $env);
     }
     if (!is_dir($envDir)) {
         return PsUtil::raise('Environment dir for [{}] not found', $env);
     }
     $envSrcDir = next_level_dir($envDir, DirManager::DIR_SRC);
     $envIncFile = file_path($envDir, $env, PsConst::EXT_PHP);
     if (!is_file($envIncFile)) {
         return PsUtil::raise('Environment include file for [{}] not found', $env);
     }
     $LOGGER = PsLogger::inst(__CLASS__);
     if ($LOGGER->isEnabled()) {
         $LOGGER->info('Including \'{}\' environment for context \'{}\'', $env, PsContext::describe());
         $LOGGER->info('Env dir:  {}', $envDir);
         $LOGGER->info('Src dir:  {}', $envSrcDir);
         $LOGGER->info('Inc file: {}', $envIncFile);
     }
     //Проинициализировано окружение
     self::$included = true;
     //Регистрируем директорию с классами, специфичными только для данного окружения
     Autoload::inst()->registerBaseDir($envSrcDir, false);
     //Выполним необходимое действие
     $PROFILER = PsProfiler::inst(__CLASS__);
     try {
         $LOGGER->info('{');
         $PROFILER->start($env);
         self::initImpl($LOGGER, $envIncFile);
         $secundomer = $PROFILER->stop();
         $LOGGER->info('}');
         $LOGGER->info('Inc file included for {} sec', $secundomer->getTime());
     } catch (Exception $ex) {
         $PROFILER->stop(false);
         $LOGGER->info('Inc file execution error: [{}]', $ex->getMessage());
         throw $ex;
         //---
     }
 }
예제 #5
0
파일: block.box.php 프로젝트: ilivanoff/www
function smarty_block_box($params, $content, Smarty_Internal_Template &$smarty)
{
    if ($content) {
        $params['class'] = to_array(array_get_value('class', $params));
        $params['class'][] = 'psbox';
        return PsHtml::div($params, PsHtml::div(array('class' => 'psboxctt'), $content));
    }
}
예제 #6
0
 function categorization($id = null)
 {
     header('Content-Type: application/json');
     $cat = $this->categorization_model->get_categorization($id);
     $cat_settings = array_get_value((array) $cat, 'cat_settings');
     $cat_settings = unserialize($cat_settings);
     $cat_settings = $cat_settings && is_json($cat_settings) ? $cat_settings : json_encode(array('url' => base_url('data/category-builder-template.js')), JSON_UNESCAPED_SLASHES);
     echo $cat_settings;
 }
예제 #7
0
function smarty_block_text($params, $content, Smarty_Internal_Template &$smarty)
{
    if (!$content) {
        return;
    }
    $content = nl2br(trim($content));
    $params['class'] = array_get_value('class', $params, '') . ' text';
    return PsHtml::div($params, $content);
}
예제 #8
0
 /**
  * Массив - строка к кол-ву повторений
  */
 public function lineGroups()
 {
     $groups = array();
     foreach ($this->lines as $line) {
         $groups[$line] = array_get_value($line, $groups, 0);
         ++$groups[$line];
     }
     return $groups;
 }
예제 #9
0
 /**
  * Метод возвращает столбцы таблицы
  */
 public function getColumns($table)
 {
     if (!$this->getCache()->has(self::CACHE_COLUMNS)) {
         $this->getCache()->set(self::CACHE_COLUMNS, $this->getObjects("\nselect LOWER(c.TABLE_NAME) as TABLE_NAME,\n       LOWER(c.COLUMN_NAME) as COLUMN_NAME,\n       \n       c.IS_NULLABLE,\n       c.DATA_TYPE,\n       c.CHARACTER_MAXIMUM_LENGTH,\n       LOWER(c.COLUMN_KEY) as COLUMN_KEY,\n       c.EXTRA,\n       c.COLUMN_COMMENT,\n       c.COLUMN_DEFAULT,\n       \n       if(upk.CONSTRAINT_TYPE is null, 0, 1) as IS_PK,\n       \n       if(ufk.CONSTRAINT_TYPE is null, 0, 1) as IS_FK,\n       LOWER(ufk.REFERENCED_TABLE_NAME) as REFERENCED_TABLE_NAME,\n       LOWER(ufk.REFERENCED_COLUMN_NAME) as REFERENCED_COLUMN_NAME\n\n  from information_schema.columns c\n\n  left join (select cpk.CONSTRAINT_TYPE,\n                    upk.TABLE_SCHEMA,\n                    upk.TABLE_NAME,\n                    upk.COLUMN_NAME,\n                    upk.TABLE_CATALOG\n               from information_schema.KEY_COLUMN_USAGE  upk,\n                    information_schema.TABLE_CONSTRAINTS cpk\n              where upk.REFERENCED_TABLE_SCHEMA is null\n                and upk.REFERENCED_TABLE_NAME is null\n                and upk.REFERENCED_COLUMN_NAME is null\n                and upk.TABLE_SCHEMA = cpk.TABLE_SCHEMA\n                and upk.TABLE_NAME = cpk.TABLE_NAME\n                and upk.CONSTRAINT_CATALOG = cpk.CONSTRAINT_CATALOG\n                and upk.CONSTRAINT_NAME = cpk.CONSTRAINT_NAME\n                and upk.CONSTRAINT_SCHEMA = cpk.CONSTRAINT_SCHEMA\n                and cpk.CONSTRAINT_TYPE is not null\n                and cpk.CONSTRAINT_TYPE = 'PRIMARY KEY') as upk\n    on c.TABLE_SCHEMA = upk.TABLE_SCHEMA\n   and c.TABLE_NAME = upk.TABLE_NAME\n   and c.COLUMN_NAME = upk.COLUMN_NAME\n   and c.TABLE_CATALOG = upk.TABLE_CATALOG\n\n  left join (select LOWER(upk.REFERENCED_TABLE_NAME) as REFERENCED_TABLE_NAME,\n                    LOWER(upk.REFERENCED_COLUMN_NAME) as REFERENCED_COLUMN_NAME,\n                    \n                    cpk.CONSTRAINT_TYPE,\n                    upk.TABLE_SCHEMA,\n                    upk.TABLE_NAME,\n                    upk.COLUMN_NAME,\n                    upk.TABLE_CATALOG,\n                    upk.REFERENCED_TABLE_SCHEMA\n               from information_schema.KEY_COLUMN_USAGE  upk,\n                    information_schema.TABLE_CONSTRAINTS cpk\n              where upk.REFERENCED_TABLE_SCHEMA is not null\n                and upk.REFERENCED_TABLE_NAME is not null\n                and upk.REFERENCED_COLUMN_NAME is not null\n                and upk.TABLE_SCHEMA = cpk.TABLE_SCHEMA\n                and upk.TABLE_NAME = cpk.TABLE_NAME\n                and upk.CONSTRAINT_CATALOG = cpk.CONSTRAINT_CATALOG\n                and upk.CONSTRAINT_NAME = cpk.CONSTRAINT_NAME\n                and upk.CONSTRAINT_SCHEMA = cpk.CONSTRAINT_SCHEMA\n                and cpk.CONSTRAINT_TYPE is not null\n                and cpk.CONSTRAINT_TYPE = 'FOREIGN KEY') as ufk\n    on c.TABLE_SCHEMA = ufk.TABLE_SCHEMA\n   and c.TABLE_SCHEMA = ufk.REFERENCED_TABLE_SCHEMA\n   and c.TABLE_NAME = ufk.TABLE_NAME\n   and c.COLUMN_NAME = ufk.COLUMN_NAME\n   and c.TABLE_CATALOG = ufk.TABLE_CATALOG\n\n where c.table_schema = DATABASE()\n   /*and c.table_name = ?*/\n\n order by c.TABLE_NAME, c.ORDINAL_POSITION", null, PsTableColumn::getClass(), null, null, function (PsTableColumn $col, &$result, $row) {
             $result[$col->getTableName()][$col->getName()] = $col;
         }));
     }
     return array_get_value(lowertrim($table), $this->getCache()->get(self::CACHE_COLUMNS), array());
 }
예제 #10
0
 /**
  * Метод возвращает склонение слова в заданном падеже
  * 
  * @param string $word - слово
  * @param string $type - требуемый падеж
  * @return type
  */
 public function getInflection($word, $type = self::TYPE_ORIG)
 {
     if ($type == self::TYPE_ORIG) {
         return $word;
         //Сразу вернём оригинальное значение
     }
     PsUtil::assertClassHasConstVithValue(__CLASS__, 'TYPE_', $type);
     return array_get_value($type, $this->getInflections($word));
 }
예제 #11
0
 /** @return PsTable */
 public function getTable($table)
 {
     if ($table instanceof FoldedResources) {
         $table = $table->getTableName();
         //Если для фолдинга нет таблицы - возвращаем null
         return array_get_value($table, $this->getTables());
     }
     return check_condition(array_get_value($table, $this->getTables()), "Таблица [{$table}] не существует.");
 }
예제 #12
0
 /**
  * Метод возвращает <img /> элемент, готовый для вставки на страницу
  */
 public static function getAvatarImg(PsUser $user = null, $dim = false, array $params = array())
 {
     $params['src'] = self::getAvatarDi($user, $dim);
     $params['alt'] = $user ? $user->getName() : 'Аноним';
     $params['data'] = $user ? array('uid' => $user->getId()) : null;
     $params['class'] = to_array(array_get_value('class', $params));
     $params['class'][] = array('avatar', $user ? 'user' : null);
     return PsHtml::img($params);
 }
예제 #13
0
파일: CssSprite.php 프로젝트: ilivanoff/www
 private function spanImpl($itemName, array $attrs = array(), $class = null)
 {
     $attrs['class'] = to_array(array_get_value('class', $attrs));
     $attrs['class'][] = $class;
     $attrs['class'][] = 'sprite';
     $attrs['class'][] = 'sprite-' . $this->name;
     $attrs['class'][] = 'sprite-' . $this->name . '-' . $itemName;
     return PsHtml::span($attrs);
 }
예제 #14
0
파일: BaseStock.php 프로젝트: ilivanoff/www
 /**
  * Идентификатор акции - хэш от типа акции и её параметров.
  * Две акции с одним типом но разными кодами считаются разными.
  * 
  * @param array $params - параметры акции
  */
 private function sign(array $params)
 {
     $type = self::getType();
     $sign['_STOCK_CLASS_TYPE_'] = $type;
     foreach (PsUtil::getClassConsts($this, 'DATA_') as $param) {
         $sign[$param] = check_condition(array_get_value($param, $params), "Для акции {$type} не указан обязательный параметр [{$param}].");
     }
     return simple_hash($sign);
 }
예제 #15
0
    private function saveImg($gallery, array $img, $order)
    {
        check_condition($gallery, 'Не задано название галереи');
        $file = check_condition(array_get_value('file', $img), 'Не задан путь к картинке');
        $this->update('
INSERT INTO ps_gallery_images 
(v_dir, v_file, b_show, b_web, v_name, v_descr, n_order) 
VALUES 
(?, ?, ?, ?, ?, ?, ?)', array($gallery, $file, !isEmptyInArray('show', $img), !isEmptyInArray('web', $img), $img['name'], $img['descr'], $order));
    }
예제 #16
0
 public function __construct(array $params = array())
 {
     // check which image library to use
     // Imagick (Image Magick) is preferable
     if (extension_loaded('imagick')) {
         $this->sImageLibrary = 'imagick';
         // what image formats does the installed version of Imagick support
         // probably overkill to call as PNG, GIF, JPEG surely supported but done for completeness
         try {
             // Fixes #473915 as queryformats no longer works as a static method.
             $oImagick = new Imagick();
             $aImageFormats = $oImagick->queryFormats();
         } catch (ImagickException $e) {
             error_log($e->getMessage());
         }
         // store supported formats for populating drop downs etc later
         if (in_array('PNG', $aImageFormats)) {
             $this->aImageTypes[] = 'PNG';
         }
         if (in_array('GIF', $aImageFormats)) {
             $this->aImageTypes[] = 'GIF';
         }
         if (in_array('JPG', $aImageFormats)) {
             $this->aImageTypes[] = 'JPG';
         }
     } else {
         // check for GD, if it fails here there is no point continuing as the tool can't generate sprite images
         // without either library
         if (!extension_loaded('gd')) {
             die('GD and Imagick extensions not loaded. This tool requires one of these to generate sprite graphics.');
         }
         $this->sImageLibrary = 'gd';
         // get info about installed GD library to get image types (some versions of GD don't include GIF support)
         $oGD = gd_info();
         // store supported formats for populating drop downs etc later
         if (array_get_value('PNG Support', $oGD)) {
             $this->aImageTypes[] = 'PNG';
         }
         if (array_get_value('GIF Create Support', $oGD)) {
             $this->aImageTypes[] = 'GIF';
         }
         if (array_get_value('JPG Support', $oGD)) {
             $this->aImageTypes[] = 'JPG';
         }
     }
     /*
      * Сразу выполним подготовку
      */
     $GenParams = array('build-direction' => 'vertical', 'vertical-offset' => 2, 'horizontal-offset' => 2, 'background' => '', 'image-output' => strtoupper(SYSTEM_IMG_TYPE), 'image-num-colours' => 'true-colour', 'image-quality' => 75, 'width-resize' => 100, 'height-resize' => 100, 'ignore-duplicates' => 'ignore', 'class-prefix' => 'sprite-', 'selector-prefix' => '', 'selector-suffix' => '', 'wrap-columns' => true, 'use-transparency' => true, 'add-width-height-to-css' => true);
     //Возможность переопределить параметры генерации
     $GenParams = array_merge($GenParams, $params);
     $isOk = $this->ProcessParams($GenParams);
     check_condition($isOk, __CLASS__ . ' prepearing error: ' . print_r($this->aFormErrors, true));
 }
예제 #17
0
 /**
  * В конструкторе проинициализируем все параметры соединения
  */
 private function __construct(array $params, $sourceDescr)
 {
     foreach (PsUtil::getClassConsts(__CLASS__, 'PARAM_') as $param) {
         $value = array_get_value(PsCheck::notEmptyString($param), $params);
         if (PsCheck::isNotEmptyString($value)) {
             $this->PARAMS[$param] = $value;
         } else {
             $this->PARAMS[$param] = null;
             //raise_error("Задано пустое значения для параметра $param в источнике $sourceDescr");
         }
     }
     $this->url = PsStrings::replaceWithBraced("{}://{}:{}@{}/{}", $this->scheme(), $this->user(), $this->password(), $this->host(), $this->database());
     $this->toString = PsStrings::replaceWithBraced("{}://{}:{}@{}/{} (source: {})", $this->scheme(), $this->user(), '***', $this->host(), $this->database(), $sourceDescr);
 }
예제 #18
0
 /**
  * Метод проверяет, работаем ли мы в контексте ajax
  */
 public static function isAjax()
 {
     /*
      * Определена ли специальная константа, которая определяется в AjaxTools
      * Парамер HTTP_X_REQUESTED_WITH может быть не установлен, например, при загрузке файла с помощью flash.
      */
     if (defined('PS_AJAX_CONTEXT') && !!PS_AJAX_CONTEXT) {
         return true;
         //---
     }
     /*
      * Проверим наличие переменной HTTP_X_REQUESTED_WITH в глобальном массиве $_SERVER
      */
     return 'xmlhttprequest' == lowertrim(array_get_value('HTTP_X_REQUESTED_WITH', $_SERVER, ''));
 }
예제 #19
0
파일: APRecEdit.php 프로젝트: ilivanoff/www
 /**
  * Различные ссылки, которые могут быть обработаны данной страницей
  */
 private static function url($mode = self::MODE_TABLES_LIST, $table = null, $recOrId = null, array $params = array())
 {
     $params['mode'] = $mode;
     if (in_array($mode, array(self::MODE_TABLES_LIST, self::MODE_INSERTS))) {
         return self::pageUrl($params);
     }
     $table = $table instanceof PsTable ? $table : TableExporter::inst()->getTable($table);
     $params['table'] = $table->getName();
     if (in_array($mode, array(self::MODE_TABLE_ROWS, self::MODE_ROW_ADD, self::MODE_TABLE_SQL, self::MODE_TABLE_ARR))) {
         return self::pageUrl($params);
     }
     $pk = $table->getPk()->getName();
     $recId = is_array($recOrId) ? array_get_value($pk, $recOrId) : $recOrId;
     $params[$pk] = $recId;
     return self::pageUrl($params);
 }
예제 #20
0
파일: block.ol.php 프로젝트: ilivanoff/www
function smarty_block_ol($params, $content, Smarty_Internal_Template &$smarty)
{
    if (isEmpty($content)) {
        return;
        //---
    }
    $params['class'] = to_array(array_get_value('class', $params));
    $params['class'][] = 'block_ol';
    $strings = explode("\n", trim($content));
    $lis = array();
    foreach ($strings as $string) {
        if (!isEmpty($string)) {
            $lis[] = '<li>' . trim($string) . '</li>';
        }
    }
    $content = join('', $lis);
    return PsHtml::html2('ol', $params, $content);
}
예제 #21
0
 private function getVotesImpl($group, $inst, $userId, $default = 0)
 {
     if (!array_key_exists($group, $this->CACHE)) {
         return $userId ? $this->BEAN->getUserVotes($group, $inst, $userId, $default) : $this->BEAN->getVotesCount($group, $inst, $default);
     }
     if ($userId) {
         //User cache
         if (!array_key_exists($userId, $this->CACHE[$group][self::CACHE_USER])) {
             $this->CACHE[$group][self::CACHE_USER][$userId] = $this->BEAN->getUserVotes4Group($group, $userId);
         }
         return array_get_value($inst, $this->CACHE[$group][self::CACHE_USER][$userId], $default);
     } else {
         //Total cache
         if (!array_key_exists(self::CACHE_TOTAL, $this->CACHE[$group])) {
             $this->CACHE[$group][self::CACHE_TOTAL] = $this->BEAN->getVotesCount4Group($group);
         }
         return array_get_value($inst, $this->CACHE[$group][self::CACHE_TOTAL], $default);
     }
 }
예제 #22
0
 private function extractUsedBubbleItems($content, array &$items = array())
 {
     $matches = array();
     $data = PsConstJs::BUBBLE_LOADER_FOLDING_DATA;
     $pattern = "/data-{$data}=\"(.+?)\"/si";
     preg_match_all($pattern, $content, $matches);
     $uniques = array_diff(array_unique(array_get_value(1, $matches, array())), array_keys($items));
     //Сначала соберём все баблы
     foreach ($uniques as $unique) {
         $bubble = PsBubble::extractFoldedEntityBubbleDiv($unique);
         if ($bubble) {
             $items[$unique] = $bubble;
         }
     }
     //Соберём баблы, вложенные в другие баблы
     foreach ($uniques as $unique) {
         $this->extractUsedBubbleItems($items[$unique], $items);
     }
 }
예제 #23
0
 function get_expand()
 {
     header('Content-Type: application/json');
     if (!$this->users->logged_in()) {
         r_direct_login();
     } else {
         $parameters = array();
         if ($this->input->server('REQUEST_METHOD') === 'POST') {
             $parameters = $_POST;
         } elseif ($this->input->server('REQUEST_METHOD') === 'GET') {
             $parameters = $_GET;
         }
         $results = $this->terms_model->call_term_expand($parameters);
         $data['results'] = $results == false ? array() : $results;
         $data['message'] = $results == false ? $this->config->item('error_start_delimiter', 'search') . lang('search_error_message') . $this->config->item('error_end_delimiter', 'search') : $this->session->flashdata('message');
         $results = array_get_value((array) $results, element('source', $parameters));
         echo json_encode($results, true);
     }
 }
 /**
  * В процессе закрытия данного класса мы напишем полный список изменённых сущностей
  */
 public function onDestruct()
 {
     foreach (array('ACTION_FOLDING_' => 'Фолдинги', 'ACTION_ENTITY_' => 'Сущности') as $CONST_PREFIX => $name) {
         $this->LOGGER->infoBox($name);
         foreach (PsUtil::getClassConsts($this, $CONST_PREFIX) as $action) {
             $idents = array_get_value($action, $this->ACTIONS, array());
             $count = count($idents);
             $this->LOGGER->info();
             $this->LOGGER->info($action . ':');
             if ($count > 0) {
                 for ($i = 0; $i < $count; $i++) {
                     $this->LOGGER->info("\t" . (1 + $i) . '. ' . $idents[$i][0] . ($idents[$i][1] ? ' [' . $idents[$i][1] . ']' : ''));
                 }
             } else {
                 $this->LOGGER->info("\t -- Нет --");
             }
         }
     }
 }
예제 #25
0
 function __construct($date)
 {
     $date = trim($date);
     if (!$date) {
         return;
         //Невалидная дата
     }
     $this->date = $date;
     //Дата - до Н.Э. (570 BC)
     if (ends_with($date, ' BC')) {
         $tmp = explode(' ', $date);
         $y = count($tmp) == 2 ? $tmp[0] : null;
         if (is_numeric($y)) {
             $this->y = (int) $y;
             $this->type = self::TYPE_BC;
             $this->weight = -$this->y;
             $this->Ymd = $date;
         }
         return;
         //---
     }
     //Дальше действовать будет date_parse:)
     $tmp = date_parse($date);
     $error_count = array_get_value('error_count', $tmp, 0);
     $warning_count = array_get_value('warning_count', $tmp, 0);
     if ($error_count || $warning_count) {
         return;
         //Невалидная дата
     }
     //Валидная дата
     $this->y = (int) $tmp['year'];
     $this->m = (int) $tmp['month'];
     $this->d = (int) $tmp['day'];
     $this->hh = (int) $tmp['hour'];
     $this->mm = (int) $tmp['minute'];
     $this->ss = (int) $tmp['second'];
     $y = pad_zero_left($this->y, 4);
     $m = pad_zero_left($this->m, 2);
     $d = pad_zero_left($this->d, 2);
     $this->type = self::TYPE_VALID;
     $this->weight = (int) "{$y}{$m}{$d}";
     $this->Ymd = "{$y}-{$m}-{$d}";
 }
예제 #26
0
function executeProcess(array $argv)
{
    $rebuses = DirItem::inst(__DIR__, 'rebuses.txt')->getTextFileAdapter();
    $MR = PsMathRebus::inst();
    $result = array();
    foreach ($rebuses->getLines() as $rebus) {
        if (starts_with($rebus, '#')) {
            continue;
            //---
        }
        $rebus = $MR->normalize($rebus);
        switch ($MR->rebusState($rebus)) {
            case PsMathRebus::STATE_HAS_ANSWERS:
                dolog("Take rebus answers: {$rebus}");
                $result[$rebus] = $MR->rebusAnswers($rebus);
                break;
            case PsMathRebus::STATE_NO_ANSWERS:
                dolog("Skipping rebus: {$rebus}");
                $result[$rebus] = array();
                break;
            case PsMathRebus::STATE_NOT_REGISTERED:
                dolog("Processing rebus: {$rebus}");
                $result[$rebus] = PsMathRebusSolver::solve($rebus);
                break;
        }
    }
    $ansDI = DirItem::inst(__DIR__, 'answers.txt');
    $ansDI->remove();
    foreach ($result as $rebus => $answers) {
        $ansDI->writeLineToFile($rebus);
        foreach ($answers as $answer) {
            $ansDI->writeLineToFile($answer);
        }
        $ansDI->writeLineToFile();
    }
    /*
     * Если передан параметр копирования, то скопируем файл после обработки
     */
    if (1 == array_get_value(1, $argv, 0)) {
        dolog('Copy from [{}] to [{}]', $ansDI->getRelPath(), $MR->getAnswersDI()->getRelPath());
        $ansDI->copyTo($MR->getAnswersDI()->getAbsPath());
    }
}
예제 #27
0
 /** @return SimpleImage */
 public function load($path)
 {
     $this->close();
     $path = $path instanceof DirItem ? $path->getAbsPath() : $path;
     PsImg::assertIsImg($path);
     $this->path = $path;
     $this->type = PsImg::getType(array_get_value(2, getimagesize($path)));
     switch ($this->type) {
         case IMAGETYPE_JPEG:
             $this->image = imagecreatefromjpeg($path);
             break;
         case IMAGETYPE_GIF:
             $this->image = imagecreatefromgif($path);
             break;
         case IMAGETYPE_PNG:
             $this->image = imagecreatefrompng($path);
             break;
     }
     return $this;
 }
예제 #28
0
function smarty_block_choice($params, $content, Smarty_Internal_Template &$smarty)
{
    $ctxtParams = SmartyBlockContext::getInstance()->registerBlock($content, __FUNCTION__);
    if (!$content) {
        return;
    }
    //<select name="$name" /> || <input type="checkbox|readio" name="$name" />
    $name = array_get_value('name', $params);
    //Если передан label, то поле будет отображено, как field формы
    $label = array_get_value('label', $params);
    //Текущее значение
    $curVal = array_get_value_unset('value', $params);
    //Текущее значение
    $choiceType = array_get_value_unset('type', $params);
    //Значения
    $options = array_get_value(SmartyBlockContext::CHOICE_OPTION, $ctxtParams);
    if (isEmpty($options)) {
        return;
        //---
    }
    switch ($choiceType) {
        case 'combo':
        case 'select':
            echo $label ? PsHtmlForm::select($label, $name, $params, $options, $curVal) : PsHtml::select($params, $options, $curVal);
            break;
        case 'check':
        case 'checkboxes':
            echo $label ? PsHtmlForm::checkboxes($label, $name, $options, $curVal) : PsHtml::checkboxes($name, $options, $curVal);
            break;
        case 'radio':
        case 'radios':
            echo $label ? PsHtmlForm::radios($label, $name, $options, $curVal) : PsHtml::radios($name, $options, $curVal);
            break;
        default:
            echo PsHtml::divErr("Неизвестный тип выбора: [{$choiceType}]");
    }
}
예제 #29
0
 function get_tag_names()
 {
     if (!$this->users->logged_in()) {
         r_direct_login();
     } else {
         $parameters = array();
         if ($this->input->server('REQUEST_METHOD') === 'POST') {
             $parameters = $_POST;
         } elseif ($this->input->server('REQUEST_METHOD') === 'GET') {
             $parameters = $_GET;
         }
         $results = $this->tags_model->call_get_tag_names($parameters);
         //$data['results'] = ($results==false) ? array() : $results;
         $results = array_get_value((array) $results, element('source', $parameters));
         $options = $this->application->get_config('options', 'actions');
         $tagnames = array_key_exists('tagnames', $options) ? element('tagnames', $options) : array();
         if (array_key_exists('text', $parameters)) {
             $results = array_filter(array_merge($results, $tagnames), function ($var) use($parameters) {
                 return stripos($var, element('text', $parameters)) !== false;
             });
         }
         echo json_encode(array_values($results), true);
     }
 }
예제 #30
0
 function index()
 {
     header('Content-Type: application/json');
     if (!$this->users->logged_in()) {
         //redirect them to the login page
         r_direct_login();
     } else {
         if ($this->query->method() == 'POST') {
             $parameters = isset($_POST) && !empty($_POST) ? $_POST : array();
             $results = $this->search_model->call_term_expand($parameters);
             $data['results'] = $results == false ? array() : $results;
             $data['message'] = $results == false ? $this->config->item('error_start_delimiter', 'search') . lang('search_error_message') . $this->config->item('error_end_delimiter', 'search') : $this->session->flashdata('message');
             $results = array_get_value(element('source', parameters), $results);
             echo json_encode($results, true);
         } elseif ($this->query->method() == 'GET') {
             $parameters = isset($_GET) && !empty($_GET) ? $_GET : array();
             $results = $this->search_model->call_term_expand($parameters);
             $data['results'] = $results == false ? array() : $results;
             $data['message'] = $results == false ? $this->config->item('error_start_delimiter', 'search') . lang('search_error_message') . $this->config->item('error_end_delimiter', 'search') : $this->session->flashdata('message');
             $results = array_get_value(element('source', parameters), $results);
             echo json_encode($results, true);
         }
     }
 }