BxDolTemplate.php 138 KB

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