Example #1
0
 protected function processImpl(PostArrayAdapter $adapter, $button)
 {
     if (!$adapter->hasAllNoEmpty('folding', self::PARAM_NEW_FOLDING_IDENT)) {
         return 'Не переданы все необходимые параметры.';
     }
     $funique = $adapter->str('folding');
     $fident = check_condition($adapter->str(self::PARAM_NEW_FOLDING_IDENT), 'Пустой идентификатор фолдинга');
     $folding = Handlers::getInstance()->getFoldingByUnique($funique);
     $folding->assertNotExistsEntity($fident);
     switch ($button) {
         case self::BUTTON_SAVE_DB:
             $action = PS_ACTION_CREATE;
             $table = TableExporter::inst()->getTable($folding);
             //Проставим руками идентификатор фолдинга для колонки из базы
             $adapter->set($folding->getTableColumnIdent(), $fident);
             $rec = $table->fetchRowFromForm($adapter->getData(), $action);
             if (!is_array($rec)) {
                 //Данные для создания записи в БД не прошли валидацию
                 return $rec;
             }
             $table->saveRec($rec, $action);
             //createFoldingDbRec($folding, $ident);
         //createFoldingDbRec($folding, $ident);
         case self::BUTTON_SAVE:
             $folding->createEntity($fident);
             break;
     }
     return new AjaxSuccess(array('url' => AP_APFoldingEdit::urlFoldingEdit($folding->getFoldedEntity($fident))));
 }
Example #2
0
 /**
  * Метод получает фактический контект для всплывающей страницы.
  * Сама страница может вернуть или IdentPageFilling, и тогда содержимое 
  * будет обработано за неё. Или непосредственно IdentPageContent,
  * если ей самой нужно обработать содержимое (например - акции).
  * 
  * @return ClientBoxContent
  */
 public final function getContent()
 {
     if ($this->cbContent) {
         return $this->cbContent;
     }
     $this->checkAccess();
     $this->profilerStart(__FUNCTION__);
     $filling = null;
     try {
         $filling = $this->getClientBoxFilling();
         check_condition($filling instanceof ClientBoxFilling, "Элемент [{$this->ident}] обработан некорректно");
     } catch (Exception $ex) {
         $this->profilerStop(false);
         return $this->cbContent = new ClientBoxContent(PsHtml::divErr(ExceptionHandler::getHtml($ex)));
     }
     //Построим заголовок
     $HEAD_PARAMS['class'][] = 'box-header';
     if ($filling->isCover()) {
         $HEAD_PARAMS['class'][] = 'covered';
         $HEAD_PARAMS['style']['background-image'] = 'url(' . $this->foldedEntity->getCover()->getRelPath() . ')';
     }
     $HEAD_CONTENT = $filling->getHref() ? PsHtml::a(array('href' => $filling->getHref()), $filling->getTitle()) : $filling->getTitle();
     $HEAD = PsHtml::html2('h3', $HEAD_PARAMS, $HEAD_CONTENT);
     $BOX_CONTENT = $this->foldedEntity->fetchTplWithResources($filling->getSmartyParams());
     $BOX = PsHtml::div(array(), $HEAD . $BOX_CONTENT);
     $this->profilerStop();
     return $this->cbContent = new ClientBoxContent($BOX, $filling->getJsParams());
 }
