Example #1
0
 public function buildContent()
 {
     $TLM = TimeLineManager::inst();
     $insts = $TLM->getEntityClassInsts();
     if (empty($insts)) {
         return;
         //Нет временных шкал для показа
     }
     $idents = array_keys($insts);
     $options = array();
     /** @var TimeLineBuilderBase */
     foreach ($insts as $ident => $inst) {
         $options[] = array('content' => $inst->getTitle(), 'value' => $this->getPageUrl(array('type' => $ident)));
     }
     usort($options, function ($e1, $e2) {
         return strcasecmp($e1['content'], $e2['content']);
     });
     $current = RequestArrayAdapter::inst()->str('type');
     $current = $current && in_array($current, $idents) ? $current : $idents[0];
     $select = PsHtml::select(array('class' => 'switcher'), $options, $this->getPageUrl(array('type' => $current)));
     /*
      * В данный момент мы определили идентификатор временной шкалы и построили элемент $select,
      * можем строить страницу.
      */
     $params['body'] = $TLM->fetchTplWithResources($current);
     $params['select'] = $select;
     return $this->getFoldedEntity()->fetchTpl($params);
 }
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
 public function getFoldedEntityPreview($ident)
 {
     $type = $this->pp->getPostType();
     $postCP = $this->pp->getPostContentProviderByIdent($ident);
     $hasInDb = is_object($postCP);
     $post = null;
     if ($hasInDb) {
         $post = $postCP->getPost();
     } else {
         //Сделаем его форсированно загружаемым из шаблона
         $virtualPostParams['b_tpl'] = 1;
         $post = $this->pp->getVirtualPost($ident, $virtualPostParams);
         $postCP = ContentProviderFactory::getContentProvider($post);
     }
     //Накачиваем страницу
     $PARAMS = array('type' => $type, 'full' => '', 'short' => '', 'error' => '');
     try {
         $PARAMS['full'] = $postCP->getPostContent()->getContent();
         $PARAMS['short'] = $postCP->getPostContentShowcase()->getContent();
     } catch (Exception $ex) {
         $PARAMS['error'] = ExceptionHandler::getHtml($ex);
     }
     $info = $hasInDb ? $this->pp->postHref($post, null, null, null, true) : PsHtml::gray($post->isVirtual() ? 'Пост не зарегистрирован в базе' : 'Пост зарегистрирован в базе, но не виден пользователю');
     $content = PSSmarty::template('post/folded_prev.tpl', $PARAMS)->fetch();
     return array('info' => $info, 'content' => $content);
 }
Example #4
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)) : '');
 }
Example #5
0
 /**
  * Возвращает ссылку на страницу:
  * <a href="helpus.php">Поддержать проект</a>
  * По умолчанию берёт название страницы, но можно передать кастомное.
  */
 public function getHref($content = null, $blank = false, $classes = null, $http = false, $urlParams = null, $sub = null, $title = null)
 {
     $PARAMS['href'] = $this->getUrl($http, $urlParams, $sub);
     $PARAMS['title'] = $title ? $title : $this->name;
     $PARAMS['class'] = $classes;
     return PsHtml::a($PARAMS, $content ? $content : $this->name, $blank);
 }
Example #6
0
 /**
  * Метод, вызываемый блоком
  * {stock name='Мозайка' img='puzzle.png' ident='mosaic' to='2013-12-11 12:00:00' enabled='1' data_id='1'}
  * для регистрации акции
  * 
  * @param ArrayAdapter $params - параметры акции.
  */
 public function registerStock(ArrayAdapter $params)
 {
     $type = $params->str('type');
     if (!$this->existsEntity($type)) {
         return PsHtml::divErr("Неизвестный тип акции - [{$type}].");
     }
     /*
     * TODO - выкинута проверка доступа
      if (!$this->hasAccess($type)) {
      return '';
      }
     */
     /* @var $stock BaseStock */
     $stock = $this->getEntityClassInst($type, false);
     if (!$stock->isUserHasAccess()) {
         return '';
     }
     $stock->init($params);
     $type = $stock->getType();
     $ident = $stock->getStockIdent();
     if (array_key_exists($ident, $this->STOCKS)) {
         return PsHtml::divErr("Акция [{$stock}] уже зарегистрирована.");
     }
     $this->STOCKS[$ident] = $stock;
     $this->LOGGER->info("STOCK [{$stock}] is registered.");
     /*
      * Акция успешно зарегистрирована, покажем её "короткий" вид
      */
     $PARAMS['stock'] = $stock;
     $PARAMS['body'] = $stock->getShortView();
     return PSSmarty::template('common/stock.tpl', $PARAMS)->fetch();
 }
