BxDolTemplate.php 131 KB

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