Example #3
0
 /**
  * Метод заменяет подстроку $delimiter в строке $text на элементы из массива 
  * подстановок $params.
  * 
  * @param string $delimiter - элемент для поиска
  * @param string $text - текст, в котором производится поиск
  * @param array $params - элементы для замены
  * @param bool $checkCount - признак, проверять ли совпадение кол-ва разделителей в строке и элементов для замены
  * @return string
  */
 public static function replaceWithParams($delimiter, $text, array $params, $checkCount = false)
 {
     $paramsCount = count($params);
     if (!$paramsCount && !$checkCount) {
         //Выходим, если параметры не переданы и нам не нужно проверять совпадение кол-ва параметров с кол-вом разделителей
         return $text;
     }
     //Разделим текст на кол-во элеметнов, плюс один
     $tokens = explode($delimiter, $text, $paramsCount + 2);
     $tokensCount = count($tokens);
     if ($checkCount) {
         check_condition($paramsCount == $tokensCount - 1, "Не совпадает кол-во элементов для замены. Разделитель: `{$delimiter}`. Строка: `{$text}`. Передано подстановок: {$paramsCount}.");
     }
     if ($tokensCount == 0 || $tokensCount == 1) {
         //Была передана пустая строка? Вернём её.
         return $text;
     }
     $idx = 0;
     $result[] = $tokens[$idx];
     foreach ($params as $param) {
         if (++$idx >= $tokensCount) {
             break;
         }
         $result[] = $param;
         $result[] = $tokens[$idx];
     }
     while (++$idx < $tokensCount) {
         $result[] = $delimiter;
         $result[] = $tokens[$idx];
     }
     return implode('', $result);
 }
Example #4
0
 private static function assertPrepeared($tableExists = null)
 {
     PsConnectionPool::assertConnectiedTo(PsConnectionParams::sdkTest());
     foreach (to_array($tableExists) as $table) {
         check_condition(PsTable::exists($table), "Таблица {$table} не существует");
     }
 }
Example #5
0
 private function getHtmlImpl(array $el)
 {
     $data['num'] = $el[0];
     $data['sym'] = $el[1];
     $data['name'] = $el[2];
     $data['mass'] = $el[3];
     //Подсчитаем уровни
     $s1 = 0;
     $s2 = 0;
     $p = 0;
     for ($index = 1; $index <= $data['num']; $index++) {
         if ($s1 < 2) {
             ++$s1;
         } else {
             if ($s2 < 2) {
                 ++$s2;
             } else {
                 ++$p;
             }
         }
     }
     check_condition($s1 >= 1 && $p <= 8, "For atom energy levels s1={$s1} and p={$p}");
     if ($p > 0) {
         $levels[] = "2p<sup>{$p}</sup>";
     }
     if ($s2 > 0) {
         $levels[] = "2s<sup>{$s2}</sup>";
     }
     $levels[] = "1s<sup>{$s1}</sup>";
     $data['levels'] = $levels;
     return PSSmarty::template('common/mend_elem.tpl', $data)->fetch();
 }
Example #6
0
 /**
  * Метод безопасно получает контент.
  * В случае возникновения ошибки возвращает её стек.
  */
 public static function getContent($objOrTpl, $method = 'buildContent')
 {
     $isCallable = is_callable($objOrTpl);
     $isTpl = $objOrTpl instanceof Smarty_Internal_Template;
     if (!$isCallable && !$isTpl) {
         check_condition(is_object($objOrTpl), 'Not object passed to ' . __FUNCTION__);
         PsUtil::assertMethodExists($objOrTpl, $method);
     }
     $returned = null;
     $flushed = null;
     ob_start();
     ob_implicit_flush(false);
     try {
         if ($isCallable) {
             $returned = call_user_func($objOrTpl);
         } else {
             if ($isTpl) {
                 $returned = $objOrTpl->fetch();
             } else {
                 $returned = $objOrTpl->{$method}();
             }
         }
     } catch (Exception $ex) {
         ob_end_clean();
         return ExceptionHandler::getHtml($ex);
     }
     $flushed = ob_get_contents();
     ob_end_clean();
     return isEmpty($returned) ? isEmpty($flushed) ? null : $flushed : $returned;
 }
Example #7
0
 public function dropTestingResults($idTestingRes, $userId)
 {
     $res = $this->getRec('select id_testing_result FROM ps_testing_results where id_user=? and id_testing_result=?', array($userId, $idTestingRes));
     check_condition($res != null, "Testing result with id {$idTestingRes} is not belongs to user with id {$userId}");
     $this->deleteTestingResultContent($idTestingRes);
     $this->update('delete from ps_testing_results where id_testing_result=?', $idTestingRes);
 }
 /** @return FoldedEntity */
 public function getFoldedEntityEnsureType($foldingType)
 {
     $entity = $this->getFoldedEntity();
     check_condition($entity, "Не установлен контекст для определения фолдинга с типом [{$foldingType}].");
     check_condition($entity->getFolding()->isItByType($foldingType), "Установленный контекст {$this->getContext()} не соответствует фолдингу с типом [{$foldingType}].");
     return $entity;
 }
