diff --git a/application/helpers/template_helper.php b/application/helpers/template_helper.php new file mode 100644 index 0000000000..6c23a33e21 --- /dev/null +++ b/application/helpers/template_helper.php @@ -0,0 +1,161 @@ + + * Date: 08.05.13 + */ + +if (!function_exists('include_file')) { + /** + * Рус: Выводит содержимое шаблона внутри другого шаблона + * Анг: Write template content in other template + * @exapmle: {include_file('templatename', array('var1' => 'value1', 'var2' => 'value2'))} + * @param string $filename - имя файла + * @param array $vars - переданные в шаблон переменные + * @return null + */ + function include_file($filename = '', array $vars = array()) { + $CI =& get_instance(); + $templator = $CI->template; + + $filename = (strrpos($filename, '.tpl') == strlen($filename) - 4) ? substr($filename, 0, -4) : $filename; + + $templator->add_array($vars); + $templator->display($filename); + } +} + +if (!function_exists('smarty_make_timestamp')) { + /** + * Рус: Внутренняя функция Smarty по обработке входной строки даты/времени. + * Анг: Smarty-function for processing string parameter for date/time + * @param $string - дата в формате строки или UNIX_TIMESTAMP (из MySQL) + * @return int|string - дата в формате UNIX_TIMESTAMP + */ + function smarty_make_timestamp($string) + { + if(empty($string)) { + $string = "now"; + } + $time = strtotime($string); + if (is_numeric($time) && $time != -1) + return $time; + + // is mysql timestamp format of YYYYMMDDHHMMSS? + if (preg_match('/^\d{14}$/', $string)) { + $time = mktime(substr($string,8,2),substr($string,10,2),substr($string,12,2), + substr($string,4,2),substr($string,6,2),substr($string,0,4)); + + return $time; + } + + // couldn't recognize it, try to return a time + $time = (int) $string; + if ($time > 0) + return $time; + else + return time(); + } +} + +if (!function_exists('date_format_likeuser_rus')) { + /** + * Рус: Выводит время в указанном формате. Во многом аналогичная php функции date, за исключением того, что вывод русифицирован и добавлены новые обозначения в форматной строке. + * Принцип: преимущественно названия выводятся с большой буквы. Если нужны все маленькие (например, "3 января"), то нужно использовать функцию toLowerCase() + * Особенности форматной строки (чем отличается от пхп-функции date): + * M - три первые буквы месяца + * F - полное название месяца в инфинитиве + * f - полное название месяца в родительном падеже + * a - относительная дата (сегодня, вчера) + * A - относительная дата (Сегодня, Вчера) + * D - кратко дни недели (Пн, Вт, ...) + * l - полно дни недели (Понедельник, Вторник, ...) + * Анг: php function date-analog for russian language + * @param $string - дата и время в строковом формате, либо в формате UNIX_TIMESTAMP (из MySQL) + * @param string $format - формат, в котором выводится дата + * @param string $default_format - формат, в котором выводится дата, если предыдущий формат вывести не удалось (если там используется a или A) + * @return string - дата по формату + */ + function date_format_likeuser_rus($string, $format = 'd M Y', $default_format = 'd M Y') { + if ($string == '') return ''; + $timestamp = smarty_make_timestamp($string); + + $rus_words = array( + 'M' => array('code' => 'n', + 'values' => array('', 'Янв', 'Фев', 'Мар', 'Апр', 'Май', 'Июн', 'Июл', 'Авг', 'Сен', 'Окт', 'Ноя', 'Дек'), + ), + 'F' => array('code' => 'n', + 'values' => array('', 'Январь', 'Февраль', 'Март', 'Апрель', 'Май', 'Июнь', 'Июль', 'Август', 'Сентябрь', 'Октябрь', 'Ноябрь', 'Декабрь'), + ), + 'f' => array('code' => 'n', + 'values' => array('', 'Января', 'Февраля', 'Марта', 'Апреля', 'Мая', 'Июня', 'Июля', 'Августа', 'Сентября', 'Октября', 'Ноября', 'Декабря'), + ), + 'a' => array('code' => '', + 'values' => array('cегодня', 'вчера'), + ), + 'A' => array('code' => '', + 'values' => array('Сегодня', 'Вчера'), + ), + 'D' => array('code' => 'w', + 'values' => array('Вс', 'Пн', 'Вт', 'Ср', 'Чт', 'Пт', 'Сб'), + ), + 'l' => array('code' => 'w', + 'values' => array('Воскресенье', 'Понедельник', 'Вторник', 'Среда', 'Четверг', 'Пятница', 'Суббота'), + ), + ); + + $result = ""; + for ($i = 0; $i < strlen($format); $i++) { + $symbol = $format{$i}; + if (array_key_exists($symbol, $rus_words)) { + if (!empty($rus_words[$symbol]['code'])) { + $id = date($rus_words[$symbol]['code'], $timestamp); + if (is_numeric($id) && array_key_exists($id, $rus_words[$symbol]['values'])) { + $result .= $rus_words[$symbol]['values'][$id]; + } + } else { + $id = 2; + $today = mktime(0, 0, 0, date('m'), date('d'), date('Y')); + if ($timestamp >= $today) { + $id = 0; + } elseif ($timestamp >= $today - 86400) { + $id = 1; + } + + if (array_key_exists($id, $rus_words[$symbol]['values'])) { + $result .= $rus_words[$symbol]['values'][$id]; + } else { + $format = str_replace($symbol, $default_format, $format); + $i--; + } + } + } else { + $result .= date($symbol, $timestamp); + } + } + + return $result; + } +} + +if (!function_exists('cutLongWords')) { + /** + * Рус: обрезает длинные слова, подставляя в конце "..." + * Анг: cut long words + * @param $text - текст, который нужно уберечь от длинных слов + * @param int $max_long - разрешённая длина слова + * @param string $replace - шаблон замены обрезанной части. Тут ?0 означает всё слово целиком, а ?1 - необрезанная часть (начинается с ?, так как движок imageCMS ругается, если использовать знак $ в шаблоне, даже если в строке). + * @return mixed|string + */ + function cutLongWords($text, $max_long = 10, $replace = '?1...') { + if (!is_string($text)) { + $text = (string)$text; + } + $max_long = (int)$max_long; + if ($max_long <= 0) return $text; + if (!is_string($replace)) { + $replace = '?1...'; + } + $replace = preg_replace('/\?(\d+)/', '\$$1', $replace); + return preg_replace('/([^\s]{' . $max_long . '})[^\s]+/', $replace, $text); + } +} \ No newline at end of file diff --git a/application/modules/CMSFactory/assetManager.php b/application/modules/CMSFactory/assetManager.php index a859d6ac82..afea2002b9 100755 --- a/application/modules/CMSFactory/assetManager.php +++ b/application/modules/CMSFactory/assetManager.php @@ -7,9 +7,11 @@ */ class assetManager { + public $useCompress = false; + public $activePattern = null; + protected static $_BehaviorInstance; protected $callMapp = null; - protected $useCompress = false; private function __construct() { @@ -62,28 +64,28 @@ public function appendData($item, $value) { * @return assetManager * @access public * @author Kaero - * @param type $name - * @param type $useCompress + * @param string $name + * @param string $pattern * @return \CMSFactory\assetManager * @copyright ImageCMS (c) 2013, Kaero */ - public function registerScript($name, $useCompress = FALSE) { + public function registerScript($name, $pattern = 'default') { /** Start. Load JS file into template */ - if ($useCompress) - \CI_Controller::get_instance()->template->registerJsScript('', 'after'); + if ($this->useCompress) + \CI_Controller::get_instance()->template->registerJsScript('', 'after'); else - \CI_Controller::get_instance()->template->registerJsFile($this->buildScriptPath($name), 'after'); + \CI_Controller::get_instance()->template->registerJsFile($this->buildScriptPath($name, $pattern), 'after'); return $this; } - public function registerScriptWithoutTemplate($name){ - $script = '/' . $this->buildScriptPath($name); + public function registerScriptWithoutTemplate($name, $pattern = 'default') { + $script = '/' . $this->buildScriptPath($name, $pattern); $this->setData(array($name=>$script)); } - public function registerStyleWithoutTemplate($name){ - $script = '/' . $this->buildStylePath($name); + public function registerStyleWithoutTemplate($name, $pattern = 'default') { + $script = '/' . $this->buildStylePath($name, $pattern); $this->setData(array($name=>$script)); } @@ -92,14 +94,13 @@ public function registerStyleWithoutTemplate($name){ * @return assetManager * @access public * @author a.gula - * @param type $script - * @param type $useCompress + * @param string $script * @return \CMSFactory\assetManager * @copyright ImageCMS (c) 2013, a.gula */ - public function registerJsScript($script, $useCompress = FALSE) { + public function registerJsScript($script) { /** Start. Load JS script into template */ - if ($useCompress) + if ($this->useCompress) \CI_Controller::get_instance()->template->registerJsScript('', 'after'); else \CI_Controller::get_instance()->template->registerJsScript('', 'after'); @@ -111,17 +112,17 @@ public function registerJsScript($script, $useCompress = FALSE) { * @return assetManager * @access public * @author Kaero - * @param type $name - * @param type $useCompress + * @param string $name + * @param string $pattern * @return \CMSFactory\assetManager * @copyright ImageCMS (c) 2013, Kaero */ - public function registerStyle($name, $useCompress = FALSE) { + public function registerStyle($name, $pattern = 'default') { /** Start. Load file into template */ - if ($useCompress) - \CI_Controller::get_instance()->template->registerCss('', 'before'); + if ($this->useCompress) + \CI_Controller::get_instance()->template->registerCss('', 'before'); else - \CI_Controller::get_instance()->template->registerCssFile($this->buildStylePath($name), 'before'); + \CI_Controller::get_instance()->template->registerCssFile($this->buildStylePath($name, $pattern), 'before'); return $this; } @@ -131,13 +132,12 @@ public function registerStyle($name, $useCompress = FALSE) { * @return assetManager * @access public * @author a.gula - * @param type $css - * @param type $useCompress + * @param string $css * @copyright ImageCMS (c) 2013, a.gula */ - public function registerStyleStr($css, $useCompress = FALSE) { + public function registerStyleStr($css) { /** Start. Load file into template */ - if ($useCompress) + if ($this->useCompress) \CI_Controller::get_instance()->template->registerCss('', 'before'); else \CI_Controller::get_instance()->template->registerCss('', 'before'); @@ -156,7 +156,7 @@ public function registerStyleStr($css, $useCompress = FALSE) { public function renderAdmin($tpl) { try { /** Start. If file doesn't exists thorow exception */ - file_exists($this->buildAdminTemplatePath($tpl) . '.tpl') OR throwException(sprintf('Can\'t load template file: %s/assets/admin/%s.tpl', $this->getTrace(), $tpl)); + file_exists($this->buildTemplatePath($tpl, 'admin') . '.tpl') OR throwException(sprintf('Can\'t load template file: %s/assets/admin/%s.tpl', $this->getTrace(), $tpl)); /** Start. Load template file */ \CI_Controller::get_instance()->template->show('file:' . $this->buildAdminTemplatePath($tpl)); @@ -173,13 +173,13 @@ public function renderAdmin($tpl) { * @author Kaero * @copyright ImageCMS (c) 2013, Kaero */ - public function render($tpl, $ignoreWrap = FALSE) { + public function render($tpl, $ignoreWrap = FALSE, $pattern = 'default') { try { /** Start. If file doesn't exists thorow exception */ - file_exists($this->buildTemplatePath($tpl) . '.tpl') OR throwException(sprintf('Can\'t load template file: %s/assets/%s.tpl', $this->getTrace(), $tpl)); + file_exists($this->buildTemplatePath($tpl, $pattern) . '.tpl') OR throwException(sprintf('Can\'t load template file: %s/assets/%s.tpl', $this->getTrace(), $tpl)); /** Start. Load template file */ - \CI_Controller::get_instance()->template->show('file:' . $this->buildTemplatePath($tpl), !$ignoreWrap); + \CI_Controller::get_instance()->template->show('file:' . $this->buildTemplatePath($tpl, $pattern), !$ignoreWrap); } catch (\Exception $exc) { log_message('error', $exc->getMessage()); show_error($exc->getMessage(), 500, 'An Template Error Was Encountered'); @@ -188,18 +188,18 @@ public function render($tpl, $ignoreWrap = FALSE) { /** Render public view * @param string $tpl Template file name - * @return void + * @return string * @access public * @author Kaero * @copyright ImageCMS (c) 2013, Kaero */ - public function fetchTemplate($tpl) { + public function fetchTemplate($tpl, $pattern = 'default') { try { /** Start. If file doesn't exists thorow exception */ - file_exists($this->buildTemplatePath($tpl) . '.tpl') OR throwException('Can\'t load template file: ' . $paths . DIRECTORY_SEPARATOR . $tpl . '.tpl'); + file_exists($this->buildTemplatePath($tpl, $pattern) . '.tpl') OR throwException('Can\'t load template file: ' . $paths /* ?? what is $paths ?? */ . DIRECTORY_SEPARATOR . $tpl . '.tpl'); /** Start. Return template file */ - return \CI_Controller::get_instance()->template->fetch('file:' . $this->buildTemplatePath($tpl)); + return \CI_Controller::get_instance()->template->fetch('file:' . $this->buildTemplatePath($tpl, $pattern)); } catch (\Exception $exc) { log_message('error', $exc->getMessage()); show_error($exc->getMessage(), 500, 'An Template Error Was Encountered'); @@ -249,43 +249,43 @@ private function getTrace($list = 'first_file') { * @access private * @copyright ImageCMS (c) 2013, Kaero */ - private function buildTemplatePath($tpl) { - return sprintf('%smodules/%s/assets/%s', APPPATH, $this->getTrace(), $tpl); + private function buildTemplatePath($tpl, $pattern) { + return sprintf('%smodules/%s/assets%s/%s', APPPATH, $this->getTrace(), $this->processingPatternName($pattern), $tpl); } /** - * Return formated path + * Return formated path for JS - script files * @return string * @access private * @copyright ImageCMS (c) 2013, Kaero */ - private function buildAdminTemplatePath($tpl) { - return sprintf('%smodules/%s/assets/admin/%s', APPPATH, $this->getTrace(), $tpl); + private function buildScriptPath($tpl, $pattern) { + return sprintf('%smodules/%s/assets%s/js/%s.js', APPPATH, $this->getTrace(), $this->processingPatternName($pattern), $tpl); } /** - * Return formated path for JS - script files + * Return formated path for css * @return string * @access private * @copyright ImageCMS (c) 2013, Kaero */ - private function buildScriptPath($tpl) { - return sprintf('%smodules/%s/assets/js/%s.js', APPPATH, $this->getTrace(), $tpl); + private function buildStylePath($tpl, $pattern) { + return sprintf('%smodules/%s/assets%s/css/%s.css', APPPATH, $this->getTrace(), $this->processingPatternName($pattern), $tpl); } /** - * Return formated path for css + * Return formatted pattern name for include it in file path + * @param string $pattern * @return string - * @access private - * @copyright ImageCMS (c) 2013, Kaero */ - private function buildStylePath($tpl) { - return sprintf('%smodules/%s/assets/css/%s.css', APPPATH, $this->getTrace(), $tpl); + private function processingPatternName($pattern) { + if (is_string($this->activePattern)) $pattern = $this->activePattern; + return !is_string($pattern) || empty($pattern) ? '' : '/' . trim($pattern, '\//'); } /** * Compressing js file - * @param type $js text of js + * @param string $js text of js * @copyright ImageCMS (c) 2013, a.gula */ private function compressJs($js) { @@ -301,18 +301,17 @@ private function compressJs($js) { /** * Compressing css file - * @param type $css text of css file + * @param string $css text of css file * @copyright ImageCMS (c) 2013, a.gula */ private function compressCss($css) { $css = preg_replace('#\s+#', ' ', $css); $css = preg_replace('#/\*.*?\*/#s', '', $css); - $css = str_replace('; ', ';', $css); - $css = str_replace(': ', ':', $css); - $css = str_replace(' {', '{', $css); - $css = str_replace('{ ', '{', $css); - $css = str_replace(', ', ',', $css); - $css = str_replace('} ', '}', $css); + foreach (str_split(';:{},') as $symbol) { + $css = str_replace(' ' . $symbol, $symbol, $css); + $css = str_replace($symbol . ' ', $symbol, $css); + } + $css = str_replace('- ', '-', $css); $css = str_replace(';}', '}', $css); return $css;