Example #7
0
function basePageHref($basePageCode, $image)
{
    $basePage = WebPage::inst($basePageCode);
    $sprites = CssSpritesManager::getDirSprite(CssSpritesManager::DIR_HEADER, $image, true);
    $href = $basePage->getHref($sprites . $basePage->getName());
    echo PsHtml::html2('li', array('class' => WebPages::getCurPage()->isMyBasePage($basePage) ? 'current' : null), $href);
}
Example #8
0
 public function getFoldedEntityPreview($ident)
 {
     $type = $this->rp->getPostType();
     $rubricCP = $this->rp->getRubricContentProviderByIdent($ident);
     $hasInDb = is_object($rubricCP);
     $rubric = null;
     if ($hasInDb) {
         $rubric = $rubricCP->getRubric();
     } else {
         //Сделаем его форсированно загружаемым из шаблона
         $virtualRubricParams['b_tpl'] = 1;
         $rubric = $this->rp->getVirtualRubric($ident, $virtualRubricParams);
         $rubricCP = ContentProviderFactory::getContentProvider($rubric);
     }
     //Накачиваем страницу
     $PARAMS = array('type' => $type, 'full' => '', 'error' => '');
     try {
         $PARAMS['full'] = $rubricCP->getContent();
     } catch (Exception $ex) {
         $PARAMS['error'] = ExceptionHandler::getHtml($ex);
     }
     $info = $hasInDb ? $this->rp->rubricHref($rubric) : PsHtml::gray($rubric->isVirtual() ? 'Рубрика не зарегистрирована в базе' : 'Рубрика зарегистрирована в базе, но не видна пользователю');
     $content = PSSmarty::template('rubric/folded_prev.tpl', $PARAMS)->fetch();
     return array('info' => $info, 'content' => $content);
 }
 private function generateImpl()
 {
     $images = DirManager::inst('ps-addon/crop')->getDirContent('oboi', DirItemFilter::FILES);
     for ($i = 0; $i < rand(2000, 3000); $i++) {
         $img = $images[array_rand($images)];
         echo PsHtml::img(array('src' => PsImgEditor::resize($img, '60x60', null)));
     }
 }
Example #10
0
function smarty_function_linkup_js($params, Smarty_Internal_Template &$smarty)
{
    $params = ArrayAdapter::inst($params);
    $dir = $params->str('dir');
    $name = $params->str('name');
    $di = DirManager::resources('scripts')->getDirItem($dir, $name, 'js');
    echo $di->isFile() ? PsHtml::linkJs($di) : '';
}
Example #11
0
 public function html()
 {
     $path = $this->path;
     if ($this->current) {
         $path[] = PsHtml::span(array(), $this->current);
     }
     return empty($path) ? '' : PsHtml::div(array('class' => 'ps-page-nav'), implode('', $path));
 }
Example #12
0
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));
    }
}
/**
 * Управление постом
 */
