PageRenderTime 56ms CodeModel.GetById 25ms RepoModel.GetById 0ms app.codeStats 1ms

/application/maxsite/templates/default/functions-template.php

https://github.com/dimmaq/MaxSiteCMSTest
PHP | 566 lines | 324 code | 101 blank | 141 comment | 84 complexity | dcadde7d3cdf6b9c2965fa3e41ca1b66 MD5 | raw file
  1. <?php if (!defined('BASEPATH')) exit('No direct script access allowed');
  2. /*
  3. * (c) MaxSite CMS
  4. * http://max-3000.com/
  5. */
  6. # файл functions-template.php
  7. # функции для работы с шаблоном
  8. # не копируйте этот файл в свой шаблон
  9. /*
  10. * ver. 10/04/2012
  11. * ver. 5/02/2012
  12. * ver. 1/02/2012
  13. * ver. 25/01/2012
  14. * ver. 23/01/2012
  15. * ver. 17/01/2012
  16. * ver. 10/01/2012
  17. * ver. 6/01/2012
  18. * ver. 3/01/2012
  19. * ver. 27/12/2011
  20. * ver. 26/12/2011
  21. * ver. 22/12/2011
  22. * ver. 7/12/2011
  23. * ver. 5/12/2011
  24. * ver. 1/12/2011
  25. * ver. 19/11/2011
  26. * ver. 6/11/2011
  27. * ver. 17/10/2011
  28. * ver. 10/09/2011
  29. * ver. 21/08/2011
  30. */
  31. # функция возвращает массив $path_url-файлов по указанному $path - каталог на сервере
  32. # $full_path - нужно ли возвращать полный адрес (true) или только имя файла (false)
  33. # $exts - массив требуемых расширений. По-умолчанию - картинки
  34. if (!function_exists('get_path_files'))
  35. {
  36. function get_path_files($path = '', $path_url = '', $full_path = true, $exts = array('jpg', 'jpeg', 'png', 'gif', 'ico'))
  37. {
  38. // если не указаны пути, то отдаём пустой массив
  39. if (!$path or !$path_url) return array();
  40. if (!is_dir($path)) return array(); // это не каталог
  41. $CI = & get_instance(); // подключение CodeIgniter
  42. $CI->load->helper('directory'); // хелпер для работы с каталогами
  43. $files = directory_map($path, true); // получаем все файлы в каталоге
  44. if (!$files) return array();// если файлов нет, то выходим
  45. $all_files = array(); // результирующий массив с нашими файлами
  46. // функция directory_map возвращает не только файлы, но и подкаталоги
  47. // нам нужно оставить только файлы. Делаем это в цикле
  48. foreach ($files as $file)
  49. {
  50. if (@is_dir($path . $file)) continue; // это каталог
  51. $ext = substr(strrchr($file, '.'), 1);// расширение файла
  52. // расширение подходит?
  53. if (in_array($ext, $exts))
  54. {
  55. if (strpos($file, '_') === 0) continue; // исключаем файлы, начинающиеся с _
  56. // добавим файл в массив сразу с полным адресом
  57. if ($full_path)
  58. $all_files[] = $path_url . $file;
  59. else
  60. $all_files[] = $file;
  61. }
  62. }
  63. natsort($all_files); // отсортируем список для красоты
  64. return $all_files;
  65. }
  66. }
  67. # возвращает файлы для favicon
  68. if (!function_exists('default_favicon'))
  69. {
  70. function default_favicon()
  71. {
  72. $all = get_path_files(getinfo('template_dir') . 'images/favicons/', getinfo('template_url') . 'images/favicons/', false);
  73. return implode($all, '#');
  74. }
  75. }
  76. # возвращает файлы для компонент
  77. if (!function_exists('default_components'))
  78. {
  79. function default_components()
  80. {
  81. static $all = false; // запоминаем результат, чтобы несколько раз не вызывать функцию get_path_files
  82. if ($all === false)
  83. $all = get_path_files(getinfo('template_dir') . 'components/', getinfo('template_url') . 'components/', false, array('php'));
  84. return '0||' . tf('Отсутствует') . '#' . implode($all, '#');
  85. }
  86. }
  87. # возвращает файлы для css-профиля
  88. if (!function_exists('default_profiles'))
  89. {
  90. function default_profiles()
  91. {
  92. $all = get_path_files(getinfo('template_dir') . 'css/profiles/', getinfo('template_url') . 'css/profiles/', false, array('css'));
  93. return implode($all, '#');
  94. }
  95. }
  96. # возвращает файлы для логотипа
  97. if (!function_exists('default_header_logo'))
  98. {
  99. function default_header_logo()
  100. {
  101. $all = get_path_files(getinfo('template_dir') . 'images/logos/', getinfo('template_url') . 'images/logos/', false);
  102. return implode($all, '#');
  103. }
  104. }
  105. # возвращает каталоги в uploads, где могут храниться файлы для шапки
  106. if (!function_exists('default_header_image'))
  107. {
  108. function default_header_image()
  109. {
  110. $CI = & get_instance(); // подключение CodeIgniter
  111. $CI->load->helper('directory'); // хелпер для работы с каталогами
  112. $all_dirs = directory_map(getinfo('uploads_dir'), true); // только в uploads
  113. $dirs = array();
  114. foreach ($all_dirs as $d)
  115. {
  116. // нас интересуют только каталоги
  117. if (is_dir( getinfo('uploads_dir') . $d) and $d != '_mso_float' and $d != 'mini' and $d != '_mso_i' and $d != 'smiles')
  118. {
  119. $dirs[] = $d;
  120. }
  121. }
  122. natsort($dirs);
  123. return '-template-||' . tf('Каталог шаблона') . '#' . implode($dirs, '#');
  124. }
  125. }
  126. # вывод подключенных css-профилей
  127. if (!function_exists('default_out_profiles'))
  128. {
  129. function default_out_profiles()
  130. {
  131. if ($default_profiles = mso_get_option('default_profiles', 'templates', array())) // есть какие-то профили оформления
  132. {
  133. $css_out = '';
  134. foreach($default_profiles as $css_file)
  135. {
  136. $fn = 'css/profiles/' . $css_file;
  137. $css_out .= mso_out_css_file($fn, false, false); // получение и обработка CSS из файла
  138. }
  139. if ($css_out)
  140. echo NR . '<style>' . $css_out . '</style>' . NR;
  141. }
  142. }
  143. }
  144. # функция возвращает полный путь к файлу компоненты для указанной опции
  145. # $option - опция
  146. # $def_file - файл по умолчанию
  147. # пример использования
  148. # if ($fn = get_component_fn('default_header_component2', 'menu.php')) require($fn);
  149. if (!function_exists('get_component_fn'))
  150. {
  151. function get_component_fn($option = '', $def_file = '')
  152. {
  153. if ($fn = mso_get_option($option, 'templates', $def_file)) // получение опции
  154. {
  155. if (file_exists(getinfo('template_dir') . 'components/' . $fn)) // проверяем если файл в наличии
  156. return (getinfo('template_dir') . 'components/' . $fn); // да
  157. else
  158. {
  159. if (file_exists(getinfo('template_dir') . 'components/' . $def_file))
  160. {
  161. if ($def_file) return getinfo('template_dir') . 'components/' . $def_file;
  162. else return false;
  163. }
  164. }
  165. }
  166. return false; // ничего нет
  167. }
  168. }
  169. # функция подключает файлы css-style установленных компонентов и выводит их содержимое в едином блоке <style>
  170. # использовать в head
  171. # $component_options - названия опций, которыми определяются компоненты в шаблоне
  172. # css-файл компонента находится в общем css-каталоге шаблона с именем компонетна, наример menu.php и menu.css
  173. if (!function_exists('out_component_css'))
  174. {
  175. function out_component_css($component_options = array('default_header_component1', 'default_header_component2', 'default_header_component3', 'default_header_component4', 'default_header_component5', 'default_footer_component1', 'default_footer_component2', 'default_footer_component3', 'default_footer_component4', 'default_footer_component5'))
  176. {
  177. // $css_files = array(); // результирующий массив css-файлов
  178. $css_out = ''; // все стили из файлов
  179. // проходимся по всем заданным опциям
  180. foreach($component_options as $option)
  181. {
  182. // и если они определены
  183. if ($fn = mso_get_option($option, 'templates', false))
  184. {
  185. // в имени файла следует заменить расширение php на css
  186. $fn = 'components/css/' . str_replace('.php', '.css', $fn);
  187. $css_out .= mso_out_css_file($fn, false, false); // получение и обработка CSS из файла
  188. }
  189. }
  190. if ($css_out) // если есть что выводить
  191. echo NR . '<style>' . $css_out . '</style>' . NR;
  192. }
  193. }
  194. # типовой вывод секции HEAD
  195. # можно использовать в header.php
  196. if (!function_exists('mso_default_head_section'))
  197. {
  198. function mso_default_head_section($options = array())
  199. {
  200. // ob_start(); # задел на будущее - буферизация
  201. // <!--[if IE]><meta http-equiv="X-UA-Compatible" content="IE=8"><![endif]-->
  202. echo '<!DOCTYPE HTML>
  203. <html><head>' . mso_hook('head-start') . '
  204. <meta charset="UTF-8">
  205. <title>' . mso_head_meta('title') . '</title>
  206. <meta name="generator" content="MaxSite CMS">
  207. <meta name="description" content="' . mso_head_meta('description') . '">
  208. <meta name="keywords" content="' . mso_head_meta('keywords') . '">
  209. <link rel="shortcut icon" href="' . getinfo('template_url') . 'images/favicons/' . mso_get_option('default_favicon', 'templates', 'favicon1.png') . '" type="image/x-icon">
  210. ';
  211. if (mso_get_option('default_canonical', 'templates', 0)) echo mso_link_rel('canonical');
  212. echo NT . '<!-- RSS -->' . NT . mso_rss();
  213. if (file_exists(getinfo('template_dir') . 'custom/head-start.php')) require(getinfo('template_dir') . 'custom/head-start.php');
  214. echo NT . '<!-- CSS -->' . NT . '<link rel="stylesheet" href="';
  215. if (file_exists(getinfo('template_dir') . 'css/css.php')) echo getinfo('template_url') . 'css/css.php';
  216. else
  217. {
  218. if (file_exists(getinfo('template_dir') . 'css/my_style.css')) // если есть css/my_style.css
  219. {
  220. echo getinfo('template_url') . 'css/my_style.css';
  221. }
  222. else
  223. {
  224. if (file_exists(getinfo('template_dir') . 'css/style-all-mini.css')) // если есть style-all-mini.css
  225. {
  226. echo getinfo('template_url') . 'css/style-all-mini.css';
  227. }
  228. elseif (file_exists(getinfo('template_dir') . 'css/style-all.css')) // нет mini, подключаем обычный файл
  229. {
  230. echo getinfo('template_url') . 'css/style-all.css';
  231. }
  232. else echo getinfo('templates_url') . 'default/css/style-all-mini.css';
  233. }
  234. }
  235. echo '">';
  236. // подключение var_style.css
  237. // если есть var_style.php, то используем только его
  238. if (file_exists(getinfo('template_dir') . 'css/var_style.php'))
  239. {
  240. require(getinfo('template_dir') . 'css/var_style.php');
  241. }
  242. else
  243. {
  244. $var_file = '';
  245. if (file_exists(getinfo('template_dir') . 'css/var_style.css'))
  246. $var_file = getinfo('template') . '/css/var_style.css';
  247. elseif (file_exists(getinfo('templates_dir') . 'default/css/var_style.css'))
  248. $var_file = 'default/css/var_style.css';
  249. // если var_style.css нулевой длины, то не подключаем его
  250. if (filesize(getinfo('templates_dir') . $var_file))
  251. echo NT . '<link rel="stylesheet" href="' . getinfo('templates_url') . $var_file . '">';
  252. }
  253. echo NT . '<link rel="stylesheet" href="' . getinfo('template_url') . 'css/print.css" media="print">';
  254. out_component_css();
  255. echo NT . mso_load_jquery();
  256. echo NT . '<!-- plugins -->' . NR;
  257. mso_hook('head');
  258. echo NT . '<!-- /plugins -->' . NR;
  259. default_out_profiles();
  260. mso_add_file('css/add_style.css');
  261. if (file_exists(getinfo('template_dir') . 'custom/head.php')) require(getinfo('template_dir') . 'custom/head.php');
  262. if ($f = mso_page_foreach('head')) require($f);
  263. if (function_exists('ushka')) echo ushka('head');
  264. if (file_exists(getinfo('template_dir') . 'js/my.js'))
  265. echo ' <script src="' . getinfo('template_url') . 'js/my.js"></script>';
  266. if ($my_style = mso_get_option('my_style', 'templates', '')) echo NR . '<!-- custom css-my_style -->' . NR . '<style>' . NR . $my_style . '</style>';
  267. mso_hook('head-end');
  268. /*
  269. # буферизация на будущее
  270. $head = ob_get_contents();
  271. ob_end_clean();
  272. echo $head;
  273. */
  274. echo NR . '</head>';
  275. if (!$_POST) flush();
  276. }
  277. }
  278. /*
  279. Вспомогательная функция mso_section_to_array
  280. преобразование входящего текста опции в массив
  281. по каждой секции по указанному патерну
  282. Вход:
  283. [slide]
  284. link = ссылка изображения
  285. title = подсказка
  286. img = адрес картинки
  287. text = текст с html без переносов. h3 для заголовка
  288. p_line1 = пагинация 1 линия
  289. p_line2 = пагинация 2 линия
  290. [/slide]
  291. Паттерн (по правилам php):
  292. '!\[slide\](.*?)\[\/slide\]!is'
  293. Выход:
  294. Array
  295. (
  296. [0] => Array
  297. (
  298. [link] => ссылка изображения
  299. [title] => подсказка
  300. [img] => адрес картинки
  301. [text] => текст с html без переносов. h3 для заголовка
  302. [p_line1] => пагинация 1 линия
  303. [p_line2] => пагинация 2 линия
  304. )
  305. )
  306. $array_default - стартовый массив опций на случай, если в опции нет обязательного ключа
  307. например
  308. array('link'=>'', 'title'=>'', 'img'=>'', 'text'=>'', 'p_line1'=>'', 'p_line2'=>'')
  309. Если $simple = true, то вхродящий паттерн используется как слово из которого
  310. будет автоматом сформирован корректный паттерн по шаблону [слово]...[/слово]
  311. */
  312. if (!function_exists('mso_section_to_array'))
  313. {
  314. function mso_section_to_array($text, $pattern, $array_default = array(), $simple = false)
  315. {
  316. if ($simple) $pattern = '!\[' . $pattern . '\](.*?)\[\/' . $pattern . '\]!is';
  317. // $array_result - массив каждой секции (0 - все вхождения)
  318. if (preg_match_all($pattern, $text, $array_result))
  319. {
  320. // массив слайдов в $array_result[1]
  321. // преобразуем его в массив полей
  322. $f = array(); // массив для всех полей
  323. $i = 0; // счетчик
  324. foreach($array_result[1] as $val)
  325. {
  326. $val = trim($val);
  327. if (!$val) continue;
  328. $val = str_replace(' = ', '=', $val);
  329. $val = str_replace('= ', '=', $val);
  330. $val = str_replace(' =', '=', $val);
  331. $val = explode("\n", $val); // разделим на строки
  332. $ar_val = array();
  333. $f[$i] = $array_default;
  334. foreach ($val as $pole)
  335. {
  336. $ar_val = explode('=', $pole); // строки разделены = type = select
  337. if ( isset($ar_val[0]) and isset($ar_val[1]))
  338. $f[$i][$ar_val[0]] = $ar_val[1];
  339. }
  340. $i++;
  341. }
  342. return $f;
  343. }
  344. return array(); // не найдено
  345. }
  346. }
  347. # получает css из указанного файла
  348. # в css-файле можно использовать php
  349. # осуществляется сжатие css
  350. # автозамена [TEMPLATE_URL] на url-шаблона
  351. # функция возвращает только стили, без обрамляющего <style>
  352. # Если <style> нужны, то $tag_style = true
  353. # Если нужен сразу вывод в браузер, то $echo = true
  354. if (!function_exists('mso_out_css_file'))
  355. {
  356. function mso_out_css_file($fn, $tag_style = true, $echo = true)
  357. {
  358. $fn = getinfo('template_dir') . $fn;
  359. $out = '';
  360. if (file_exists($fn)) // проверяем если ли файл в наличии
  361. {
  362. if ($r = @file_get_contents($fn)) $out .= $r . NR; // получаем содержимое
  363. if ($out)
  364. {
  365. ob_start();
  366. eval( '?>' . stripslashes($out) . '<?php ');
  367. $out = ob_get_contents();
  368. ob_end_clean();
  369. $out = str_replace('[TEMPLATE_URL]', getinfo('template_url'), $out);
  370. $out = str_replace(array("\r\n", "\r", "\n", "\t", ' ', ' ', ' '), '', $out);
  371. $out = str_replace(array('; ', ' {', ': ', ', '), array(';', '{', ':', ','), $out);
  372. }
  373. if ($tag_style) $out = NR . '<style>' . $out . '</style>' . NR;
  374. if ($echo) echo $out;
  375. }
  376. return $out;
  377. }
  378. }
  379. # формирование <script> с внешним js-файлом или
  380. # формирование <link rel="stylesheet> с внешним css-файлом
  381. # имя файла указывается относительно каталога шаблона
  382. # если файла нет, то ничего не происходит
  383. if (!function_exists('mso_add_file'))
  384. {
  385. function mso_add_file($fn)
  386. {
  387. if (file_exists(getinfo('template_dir') . $fn))
  388. {
  389. $ext = substr(strrchr($fn, '.'), 1);// расширение файла
  390. if ($ext == 'js') echo NT . '<script src="' . getinfo('template_url') . $fn . '"></script>';
  391. elseif ($ext == 'css') echo NT . '<link rel="stylesheet" href="' . getinfo('template_url') . $fn . '">';
  392. elseif ($ext == 'less') echo NT . '<link rel="stylesheet/less" href="' . getinfo('template_url') . $fn . '" type="text/css">';
  393. }
  394. }
  395. }
  396. # получение адреса первой картинки IMG в тексте
  397. # адрес обрабатывается, чтобы сформировать адрес полный (full), миниатюра (mini) и превью (prev)
  398. # результат записит от значения $res
  399. # если $res = true => найденный адрес или $default
  400. # если $res = 'mini' => адрес mini
  401. # если $res = 'prev' => адрес prev
  402. # если $res = 'full' => адрес full
  403. # если $res = 'all' => массив из всех сразу:
  404. # [full] => http://сайт/uploads/image.jpg
  405. # [mini] => http://сайт/uploads/mini/image.jpg
  406. # [prev] => http://сайт/uploads/_mso_i/image.jpg
  407. if (!function_exists('mso_get_first_image_url'))
  408. {
  409. function mso_get_first_image_url($text = '', $res = true, $default = '')
  410. {
  411. $pattern = '!<img.*?src="(.*?)"!i';
  412. //$pattern = '!<img.+src=[\'"]([^\'"]+)[\'"].*>!i';
  413. preg_match_all($pattern, $text, $matches);
  414. //pr($matches);
  415. if (isset($matches[1][0]))
  416. {
  417. $url = $matches[1][0];
  418. if(empty($url)) $url = $default;
  419. }
  420. else
  421. $url = $default;
  422. //_pr($url,1);
  423. if (strpos($url, '/uploads/smiles/') !== false) return ''; // смайлики исключаем
  424. if ($res === true) return $url;
  425. $out = array();
  426. // если адрес не из нашего uploads, то отдаем для всех картинок исходный адрес
  427. if (strpos($url, getinfo('uploads_url')) === false)
  428. {
  429. $out['mini'] = $out['full'] = $out['prev'] = $url;
  430. if ($res == 'mini' or $res == 'prev' or $res == 'full') return $out['mini'];
  431. else return $out;
  432. }
  433. if (strpos($url, '/mini/') !== false) // если в адресе /mini/ - это миниатюра
  434. {
  435. $out['mini'] = $url;
  436. $out['full'] = str_replace('/mini/', '/', $url);
  437. $out['prev'] = str_replace('/mini/', '/_mso_i/', $url);
  438. }
  439. elseif(strpos($url, '/_mso_i/') !== false) // если в адресе /_mso_i/ - это превью 100х100
  440. {
  441. $out['prev'] = $url;
  442. $out['full'] = str_replace('/_mso_i/', '/', $url);
  443. $out['mini'] = str_replace('/_mso_i/', '/mini/', $url);
  444. }
  445. else // обычная картинка
  446. {
  447. $fn = end(explode("/", $url)); // извлекаем имя файла
  448. $out['full'] = $url;
  449. $out['mini'] = str_replace($fn, 'mini/' . $fn, $url);
  450. $out['prev'] = str_replace($fn, '_mso_i/' . $fn, $url);
  451. }
  452. if ($res == 'mini') return $out['mini'];
  453. elseif ($res == 'prev') return $out['prev'];
  454. elseif ($res == 'full') return $out['full'];
  455. else return $out;
  456. }
  457. }
  458. # end file