BxDolTemplate.php 98 KB

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