BxDolTemplate.php 140 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836
  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. ]);
  2863. $aValues = array_merge($aValues, [
  2864. "<?php echo \$this->getMenu('\\1'); ?>",
  2865. BX_DOL_URL_ROOT,
  2866. BX_DOL_URL_STUDIO,
  2867. ]);
  2868. //--- Parse Predefined Keys ---//
  2869. $sContent = preg_replace($aKeys, $aValues, $sContent);
  2870. //--- Parse System Keys ---//
  2871. $sContent = preg_replace( "'" . $aKeyWrappers['left'] . "([a-zA-Z0-9_-]+)" . $aKeyWrappers['right'] . "'", "<?php echo \$this->parseSystemKey('\\1', \$mixedKeyWrapperHtml);?>", $sContent);
  2872. return $sContent;
  2873. }
  2874. protected function _parseContentKeys($sContent, $aCallbackPatterns = array())
  2875. {
  2876. $oTemplate = &$this;
  2877. $aCallbackPatterns = array_merge($aCallbackPatterns, array(
  2878. "'<bx_image_auto:([^\s]+) \/>'s" => "get_image_auto",
  2879. "'<bx_image_url:([^\s]+) \/>'s" => "get_image_url",
  2880. "'<bx_icon_url:([^\s]+) \/>'s" => "get_icon_url",
  2881. "'<bx_icon_inline:([^\s]+) \/>'s" => "get_icon_inline",
  2882. "'<bx_text:([_\{\}\w\d\s]+[^\s]{1}) \/>'s" => "get_text",
  2883. "'<bx_text_js:([^\s]+) \/>'s" => "get_text_js",
  2884. "'<bx_text_attribute:([^\s]+) \/>'s" => "get_text_attribute",
  2885. "'<bx_page:([^\s]+) \/>'s" => "get_page",
  2886. ));
  2887. foreach($aCallbackPatterns as $sPattern => $sAction)
  2888. $sContent = preg_replace_callback($sPattern, function($aMatches) use($oTemplate, $sAction) {
  2889. $sResult = '';
  2890. switch($sAction) {
  2891. case 'get_image_auto':
  2892. $sResult = $oTemplate->getImageAuto($aMatches[1]);
  2893. break;
  2894. case 'get_image_url':
  2895. $sResult = $oTemplate->getImageUrl($aMatches[1]);
  2896. break;
  2897. case 'get_icon_url':
  2898. $sResult = $oTemplate->getIconUrl($aMatches[1]);
  2899. break;
  2900. case 'get_icon_inline':
  2901. if(($sResult = $this->getIconContent($aMatches[1])) === false)
  2902. $sResult = '';
  2903. break;
  2904. case 'get_text':
  2905. $sResult = _t($aMatches[1]);
  2906. break;
  2907. case 'get_text_js':
  2908. $sResult = bx_js_string(_t($aMatches[1]));
  2909. break;
  2910. case 'get_text_attribute':
  2911. $sResult = bx_html_attribute(_t($aMatches[1]));
  2912. break;
  2913. case 'get_injection':
  2914. $sResult = $oTemplate->processInjection($oTemplate->getPageNameIndex(), $aMatches[1]);
  2915. break;
  2916. case 'get_menu':
  2917. $sResult = $oTemplate->getMenu($aMatches[1]);
  2918. break;
  2919. case 'get_page':
  2920. $oPage = BxDolPage::getObjectInstanceByURI($aMatches[1], false, true);
  2921. $oPage->setSubPage(true);
  2922. $sResult = $oPage ? $oPage->getCode() : '';
  2923. break;
  2924. }
  2925. return $sResult;
  2926. }, $sContent);
  2927. return $sContent;
  2928. }
  2929. /**
  2930. * Get absolute location of some template's part.
  2931. *
  2932. * @param string $sType - result type. Available values 'url' and 'path'.
  2933. * @param string $sFolder - folders to be searched in. @see $_sFolderHtml, $_sFolderCss, $_sFolderImages and $_sFolderIcons
  2934. * @param string $sName - requested part name.
  2935. * @param string $sCheckIn where the content would be searched(base, template, both)
  2936. * @return string absolute location (path/url) of the part.
  2937. */
  2938. function _getAbsoluteLocation($sType, $sFolder, $sName, $sCheckIn = BX_DOL_TEMPLATE_CHECK_IN_BOTH)
  2939. {
  2940. $sDirectory = $this->getPath();
  2941. if($sType == 'path') {
  2942. $sDivider = DIRECTORY_SEPARATOR;
  2943. $sRoot = BX_DIRECTORY_PATH_ROOT;
  2944. } else if($sType == 'url') {
  2945. $sDivider = '/';
  2946. $sRoot = BX_DOL_URL_ROOT;
  2947. }
  2948. $aParts = [];
  2949. if(strpos($sName,'|') !== false) {
  2950. $aParts = explode('|', $sName);
  2951. $sName = $aParts[1];
  2952. if(strpos($aParts[0],'@') !== false) {
  2953. $aLocationParts = explode('@', $aParts[0]);
  2954. $sLocationKey = $this->addLocation($aLocationParts[0], BX_DIRECTORY_PATH_ROOT . $aLocationParts[1], BX_DOL_URL_ROOT . $aLocationParts[1]);
  2955. }
  2956. }
  2957. /**
  2958. * Module(mod) related locations will be checked first in TMPL and BASE,
  2959. * then system(sys) location(s) will be checked in TMPL and BASE.
  2960. */
  2961. $aLocationsList = array_reverse($this->_aLocations, true);
  2962. $aLocationsGrouped = ['mod' => [], 'sys' => []];
  2963. foreach($aLocationsList as $sLocation => $aLocation) {
  2964. if(in_array($sLocation, ['system', 'studio']))
  2965. $aLocationsGrouped['sys'][$sLocation] = $aLocation;
  2966. else
  2967. $aLocationsGrouped['mod'][$sLocation] = $aLocation;
  2968. }
  2969. $sResult = '';
  2970. foreach($aLocationsGrouped as $aLocations) {
  2971. //--- Check it Template.
  2972. $bInSub = false;
  2973. $aCheckIn = [BX_DOL_TEMPLATE_CHECK_IN_BOTH, BX_DOL_TEMPLATE_CHECK_IN_TMPL];
  2974. if(in_array($sCheckIn, $aCheckIn) || $bInSub = (isset($sCheckIn['in'], $sCheckIn['sub']) && in_array($sCheckIn['in'], $aCheckIn)))
  2975. foreach($aLocations as $sKey => $aLocation)
  2976. 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)) {
  2977. $sResult = $sRoot . 'modules' . $sDivider . $sDirectory. 'data' . $sDivider . BX_DOL_TEMPLATE_FOLDER_ROOT . $sDivider . $sKey . $sDivider . $sFolder . $sName;
  2978. break 2;
  2979. }
  2980. //--- Check it Base.
  2981. $bInSub = false;
  2982. $aCheckIn = [BX_DOL_TEMPLATE_CHECK_IN_BOTH, BX_DOL_TEMPLATE_CHECK_IN_BASE];
  2983. if(empty($sResult) && (in_array($sCheckIn, $aCheckIn) || $bInSub = (isset($sCheckIn['in'], $sCheckIn['sub']) && in_array($sCheckIn['in'], $aCheckIn))))
  2984. foreach($aLocations as $sKey => $aLocation)
  2985. if((!$bInSub || $sCheckIn['sub'] == $sKey) && extFileExists($aLocation['path'] . BX_DOL_TEMPLATE_FOLDER_ROOT . DIRECTORY_SEPARATOR . $sFolder . $sName)) {
  2986. $sResult = $aLocation[$sType] . BX_DOL_TEMPLATE_FOLDER_ROOT . $sDivider . $sFolder . $sName;
  2987. break 2;
  2988. }
  2989. }
  2990. /**
  2991. * try to find from received path
  2992. */
  2993. if(!$sResult && isset($aParts[0], $aParts[1]) && @is_file(BX_DIRECTORY_PATH_ROOT . $aParts[0] . DIRECTORY_SEPARATOR . $aParts[1]))
  2994. $sResult = $sRoot . $aParts[0] . $sDivider . $aParts[1];
  2995. if(isset($sLocationKey))
  2996. $this->removeLocation($sLocationKey);
  2997. return $sType == 'path' && !empty($sResult) ? realpath($sResult) : $sResult;
  2998. }
  2999. /**
  3000. * Get absolute location of some template's part.
  3001. *
  3002. * @param string $sType result type. Available values 'url' and 'path'.
  3003. * @param string $sName requested part name.
  3004. * @return string absolute location (path/url) of the part.
  3005. */
  3006. function _getAbsoluteLocationJs($sType, $sName)
  3007. {
  3008. $sResult = '';
  3009. $aLocations = array_reverse($this->_aLocationsJs, true);
  3010. foreach($aLocations as $sKey => $aLocation) {
  3011. if(extFileExists($aLocation['path'] . $sName))
  3012. $sResult = $aLocation[$sType] . $sName;
  3013. else
  3014. continue;
  3015. break;
  3016. }
  3017. return $sType == 'path' && !empty($sResult) ? realpath($sResult) : $sResult;
  3018. }
  3019. function _getAbsoluteLocationCss($sType, $sName)
  3020. {
  3021. $sNameLess = str_replace('.css', '.less', $sName);
  3022. $sResult = $this->_getAbsoluteLocation($sType, $this->_sFolderCss, $sNameLess);
  3023. if(!empty($sResult))
  3024. return $sResult;
  3025. return $this->_getAbsoluteLocation($sType, $this->_sFolderCss, $sName);
  3026. }
  3027. /**
  3028. * Get inline data for Images and Icons.
  3029. *
  3030. * @param string $sType image/icon
  3031. * @param string $sName file name
  3032. * @param string $sCheckIn where the content would be searched(base, template, both)
  3033. * @return unknown
  3034. */
  3035. function _getInlineData($sType, $sName, $sCheckIn, $bForceInline = false)
  3036. {
  3037. switch($sType) {
  3038. case 'image':
  3039. $sFolder = $this->_sFolderImages;
  3040. break;
  3041. case 'icon':
  3042. $sFolder = $this->_sFolderIcons;
  3043. break;
  3044. }
  3045. $sPath = $this->_getAbsoluteLocation('path', $sFolder, $sName, $sCheckIn);
  3046. $iFileSize = 0;
  3047. if(($this->_bImagesInline && ($iFileSize = filesize($sPath)) !== false && $iFileSize < $this->_iImagesMaxSize) || $bForceInline) {
  3048. $aFileInfo = pathinfo($sPath);
  3049. return $this->getImageMimeType($aFileInfo['extension']) . ";base64," . base64_encode(file_get_contents($sPath));
  3050. }
  3051. return false;
  3052. }
  3053. /**
  3054. * Get file name where the template would be cached.
  3055. *
  3056. * @param string $sAbsolutePath template's real path.
  3057. * @return string the result of operation.
  3058. */
  3059. function _getCacheFileName($sType, $sAbsolutePath)
  3060. {
  3061. $sResult = bx_site_hash($sAbsolutePath);
  3062. switch($sType) {
  3063. case 'html':
  3064. $sResult = $this->_sCacheFilePrefix . bx_lang_name() . '_' . $this->_sCode . '_' . $sResult;
  3065. break;
  3066. case 'css':
  3067. $sResult = $this->_sCssCachePrefix . (!empty($this->_iMix) ? $this->_iMix . '_' : '') . $sResult;
  3068. break;
  3069. case 'js':
  3070. $sResult = $this->_sJsCachePrefix . $sResult;
  3071. break;
  3072. }
  3073. return $sResult;
  3074. }
  3075. /**
  3076. * Get template key wrappers(left, right)
  3077. *
  3078. * @param mixed $mixedKeyWrapperHtml key wrapper(string value if left and right parts are the same, array(0 => left, 1 => right) otherwise).
  3079. * @return array result of operation.
  3080. */
  3081. function _getKeyWrappers($mixedKeyWrapperHtml)
  3082. {
  3083. $aResult = array();
  3084. if(!empty($mixedKeyWrapperHtml) && is_string($mixedKeyWrapperHtml))
  3085. $aResult = array('left' => $mixedKeyWrapperHtml, 'right' => $mixedKeyWrapperHtml);
  3086. else if(!empty($mixedKeyWrapperHtml) && is_array($mixedKeyWrapperHtml))
  3087. $aResult = array('left' => $mixedKeyWrapperHtml[0], 'right' => $mixedKeyWrapperHtml[1]);
  3088. else
  3089. $aResult = array('left' => $this->_sKeyWrapperHtml, 'right' => $this->_sKeyWrapperHtml);
  3090. return $aResult;
  3091. }
  3092. /**
  3093. * Process all added language translations and return them as a string.
  3094. *
  3095. * @return string with JS code.
  3096. */
  3097. function _processJsTranslations()
  3098. {
  3099. $sReturn = '';
  3100. if(isset($this->aPage['js_translations']) && is_array($this->aPage['js_translations'])) {
  3101. foreach($this->aPage['js_translations'] as $sKey => $sString)
  3102. $sReturn .= "'" . bx_js_string($sKey) . "': '" . bx_js_string($sString) . "',";
  3103. $sReturn = substr($sReturn, 0, -1);
  3104. }
  3105. return '
  3106. <script language="javascript">
  3107. if (\'undefined\' === typeof(aDolLang))
  3108. var aDolLang = {' . $sReturn . '};
  3109. else
  3110. $.extend(aDolLang, {' . $sReturn . '});
  3111. </script>';
  3112. }
  3113. /**
  3114. * Process all added options and return them as a string.
  3115. *
  3116. * @return string with JS code.
  3117. */
  3118. function _processJsOptions()
  3119. {
  3120. $sReturn = '';
  3121. if(isset($this->aPage['js_options']) && is_array($this->aPage['js_options'])) {
  3122. foreach($this->aPage['js_options'] as $sName => $mixedValue)
  3123. $sReturn .= "'" . bx_js_string($sName) . "': '" . bx_js_string($mixedValue) . "',";
  3124. $sReturn = substr($sReturn, 0, -1);
  3125. }
  3126. return '<script language="javascript">var aDolOptions = {' . $sReturn . '};</script>';
  3127. }
  3128. /**
  3129. * Process all added images and return them as a string.
  3130. *
  3131. * @return string with JS code.
  3132. */
  3133. function _processJsImages()
  3134. {
  3135. $sReturn = '';
  3136. if(isset($this->aPage['js_images']) && is_array($this->aPage['js_images'])) {
  3137. foreach($this->aPage['js_images'] as $sKey => $sUrl)
  3138. $sReturn .= "'" . bx_js_string($sKey) . "': '" . bx_js_string($sUrl) . "',";
  3139. $sReturn = substr($sReturn, 0, -1);
  3140. }
  3141. return '<script language="javascript">var aDolImages = {' . $sReturn . '};</script>';
  3142. }
  3143. /**
  3144. * Get Gzip loader URL.
  3145. *
  3146. * @param $sType content type CSS/JS
  3147. * @param $sName file name.
  3148. * @return string with URL
  3149. */
  3150. function _getLoaderUrl($sType, $sName)
  3151. {
  3152. return BX_DOL_URL_ROOT . 'gzip_loader.php?file=' . $sName . '.' . $sType;
  3153. }
  3154. /**
  3155. * Get current revision number.
  3156. *
  3157. * @return integer number
  3158. */
  3159. public function getRevision()
  3160. {
  3161. return (int)getParam('sys_revision');
  3162. }
  3163. /**
  3164. * Add current revision number to URL.
  3165. *
  3166. * @return string with URL
  3167. */
  3168. public function addRevision($sUrl)
  3169. {
  3170. return bx_append_url_params($sUrl, ['rev' => $this->getRevision()]);
  3171. }
  3172. /**
  3173. *
  3174. * Functions to display pages with errors, messages and so on.
  3175. *
  3176. */
  3177. function displayAccessDenied ($sMsg = '', $iPage = BX_PAGE_DEFAULT, $iDesignBox = BX_DB_PADDING_DEF)
  3178. {
  3179. bx_import('BxDolLanguages');
  3180. header('HTTP/1.0 403 Forbidden');
  3181. header('Status: 403 Forbidden');
  3182. $a = [
  3183. 'title' => _t('_access_denied_page_title'),
  3184. 'content' => _t('_access_denied_page_content'),
  3185. ];
  3186. $this->displayMsg($sMsg ? $sMsg : _t('_Access denied'), false, $iPage, $iDesignBox);
  3187. }
  3188. function displayNoData ($sMsg = '', $iPage = BX_PAGE_DEFAULT, $iDesignBox = BX_DB_PADDING_DEF)
  3189. {
  3190. bx_import('BxDolLanguages');
  3191. header('HTTP/1.0 204 No Content');
  3192. header('Status: 204 No Content');
  3193. $this->displayMsg($sMsg ? $sMsg : _t('_Empty'), false, $iPage, $iDesignBox);
  3194. }
  3195. function displayErrorOccured ($sMsg = '', $iPage = BX_PAGE_DEFAULT, $iDesignBox = BX_DB_PADDING_DEF)
  3196. {
  3197. bx_import('BxDolLanguages');
  3198. header('HTTP/1.0 500 Internal Server Error');
  3199. header('Status: 500 Internal Server Error');
  3200. $this->displayMsg($sMsg ? $sMsg : _t('_error occured'), false, $iPage, $iDesignBox);
  3201. }
  3202. function displayPageNotFound ($sMsg = '', $iPage = BX_PAGE_DEFAULT, $iDesignBox = BX_DB_PADDING_DEF)
  3203. {
  3204. bx_import('BxDolLanguages');
  3205. header('HTTP/1.0 404 Not Found');
  3206. header('Status: 404 Not Found');
  3207. $this->displayMsg($sMsg ? $sMsg : _t('_sys_request_page_not_found_cpt'), false, $iPage, $iDesignBox);
  3208. }
  3209. function displayMsg ($s, $bTranslate = false, $iPage = BX_PAGE_DEFAULT, $iDesignBox = BX_DB_PADDING_DEF)
  3210. {
  3211. $sError = '_Error';
  3212. $bArray = is_array($s);
  3213. $sTitle = $bArray ? $s['title'] : ($bTranslate ? $sError : _t($sError));
  3214. $sContent = $bArray ? $s['content'] : $s;
  3215. if($bTranslate) {
  3216. $sTitle = _t($sTitle);
  3217. $sContent = _t($sContent);
  3218. }
  3219. if (bx_is_api())
  3220. return [bx_api_get_msg($sContent)];
  3221. $sContent = MsgBox($sContent);
  3222. if($iPage == BX_PAGE_DEFAULT)
  3223. $sContent = DesignBoxContent($sTitle, $sContent, $iDesignBox);
  3224. $oTemplate = BxDolTemplate::getInstance();
  3225. $oTemplate->setPageNameIndex ($iPage);
  3226. $oTemplate->setPageHeader ($sTitle);
  3227. $oTemplate->setPageContent ('page_main_code', $sContent);
  3228. $oTemplate->getPageCode();
  3229. exit;
  3230. }
  3231. /**
  3232. * * * * Static methods for work with template injections * * *
  3233. *
  3234. * Static method is used to add/replace the content of some key in the template.
  3235. * It's usefull when you don't want to modify existing template but need to add some data to existing template key.
  3236. *
  3237. * @param integer $iPageIndex - page index where injections would processed. Use 0 if you want it to be done on all the pages.
  3238. * @param string $sKey - template key.
  3239. * @param string $sValue - the data to be added.
  3240. * @return string the result of operation.
  3241. */
  3242. function processInjection($iPageIndex, $sKey, $sValue = "")
  3243. {
  3244. if($iPageIndex != 0 && isset($this->aPage['injections']['page_0'][$sKey]) && isset($this->aPage['injections']['page_' . $iPageIndex][$sKey]))
  3245. $aSelection = @array_merge($this->aPage['injections']['page_0'][$sKey], $this->aPage['injections']['page_' . $iPageIndex][$sKey]);
  3246. else if(isset($this->aPage['injections']['page_0'][$sKey]))
  3247. $aSelection = $this->aPage['injections']['page_0'][$sKey];
  3248. else if(isset($this->aPage['injections']['page_' . $iPageIndex][$sKey]))
  3249. $aSelection = $this->aPage['injections']['page_' . $iPageIndex][$sKey];
  3250. else
  3251. $aSelection = array();
  3252. if(is_array($aSelection))
  3253. foreach($aSelection as $aInjection) {
  3254. if (isset($GLOBALS['bx_profiler'])) $GLOBALS['bx_profiler']->beginInjection($sRand = time().rand());
  3255. $sInjData = '';
  3256. switch($aInjection['type']) {
  3257. case 'text':
  3258. $sInjData = $aInjection['data'];
  3259. break;
  3260. case 'service':
  3261. if(BxDolService::isSerializedService($aInjection['data']))
  3262. $sInjData = BxDolService::callSerialized($aInjection['data']);
  3263. break;
  3264. }
  3265. if((int)$aInjection['replace'] == 1)
  3266. $sValue = $sInjData;
  3267. else
  3268. $sValue .= $sInjData;
  3269. if (isset($GLOBALS['bx_profiler'])) $GLOBALS['bx_profiler']->endInjection($sRand, $aInjection);
  3270. }
  3271. return $sValue != '__' . $sKey . '__' ? str_replace('__' . $sKey . '__', '', $sValue) : $sValue;
  3272. }
  3273. /**
  3274. * Static method to add ingection available on the current page only.
  3275. *
  3276. * @param string $sKey - template's key.
  3277. * @param string $sType - injection type(text, php).
  3278. * @param string $sData - the data to be added.
  3279. * @param integer $iReplace - replace already existed data or not.
  3280. */
  3281. function addInjection($sKey, $sType, $sData, $iReplace = 0)
  3282. {
  3283. $this->aPage['injections']['page_0'][$sKey][] = array(
  3284. 'page_index' => 0,
  3285. 'key' => $sKey,
  3286. 'type' => $sType,
  3287. 'data' => $sData,
  3288. 'replace' => $iReplace
  3289. );
  3290. }
  3291. function getPageCode($oTemplate = null)
  3292. {
  3293. if (empty($oTemplate))
  3294. $oTemplate = $this;
  3295. /**
  3296. * @hooks
  3297. * @hookdef hook-system-design_before_output 'system', 'design_before_output' - hook on before page's html generated
  3298. * - $unit_name - equals `system`
  3299. * - $action - equals `design_before_output`
  3300. * - $object_id - not used
  3301. * - $sender_id - not used
  3302. * - $extra_params - array of additional params with the following array keys:
  3303. * - `page` - [array] by ref, page object paramenters, can be overridden in hook processing
  3304. * - `page_content` - [array] by ref, page content values, can be overridden in hook processing
  3305. * @hook @ref hook-system-design_before_output
  3306. */
  3307. bx_alert('system', 'design_before_output', 0, 0, ['page' => &$this->aPage, 'page_content' => &$this->aPageContent]);
  3308. header( 'Content-type: text/html; charset=utf-8' );
  3309. $sXFrameOpts = getParam('sys_x_frame_options');
  3310. if ('Off' !== $sXFrameOpts)
  3311. header( 'X-Frame-Options: ' . $sXFrameOpts );
  3312. if (BX_PAGE_EMBED == $oTemplate->getPageNameIndex())
  3313. header('Content-Security-Policy: frame-ancestors ' . getParam('sys_csp_frame_ancestors'));
  3314. $sResult = $oTemplate->parsePageByName('page_' . $oTemplate->getPageNameIndex() . '.html', $oTemplate->getPageContent());
  3315. /**
  3316. * @hooks
  3317. * @hookdef hook-system-design_after_output 'system', 'design_after_output' - hook on after page's html generated
  3318. * - $unit_name - equals `system`
  3319. * - $action - equals `design_after_output`
  3320. * - $object_id - not used
  3321. * - $sender_id - not used
  3322. * - $extra_params - array of additional params with the following array keys:
  3323. * - `override_result` - [string] by ref, html content for current page, can be overridden in hook processing
  3324. * @hook @ref hook-system-design_after_output
  3325. */
  3326. bx_alert('system', 'design_after_output', 0, false, ['override_result' => &$sResult]);
  3327. echo $sResult;
  3328. }
  3329. }
  3330. /** @} */