function smarty_modifier_post_header_controls($post)
{
    $post = $post instanceof PostContentProvider ? $post->getPost() : $post;
    $pp = Handlers::getInstance()->getPostsProcessorByPostType($post->getPostType());
    /*
     * Собираем кнопки управления
     */
    $buttons = array();
    $hintClasses = 'hint--top hint--info hint--rounded';
    //Печать поста
    $attrs = array();
    $title = 'Версия для печати';
    $attrs['href'] = '#print';
    $attrs['title'] = $title;
    $attrs['data'] = array('hint' => $title);
    $attrs['class'] = $hintClasses;
    $content = CssSpritesManager::getDirSprite(CssSpritesManager::DIR_ICO, 'print', true);
    $buttons[] = PsHtml::a($attrs, $content);
    //Оригинальный вид поста
    if (PsDefines::isReplaceFormulesWithImages()) {
        $attrs = array();
        $title = 'Просмотр ' . ps_strtolower($pp->postTitle(null, 2)) . ' без замены формул на картинки';
        $attrs['href'] = '#originalView';
        $attrs['title'] = $title;
        $attrs['data'] = array('hint' => $title);
        $attrs['class'] = $hintClasses;
        $content = CssSpritesManager::getDirSprite(CssSpritesManager::DIR_ICO, 'formula', true);
        $buttons[] = PsHtml::a($attrs, $content);
    }
    //Быстрый просмотр постов (перелистывание)
    $attrs = array();
    $title = 'Предыдущий/следующий ' . ps_strtolower($pp->postTitle(null, 1));
    $attrs['href'] = '#prevNextView';
    $attrs['title'] = $title;
    $attrs['data'] = array('hint' => $title);
    $attrs['class'] = $hintClasses;
    $content = CssSpritesManager::getDirSprite(CssSpritesManager::DIR_ICO, 'prev_next', true);
    $buttons[] = PsHtml::a($attrs, $content);
    //Предыдущий пост
    $prevPost = $pp->getPrevPost($post->getId(), false);
    if ($prevPost) {
        $attrs = array();
        $attrs['data']['hint'] = $pp->postTitle($prevPost);
        $attrs['class'] = $hintClasses;
        $content = CssSpritesManager::getDirSprite(CssSpritesManager::DIR_ICO, 'prev_s', true);
        $buttons[] = $pp->postHref($prevPost, $content, null, $attrs);
    }
    //Следующий пост
    $nextPost = $pp->getNextPost($post->getId(), false);
    if ($nextPost) {
        $attrs = array();
        $attrs['data']['hint'] = $pp->postTitle($nextPost);
        $attrs['class'] = $hintClasses;
        $content = CssSpritesManager::getDirSprite(CssSpritesManager::DIR_ICO, 'next_s', true);
        $buttons[] = $pp->postHref($nextPost, $content, null, $attrs);
    }
    return PsHtml::div(array('class' => PsConstJs::POST_HEAD_CONTROLS), implode(' ', $buttons));
}
Example #14
0
 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);
 }
Example #15
0
 public static function post_anons_placeholder($post)
 {
     if ($post instanceof PostContentProvider) {
         $post = $post->getPost();
     }
     $params['class'] = $post->getPostType() . '-anons-placeholder';
     $params['data'] = array('id' => $post->getId());
     return PsHtml::div($params, 'Идёт построение списка...');
 }
Example #16
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);
}
Example #17
0
function smarty_function_linkup_css($params, Smarty_Internal_Template &$smarty)
{
    $params = ArrayAdapter::inst($params);
    $dir = $params->str('dir');
    $name = $params->str('name');
    $media = $params->str('media');
    $di = DirManager::resources('css')->getDirItem($dir, $name, 'css');
    echo $di->isFile() ? PsHtml::linkCss($di, $media) : '';
}
Example #18
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);
 }
Example #19
0
 public function rubricHref($rubric, $content = null, $classes = null)
 {
     $rubric = $this->extractRubric($rubric);
     $content = $content ? $content : $rubric->getName();
     $PARAMS['href'] = $this->rubricUrl($rubric);
     $PARAMS['class'] = $classes;
     $PARAMS['title'] = $this->rubricTitle($rubric);
     return PsHtml::a($PARAMS, $content);
 }
 public function getBlockImgHref($imageId)
 {
     $imageId = trim($imageId);
     $num = $this->getNextImgNum($imageId, false);
     if (!is_numeric($num)) {
         return PsHtml::spanErr("Ссылка на незарегистрированную картинку с идентификатором '{$imageId}'");
     }
     $boxId = $this->getImgElId($imageId);
     return PsBubble::spanById($boxId, "рис. " . PsConstJs::numeratorHrefIndex(self::CSS_NUMERATOR_IMG, $num));
 }