Example #9
0
 public function doProcess(ArrayAdapter $params)
 {
     $postId = $params->int('postId');
     $postType = $params->str('postType');
     $this->postCP = Handlers::getInstance()->getPostsProcessorByPostType($postType)->getPostContentProvider($postId);
     check_condition(!!$this->postCP, "Not found post with id='{$postId}' for post type='{$postType}'");
 }
Example #10
0
 /**
  * Метод возвращает все фолдинги из всех доступных хранилищ, относящихся к заданному контексту
  */
 public function getFoldings($scope = ENTITY_SCOPE_ALL)
 {
     switch ($scope) {
         case ENTITY_SCOPE_ALL:
             return $this->UNIQUE_2_FOLDING;
         case ENTITY_SCOPE_SDK:
         case ENTITY_SCOPE_PROJ:
             if (array_key_exists($scope, $this->PROVIDER_2_UNIQUE_2_FOLDING)) {
                 return $this->PROVIDER_2_UNIQUE_2_FOLDING[$scope];
             }
             $this->PROFILER->start('Foldings[' . $scope . ']');
             $this->PROVIDER_2_UNIQUE_2_FOLDING[$scope] = array();
             $this->LOGGER->info();
             $this->LOGGER->info('Foldings for scope [{}]:', $scope);
             foreach ($this->UNIQUE_2_PROVIDER as $funique => $provider) {
                 if ($provider::isInScope($scope)) {
                     $this->PROVIDER_2_UNIQUE_2_FOLDING[$scope][$funique] = check_condition($this->UNIQUE_2_FOLDING[$funique], "Unknown folding [{$funique}]");
                     $this->LOGGER->info('[>] {} ({})', $funique, $provider);
                 }
             }
             $this->PROFILER->stop();
             return $this->PROVIDER_2_UNIQUE_2_FOLDING[$scope];
     }
     raise_error("Invalid entity scope [{$scope}]");
 }
Example #11
0
 protected function onInit(DirItem $di)
 {
     $this->info = getimagesize($di->getAbsPath());
     check_condition($this->info, "В ImageAdapter передана невалидная картинка [{$di->getRelPath()}].");
     $this->width = $this->info[0];
     $this->height = $this->info[1];
 }
Example #12
0
 /**
  * Функция возвращает код журнала по его id
  */
 public static function ident2id($ident)
 {
     check_condition(starts_with($ident, self::IDENT_PREFIX), "Bad issue ident: [{$ident}]");
     $postId = cut_string_start($ident, self::IDENT_PREFIX);
     check_condition(is_numeric($postId), "Bad issue ident: [{$ident}]");
     return 1 * $postId;
 }
Example #13
0
 /** @return DirItem */
 private function getAvatarImg()
 {
     if (!isset($this->avatars)) {
         $this->avatars = array_values(DirManager::images('avatars')->getDirContent(null, DirItemFilter::IMAGES));
         check_condition($this->avatars, 'No avatar images');
     }
     return $this->avatars[rand(0, count($this->avatars) - 1)];
 }
Example #14
0
 /**
  * Создание новой галереи. Будет создана директория и запись в базе.
  */
 public static function makeNew($gallery, $name)
 {
     AuthManager::checkAdminAccess();
     check_condition($gallery, 'Не передано название галереи');
     check_condition(!array_key_exists($gallery, self::allInsts()), "Галерея [{$gallery}] уже существует");
     DirManager::gallery()->makePath($gallery);
     self::inst($gallery)->saveGallery($name, array());
 }
Example #15
0
 public function __construct(Smarty $smarty)
 {
     foreach ($this->methodsMap as $filterType => $method) {
         check_condition(method_exists($this, $method), "Method [{$method}] not exists in class " . __CLASS__);
         $this->CALLS[$method] = 0;
         $smarty->registerFilter($filterType, array($this, "_{$method}"));
     }
 }
