Example #1
0
 private function processAnswersFile()
 {
     $result = array();
     $lines = explode("\n", trim($this->getAnswersDI()->getFileContents(false)));
     $current = null;
     foreach ($lines as $line) {
         $line = trim($line);
         if ($line && !$current) {
             //Начинается новый ребус
             $current = $line;
             $result[$current] = array();
         } else {
             if ($line && $current) {
                 //Ответ на ребус
                 $result[$current][] = $line;
             } else {
                 if (!$line && $current) {
                     //Пробел, закончили ребус
                     $current = null;
                 }
             }
         }
     }
     $this->LOGGER->info(print_r($result, true));
     return $result;
 }
Example #2
0
 /**
  * Метод разбирает файл с ребусами, который выглядит как:
  * 
  * ребус 1
  * ответ 1.1
  * ответ 1.2
  * 
  * ребус 2
  * ответ 2.1
  * ответ 2.2
  * 
  * @return type
  */
 private function parseAnswersFile(DirItem $di)
 {
     $result = array();
     $lines = explode("\n", trim($di->getFileContents(false)));
     $current = null;
     foreach ($lines as $line) {
         $line = trim($line);
         if ($line && !$current) {
             //Начинается новый ребус
             $current = $line;
             $result[$current] = array();
         } else {
             if ($line && $current) {
                 //Ответ на ребус
                 $result[$current][] = $line;
             } else {
                 if (!$line && $current) {
                     //Пробел, закончили ребус
                     $current = null;
                 }
             }
         }
     }
     if ($this->LOGGER->isEnabled()) {
         $this->LOGGER->info('Rebuses of {}:', $di->getRelPath());
         $this->LOGGER->info(print_r($result, true));
         $this->LOGGER->info();
     }
     return $result;
 }
Example #3
0
 /**
  * Основной метод, вызываемый для регистрации плагинов, предоставляемых данным классом для выполнения смарти-функций
  */
 public final function registerPlugins(Smarty $smarty)
 {
     $this->LOGGER->info('Регистрируем плагины класса [{}]', $this->CLASS);
     foreach ($this->getPlugins() as $tagName => $pluginType) {
         PSSmartyTools::checkFunctionType($pluginType);
         if (array_key_exists($pluginType, $smarty->registered_plugins) && array_key_exists($tagName, $smarty->registered_plugins[$pluginType])) {
             $this->LOGGER->info('Не зарeгистрирован плагин [{}]', 'smarty_' . $pluginType . '_' . $tagName);
         } else {
             $smarty->registerPlugin($pluginType, $tagName, array($this, 'do_' . $pluginType . '_' . $tagName));
             $this->LOGGER->info('Зарeгистрирован плагин [{}]', 'smarty_' . $pluginType . '_' . $tagName);
         }
     }
 }
Example #4
0
 public final function ctxtAction(AbstractContext $ctxt, $isSetted)
 {
     if (!$this->isOurContext($ctxt)) {
         return;
         //---
     }
     if ($isSetted) {
         $this->CTXTS[] = $ctxt;
     } else {
         check_condition($this->CTXTS, 'Попытка сбросить контекст, который не был стартован');
         $lastCtxt = array_pop($this->CTXTS);
         check_condition($lastCtxt === $ctxt, 'Сбрасываемый контекст не соответствует установленному: ' . get_class($lastCtxt) . '-' . get_class($ctxt));
     }
     $this->LOGGER->info("{} context: {} - {}", $isSetted ? '+' : '-', get_class($ctxt), $ctxt->getContextIdent());
 }
