BxDolTemplate.php 113 KB

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