Example #21
0
function smarty_modifier_exhref($exId)
{
    $exId = trim($exId);
    $num = PostFetchingContext::getInstance()->getExampleNum($exId, false);
    $elId = PostFetchingContext::getInstance()->getExampleElId($exId);
    if (!$num) {
        return PsHtml::spanErr("Ссылка на незарегистрированный пример с идентификатором '{$exId}'");
    }
    return PsBubble::aById($elId, "№{$num}", 'example');
}
Example #22
0
 public static function psctrl(array $params)
 {
     $id = array_get_value_unset('id', $params);
     $class = to_array(array_get_value_unset('class', $params));
     $class[] = 'pscontrols';
     if (!empty($params)) {
         array_remove_keys($params, array_diff(array_keys($params), PsUtil::getClassConsts(__CLASS__, 'ACTION_')));
     }
     return empty($params) ? '' : PSSmarty::template('common/pscontrols.tpl', array('id' => $id, 'class' => PsHtml::classes2string($class), 'actions' => $params))->fetch();
 }
Example #23
0
function smarty_modifier_thhref($thId)
{
    $thId = trim($thId);
    $CTXT = PostFetchingContext::getInstance();
    $num = $CTXT->getNextThNum($thId, false);
    if (!$num) {
        return PsHtml::spanErr("Ссылка на незарегистрированную теорему с идентификатором '{$thId}'");
    }
    return PsBubble::aById($CTXT->getThElId($thId), "№{$num}", 'theorem');
}
 public function getFormulaHref($formulaId)
 {
     $formulaId = trim($formulaId);
     $num = $this->getNextFormulaNum($formulaId, false);
     if (!$num) {
         return PsHtml::spanErr("Ссылка на незарегистрированную формулу с идентификатором '{$formulaId}'");
     }
     $boxId = $this->getFormulaElId($formulaId);
     return PsBubble::spanById($boxId, '(' . PsConstJs::numeratorHrefIndex(self::CSS_NUMERATOR_FORMULA, $num) . ')', 'formula');
 }
Example #25
0
 protected function postProcessImpl(PageParams $pageParams, \RequestArrayAdapter $requestParams)
 {
     $SMARTY_PARAMS['JS_DEFS'] = PageBuilder::inst()->buildJsDefs($pageParams);
     $SMARTY_PARAMS_PAGE = $pageParams->getSmartyParams4Resources();
     $SMARTY_PARAMS = array_merge($SMARTY_PARAMS, $SMARTY_PARAMS_PAGE);
     $resources = PSSmarty::template('page/environment/wordpress/wp_page_resources_footer.tpl', $SMARTY_PARAMS)->fetch();
     $resources = trim($resources);
     $this->LOGGER->infoBox('PAGE_RESOURCES_FOOTER', $resources);
     echo PsHtml::div(array(), $resources);
 }
Example #26
0
function smarty_block_chessboard($params, $content, Smarty_Internal_Template &$template)
{
    if (!$content) {
        return;
    }
    $content = normalize_string($content, true);
    $content = strtolower($content);
    $arr = explode(',', $content);
    $sets = array();
    foreach ($arr as $value) {
        if (strlen($value) >= 4) {
            $fig = substr($value, 0, 2);
            $pos = substr($value, 2, 2);
            $sets[$pos] = $fig;
            $colNum = false;
            $rowNum = $pos[1];
            switch ($pos[0]) {
                case 'a':
                    $colNum = 1;
                    break;
                case 'b':
                    $colNum = 2;
                    break;
                case 'c':
                    $colNum = 3;
                    break;
                case 'd':
                    $colNum = 4;
                    break;
                case 'e':
                    $colNum = 5;
                    break;
                case 'f':
                    $colNum = 6;
                    break;
                case 'g':
                    $colNum = 7;
                    break;
                case 'h':
                    $colNum = 8;
                    break;
                default:
                    return PsHtml::spanErr("Bad chess board position: [{$value}]");
            }
            if ($colNum) {
                $sets[$colNum . $rowNum] = $fig;
            }
        }
    }
    /* @var $chessBoardTpl Smarty_Internal_Template */
    $chessBoardTpl = $template->smarty->createTemplate('common/chessboard.tpl');
    $chessBoardTpl->assign('figures', $sets);
    $chessBoardTpl->assign('small', array_key_exists('small', $params));
    $chessBoardTpl->display();
}
Example #27
0
 /**
  * Все типы аудитов для формы поиска
  */
 public static function getAuditActionsCombo()
 {
     $data = array();
     /* @var $audit BaseAudit */
     foreach (BaseAudit::getAll() as $audit) {
         foreach ($audit->getActions() as $name => $code) {
             $data[] = PsHtml::comboOption($code, $name . "&nbsp;&nbsp;({$code})", array('data' => array('process' => $audit->getProcessCode())));
         }
     }
     return $data;
 }
