Тема: Хочу подилиться своими разработками код Shortcode - для вывода галереи
При реализации одного проекта понадобилось сделать вывод галереи при создании страницы в любом месте в тексте.
Решил что можно реализовать решение написав свою библиотеку, которая обрабатывает в тексте [bb code] и переводит этот код ББ в код ПХП для вывода самих фотографий.
Собственно файл библиотеки Shortcodes.php - которая обрабатывает текст страницы и ищет в нём код BB, закидываем данный файл в папку application/libraries/Shortcodes.php
<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
class Shortcodes {
/**
* ImageCMS API для создания bbcode тэгов в нутри вашего контента
* Парсинг тегов и атрибутов или кода регулярных выражений основанных на Textpattern tag parser.
* Несколько примеров приведённые ниже:
*
* [shortcode /]
* [shortcode foo="bar" baz="bing" /]
* [shortcode foo="bar"]content[/shortcode]
*
* Shortcode тэги поддерживаю атрибуты и закрытый контент, но не включают поддержку тэгов
* <shortcode></shortcode>.
*
* Добавление shortcode тэгов в контент:
*
* <code>
* $out = do_shortcode($content);
* </code>
*
* @package ImageCMS
* @subpackage Shortcodes
* @since 4.6.1
*/
/**
* Container for storing shortcode tags and their hook to call for the shortcode
*
* @since 2.5
* @name $shortcode_tags
* @var array
* @global array $shortcode_tags
* @authors Aleksandr Ivanov
*/
private $_ci;
public $shortcode_tags = array();
public function __construct() {
$this->_ci = & get_instance();
//$shortcode_tags = array();
}
public function add_shortcode($tag, $func) {
//global $shortcode_tags;
if (is_callable($func)) {
$this->shortcode_tags[$tag] = $func;
}
}
/**
* Removes hook for shortcode.
*
* @since 2.5
* @uses $shortcode_tags
*
* @param string $tag shortcode tag to remove hook for.
*/
public function remove_shortcode($tag) {
//global $this->shortcode_tags;
unset($this->shortcode_tags[$tag]);
}
/**
* Clear all shortcodes.
*
* This function is simple, it clears all of the shortcode tags by replacing the
* shortcodes global by a empty array. This is actually a very efficient method
* for removing all shortcodes.
*
* @since 2.5
* @uses $shortcode_tags
*/
public function remove_all_shortcodes() {
//global $shortcode_tags;
$this->shortcode_tags = array();
}
/**
* Whether a registered shortcode exists named $tag
*
* @since 3.6.0
*
* @global array $shortcode_tags
* @param string $tag
* @return boolean
*/
public function shortcode_exists($tag) {
//global $shortcode_tags;
return array_key_exists($tag, $this->shortcode_tags);
}
/**
* Whether the passed content contains the specified shortcode
*
* @since 3.6.0
*
* @global array $shortcode_tags
* @param string $tag
* @return boolean
*/
public function has_shortcode($content, $tag) {
if ($this->shortcode_exists($tag)) {
preg_match_all('/' . $this->get_shortcode_regex() . '/s', $content, $matches, PREG_SET_ORDER);
if (empty($matches))
return false;
foreach ($matches as $shortcode) {
if ($tag === $shortcode[2])
return true;
}
}
return false;
}
/**
* Search content for shortcodes and filter shortcodes through their hooks.
*
* If there are no shortcode tags defined, then the content will be returned
* without any filtering. This might cause issues when plugins are disabled but
* the shortcode will still show up in the post or content.
*
* @since 2.5
* @uses $shortcode_tags
* @uses get_shortcode_regex() Gets the search pattern for searching shortcodes.
*
* @param string $content Content to search for shortcodes
* @return string Content with shortcodes filtered out.
*/
public function do_shortcode($content) {
//global $shortcode_tags;
if (empty($this->shortcode_tags) || !is_array($this->shortcode_tags))
return $content;
$pattern = $this->get_shortcode_regex();
return preg_replace_callback("/$pattern/s", array($this, 'do_shortcode_tag'), $content);
}
/**
* Retrieve the shortcode regular expression for searching.
*
* The regular expression combines the shortcode tags in the regular expression
* in a regex class.
*
* The regular expression contains 6 different sub matches to help with parsing.
*
* 1 - An extra [ to allow for escaping shortcodes with double [[]]
* 2 - The shortcode name
* 3 - The shortcode argument list
* 4 - The self closing /
* 5 - The content of a shortcode when it wraps some content.
* 6 - An extra ] to allow for escaping shortcodes with double [[]]
*
* @since 2.5
* @uses $shortcode_tags
*
* @return string The shortcode search regular expression
*/
public function get_shortcode_regex() {
//global $shortcode_tags;
$tagnames = array_keys($this->shortcode_tags);
$tagregexp = join('|', array_map('preg_quote', $tagnames));
// WARNING! Do not change this regex without changing do_shortcode_tag() and strip_shortcode_tag()
// Also, see shortcode_unautop() and shortcode.js.
return
'\\[' // Opening bracket
. '(\\[?)' // 1: Optional second opening bracket for escaping shortcodes: [[tag]]
. "($tagregexp)" // 2: Shortcode name
. '(?![\\w-])' // Not followed by word character or hyphen
. '(' // 3: Unroll the loop: Inside the opening shortcode tag
. '[^\\]\\/]*' // Not a closing bracket or forward slash
. '(?:'
. '\\/(?!\\])' // A forward slash not followed by a closing bracket
. '[^\\]\\/]*' // Not a closing bracket or forward slash
. ')*?'
. ')'
. '(?:'
. '(\\/)' // 4: Self closing tag ...
. '\\]' // ... and closing bracket
. '|'
. '\\]' // Closing bracket
. '(?:'
. '(' // 5: Unroll the loop: Optionally, anything between the opening and closing shortcode tags
. '[^\\[]*+' // Not an opening bracket
. '(?:'
. '\\[(?!\\/\\2\\])' // An opening bracket not followed by the closing shortcode tag
. '[^\\[]*+' // Not an opening bracket
. ')*+'
. ')'
. '\\[\\/\\2\\]' // Closing shortcode tag
. ')?'
. ')'
. '(\\]?)'; // 6: Optional second closing brocket for escaping shortcodes: [[tag]]
}
/**
* Regular Expression callable for do_shortcode() for calling shortcode hook.
* @see get_shortcode_regex for details of the match array contents.
*
* @since 2.5
* @access private
* @uses $shortcode_tags
*
* @param array $m Regular expression match array
* @return mixed False on failure.
*/
public function do_shortcode_tag($m) {
//global $shortcode_tags;
// allow [[foo]] syntax for escaping a tag
if ($m[1] == '[' && $m[6] == ']') {
return substr($m[0], 1, -1);
}
$tag = $m[2];
$attr = $this->shortcode_parse_atts($m[3]);
if (isset($m[5])) {
// enclosing tag - extra parameter
return $m[1] . call_user_func($this->shortcode_tags[$tag], $attr, $m[5], $tag) . $m[6];
}
else {
// self-closing tag
return $m[1] . call_user_func($this->shortcode_tags[$tag], $attr, null, $tag) . $m[6];
}
}
/**
* Retrieve all attributes from the shortcodes tag.
*
* The attributes list has the attribute name as the key and the value of the
* attribute as the value in the key/value pair. This allows for easier
* retrieval of the attributes, since all attributes have to be known.
*
* @since 2.5
*
* @param string $text
* @return array List of attributes and their value.
*/
public function shortcode_parse_atts($text) {
$atts = array();
$pattern = '/(\w+)\s*=\s*"([^"]*)"(?:\s|$)|(\w+)\s*=\s*\'([^\']*)\'(?:\s|$)|(\w+)\s*=\s*([^\s\'"]+)(?:\s|$)|"([^"]*)"(?:\s|$)|(\S+)(?:\s|$)/';
$text = preg_replace("/[\x{00a0}\x{200b}]+/u", " ", $text);
if (preg_match_all($pattern, $text, $match, PREG_SET_ORDER)) {
foreach ($match as $m) {
if (!empty($m[1]))
$atts[strtolower($m[1])] = stripcslashes($m[2]);
elseif (!empty($m[3]))
$atts[strtolower($m[3])] = stripcslashes($m[4]);
elseif (!empty($m[5]))
$atts[strtolower($m[5])] = stripcslashes($m[6]);
elseif (isset($m[7]) and strlen($m[7]))
$atts[] = stripcslashes($m[7]);
elseif (isset($m[8]))
$atts[] = stripcslashes($m[8]);
}
} else {
$atts = ltrim($text);
}
return $atts;
}
/**
* Combine user attributes with known attributes and fill in defaults when needed.
*
* The pairs should be considered to be all of the attributes which are
* supported by the caller and given as a list. The returned attributes will
* only contain the attributes in the $pairs list.
*
* If the $atts list has unsupported attributes, then they will be ignored and
* removed from the final returned list.
*
* @since 2.5
*
* @param array $pairs Entire list of supported attributes and their defaults.
* @param array $atts User defined attributes in shortcode tag.
* @param string $shortcode Optional. The name of the shortcode, provided for context to enable filtering
* @return array Combined and filtered attribute list.
*/
public function shortcode_atts($pairs, $atts, $shortcode = '') {
$atts = (array) $atts;
$out = array();
foreach ($pairs as $name => $default) {
if (array_key_exists($name, $atts))
$out[$name] = $atts[$name];
else
$out[$name] = $default;
}
if ($shortcode)
$out = apply_filters("shortcode_atts_{$shortcode}", $out, $pairs, $atts);
return $out;
}
/**
* Remove all shortcode tags from the given content.
*
* @since 2.5
* @uses $shortcode_tags
*
* @param string $content Content to remove shortcode tags.
* @return string Content without shortcode tags.
*/
public function strip_shortcodes($content) {
//global $shortcode_tags;
if (empty($this->shortcode_tags) || !is_array($this->shortcode_tags))
return $content;
$pattern = $this->get_shortcode_regex();
return preg_replace_callback("/$pattern/s", 'strip_shortcode_tag', $content);
}
public function strip_shortcode_tag($m) {
// allow [[foo]] syntax for escaping a tag
if ($m[1] == '[' && $m[6] == ']') {
return substr($m[0], 1, -1);
}
return $m[1] . $m[6];
}
}
Когда библиотека создана, приступаем к созданию хелпера, который вызывал бы код вывода галлереи:
shortcode_helper.php - загружаем файл в папку application/helpers/shortcode_helper.php
Код файла:
<?php
if (!defined('BASEPATH')) exit('No direct script access allowed');
$CI = get_instance();
$CI->load->library("shortcodes");
$CI->shortcodes->add_shortcode('fullgallery','get_fullgallery');
$CI->shortcodes->add_shortcode('gallery','get_gallery');
// Вывод всех изображений альбома
function get_gallery($atts) {
global $CI;
extract($CI->shortcodes->shortcode_atts(array('id' => ''), $atts));
// ID альбома
$ids = (int)$id;
// Список всех изображений
$imagelist = $CI->get_gallery_images($ids);
// Если есть список
if($imagelist) {
$images = '<div style="margin: 0 auto; width:720px;">';
// Перебираем изображения
foreach ($imagelist as $image)
$images .= "<a rel='group' href='http://www.vashsait.ru/uploads/gallery/".$ids."/".$image['file_name']."".$image['file_ext']."'><img style='margin:5px;' src='http://www.vashsait.ru/uploads/gallery/".$ids."/_thumbs/".$image['file_name']."".$image['file_ext']."'></a>";
}
$images .="</div>";
return $images;
}
// Вывод всех изображений альбома
function get_fullgallery($atts) {
global $CI;
extract($CI->shortcodes->shortcode_atts(array('id' => ''), $atts));
// ID альбома
$ids = (int)$id;
// Список всех изображений
$imagelist = $CI->get_full_gallery_images($ids);
// Если есть список
if($imagelist) {
$images = '<section class="slider">
<div id="slider" class="flexslider">
<ul class="slides">';
// Перебираем изображения
foreach ($imagelist as $image)
$images .= "<li><img src='http://www.vashadresssaita.ru/uploads/gallery/".$ids."/".$image['file_name']."".$image['file_ext']."'></li>";
}
$images .= '</ul></div>';
if($imagelist) {
$images .= '
<div id="carousel" class="flexslider" style="margin-top: -170px; margin-left: 20px; margin-right: 20px;">
<ul class="slides">';
// Перебираем изображения
foreach ($imagelist as $image2)
$images .= "<li><img style='border:1px solid #fff;' src='http://www.vashadresssaita.ru/uploads/gallery/".$ids."/_thumbs/".$image2['file_name']."".$image2['file_ext']."'></li>";
}
$images .= '</ul></div></section>';
return $images;
}
Вы в принципе можете любой написать код и свои функции, которые по вашему тегу ББ вызывать нужные вам функции.
Готово!
Подключаем функционал к сайту, открываем файл application/config/autoload.php
autoload.php - в этом файле прописываем автозагрузку хелпера shortcode_helper.php
В строке добавляем название хелпера shortcode
$autoload['helper'] = array('shortcode', 'url', 'language', 'array', 'rules', 'widget', 'form_csrf', 'my_url', 'category', 'page', 'cache', 'html', 'javascript', 'security', 'siteinfo', 'form_helper');
Теперь надо чтобы при выводе страницы выводились сами фотографии!!!!
Так как мы данный функционал должны использовать на страницах и категориях сайта, то добавляем в файл application/modules/core/core.php - код.
Я предлагаю подробно не разбирать файл, а заменить его на этот, где у меня описан функционал:
<?php
if (!defined('BASEPATH'))
exit('No direct script access allowed');
/**
* Image CMS
*
* core.php
* @property Cms_base $cms_base
*/
class Core extends MY_Controller {
public $langs = array(); // Langs array
public $def_lang = array(); // Default language array
public $page_content = array(); // Page data
public $cat_content = array(); // Category data
public $settings = array(); // Site settings
public $modules = array(); // Modules array
public $action = '';
public $by_pages = FALSE;
public $cat_page = 0;
public $tpl_data = array();
public $core_data = array('data_type' => null);
public function __construct() {
parent::__construct();
$this->_load_languages();
Modules::$registry['core'] = $this;
$lang = new MY_Lang();
$lang->load('core');
$this->load->library('shortcodes');
}
public function index() {
$page_found = FALSE;
$without_cat = FALSE;
$SLASH = '';
$mod_segment = 1;
$data_type = '';
$com_links = array();
$cat_path = $this->uri->uri_string();
($hook = get_hook('core_init')) ? eval($hook) : NULL;
$this->settings = $this->cms_base->get_settings();
($hook = get_hook('core_settings_loaded')) ? eval($hook) : NULL;
// Set site main template
$this->config->set_item('template', $this->settings['site_template']);
// Load Template library
($hook = get_hook('core_load_template_engine')) ? eval($hook) : NULL;
$this->load->library('template');
if ((!empty($_GET) || strstr($_SERVER['REQUEST_URI'], '?')) && $this->uri->uri_string() == '')
$this->template->registerCanonical(site_url());
$last_element = key($this->uri->uri_to_assoc(0));
if (defined('ICMS_INIT') AND ICMS_INIT === TRUE) {
$data_type = 'bridge';
}
/* Show Analytic codes if some value inserted in admin panel */
$this->load->library('lib_seo')->init($this->settings);
// DETECT LANGUAGE
if ($this->uri->total_segments() >= 1) {
if (array_key_exists($this->uri->segment(1), $this->langs)) {
($hook = get_hook('core_set_lang')) ? eval($hook) : NULL;
$cat_path = substr($cat_path, strlen($this->uri->segment(1)));
// Delete first slash
if (substr($cat_path, 0, 1) == '/')
$cat_path = substr($cat_path, 1);
$uri_lang = $this->uri->segment(1);
$this->config->set_item('language', $this->langs[$uri_lang]['folder']);
$this->lang->load('main', $this->langs[$uri_lang]['folder']);
$this->config->set_item('cur_lang', $this->langs[$uri_lang]['id']);
// Set language template
$this->config->set_item('template', $this->langs[$uri_lang]['template']);
$this->template->set_config_value('tpl_path', TEMPLATES_PATH . $this->langs[$uri_lang]['template'] . '/');
($hook = get_hook('core_changed_tpl_path')) ? eval($hook) : NULL;
$this->load_functions_file($this->langs[$uri_lang]['template']);
// Reload template settings
$this->template->load();
// Add language identificator to base_url
$this->config->set_item('base_url', base_url() . $uri_lang);
$mod_segment = 2;
}
else {
$this->use_def_language();
}
} else {
$this->use_def_language();
}
// End language detect
if ($this->settings['site_offline'] == 'yes') {
if ($this->session->userdata('DX_role_id') != 1) {
($hook = get_hook('core_goes_offline')) ? eval($hook) : NULL;
header('HTTP/1.1 503 Service Unavailable');
$this->template->display('offline');
exit;
}
}
if ($this->uri->segment(1) == $this->def_lang[0]['identif']) {
$url = implode('/', array_slice($this->uri->segment_array(), 1));
header('Location:/' . $url);
}
// Load categories
($hook = get_hook('core_load_lib_category')) ? eval($hook) : NULL;
$this->load->library('lib_category');
$categories = $this->lib_category->build();
$this->tpl_data['categories'] = $categories;
$cats_unsorted = $this->lib_category->unsorted();
// Load modules
$query = $this->cms_base->get_modules();
if ($query->num_rows() > 0) {
$this->modules = $query->result_array();
($hook = get_hook('core_load_modules_urls')) ? eval($hook) : NULL;
foreach ($this->modules as $k) {
$com_links[$k['name']] = '/' . $k['identif'];
}
$this->tpl_data['modules'] = $com_links;
}
// Load auth library
($hook = get_hook('core_load_auth_lib')) ? eval($hook) : NULL;
$this->load->library('DX_Auth');
// Are we on main page?
if (($cat_path == '/' OR $cat_path == FALSE) AND $data_type != 'bridge') {
$data_type = 'main';
($hook = get_hook('core_set_type_main')) ? eval($hook) : NULL;
}
if (is_numeric($last_element) AND is_int($last_element)) {
if (substr($cat_path, -1) == '/')
$cat_path = substr($cat_path, 0, -1);
// Delete page number from path
$cat_path = substr($cat_path, 0, strripos($cat_path, '/'));
$this->by_pages = TRUE;
$this->cat_page = $last_element;
($hook = get_hook('core_enable_pagination')) ? eval($hook) : NULL;
}
if (substr($cat_path, -1) != '/')
$SLASH = '/';
foreach ($cats_unsorted as $cat) {
if ($cat['path_url'] == $cat_path . $SLASH) {
$this->cat_content = $cat;
$data_type = 'category';
($hook = get_hook('core_set_type_category')) ? eval($hook) : NULL;
break;
}
}
if ($data_type != 'main' AND $data_type != 'category' AND $data_type != 'bridge') {
$cat_path_url = substr($cat_path, 0, strripos($cat_path, '/') + 1);
($hook = get_hook('core_try_find_page')) ? eval($hook) : NULL;
// Select page permissions and page data
$this->db->select('content.*');
$this->db->select('CONCAT_WS("", content.cat_url, content.url) as full_url');
$this->db->select('content_permissions.data as roles', FALSE);
$this->db->where('url', $last_element);
$this->db->where('post_status', 'publish');
$this->db->where('publish_date <=', time());
$this->db->where('lang', $this->config->item('cur_lang'));
$this->db->join('content_permissions', 'content_permissions.page_id = content.id', 'left');
// Search page without category
if ($cat_path == $last_element) {
$this->db->where('content.category', 0);
$without_cat = TRUE;
} else {
$this->db->where('content.cat_url', $cat_path_url);
}
($hook = get_hook('core_get_page_query')) ? eval($hook) : NULL;
$query = $this->db->get('content', 1);
if ($query->num_rows() > 0) {
($hook = get_hook('core_page_found')) ? eval($hook) : NULL;
if (substr($cat_path, -1) == '/')
$cat_path = substr($cat_path, 0, -1);
$cat_path = substr($cat_path, 0, strripos($cat_path, '/'));
$page_info = $query->row_array();
$page_info['roles'] = unserialize($page_info['roles']);
if ($without_cat == FALSE) {
// load page and category
foreach ($cats_unsorted as $cat) {
if (($cat['path_url'] == $cat_path . $SLASH) AND ($cat['id'] == $page_info['category'])) {
$page_found = TRUE;
$data_type = 'page';
$this->page_content = $page_info;
$this->cat_content = $cat;
($hook = get_hook('core_set_page_data')) ? eval($hook) : NULL;
break;
}
}
} else {
// display page without category
$data_type = 'page';
$this->page_content = $page_info;
($hook = get_hook('core_set_page_data')) ? eval($hook) : NULL;
($hook = get_hook('core_set_type_nocat')) ? eval($hook) : NULL;
}
} else {
$data_type = '404';
($hook = get_hook('core_type_404')) ? eval($hook) : NULL;
}
}
($hook = get_hook('core_assign_data_type')) ? eval($hook) : NULL;
$this->core_data = array(
'data_type' => $data_type, // Possible values: page/category/main/404
);
// Assign userdata
if ($this->dx_auth->is_logged_in() == TRUE) {
($hook = get_hook('core_user_is_logged_in')) ? eval($hook) : NULL;
$this->tpl_data['is_logged_in'] = TRUE;
$this->tpl_data['username'] = $this->dx_auth->get_username();
}
$agent = $this->user_browser($_SERVER['HTTP_USER_AGENT']);
$this->template->add_array(array(
'agent' => $agent,
));
//Assign captcha type
if ($this->dx_auth->use_recaptcha)
$this->tpl_data['captcha_type'] = 'recaptcha';
else
$this->tpl_data['captcha_type'] = 'captcha';
// Assign template variables and load modules
$this->_process_core_data();
if (strstr($_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'], '//'))
$this->error_404();
// on every page load
\CMSFactory\Events::create()->registerEvent(NULL, 'Core:pageLoaded');
// If module than exit from core and load module
if ($this->is_module($mod_segment) == TRUE)
return TRUE;
switch ($this->settings['main_type']) {
case 'page':
$main_id = $this->settings['main_page_id'];
break;
case 'category':
$main_id = $this->settings['main_page_cat'];
break;
case 'module':
$main_id = $this->settings['main_page_module'];
break;
break;
}
if ($this->core_data['data_type'] == 'main') {
$this->core->core_data['id'] = $main_id;
$this->_mainpage();
} elseif ($this->core_data['data_type'] == 'category') {
$this->core->core_data['id'] = $this->cat_content['id'];
$this->_display_category($this->cat_content);
} elseif ($this->core_data['data_type'] == 'page') {
$this->check_page_access($this->page_content['roles']);
$this->core->core_data['id'] = $this->page_content['id'];
$this->_display_page_and_cat($this->page_content, $this->cat_content);
} elseif ($this->core_data['data_type'] == '404') {
$this->error_404();
} elseif ($this->core_data['data_type'] == 'bridge') {
log_message('debug', 'Bridge initialized.');
}
//you can use if statement in that hook
($hook = get_hook('core_datatype_switch')) ? eval($hook) : NULL;
}
public function get_gallery_images($album_id) {
$this->db->where('album_id', $album_id);
$query = $this->db->get('gallery_images', 4);
if ($query->num_rows() > 0) {
return $query->result_array();
} else {
return FALSE;
}
}
public function get_full_gallery_images($album_id) {
$this->db->where('album_id', $album_id);
$query = $this->db->get('gallery_images');
if ($query->num_rows() > 0) {
return $query->result_array();
} else {
return FALSE;
}
}
/**
* Display main page
*/
function _mainpage() {
/** Register event 'Core:_mainpage' */
\CMSFactory\Events::create()->registerEvent(NULL, 'Core:_mainPage')->runFactory();
switch ($this->settings['main_type']) {
// Load main page
case 'page':
$main_page_id = $this->settings['main_page_id'];
$this->db->where('lang', $this->config->item('cur_lang'));
$this->db->where('id', $main_page_id);
$query = $this->db->get('content', 1);
if ($query->num_rows() == 0) {
$this->db->where('lang', $this->config->item('cur_lang'));
$this->db->where('lang_alias', $main_page_id);
$query = $this->db->get('content', 1);
}
if ($query->num_rows() > 0) {
$page = $query->row_array();
} else {
$this->error(lang("Home page not found.", "core"));
}
// Set page template file
if ($page['full_tpl'] == NULL) {
$page_tpl = 'page_full';
} else {
$page_tpl = $page['full_tpl'];
}
$page['prev_text'] = $this->shortcodes->do_shortcode($page['prev_text']);
$page['full_text'] = $this->shortcodes->do_shortcode($page['full_text']);
($hook = get_hook('core_read_main_page_tpl')) ? eval($hook) : NULL;
$this->template->assign('content', $this->template->read($page_tpl, array('page' => $page)));
($hook = get_hook('core_set_main_page_meta')) ? eval($hook) : NULL;
//$this->set_meta_tags($this->settings['site_title'], $this->settings['site_keywords'], $this->settings['site_description']);
$this->set_meta_tags($page['meta_title'] == NULL ? $page['title'] : $page['meta_title'], $page['keywords'], $page['description']);
($hook = get_hook('core_show_main_page')) ? eval($hook) : NULL;
if (empty($page['main_tpl'])) {
$this->template->show();
} else {
$this->template->display($page['main_tpl']);
}
break;
// Category
case 'category':
($hook = get_hook('core_show_main_cat')) ? eval($hook) : NULL;
$m_category = $this->lib_category->get_category($this->settings['main_page_cat']);
$this->_display_category($m_category);
break;
// Run module as main page
case 'module':
$modName = $this->settings['main_page_module'] . '';
$module = $this->load->module($modName);
if (is_object($module) && method_exists($module, 'index')) {
$module->index();
} else {
$this->error(lang("Module uploading or loading error", "core") . $modName);
}
break;
}
}
/**
* Display page
*/
function _display_page_and_cat($page = array(), $category = array()) {
/** Register event 'Core:_displayPage' */
\CMSFactory\Events::create()->registerEvent($this->page_content, 'Core:_displayPage')->runFactory();
//$this->load->library('typography');
($hook = get_hook('core_disp_page_and_cat')) ? eval($hook) : NULL;
if (empty($page['full_text'])) {
$page['full_text'] = $page['prev_text'];
}
$page['prev_text'] = $this->shortcodes->do_shortcode($page['prev_text']);
$page['full_text'] = $this->shortcodes->do_shortcode($page['full_text']);
if (sizeof($category) > 0) {
// Set page template file
if ($page['full_tpl'] == NULL) {
$page_tpl = $category['page_tpl'];
} else {
$page_tpl = $page['full_tpl'];
}
$tpl_name = $category['main_tpl'];
} else {
if ($page['full_tpl']) {
$page_tpl = $page['full_tpl'];
}
$tpl_name = False;
}
empty($page_tpl) ? $page_tpl = 'page_full' : TRUE;
$this->template->add_array(array(
'page' => $page,
'category' => $category
));
if (!empty($_GET))
$this->template->registerCanonical(site_url());
$this->template->assign('content', $this->template->read($page_tpl));
if ($this->settings['create_description'] == 'auto' && !$page['description']) {
$page['description'] = $this->lib_seo->get_description($page['full_text']);
}
if ($this->settings['create_keywords'] == 'auto' && !$page['keywords']) {
$keywords = $this->lib_seo->get_keywords($page['full_text'], TRUE);
$i = FALSE;
foreach ($keywords as $key => $value) {
if (!$i) {
$page['keywords'] .= $key;
$i = TRUE;
} else {
$page['keywords'] .= ', ' . $key;
}
}
}
$this->set_meta_tags($page['meta_title'] == NULL ? $page['title'] : $page['meta_title'], $page['keywords'], $page['description']);
$this->db->set('showed', 'showed + 1', FALSE);
$this->db->where('id', $page['id']);
$this->db->limit(1);
$this->db->update('content');
if (!empty($page['main_tpl']))
$tpl_name = $page['main_tpl'];
if (!$tpl_name) {
$this->core->core_data['id'] = $page['id'];
$this->template->show();
} else {
$this->template->display($tpl_name);
}
}
// Select or count pages in category
public function _get_category_pages($category = array(), $row_count = 0, $offset = 0, $count = FALSE) {
($hook = get_hook('core_get_category_pages')) ? eval($hook) : NULL;
$this->db->where('post_status', 'publish');
$this->db->where('publish_date <=', time());
$this->db->where('lang', $this->config->item('cur_lang'));
if (count($category['fetch_pages']) > 0) {
$category['fetch_pages'][] = $category['id'];
$this->db->where_in('category', $category['fetch_pages']);
} else {
$this->db->where('category', $category['id']);
}
$this->db->select('content.*');
$this->db->select('CONCAT_WS("", content.cat_url, content.url) as full_url', FALSE);
$this->db->order_by($category['order_by'], $category['sort_order']);
if ($count === FALSE) {
if ($row_count > 0) {
$query = $this->db->get('content', (int) $row_count, (int) $offset);
} else {
$query = $this->db->get('content');
}
} else {
// Return total pages for pagination
($hook = get_hook('core_return_pages_count')) ? eval($hook) : NULL;
$this->db->from('content');
return $this->db->count_all_results();
}
$pages = $query->result_array();
($hook = get_hook('core_return_category_pages')) ? eval($hook) : NULL;
return $pages;
}
/**
* Display category
*/
function _display_category($category = array()) {
/** Register event 'Core:_displayCategory' */
\CMSFactory\Events::create()->registerEvent($this->cat_content, 'Core:_displayCategory')->runFactory();
($hook = get_hook('core_disp_category')) ? eval($hook) : NULL;
$category['fetch_pages'] = unserialize($category['fetch_pages']);
$content = '';
preg_match('/^\d+$/', $this->uri->segment($this->uri->total_segments()), $matches);
if (!empty($matches)) {
$offset = $this->uri->segment($this->uri->total_segments());
$segment = $this->uri->total_segments();
} else {
$offset = 0;
$segment = $this->uri->total_segments() + 1;
}
$offset == FALSE ? $offset = 0 : TRUE;
$row_count = $category['per_page'];
$pages = $this->_get_category_pages($category, $row_count, $offset);
// Count total pages for pagination
$category['total_pages'] = $this->_get_category_pages($category, 0, 0, TRUE);
if ($category['total_pages'] > $category['per_page']) {
$this->load->library('Pagination');
if (array_key_exists($this->uri->segment(1), $this->langs)) {
$config['base_url'] = '/' . $this->uri->segment(1) . "/" . $category['path_url'];
} else {
$config['base_url'] = '/' . $category['path_url'];
}
$config['total_rows'] = $category['total_pages'];
$config['per_page'] = $category['per_page'];
$config['uri_segment'] = $segment;
$config['first_link'] = lang("The first", "core");
$config['last_link'] = lang("Last", "core");
$this->pagination->num_links = 5;
($hook = get_hook('core_dispcat_set_pagination')) ? eval($hook) : NULL;
$this->pagination->initialize($config);
$this->template->assign('pagination', $this->pagination->create_links());
}
// End pagination
($hook = get_hook('core_dispcat_set_category_data')) ? eval($hook) : NULL;
$this->template->assign('category', $category);
$cnt = count($pages);
if ($category['tpl'] == '') {
$cat_tpl = 'category';
} else {
$cat_tpl = $category['tpl'];
}
if ($cnt > 0) {
// Locate category tpl file
if (!file_exists($this->template->template_dir . $cat_tpl . '.tpl')) {
($hook = get_hook('core_dispcat_tpl_error')) ? eval($hook) : NULL;
show_error(lang("Can't locate category template file."));
}
($hook = get_hook('core_dispcat_read_ptpl')) ? eval($hook) : NULL;
$content = $this->template->read($cat_tpl, array('pages' => $pages));
} else {
($hook = get_hook('core_dispcat_no_pages')) ? eval($hook) : NULL;
$content = $this->template->read($cat_tpl, array('no_pages' => lang("In the category has no pages.", "core")));
}
$category['title'] == NULL ? $category['title'] = $category['name'] : TRUE;
($hook = get_hook('core_dispcat_set_meta')) ? eval($hook) : NULL;
// Generate auto meta-tags
if ($this->settings['create_description'] == 'auto' && !$category['description']) {
$category['description'] = $this->lib_seo->get_description($category['short_desc']);
}
if ($this->settings['create_keywords'] == 'auto' && !$category['keywords']) {
$keywords = $this->lib_seo->get_keywords($category['short_desc'], TRUE);
$i = FALSE;
foreach ($keywords as $key => $value) {
if (!$i) {
$category['keywords'] .= $key;
$i = TRUE;
} else {
$category['keywords'] .= ', ' . $key;
}
}
}
// adding page number for pages with pagination (from second page)
$curPage = $this->pagination->cur_page;
if ($curPage > 1) {
$title = $category['title'] . ' - ' . $curPage;
$description = $category['description'] . ' - ' . $curPage;
$this->set_meta_tags($title, $category['keywords'], $description);
} else {
$this->set_meta_tags($category['title'], $category['keywords'], $category['description']);
}
($hook = get_hook('core_dispcat_set_content')) ? eval($hook) : NULL;
$this->template->assign('content', $content);
($hook = get_hook('core_dispcat_show_content')) ? eval($hook) : NULL;
if (!$category['main_tpl']) {
$this->core->core_data['id'] = $category['id'];
$this->template->show();
} else {
$this->core->core_data['id'] = $category['id'];
$this->template->display($category['main_tpl']);
}
}
/**
* Load site languages
*/
public function _load_languages() {
// Load languages
($hook = get_hook('core_load_languages')) ? eval($hook) : NULL;
if (($langs = $this->cache->fetch('main_site_langs')) === FALSE) {
$langs = $this->cms_base->get_langs();
$this->cache->store('main_site_langs', $langs);
}
foreach ($langs as $lang) {
$this->langs[$lang['identif']] = array(
'id' => $lang['id'],
'name' => $lang['lang_name'],
'folder' => $lang['folder'],
'template' => $lang['template']
);
if ($lang['default'] == 1)
$this->def_lang = array($lang);
}
}
/**
* Load and run modules
*/
private function load_modules() {
($hook = get_hook('core_load_modules')) ? eval($hook) : NULL;
foreach ($this->modules as $module) {
if ($module['autoload'] == 1) {
$mod_name = $module['name'];
$this->load->module($mod_name);
if (method_exists($mod_name, 'autoload') === TRUE) {
$this->core_data['module'] = $mod_name;
($hook = get_hook('core_load_module_autoload')) ? eval($hook) : NULL;
// if (!self::$detect_load[$mod_name]) {
$this->$mod_name->autoload();
self::$detect_load[$mod_name] = 1;
// }
}
}
}
// Check url segments
$this->_check_url();
}
/**
* Deny access to modules install/deinstall/rules/etc/ methods
*/
private function _check_url() {
$CI = & get_instance();
($hook = get_hook('core_check_url')) ? eval($hook) : NULL;
$error_text = $this->lang->line('uri_access_deny');
$not_permitted = array('_install', '_deinstall', '_install_rules', 'autoload', '__construct');
$url_segs = $CI->uri->segment_array();
// Deny uri access to all methods like _somename
if (count(explode('/_', $CI->uri->uri_string())) > 1) {
$this->error($error_text, FALSE);
}
if (count($url_segs) > 0) {
foreach ($url_segs as $segment) {
if (in_array($segment, $not_permitted) == TRUE) {
($hook = get_hook('core_checkurl_access_false')) ? eval($hook) : NULL;
$this->error($error_text, FALSE);
}
}
}
return TRUE;
}
private function _process_core_data() {
($hook = get_hook('core_set_tpl_data')) ? eval($hook) : NULL;
$this->template->add_array($this->tpl_data);
$this->load_modules();
return TRUE;
}
/**
* htmlspecialchars_decode text
*
* @return string
*/
function _prepare_content($text = '') {
return htmlspecialchars_decode($text);
}
/**
* Page not found
* Show 404 error
*/
function error_404() {
($hook = get_hook('core_init_error_404')) ? eval($hook) : NULL;
header('HTTP/1.1 404 Not Found');
($hook = get_hook('core_display_error_404')) ? eval($hook) : NULL;
$this->set_meta_tags(lang("Page not found", "core"));
$this->template->assign('error_text', lang("Page not found.", "core"));
$this->template->show('404');
//$this->template->show();
exit;
}
/**
* Display error template end exit
*/
function error($text, $back = TRUE) {
($hook = get_hook('core_display_errors_tpl')) ? eval($hook) : NULL;
$this->template->add_array(array(
'content' => $this->template->read('error', array('error_text' => $text, 'back_button' => $back))
));
$this->template->show();
exit;
}
/**
* Language detection in url segments
*/
function segment($n) {
if (array_key_exists($this->uri->segment(1), $this->langs)) {
$n++;
return $this->uri->segment($n);
}
return $this->uri->segment($n);
}
/**
* Run module
*
* @access private
* @return bool
*/
private function is_module($n) {
$segment = $this->uri->segment($n);
$found = FALSE;
($hook = get_hook('core_is_seg_module')) ? eval($hook) : NULL;
foreach ($this->modules as $k) {
if ($k['identif'] === $segment AND $k['enabled'] == 1) {
$found = TRUE;
$mod_name = $k['identif'];
}
}
if ($found == TRUE) {
//$mod_name = $this->modules[$this->uri->segment($n)];
$mod_function = $this->uri->segment($n + 1);
if ($mod_function == FALSE)
$mod_function = 'index';
$file = APPPATH . 'modules/' . $mod_name . '/' . $mod_function . EXT;
$this->core_data['module'] = $mod_name;
if (file_exists($file)) {
($hook = get_hook('core_run_module_by_seg')) ? eval($hook) : NULL;
// Run module
$func = $this->uri->segment($n + 2);
if ($func == FALSE)
$func = 'index';
$args = $this->grab_variables($n + 3);
$this->load->module($mod_name . '/' . $mod_function);
if (method_exists($mod_function, $func)) {
echo modules::run($mod_name . '/' . $mod_function . '/' . $func, $args);
} else {
$this->error_404();
}
} else {
$args = $this->grab_variables($n + 2);
$this->load->module($mod_name);
if (method_exists($mod_name, $mod_function)) {
echo modules::run($mod_name . '/' . $mod_name . '/' . $mod_function, $args);
} else {
// If method not found display 404 error.
$this->error_404();
}
}
return TRUE;
}
return FALSE;
}
/*
* Check user access for page
*/
function check_page_access($roles) {
($hook = get_hook('core_check_page_access')) ? eval($hook) : NULL;
if ($roles == FALSE OR count($roles) == 0)
return TRUE;
// if (count($roles) == 0) return TRUE;
$access = FALSE;
$logged = $this->dx_auth->is_logged_in();
$my_role = $this->dx_auth->get_role_id();
if ($this->dx_auth->is_admin() === TRUE)
$access = TRUE;
// Check roles access
if ($access != TRUE) {
foreach ($roles as $role) {
if ($role['role_id'] == $my_role)
$access = TRUE;
if ($role['role_id'] == 1 AND $logged == TRUE)
$access = TRUE;
if ($role['role_id'] == '0')
$access = TRUE;
}
}
if ($access == FALSE) {
($hook = get_hook('core_page_access_deny')) ? eval($hook) : NULL;
$this->dx_auth->deny_access('deny');
exit;
}
}
/**
* Grab uri segments to args array
*
* @access public
* @return array
*/
function grab_variables($n) {
$args = array();
foreach ($this->uri->uri_to_assoc($n) as $k => $v) {
if (isset($k))
array_push($args, $k);
if (isset($v))
array_push($args, $v);
}
for ($i = 0, $cnt = count($args); $i < $cnt; $i++) {
if ($args[$i] === FALSE)
unset($args[$i]);
}
return $args;
}
/*
* Use default language
*/
private function use_def_language() {
($hook = get_hook('core_load_def_lang')) ? eval($hook) : NULL;
$this->load_functions_file($this->settings['site_template']);
// Load language variables into template
//$this->template->add_array($this->lang->load('main',$this->def_lang[0]['folder'],TRUE));
// Set config item
$this->config->set_item('language', $this->def_lang[0]['folder']);
// Load Language
$this->lang->load('main', $this->def_lang[0]['folder']);
// Set current language variable
$this->config->set_item('cur_lang', $this->def_lang[0]['id']);
}
private function load_functions_file($tpl_name) {
($hook = get_hook('core_load_functions_php')) ? eval($hook) : NULL;
$full_path = './templates/' . $tpl_name . '/functions.php';
if (file_exists($full_path)) {
include($full_path);
}
}
/**
* Set meta tags for pages
*/
public function set_meta_tags($title = '', $keywords = '', $description = '', $page_number = '', $showsitename = 0, $category = '') {
($hook = get_hook('core_set_meta_tags')) ? eval($hook) : NULL;
if ($this->core_data['data_type'] == 'main') {
$this->template->add_array(array(
'site_title' => empty($this->settings['site_title']) ? $title : $this->settings['site_title'],
'site_description' => empty($this->settings['site_description']) ? $description : $this->settings['site_description'],
'site_keywords' => empty($this->settings['site_keywords']) ? $keywords : $this->settings['site_keywords']
));
} else {
if (($page_number > 1) && ($page_number != '')) {
$title = $page_number . ' - ' . $title;
}
if ($description != '') {
if ($page_number > 1 && $page_number != '') {
$description = "$page_number - $description {$this->settings['delimiter']} {$this->settings['site_short_title']}";
} else {
$description = "$description {$this->settings['delimiter']} {$this->settings['site_short_title']}";
}
}
if ($this->settings['add_site_name_to_cat']) {
if ($category != '') {
$title .= ' - ' . $category;
}
}
if ($this->core_data['data_type'] == 'page' AND $this->page_content['category'] != 0 AND $this->settings['add_site_name_to_cat']) {
$title .= ' ' . $this->settings['delimiter'] . ' ' . $this->cat_content['name'];
}
if (is_array($title)) {
$n_title = '';
foreach ($title as $k => $v) {
$n_title .= $v;
if ($k < count($title) - 1) {
$n_title .= ' ' . $this->settings['delimiter'] . ' ';
}
}
$title = $n_title;
}
if ($this->settings['add_site_name'] == 1 && $showsitename != 1) {
$title .= ' ' . $this->settings['delimiter'] . ' ' . $this->settings['site_short_title'];
}
if ($this->settings['create_description'] == 'empty')
$description = '';
if ($this->settings['create_keywords'] == 'empty')
$keywords = '';
$this->template->add_array(array(
'site_title' => $title,
'site_description' => strip_tags($description),
'site_keywords' => $keywords,
'page_number' => $page_number
));
}
}
private function user_browser($agent) {
preg_match("/(MSIE|Opera|Firefox|Chrome|Version|Opera Mini|Netscape|Konqueror|SeaMonkey|Camino|Minefield|Iceweasel|K-Meleon|Maxthon)(?:\/| )([0-9.]+)/", $agent, $browser_info);
list(, $browser, $version) = $browser_info;
if (preg_match("/Opera ([0-9.]+)/i", $agent, $opera))
return $browserIn = array('0' => 'Opera', '1' => $opera[1]);
if ($browser == 'MSIE') {
preg_match("/(Maxthon|Avant Browser|MyIE2)/i", $agent, $ie); // check to see whether the development is based on IE
if ($ie)
return $browserIn = array('0' => $ie[1], '1' => $version); // If so, it returns an
return $browserIn = array('0' => 'IE', '1' => $version); // otherwise just return the IE and the version number
}
if ($browser == 'Firefox') {
preg_match("/(Flock|Navigator|Epiphany)\/([0-9.]+)/", $agent, $ff); // check to see whether the development is based on Firefox
if ($ff)
return $browserIn = array('0' => $ff[1], '1' => $ff[2]); // if so, shows the number and version
}
if ($browser == 'Opera' && $version == '9.80')
return $browserIn = array('0' => 'Opera', '1' => substr($agent, -5));
if ($browser == 'Version')
return $browserIn = array('0' => 'Safari', '1' => $version); // define Safari
if (!$browser && strpos($agent, 'Gecko'))
return 'Browser based on Gecko'; // unrecognized browser check to see if they are on the engine, Gecko, and returns a message about this
return $browserIn = array('0' => $browser, '1' => $version); // for the rest of the browser and return the version
}
}
/* End of file core.php */