Beispiel #1
0
 protected function doBuild(\PageContext $ctxt, \PageBuilderContext $builderCtxt, \RequestArrayAdapter $requestParams, \ArrayAdapter $buildParams)
 {
     //1. ЗАГОЛОВОК
     $builderCtxt->setTitle($this->authed ? 'Админка | ' . $this->adminPage->title() : 'xxx');
     //2. JAVASCRIPT
     $builderCtxt->setJsParams($this->authed ? $this->adminPage->getJsParams() : null);
     //3. SMARTY RESOURCES
     if ($this->authed) {
         $builderCtxt->setSmartyParams4Resources($this->adminPage->getSmartyParams4Resources());
         $builderCtxt->setSmartyParam4Resources('IDENT', $this->adminPage->getPageIdent());
         $builderCtxt->setSmartyParam4Resources('TIMELINE_ENABE', true);
     }
     $smartyParams['authed'] = $this->authed;
     if (!$this->authed) {
         return $smartyParams;
     }
     //Запустим неограниченный по времени режим - мало ли, что мы там будем делать:)
     PsUtil::startUnlimitedMode();
     //Получаем содержимое админской страницы
     $content = ContentHelper::getContent($this->adminPage);
     //Добавляем к ней ресурсы
     $content = APagesResources::inst()->getResourcesLinks($this->adminPage->getPageIdent(), $content);
     $smartyParams['page'] = $this->adminPage;
     $smartyParams['content'] = $content;
     $smartyParams['pagesLayout'] = AdminPagesManager::getInstance()->getLayout();
     return $smartyParams;
 }
Beispiel #2
0
 /**
  * Вызов выполнения метода. Используется из ajax.
  */
 public static function execute($method, array $params)
 {
     check_condition(array_key_exists($method, self::getMethodsList()), "Method TestManager::{$method} cannot be called");
     PsUtil::startUnlimitedMode();
     PsLogger::inst('TestManager')->info("Method TestManager::{$method} called with params: " . array_to_string($params));
     $s = Secundomer::startedInst();
     call_user_func_array(array(TestManager::inst(), $method), $params);
     $s->stop();
     PsLogger::inst('TestManager')->info("Call done in {$s->getTotalTime()} seconds");
 }
Beispiel #3
0
 public function buildContent()
 {
     PsUtil::startUnlimitedMode();
     $s = Secundomer::inst();
     $data = array();
     for ($num = 0; $num <= self::REQUESTS_COUNT; $num++) {
         $s->start();
         file_get_contents($this->url);
         $s->stop();
         $data[$num]['time'] = $s->getTime();
         $data[$num]['total'] = $s->getTotalTime();
         if ($num == 0) {
             //Запросим один раз, чтобы сработало кеширование, если оно включено
             $s->clear();
         }
     }
     $params = array('url' => $this->url, 'data' => $data, 'average' => $s->getAverage());
     echo $this->getFoldedEntity()->fetchTpl($params);
 }
Beispiel #4
0
 private function executeImpl($lifeTimeOnCall, $__FUNCTION__)
 {
     if ($this->called) {
         return $this->executed;
         //---
     }
     $this->called = true;
     $LOGGER = PsLogger::inst(__CLASS__);
     $LOGGER->info("Function [{$__FUNCTION__}] called.");
     $needProcess = false;
     $LOCKFILE = DirManager::autogen('service')->getDirItem(null, __CLASS__, 'lock');
     if ($LOCKFILE->isFile()) {
         $lifeTime = $LOCKFILE->getFileLifetime();
         $needProcess = !$lifeTime || !$lifeTimeOnCall || $lifeTime >= $lifeTimeOnCall;
         $LOGGER->info('{} process. Lock file modified {} seconds ago. Process delay: {} seconds.', $needProcess ? 'Need' : 'Not need', $lifeTime, $lifeTimeOnCall);
     } else {
         $needProcess = true;
         $LOGGER->info('Need process. Lock file is not exists.');
     }
     if (!$needProcess) {
         return $this->executed;
         //---
     }
     $locked = PsLock::lock(__CLASS__, false);
     $LOGGER->info('External process lock {} execution.', $locked ? 'acquired, start' : 'not acquired, skip');
     if ($locked) {
         $LOCKFILE->touch();
         PsUtil::startUnlimitedMode();
         //Отпустим лок, так как внутри он может потребоваться для выполнения других действий, например для перестройки спрайтов
         PsLock::unlock();
         //Начинаем выполнение
         $this->executed = true;
         $job = new ExternalProcessJob();
         PsProfiler::inst(__CLASS__)->start(__FUNCTION__);
         $job->execute();
         $secundomer = PsProfiler::inst(__CLASS__)->stop();
         if ($secundomer) {
             $LOGGER->info("{$secundomer}");
         }
     }
     return $this->executed;
 }