Example #5
0
 /**
  * Генерация комментариев к постам.
  * rootCount - кол-во root комментариев
  * childCount - кол-во дочерних комментариев, при этом они привязываются случайным образом
  * postType - если передан, то комментарии будут сгенерированы только к постам этого типа
  * postId - для генерации комменариев к конкретному посту
  * takeTextFromPost - признак, брать ли текст комментариев из тела поста
  */
 public final function generateComments($rootCount = 20, $childCount = 50, $postType = null, $postId = null, $takeTextFromPost = true)
 {
     $cproc = $this->getCommentsProcessor($postType);
     /* @var $proc PostsProcessor */
     foreach ($cproc as $proc) {
         $this->LOGGER->info("<<<CREATING COMMENTS FOR POSTS OF TYPE [" . $proc->getPostType() . "]>>>");
         if ($postId) {
             $posts[] = $proc->getPost($postId);
         } else {
             $posts = $proc->getPosts();
         }
         /* @var $post AbstractPost */
         foreach ($posts as $post) {
             $this->LOGGER->info("Creating comments for post " . $post->getPostType() . '|' . $post->getName());
             for ($i = 1; $i <= $rootCount; $i++) {
                 $proc->getDiscussionController()->saveMessage($post->getId(), null, $this->getText($proc, $post->getId(), $takeTextFromPost), null, PsUser::inst(TESTBean::inst()->getRandomUserId()));
             }
             for ($i = 1; $i <= $childCount; $i++) {
                 $commentsTable = $proc->dbBean()->getCommentsTable();
                 $parentId = TESTBean::inst()->getRandomCommentId($commentsTable, $post->getId());
                 $proc->getDiscussionController()->saveMessage($post->getId(), $parentId, $this->getText($proc, $post->getId(), $takeTextFromPost), null, PsUser::inst(TESTBean::inst()->getRandomUserId()));
             }
         }
     }
 }
 /**
  * В конструкторе зарегистрируем все страницы
  */
 protected final function __construct()
 {
     //Инициализируем хранилище, чтобы честно замерять время создания регистрации самих экземпляров
     FoldedStorage::init();
     $class = get_called_class();
     $basic = __CLASS__ == $class;
     //Логгер
     $this->LOGGER = PsLogger::inst(__CLASS__);
     $this->LOGGER->info('USING {} STORAGE: {}', $basic ? 'SDK' : 'CUSTOM', $class);
     //Стартуем профайлер
     $this->PROFILER = PsProfiler::inst(__CLASS__);
     $this->PROFILER->start('Loading folding insts');
     //Регистрируем фолдинги SDK
     $this->LOGGER->info();
     $this->LOGGER->info('FOLDINGS SDK:');
     $this->registerSdkFoldings();
     //Если используем не SDK провайдер, вызываем регистратор
     if (!$basic) {
         $this->LOGGER->info();
         $this->LOGGER->info('FOLDINGS PROJECT:');
         $this->registerProjectFoldings();
     }
     //Отсортируем фолдинги по идентификаторам
     ksort($this->FOLDINGS);
     //Останавливаем профайлер
     $sec = $this->PROFILER->stop();
     //Логируем
     $this->LOGGER->info();
     $this->LOGGER->info('COLLECTING TIME: {} sec', $sec->getTotalTime());
 }
Example #7
0
 public function clean($group = null)
 {
     $this->LOGGER->info($group ? "Очистка кеша по группе [{$group}]" : 'Полная очистка кеша');
     $this->CACHELITE->clean($group);
     if ($group) {
         //Эту группу больше не нужно валидировать
         $this->TREE->setGroupValidated($group);
         //Очистим ключи локального хранилища
         $keys = $this->CACHE->keys();
         $removed = array();
         $prefix = $this->localCacheGroup($group);
         foreach ($keys as $key) {
             if (starts_with($key, $prefix)) {
                 $removed[] = $key;
                 $this->CACHE->remove($key);
             }
         }
         if ($removed) {
             $this->LOGGER->info('В локальном кеше были удалены следующие ключи: {}.', concat($removed));
         }
     } else {
         $this->CACHE->clear();
         $this->TREE->setAllValidated('Полная очистка кеша');
     }
 }
Example #8
0
 /**
  * В процессе закрытия данного класса мы напишем полный список изменённых сущностей
  */
 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 -- Нет --");
             }
         }
     }
     /**
      * Распечатаем карту зависимости сущностей фолдинга.
      * Операция настолько тяжёлая, что в режиме ajax также будем избегать её выполнение.
      */
     if (PsDefines::isDevmode() && !PageContext::inst()->isAjax()) {
         $this->LOGGER->infoBox('Карта зависимости сущностей фолдингов:');
         foreach ($this->getDependsOnMap() as $who => $fromWhoArr) {
             $this->LOGGER->info("\t{$who}:");
             foreach ($fromWhoArr as $fromWho) {
                 $this->LOGGER->info("\t\t{$fromWho}");
             }
         }
     }
 }