Example #16
0
 /**
  * Остановка профилирования
  * 
  * @return Secundomer последний запушеный секундомер
  */
 public function stop($save = true)
 {
     check_condition($this->num > 0, 'Не установлен текущий идентификатор профилирования для ' . $this->profilerId);
     $secundomer = $this->secundomers[$this->idents[$this->num]]->stop($save);
     unset($this->idents[$this->num]);
     --$this->num;
     return $secundomer;
 }
Example #17
0
 /**
  * Метод получения экземпляра маппинга
  * @return MappingClient
  */
 public static final function inst(MappingSource $lsrc, MappingSource $rsrc, $descr)
 {
     $hash = md5($lsrc->getHash() . '|' . $rsrc->getHash());
     if (!array_key_exists($hash, self::$insts)) {
         check_condition($lsrc->getMident() == $rsrc->getMident(), "Источники не совместимы: {$lsrc} <> {$rsrc}");
         self::$insts[$hash] = new Mapping($lsrc, $rsrc, $hash, $descr);
     }
     return self::$insts[$hash];
 }
Example #18
0
 /**
  * Идентификатор акции - хэш от типа акции и её параметров.
  * Две акции с одним типом но разными кодами считаются разными.
  * 
  * @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);
 }
Example #19
0
 /**
  * Основной метод, возвращающий экземпляры оболочек над группами кешей
  * @return PSCacheInst
  */
 public static function inst($group, $sign = null)
 {
     $key = "G:{$group};S:{$sign}";
     if (!array_key_exists($key, self::$insts)) {
         check_condition(in_array($group, PSCache::getCacheGroups()), "Неизвестная группа кеширования [{$group}].");
         self::$insts[$key] = new PSCacheInst($group, $sign);
     }
     return self::$insts[$key];
 }
Example #20
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}] не существует.");
 }
Example #21
0
 public final function __construct(FoldedEntity $foldedEntity)
 {
     $this->ident = $foldedEntity->getIdent();
     $this->folding = $foldedEntity->getFolding();
     $this->foldedEntity = $foldedEntity;
     check_condition($this->ident === self::getIdent(), "Несовпадение идентификаторов в экземпляре класса для сущности {$foldedEntity}");
     //Позволим предкам проинициализироваться
     $this->_construct();
 }
Example #22
0
/**
 * Процесс строит скрипты для вставки ячеек в БД
 * 
 * @param array $argv
 */
function executeProcess(array $argv)
{
    $DM = DirManager::inst(array(__DIR__, 'output'));
    $customNum = $argv[1];
    dolog('Processing mosaic demo, custom num={}', $customNum);
    /* @var $dir DirItem */
    foreach ($DM->getDirContent(null, DirItemFilter::DIRS) as $dir) {
        if (is_inumeric($customNum) && $customNum != $dir->getName()) {
            continue;
            //----
        }
        $imgDM = DirManager::inst($dir->getAbsPath());
        $imgDI = end($imgDM->getDirContent(null, DirItemFilter::IMAGES));
        $map = $imgDM->getDirItem(null, 'map', 'txt')->getFileAsProps();
        $demoDM = DirManager::inst($imgDM->absDirPath(), 'demo');
        $demoDM->clearDir();
        dolog("Building map for: [{}].", $imgDI->getRelPath());
        //CELLS BINDING
        $dim = $imgDM->getDirItem(null, 'settings', 'txt')->getFileAsProps();
        $dim = $dim['dim'];
        $dim = explode('x', $dim);
        $cw = 1 * $dim[0];
        $ch = 1 * $dim[1];
        $sourceImg = SimpleImage::inst()->load($imgDI);
        $w = $sourceImg->getWidth();
        $h = $sourceImg->getHeight();
        $destImg = SimpleImage::inst()->create($w, $h, MosaicImage::BG_COLOR);
        dolog("Img size: [{$w} x {$h}].");
        check_condition($w > 0 && !($w % $cw), 'Bad width');
        check_condition($h > 0 && !($h % $ch), 'Bad height');
        $totalCells = count($map);
        $lengtn = strlen("{$totalCells}");
        //dolog("Cells cnt: [$xcells x $ycells], total: $totalCells.");
        //СТРОИМ КАРТИНКИ
        $secundomer = Secundomer::startedInst();
        //$encoder = new PsGifEncoder();
        for ($cellCnt = 0; $cellCnt <= $totalCells; $cellCnt++) {
            $name = pad_zero_left($cellCnt, $lengtn);
            $copyTo = $demoDM->absFilePath(null, $name, 'jpg');
            if ($cellCnt > 0) {
                $cellParams = $map[$cellCnt];
                $cellParams = explode('x', $cellParams);
                $xCell = $cellParams[0];
                $yCell = $cellParams[1];
                $x = ($xCell - 1) * $cw;
                $y = ($yCell - 1) * $ch;
                $destImg->copyFromAnother($sourceImg, $x, $y, $x, $y, $cw, $ch);
            }
            $destImg->save($copyTo);
            dolog("[{$totalCells}] {$copyTo}");
        }
        //$encoder->saveToFile($demoDM->absFilePath(null, 'animation'));
        $secundomer->stop();
        dolog('Execution time: ' . $secundomer->getTotalTime());
    }
}
Example #23
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");
 }