Beispiel #5
0
 protected function doProcess(PageContext $ctxt, RequestArrayAdapter $requestParams, ArrayAdapter $buildParams)
 {
     PsDefines::assertProductionOff(__CLASS__);
     PsUtil::startUnlimitedMode();
 }
Beispiel #6
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();
 }
Beispiel #7
0
 /**
  * Метод вызывается для выполнения периодических задач cron
  * 
  * @return type
  */
 public function execute()
 {
     if ($this->called) {
         return $this->executed;
         //---
     }
     $this->called = true;
     $LOGGER = PsLogger::inst(__CLASS__);
     $LOGGER->info('Executing {}', __CLASS__);
     /*
      * Получим список классов, которые нужно выполнить
      */
     $processes = ConfigIni::cronProcesses();
     if (empty($processes)) {
         $LOGGER->info('No cron processes configured, fast return...');
         return $this->executed;
         //---
     }
     $processes = array_unique($processes);
     $LOGGER->info('Configured processes: {}', array_to_string($processes));
     foreach ($processes as $class) {
         if (!PsUtil::isInstanceOf($class, 'PsCronProcess')) {
             PsUtil::raise("Class {$class} cannot be executed as cron process, it should be instance of PsCronProcess");
         }
     }
     $locked = PsLock::lock(__CLASS__, false);
     $LOGGER->info('Lock accured ? {}', var_export($locked, true));
     if (!$locked) {
         return $this->executed;
         //---
     }
     $LOCKFILE = DirManager::autoNoDel(DirManager::DIR_SERVICE)->getDirItem(null, __CLASS__, PsConst::EXT_LOCK);
     $LOCKFILE_LIFETIME = $LOCKFILE->getFileLifetime();
     $MAX_LIFETIME = 5 * 60;
     $NED_PROCESS = $LOCKFILE_LIFETIME === null || $LOCKFILE_LIFETIME > $MAX_LIFETIME;
     $LOGGER->info("Lock file {}: {}", $LOCKFILE_LIFETIME === null ? 'NOT EXISTS' : 'EXISTS', $LOCKFILE->getRelPath());
     if ($LOCKFILE_LIFETIME !== null) {
         $LOGGER->info('Last modified: {} seconds ago. Max process delay: {} seconds.', $LOCKFILE_LIFETIME, $MAX_LIFETIME);
         //
     }
     if (!$NED_PROCESS) {
         $LOGGER->info('Skip execution.');
         //Отпустим лок
         PsLock::unlock();
         //Выходим
         return $this->executed;
         //---
     }
     //Обновим время последнего выполнения
     $LOCKFILE->touch();
     //Отпустим лок, так как внутри он может потребоваться для выполнения других действий, например для перестройки спрайтов
     PsLock::unlock();
     $LOGGER->info();
     $LOGGER->info('External process execution started...');
     //Запускаем режим неограниченного выполнения
     PsUtil::startUnlimitedMode();
     //Начинаем выполнение
     $this->executed = true;
     //Создаём профайлер
     $PROFILER = PsProfiler::inst(__CLASS__);
     //Создадим конфиг выполнения процесса
     $config = new PsCronProcessConfig();
     //Пробегаемся по процессам и выполняем. При первой ошибке - выходим.
     foreach ($processes as $class) {
         $LOGGER->info('Executing cron process {}', $class);
         $PROFILER->start($class);
         try {
             $inst = new $class();
             $inst->onCron($config);
             $secundomer = $PROFILER->stop();
             $LOGGER->info(" > Cron process '{}' executed in {} seconds", $class, $secundomer->getTotalTime());
         } catch (Exception $ex) {
             $PROFILER->stop();
             $LOGGER->info(" > Cron process '{}' execution error: '{}'", $class, $ex->getMessage());
         }
     }
     $LOGGER->info('Removing cron lock file.');
     $LOCKFILE->remove();
     return $this->executed;
 }
