function contentGenerator($template) { $USERFILES_DIRS = CMS::$R['USERFILES_DIRS']; // если этот флажок есть, будет вызван редактор вместо отображения контента $edit_mode = isset($_GET['edit']); // идентификатор странички, которую надо вставить в шаблон. валидация не нужна - делается поиск в массиве // собираем список имеющихся страниц $pages = array(); $query = CMS::$DB->query("select * from `{$this->CONFIG['table']}`"); while ($row = $query->fetch(PDO::FETCH_ASSOC)) { $pages[$row['alias']] = $row; } $page_id = isset($_GET['p_id']) ? $_GET['p_id'] : DEFAULT_PAGE_ALIAS; // ок, берем стандартную страницу, если таковая есть $page_found = false; if (isset($pages[$page_id])) { $page_found = true; $page_info = $pages[$page_id]; } else { // если нужного идентификатора нет в страницах, посмотрим в меню, если там найдется - пускай сами разбираются if (module_get_config('menu', $menu_module_config) === true) { $query = CMS::$DB->query("select alias from `{$menu_module_config['config']['table_menu']}` where alias > ''"); while ($row = $query->fetch(PDO::FETCH_ASSOC)) { if ($page_id == $row['alias']) { $page_found = true; return $template; } } } } // если страница не найдена, попробуем использовать то, что указано в настройках для страницы 404, // если и там нету - тупо заменяем макрос на строку и вываливаемся if (!$page_found) { header('HTTP/1.1 404 Not found'); if (isset($pages[$this->CONFIG['page_404']])) { $page_info = $pages[$this->CONFIG['page_404']]; } else { $template = preg_replace(macro_regexp('content'), 'Страница не найдена', $template); return $template; } } // имя файла с контентом $content_filename = isset($page_info['filename']) && file_exists($USERFILES_DIRS['pages']['dir'] . $page_info['filename']) ? $USERFILES_DIRS['pages']['dir'] . $page_info['filename'] : $this->CONFIG['page_404']; // в режиме редактирования текст/xml не генерируем, а показываем в редакторе (textarea) if ($edit_mode && user_allowed_to('edit pages')) { switch (pathinfo($page_info['filename'], PATHINFO_EXTENSION)) { case 'php': case 'xml': $pagehtml = sprintf(MODULE_CONTENT_TEXTAREA_WRAPPER_PHP, $page_id, @file_get_contents($content_filename)); break; default: $pagecontent = @file_get_contents($content_filename); // при редактировании заменим макросы на защищенную версию, иначе следующие модули на них среагируют // и заменят на свой контент, что наи не нужно. ядро само заменит их обратно потом $pagecontent = str_replace('<macro', '<protected-macro', $pagecontent); $pagecontent = str_replace('[macro', '[protected-macro', $pagecontent); $pagecontent = str_replace('</macro', '</protected-macro', $pagecontent); $pagecontent = str_replace('[/macro', '[/protected-macro', $pagecontent); $pagehtml = sprintf(MODULE_CONTENT_TEXTAREA_WRAPPER, $page_id, $pagecontent); break; } } else { // если html, тащим как есть, иначе формируем с помошью генератора или XSLT switch ($ext = pathinfo($content_filename, PATHINFO_EXTENSION)) { case 'php': include_once $content_filename; $pagehtml = call_user_func($page_info['generator']); break; case 'xml': $pagehtml = XSLTransform($content_filename, $USERFILES_DIRS['xsl']['dir'] . $page_info['xsl'], false, false); break; default: ($pagehtml = file_get_contents($content_filename)) !== false or $pagehtml = 'error reading page content (code CONTENT/001)'; break; } } // если есть BODY, берем его внутреннее содержимое, иначе весь файл целиком if (preg_match(self::REGEXP_HTML_BODY, $pagehtml, $page_body) > 0) { $replace = $page_body[1]; } else { $replace = $pagehtml; } if (isset($_GET['print'])) { $template = str_replace('%content%', $replace, MODULE_CONTENT_PRINT_FORM); } else { $template = preg_replace(macro_regexp('content'), $replace, $template); } // мета в заголовке. если только буквы-цифры, делаем мету keywords if (preg_match('~^[a-zA-Zа-яА-Я0-9,.\\-\\s]+$~ui', $page_info['meta'], $match)) { $template = add_meta($template, 'name', 'keywords', $match[0]); } elseif (preg_match_all('~(\\(([a-zA-Z\\-]*)\\|([a-zA-Z\\-0-9]+)\\|([a-zA-Z\\-0-9а-яА-Я.,;:\\s+=!@#$%^&*\\(\\)]*)\\))~smui', $page_info['meta'], $matches)) { // не прокатило, попробуем структуру со скобками и пайпами for ($i = 0; $i < count($matches[0]); $i++) { $template = add_meta($template, $matches[2][$i], $matches[3][$i], $matches[4][$i]); } } elseif (preg_match_all('~<meta\\s[^>]+>~smui', $page_info['meta'], $matches)) { // проверим, возможно вписали сырые теги for ($i = 0; $i < count($matches[0]); $i++) { $template = str_insert_before('</head>', $matches[0][$i] . PHP_EOL, $template); } } // заменяем залоговок страницы, если определен if (isset($page_info['title']) && ($replace = $page_info['title']) > '') { $template = preg_replace(macro_regexp('page_title'), $replace, $template, 1); } // кастомный CSS, если указан if (isset($page_info['custom_css']) && ($css = $page_info['custom_css']) > '') { add_CSS(CMS::$R['USERFILES_DIRS']['css']['dir'] . $css); } // кастомный JS, если указан if (isset($page_info['custom_js']) && ($js = $page_info['custom_js']) > '') { add_JS(CMS::$R['USERFILES_DIRS']['js']['dir'] . $js); } return $template; }
/** * Places feedback form from the file * * Macro parameters available: * "form" : specifies a file to get a form from (no extension, will be added automatically, "default" by default) * "target" : get recipient from the config list (first item by default) * "template" : forces to add "template" hidden input to the form causing sender to use alternate email template * * @param string $template source template * @return string */ function contentGenerator($template) { // look for macro while (preg_match(macro_regexp('feedback'), $template, $match) > 0) { $params = parse_plugin_template($match[0]); // now get form HTML. if no source found specified, try to use "default.html". Malformed values always generate an error if ($filename = get_array_value($params, 'form', 'default', REGEXP_IDENTIFIER)) { if (file_exists(__DIR__ . '/forms/' . $filename . '.html')) { $form = file_get_contents(__DIR__ . '/forms/' . $filename . '.html'); } else { $form = '<b>[JuliaCMS][feedback] error:</b> form file "' . $filename . '.html" not found'; } } else { $form = '<b>[JuliaCMS][feedback] error:</b> bad form name "' . $params['form'] . '"'; } // let's determine form target (source form's one will be deleted automatically) $target = get_array_value($params, 'target', false); $address_keys = array_keys($this->CONFIG['addresses']); $recipient = isset($this->CONFIG['addresses'][$target]) ? $target : array_shift($address_keys); // ok, implant recipient field into a form (first, cut existing if any) $form = preg_replace('~<input\\s[^>]*?name="recipient"[^/>]*/?>~', '', $form); $form = str_insert_before('</form>', '<input type="hidden" name="recipient" value="' . $recipient . '" />', $form); // add (or replace) template identifier, if specified $message_template_name = get_array_value($params, 'template', '', REGEXP_IDENTIFIER); if ($message_template_name > '') { $form = preg_replace('~<input\\s[^>]*?name="template"[^/>]*/?>~', '', $form); $form = str_insert_before('</form>', '<input type="hidden" name="template" value="' . $message_template_name . '" />', $form); } // form ready, add it to template! $template = str_replace($match[0], $form, $template); } return $template; }
/** * */ function contentGenerator($template) { // catalog mode: intercept _GET page alias, look in self elements, display child items list if exists $input_filter = array('p_id' => array('filter' => FILTER_VALIDATE_REGEXP, 'options' => array('regexp' => REGEXP_ALIAS))); $_INPUT = get_filtered_input($input_filter, array(FILTER_GET_BY_LIST)); if ($_INPUT['p_id'] > '') { // this will mean that nothing was found $id = -1; $query = CMS::$DB->query("select * from `{$this->CONFIG['table_menu']}` where alias = '{$_INPUT['p_id']}'"); if ($row = $query->fetch(PDO::FETCH_ASSOC)) { $id = $row['id']; $css_content = $row['style_content']; $caption = $row['caption']; $title = $row['title'] ? $row['title'] : $row['caption']; $meta = $row['meta']; } // if we found something, insert it instead content if ($id >= 0) { while (preg_match(macro_regexp('content'), $template, $match) > 0) { $params = parse_plugin_template($match[0]); $html = $this->generateCatalogPageHTML($_INPUT['p_id'], $params); // possibly we will need navigator from the current page if (get_array_value($params, 'show-navigator', 'yes') == 'yes') { $html = $this->generateNavigatorHTML($_INPUT['p_id'], $params) . $html; } $template = preg_replace(macro_regexp('content'), $html, $template); $template = preg_replace(macro_regexp('page_title'), $title, $template); // add meta. if only letter and digits, make "keywords" meta (!copy-paste detected!) if (preg_match('~^[a-zA-Zа-яА-Я0-9,.\\-\\s]+$~ui', $meta, $match)) { $template = add_meta($template, 'name', 'keywords', $match[0]); } elseif (preg_match_all('~(\\(([a-zA-Z\\-]*)\\|([a-zA-Z\\-0-9]+)\\|([a-zA-Z\\-0-9а-яА-Я.,;:\\s+=!@#$%^&*\\(\\)]*)\\))~smui', $meta, $matches)) { // не прокатило, попробуем структуру со скобками и пайпами for ($i = 0; $i < count($matches[0]); $i++) { $template = add_meta($template, $matches[2][$i], $matches[3][$i], $matches[4][$i]); } } elseif (preg_match_all('~<[a-zA-Z]+\\s[^<>]+>~smui', $meta, $matches)) { // check if raw tags there for ($i = 0; $i < count($matches[0]); $i++) { $template = str_insert_before('</head>', $matches[0][$i] . PHP_EOL, $template); } } // yeah, nice stylesheets add_CSS($css_content, CMS::$R['USERFILES_DIRS']['css']['dir']); } } } // standard behavior - menu by macro while (preg_match(macro_regexp('menu'), $template, $match) > 0) { // parse template parameters into array $params = parse_plugin_template($match[0]); // generate menu HTML $xml = $this->generateMenuAsXML(get_array_value($params, 'start-from', '')); $xsl = get_array_value($params, 'menu-template', 'default'); // now test with path $xsl_filename = __DIR__ . '/../../userfiles/_data_modules/menu/templates/menu/' . $xsl . '.xsl'; if (!file_exists($xsl_filename)) { $xsl_filename = __DIR__ . '/templates/' . $catalog_dir . '/' . $xsl . '.xsl'; } $html = XSLTransform($xml->saveXML($xml->documentElement), $xsl_filename); // replace it $template = str_replace($match[0], $html, $template); } // navigator mode while (preg_match(macro_regexp('menu-navigator'), $template, $match) > 0) { // parse template parameters into array $params = parse_plugin_template($match[0]); // generate navigator HTML $html = $this->generateNavigatorHTML(get_array_value($params, 'start-from', ''), $params); // replace it $template = str_replace($match[0], $html, $template); } // yeah we are ready return $template; }
/** * Converts pre-stored messages to special div's (invisible, JS will display them later) * * Note that NO CHECK performed on parameters, so use tags carefully * * @param $string current page template * @return string modified template */ function popup_messages_to_template($template) { $classes = array(JCMS_MESSAGE_INFO => 'popup-info', JCMS_MESSAGE_OK => 'popup-ok', JCMS_MESSAGE_WARNING => 'popup-warning', JCMS_MESSAGE_ERROR => 'popup-error', JCMS_MESSAGE_FATAL => 'popup-fatal'); // first, get older popups stored at $_SESSION $all_popups = array_merge(get_array_value($_SESSION, 'popups', array()), CMS::Get('J_CMS_messages', 'array')); // prevent popups to be displayed one again $_SESSION['popups'] = array(); foreach ($all_popups as $message) { $html = '<div style="display: none;" class="popup-message ' . $classes[$message['type']] . '">' . htmlspecialchars($message['message']) . '</div>'; $template = str_insert_before('</body>', $html, $template); } // clean queue to prevent forwarding its content to $_SESSION at terminate() CMS::$R['J_CMS_messages'] = array(); return $template; }