Example #28
0
function smarty_function_chess_fugure($params, Smarty_Internal_Template &$template)
{
    // Постановка фигуры на доску
    $x = $params['x'];
    $y = $params['y'];
    $value = '';
    $figure = '';
    $data = array();
    $class = array();
    if ($y == 0 || $y == 9) {
        switch ($x) {
            case 1:
                $value = 'A';
                break;
            case 2:
                $value = 'B';
                break;
            case 3:
                $value = 'C';
                break;
            case 4:
                $value = 'D';
                break;
            case 5:
                $value = 'E';
                break;
            case 6:
                $value = 'F';
                break;
            case 7:
                $value = 'G';
                break;
            case 8:
                $value = 'H';
                break;
        }
    } else {
        if ($x == 0 || $x == 9) {
            $value = $y;
        } else {
            $class[] = ($x + $y) % 2 == 0 ? 'even' : 'odd';
            $figs = $template->getTemplateVars('figures');
            $pos = $x . $y;
            //Позиция фигуры, например a6
            if (is_array($figs) && array_key_exists($pos, $figs)) {
                $figure = $figs[$pos];
                $value = "<span class=\"{$figure}\"></span>";
            }
        }
    }
    return PsHtml::html2('td', array('class' => $class), $value);
}
Example #29
0
 /**
  * Метод возвращает ссылку, открывающую загружаемую страницу.
  * Для работы загружаемой страницы нужны ресурсы фолдинга этой страницы - они также будут добавлены к ссылке.
  * 
  * <a title="Новости" class="ip-opener" href="#news"><img alt="news.png" src="/autogen/images/16x16/folding/idents/news.png"></a>
  * 
  * @param BaseIdentPage or String $item
  * @param array $params - параметры ссылки
  * @param type $content - содержимое ссылки. Если нет, то будет подставлена картинка.
  */
 public final function getIdentPageHref(array $params = array(), $content = null)
 {
     $this->checkAccess();
     $params['class'][] = 'ip-opener';
     $params['class'][] = $this->foldedEntity->getUnique();
     $params['title'] = $this->getTitle();
     $params['href'] = "#" . $this->foldedEntity->getIdent();
     //Если не передано содержимое, то добавим картинку
     $content = $content ? $content : PsHtml::img(array('src' => $this->foldedEntity->getCover()));
     //Добавим все необходимые ресурсы
     $content = $this->foldedEntity->getResourcesLinks($content);
     return PsHtml::a($params, $content);
 }
Example #30
0
 private function buildJsDefs(PageParams $params, PageContext $ctxt)
 {
     $JS_CLASS_CONSTS = PsUtil::getClassConsts('PsConstJs');
     $JS_CONSTS = $this->jsConsts();
     $JS_COMMON = $this->jsCommon($ctxt);
     $JS_PAGE = $params->getJsParams();
     $defs = json_encode(array_merge($JS_CONSTS, $JS_COMMON, $JS_PAGE));
     $const = json_encode($JS_CLASS_CONSTS);
     $defs = "var defs={$defs}; var CONST={$const};";
     $defs = PsHtml::linkJs(null, $defs);
     $this->LOGGER->infoBox('JS DEFS', $defs);
     return $defs;
 }