BxDolTemplate.php 145 KB

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