Example #9
0
 /**
  * Метод возвращает формы слова во всех падежах
  * 
  * @param type $word
  * @return array - все склонения слова в виде массива, где под индексом 0 - оригинальное значение
  */
 public function getInflections($word)
 {
     $word = PsCheck::notEmptyString(trim($word));
     if ($this->CACHE->has($word)) {
         return $this->CACHE->get($word);
     }
     $this->LOGGER->info();
     $this->LOGGER->info('> Запрошено склонение для слова [{}]', $word);
     //$fileName = iconv('UTF-8', 'cp1251', $word);
     /*
      * Ищем в БД
      */
     $inflections = InflectsBean::inst()->getInflections($word);
     if (is_array($inflections)) {
         $this->LOGGER->info('< Cклонение для [{}] найдено в базе: {}', $word, array_to_string($inflections));
         return $this->CACHE->set($word, $inflections);
     }
     /*
      * Загружаем с сервиса
      */
     $inflections = $this->loadInflectionImpl($word);
     if (is_array($inflections) && count($inflections) == 7) {
         $this->LOGGER->info('< Склонение для [{}] успешно загружено: {}', $word, array_to_string($inflections));
         //Не забудем сохранить полеченное склонение для слова
         InflectsBean::inst()->saveInflections($inflections);
         return $this->CACHE->set($word, $inflections);
     }
     /*
      * Загрузить не удалось, возвращаем балванку
      */
     $inflections = array_fill(0, 7, $word);
     $this->LOGGER->info('< Склонение для [{}] не определено, возвращаем "болванку": {}', $word, array_to_string($inflections));
     return $this->CACHE->set($word, $inflections);
 }
Example #10
0
 /**
  * В конструкторе зарегистрируем все страницы
  */
 protected final function __construct()
 {
     $class = get_called_class();
     $basic = __CLASS__ == $class;
     //Логгер
     $this->LOGGER = PsLogger::inst(__CLASS__);
     $this->LOGGER->info('USING {} PLUGIN PROVIDER: {}', $basic ? 'SDK' : 'CUSTOM', $class);
     //Стартуем профайлер
     $this->PROFILER = PsProfiler::inst(__CLASS__);
     $this->PROFILER->start('Loading plugins');
     //Регистрируем фолдинги SDK
     $this->LOGGER->info();
     $this->LOGGER->info('PLUGINS SDK:');
     $this->registerSdkSmartyPlugins();
     //Если используем не SDK провайдер, вызываем регистратор
     if (!$basic) {
         $this->LOGGER->info();
         $this->LOGGER->info('PLUGINS PROJECT:');
         $this->registerProjectSmartyPlugins();
     }
     //Останавливаем профайлер
     $sec = $this->PROFILER->stop();
     //Логируем
     $this->LOGGER->info();
     $this->LOGGER->info('COLLECTING TIME: {} sec', $sec->getTotalTime());
 }
Example #11
0
 /**
  * Предварительная обработка страницы - самое время выполнить сабмит формы, редирект и остальные подобные вещи
  */
 private final function postProcess()
 {
     //Проверим и сменим состояние
     $this->changeState(self::STATE_STARTED, self::STATE_FINISHED);
     //Устанавливаем контекст
     $BUILDER_CTXT = PageBuilderContext::getInstance();
     //Проверим, что наш контекст не был сброшен
     check_condition(__CLASS__ == $BUILDER_CTXT->getContextIdent(), 'Unexpected ' . get_class($BUILDER_CTXT) . ': ' . $BUILDER_CTXT->getContextIdent());
     //Получим параметры страницы
     $pagePrams = new PageParams($BUILDER_CTXT->finalizeTplContent(null));
     //Сброим контекст, он нам больше не нужен
     $BUILDER_CTXT->dropContext();
     try {
         //Вызываем завершающую обработку страницы
         $result = $this->postProcessImpl($pagePrams, RequestArrayAdapter::inst());
         //Останавливаем профайлер
         $sec = $this->PROFILER->stop();
         //Отлогируем
         $this->LOGGER->info('Page build done in {} sec', $sec->getTime());
         //Вернём
         return $result;
         //---
     } catch (Exception $ex) {
         $this->PROFILER->stop(false);
         throw $ex;
     }
 }
