BxDolTemplate.php 136 KB

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