BxDolTemplate.php 97 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677
  1. <?php defined('BX_DOL') or die('hack attempt');
  2. /**
  3. * Copyright (c) UNA, Inc - https://una.io
  4. * MIT License - https://opensource.org/licenses/MIT
  5. *
  6. * @defgroup UnaCore UNA Core
  7. * @{
  8. */
  9. ini_set('pcre.backtrack_limit', 1000000);
  10. define('BX_DOL_TEMPLATE_CODE_KEY', 'skin');
  11. define('BX_DOL_TEMPLATE_DEFAULT_CODE', 'protean');
  12. define('BX_DOL_TEMPLATE_FOLDER_ROOT', 'template');
  13. define('BX_DOL_TEMPLATE_INJECTIONS_CACHE', 'sys_injections.inc');
  14. define('BX_DOL_TEMPLATE_CHECK_IN_BOTH', 'both');
  15. define('BX_DOL_TEMPLATE_CHECK_IN_BASE', 'base');
  16. define('BX_DOL_TEMPLATE_CHECK_IN_TMPL', 'tmpl');
  17. define('BX_DOL_COLOR_BG', 'bg');
  18. define('BX_DOL_COLOR_FT', 'ft');
  19. define('BX_PAGE_DEFAULT', 0); ///< default, regular page
  20. define('BX_PAGE_CLEAR', 2); ///< clear page, without any headers and footers
  21. define('BX_PAGE_POPUP', 44); ///< popup page, without any headers and footers
  22. define('BX_PAGE_TRANSITION', 150); ///< transition page with redirect to display some msg, like 'please wait', without headers footers
  23. /**
  24. * Template engine.
  25. *
  26. * An object of the class allows to:
  27. * 1. Manage HTML templates.
  28. * 2. Get URL/path for any template image/icon.
  29. * 3. Attach CSS/JavaScript files to the output.
  30. * 4. Add some content to any template key using Injection engine.
  31. *
  32. *
  33. * Avalable constructions.
  34. * 1. &lt;bx_include_auto:template_name.html /&gt; - the content of the file would be inserted. File would be taken from current template if it existes there, and from base directory otherwise.
  35. * 2. &lt;bx_include_base:template_name.html /&gt; - the content of the file would be inserted. File would be taken from base directory.
  36. * 3. &lt;bx_include_tmpl:template_name.html /&gt; - the content of the file would be inserted. File would be taken from tmpl_xxx directory.
  37. * 4. &lt;bx_url_root /&gt; - the value of BX_DOL_URL_ROOT variable will be inserted.
  38. * 5. &lt;bx_url_admin /&gt; - the value of BX_DOL_URL_ADMIN variable will be inserted.
  39. * 6. &lt;bx_text:_language_key /&gt; - _language_key will be translated using language file(function _t()) and inserted.
  40. &lt;bx_text_js:_language_key /&gt; - _language_key will be translated using language file(function _t()) and inserted, use it to insert text into js string.
  41. &lt;bx_text_attribute:_language_key /&gt; - _language_key will be translated using language file(function _t()) and inserted, use it to insert text into html attribute.
  42. * 7. &lt;bx_image_url:image_file_name /&gt; - image with 'image_file_name' file name will be searched in the images folder of current template.
  43. * If it's not found, then it will be searched in the images folder of base template. On success full URL will be inserted, otherwise an empty string.
  44. * 8. &lt;bx_icon_url:icon_file_name /&gt; - the same with &lt;bx_image_url:image_file_name /&gt;, but icons will be searched in the images/icons/ folders.
  45. * 9. &lt;bx_injection:injection_name /&gt; - will be replaced with injections registered with the page and injection_name in the `sys_injections`/`sys_injections_admin`/ tables.
  46. * 10. &lt;bx_if:tag_name&gt;some_HTML&lt;/bx_if:tag_name&gt; - will be replaced with provided content if the condition is true, and with empty string otherwise.
  47. * 11. &lt;bx_repeat:cycle_name&gt;some_HTML&lt;/bx_repeat:cycle_name&gt; - an inner HTML content will be repeated in accordance with received data.
  48. *
  49. *
  50. * Related classes:
  51. * BxDolTemplateAdmin - for processing admin templates.
  52. * Template classes in modules - for processing modiles' templates.
  53. *
  54. *
  55. * Global variables:
  56. * oSysTemplate - is used for template processing in user part.
  57. * oAdmTemplate - is used for template processing in admin part.
  58. *
  59. *
  60. * Add injection:
  61. * 1. Register it in the `sys_injections` table or `sys_injections_admin` table for admin panel.
  62. * 2. Clear injections cache(sys_injections.inc and sys_injections_admin.inc in cache folder).
  63. *
  64. *
  65. * Predefined template keys to add injections:
  66. * 1. injection_head - add injections in the &lt;head&gt; tag.
  67. * 2. injection_body - add ingection(attribute) in the &lt;body&gt; tag.
  68. * 3. injection_header - add injection inside the &lt;body&gt; tag at the very beginning.
  69. * 4. injection_logo_before - add injection at the left of the main logo(inside logo's DIV).
  70. * 5. injection_logo_after - add injection at the right of the main logo(inside logo's DIV).
  71. * 6. injection_between_logo_top_menu - add injection between logo and top menu.
  72. * 7. injection_top_menu_before - add injection at the left of the top menu(inside top menu's DIV).
  73. * 8. injection_top_menu_after - add injection at the right of the top menu(inside top menu's DIV).
  74. * 13. injection_content_before - add injection just before main content(inside content's DIV).
  75. * 14. injection_content_after - add injection just after main content(inside content's DIV).
  76. * 15. injection_between_content_footer - add injection between content and footer.
  77. * 16. injection_footer_before - add injection at the left of the footer(inside footer's DIV).
  78. * 17. injection_footer_after - add injection at the right of the footer(inside footer's DIV).
  79. * 18. injection_footer - add injection inside the &lt;body&gt; tag at the very end.
  80. *
  81. *
  82. * Example of usage:
  83. * @code
  84. * $oSysTemplate = BxDolTemplate::getInstance();
  85. *
  86. * $oSysTemplate->addCss(array('test1.css', 'test2.css'));
  87. * $oSysTemplate->addJs(array('test1.js', 'test2.js'));
  88. * $oSysTemplate->parseHtmlByName('messageBox.html', array(
  89. * 'id' => $iId,
  90. * 'msgText' => $sText,
  91. * 'bx_if:timer' => array(
  92. * 'condition' => $iTimer > 0,
  93. * 'content' => array(
  94. * 'id' => $iId,
  95. * 'time' => 1000 * $iTimer,
  96. * 'on_close' => $sOnClose,
  97. * )
  98. * ),
  99. * 'bx_if:timer' => array(
  100. * array(
  101. * 'name' => $sName,
  102. * 'title' => $sTitle
  103. * ),
  104. * array(
  105. * 'name' => $sName,
  106. * 'title' => $sTitle
  107. * )
  108. * )
  109. * ));
  110. * @endcode
  111. *
  112. *
  113. * Memberships/ACL:
  114. * Doesn't depend on user's membership.
  115. *
  116. *
  117. * Alerts:
  118. * no alerts available
  119. *
  120. */
  121. class BxDolTemplate extends BxDolFactory implements iBxDolSingleton
  122. {
  123. protected static $_aColors = array(
  124. 'red1' => array(216, 9, 96),
  125. 'red1-dark' => array(194, 7, 86),
  126. 'red2' => array(231, 68, 30),
  127. 'red2-dark' => array(207, 60, 25),
  128. 'red3' => array(243, 143, 0),
  129. 'red3-dark' => array(218, 128, 0),
  130. 'green1' => array(96, 174, 0),
  131. 'green1-dark' => array(86, 156, 0),
  132. 'green2' => array(209, 211, 0),
  133. 'green2-dark' => array(186, 188, 0),
  134. 'green3' => array(48, 116, 36),
  135. 'green3-dark' => array(43, 104, 32),
  136. 'blue1' => array(10, 61, 143),
  137. 'blue1-dark' => array(9, 54, 128),
  138. 'blue2' => array(0, 164, 165),
  139. 'blue2-dark' => array(0, 146, 148),
  140. 'blue3' => array(0, 160, 206),
  141. 'blue3-dark' => array(0, 143, 184),
  142. 'gray' => array(97, 97, 97),
  143. 'gray-dark' => array(87, 87, 87)
  144. );
  145. /**
  146. * Main fields
  147. */
  148. protected $_sName;
  149. protected $_sPrefix;
  150. protected $_sRootPath;
  151. protected $_sRootUrl;
  152. protected $_sSubPath;
  153. protected $_sInjectionsTable;
  154. protected $_sInjectionsCache;
  155. protected $_sCode;
  156. protected $_sCodeKey;
  157. protected $_sKeyWrapperHtml;
  158. protected $_sFolderHtml;
  159. protected $_sFolderCss;
  160. protected $_sFolderImages;
  161. protected $_sFolderIcons;
  162. protected $_aTemplates;
  163. protected $_aLocations;
  164. protected $_aLocationsJs;
  165. /**
  166. * Cache related fields
  167. */
  168. protected $_bCacheEnable;
  169. protected $_sCacheFolderUrl;
  170. protected $_sCachePublicFolderUrl;
  171. protected $_sCachePublicFolderPath;
  172. protected $_sCacheFilePrefix;
  173. protected $_bImagesInline;
  174. protected $_iImagesMaxSize;
  175. protected $_bCssCache;
  176. protected $_bCssMinify;
  177. protected $_bCssArchive;
  178. protected $_sCssCachePrefix;
  179. protected $_bJsCache;
  180. protected $_bJsMinify;
  181. protected $_bJsArchive;
  182. protected $_sJsCachePrefix;
  183. /**
  184. * Less related fields
  185. */
  186. protected $_bLessEnable;
  187. protected $_sLessCachePrefix;
  188. protected $aPage;
  189. protected $aPageContent;
  190. protected $_oTemplateConfig;
  191. protected $_oTemplateFunctions;
  192. /**
  193. * Constructor
  194. */
  195. protected function __construct($sRootPath = BX_DIRECTORY_PATH_ROOT, $sRootUrl = BX_DOL_URL_ROOT)
  196. {
  197. if (isset($GLOBALS['bxDolClasses'][get_class($this)]))
  198. trigger_error ('Multiple instances are not allowed for the class: ' . get_class($this), E_USER_ERROR);
  199. parent::__construct();
  200. $this->_sPrefix = 'BxDolTemplate';
  201. $this->_sRootPath = $sRootPath;
  202. $this->_sRootUrl = $sRootUrl;
  203. $this->_sInjectionsTable = 'sys_injections';
  204. $this->_sInjectionsCache = BX_DOL_TEMPLATE_INJECTIONS_CACHE;
  205. $this->_sCodeKey = BX_DOL_TEMPLATE_CODE_KEY;
  206. list(
  207. $this->_sCode,
  208. $this->_sName,
  209. $this->_sSubPath
  210. ) = self::retrieveCode($this->_sCodeKey, $this->_sRootPath);
  211. if (!$this->_sSubPath)
  212. $this->_sSubPath = 'boonex/' . BX_DOL_TEMPLATE_DEFAULT_CODE . '/';
  213. if (!file_exists(BX_DIRECTORY_PATH_MODULES . $this->_sSubPath)) // just for 8.0.0-A6 upgrade
  214. $this->_sSubPath = 'boonex/uni/';
  215. if(isset($_GET[$this->_sCodeKey])) {
  216. if(BxDolPermalinks::getInstance()->redirectIfNecessary(array($this->_sCodeKey)))
  217. exit;
  218. }
  219. $this->_sKeyWrapperHtml = '__';
  220. $this->_sFolderHtml = '';
  221. $this->_sFolderCss = 'css/';
  222. $this->_sFolderImages = 'images/';
  223. $this->_sFolderIcons = 'images/icons/';
  224. $this->_aTemplates = array('html_tags', 'menu_item_addon');
  225. $this->addLocation('system', $this->_sRootPath, $this->_sRootUrl);
  226. $this->addLocationJs('system_inc_js', BX_DIRECTORY_PATH_INC . 'js/' , BX_DOL_URL_ROOT . 'inc/js/');
  227. $this->addLocationJs('system_inc_js_classes', BX_DIRECTORY_PATH_INC . 'js/classes/' , BX_DOL_URL_ROOT . 'inc/js/classes/');
  228. $this->addLocationJs('system_plugins_public', BX_DIRECTORY_PATH_PLUGINS_PUBLIC, BX_DOL_URL_PLUGINS_PUBLIC);
  229. $this->_bCacheEnable = !defined('BX_DOL_CRON_EXECUTE') && getParam('sys_template_cache_enable') == 'on';
  230. $this->_sCacheFolderUrl = '';
  231. $this->_sCachePublicFolderUrl = BX_DOL_URL_CACHE_PUBLIC;
  232. $this->_sCachePublicFolderPath = BX_DIRECTORY_PATH_CACHE_PUBLIC;
  233. $this->_sCacheFilePrefix = "bx_templ_";
  234. $this->_bImagesInline = getParam('sys_template_cache_image_enable') == 'on';
  235. $this->_iImagesMaxSize = (int)getParam('sys_template_cache_image_max_size') * 1024;
  236. $bArchive = getParam('sys_template_cache_compress_enable') == 'on';
  237. $this->_bCssCache = !defined('BX_DOL_CRON_EXECUTE') && getParam('sys_template_cache_css_enable') == 'on';
  238. $this->_bCssMinify = $this->_bCssCache && getParam('sys_template_cache_minify_css_enable') == 'on';
  239. $this->_bCssArchive = $this->_bCssCache && $bArchive;
  240. $this->_sCssCachePrefix = $this->_sCacheFilePrefix . 'css_';
  241. $this->_bJsCache = !defined('BX_DOL_CRON_EXECUTE') && getParam('sys_template_cache_js_enable') == 'on';
  242. $this->_bJsMinify = $this->_bJsCache && getParam('sys_template_cache_minify_js_enable') == 'on';
  243. $this->_bJsArchive = $this->_bJsCache && $bArchive;
  244. $this->_sJsCachePrefix = $this->_sCacheFilePrefix . 'js_';
  245. $this->_bLessEnable = true;
  246. $this->_sLessCachePrefix = $this->_sCacheFilePrefix . 'less_';
  247. $this->aPage = array();
  248. $this->aPageContent = array();
  249. }
  250. /**
  251. * Prevent cloning the instance
  252. */
  253. public function __clone()
  254. {
  255. if (isset($GLOBALS['bxDolClasses'][get_class($this)]))
  256. trigger_error('Clone is not allowed for the class: ' . get_class($this), E_USER_ERROR);
  257. }
  258. /**
  259. * Get singleton instance of the class
  260. */
  261. public static function getInstance()
  262. {
  263. if(!isset($GLOBALS['bxDolClasses'][__CLASS__])) {
  264. $GLOBALS['bxDolClasses'][__CLASS__] = new BxDolTemplate();
  265. $GLOBALS['bxDolClasses'][__CLASS__]->init();
  266. }
  267. return $GLOBALS['bxDolClasses'][__CLASS__];
  268. }
  269. /**
  270. * Retrieve template code and check whether it's associated with active template or not.
  271. *
  272. * @param string $sCodeKey template's code key.
  273. * @param string $sRootPath path to root directory.
  274. */
  275. public static function retrieveCode($sCodeKey = BX_DOL_TEMPLATE_CODE_KEY, $sRootPath = BX_DIRECTORY_PATH_ROOT)
  276. {
  277. $fCheckCode = function($sCode, $bSetCookie) use($sCodeKey, $sRootPath) {
  278. if(empty($sCode) || !preg_match('/^[A-Za-z0-9_-]+$/', $sCode))
  279. return false;
  280. $aModule = BxDolModuleQuery::getInstance()->getModuleByUri($sCode);
  281. if(empty($aModule) || !is_array($aModule) || (int)$aModule['enabled'] != 1 || !file_exists($sRootPath . 'modules/' . $aModule['path'] . 'data/template/'))
  282. return false;
  283. $oConfig = new BxDolModuleConfig($aModule);
  284. $aResult = array(
  285. $oConfig->getUri(), //--- Template module's URI is used as template Code.
  286. $oConfig->getName(),
  287. $oConfig->getDirectory()
  288. );
  289. if(!$bSetCookie || bx_get('preview'))
  290. return $aResult;
  291. $aUrl = parse_url(BX_DOL_URL_ROOT);
  292. $sPath = isset($aUrl['path']) && !empty($aUrl['path']) ? $aUrl['path'] : '/';
  293. setcookie($sCodeKey, $sCode, time() + 60*60*24*365, $sPath);
  294. return $aResult;
  295. };
  296. $sCode = getParam('template');
  297. if(empty($sCode))
  298. $sCode = BX_DOL_TEMPLATE_DEFAULT_CODE;
  299. $aResult = $fCheckCode($sCode, false);
  300. //--- Check selected template in COOKIE(the lowest priority) ---//
  301. $sCode = !empty($_COOKIE[$sCodeKey]) ? $_COOKIE[$sCodeKey] : '';
  302. $aResultCheck = $fCheckCode($sCode, false);
  303. if($aResultCheck !== false)
  304. $aResult = $aResultCheck;
  305. //--- Check selected template in GET(the highest priority) ---//
  306. $sCode = !empty($_GET[$sCodeKey]) ? $_GET[$sCodeKey] : '';
  307. $aResultCheck = $fCheckCode($sCode, true);
  308. if($aResultCheck !== false)
  309. $aResult = $aResultCheck;
  310. return $aResult;
  311. }
  312. public static function getColorCode($mixedName = false, $fOpacity = false)
  313. {
  314. $aClasses = array_keys(self::$_aColors);
  315. if($mixedName === false || (is_string($mixedName) && !is_numeric($mixedName) && !in_array($mixedName, $aClasses)))
  316. $mixedName = $aClasses[rand(0, count($aClasses) - 1)];
  317. else if(is_numeric($mixedName))
  318. $mixedName = $aClasses[(int)$mixedName % count($aClasses)];
  319. $aColor = self::$_aColors[$mixedName];
  320. if($fOpacity !== false && is_numeric($fOpacity))
  321. $aColor[] = $fOpacity;
  322. return $aColor;
  323. }
  324. public static function getColorClass($sType = BX_DOL_COLOR_FT, $sName = '')
  325. {
  326. $aClasses = array_keys(self::$_aColors);
  327. if(empty($sName) || !in_array($sName, $aClasses))
  328. $sName = $aClasses[rand(0, count($aClasses) - 1)];
  329. $sPrefix = '';
  330. switch ($sType) {
  331. case BX_DOL_COLOR_FT:
  332. $sPrefix = 'col-';
  333. break;
  334. case BX_DOL_COLOR_BG:
  335. $sPrefix = 'bg-col-';
  336. break;
  337. }
  338. return $sPrefix . $sName;
  339. }
  340. /**
  341. * Load templates.
  342. */
  343. function loadTemplates()
  344. {
  345. $aResult = array();
  346. foreach($this->_aTemplates as $sName)
  347. $aResult[$sName] = $this->getHtml($sName . '.html');
  348. $this->_aTemplates = $aResult;
  349. }
  350. /**
  351. * Initialize template engine.
  352. * Note. The method is executed with the system, you shouldn't execute it in your subclasses.
  353. */
  354. function init()
  355. {
  356. $this->loadTemplates();
  357. //--- Load page elements related static variables ---//
  358. $this->aPage = array(
  359. 'name_index' => BX_PAGE_DEFAULT,
  360. 'header' => '',
  361. 'header_text' => '',
  362. 'keywords' => array(),
  363. 'location' => array(),
  364. 'description' => '',
  365. 'robots' => '',
  366. 'css_name' => array(),
  367. 'css_compiled' => array(),
  368. 'css_system' => array(),
  369. 'js_name' => array(),
  370. 'js_compiled' => array(),
  371. 'js_system' => array(),
  372. 'js_options' => array(),
  373. 'js_translations' => array(),
  374. 'js_images' => array(),
  375. 'injections' => array()
  376. );
  377. //--- Load default CSS ---//
  378. $this->addCssSystem(array(
  379. 'common.css',
  380. 'default.less',
  381. 'general.css',
  382. 'icons.css',
  383. 'colors.css',
  384. 'forms.css',
  385. 'media-desktop.css',
  386. 'media-tablet.css',
  387. 'media-phone.css',
  388. 'media-print.css',
  389. BX_DIRECTORY_PATH_PLUGINS_PUBLIC . 'marka/|marka.min.css',
  390. BX_DIRECTORY_PATH_PLUGINS_PUBLIC . 'tinymce-mention/css/|autocomplete.css',
  391. ));
  392. //--- Load default JS ---//
  393. $this->addJsSystem(array(
  394. 'jquery/jquery.min.js',
  395. 'jquery/jquery-migrate.min.js',
  396. 'jquery-ui/jquery.ui.position.min.js',
  397. 'spin.min.js',
  398. 'jquery.easing.js',
  399. 'jquery.cookie.min.js',
  400. 'moment-with-locales.min.js',
  401. 'functions.js',
  402. 'jquery.webForms.js',
  403. 'jquery.dolPopup.js',
  404. 'jquery.dolConverLinks.js',
  405. 'marka/marka.min.js',
  406. 'headroom.min.js',
  407. ));
  408. //--- Load translations in JS ---//
  409. bx_import('BxDolLanguages');
  410. $this->addJsTranslation(array(
  411. '_Are_you_sure',
  412. '_error occured',
  413. '_sys_loading',
  414. '_copyright'
  415. ));
  416. //--- Load Embed.ly if Key and Pattern are available ---//
  417. $bEmbedly = !empty(getParam('sys_embedly_api_key'));
  418. if($bEmbedly) {
  419. $this->addJsSystem(array(
  420. 'jquery.embedly.min.js',
  421. ));
  422. $this->addJsOption(array(
  423. 'sys_embedly_api_key',
  424. 'sys_embedly_api_pattern',
  425. ));
  426. }
  427. //--- Load Iframely if Key is available and Embed.ly is disabled ---//
  428. $sIframely = getParam('sys_iframely_api_key');
  429. $bIframely = !$bEmbedly && !empty($sIframely);
  430. if($bIframely) {
  431. $this->addJsSystem(array(
  432. bx_proto() . '://cdn.iframe.ly/embed.js?key=' . md5($sIframely)
  433. ));
  434. $this->addJsOption(array(
  435. 'sys_iframely_api_key'
  436. ));
  437. }
  438. //--- Load injection's cache ---//
  439. if (getParam('sys_db_cache_enable')) {
  440. $oDb = BxDolDb::getInstance();
  441. $oCache = $oDb->getDbCacheObject();
  442. $sCacheKey = $oDb->genDbCacheKey($this->_sInjectionsCache);
  443. $aInjections = $oCache->getData($sCacheKey);
  444. if ($aInjections === null) {
  445. $aInjections = $this->getInjectionsData();
  446. $oCache->setData ($sCacheKey, $aInjections);
  447. }
  448. }
  449. else
  450. $aInjections = $this->getInjectionsData();
  451. $this->aPage['injections'] = $aInjections;
  452. bx_import('BxTemplConfig'); // TODO: for some reason autoloader isn't working here....
  453. $this->_oTemplateConfig = BxTemplConfig::getInstance();
  454. bx_import('BxTemplFunctions');
  455. $this->_oTemplateFunctions = BxTemplFunctions::getInstance($this);
  456. }
  457. protected function getInjectionsData ()
  458. {
  459. $oDb = BxDolDb::getInstance();
  460. $aInjections = $oDb->getAll("SELECT `page_index`, `name`, `key`, `type`, `data`, `replace` FROM `" . $this->_sInjectionsTable . "` WHERE `active`='1'");
  461. if (!$aInjections)
  462. return array();
  463. foreach ($aInjections as $aInjection)
  464. $aInjections['page_' . $aInjection['page_index']][$aInjection['key']][] = $aInjection;
  465. return $aInjections;
  466. }
  467. /**
  468. * Set page name index
  469. * @param int $i name index
  470. */
  471. function setPageNameIndex($i)
  472. {
  473. $this->aPage['name_index'] = $i;
  474. }
  475. /**
  476. * Get page name index
  477. * @return int $i name index
  478. */
  479. function getPageNameIndex()
  480. {
  481. return isset($this->aPage['name_index']) ? (int)$this->aPage['name_index'] : 0;
  482. }
  483. /**
  484. * Set page header
  485. * @param string $s page header
  486. */
  487. function setPageHeader($s)
  488. {
  489. $this->aPage['header'] = $s;
  490. }
  491. /**
  492. * Get page header
  493. * @return string $s page header
  494. */
  495. function getPageHeader()
  496. {
  497. return $this->aPage['header'];
  498. }
  499. /**
  500. * Set page params. Available page params are: name_index, header
  501. * @param array $a page params
  502. */
  503. function setPageParams($a)
  504. {
  505. if (!empty($this->aPage))
  506. $this->aPage = array_merge($this->aPage, $a);
  507. else
  508. $this->aPage = $a;
  509. }
  510. /**
  511. * Get page params.
  512. * @return array $a page params
  513. */
  514. function getPageParams()
  515. {
  516. return $this->aPage;
  517. }
  518. /**
  519. * Set page description.
  520. *
  521. * @param string $sDescription necessary page description.
  522. */
  523. function setPageDescription($sDescription)
  524. {
  525. $this->aPage['description'] = $sDescription;
  526. }
  527. /**
  528. * Set page meta robots.
  529. *
  530. * @param string $s page meta robots.
  531. */
  532. function setPageMetaRobots($s)
  533. {
  534. $this->aPage['robots'] = $s;
  535. }
  536. /**
  537. * Set page content for some variable.
  538. * @param string $sVar name of content variable
  539. * @param string $sContent content for $sVar variable
  540. * @param int $iIndex optional page index, default is index which was set before with @see setPageNameIndex function, or 0
  541. */
  542. function setPageContent($sVar, $sContent, $iIndex = false)
  543. {
  544. $i = false !== $iIndex ? $iIndex : $this->getPageNameIndex();
  545. $this->aPageContent[$i][$sVar] = $sContent;
  546. }
  547. /**
  548. * Get page content for some variable.
  549. * @param string $sVar name of content variable
  550. * @param int $iIndex optional page index, default is index which was set before with @see setPageNameIndex function, or 0
  551. * @return string page content for some variable or for the whole page.
  552. */
  553. function getPageContent($sVar = false, $iIndex = false)
  554. {
  555. $i = false !== $iIndex ? $iIndex : $this->getPageNameIndex();
  556. return false !== $sVar ? $this->aPageContent[$i][$sVar] : $this->aPageContent[$i];
  557. }
  558. /**
  559. * Get currently active template name.
  560. *
  561. * @return string template's name.
  562. */
  563. function getName()
  564. {
  565. return $this->_sName;
  566. }
  567. /**
  568. * Get currently active template code.
  569. *
  570. * @return string template's code.
  571. */
  572. function getCode()
  573. {
  574. return $this->_sCode;
  575. }
  576. /**
  577. * Get currently active template path.
  578. *
  579. * @return string template's path.
  580. */
  581. function getPath()
  582. {
  583. return $this->_sSubPath;
  584. }
  585. /**
  586. * Set page title.
  587. * @deprecated use setPageHeader
  588. *
  589. * @param string $sTitle necessary page title.
  590. */
  591. function setPageTitle($sTitle)
  592. {
  593. $this->setPageHeader($sTitle);
  594. }
  595. /**
  596. * Set page's main box title.
  597. * @deprecated use setPageParams
  598. *
  599. * @param string $sTitle necessary page's main box title.
  600. */
  601. function setPageMainBoxTitle($sTitle)
  602. {
  603. $this->setPageParams(array('header_text' => $sTitle));
  604. }
  605. /**
  606. * Check whether location exists or not.
  607. * @param string $sKey - location's unique key.
  608. */
  609. function isLocation($sKey)
  610. {
  611. return isset($this->_aLocations[$sKey]);
  612. }
  613. /**
  614. * Add location in array of locations.
  615. * Note. Location is the path/url to folder where 'templates' folder is stored.
  616. *
  617. * @param string $sKey - location's unique key.
  618. * @param string $sLocationPath - location's path. For modules: '[path_to_script]/modules/[vendor_name]/[module_name]/'
  619. * @param string $sLocationUrl - location's url. For modules: '[url_to_script]/modules/[vendor_name]/[module_name]/'
  620. */
  621. function addLocation($sKey, $sLocationPath, $sLocationUrl)
  622. {
  623. $this->_aLocations[$sKey] = array(
  624. 'path' => $sLocationPath,
  625. 'url' => $sLocationUrl,
  626. );
  627. return $sKey;
  628. }
  629. /**
  630. * Add dynamic location.
  631. *
  632. * @param string $sLocationPath - location's path. For modules: '[path_to_script]/modules/[vendor_name]/[module_name]/'
  633. * @param string $sLocationUrl - location's url. For modules: '[url_to_script]/modules/[vendor_name]/[module_name]/'
  634. * @return location key. Is needed to remove the location.
  635. */
  636. function addDynamicLocation($sLocationPath, $sLocationUrl)
  637. {
  638. $sLocationKey = time() . mt_rand();
  639. $this->addLocation($sLocationKey, $sLocationPath, $sLocationUrl);
  640. return $sLocationKey;
  641. }
  642. /**
  643. * Remove location from array of locations.
  644. * Note. Location is the path/url to folder where templates are stored.
  645. *
  646. * @param string $sKey - location's unique key.
  647. */
  648. function removeLocation($sKey)
  649. {
  650. if(isset($this->_aLocations[$sKey]))
  651. unset($this->_aLocations[$sKey]);
  652. }
  653. /**
  654. * Add JS location in array of JS locations.
  655. * Note. Location is the path/url to folder where JS files are stored.
  656. *
  657. * @param string $sKey - location's unique key.
  658. * @param string $sLocationPath - location's path. For modules: '[path_to_script]/modules/[vendor_name]/[module_name]/js/'
  659. * @param string $sLocationUrl - location's url. For modules: '[url_to_script]/modules/[vendor_name]/[module_name]/js/'
  660. */
  661. function addLocationJs($sKey, $sLocationPath, $sLocationUrl)
  662. {
  663. $this->_aLocationsJs[$sKey] = array(
  664. 'path' => $sLocationPath,
  665. 'url' => $sLocationUrl
  666. );
  667. }
  668. /**
  669. * Add dynamic JS location.
  670. *
  671. * @param string $sLocationPath - location's path. For modules: '[path_to_script]/modules/[vendor_name]/[module_name]/'
  672. * @param string $sLocationUrl - location's url. For modules: '[url_to_script]/modules/[vendor_name]/[module_name]/'
  673. * @return location key. Is needed to remove the location.
  674. */
  675. function addDynamicLocationJs($sLocationPath, $sLocationUrl)
  676. {
  677. $sLocationKey = time() . mt_rand();
  678. $this->addLocationJs($sLocationKey, $sLocationPath, $sLocationUrl);
  679. return $sLocationKey;
  680. }
  681. /**
  682. * Remove JS location from array of locations.
  683. * Note. Location is the path/url to folder where templates are stored.
  684. *
  685. * @param string $sKey - JS location's unique key.
  686. */
  687. function removeLocationJs($sKey)
  688. {
  689. if(isset($this->_aLocationsJs[$sKey]))
  690. unset($this->_aLocationsJs[$sKey]);
  691. }
  692. /**
  693. * Add Option in JS output.
  694. *
  695. * @param mixed $mixedName option's name or an array of options' names.
  696. */
  697. function addJsOption($mixedName)
  698. {
  699. if(is_string($mixedName))
  700. $mixedName = array($mixedName);
  701. foreach($mixedName as $sName)
  702. $this->aPage['js_options'][$sName] = getParam($sName);
  703. }
  704. /**
  705. * Add language translation for key in JS output.
  706. *
  707. * @param mixed $mixedKey language key or an array of keys.
  708. */
  709. function addJsTranslation($mixedKey)
  710. {
  711. if(is_string($mixedKey))
  712. $mixedKey = array($mixedKey);
  713. foreach($mixedKey as $sKey)
  714. $this->aPage['js_translations'][$sKey] = _t($sKey, '{0}', '{1}');
  715. }
  716. /**
  717. * Add image in JS output.
  718. *
  719. * @param array $aImages an array of image descriptors.
  720. * The descriptor is a key/value pear in the array of descriptors.
  721. */
  722. function addJsImage($aImages)
  723. {
  724. if(!is_array($aImages))
  725. return;
  726. foreach($aImages as $sKey => $sFile) {
  727. $sUrl = $this->getImageUrl($sFile);
  728. if(empty($sUrl))
  729. continue;
  730. $this->aPage['js_images'][$sKey] = $sUrl;
  731. }
  732. }
  733. /**
  734. * Add icon in JS output.
  735. *
  736. * @param array $aIcons an array of icons descriptors.
  737. * The descriptor is a key/value pear in the array of descriptors.
  738. */
  739. function addJsIcon($aIcons)
  740. {
  741. if(!is_array($aIcons))
  742. return;
  743. foreach($aIcons as $sKey => $sFile) {
  744. $sUrl = $this->getIconUrl($sFile);
  745. if(empty($sUrl))
  746. continue;
  747. $this->aPage['js_images'][$sKey] = $sUrl;
  748. }
  749. }
  750. /**
  751. * Add CSS style.
  752. *
  753. * @param string $sName CSS class name.
  754. * @param string $sContent CSS class styles.
  755. */
  756. function addCssStyle($sName, $sContent)
  757. {
  758. $this->aPage['css_styles'][$sName] = $sContent;
  759. }
  760. /**
  761. * Set page keywords.
  762. *
  763. * @param mixed $mixedKeywords necessary page keywords(string - single keyword, array - an array of keywords).
  764. * @param string $sDevider - string devider.
  765. */
  766. function addPageKeywords($mixedKeywords, $sDevider = ',')
  767. {
  768. if(is_string($mixedKeywords))
  769. $mixedKeywords = strpos($mixedKeywords, $sDevider) !== false ? explode($sDevider, $mixedKeywords) : array($mixedKeywords);
  770. foreach($mixedKeywords as $iKey => $sValue)
  771. $mixedKeywords[$iKey] = trim($sValue);
  772. $this->aPage['keywords'] = isset($this->aPage['keywords']) && is_array($this->aPage['keywords']) ? array_merge($this->aPage['keywords'], $mixedKeywords) : $mixedKeywords;
  773. }
  774. /**
  775. * Set page locatoin coordinates.
  776. *
  777. * @param $fLat latitude
  778. * @param $fLng longitude
  779. */
  780. function addPageMetaLocation($fLat, $fLng, $sCountryCode)
  781. {
  782. $this->aPage['location'] = array('lat' => $fLat, 'lng' => $fLng, 'country' => $sCountryCode);
  783. }
  784. /**
  785. * Set page meta image.
  786. *
  787. * @param $sImageUrl meta image url
  788. */
  789. function addPageMetaImage($sImageUrl)
  790. {
  791. $this->aPage['image'] = $sImageUrl;
  792. }
  793. /**
  794. * Set page rss link.
  795. *
  796. * @param $sTitle - rss feed title
  797. * @param $sUrl - rss feed URL
  798. */
  799. function addPageRssLink($sTitle, $sUrl)
  800. {
  801. if (!isset($this->aPage['rss']))
  802. $this->aPage['rss'] = array('title' => $sTitle, 'url' => $sUrl);
  803. else
  804. $this->aPage['rss'] = false;
  805. }
  806. /**
  807. * Returns page meta info, like meta keyword, meta description, location, etc
  808. */
  809. function getMetaInfo()
  810. {
  811. $sRet = '';
  812. if (!empty($this->aPage['keywords']) && is_array($this->aPage['keywords']))
  813. $sRet .= '<meta name="keywords" content="' . bx_html_attribute(implode(',', $this->aPage['keywords'])) . '" />';
  814. $bDescription = !empty($this->aPage['description']) && is_string($this->aPage['description']);
  815. if ($bDescription)
  816. $sRet .= '<meta name="description" content="' . bx_html_attribute($this->aPage['description']) . '" />';
  817. if (!empty($this->aPage['location']) && isset($this->aPage['location']['lat']) && isset($this->aPage['location']['lng']) && isset($this->aPage['location']['country']))
  818. $sRet .= '
  819. <meta name="ICBM" content="' . $this->aPage['location']['lat'] . ';' . $this->aPage['location']['lng'] . '" />
  820. <meta name="geo.position" content="' . $this->aPage['location']['lat'] . ';' . $this->aPage['location']['lng'] . '" />
  821. <meta name="geo.region" content="' . bx_html_attribute($this->aPage['location']['country']) . '" />';
  822. if (!empty($this->aPage['image'])) {
  823. $sRet .= '<meta property="og:image" content="' . $this->aPage['image'] . '" />';
  824. $sRet .= '
  825. <meta name="twitter:card" content="summary_large_image" />
  826. <meta name="twitter:title" content="' . (isset($this->aPage['header']) ? bx_html_attribute(strip_tags($this->aPage['header'])) : '') . '" />
  827. <meta name="twitter:description" content="' . ($bDescription ? bx_html_attribute($this->aPage['description']) : '') . '" />
  828. <meta name="twitter:image" content="' . $this->aPage['image'] . '" />';
  829. }
  830. $oFunctions = BxTemplFunctions::getInstance();
  831. $sRet .= $oFunctions->getManifests();
  832. $sRet .= $oFunctions->getMetaIcons();
  833. if (!empty($this->aPage['rss']) && !empty($this->aPage['rss']['url']))
  834. $sRet .= '<link rel="alternate" type="application/rss+xml" title="' . bx_html_attribute($this->aPage['rss']['title'], BX_ESCAPE_STR_QUOTE) . '" href="' . $this->aPage['rss']['url'] . '" />';
  835. return $sRet;
  836. }
  837. /**
  838. * Get template, which was loaded earlier.
  839. * @see method this->loadTemplates and field this->_aTemplates
  840. *
  841. * @param string $sName - template name.
  842. * @return string template's content.
  843. */
  844. public function getTemplate($sName)
  845. {
  846. return $this->_aTemplates[$sName];
  847. }
  848. /**
  849. * Get template functions object.
  850. * @see BxBaseFunctions
  851. */
  852. public function getTemplateFunctions()
  853. {
  854. return $this->_oTemplateFunctions;
  855. }
  856. /**
  857. * Get icon template in dependence of a value, provided in $mixedId.
  858. *
  859. * @param mixed $mixedId numeric id from Storage, string with template's file name or string with font icon.
  860. */
  861. public function getIcon($mixedId, $aParams = array())
  862. {
  863. return $this->_getImage('icon', $mixedId, $aParams);
  864. }
  865. /**
  866. * Get image template in dependence of a value, provided in $mixedId.
  867. *
  868. * @param mixed $mixedId numeric id from Storage, string with template's file name or string with font icon.
  869. */
  870. public function getImage($mixedId, $aParams = array())
  871. {
  872. return $this->_getImage('image', $mixedId, $aParams);
  873. }
  874. protected function _getImage($sType, $mixedId, $aParams = array())
  875. {
  876. $sUrl = "";
  877. $aType2Method = array('image' => 'getImageUrl', 'icon' => 'getIconUrl');
  878. //--- Check in System Storage.
  879. if(is_numeric($mixedId) && (int)$mixedId > 0) {
  880. $sStorage = BX_DOL_STORAGE_OBJ_IMAGES;
  881. if(!empty($aParams['storage'])) {
  882. $sStorage = $aParams['storage'];
  883. unset($aParams['storage']);
  884. }
  885. if(($sResult = BxDolStorage::getObjectInstance($sStorage)->getFileUrlById((int)$mixedId)) !== false)
  886. $sUrl = $sResult;
  887. }
  888. //--- Check in template folders.
  889. if($sUrl == "" && is_string($mixedId) && strpos($mixedId, '.') !== false)
  890. $sUrl = $this->{$aType2Method[$sType]}($mixedId);
  891. if($sUrl != "")
  892. return $this->parseImage($sUrl, array(
  893. 'class' => isset($aParams['class']) && !empty($aParams['class']) ? $aParams['class'] : '',
  894. 'alt' => isset($aParams['alt']) && !empty($aParams['alt']) ? $aParams['alt'] : ''
  895. ));
  896. //--- Use iconic font.
  897. return $this->parseIcon($mixedId);
  898. }
  899. /**
  900. * Get full URL for the icon.
  901. *
  902. * @param string $sName icon's file name.
  903. * @param string $sCheckIn where the content would be searched(base, template, both)
  904. * @return string full URL.
  905. */
  906. function getIconUrl($sName, $sCheckIn = BX_DOL_TEMPLATE_CHECK_IN_BOTH)
  907. {
  908. $sContent = "";
  909. if(($sContent = $this->_getInlineData('icon', $sName, $sCheckIn)) !== false)
  910. return $sContent;
  911. return $this->_getAbsoluteLocation('url', $this->_sFolderIcons, $sName, $sCheckIn);
  912. }
  913. /**
  914. * Get absolute Path for the icon.
  915. *
  916. * @param string $sName - icon's file name.
  917. * @param string $sCheckIn where the content would be searched(base, template, both)
  918. * @return string absolute path.
  919. */
  920. function getIconPath($sName, $sCheckIn = BX_DOL_TEMPLATE_CHECK_IN_BOTH)
  921. {
  922. return $this->_getAbsoluteLocation('path', $this->_sFolderIcons, $sName, $sCheckIn);
  923. }
  924. /**
  925. * Get full URL for the image.
  926. *
  927. * @param string $sName - images's file name.
  928. * @param string $sCheckIn where the content would be searched(base, template, both)
  929. * @return string full URL.
  930. */
  931. function getImageUrl($sName, $sCheckIn = BX_DOL_TEMPLATE_CHECK_IN_BOTH)
  932. {
  933. $sContent = "";
  934. if(($sContent = $this->_getInlineData('image', $sName, $sCheckIn)) !== false)
  935. return $sContent;
  936. return $this->_getAbsoluteLocation('url', $this->_sFolderImages, $sName, $sCheckIn);
  937. }
  938. /**
  939. * Get absolute Path for the image.
  940. *
  941. * @param string $sName - image's file name.
  942. * @param string $sCheckIn where the content would be searched(base, template, both)
  943. * @return string absolute path.
  944. */
  945. function getImagePath($sName, $sCheckIn = BX_DOL_TEMPLATE_CHECK_IN_BOTH)
  946. {
  947. return $this->_getAbsoluteLocation('path', $this->_sFolderImages, $sName, $sCheckIn);
  948. }
  949. /**
  950. * Get full URL of CSS file.
  951. *
  952. * @param string $sName - CSS file name.
  953. * @param string $sCheckIn where the content would be searched(base, template, both)
  954. * @return string full URL.
  955. */
  956. function getCssUrl($sName, $sCheckIn = BX_DOL_TEMPLATE_CHECK_IN_BOTH)
  957. {
  958. return $this->_getAbsoluteLocation('url', $this->_sFolderCss, $sName, $sCheckIn);
  959. }
  960. /**
  961. * Get full Path of CSS file.
  962. *
  963. * @param string $sName - CSS file name.
  964. * @param string $sCheckIn where the content would be searched(base, template, both)
  965. * @return string full URL.
  966. */
  967. function getCssPath($sName, $sCheckIn = BX_DOL_TEMPLATE_CHECK_IN_BOTH)
  968. {
  969. return $this->_getAbsoluteLocation('path', $this->_sFolderCss, $sName, $sCheckIn);
  970. }
  971. /**
  972. * Get full URL of JS file.
  973. *
  974. * @param string $sName - JS file name.
  975. * @return string full URL.
  976. */
  977. function getJsUrl($sName)
  978. {
  979. return $this->_getAbsoluteLocationJs('url', $sName);
  980. }
  981. /**
  982. * Get full Path of JS file.
  983. *
  984. * @param string $sName - JS file name.
  985. * @return string full URL.
  986. */
  987. function getJsPath($sName)
  988. {
  989. return $this->_getAbsoluteLocationJs('path', $sName);
  990. }
  991. /**
  992. * Get full URL of Template (HTML) file.
  993. *
  994. * @param string $sName - Template file name.
  995. * @return string full URL.
  996. */
  997. function getTemplateUrl($sName, $sCheckIn = BX_DOL_TEMPLATE_CHECK_IN_BOTH)
  998. {
  999. return $this->_getAbsoluteLocation('url', $this->_sFolderHtml, $sName, $sCheckIn);
  1000. }
  1001. /**
  1002. * Get full Path of JS file.
  1003. *
  1004. * @param string $sName - JS file name.
  1005. * @return string full URL.
  1006. */
  1007. function getTemplatePath($sName, $sCheckIn = BX_DOL_TEMPLATE_CHECK_IN_BOTH)
  1008. {
  1009. return $this->_getAbsoluteLocation('path', $this->_sFolderHtml, $sName, $sCheckIn);
  1010. }
  1011. /**
  1012. * Get menu.
  1013. * @param $s menu object name
  1014. * @return html or empty string
  1015. */
  1016. function getMenu ($s)
  1017. {
  1018. $oMenu = BxDolMenu::getObjectInstance($s);
  1019. return $oMenu ? $oMenu->getCode () : '';
  1020. }
  1021. /**
  1022. * Get content of HTML file.
  1023. *
  1024. * @param string $sName - HTML file name.
  1025. * @param string $sCheckIn where the content would be searched(base, template, both)
  1026. * @return string full content of the file and false on failure.
  1027. */
  1028. function getHtml($sName, $sCheckIn = BX_DOL_TEMPLATE_CHECK_IN_BOTH)
  1029. {
  1030. $sAbsolutePath = $this->_getAbsoluteLocation('path', $this->_sFolderHtml, $sName, $sCheckIn);
  1031. return !empty($sAbsolutePath) ? trim(file_get_contents($sAbsolutePath)) : false;
  1032. }
  1033. /**
  1034. * Parse HTML template. Search for the template with accordance to it's file name.
  1035. *
  1036. * @see allows to use cache.
  1037. *
  1038. * @param string $sName - HTML file name.
  1039. * @param array $aVariables - key/value pairs. key should be the same as template's key, but without prefix and postfix.
  1040. * @param mixed $mixedKeyWrapperHtml - key wrapper(string value if left and right parts are the same, array(left, right) otherwise).
  1041. * @param string $sCheckIn where the content would be searched(base, template, both)
  1042. * @return string the result of operation.
  1043. */
  1044. function parseHtmlByName($sName, $aVariables, $mixedKeyWrapperHtml = null, $sCheckIn = BX_DOL_TEMPLATE_CHECK_IN_BOTH)
  1045. {
  1046. if (isset($GLOBALS['bx_profiler'])) $GLOBALS['bx_profiler']->beginTemplate($sName, $sRand = time().rand());
  1047. if (($sContent = $this->getCached($sName, $aVariables, $mixedKeyWrapperHtml, $sCheckIn)) !== false) {
  1048. if (isset($GLOBALS['bx_profiler'])) $GLOBALS['bx_profiler']->endTemplate($sName, $sRand, $sRet, true);
  1049. return $sContent;
  1050. }
  1051. $sRet = '';
  1052. if (($sContent = $this->getHtml($sName, $sCheckIn)) !== false)
  1053. $sRet = $this->_parseContent($sContent, $aVariables, $mixedKeyWrapperHtml);
  1054. if (isset($GLOBALS['bx_profiler'])) $GLOBALS['bx_profiler']->endTemplate($sName, $sRand, $sRet, false);
  1055. return $sRet;
  1056. }
  1057. /**
  1058. * Parse HTML template.
  1059. *
  1060. * @see Doesn't allow to use cache.
  1061. *
  1062. * @param string $sContent - HTML file content.
  1063. * @param array $aVariables - key/value pairs. key should be the same as template's key, but without prefix and postfix.
  1064. * @param mixed $mixedKeyWrapperHtml - key wrapper(string value if left and right parts are the same, array(left, right) otherwise).
  1065. * @return string the result of operation.
  1066. */
  1067. function parseHtmlByContent($sContent, $aVariables, $mixedKeyWrapperHtml = null)
  1068. {
  1069. if(empty($sContent))
  1070. return "";
  1071. return $this->_parseContent($sContent, $aVariables, $mixedKeyWrapperHtml);
  1072. }
  1073. /**
  1074. * Parse earlier loaded HTML template.
  1075. *
  1076. * @see Doesn't allow to use cache.
  1077. *
  1078. * @param string $sName - template name.
  1079. * @param array $aVariables - key/value pairs. Key should be the same as template's key, excluding prefix and postfix.
  1080. * @return string the result of operation.
  1081. * @see $this->_aTemplates
  1082. */
  1083. function parseHtmlByTemplateName($sName, $aVariables, $mixedKeyWrapperHtml = null)
  1084. {
  1085. if(!isset($this->_aTemplates[$sName]) || empty($this->_aTemplates[$sName]))
  1086. return "";
  1087. return $this->_parseContent($this->_aTemplates[$sName], $aVariables, $mixedKeyWrapperHtml);
  1088. }
  1089. /**
  1090. * Parse page HTML template. Search for the page's template with accordance to it's file name.
  1091. *
  1092. * @see allows to use cache.
  1093. *
  1094. * @param string $sName - HTML file name.
  1095. * @param array $aVariables - key/value pairs. key should be the same as template's key, but without prefix and postfix.
  1096. * @return string the result of operation.
  1097. */
  1098. function parsePageByName($sName, $aVariables)
  1099. {
  1100. if (isset($GLOBALS['bx_profiler'])) $GLOBALS['bx_profiler']->beginPage($sName);
  1101. $sContent = $this->parseHtmlByName($sName, $aVariables, $this->_sKeyWrapperHtml, BX_DOL_TEMPLATE_CHECK_IN_BOTH);
  1102. if(empty($sContent))
  1103. $sContent = $this->parseHtmlByName('default.html', $aVariables, $this->_sKeyWrapperHtml, BX_DOL_TEMPLATE_CHECK_IN_BOTH);
  1104. //--- Add CSS and JS at the very last ---//
  1105. if(strpos($sContent, '<bx_include_css_styles />') !== false) {
  1106. $aStyles = array(
  1107. 'display' => 'none !important'
  1108. );
  1109. if(isLogged())
  1110. $this->addCssStyle('.bx-hide-when-logged-in', $aStyles);
  1111. else
  1112. $this->addCssStyle('.bx-hide-when-logged-out', $aStyles);
  1113. $sContent = str_replace('<bx_include_css_styles />', $this->includeCssStyles(), $sContent);
  1114. }
  1115. if(strpos($sContent , '<bx_include_css_system />') !== false) {
  1116. $sContent = str_replace('<bx_include_css_system />', $this->includeFiles('css', true), $sContent);
  1117. }
  1118. if(strpos($sContent , '<bx_include_css />') !== false) {
  1119. if (!empty($this->aPage['css_name']))
  1120. $this->addCss($this->aPage['css_name']);
  1121. $sContent = str_replace('<bx_include_css />', $this->includeFiles('css'), $sContent);
  1122. }
  1123. if(strpos($sContent , '<bx_include_js_system />') !== false) {
  1124. $sContent = str_replace('<bx_include_js_system />', $this->includeFiles('js', true), $sContent);
  1125. }
  1126. if(strpos($sContent , '<bx_include_js />') !== false) {
  1127. if (!empty($this->aPage['js_name']))
  1128. $this->addJs($this->aPage['js_name']);
  1129. $sContent = str_replace('<bx_include_js />', $this->includeFiles('js'), $sContent);
  1130. }
  1131. if (isset($GLOBALS['bx_profiler'])) $GLOBALS['bx_profiler']->endPage($sContent);
  1132. return $sContent;
  1133. }
  1134. /**
  1135. * Parse system keys.
  1136. *
  1137. * @param string $sKey key
  1138. * @return string value associated with the key.
  1139. */
  1140. function parseSystemKey($sKey, $mixedKeyWrapperHtml = null, $bProcessInjection = true)
  1141. {
  1142. $aKeyWrappers = $this->_getKeyWrappers($mixedKeyWrapperHtml);
  1143. $sRet = '';
  1144. switch( $sKey ) {
  1145. case 'page_charset':
  1146. $sRet = 'UTF-8';
  1147. break;
  1148. case 'page_robots':
  1149. if(!empty($this->aPage['robots']) && is_string($this->aPage['robots']))
  1150. $sRet = '<meta name="robots" content="' . bx_html_attribute($this->aPage['robots']) . '" />';
  1151. break;
  1152. case 'meta_info':
  1153. $sRet = $this->getMetaInfo();
  1154. break;
  1155. case 'page_header':
  1156. if(isset($this->aPage['header']))
  1157. $sRet = bx_process_output(strip_tags($this->aPage['header']));
  1158. break;
  1159. case 'page_header_text':
  1160. if(isset($this->aPage['header_text']))
  1161. $sRet = bx_process_output($this->aPage['header_text']);
  1162. break;
  1163. case 'system_injection_head':
  1164. $sRet = $this->_oTemplateFunctions->getInjectionHead();
  1165. break;
  1166. case 'system_injection_header':
  1167. $sRet = $this->_oTemplateFunctions->getInjectionHeader();
  1168. break;
  1169. case 'system_injection_footer':
  1170. $sRet = $this->_oTemplateFunctions->getInjectionFooter();
  1171. break;
  1172. case 'lang':
  1173. $sRet = bx_lang_name();
  1174. break;
  1175. case 'lang_direction':
  1176. $sRet = bx_lang_direction();
  1177. break;
  1178. case 'main_logo':
  1179. $sRet = BxTemplFunctions::getInstance()->getMainLogo();
  1180. break;
  1181. case 'informer':
  1182. $oInformer = BxDolInformer::getInstance($this);
  1183. $sRet = $oInformer ? $oInformer->display() : '';
  1184. break;
  1185. case 'cover':
  1186. $oCover = BxDolCover::getInstance($this);
  1187. if(!$oCover)
  1188. break;
  1189. $bCover = true;
  1190. $oPage = BxDolPage::getObjectInstanceByURI();
  1191. if($oPage !== false) {
  1192. $bCover = $oPage->isPageCover();
  1193. if($bCover && !$oCover->isCover()) {
  1194. $aCover = $oPage->getPageCoverImage();
  1195. if(!empty($aCover))
  1196. $oCover->setCoverImageUrl($aCover);
  1197. }
  1198. }
  1199. $sRet = $bCover ? $oCover->display() : $oCover->displayEmpty();
  1200. break;
  1201. case 'dol_images':
  1202. $sRet = $this->_processJsImages();
  1203. break;
  1204. case 'dol_lang':
  1205. $sRet = $this->_processJsTranslations();
  1206. break;
  1207. case 'dol_options':
  1208. $sRet = $this->_processJsOptions();
  1209. break;
  1210. case 'copyright':
  1211. $sRet = _t( '_copyright', date('Y') ) . getVersionComment();
  1212. break;
  1213. case 'copyright_attr':
  1214. $sRet = bx_html_attribute(_t('_copyright', date('Y')));
  1215. break;
  1216. case 'extra_js':
  1217. $sRet = empty($this->aPage['extra_js']) ? '' : $this->aPage['extra_js'];
  1218. break;
  1219. case 'is_profile_page':
  1220. $sRet = (defined('BX_PROFILE_PAGE')) ? 'true' : 'false';
  1221. break;
  1222. default:
  1223. $sRet = ($sTemplAdd = BxTemplFunctions::getInstance()->TemplPageAddComponent($sKey)) !== false ? $sTemplAdd : $aKeyWrappers['left'] . $sKey . $aKeyWrappers['right'];
  1224. }
  1225. if($bProcessInjection)
  1226. $sRet = $this->processInjection($this->getPageNameIndex(), $sKey, $sRet);
  1227. return $sRet;
  1228. }
  1229. /**
  1230. * Parse tag <A>
  1231. *
  1232. * @param string $sLink link URL
  1233. * @param string $sContent link content
  1234. * @param array $aAttrs an array of key => value pairs
  1235. */
  1236. function parseLink($sLink, $sContent, $aAttrs = array())
  1237. {
  1238. $sAttrs = '';
  1239. foreach($aAttrs as $sKey => $sValue)
  1240. $sAttrs .= ' ' . $sKey . '="' . bx_html_attribute($sValue) . '"';
  1241. return '<a href="' . $sLink . '"' . $sAttrs . '>' . $sContent . '</a>';
  1242. }
  1243. /**
  1244. * Parse tag <BUTTON>
  1245. *
  1246. * @param string $sContent link content
  1247. * @param array $aAttrs an array of key => value pairs
  1248. */
  1249. function parseButton($sContent, $aAttrs = array())
  1250. {
  1251. $sAttrs = '';
  1252. foreach($aAttrs as $sKey => $sValue)
  1253. $sAttrs .= ' ' . $sKey . '="' . bx_html_attribute($sValue) . '"';
  1254. return '<button' . $sAttrs . '>' . $sContent . '</button>';
  1255. }
  1256. /**
  1257. * Parse tag <IMG>
  1258. *
  1259. * @param string $sLink URL to image source
  1260. * @param array $aAttrs an array of key => value pairs
  1261. */
  1262. function parseImage($sLink, $aAttrs = array())
  1263. {
  1264. $sAttrs = '';
  1265. foreach($aAttrs as $sKey => $sValue)
  1266. $sAttrs .= ' ' . $sKey . '="' . bx_html_attribute($sValue) . '"';
  1267. return '<img src="' . $sLink . '"' . $sAttrs . ' />';
  1268. }
  1269. /**
  1270. * Parse font based icon in <I> tag
  1271. *
  1272. * @param string $sName font icon name
  1273. * @param array $aAttrs an array of key => value pairs
  1274. */
  1275. function parseIcon($sName, $aAttrs = array())
  1276. {
  1277. if(!empty($aAttrs['class'])) {
  1278. $sName .= ' ' . $aAttrs['class'];
  1279. unset($aAttrs['class']);
  1280. }
  1281. $sAttrs = '';
  1282. foreach($aAttrs as $sKey => $sValue)
  1283. $sAttrs .= ' ' . $sKey . '="' . bx_html_attribute($sValue) . '"';
  1284. return '<i class="sys-icon ' . $sName . '"' . $sAttrs . '></i>';
  1285. }
  1286. function getCacheFilePrefix($sType)
  1287. {
  1288. $sResult = '';
  1289. switch($sType) {
  1290. case 'template':
  1291. $sResult = $this->_sCacheFilePrefix;
  1292. break;
  1293. case 'css':
  1294. $sResult = $this->_sCssCachePrefix;
  1295. break;
  1296. case 'js':
  1297. $sResult = $this->_sJsCachePrefix;
  1298. break;
  1299. }
  1300. return $sResult;
  1301. }
  1302. /**
  1303. * Get cache object for templates
  1304. * @return cache class instance
  1305. */
  1306. function getTemplatesCacheObject ()
  1307. {
  1308. $sCacheEngine = getParam('sys_template_cache_engine');
  1309. $oCacheEngine = bx_instance('BxDolCache' . $sCacheEngine);
  1310. if(!$oCacheEngine->isAvailable())
  1311. $oCacheEngine = bx_instance('BxDolCacheFileHtml');
  1312. return $oCacheEngine;
  1313. }
  1314. /**
  1315. * Get template from cache if it's enabled.
  1316. *
  1317. * @param string $sName template name
  1318. * @param string $aVariables key/value pairs. key should be the same as template's key, but without prefix and postfix.
  1319. * @param mixed $mixedKeyWrapperHtml - key wrapper(string value if left and right parts are the same, array(0 => left, 1 => right) otherwise).
  1320. * @param string $sCheckIn where the content would be searched(base, template, both)
  1321. * @param boolean $bEvaluate need to evaluate the template or not.
  1322. * @return string result of operation or false on failure.
  1323. */
  1324. function getCached($sName, &$aVariables, $mixedKeyWrapperHtml = null, $sCheckIn = BX_DOL_TEMPLATE_CHECK_IN_BOTH, $bEvaluate = true)
  1325. {
  1326. // initialization
  1327. if(!$this->_bCacheEnable)
  1328. return false;
  1329. $sAbsolutePath = $this->_getAbsoluteLocation('path', $this->_sFolderHtml, $sName, $sCheckIn);
  1330. if(empty($sAbsolutePath))
  1331. return false;
  1332. $oCacheEngine = $this->getTemplatesCacheObject ();
  1333. $isFileBasedEngine = $bEvaluate && method_exists($oCacheEngine, 'getDataFilePath');
  1334. // try to get cached content
  1335. $sCacheVariableName = "a";
  1336. $sCacheKey = $this->_getCacheFileName('html', $sAbsolutePath) . '.php';
  1337. if ($isFileBasedEngine)
  1338. $sCacheContent = $oCacheEngine->getDataFilePath($sCacheKey);
  1339. else
  1340. $sCacheContent = $oCacheEngine->getData($sCacheKey);
  1341. // recreate cache if it is empty
  1342. if ($sCacheContent === null && ($sContent = file_get_contents($sAbsolutePath)) !== false && ($sContent = $this->_compileContent($sContent, "\$" . $sCacheVariableName, 1, $aVariables, $mixedKeyWrapperHtml)) !== false) {
  1343. if (false === $oCacheEngine->setData($sCacheKey, trim($sContent)))
  1344. return false;
  1345. if ($isFileBasedEngine)
  1346. $sCacheContent = $oCacheEngine->getDataFilePath($sCacheKey);
  1347. else
  1348. $sCacheContent = $sContent;
  1349. }
  1350. if ($sCacheContent === null)
  1351. return false;
  1352. // return simple cache content
  1353. if(!$bEvaluate)
  1354. return $sCacheContent;
  1355. // return evaluated cache content
  1356. ob_start();
  1357. $$sCacheVariableName = &$aVariables;
  1358. if ($isFileBasedEngine)
  1359. include($sCacheContent);
  1360. else
  1361. eval('?'.'>' . $sCacheContent);
  1362. $sContent = ob_get_clean();
  1363. return $sContent;
  1364. }
  1365. /**
  1366. * Add JS file(s) to global output.
  1367. *
  1368. * @param mixed $mixedFiles string value represents a single JS file name. An array - array of JS file names.
  1369. * @param boolean $bDynamic in the dynamic mode JS file(s) are not included to global output, but are returned from the function directly.
  1370. * @return boolean/string result of operation.
  1371. */
  1372. function addJs($mixedFiles, $bDynamic = false)
  1373. {
  1374. return $this->_processFiles('js', 'add', $mixedFiles, $bDynamic);
  1375. }
  1376. /**
  1377. * Add System JS file(s) to global output.
  1378. * System JS files are the files which are attached to all pages. They will be cached separately from the others.
  1379. *
  1380. * @param mixed $mixedFiles string value represents a single JS file name. An array - array of JS file names.
  1381. * @param boolean $bDynamic in the dynamic mode JS file(s) are not included to global output, but are returned from the function directly.
  1382. * @return boolean/string result of operation.
  1383. */
  1384. function addJsSystem($mixedFiles)
  1385. {
  1386. return $this->_processFiles('js', 'add', $mixedFiles, false, true);
  1387. }
  1388. /**
  1389. * Delete JS file(s) from global output.
  1390. *
  1391. * @param mixed $mixedFiles string value represents a single JS file name. An array - array of JS file names.
  1392. * @return boolean result of operation.
  1393. */
  1394. function deleteJs($mixedFiles)
  1395. {
  1396. return $this->_processFiles('js', 'delete', $mixedFiles);
  1397. }
  1398. /**
  1399. * Delete System JS file(s) from global output.
  1400. *
  1401. * @param mixed $mixedFiles string value represents a single JS file name. An array - array of JS file names.
  1402. * @return boolean result of operation.
  1403. */
  1404. function deleteJsSystem($mixedFiles)
  1405. {
  1406. return $this->_processFiles('js', 'delete', $mixedFiles, false, true);
  1407. }
  1408. /**
  1409. * Compile JS files in one file.
  1410. *
  1411. * @param string $sAbsolutePath CSS file absolute path(full URL for external CSS/JS files).
  1412. * @param array $aIncluded an array of already included JS files.
  1413. * @return string result of operation.
  1414. */
  1415. function _compileJs($sAbsolutePath, &$aIncluded)
  1416. {
  1417. if(isset($aIncluded[$sAbsolutePath]))
  1418. return '';
  1419. $bExternal = strpos($sAbsolutePath, "http://") !== false || strpos($sAbsolutePath, "https://") !== false;
  1420. if($bExternal) {
  1421. $sPath = $sAbsolutePath;
  1422. $sName = '';
  1423. $sContent = bx_file_get_contents($sAbsolutePath);
  1424. } else {
  1425. $aFileInfo = pathinfo($sAbsolutePath);
  1426. $sPath = $aFileInfo['dirname'] . DIRECTORY_SEPARATOR;
  1427. $sName = $aFileInfo['basename'];
  1428. $sContent = file_get_contents($sPath . $sName);
  1429. }
  1430. if(empty($sContent))
  1431. return '';
  1432. $sUrl = bx_ltrim_str($sPath, realpath(BX_DIRECTORY_PATH_ROOT), BX_DOL_URL_ROOT);
  1433. $sUrl = str_replace(DIRECTORY_SEPARATOR, '/', $sUrl);
  1434. $sContent = "\r\n/*--- BEGIN: " . $sUrl . $sName . "---*/\r\n" . $sContent . ";\r\n/*--- END: " . $sUrl . $sName . "---*/\r\n";
  1435. $sContent = str_replace(array("\n\r", "\r\n", "\r"), "\n", $sContent);
  1436. $aIncluded[$sAbsolutePath] = 1;
  1437. return preg_replace(
  1438. array(
  1439. "'<bx_url_root />'",
  1440. "'\r\n'"
  1441. ),
  1442. array(
  1443. BX_DOL_URL_ROOT,
  1444. "\n"
  1445. ),
  1446. $sContent
  1447. );
  1448. }
  1449. /**
  1450. * Minify JS
  1451. *
  1452. * @param string $s JS string to minify
  1453. * @return string minified JS string.
  1454. */
  1455. function _minifyJs($s)
  1456. {
  1457. // since each JS file is minified separately, it has to be in own scope
  1458. return "\n {\n" . BxDolMinify::getInstance()->minifyJs($s) . "\n }\n";
  1459. }
  1460. /**
  1461. * Wrap an URL to JS file into JS tag.
  1462. *
  1463. * @param string $sFile - URL to JS file.
  1464. * @return string the result of operation.
  1465. */
  1466. function _wrapInTagJs($sFile)
  1467. {
  1468. return "<script language=\"javascript\" type=\"text/javascript\" src=\"" . $sFile . "\"></script>";
  1469. }
  1470. /**
  1471. * Wrap JS code into JS tag.
  1472. *
  1473. * @param string $sCode - JS code.
  1474. * @return string the result of operation.
  1475. */
  1476. function _wrapInTagJsCode($sCode)
  1477. {
  1478. return "<script language=\"javascript\" type=\"text/javascript\">\n<!--\n" . $sCode . "\n-->\n</script>";
  1479. }
  1480. /**
  1481. * Add CSS file(s) to global output.
  1482. *
  1483. * @param mixed $mixedFiles string value represents a single CSS file name. An array - array of CSS file names.
  1484. * @param boolean $bDynamic in the dynamic mode CSS file(s) are not included to global output, but are returned from the function directly.
  1485. * @return boolean/string result of operation
  1486. */
  1487. function addCss($mixedFiles, $bDynamic = false)
  1488. {
  1489. return $this->_processFiles('css', 'add', $mixedFiles, $bDynamic);
  1490. }
  1491. /**
  1492. * Add System CSS file(s) to global output.
  1493. * System CSS files are the files which are attached to all pages. They will be cached separately from the others.
  1494. *
  1495. * @param mixed $mixedFiles string value represents a single CSS file name. An array - array of CSS file names.
  1496. * @return boolean/string result of operation
  1497. */
  1498. function addCssSystem($mixedFiles)
  1499. {
  1500. return $this->_processFiles('css', 'add', $mixedFiles, false, true);
  1501. }
  1502. /**
  1503. * Delete CSS file(s) from global output.
  1504. *
  1505. * @param mixed $mixedFiles string value represents a single CSS file name. An array - array of CSS file names.
  1506. * @return boolean result of operation.
  1507. */
  1508. function deleteCss($mixedFiles)
  1509. {
  1510. return $this->_processFiles('css', 'delete', $mixedFiles);
  1511. }
  1512. /**
  1513. * Delete System CSS file(s) from global output.
  1514. *
  1515. * @param mixed $mixedFiles string value represents a single CSS file name. An array - array of CSS file names.
  1516. * @return boolean result of operation.
  1517. */
  1518. function deleteCssSystem($mixedFiles)
  1519. {
  1520. return $this->_processFiles('css', 'delete', $mixedFiles, false, true);
  1521. }
  1522. /**
  1523. * Compile CSS files' structure(@see \@import css_file_path) in one file.
  1524. *
  1525. * @param string $sAbsolutePath CSS file absolute path(full URL for external CSS/JS files).
  1526. * @param array $aIncluded an array of already included CSS files.
  1527. * @return string result of operation.
  1528. */
  1529. function _compileCss($sAbsolutePath, &$aIncluded)
  1530. {
  1531. if(isset($aIncluded[$sAbsolutePath]))
  1532. return '';
  1533. $bExternal = strpos($sAbsolutePath, "http://") !== false || strpos($sAbsolutePath, "https://") !== false;
  1534. if($bExternal) {
  1535. $sPath = $sAbsolutePath;
  1536. $sName = '';
  1537. $aAPUrl = parse_url($sAbsolutePath);
  1538. if(!empty($aAPUrl['path'])) {
  1539. $aAPPath = pathinfo($aAPUrl['path']);
  1540. if(!empty($aAPPath['basename'])) {
  1541. $sPath = bx_rtrim_str($sAbsolutePath, $aAPPath['basename']);
  1542. $sName = $aAPPath['basename'];
  1543. }
  1544. }
  1545. $sContent = bx_file_get_contents($sAbsolutePath);
  1546. } else {
  1547. $aFileInfo = pathinfo($sAbsolutePath);
  1548. $sPath = $aFileInfo['dirname'] . DIRECTORY_SEPARATOR;
  1549. $sName = $aFileInfo['basename'];
  1550. $sContent = file_get_contents($sPath . $sName);
  1551. }
  1552. if(empty($sContent))
  1553. return '';
  1554. $sUrl = bx_ltrim_str($sPath, realpath(BX_DIRECTORY_PATH_ROOT), BX_DOL_URL_ROOT);
  1555. $sUrl = str_replace(DIRECTORY_SEPARATOR, '/', $sUrl);
  1556. $sContent = "\r\n/*--- BEGIN: " . $sUrl . $sName . "---*/\r\n" . $sContent . "\r\n/*--- END: " . $sUrl . $sName . "---*/\r\n";
  1557. $aIncluded[$sAbsolutePath] = 1;
  1558. $sContent = str_replace(array("\n\r", "\r\n", "\r"), "\n", $sContent);
  1559. if($bExternal) {
  1560. $sContent = preg_replace(
  1561. array(
  1562. "'@import\s+url\s*\(\s*[\'|\"]*\s*([a-zA-Z0-9\.\/_-]+)\s*[\'|\"]*\s*\)\s*;'",
  1563. "'url\s*\(\s*[\'|\"]*\s*([a-zA-Z0-9\.\/\?\#_=-]+)\s*[\'|\"]*\s*\)'"
  1564. ),
  1565. array(
  1566. "",
  1567. "url(" . $sPath . "\\1)"
  1568. ),
  1569. $sContent
  1570. );
  1571. }
  1572. else {
  1573. try {
  1574. $oTemplate = &$this;
  1575. /* Match URL based imports like the following:
  1576. * @import 'http://[domain]/modules/[vendor]/[module]/template/css/view.css';
  1577. * Is mainly needed for CSS files which are gotten from LESS compiler.
  1578. */
  1579. $sContent = preg_replace_callback(
  1580. "'@import\s+[\'|\"]*\s*" . str_replace("/", "\/", BX_DOL_URL_ROOT) . "([a-zA-Z0-9\.\/_-]+)\s*[\'|\"]*\s*;'", function ($aMatches) use($oTemplate, $sPath, $aIncluded) {
  1581. return $oTemplate->_compileCss(realpath(BX_DIRECTORY_PATH_ROOT . $aMatches[1]), $aIncluded);
  1582. }, $sContent);
  1583. /* Match relative path based imports like the following:
  1584. * @import url(../../../../../../base/profile/template/css/main.css);
  1585. * Is mainly needed for default CSS files.
  1586. */
  1587. $sContent = preg_replace_callback(
  1588. "'@import\s+url\s*\(\s*[\'|\"]*\s*([a-zA-Z0-9\.\/_-]+)\s*[\'|\"]*\s*\)\s*;'", function ($aMatches) use($oTemplate, $sPath, $aIncluded) {
  1589. return $oTemplate->_compileCss(realpath($sPath . dirname($aMatches[1])) . DIRECTORY_SEPARATOR . basename($aMatches[1]), $aIncluded);
  1590. }, $sContent);
  1591. $sContent = preg_replace_callback(
  1592. "'url\s*\(\s*[\'|\"]*\s*([a-zA-Z0-9\.\/\?\#_=-]+)\s*[\'|\"]*\s*\)'", function ($aMatches) use($oTemplate, $sPath) {
  1593. $sFile = basename($aMatches[1]);
  1594. $sDirectory = dirname($aMatches[1]);
  1595. $sRootPath = realpath(BX_DIRECTORY_PATH_ROOT);
  1596. $sAbsolutePath = realpath(addslashes($sPath) . $sDirectory) . DIRECTORY_SEPARATOR . $sFile;
  1597. $sRootPath = str_replace(DIRECTORY_SEPARATOR, '/', $sRootPath);
  1598. $sAbsolutePath = str_replace(DIRECTORY_SEPARATOR, '/', $sAbsolutePath);
  1599. return 'url(' . bx_ltrim_str($sAbsolutePath, $sRootPath, BX_DOL_URL_ROOT) . ')';
  1600. }, $sContent);
  1601. }
  1602. catch(Exception $oException) {
  1603. return '';
  1604. }
  1605. }
  1606. return $sContent;
  1607. }
  1608. /**
  1609. * Less CSS
  1610. *
  1611. * @param mixed $mixed CSS string to process with Less compiler or an array with CSS file's Path and URL.
  1612. * @return mixed string or an array with CSS file's Path and URL.
  1613. */
  1614. function _lessCss($mixed)
  1615. {
  1616. require_once(BX_DIRECTORY_PATH_PLUGINS . 'lessphp/Less.php');
  1617. if(is_array($mixed) && isset($mixed['url']) && isset($mixed['path'])) {
  1618. $sPathFile = realpath($mixed['path']);
  1619. $aInfoFile = pathinfo($sPathFile);
  1620. if (!isset($aInfoFile['extension']) || $aInfoFile['extension'] != 'less')
  1621. return $mixed;
  1622. require_once(BX_DIRECTORY_PATH_PLUGINS . 'lessphp/Cache.php');
  1623. $aFiles = array($mixed['path'] => $mixed['url']);
  1624. $aOptions = array('cache_dir' => $this->_sCachePublicFolderPath);
  1625. $sFile = Less_Cache::Get($aFiles, $aOptions, $this->_oTemplateConfig->aLessConfig);
  1626. return array('url' => $this->_sCachePublicFolderUrl . $sFile, 'path' => $this->_sCachePublicFolderPath . $sFile);
  1627. }
  1628. $oLess = new Less_Parser();
  1629. $oLess->ModifyVars($this->_oTemplateConfig->aLessConfig);
  1630. $oLess->parse($mixed);
  1631. return $oLess->getCss();
  1632. }
  1633. /**
  1634. * Minify CSS
  1635. *
  1636. * @param string $s CSS string to minify
  1637. * @return string minified CSS string.
  1638. */
  1639. function _minifyCss($s)
  1640. {
  1641. return BxDolMinify::getInstance()->minifyCss($s);
  1642. }
  1643. /**
  1644. * Wrap an URL to CSS file into CSS tag.
  1645. *
  1646. * @param string $sFile - URL to CSS file.
  1647. * @return string the result of operation.
  1648. */
  1649. function _wrapInTagCss($sFile)
  1650. {
  1651. if (!$sFile)
  1652. return '';
  1653. return "<link href=\"" . $sFile . "\" rel=\"stylesheet\" type=\"text/css\" />";
  1654. }
  1655. /**
  1656. * Wrap CSS code into CSS tag.
  1657. *
  1658. * @param string $sCode - CSS code.
  1659. * @return string the result of operation.
  1660. */
  1661. function _wrapInTagCssCode($sCode)
  1662. {
  1663. return "<style>" . $sCode . "</style>";
  1664. }
  1665. /**
  1666. * Include CSS style(s) in the page's head section.
  1667. */
  1668. function includeCssStyles()
  1669. {
  1670. $sResult = "";
  1671. if(empty($this->aPage['css_styles']) || !is_array($this->aPage['css_styles']))
  1672. return $sResult;
  1673. foreach($this->aPage['css_styles'] as $sName => $aContent) {
  1674. $sContent = "";
  1675. if(!empty($aContent) && is_array($aContent))
  1676. foreach($aContent as $sStyleName => $sStyleValue)
  1677. $sContent .= "\t" . $sStyleName . ": " . $sStyleValue . ";\r\n";
  1678. $sResult .= $sName . " {\r\n" . $sContent . "}\r\n";
  1679. }
  1680. return !empty($sResult) ? $this->_wrapInTagCssCode($sResult) : '';
  1681. }
  1682. /**
  1683. * Include CSS/JS file(s) attached to the page in its head section.
  1684. * @see the method is system and would be called automatically.
  1685. *
  1686. * @param string $sType the type of file('js' or 'css')
  1687. * @return string the result CSS code.
  1688. */
  1689. function includeFiles($sType, $bSystem = false)
  1690. {
  1691. $sUpcaseType = ucfirst($sType);
  1692. $sArrayKey = $sType . ($bSystem ? '_system' : '_compiled');
  1693. $aFiles = isset($this->aPage[$sArrayKey]) ? $this->aPage[$sArrayKey] : array();
  1694. if(empty($aFiles) || !is_array($aFiles))
  1695. return "";
  1696. if(!$this->{'_b' . $sUpcaseType . 'Cache'})
  1697. return $this->_includeFiles($sType, $aFiles);
  1698. //--- If cache already exists, return it ---//
  1699. $sMethodWrap = '_wrapInTag' . $sUpcaseType;
  1700. $sMethodCompile = '_compile' . $sUpcaseType;
  1701. $sMethodLess = '_less' . $sUpcaseType;
  1702. $sMethodMinify = '_minify' . $sUpcaseType;
  1703. ksort($aFiles);
  1704. $sName = "";
  1705. foreach($aFiles as $aFile)
  1706. $sName .= $aFile['url'];
  1707. $sName = $this->_getCacheFileName($sType, $sName);
  1708. $sCacheAbsoluteUrl = $this->_sCachePublicFolderUrl . $sName . '.' . $sType;
  1709. $sCacheAbsolutePath = $this->_sCachePublicFolderPath . $sName . '.' . $sType;
  1710. if(file_exists($sCacheAbsolutePath)) {
  1711. if($this->{'_b' . $sUpcaseType . 'Archive'})
  1712. $sCacheAbsoluteUrl = $this->_getLoaderUrl($sType, $sName);
  1713. return $this->$sMethodWrap($sCacheAbsoluteUrl);
  1714. }
  1715. //--- Collect all attached CSS/JS in one file ---//
  1716. $bLess = $this->_bLessEnable && method_exists($this, $sMethodLess);
  1717. $sResult = "";
  1718. $aIncluded = array();
  1719. foreach($aFiles as $aFile) {
  1720. if($bLess)
  1721. $aFile = $this->$sMethodLess($aFile);
  1722. if(($sContent = $this->$sMethodCompile($aFile['path'], $aIncluded)) === false)
  1723. continue;
  1724. if (!preg_match('/[\.-]min.(js|css)$/i', $aFile['path']) && $this->{'_b' . $sUpcaseType . 'Minify'}) // don't minify minified files
  1725. $sContent = $this->$sMethodMinify($sContent);
  1726. $sResult .= $sContent;
  1727. }
  1728. $mixedWriteResult = false;
  1729. if(!empty($sResult) && ($rHandler = fopen($sCacheAbsolutePath, 'w')) !== false) {
  1730. $mixedWriteResult = fwrite($rHandler, $sResult);
  1731. fclose($rHandler);
  1732. @chmod ($sCacheAbsolutePath, BX_DOL_FILE_RIGHTS);
  1733. }
  1734. if($mixedWriteResult === false)
  1735. return $this->_includeFiles($sType, $aFiles);
  1736. if($this->{'_b' . $sUpcaseType . 'Archive'})
  1737. $sCacheAbsoluteUrl = $this->_getLoaderUrl($sType, $sName);
  1738. return $this->$sMethodWrap($sCacheAbsoluteUrl);
  1739. }
  1740. /**
  1741. * Include CSS/JS files without caching.
  1742. *
  1743. * @param string $sType the file type (css or js)
  1744. * @param array $aFiles CSS/JS files to be added to the page.
  1745. * @return string result of operation.
  1746. */
  1747. function _includeFiles($sType, &$aFiles)
  1748. {
  1749. $sUpcaseType = ucfirst($sType);
  1750. $sMethodWrap = '_wrapInTag' . $sUpcaseType;
  1751. $sMethodLess = '_less' . $sUpcaseType;
  1752. $sResult = "";
  1753. foreach($aFiles as $aFile) {
  1754. if($this->_bLessEnable && method_exists($this, $sMethodLess))
  1755. $aFile = $this->$sMethodLess($aFile);
  1756. $sResult .= $this->$sMethodWrap($aFile['url']);
  1757. }
  1758. return $sResult;
  1759. }
  1760. /**
  1761. * Insert/Delete CSS file from output stack.
  1762. *
  1763. * @param string $sType the file type (css or js)
  1764. * @param string $sAction add/delete
  1765. * @param mixed $mixedFiles string value represents a single CSS file name. An array - array of CSS file names.
  1766. * @return boolean result of operation.
  1767. */
  1768. function _processFiles($sType, $sAction, $mixedFiles, $bDynamic = false, $bSystem = false)
  1769. {
  1770. if(empty($mixedFiles))
  1771. return $bDynamic ? "" : false;
  1772. if(is_string($mixedFiles))
  1773. $mixedFiles = array($mixedFiles);
  1774. $sUpcaseType = ucfirst($sType);
  1775. $sMethodLocate = '_getAbsoluteLocation' . $sUpcaseType;
  1776. $sMethodWrap = '_wrapInTag' . $sUpcaseType;
  1777. $sResult = '';
  1778. foreach($mixedFiles as $sFile) {
  1779. //--- Process 3d Party CSS/JS file ---//
  1780. if(strpos($sFile, "http://") !== false || strpos($sFile, "https://") !== false) {
  1781. $sUrl = $sFile;
  1782. $sPath = $sFile;
  1783. }
  1784. //--- Process Custom CSS/JS file ---//
  1785. else if(strpos($sFile, "|") !== false) {
  1786. $sFile = implode('', explode("|", $sFile));
  1787. $sFile = bx_ltrim_str($sFile, BX_DIRECTORY_PATH_ROOT);
  1788. $sUrl = BX_DOL_URL_ROOT . $sFile;
  1789. $sPath = realpath(BX_DIRECTORY_PATH_ROOT . $sFile);
  1790. }
  1791. //--- Process Common CSS/JS file(check in default locations) ---//
  1792. else {
  1793. $sUrl = $this->$sMethodLocate('url', $sFile);
  1794. $sPath = $this->$sMethodLocate('path', $sFile);
  1795. }
  1796. if(empty($sPath) || empty($sUrl))
  1797. continue;
  1798. $sArrayKey = $sType . ($bSystem ? '_system' : '_compiled');
  1799. switch($sAction) {
  1800. case 'add':
  1801. if($bDynamic)
  1802. $sResult .= $this->$sMethodWrap($sUrl);
  1803. else {
  1804. $bFound = false;
  1805. $aSearchIn = $bSystem ? $this->aPage[$sArrayKey] : array_merge($this->aPage[$sType . '_system'], $this->aPage[$sArrayKey]);
  1806. foreach($aSearchIn as $iKey => $aValue)
  1807. if($aValue['url'] == $sUrl && $aValue['path'] == $sPath) {
  1808. $bFound = true;
  1809. break;
  1810. }
  1811. if(!$bFound)
  1812. $this->aPage[$sArrayKey][] = array('url' => $sUrl, 'path' => $sPath);
  1813. }
  1814. break;
  1815. case 'delete':
  1816. if(!$bDynamic)
  1817. foreach($this->aPage[$sArrayKey] as $iKey => $aValue)
  1818. if($aValue['url'] == $sUrl) {
  1819. unset($this->aPage[$sArrayKey][$iKey]);
  1820. break;
  1821. }
  1822. break;
  1823. }
  1824. }
  1825. return $bDynamic ? $sResult : true;
  1826. }
  1827. /**
  1828. * Parse content.
  1829. *
  1830. * @param string $sContent - HTML file's content.
  1831. * @param array $aVariables - key/value pairs. key should be the same as template's key, but without prefix and postfix.
  1832. * @param mixed $mixedKeyWrapperHtml - key wrapper(string value if left and right parts are the same, array(0 => left, 1 => right) otherwise).
  1833. * @return string the result of operation.
  1834. */
  1835. function _parseContent($sContent, $aVariables, $mixedKeyWrapperHtml = null)
  1836. {
  1837. $aKeysSrc = array_keys($aVariables);
  1838. $aValuesSrc = array_values($aVariables);
  1839. $aKeyWrappers = $this->_getKeyWrappers($mixedKeyWrapperHtml);
  1840. $sKeyIf = 'bx_if:';
  1841. $sKeyRepeat = 'bx_repeat:';
  1842. $iCountKeys = count($aKeysSrc);
  1843. $aKeys = $aValues = array();
  1844. //--- Parse simple keys ---//
  1845. for ($i = 0; $i < $iCountKeys; $i++) {
  1846. if (strncmp($aKeysSrc[$i], $sKeyRepeat, 10) === 0 || strncmp($aKeysSrc[$i], $sKeyIf, 6) === 0)
  1847. continue;
  1848. $aKeys[] = "'" . $aKeyWrappers['left'] . $aKeysSrc[$i] . $aKeyWrappers['right'] . "'s";
  1849. $aValues[] = str_replace('$', '\\$', $aValuesSrc[$i]);
  1850. }
  1851. //--- Parse keys with constructions ---//
  1852. for ($i = 0; $i < $iCountKeys; $i++) {
  1853. if (strncmp($aKeysSrc[$i], $sKeyRepeat, 10) === 0) {
  1854. $sKey = "'<" . $aKeysSrc[$i] . ">(.*)<\/" . $aKeysSrc[$i] . ">'s";
  1855. $aMatches = array();
  1856. preg_match($sKey, $sContent, $aMatches);
  1857. $sValue = '';
  1858. if(isset($aMatches[1]) && !empty($aMatches[1])) {
  1859. if(is_array($aValuesSrc[$i]))
  1860. foreach($aValuesSrc[$i] as $aValue)
  1861. $sValue .= $this->parseHtmlByContent($aMatches[1], $aValue, $mixedKeyWrapperHtml);
  1862. else if(is_string($aValuesSrc[$i]))
  1863. $sValue = $aValuesSrc[$i];
  1864. }
  1865. }
  1866. else if (strncmp($aKeysSrc[$i], $sKeyIf, 6) === 0) {
  1867. $sKey = "'<" . $aKeysSrc[$i] . ">(.*)<\/" . $aKeysSrc[$i] . ">'s";
  1868. $aMatches = array();
  1869. preg_match($sKey, $sContent, $aMatches);
  1870. $sValue = '';
  1871. if(isset($aMatches[1]) && !empty($aMatches[1]))
  1872. if(is_array($aValuesSrc[$i]) && isset($aValuesSrc[$i]['content']) && isset($aValuesSrc[$i]['condition']) && $aValuesSrc[$i]['condition'])
  1873. $sValue .= $this->parseHtmlByContent($aMatches[1], $aValuesSrc[$i]['content'], $mixedKeyWrapperHtml);
  1874. }
  1875. else
  1876. continue;
  1877. $aKeys[] = $sKey;
  1878. $aValues[] = str_replace('$', '\\$', $sValue);
  1879. }
  1880. try {
  1881. $oTemplate = &$this;
  1882. $aCallbackPatterns = array(
  1883. "'<bx_include_auto:([^\s]+) \/>'s" => BX_DOL_TEMPLATE_CHECK_IN_BOTH,
  1884. "'<bx_include_base:([^\s]+) \/>'s" => BX_DOL_TEMPLATE_CHECK_IN_BASE,
  1885. "'<bx_include_tmpl:([^\s]+) \/>'s" => BX_DOL_TEMPLATE_CHECK_IN_TMPL
  1886. );
  1887. foreach($aCallbackPatterns as $sPattern => $sCheckIn)
  1888. $sContent = preg_replace_callback($sPattern, function($aMatches) use($oTemplate, $aVariables, $mixedKeyWrapperHtml, $sCheckIn) {
  1889. return $oTemplate->parseHtmlByName($aMatches[1], $aVariables, $mixedKeyWrapperHtml, $sCheckIn);
  1890. }, $sContent);
  1891. $sContent = $this->_parseContentKeys($sContent, array(
  1892. "'<bx_injection:([^\s]+) />'s" => 'get_injection',
  1893. "'<bx_menu:([^\s]+) \/>'s" => 'get_menu',
  1894. ));
  1895. }
  1896. catch(Exception $oException) {
  1897. return '';
  1898. }
  1899. $aKeys = array_merge($aKeys, array(
  1900. "'<bx_url_root />'",
  1901. "'<bx_url_studio />'",
  1902. ));
  1903. $aValues = array_merge($aValues, array(
  1904. BX_DOL_URL_ROOT,
  1905. BX_DOL_URL_STUDIO,
  1906. ));
  1907. //--- Parse Predefined Keys ---//
  1908. $sContent = preg_replace($aKeys, $aValues, $sContent);
  1909. //--- Parse System Keys ---//
  1910. $sContent = preg_replace_callback("'" . $aKeyWrappers['left'] . "([a-zA-Z0-9_-]+)" . $aKeyWrappers['right'] . "'", function($aMatches) use($oTemplate, $mixedKeyWrapperHtml) {
  1911. return $oTemplate->parseSystemKey($aMatches[1], $mixedKeyWrapperHtml);
  1912. }, $sContent);
  1913. return $sContent;
  1914. }
  1915. /**
  1916. * Compile content
  1917. *
  1918. * @param string $sContent template.
  1919. * @param string $aVarName variable name to be saved in the output file.
  1920. * @param integer $iVarDepth depth is used to process nesting, for example, in cycles.
  1921. * @param array $aVarValues values to be compiled in.
  1922. * @param mixed $mixedKeyWrapperHtml key wrapper(string value if left and right parts are the same, array(0 => left, 1 => right) otherwise).
  1923. * @return string the result of operation.
  1924. */
  1925. function _compileContent($sContent, $aVarName, $iVarDepth, $aVarValues, $mixedKeyWrapperHtml = null)
  1926. {
  1927. $aKeys = array_keys($aVarValues);
  1928. $aValues = array_values($aVarValues);
  1929. $aKeyWrappers = $this->_getKeyWrappers($mixedKeyWrapperHtml);
  1930. for($i = 0; $i < count($aKeys); $i++) {
  1931. if(strpos($aKeys[$i], 'bx_repeat:') === 0) {
  1932. $sKey = "'<" . $aKeys[$i] . ">(.*)<\/" . $aKeys[$i] . ">'s";
  1933. $aMatches = array();
  1934. preg_match($sKey, $sContent, $aMatches);
  1935. $sValue = '';
  1936. if(isset($aMatches[1]) && !empty($aMatches[1])) {
  1937. if(empty($aValues[$i]) || !is_array($aValues[$i]))
  1938. return false;
  1939. $sIndex = "\$" . str_repeat("i", $iVarDepth);
  1940. $sValue .= "<?php if(is_array(" . $aVarName . "['" . $aKeys[$i] . "'])) for(" . $sIndex . "=0; " . $sIndex . "<count(" . $aVarName . "['" . $aKeys[$i] . "']); " . $sIndex . "++){ ?>";
  1941. if(($sInnerValue = $this->_compileContent($aMatches[1], $aVarName . "['" . $aKeys[$i] . "'][" . $sIndex . "]", $iVarDepth + 1, current($aValues[$i]), $mixedKeyWrapperHtml)) === false)
  1942. return false;
  1943. $sValue .= $sInnerValue;
  1944. $sValue .= "<?php } else if(is_string(" . $aVarName . "['" . $aKeys[$i] . "'])) echo " . $aVarName . "['" . $aKeys[$i] . "']; ?>";
  1945. }
  1946. } else if(strpos($aKeys[$i], 'bx_if:') === 0) {
  1947. $sKey = "'<" . $aKeys[$i] . ">(.*)<\/" . $aKeys[$i] . ">'s";
  1948. $aMatches = array();
  1949. preg_match($sKey, $sContent, $aMatches);
  1950. $sValue = '';
  1951. if(isset($aMatches[1]) && !empty($aMatches[1])) {
  1952. if(!is_array($aValues[$i]) || !isset($aValues[$i]['content']) || empty($aValues[$i]['content']) || !is_array($aValues[$i]['content']))
  1953. return false;
  1954. $sValue .= "<?php if(" . $aVarName . "['" . $aKeys[$i] . "']['condition']){ ?>";
  1955. if(($sInnerValue = $this->_compileContent($aMatches[1], $aVarName . "['" . $aKeys[$i] . "']['content']", $iVarDepth, $aValues[$i]['content'], $mixedKeyWrapperHtml)) === false)
  1956. return false;
  1957. $sValue .= $sInnerValue;
  1958. $sValue .= "<?php } ?>";
  1959. }
  1960. } else {
  1961. $sKey = "'" . $aKeyWrappers['left'] . $aKeys[$i] . $aKeyWrappers['right'] . "'s";
  1962. $sValue = "<?php echo " . $aVarName . "['" . $aKeys[$i] . "'];?>";
  1963. }
  1964. $aKeys[$i] = $sKey;
  1965. $aValues[$i] = $sValue;
  1966. }
  1967. try {
  1968. $oTemplate = &$this;
  1969. $aCallbackPatterns = array(
  1970. "'<bx_include_auto:([^\s]+) \/>'s" => BX_DOL_TEMPLATE_CHECK_IN_BOTH,
  1971. "'<bx_include_base:([^\s]+) \/>'s" => BX_DOL_TEMPLATE_CHECK_IN_BASE,
  1972. "'<bx_include_tmpl:([^\s]+) \/>'s" => BX_DOL_TEMPLATE_CHECK_IN_TMPL
  1973. );
  1974. foreach($aCallbackPatterns as $sPattern => $sCheckIn)
  1975. $sContent = preg_replace_callback($sPattern, function($aMatches) use($oTemplate, $aVarValues, $mixedKeyWrapperHtml, $sCheckIn) {
  1976. $mixedResult = $oTemplate->getCached($aMatches[1], $aVarValues, $mixedKeyWrapperHtml, $sCheckIn, false);
  1977. if($mixedResult === false)
  1978. throw new Exception('Unable to create cache file.');
  1979. return $mixedResult;
  1980. }, $sContent);
  1981. $sContent = $this->_parseContentKeys($sContent);
  1982. }
  1983. catch(Exception $oException) {
  1984. return false;
  1985. }
  1986. $aKeys = array_merge($aKeys, array(
  1987. "'<bx_injection:([^\s]+) />'s",
  1988. "'<bx_menu:([^\s]+) \/>'s",
  1989. "'<bx_url_root />'",
  1990. "'<bx_url_studio />'"
  1991. ));
  1992. $aValues = array_merge($aValues, array(
  1993. "<?php echo \$this->processInjection(\$this->aPage['name_index'], '\\1'); ?>",
  1994. "<?php echo \$this->getMenu('\\1'); ?>",
  1995. BX_DOL_URL_ROOT,
  1996. BX_DOL_URL_STUDIO
  1997. ));
  1998. //--- Parse Predefined Keys ---//
  1999. $sContent = preg_replace($aKeys, $aValues, $sContent);
  2000. //--- Parse System Keys ---//
  2001. $sContent = preg_replace( "'" . $aKeyWrappers['left'] . "([a-zA-Z0-9_-]+)" . $aKeyWrappers['right'] . "'", "<?php echo \$this->parseSystemKey('\\1', \$mixedKeyWrapperHtml);?>", $sContent);
  2002. return $sContent;
  2003. }
  2004. protected function _parseContentKeys($sContent, $aCallbackPatterns = array())
  2005. {
  2006. $oTemplate = &$this;
  2007. $aCallbackPatterns = array_merge($aCallbackPatterns, array(
  2008. "'<bx_image_url:([^\s]+) \/>'s" => "get_image_url",
  2009. "'<bx_icon_url:([^\s]+) \/>'s" => "get_icon_url",
  2010. "'<bx_text:([_\{\}\w\d\s]+[^\s]{1}) \/>'s" => "get_text",
  2011. "'<bx_text_js:([^\s]+) \/>'s" => "get_text_js",
  2012. "'<bx_text_attribute:([^\s]+) \/>'s" => "get_text_attribute",
  2013. ));
  2014. foreach($aCallbackPatterns as $sPattern => $sAction)
  2015. $sContent = preg_replace_callback($sPattern, function($aMatches) use($oTemplate, $sAction) {
  2016. $sResult = '';
  2017. switch($sAction) {
  2018. case 'get_image_url':
  2019. $sResult = $oTemplate->getImageUrl($aMatches[1]);
  2020. break;
  2021. case 'get_icon_url':
  2022. $sResult = $oTemplate->getIconUrl($aMatches[1]);
  2023. break;
  2024. case 'get_text':
  2025. $sResult = _t($aMatches[1]);
  2026. break;
  2027. case 'get_text_js':
  2028. $sResult = bx_js_string(_t($aMatches[1]));
  2029. break;
  2030. case 'get_text_attribute':
  2031. $sResult = bx_html_attribute(_t($aMatches[1]));
  2032. break;
  2033. case 'get_injection':
  2034. $sResult = $oTemplate->processInjection($oTemplate->getPageNameIndex(), $aMatches[1]);
  2035. break;
  2036. case 'get_menu':
  2037. $sResult = $oTemplate->getMenu($aMatches[1]);
  2038. break;
  2039. }
  2040. return $sResult;
  2041. }, $sContent);
  2042. return $sContent;
  2043. }
  2044. /**
  2045. * Get absolute location of some template's part.
  2046. *
  2047. * @param string $sType - result type. Available values 'url' and 'path'.
  2048. * @param string $sFolder - folders to be searched in. @see $_sFolderHtml, $_sFolderCss, $_sFolderImages and $_sFolderIcons
  2049. * @param string $sName - requested part name.
  2050. * @param string $sCheckIn where the content would be searched(base, template, both)
  2051. * @return string absolute location (path/url) of the part.
  2052. */
  2053. function _getAbsoluteLocation($sType, $sFolder, $sName, $sCheckIn = BX_DOL_TEMPLATE_CHECK_IN_BOTH)
  2054. {
  2055. $sDirectory = $this->getPath();
  2056. if($sType == 'path') {
  2057. $sDivider = DIRECTORY_SEPARATOR;
  2058. $sRoot = BX_DIRECTORY_PATH_ROOT;
  2059. } else if($sType == 'url') {
  2060. $sDivider = '/';
  2061. $sRoot = BX_DOL_URL_ROOT;
  2062. }
  2063. if(strpos($sName,'|') !== false) {
  2064. $aParts = explode('|', $sName);
  2065. $sName = $aParts[1];
  2066. if(strpos($aParts[0],'@') !== false) {
  2067. $aLocationParts = explode('@', $aParts[0]);
  2068. $sLocationKey = $this->addLocation($aLocationParts[0], BX_DIRECTORY_PATH_ROOT . $aLocationParts[1], BX_DOL_URL_ROOT . $aLocationParts[1]);
  2069. }
  2070. }
  2071. $sResult = '';
  2072. $aLocations = array_reverse($this->_aLocations, true);
  2073. foreach($aLocations as $sKey => $aLocation) {
  2074. if(($sCheckIn == BX_DOL_TEMPLATE_CHECK_IN_BOTH || $sCheckIn == BX_DOL_TEMPLATE_CHECK_IN_TMPL) && extFileExists(BX_DIRECTORY_PATH_MODULES . $this->getPath(). 'data' . DIRECTORY_SEPARATOR . BX_DOL_TEMPLATE_FOLDER_ROOT . DIRECTORY_SEPARATOR . $sKey . DIRECTORY_SEPARATOR . $sFolder . $sName))
  2075. $sResult = $sRoot . 'modules' . $sDivider . $sDirectory. 'data' . $sDivider . BX_DOL_TEMPLATE_FOLDER_ROOT . $sDivider . $sKey . $sDivider . $sFolder . $sName;
  2076. else if(($sCheckIn == BX_DOL_TEMPLATE_CHECK_IN_BOTH || $sCheckIn == BX_DOL_TEMPLATE_CHECK_IN_BASE) && extFileExists($aLocation['path'] . BX_DOL_TEMPLATE_FOLDER_ROOT . DIRECTORY_SEPARATOR . $sFolder . $sName))
  2077. $sResult = $aLocation[$sType] . BX_DOL_TEMPLATE_FOLDER_ROOT . $sDivider . $sFolder . $sName;
  2078. else
  2079. continue;
  2080. break;
  2081. }
  2082. /**
  2083. * try to find from received path
  2084. */
  2085. if(!$sResult && @is_file(BX_DIRECTORY_PATH_ROOT . $aParts[0] . DIRECTORY_SEPARATOR . $aParts[1])) {
  2086. $sResult = $sRoot . $aParts[0] . $sDivider . $aParts[1];
  2087. }
  2088. if(isset($sLocationKey))
  2089. $this->removeLocation($sLocationKey);
  2090. return $sType == 'path' && !empty($sResult) ? realpath($sResult) : $sResult;
  2091. }
  2092. /**
  2093. * Get absolute location of some template's part.
  2094. *
  2095. * @param string $sType result type. Available values 'url' and 'path'.
  2096. * @param string $sName requested part name.
  2097. * @return string absolute location (path/url) of the part.
  2098. */
  2099. function _getAbsoluteLocationJs($sType, $sName)
  2100. {
  2101. $sResult = '';
  2102. $aLocations = array_reverse($this->_aLocationsJs, true);
  2103. foreach($aLocations as $sKey => $aLocation) {
  2104. if(extFileExists($aLocation['path'] . $sName))
  2105. $sResult = $aLocation[$sType] . $sName;
  2106. else
  2107. continue;
  2108. break;
  2109. }
  2110. return $sType == 'path' && !empty($sResult) ? realpath($sResult) : $sResult;
  2111. }
  2112. function _getAbsoluteLocationCss($sType, $sName)
  2113. {
  2114. $sNameLess = str_replace('.css', '.less', $sName);
  2115. $sResult = $this->_getAbsoluteLocation($sType, $this->_sFolderCss, $sNameLess);
  2116. if(!empty($sResult))
  2117. return $sResult;
  2118. return $this->_getAbsoluteLocation($sType, $this->_sFolderCss, $sName);
  2119. }
  2120. /**
  2121. * Get inline data for Images and Icons.
  2122. *
  2123. * @param string $sType image/icon
  2124. * @param string $sName file name
  2125. * @param string $sCheckIn where the content would be searched(base, template, both)
  2126. * @return unknown
  2127. */
  2128. function _getInlineData($sType, $sName, $sCheckIn)
  2129. {
  2130. switch($sType) {
  2131. case 'image':
  2132. $sFolder = $this->_sFolderImages;
  2133. break;
  2134. case 'icon':
  2135. $sFolder = $this->_sFolderIcons;
  2136. break;
  2137. }
  2138. $sPath = $this->_getAbsoluteLocation('path', $sFolder, $sName, $sCheckIn);
  2139. $iFileSize = 0;
  2140. if($this->_bImagesInline && ($iFileSize = filesize($sPath)) !== false && $iFileSize < $this->_iImagesMaxSize) {
  2141. $aFileInfo = pathinfo($sPath);
  2142. return "data:image/" . strtolower($aFileInfo['extension']) . ";base64," . base64_encode(file_get_contents($sPath));
  2143. }
  2144. return false;
  2145. }
  2146. /**
  2147. * Get file name where the template would be cached.
  2148. *
  2149. * @param string $sAbsolutePath template's real path.
  2150. * @return string the result of operation.
  2151. */
  2152. function _getCacheFileName($sType, $sAbsolutePath)
  2153. {
  2154. $sResult = bx_site_hash($sAbsolutePath);
  2155. switch($sType) {
  2156. case 'html':
  2157. $sResult = $this->_sCacheFilePrefix . bx_lang_name() . '_' . $this->_sCode . '_' . $sResult;
  2158. break;
  2159. case 'css':
  2160. $sResult = $this->_sCssCachePrefix . $sResult;
  2161. break;
  2162. case 'js':
  2163. $sResult = $this->_sJsCachePrefix . $sResult;
  2164. break;
  2165. }
  2166. return $sResult;
  2167. }
  2168. /**
  2169. * Get template key wrappers(left, right)
  2170. *
  2171. * @param mixed $mixedKeyWrapperHtml key wrapper(string value if left and right parts are the same, array(0 => left, 1 => right) otherwise).
  2172. * @return array result of operation.
  2173. */
  2174. function _getKeyWrappers($mixedKeyWrapperHtml)
  2175. {
  2176. $aResult = array();
  2177. if(!empty($mixedKeyWrapperHtml) && is_string($mixedKeyWrapperHtml))
  2178. $aResult = array('left' => $mixedKeyWrapperHtml, 'right' => $mixedKeyWrapperHtml);
  2179. else if(!empty($mixedKeyWrapperHtml) && is_array($mixedKeyWrapperHtml))
  2180. $aResult = array('left' => $mixedKeyWrapperHtml[0], 'right' => $mixedKeyWrapperHtml[1]);
  2181. else
  2182. $aResult = array('left' => $this->_sKeyWrapperHtml, 'right' => $this->_sKeyWrapperHtml);
  2183. return $aResult;
  2184. }
  2185. /**
  2186. * Process all added language translations and return them as a string.
  2187. *
  2188. * @return string with JS code.
  2189. */
  2190. function _processJsTranslations()
  2191. {
  2192. $sReturn = '';
  2193. if(isset($this->aPage['js_translations']) && is_array($this->aPage['js_translations'])) {
  2194. foreach($this->aPage['js_translations'] as $sKey => $sString)
  2195. $sReturn .= "'" . bx_js_string($sKey) . "': '" . bx_js_string($sString) . "',";
  2196. $sReturn = substr($sReturn, 0, -1);
  2197. }
  2198. return '<script type="text/javascript" language="javascript">var aDolLang = {' . $sReturn . '};</script>';
  2199. }
  2200. /**
  2201. * Process all added options and return them as a string.
  2202. *
  2203. * @return string with JS code.
  2204. */
  2205. function _processJsOptions()
  2206. {
  2207. $sReturn = '';
  2208. if(isset($this->aPage['js_options']) && is_array($this->aPage['js_options'])) {
  2209. foreach($this->aPage['js_options'] as $sName => $mixedValue)
  2210. $sReturn .= "'" . bx_js_string($sName) . "': '" . bx_js_string($mixedValue) . "',";
  2211. $sReturn = substr($sReturn, 0, -1);
  2212. }
  2213. return '<script type="text/javascript" language="javascript">var aDolOptions = {' . $sReturn . '};</script>';
  2214. }
  2215. /**
  2216. * Process all added images and return them as a string.
  2217. *
  2218. * @return string with JS code.
  2219. */
  2220. function _processJsImages()
  2221. {
  2222. $sReturn = '';
  2223. if(isset($this->aPage['js_images']) && is_array($this->aPage['js_images'])) {
  2224. foreach($this->aPage['js_images'] as $sKey => $sUrl)
  2225. $sReturn .= "'" . bx_js_string($sKey) . "': '" . bx_js_string($sUrl) . "',";
  2226. $sReturn = substr($sReturn, 0, -1);
  2227. }
  2228. return '<script type="text/javascript" language="javascript">var aDolImages = {' . $sReturn . '};</script>';
  2229. }
  2230. /**
  2231. * Get Gzip loader URL.
  2232. *
  2233. * @param $sType content type CSS/JS
  2234. * @param $sName file name.
  2235. * @return string with URL
  2236. */
  2237. function _getLoaderUrl($sType, $sName)
  2238. {
  2239. return BX_DOL_URL_ROOT . 'gzip_loader.php?file=' . $sName . '.' . $sType;
  2240. }
  2241. /**
  2242. *
  2243. * Functions to display pages with errors, messages and so on.
  2244. *
  2245. */
  2246. function displayAccessDenied ($sMsg = '')
  2247. {
  2248. bx_import('BxDolLanguages');
  2249. header("HTTP/1.0 403 Forbidden");
  2250. $this->displayMsg($sMsg ? $sMsg : _t('_Access denied'));
  2251. }
  2252. function displayNoData ($sMsg = '')
  2253. {
  2254. bx_import('BxDolLanguages');
  2255. header("HTTP/1.0 204 No Content");
  2256. $this->displayMsg($sMsg ? $sMsg : _t('_Empty'));
  2257. }
  2258. function displayErrorOccured ($sMsg = '')
  2259. {
  2260. bx_import('BxDolLanguages');
  2261. header("HTTP/1.0 500 Internal Server Error");
  2262. $this->displayMsg($sMsg ? $sMsg : _t('_error occured'));
  2263. }
  2264. function displayPageNotFound ($sMsg = '')
  2265. {
  2266. bx_import('BxDolLanguages');
  2267. header("HTTP/1.0 404 Not Found");
  2268. $this->displayMsg($sMsg ? $sMsg : _t('_sys_request_page_not_found_cpt'));
  2269. }
  2270. function displayMsg ($s, $bTranslate = false)
  2271. {
  2272. $sTitle = $bTranslate ? _t($s) : $s;
  2273. $oTemplate = BxDolTemplate::getInstance();
  2274. $oTemplate->setPageNameIndex (BX_PAGE_DEFAULT);
  2275. $oTemplate->setPageHeader (_t('_Error'));
  2276. $oTemplate->setPageContent ('page_main_code', DesignBoxContent(_t('_Error'), MsgBox($sTitle), BX_DB_PADDING_DEF));
  2277. $oTemplate->getPageCode();
  2278. exit;
  2279. }
  2280. /**
  2281. * * * * Static methods for work with template injections * * *
  2282. *
  2283. * Static method is used to add/replace the content of some key in the template.
  2284. * It's usefull when you don't want to modify existing template but need to add some data to existing template key.
  2285. *
  2286. * @param integer $iPageIndex - page index where injections would processed. Use 0 if you want it to be done on all the pages.
  2287. * @param string $sKey - template key.
  2288. * @param string $sValue - the data to be added.
  2289. * @return string the result of operation.
  2290. */
  2291. function processInjection($iPageIndex, $sKey, $sValue = "")
  2292. {
  2293. if($iPageIndex != 0 && isset($this->aPage['injections']['page_0'][$sKey]) && isset($this->aPage['injections']['page_' . $iPageIndex][$sKey]))
  2294. $aSelection = @array_merge($this->aPage['injections']['page_0'][$sKey], $this->aPage['injections']['page_' . $iPageIndex][$sKey]);
  2295. else if(isset($this->aPage['injections']['page_0'][$sKey]))
  2296. $aSelection = $this->aPage['injections']['page_0'][$sKey];
  2297. else if(isset($this->aPage['injections']['page_' . $iPageIndex][$sKey]))
  2298. $aSelection = $this->aPage['injections']['page_' . $iPageIndex][$sKey];
  2299. else
  2300. $aSelection = array();
  2301. if(is_array($aSelection))
  2302. foreach($aSelection as $aInjection) {
  2303. if (isset($GLOBALS['bx_profiler'])) $GLOBALS['bx_profiler']->beginInjection($sRand = time().rand());
  2304. $sInjData = '';
  2305. switch($aInjection['type']) {
  2306. case 'text':
  2307. $sInjData = $aInjection['data'];
  2308. break;
  2309. case 'service':
  2310. if(BxDolService::isSerializedService($aInjection['data']))
  2311. $sInjData = BxDolService::callSerialized($aInjection['data']);
  2312. break;
  2313. }
  2314. if((int)$aInjection['replace'] == 1)
  2315. $sValue = $sInjData;
  2316. else
  2317. $sValue .= $sInjData;
  2318. if (isset($GLOBALS['bx_profiler'])) $GLOBALS['bx_profiler']->endInjection($sRand, $aInjection);
  2319. }
  2320. return $sValue != '__' . $sKey . '__' ? str_replace('__' . $sKey . '__', '', $sValue) : $sValue;
  2321. }
  2322. /**
  2323. * Static method to add ingection available on the current page only.
  2324. *
  2325. * @param string $sKey - template's key.
  2326. * @param string $sType - injection type(text, php).
  2327. * @param string $sData - the data to be added.
  2328. * @param integer $iReplace - replace already existed data or not.
  2329. */
  2330. function addInjection($sKey, $sType, $sData, $iReplace = 0)
  2331. {
  2332. $this->aPage['injections']['page_0'][$sKey][] = array(
  2333. 'page_index' => 0,
  2334. 'key' => $sKey,
  2335. 'type' => $sType,
  2336. 'data' => $sData,
  2337. 'replace' => $iReplace
  2338. );
  2339. }
  2340. function getPageCode($oTemplate = null)
  2341. {
  2342. if (empty($oTemplate))
  2343. $oTemplate = $this;
  2344. $oZ = new BxDolAlerts('system', 'design_before_output', 0, 0, array('page' => &$this->aPage, 'page_content' => &$this->aPageContent));
  2345. $oZ->alert();
  2346. header( 'Content-type: text/html; charset=utf-8' );
  2347. header( 'X-Frame-Options: sameorigin' );
  2348. echo $oTemplate->parsePageByName('page_' . $oTemplate->getPageNameIndex() . '.html', $oTemplate->getPageContent());
  2349. }
  2350. }
  2351. /** @} */