Example #12
0
 /**
  * В конструкторе зарегистрируем все страницы
  */
 protected final function __construct()
 {
     $class = get_called_class();
     $basic = __CLASS__ == $class;
     //Логгер
     $this->LOGGER = PsLogger::inst(__CLASS__);
     $this->LOGGER->info('USING {} STORAGE: {}', $basic ? 'SDK' : 'CUSTOM', $class);
     //Стартуем профайлер
     $this->PROFILER = PsProfiler::inst(__CLASS__);
     $this->PROFILER->start('Registering Web pages');
     //Регистрируем страницы SDK
     $this->LOGGER->info();
     $this->LOGGER->info('PAGES SDK:');
     $this->registerSdkPages();
     //Если используем не SDK провайдер, вызываем регистратор
     if (!$basic) {
         $this->LOGGER->info();
         $this->LOGGER->info('PAGES PROJECT:');
         $this->registerProjectPages();
     }
     //Проведём инициализацию
     $this->LOGGER->info();
     $this->LOGGER->info('INITIALIZING...');
     $this->init();
     //Останавливаем профайлер
     $sec = $this->PROFILER->stop();
     //Логируем
     $this->LOGGER->info();
     $this->LOGGER->info('REGISTERING TIME: {} sec', $sec->getTotalTime());
 }
Example #13
0
 /**
  * Метод утверждает, что мы можем выполнять модификацию пользователя, что возможно, если:
  * 1. Данный пользователь является нами
  * 2. Мы авторизованы под администратором
  */
 protected final function assertCanEdit($__FUNCTION__, $doAssert = true)
 {
     if ($doAssert) {
         $this->LOGGER->info('[{}] {}({})', $this->userId, __FUNCTION__, $__FUNCTION__);
         check_condition($this->canEdit, 'Cannot call ' . $__FUNCTION__ . ' for user ' . $this->userId);
     }
 }
Example #14
0
 private function __construct()
 {
     $this->CLASS = get_called_class();
     $this->CACHE = new SimpleDataCache();
     $this->DBTYPE = $this->getUploadType();
     $this->LOGGER = PsLogger::inst($this->CLASS);
     $this->LOGGER->info('Instance created. Work with db ? {}. Is autonomous ? {}.', var_export($this->isStoreToDb(), true), var_export($this->isAutonomous(), true));
     $this->LOGGER->info();
 }
 protected final function __construct()
 {
     $this->LOGGER = PsLogger::inst(__CLASS__);
     $class = 'Memcache';
     if (!class_exists($class)) {
         $this->LOGGER->info($class . ' class is not exists!');
         return;
         //---
     }
     $this->MEMCACHE = new $class();
     if (!@$this->MEMCACHE->connect('127.0.0.1', 11211)) {
         $this->LOGGER->info('Could not connect to localhost!');
         $this->MEMCACHE = null;
         return;
         //---
     }
     $this->LOGGER->info($class . ' is enabled.');
 }
Example #16
0
 /**
  * Метод должен быть вызван перед подключением библиотеки для предотвращения повторного подключения
  * Пример использования:
  * 
  * if ($this->isAlreadyIncluded(__FUNCTION__)) {
  *     return;//---
  * }
  * 
  * @param string $libName - название подключаемой библиотеки
  * @return boolean - признак, нужно ли подключать данную библиотеку
  */
 protected final function isAlreadyIncluded($libName)
 {
     if (in_array($libName, $this->INCLUDED)) {
         return true;
     }
     $this->INCLUDED[] = $libName;
     $this->LOGGER->info('+ {}', $libName);
     return false;
 }
 /**
  * Метод строит композицию временной шкалы.
  * Построенная композиция будет автоматически сохранена в кеш.
  * Методы были разделены осознанно, возможно нам нужно будет получить именно композицию.
  * 
  * @return TimeLineItemsComposite
  */
 public final function getTimeLineComposition(ArrayAdapter $params)
 {
     $cacheKey = $this->prepareBuildCompositionParamsAndGetCahceKey($params);
     $this->LOGGER->info('Строим хронологическую шкалу, данные: ' . $cacheKey);
     $this->profilerStart(__FUNCTION__);
     try {
         $composition = $this->buildComposition($params);
         check_condition($composition instanceof TimeLineItemsComposite, 'Некорректно построена хронологическая шкала');
         $this->profilerStop();
         $this->LOGGER->info('Шкала успешно построена');
         PSCacheGroups::TIMELINES()->saveToCache($composition->getTimeLineJson(), $cacheKey);
         $this->LOGGER->info('Шкала сохранена в кеш под ключём: ' . $cacheKey);
         return $composition;
     } catch (Exception $ex) {
         $this->profilerStop(false);
         $this->LOGGER->info('Ошибка построения шкалы: ' . $ex->getMessage());
         throw $ex;
     }
 }
 /**
  * В процессе закрытия данного класса мы напишем полный список изменённых сущностей
  */
 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 -- Нет --");
             }
         }
     }
 }