Beispiel #8
0
 /**
  * Метод выполняет дамп таблицы
  */
 public static function dumpTable($idColumn, $table, array $where = array(), $order = null)
 {
     //Стартуем секундомер
     $secundomer = Secundomer::startedInst("Снятие дампа {$table}");
     //Отключим ограничение по времени
     PsUtil::startUnlimitedMode();
     //Получим экземпляр логгера
     $LOGGER = PsLogger::inst(__CLASS__);
     //Текущий пользователь
     $userId = AuthManager::getUserIdOrNull();
     //Для логов, запросов и все остального
     $table = strtoupper(PsCheck::tableName($table));
     //Макс кол-во записей
     $limit = PsDefines::getTableDumpPortion();
     //Проверим наличие id
     $idColumn = PsCheck::tableColName($idColumn);
     $LOGGER->info('Dumping table {}. Id column: {}, limit: {}. User id: {}.', $table, $idColumn, $limit, $userId);
     //Получаем лок (без ожидания)
     $lockName = "DUMP table {$table}";
     $locked = PsLock::lock($lockName, false);
     $LOGGER->info('Lock name: {}, locked ? {}.', $lockName, var_export($locked, true));
     if (!$locked) {
         return false;
         //Не удалось получить лок
     }
     $zipDi = false;
     try {
         //ЗПРОСЫ:
         //1. Запрос на извлечение колва записей, подлежащих дампированию
         $queryCnt = Query::select("count({$idColumn}) as cnt", $table, $where);
         //2. Запрос на извлечение данных, подлежащих дампированию
         $queryDump = Query::select('*', $table, $where, null, $order, $limit);
         //3. Запрос на извлечение кодов дампируемых записей
         $selectIds = Query::select($idColumn, $table, $where, null, $order, $limit);
         //4. Запрос на удаление дампированных данных
         $queryDel = Query::delete($table, Query::plainParam("{$idColumn} in (select {$idColumn} from (" . $selectIds->build($delParams) . ') t )', $delParams));
         //Выполним запрос для получения кол-ва записей, подлежащих дампу
         $cnt = PsCheck::int(array_get_value('cnt', PSDB::getRec($queryCnt, null, true)));
         $LOGGER->info('Dump recs count allowed: {}.', $cnt);
         if ($cnt < $limit) {
             $LOGGER->info('SKIP dumping table, count allowed ({}) < limit ({})...', $cnt, $limit);
             $LOGGER->info("Query for extract dump records count: {$queryCnt}");
             PsLock::unlock($lockName);
             return false;
         }
         //Время дампа
         $date = PsUtil::fileUniqueTime(false);
         $time = time();
         //Название файлов
         $zipName = $date . ' ' . $table;
         //Элемент, указывающий на zip архив
         $zipDi = DirManager::stuff(null, array(self::DUMPS_TABLE, $table))->getDirItem(null, $zipName, PsConst::EXT_ZIP);
         $LOGGER->info('Dump to: [{}].', $zipDi->getAbsPath());
         if ($zipDi->isFile()) {
             $LOGGER->info('Dump file exists, skip dumping table...');
             PsLock::unlock($lockName);
             return false;
         }
         //Комментарий к таблице
         $commentToken[] = "Date: {$date}";
         $commentToken[] = "Time: {$time}";
         $commentToken[] = "Table: {$table}";
         $commentToken[] = "Manager: {$userId}";
         $commentToken[] = "Recs dumped: {$limit}";
         $commentToken[] = "Total allowed: {$cnt}";
         $commentToken[] = "Query dump cnt:   {$queryCnt}";
         $commentToken[] = "Query dump data:  {$queryDump}";
         $commentToken[] = "Query dump ids:   {$selectIds}";
         $commentToken[] = "Query del dumped: {$queryDel}";
         $comment = implode("\n", $commentToken);
         //Начинаем zip и сохраняем в него данные
         $zip = $zipDi->startZip();
         $zip->addFromString($zipName, serialize(PSDB::getArray($queryDump)));
         $zip->setArchiveComment($comment);
         $zip->close();
         $LOGGER->info('Data successfully dumped, zip comment:');
         $LOGGER->info("[\n{$comment}\n]");
         //Удалим те записи, дамп которых был снят
         $LOGGER->info('Clearing dumped table records...');
         $affected = PSDB::update($queryDel);
         $LOGGER->info('Rows deleted: {}.', $affected);
         $LOGGER->info('Dumping is SUCCESSFULLY finished. Total time: {} sec.', $secundomer->stop()->getAverage());
     } catch (Exception $ex) {
         PsLock::unlock($lockName);
         ExceptionHandler::dumpError($ex);
         $LOGGER->info('Error occured: {}', $ex->getMessage());
         throw $ex;
     }
     return $zipDi;
 }