Example #24
0
 public static function normalizeResourceFile($type, $content)
 {
     switch ($type) {
         case 'css':
             return self::normalizeCssFile($content);
         case 'js':
             return self::normalizeJsFile($content);
     }
     check_condition(false, "Unknown resource type [{$type}] given for normalization.");
 }
Example #25
0
 private function __construct(DirItem $di, $min, $max, $step)
 {
     $this->di = $di;
     $this->min = PsCheck::int($min);
     $this->max = PsCheck::int($max);
     $this->step = PsCheck::int($step);
     //Проверки
     check_condition($this->max > $this->min, "Некорректные границы [{$this->min}, {$this->max}] для {$this}");
     check_condition($this->step > 0, "Некорректный шаг [{$this->step}] для {$this}");
 }
Example #26
0
 /**
  * Выдача очков пользователю. Если очки будут успешно выданы, вернётся созданная в базе запись,
  * иначе - null
  * 
  * @return UserPointDO
  */
 public function givePoints($userId, $reasonId, $cnt, $data)
 {
     if ($this->hasPointsWithData($userId, $reasonId, $data)) {
         return null;
     }
     $cnt = is_numeric($cnt) ? 1 * $cnt : null;
     check_condition(is_integer($cnt) && $cnt > 0, "Нельзя выдать [{$cnt}] очков");
     $pointId = $this->insert('INSERT INTO ps_user_points (id_user, id_reason, n_cnt, v_data, dt_event) VALUES (?, ?, ?, ?, unix_timestamp())', array($userId, $reasonId, $cnt, $data));
     return new UserPointDO($this->getRecEnsure('SELECT * FROM ps_user_points where id_point=?', $pointId));
 }
Example #27
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));
    }
Example #28
0
 /**
  * Метод добавления события в блок событий.
  * 
  * При этом дата самого событийного блока определяется датой первого добавленного в него события.
  * Все остальные собыия должны иметь ту же дату.
  * 
  * @param NewsEvent $event
  */
 public function addEvent(NewsEvent $event)
 {
     if (empty($this->events)) {
         $this->blockDate = $event->getBlockDate();
         $this->pickerDate = DatesTools::inst()->uts2dateInCurTZ($event->getNewsEventUtc(), DF_JS_DATEPICKER);
     } else {
         check_condition($this->blockDate == $event->getBlockDate(), "Новость на дату [{$event->getBlockDate()}] не может быть добавлена в блок на дату [{$this->blockDate}]");
     }
     $this->events[] = $event;
 }
Example #29
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));
 }
Example #30
0
 public function getCellNum()
 {
     ++$this->last;
     check_condition($this->last <= $this->total, 'More then max allowed cells requested.');
     $cellNum = 0;
     do {
         $cellNum = rand(1, $this->total);
     } while (array_key_exists($cellNum, $this->CELLS));
     $this->CELLS[$cellNum] = $this->last;
     return $cellNum;
 }