Example #19
0
 private function __construct()
 {
     $this->CLASS = get_called_class();
     $this->CACHE = new SimpleDataCache();
     $this->DBTYPE = $this->isStoreToDb() ? $this->CLASS : null;
     $this->DIR_MANAGER = DirManager::inst(array(ConfigIni::uploadsDirRel(), $this->CLASS));
     $this->LOGGER = PsLogger::inst($this->CLASS);
     $this->LOGGER->info('Instance created. Work with db ? {}. Is autonomous ? {}.', var_export($this->isStoreToDb(), true), var_export($this->isAutonomous(), true));
     $this->LOGGER->info('Upload dir: [{}].', $this->DIR_MANAGER->relDirPath());
     $this->LOGGER->info();
 }
Example #20
0
 /**
  * Редактирование сущности фолдинга
  */
 public function editEntity($ident, ArrayAdapter $params)
 {
     $this->assertAdminCanDo(__FUNCTION__, $ident);
     foreach ($this->RESOURCE_TYPES_ALLOWED as $type) {
         if ($params->has($type)) {
             $this->getResourceDi($ident, $type)->writeToFile($params->str($type), true);
         }
     }
     //Сущность могла стать видна из-за редактирования записи в базе
     $this->LOGGER->info('Очищаем кеш доступных сущностей');
     $this->IDENTS = null;
     $this->onEntityChanged($ident);
 }
Example #21
0
 /**
  * В конструкторе пробежимся по всем хранилищам и соберём все фолдинги
  */
 protected function __construct()
 {
     $this->LOGGER = PsLogger::inst(__CLASS__);
     $this->PROFILER = PsProfiler::inst(__CLASS__);
     /*
      * Инициалилизируем коллекцию
      */
     $this->PROVIDERS = array();
     /*
      * Собираем полный список доступных хранилищ и менеджеров фолдингов в них
      */
     $providerClasses = ConfigIni::getPropCheckType(ConfigIni::GROUP_FOLDINGS, 'providers', array(PsConst::PHP_TYPE_ARRAY, PsConst::PHP_TYPE_NULL));
     $providerClasses = to_array($providerClasses);
     $providerClasses[] = FoldingsProviderSdk::calledClass();
     $this->LOGGER->info('Providers: {}', array_to_string($providerClasses));
     foreach ($providerClasses as $provider) {
         if (in_array($provider, $this->PROVIDERS)) {
             $this->LOGGER->info('[-] {} - {}', $provider, 'is already registered');
             continue;
             //---
         }
         if (!class_exists($provider)) {
             $this->LOGGER->info('[-] {} - {}', $provider, 'is not included');
             continue;
             //---
         }
         if (!PsUtil::isInstanceOf($provider, FoldingsProviderAbstract::calledClass())) {
             $this->LOGGER->info('[-] {} - {}', $provider, 'is not instance of ' . FoldingsProviderAbstract::calledClass());
             continue;
             //---
         }
         $this->LOGGER->info('[+] {}', $provider);
         $this->PROVIDERS[] = $provider;
         /*
          * Для каждого хранилища загружаем список входящих в него фолдингов
          */
         $this->PROFILER->start($provider . '::list');
         /* @var $folding FoldedResources */
         foreach ($provider::listFoldings() as $folding) {
             $funique = $folding->getUnique();
             if (array_key_exists($funique, $this->UNIQUE_2_PROVIDER)) {
                 raise_error(PsStrings::replaceWithBraced('Folding {} is provided by: {}, {}', $funique, $this->UNIQUE_2_PROVIDER[$funique], $provider));
             }
             $this->LOGGER->info(' [>] {}', $funique);
             $this->UNIQUE_2_PROVIDER[$funique] = $provider;
             $this->UNIQUE_2_FOLDING[$funique] = $folding;
         }
         $this->PROFILER->stop();
     }
 }
