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); }
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(); }
function smarty_block_task($params, $content, Smarty_Internal_Template &$template) { $ctxtParams = SmartyBlockContext::getInstance()->registerBlock($content, __FUNCTION__); if (!$content) { return; //--- } /* @var $taskTpl Smarty_Internal_Template */ $taskTpl = PSSmarty::template('common/task.tpl', $ctxtParams); $from = value_Array(array('from', 'c_from'), $params); $taskTpl->assign('from', $from); $taskTpl->assign('body', $content); $isSubTask = SmartyBlockContext::getInstance()->hasParentBlock('tasks'); $taskTpl->assign('sub_task', $isSubTask); $taskNum = null; if (!$isSubTask) { $taskNumber = null; //Допускается вывод задач не в контексте $ctxt = FoldedContextWatcher::getInstance()->getTasksNumeratorContext(false); if ($ctxt) { $taskNumber = $ctxt->getNextTaskNumber(); } $taskNum = $taskNumber ? "Задача № {$taskNumber}" : null; } $taskTpl->assign('task_num', $taskNum); $taskTpl->display(); }
/** * Метод, вызываемый блоком * {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(); }
function smarty_block_citatas($params, $content, Smarty_Internal_Template &$template) { SmartyBlockContext::getInstance()->registerBlock($content, __FUNCTION__); if ($content) { PSSmarty::template('common/citatas.tpl', array('c_body' => trim($content)))->display(); } }
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); }
function smarty_function_progress($params, Smarty_Internal_Template &$smarty) { $PA = ArrayAdapter::inst($params); $params['total'] = $PA->int('total'); $params['current'] = $PA->int('current'); $params['title'] = $PA->has('title') ? $PA->str('title') : 'Прогресс'; PSSmarty::template('common/progress.tpl', $params)->display(); }
function smarty_function_page_footer($params, Smarty_Internal_Template &$template) { /* @var $footerTpl Smarty_Internal_Template */ $footerTpl = PSSmarty::template('page/footer.tpl'); //TODO - редиректить, если тип PageBuilder отличен от basic $footerTpl->assign('_blank', WebPages::isCurPage(PAGE_POPUP)); $footerTpl->display(); }
public function getBlockHtml() { $block = PSCache::NEWS()->getFromCache($this->blockDate); if (!$block) { $block = PSSmarty::template('news/date_news.tpl', array('block' => $this))->fetch(); PSCache::NEWS()->saveToCache($block, $this->blockDate); } return $block; }
function smarty_block_todo($params, $content, Smarty_Internal_Template &$smarty) { if (!$content) { return; } $tpl = PSSmarty::template('common/todo.tpl'); $tpl->assign('c_todo', trim($content)); $tpl->display(); }
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(); }
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); }
/** * html - панели с плагинами. * Суть довольно проста - самы кнопки переключения виды, это - обычные хрефы. * После них мы помещаем невидимый див во всем содержимым, необходимым для работы кнопки переключения: * 1. Первоначальный див для предпросмотра постов * 2. Собственные кнопочки для данного типа предпросмотра (ShowcasesControllerItem::getPlugins) * * Позже, на самой странице, при инициализации плагина всё это будет добавлено и "раскидано" жаваскриптом * куда следует (client.js -> PsShowcasesViewController). * * Сам плагин управляется из своего .js файла, относящегося к фолдингу данного плагина. * Там у него будет весь необходимый API. */ public function getHtml() { $params['items'] = $this->items; //Решение о том, показывать ли панель, примем на сервере. //Если её прятать на клиенте, то на мгновение пользователь всё равно увидит панель. //Проверяем empty($this->contents)>0 потому, что list и так будет добавлен вседа $params['maincss'] = 'ps-showcases-ctrl-panel' . (empty($this->items) ? ' hidden' : ''); $params['hintcss'] = 'hint--top hint--info hint--rounded'; return PSSmarty::template('common/showcases_ctrl_panel.tpl', $params)->fetch(); }
public function wrapFormulaBox($formulaId, $formula) { $formulaId = trim($formulaId); $num = $this->getNextFormulaNum($formulaId, true); $elId = $this->getFormulaElId($formulaId); $tpl = PSSmarty::template('common/formula_jax_block.tpl'); $tpl->assign('id', $elId); $tpl->assign('text', $formula); $tpl->assign('index', PsConstJs::numeratorItemIndex(self::CSS_NUMERATOR_FORMULA, $num)); return $tpl->fetch(); }
function smarty_block_answers($params, $content, Smarty_Internal_Template &$smarty) { $ctxtParams = SmartyBlockContext::getInstance()->registerBlock($content, __FUNCTION__); if (!$content) { return; } $answers = value_Array(SmartyBlockContext::MULTIPLE_ANSWERS, $ctxtParams); if ($answers) { PSSmarty::template('common/answers.tpl', array('answers' => $answers))->display(); } }
function smarty_function_gymex_body($params, Smarty_Internal_Template &$template) { /* @var $ex GymEx */ $ex = $params['ex']; $exId = $ex->getId(); $tplPath = "gym/exercises/{$exId}.tpl"; if (PSSmarty::smarty()->templateExists($tplPath)) { PSSmarty::template($tplPath)->display(); } else { // message_warn("Шаблон для упражнения с кодом [$exId] не найден"); } }
function saveResult2Html($tplName, $params = null, $__DIR__ = __DIR__, $htmlName = 'results.html', $title = null) { $tplName = ensure_file_ext($tplName, 'tpl'); $pageClass = cut_string_end($tplName, '.tpl'); $body = PSSmarty::template("hometools/{$tplName}", $params)->fetch(); $pageParams['title'] = $title == null ? 'Результаты' : $title; $pageParams['body'] = $body; $pageParams['class'] = $pageClass; $html = PSSmarty::template('hometools/page_pattern.tpl', $pageParams)->fetch(); $htmlName = ensure_file_ext($htmlName, 'html'); DirItem::inst($__DIR__, $htmlName)->writeToFile($html, true); }
function smarty_block_th($params, $content, Smarty_Internal_Template &$smarty) { $ctxtParams = SmartyBlockContext::getInstance()->registerBlock($content, __FUNCTION__); if (!$content) { return; //--- } $thId = trim(value_Array(array('id', 'num'), $params)); $num = PostFetchingContext::getInstance()->getNextThNum($thId, true); $elId = $thId ? PostFetchingContext::getInstance()->getThElId($thId) : null; $tpl = PSSmarty::template('common/theorem.tpl'); $tpl->assign('id', $elId); $tpl->assign('num', $num); $tpl->assign('c_body', $content); $tpl->assign($ctxtParams); $tpl->display(); }
function smarty_modifier_post_full_read(PostContentProvider $postCP) { $post = $postCP->getPost(); $type = $post->getPostType(); $text = 'Читать полностью »'; switch ($type) { case POST_TYPE_ISSUE: $text = 'Читать выпуск полностью »'; break; case POST_TYPE_TRAINING: $text = 'Перейти к занятию »'; break; } $tpl = PSSmarty::template('post/full_read.tpl'); $tpl->assign('text', $text); $tpl->assign('post', $post); $tpl->display(); }
function smarty_block_sortable($params, $content, Smarty_Internal_Template &$smarty) { if (!$content) { return; //--- } $params = ArrayAdapter::inst($params); $sep = $params->str('sep'); $strings = explode("\n", trim($content)); $res = array(); foreach ($strings as $str) { if (isEmpty($str)) { continue; } $items = explode('||', $str); $res[] = array('l' => trim($items[0]), 'r' => trim($items[1]), 's' => $sep); } PSSmarty::template('common/sortable.tpl', array('strings' => $res))->display(); }
/** * Основной метод, выполняющий всю работу. * К этому моменту мы уже определили плагин и установили контекст. * Остаётся только построить сам плагин. */ private function buildImpl(BasePlugin $plugin, $content, ArrayAdapter $params) { //Если $content === null, то мы отображаем плагин в popup окне //В противном случае запросим УРЛ для перехода к popup-виду плагина $popupUrl = $content === null ? null : PopupPagesManager::inst()->getPluginUrl($plugin); $ident = $plugin->getIdent(); $content = trim($content); try { $pluginContent = $plugin->getPluginContent($content, $params, PluginFetchingContext::getInstance()); $tpl = PSSmarty::template('psplugins/BASE.tpl'); $tpl->assign('url', $popupUrl); $tpl->assign('ident', $ident); $tpl->assign('content', $this->getResourcesLinks($ident, $pluginContent->getContent())); return $tpl->fetch(); } catch (Exception $e) { //Произошла ошибка... От нас требуется вернуть её текстовое представление, //так как самое важное - отключить контекст выполнения плагина. return ExceptionHandler::getHtml($e); } }
function smarty_block_table($params, $content, Smarty_Internal_Template &$smarty) { if (!$content) { return; //--- } $params = ArrayAdapter::inst($params); $strings = explode("\n", trim($content)); $res = array(); foreach ($strings as $str) { $items = explode('||', $str); if (isEmpty($items)) { continue; } $processed = array(); foreach ($items as $item) { $processed[] = explode('::', trim($item)); } $res[] = $processed; } PSSmarty::template('common/table.tpl', array('items' => $res, 'class' => $params->str('class')))->display(); }
function smarty_block_ex($params, $content, Smarty_Internal_Template &$template) { $ctxtParams = SmartyBlockContext::getInstance()->registerBlock($content, __FUNCTION__); if (!$content) { return; //--- } $ctxt = PostFetchingContext::getInstance(); if (array_key_exists('reset', $params)) { $ctxt->resetExamplesNum(); } $exId = trim(value_Array(array('id', 'num'), $params)); $num = $ctxt->getExampleNum($exId, true); $elId = $exId ? $ctxt->getExampleElId($exId) : null; /* @var $exampleTpl Smarty_Internal_Template */ $exampleTpl = PSSmarty::template('common/example.tpl'); $exampleTpl->assign('id', $elId); $exampleTpl->assign('num', $num); $exampleTpl->assign('c_body', $content); $exampleTpl->assign($ctxtParams); $exampleTpl->display(); }
function smarty_modifier_short_tr_info(PostContentProvider $postCP) { $fetchData = $postCP->getPostParams(); /* * Обработаем данные плагинов */ $PLUGIN_TESTINGS = array(); $pluginsData = $fetchData->getPluginsData(); foreach ($pluginsData as $pldata) { $ident = $pldata[0]; $data = $pldata[1]; //#1 switch ($ident) { case PluginsManager::PLUGIN_TESTING: $testingId = $data; $PLUGIN_TESTINGS[] = array(TestingBean::inst()->getTestingById($testingId), TestingManager::getInstance()->getTestingResults($testingId)); break; } //#1 } PSSmarty::template('tr/short_info.tpl', array('data' => $fetchData, 'testings' => $PLUGIN_TESTINGS))->display(); }
/** * Построение простой дискуссии - для одного листа. Выполняет основные действия. */ public final function buildDiscussionSimple(DiscussionMsg $leaf) { //Tree js data $treeData[self::JS_DATA_UPDOWN] = true; $treeData[self::JS_DATA_THREAD] = $leaf->getThreadId(); $treeData[self::JS_DATA_UNIQUE] = $this->SETTINGS->getUnique(); $treeData[self::JS_DATA_THEMED] = $this->SETTINGS->isThemed(); $params['tree'] = $this->buildLeaf($leaf, true); $params['data'] = PsHtml::data2string($treeData); return PSSmarty::template('discussion/common/discussion_simple.tpl', $params)->fetch(); }
public function getUserAnswerHtml($userId = null) { /* @var $ans UserAnsDO */ $ans = $this->BEAN->getUserAnswer($this->id, AuthManager::extractUserId($userId)); return $ans ? PSSmarty::template('mosaic/user_answer.tpl', array('ans' => $ans))->fetch() : null; }
/** * {gallery dir='trainings' lazy=1} */ public function getGalleryBox($isLazy) { $DATA = $this->getSnapshot(); $DATA['id'] = $this->gallery; $DATA['lazy'] = $isLazy; return PSSmarty::template('mmedia/gallery/box.tpl', $DATA)->fetch(); }
/** * Метод создаёт новый фолдинг */ public function makeNewFolding(ArrayAdapter $adapter) { $ifaces = $adapter->arr('ifaces'); $rtypes = $adapter->arr('rtypes'); $type = lowertrim($adapter->str('FoldingType')); $subtype = lowertrim($adapter->str('FoldingSubType')); $group = $adapter->str('FoldingGroup'); $classPrefix = $adapter->str('FoldingClassPrefix'); check_condition($type, 'Не передан тип фолдинга'); check_condition($group, 'Не передана группа для фолдинга'); check_condition($classPrefix, 'Не передан префикс для классов фолдинга'); //TODO - определять директорию для воздания менеджера фолдингов. die('Folding dir is not deffined.'); $classesDi = DirItem::inst(array('sdk/kit', 'folded'), $group); check_condition(!$classesDi->isDir(), "Директория {$classesDi} уже существует"); check_condition(!$classesDi->isFile(), "Элемент {$classesDi} не может быть файлом"); $rtypes = array_intersect(array_keys(PsUtil::getClassConsts('FoldedResources', 'RTYPE_')), $rtypes); $rtypesArr = trim(implode(', self::', $rtypes)); $rtypesArr = $rtypesArr ? "self::{$rtypesArr}" : ''; $hasPhp = in_array('RTYPE_PHP', $rtypes); $classesDm = DirManager::inst($classesDi->getRelPath())->makePath(); $resourcesPatternDmTo = DirManager::resources(array('folded', $group, FoldedResources::PATTERN_NAME)); check_condition(!$resourcesPatternDmTo->isDir(), "Целевая директория {$resourcesPatternDmTo} существует"); $resourcesPatternDmFrom = DirManager::resources(array('folded', FoldedResources::PATTERN_NAME)); check_condition($resourcesPatternDmFrom->isDir(), "Некорректна директория-источник {$resourcesPatternDmFrom}"); $interfaces = array(); foreach ($this->getFoldedInterfaces($ifaces) as $name => $ifaceClass) { $ctt = $ifaceClass->getClassBody(); if ($ctt) { $interfaces[] = "/****************\n\t * {$name}\n\t ****************/\n" . $ctt; } } $smParams = $adapter->getData(); $smParams['rtypes'] = $rtypesArr; $smParams['funique'] = FoldedResources::unique($type, $subtype); $smParams['BaseClass'] = 'Base' . $classPrefix; $smParams['ManagerClass'] = $classPrefix . 'Manager'; $smParams['ResourcesClass'] = $classPrefix . 'Resources'; $smParams['implements'] = $ifaces ? 'implements ' . implode(', ', $ifaces) . ' ' : ''; $smParams['interfaces'] = $interfaces ? implode("\n\n\t", $interfaces) : ''; try { //КЛАССЫ //Resources $tpl = PSSmarty::template(DirItem::inst(array(__DIR__, 'tpls'), 'resources.tpl'), $smParams); $di = $classesDm->getDirItem(null, $smParams['ResourcesClass'], 'php'); $di->writeToFile(trim($tpl->fetch()), true); //Manager $tpl = PSSmarty::template(DirItem::inst(array(__DIR__, 'tpls'), 'manager.tpl'), $smParams); $di = $classesDm->getDirItem(null, $smParams['ManagerClass'], 'php'); $di->writeToFile(trim($tpl->fetch()), true); if ($hasPhp) { //BaseClass $tpl = PSSmarty::template(DirItem::inst(array(__DIR__, 'tpls'), 'baseclass.tpl'), $smParams); $di = $classesDm->getDirItem(null, $smParams['BaseClass'], 'php'); $di->writeToFile(trim($tpl->fetch()), true); } //ШАБЛОН ДЛЯ СУЩНОСТЕЙ $resourcesPatternDmTo->makePath(); foreach ($rtypes as $rtype) { $ext = FoldedResources::resourceTypeToExt(PsUtil::newReflectionClass('FoldedResources')->getConstant($rtype)); $diTo = $resourcesPatternDmTo->getDirItem(null, FoldedResources::PATTERN_NAME, $ext); $diFrom = $resourcesPatternDmFrom->getDirItem(null, FoldedResources::PATTERN_NAME, $ext); if ($ext == PsConst::EXT_PHP) { $diTo->writeToFile(str_replace('eclassnamebase', $smParams['BaseClass'], $diFrom->getFileContents())); continue; } $diFrom->copyTo($diTo); } } catch (Exception $ex) { $classesDm->clearDir(null, true); $resourcesPatternDmTo->clearDir(null, true); throw $ex; } }
function smarty_function_dekart($params, Smarty_Internal_Template &$smarty) { PSSmarty::template('common/dekart.tpl')->display(); }
/** * Строит содержимое для id-card */ public function getIdCardContent() { return normalize_string(PSSmarty::template('idcard/content.tpl', array('user' => $this))->fetch()); }