BxDolTemplate.php 115 KB

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