Example #22
0
 public function CreateSprite(CssSprite $sprite)
 {
     if ($sprite->exists()) {
         return;
         //--- Спрайт существует
     }
     $this->LOGGER->info("Waiting to make {$sprite}");
     PsLock::lockMethod(__CLASS__, __FUNCTION__);
     try {
         if ($sprite->exists()) {
             $this->LOGGER->info('Sprite was created in another thread, skipping');
         } else {
             $this->PROFILER->start('Sprite creation');
             $this->CssSpriteGen->CreateSprite($sprite);
             $this->LOGGER->info('Sprite was successfully created, path: ' . $sprite->getCssDi()->getAbsPath());
             $this->PROFILER->stop();
         }
     } catch (Exception $ex) {
         PsLock::unlock();
         throw $ex;
     }
     PsLock::unlock();
 }
Example #23
0
 /**
  * Основной метод, получающий абсолютный путь к классу.
  * 
  * @param str $class
  * @return str - Путь к файлу
  */
 private function getClassPathImpl($class)
 {
     /* @var $classPathDir AutoloadDir */
     foreach ($this->DIRS as $classPathDir) {
         //ИЩЕМ КЛАСС
         $path = $classPathDir->getClassPath($class);
         if ($path) {
             /*
              * Мы нашли класс!
              * Если он отмечен, как исключённый для всех - сборосим список исключённых.
              * Могло так случиться, что класс загружался без подключённой директорией (например admin).
              */
             if ($this->isCommonExcluded($class)) {
                 $this->LOGGER->info("Class [{$class}] was marked as excluded, but now found in {$classPathDir}. Clearing excluded.");
                 $this->cleanCommonExcluded();
             }
             return $path;
         }
     }
     //ПОПРОБУЕМ ВОСПОЛЬЗОВАТЬСЯ ФОЛДИНГАМИ
     $path = Handlers::tryGetFoldedEntityClassPath($class);
     if ($path) {
         $this->LOGGER->info("Class path for [{$class}] found with folded resources.");
         return $path;
     }
     //МЫ НЕ НАШЛИ НАШ КЛАСС В ПУТЯХ, А МОЖЕТ ОН ИСКЛЮЧЁН ДЛЯ ВСЕХ?
     if ($this->isCommonExcluded($class)) {
         $this->LOGGER->info("Class [{$class}] is common excluded.");
         return null;
     }
     //КЛАСС НЕ ЯВЛЯЕТСЯ КЛАССОМ СУЩНОСТИ ФОЛДИНГА. ПЕРЕСТРОИМ КЛАССПАСЫ ДЛЯ ЗАКЕШОРОВАННЫХ ДИРЕКТОРИЙ ИЛИ ОТМЕТИМ КЛАСС, КАК ИСКЛЮЧЁННЫЙ
     /* @var $classPathDir AutoloadDir */
     foreach ($this->DIRS as $classPathDir) {
         if ($classPathDir->isRebuilded()) {
             //Данную директорию уже перезагружали, в ней класса точно нет
             continue;
         }
         //Если файл не найден, но при этом класспас не перестраивался, то необходимо поискать его заново
         $this->LOGGER->info("Class [{$class}] not excluded, need to check {$classPathDir} again.");
         $path = $classPathDir->rebuild()->getClassPath($class);
         if ($path) {
             //Ура, наши класс в одной из директорий
             $this->LOGGER->info("Class [{$class}] found for {$classPathDir} after rebuild.");
             return $path;
         }
     }
     $this->saveCommonExcluded($class);
     $this->LOGGER->info("Class [{$class}] is marked as excluded, null is returned.");
     return null;
 }
Example #24
0
 private function checkCombination(array $char2num)
 {
     $expr = PsStrings::replaceMap($this->EXPR, $char2num);
     $res = PsMathEvaluator::inst()->e($expr);
     if ($res === false) {
         $error = 'Ошибка обработки ребуса: ' . PsMathEvaluator::inst()->lastError();
         $this->LOGGER->info($error);
         raise_error($error);
     }
     if ($res == 0) {
         $combination = PsStrings::replaceMap($this->REBUS, $char2num);
         $this->COMBINATIONS[] = $combination;
         $this->LOGGER->info($combination);
     }
     ++$this->cnt;
 }
