BxDolTemplate.php 140 KB

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