Example #25
0
 /**
  * Метод отпускает полученную ранее блокировку.
  */
 private function doUnlock()
 {
     if ($this->lockCnt > 1) {
         $this->lockCnt--;
         $this->LOGGER->info('Lock ident [{}] counter decreased to {}.', $this->lockName, $this->lockCnt);
         return;
         //---
     }
     if ($this->lockCnt == 1) {
         $this->lockCnt--;
         flock($this->lockFile, LOCK_UN);
         fclose($this->lockFile);
         $this->LOGGER->info("Lock [{$this->lockName}] released!\n");
         $this->lockFile = null;
         $this->lockName = null;
     }
 }
Example #26
0
 /**
  * Копирует ячейки из картинки-источника в картинку-мозайку.
  * 
  * @param array $INFO - информация о картинке
  * @param array $cells - ячейки из БД, которые будут скопированы
  * @param type $userId - код пользователя, к которому ячейки будут привязаны
  */
 private function copyCells(array $cells, $userId = null)
 {
     //Проверим, есть ли сейчас "чистая" картинка, на которую мы будем копировать ячейки
     if (!$this->diDst()->isImg()) {
         SimpleImage::inst()->create($this->width, $this->height, self::BG_COLOR)->save($this->diDst())->close();
     }
     if (empty($cells)) {
         return;
         //---
     }
     if ($this->LOGGER->isEnabled()) {
         $this->LOGGER->info('Copy cells of image ' . $this->id . ', user for bind: ' . var_export($userId, true));
         $this->LOGGER->info('Not processed cells: ' . print_r($cells, true));
     }
     PsUtil::startUnlimitedMode();
     $this->PROFILER->start('Copy cells of img ' . $this->id);
     //1. Разберёмся с ячейками - привяжем к пользователю те их них, которые никому не принадлежат
     foreach ($cells as $cell) {
         $n_part = 1 * $cell['n_part'];
         $owned = !!$cell['owned'];
         //Ячейка должна кому-то принадлежать, либо быть привязана к переданному пользователю
         check_condition($owned || is_numeric($userId), "Ячейка {$this->id}.{$n_part} никому не принадлежит.");
         if (!$owned) {
             //Если ячейка уже привязана к пользователю, то не будем лишний раз дёргать базу
             $this->LOGGER->info('{}. Cell binded to user {}', $n_part, $userId);
             $this->BEAN->markAsOwned($userId, $this->id, $n_part);
         }
     }
     //2. Копируем ячейки, предварительно объединив их
     $srcImg = SimpleImage::inst()->load($this->diSrc());
     $dstImg = SimpleImage::inst()->load($this->diDst());
     $unioned = MosaicImageCellsCompositor::union($cells, $this->cellWidth, $this->cellHeight, false);
     foreach ($unioned as $cell) {
         $x1 = $cell[0];
         $y1 = $cell[1];
         $x2 = $cell[2];
         $y2 = $cell[3];
         $w = $x2 - $x1;
         $h = $y2 - $y1;
         $dstImg->copyFromAnother($srcImg, $x1, $y1, $x1, $y1, $w, $h)->save();
         $this->LOGGER->info('Copied rectangle: {}x{}-{}x{}', $x1, $y1, $x2, $y2);
     }
     $srcImg->close();
     $dstImg->close();
     $this->PROFILER->stop();
 }
Example #27
0
 /**
  * Непосредственное наполнение
  */
 private function doFill($filterName = null)
 {
     $this->LOGGER->info("Loading full content of dir [{}] with [{}] filter.", $this->PATH, PsUtil::toString($filterName));
     $this->PROFILER->start('doFill');
     /*
      * На данный момент у нас все директории собраны, остаётся только пробежаться по ним
      * и взять всё необходимое.
      * При этом нужно выполнить array_values, так как getDirContent возвращает ассоциативный массив,
      * а файлы в директориях могут повторяться.
      */
     $RESULT = array();
     foreach ($this->DIRS as $dirPath) {
         $items = DirManager::inst($dirPath)->getDirContent(null, $filterName);
         $RESULT = array_merge($RESULT, array_values($items));
     }
     $this->LOGGER->info('Loading finished, items count: {}. Taken time: {}sec.', count($RESULT), $this->PROFILER->stop()->getTime());
     $this->LOGGER->info('');
     return $RESULT;
 }
Example #28
0
 /**
  * Перестроение спрайта
  * 
  * @return CssSprite
  */
 public function rebuild($force = true)
 {
     if (!$this->rebuilded && ($force || !$this->exists())) {
         //Отлогируем
         $this->LOGGER->info("REBUILDING SPRITE FOR [{$this->name}]");
         //Поставим признак перестроенносьти
         $this->rebuilded = true;
         //Сбросим закешированные элементы, так как css файл мог поменяться
         $this->items = null;
         //Удалим .css файл
         $this->cssDi->remove();
         //Перестроим
         CssSpritesCreator::inst()->CreateSprite($this);
         //Создадим .css файл, даже если он не был создан в процессе построения. Просто у нас нет картинок в $spritable.
         $this->cssDi->touch();
     }
     return $this;
     //---
 }
 /**
  * Метод получения коннекта к БД
  * 
  * @return ADOConnection
  */
 protected final function getConnection()
 {
     if ($this->CONNECTION != null) {
         return $this->CONNECTION;
         //---
     }
     if (!$this->isConfigured()) {
         PsUtil::raise('Cannot get DB connection, {} is not configured.', get_called_class());
     }
     $this->LOGGER->info();
     $this->LOGGER->info('?  Connection for [{}] is requested', $this->CONNECTION_PARAMS);
     $URL = $this->CONNECTION_PARAMS->url();
     //Посмотрим, есть ли у нас нужный коннект
     if (array_key_exists($URL, $this->CONNECTIONS)) {
         $this->LOGGER->info('<  Fast returned from cache');
         return $this->CONNECTION = $this->CONNECTIONS[$URL];
     }
     //Отлогируем
     $this->LOGGER->info('+  Establishing connection {}', $this->CONNECTION_PARAMS);
     //Подключаем adodb
     PsLibs::inst()->AdoDb();
     //Подключаемся
     $this->CONNECTION = ADONewConnection($URL);
     if (!is_object($this->CONNECTION)) {
         PsUtil::raise("Unable to connect to [{}]", $this->CONNECTION_PARAMS);
     }
     //Зададим некоторые настройки
     $this->CONNECTION->debug = ADODB_DEBUG;
     $this->CONNECTION->SetFetchMode(ADODB_FETCH_ASSOC);
     $this->CONNECTION->query("SET NAMES 'utf8'");
     $this->CONNECTION->query("SET CHARACTER SET 'utf8'");
     //Положим соединение в пул
     if (array_key_exists($URL, $this->CONNECTIONS)) {
         raise_error('Double trying to register db connection');
     }
     $this->LOGGER->info('<  Established connection returned');
     return $this->CONNECTIONS[$URL] = $this->CONNECTION;
 }
Example #30
0
 /**
  * Конструктор класса для работы с кешем.
  * Кеширование идёт в два этапа:
  * 1. Кеширование на уровне класса для максимально быстрого доступа
  * 2. Кеширование в долгосрочном хранилище, которое реализуется отдельным классом - "движком" кеширования
  * 
  * Движок кеширования должен быть задан на уровне config.ini
  * 
  * @return PSCache
  */
 protected function __construct()
 {
     $this->LOGGER = PsLogger::inst(__CLASS__);
     /*
      * Получим название класса "движка" кеширования
      */
     $class = ConfigIni::cacheEngine();
     /*
      * Проверим наличие класса
      */
     $classPath = Autoload::inst()->getClassPath($class);
     if (!PsCheck::isNotEmptyString($classPath)) {
         return PsUtil::raise('Не удалось найти класс для кеширования [{}]', $class);
     }
     /*
      * Правильный ли класс указан?
      */
     if (!PsUtil::isInstanceOf($class, 'PSCacheEngine')) {
         return PsUtil::raise('Указанный класс кеширования [{}] не является наследником класса [{}]', $class, 'PSCacheEngine');
     }
     $this->LOGGER->info('Используем движок кеширования: {}', $class);
     $this->CACHE_ENGINE = new $class();
 }