| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851 |
- <?php defined('BX_DOL') or die('hack attempt');
- /**
- * Copyright (c) UNA, Inc - https://una.io
- * MIT License - https://opensource.org/licenses/MIT
- *
- * @defgroup UnaCore UNA Core
- * @{
- */
- ini_set('pcre.backtrack_limit', 1000000);
- define('BX_DOL_TEMPLATE_CODE_KEY', 'skin');
- define('BX_DOL_TEMPLATE_MIX_KEY', 'mix');
- define('BX_DOL_TEMPLATE_DEFAULT_CODE', 'protean');
- define('BX_DOL_TEMPLATE_FOLDER_ROOT', 'template');
- define('BX_DOL_TEMPLATE_INJECTIONS_CACHE', 'sys_injections.inc');
- define('BX_DOL_TEMPLATE_CHECK_IN_BOTH', 'both');
- define('BX_DOL_TEMPLATE_CHECK_IN_BASE', 'base');
- define('BX_DOL_TEMPLATE_CHECK_IN_TMPL', 'tmpl');
- define('BX_DOL_COLOR_BG', 'bg');
- define('BX_DOL_COLOR_FT', 'ft');
- define('BX_DOL_PAGE_WIDTH', '1024px');
- /**
- * Page display levels.
- * Note. Both levels may refer to the same HTML templates.
- *
- * 'System' level. It uses page's NameIndex and
- * is mainly used for pages which aren't registered
- * in 'sys_objects_page' table. Also it's used
- * in 'Injections' engine.
- */
- define('BX_PAGE_DEFAULT', 0); ///< default, regular page
- define('BX_PAGE_CLEAR', 2); ///< clear page, without any headers and footers
- define('BX_PAGE_EMBED', 22); ///< page used for embeds
- define('BX_PAGE_POPUP', 44); ///< popup page, without any headers and footers
- define('BX_PAGE_TRANSITION', 150); ///< transition page with redirect to display some msg, like 'please wait', without headers footers
- /**
- * 'Builder based' level. It uses page's Type
- * from BxDolPage class and is used for pages
- * which are registered in 'sys_objects_page' table.
- * Changeable in Studio -> Pages Builder -> Settings.
- */
- define('BX_PAGE_TYPE_DEFAULT', 1); ///< default, regular page
- define('BX_PAGE_TYPE_DEFAULT_WO_HF', 2); ///< clear page, without any headers and footers
- /**
- * Template engine.
- *
- * An object of the class allows to:
- * 1. Manage HTML templates.
- * 2. Get URL/path for any template image/icon.
- * 3. Attach CSS/JavaScript files to the output.
- * 4. Add some content to any template key using Injection engine.
- *
- *
- * Avalable constructions.
- * 1. <bx_include_auto:template_name.html /> - the content of the file would be inserted. File would be taken from current template if it existes there, and from base directory otherwise.
- * 2. <bx_include_base:template_name.html /> - the content of the file would be inserted. File would be taken from base directory.
- * 3. <bx_include_tmpl:template_name.html /> - the content of the file would be inserted. File would be taken from tmpl_xxx directory.
- * 4. <bx_url_root /> - the value of BX_DOL_URL_ROOT variable will be inserted.
- * 5. <bx_url_admin /> - the value of BX_DOL_URL_ADMIN variable will be inserted.
- * 6. <bx_text:_language_key /> - _language_key will be translated using language file(function _t()) and inserted.
- <bx_text_js:_language_key /> - _language_key will be translated using language file(function _t()) and inserted, use it to insert text into js string.
- <bx_text_attribute:_language_key /> - _language_key will be translated using language file(function _t()) and inserted, use it to insert text into html attribute.
- * 7. <bx_image_url:image_file_name /> - image with 'image_file_name' file name will be searched in the images folder of current template.
- * 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.
- * 8. <bx_icon_url:icon_file_name /> - the same with <bx_image_url:image_file_name />, but icons will be searched in the images/icons/ folders.
- * 9. <bx_injection:injection_name /> - will be replaced with injections registered with the page and injection_name in the `sys_injections`/`sys_injections_admin`/ tables.
- * 10. <bx_if:tag_name>some_HTML</bx_if:tag_name> - will be replaced with provided content if the condition is true, and with empty string otherwise.
- * 11. <bx_repeat:cycle_name>some_HTML</bx_repeat:cycle_name> - an inner HTML content will be repeated in accordance with received data.
- *
- *
- * Related classes:
- * BxDolTemplateAdmin - for processing admin templates.
- * Template classes in modules - for processing modiles' templates.
- *
- *
- * Global variables:
- * oSysTemplate - is used for template processing in user part.
- * oAdmTemplate - is used for template processing in admin part.
- *
- *
- * Add injection:
- * 1. Register it in the `sys_injections` table or `sys_injections_admin` table for admin panel.
- * 2. Clear injections cache(sys_injections.inc and sys_injections_admin.inc in cache folder).
- *
- *
- * Predefined template keys to add injections:
- * 1. injection_head - add injections in the <head> tag.
- * 2. injection_body - add ingection(attribute) in the <body> tag.
- * 3. injection_header - add injection inside the <body> tag at the very beginning.
- * 4. injection_logo_before - add injection at the left of the main logo(inside logo's DIV).
- * 5. injection_logo_after - add injection at the right of the main logo(inside logo's DIV).
- * 6. injection_between_logo_top_menu - add injection between logo and top menu.
- * 7. injection_top_menu_before - add injection at the left of the top menu(inside top menu's DIV).
- * 8. injection_top_menu_after - add injection at the right of the top menu(inside top menu's DIV).
- * 13. injection_content_before - add injection just before main content(inside content's DIV).
- * 14. injection_content_after - add injection just after main content(inside content's DIV).
- * 15. injection_between_content_footer - add injection between content and footer.
- * 16. injection_footer_before - add injection at the left of the footer(inside footer's DIV).
- * 17. injection_footer_after - add injection at the right of the footer(inside footer's DIV).
- * 18. injection_footer - add injection inside the <body> tag at the very end.
- *
- *
- * Example of usage:
- * @code
- * $oSysTemplate = BxDolTemplate::getInstance();
- *
- * $oSysTemplate->addCss(array('test1.css', 'test2.css'));
- * $oSysTemplate->addJs(array('test1.js', 'test2.js'));
- * $oSysTemplate->parseHtmlByName('messageBox.html', array(
- * 'id' => $iId,
- * 'msgText' => $sText,
- * 'bx_if:timer' => array(
- * 'condition' => $iTimer > 0,
- * 'content' => array(
- * 'id' => $iId,
- * 'time' => 1000 * $iTimer,
- * 'on_close' => $sOnClose,
- * )
- * ),
- * 'bx_if:timer' => array(
- * array(
- * 'name' => $sName,
- * 'title' => $sTitle
- * ),
- * array(
- * 'name' => $sName,
- * 'title' => $sTitle
- * )
- * )
- * ));
- * @endcode
- *
- *
- * Memberships/ACL:
- * Doesn't depend on user's membership.
- *
- *
- * Alerts:
- * no alerts available
- *
- */
- class BxDolTemplate extends BxDolFactory implements iBxDolSingleton
- {
- protected static $_aColors = array(
- 'red1' => array(216, 9, 96),
- 'red1-dark' => array(194, 7, 86),
- 'red2' => array(231, 68, 30),
- 'red2-dark' => array(207, 60, 25),
- 'red3' => array(243, 143, 0),
- 'red3-dark' => array(218, 128, 0),
- 'green1' => array(96, 174, 0),
- 'green1-dark' => array(86, 156, 0),
- 'green2' => array(209, 211, 0),
- 'green2-dark' => array(186, 188, 0),
- 'green3' => array(48, 116, 36),
- 'green3-dark' => array(43, 104, 32),
- 'blue1' => array(10, 61, 143),
- 'blue1-dark' => array(9, 54, 128),
- 'blue2' => array(0, 164, 165),
- 'blue2-dark' => array(0, 146, 148),
- 'blue3' => array(0, 160, 206),
- 'blue3-dark' => array(0, 143, 184),
- 'gray' => array(97, 97, 97),
- 'gray-dark' => array(87, 87, 87)
- );
- /**
- * Main fields
- */
- protected $_sName;
- protected $_sPrefix;
- protected $_sRootPath;
- protected $_sRootUrl;
- protected $_sSubPath;
- protected $_sInjectionsTable;
- protected $_sInjectionsCache;
- protected $_sCode;
- protected $_sCodeKey;
- protected $_iMix;
- protected $_sMixKey;
- protected $_sKeyWrapperHtml;
- protected $_sFolderHtml;
- protected $_sFolderCss;
- protected $_sFolderImages;
- protected $_sFolderIcons;
- protected $_aTemplates;
- protected $_aLocations;
- protected $_aLocationsJs;
- /**
- * Cache related fields
- */
- protected $_bCacheEnable;
- protected $_sCacheFolderUrl;
- protected $_sCachePublicFolderUrl;
- protected $_sCachePublicFolderPath;
- protected $_sCacheFilePrefix;
- protected $_bImagesInline;
- protected $_iImagesMaxSize;
- protected $_bCssCache;
- protected $_bCssMinify;
- protected $_bCssArchive;
- protected $_sCssCachePrefix;
- protected $_bJsCache;
- protected $_bJsMinify;
- protected $_bJsArchive;
- protected $_sJsCachePrefix;
- /**
- * Less related fields
- */
- protected $_bLessEnable;
- protected $_sLessCachePrefix;
- protected $aPage;
- protected $aPageContent;
- protected $_oTemplateConfig;
- protected $_oTemplateFunctions;
- /**
- * Constructor
- */
- protected function __construct($sRootPath = BX_DIRECTORY_PATH_ROOT, $sRootUrl = BX_DOL_URL_ROOT)
- {
- if(isset($GLOBALS['bxDolClasses'][get_class($this)]))
- trigger_error ('Multiple instances are not allowed for the class: ' . get_class($this), E_USER_ERROR);
- parent::__construct();
- $this->_sPrefix = 'BxDolTemplate';
- $this->_sRootPath = $sRootPath;
- $this->_sRootUrl = $sRootUrl;
- $this->_sInjectionsTable = 'sys_injections';
- $this->_sInjectionsCache = BX_DOL_TEMPLATE_INJECTIONS_CACHE;
- $this->_sCodeKey = BX_DOL_TEMPLATE_CODE_KEY;
- $this->_sMixKey = BX_DOL_TEMPLATE_MIX_KEY;
- list(
- $this->_sCode,
- $this->_sName,
- $this->_sSubPath
- ) = self::retrieveCode($this->_sCodeKey, $this->_sMixKey, $this->_sRootPath);
- $this->_iMix = 0;
- if(is_array($this->_sCode))
- list($this->_sCode, $this->_iMix) = $this->_sCode;
- if(!$this->_sSubPath)
- $this->_sSubPath = 'boonex/' . BX_DOL_TEMPLATE_DEFAULT_CODE . '/';
- if(!file_exists(BX_DIRECTORY_PATH_MODULES . $this->_sSubPath)) // just for 8.0.0-A6 upgrade
- $this->_sSubPath = 'boonex/uni/';
- if(isset($_GET[$this->_sCodeKey])) {
- if(BxDolPermalinks::getInstance()->redirectIfNecessary(array($this->_sCodeKey)))
- exit;
- }
- $this->_sKeyWrapperHtml = '__';
- $this->_sFolderHtml = '';
- $this->_sFolderCss = 'css/';
- $this->_sFolderImages = 'images/';
- $this->_sFolderIcons = 'images/icons/';
- $this->_aTemplates = array('html_tags', 'menu_item_addon', 'menu_item_addon_small', 'menu_item_addon_middle');
- $this->addLocation('system', $this->_sRootPath, $this->_sRootUrl);
- $this->addLocationJs('system_inc_js', BX_DIRECTORY_PATH_INC . 'js/' , BX_DOL_URL_ROOT . 'inc/js/');
- $this->addLocationJs('system_inc_js_classes', BX_DIRECTORY_PATH_INC . 'js/classes/' , BX_DOL_URL_ROOT . 'inc/js/classes/');
- $this->addLocationJs('system_plugins_public', BX_DIRECTORY_PATH_PLUGINS_PUBLIC, BX_DOL_URL_PLUGINS_PUBLIC);
- $this->_bCacheEnable = !defined('BX_DOL_CRON_EXECUTE') && getParam('sys_template_cache_enable') == 'on';
- $this->_sCacheFolderUrl = '';
- $this->_sCachePublicFolderUrl = BX_DOL_URL_CACHE_PUBLIC;
- $this->_sCachePublicFolderPath = BX_DIRECTORY_PATH_CACHE_PUBLIC;
- $this->_sCacheFilePrefix = "bx_templ_";
- $this->_bImagesInline = getParam('sys_template_cache_image_enable') == 'on';
- $this->_iImagesMaxSize = (int)getParam('sys_template_cache_image_max_size') * 1024;
- $bArchive = getParam('sys_template_cache_compress_enable') == 'on';
- $this->_bCssCache = !defined('BX_DOL_CRON_EXECUTE') && getParam('sys_template_cache_css_enable') == 'on';
- $this->_bCssMinify = $this->_bCssCache && getParam('sys_template_cache_minify_css_enable') == 'on';
- $this->_bCssArchive = $this->_bCssCache && $bArchive;
- $this->_sCssCachePrefix = $this->_sCacheFilePrefix . 'css_';
- $this->_bJsCache = !defined('BX_DOL_CRON_EXECUTE') && getParam('sys_template_cache_js_enable') == 'on';
- $this->_bJsMinify = $this->_bJsCache && getParam('sys_template_cache_minify_js_enable') == 'on';
- $this->_bJsArchive = $this->_bJsCache && $bArchive;
- $this->_sJsCachePrefix = $this->_sCacheFilePrefix . 'js_';
- $this->_bLessEnable = true;
- $this->_sLessCachePrefix = $this->_sCacheFilePrefix . 'less_';
- $this->aPage = array();
- $this->aPageContent = array();
- }
- /**
- * Prevent cloning the instance
- */
- public function __clone()
- {
- if (isset($GLOBALS['bxDolClasses'][get_class($this)]))
- trigger_error('Clone is not allowed for the class: ' . get_class($this), E_USER_ERROR);
- }
- /**
- * Get singleton instance of the class
- */
- public static function getInstance()
- {
- if(!isset($GLOBALS['bxDolClasses'][__CLASS__])) {
- $GLOBALS['bxDolClasses'][__CLASS__] = new BxDolTemplate();
- $GLOBALS['bxDolClasses'][__CLASS__]->init();
- }
- return $GLOBALS['bxDolClasses'][__CLASS__];
- }
- /**
- * Retrieve template code and check whether it's associated with active template or not.
- *
- * @param string $sCodeKey template's code key.
- * @param string $sMixKey template's mix key.
- * @param string $sRootPath path to root directory.
- */
- public static function retrieveCode($sCodeKey = BX_DOL_TEMPLATE_CODE_KEY, $sMixKey = BX_DOL_TEMPLATE_MIX_KEY, $sRootPath = BX_DIRECTORY_PATH_ROOT)
- {
- $oDb = BxDolDb::getInstance();
- $fCheckCode = function($sCode, $bSetCookie) use($sCodeKey, $sRootPath) {
- if(empty($sCode) || !preg_match('/^[A-Za-z0-9_-]+$/', $sCode))
- return false;
- $aModule = BxDolModuleQuery::getInstance()->getModuleByUri($sCode);
- if(empty($aModule) || !is_array($aModule) || (int)$aModule['enabled'] != 1 || !file_exists($sRootPath . 'modules/' . $aModule['path'] . 'data/template/'))
- return false;
- $oConfig = new BxDolModuleConfig($aModule);
- $aResult = array(
- $oConfig->getUri(), //--- Template module's URI is used as template Code.
- $oConfig->getName(),
- $oConfig->getDirectory()
- );
- if(!$bSetCookie || bx_get('preview'))
- return $aResult;
- $aUrl = parse_url(BX_DOL_URL_ROOT);
- $sPath = isset($aUrl['path']) && !empty($aUrl['path']) ? $aUrl['path'] : '/';
- setcookie($sCodeKey, $sCode, time() + 60*60*24*365, $sPath);
- return $aResult;
- };
- $fCheckMix = function($aResult, $iMix, $bSetCookie) use($sMixKey, $sRootPath, $oDb) {
- list($sCode, $sName) = $aResult;
- if(empty($sName) || empty($iMix))
- return false;
- $aMix = $oDb->getParamsMix($iMix);
- if(empty($aMix) || !is_array($aMix) || $aMix['type'] != $sName)
- return false;
- if(!$bSetCookie)
- return $iMix;
- $aUrl = parse_url(BX_DOL_URL_ROOT);
- $sPath = isset($aUrl['path']) && !empty($aUrl['path']) ? $aUrl['path'] : '/';
- setcookie($sMixKey, $iMix, time() + 60*60*24*365, $sPath);
- return $iMix;
- };
- $sCode = getParam('template');
- if(empty($sCode))
- $sCode = BX_DOL_TEMPLATE_DEFAULT_CODE;
- $aResult = $fCheckCode($sCode, false);
- //--- Check selected template in COOKIE(the lowest priority) ---//
- $sCode = !empty($_COOKIE[$sCodeKey]) ? $_COOKIE[$sCodeKey] : '';
- $aResultCheck = $fCheckCode($sCode, false);
- if($aResultCheck !== false)
- $aResult = $aResultCheck;
- //--- Check selected template in GET(the highest priority) ---//
- $sCode = !empty($_GET[$sCodeKey]) ? $_GET[$sCodeKey] : '';
- $aResultCheck = $fCheckCode($sCode, true);
- if($aResultCheck !== false)
- $aResult = $aResultCheck;
- if($aResult === false)
- return $aResult;
- if(!is_array($aResult[0]))
- $aResult[0] = array($aResult[0]);
- $iMixDefault = !empty($aResult[1]) ? (int)getParam($aResult[1] . '_default_mix') : 0;
- //--- Check selected mix in COOKIE(the lowest priority) ---//
- $iMix = !empty($_COOKIE[$sMixKey]) ? (int)$_COOKIE[$sMixKey] : 0;
- $iResultCheck = $fCheckMix($aResult, $iMix, false);
- if($iResultCheck !== false) {
- $aMix = $oDb->getParamsMix($iMix);
- if((int)$aMix['published'] == 0 && $iMix != $iMixDefault) {
- $aUrl = parse_url(BX_DOL_URL_ROOT);
- $sPath = isset($aUrl['path']) && !empty($aUrl['path']) ? $aUrl['path'] : '/';
- setcookie($sMixKey, '', time() - 96 * 3600, $sPath);
- unset($_COOKIE[$sMixKey]);
- }
- else
- $aResult[0][1] = $iResultCheck;
- }
- //--- Check selected mix in GET(the highest priority) ---//
- $iMix = !empty($_GET[$sMixKey]) ? (int)$_GET[$sMixKey] : 0;
- $iResultCheck = $fCheckMix($aResult, $iMix, true);
- if($iResultCheck !== false)
- $aResult[0][1] = $iResultCheck;
- //--- Get default mix for currently selected template ---//
- if(empty($aResult[0][1]) && !empty($iMixDefault)) {
- $iResultCheck = $fCheckMix($aResult, $iMixDefault, false);
- if($iResultCheck !== false)
- $aResult[0][1] = $iResultCheck;
- }
- if(is_array($aResult[0]) && count($aResult[0]) == 1)
- $aResult[0] = $aResult[0][0];
- return $aResult;
- }
- public static function getColorCode($mixedName = false, $fOpacity = false)
- {
- $aClasses = array_keys(self::$_aColors);
- if($mixedName === false || (is_string($mixedName) && !is_numeric($mixedName) && !in_array($mixedName, $aClasses)))
- $mixedName = $aClasses[rand(0, count($aClasses) - 1)];
- else if(is_numeric($mixedName))
- $mixedName = $aClasses[(int)$mixedName % count($aClasses)];
- $aColor = self::$_aColors[$mixedName];
- if($fOpacity !== false && is_numeric($fOpacity))
- $aColor[] = $fOpacity;
- return $aColor;
- }
- public static function getColorClass($sType = BX_DOL_COLOR_FT, $sName = '')
- {
- $aClasses = array_keys(self::$_aColors);
- if(empty($sName) || !in_array($sName, $aClasses))
- $sName = $aClasses[rand(0, count($aClasses) - 1)];
- $sPrefix = '';
- switch ($sType) {
- case BX_DOL_COLOR_FT:
- $sPrefix = 'col-';
- break;
- case BX_DOL_COLOR_BG:
- $sPrefix = 'bg-col-';
- break;
- }
- return $sPrefix . $sName;
- }
- /**
- * Load templates.
- */
- function loadTemplates()
- {
- $aResult = array();
- foreach($this->_aTemplates as $sName)
- $aResult[$sName] = $this->getHtml($sName . '.html');
- $this->_aTemplates = $aResult;
- }
- /**
- * Initialize template engine.
- * Note. The method is executed with the system, you shouldn't execute it in your subclasses.
- */
- function init()
- {
- $this->loadTemplates();
- //--- Load page elements related static variables ---//
- $this->aPage = array(
- 'name_index' => BX_PAGE_DEFAULT,
- 'type' => BX_PAGE_TYPE_DEFAULT,
- 'header' => '',
- 'header_text' => '',
- 'keywords' => array(),
- 'location' => array(),
- 'description' => '',
- 'robots' => '',
- 'css_name' => array(),
- 'css_compiled' => array(),
- 'css_system' => array(),
- 'css_async' => array(),
- 'js_name' => array(),
- 'js_compiled' => array(),
- 'js_system' => array(),
- 'js_options' => array(),
- 'js_translations' => array(),
- 'js_images' => array(),
- 'injections' => array()
- );
- //--- Load default CSS, JS, etc ---//
- BxDolPreloader::getInstance()->perform($this);
- //--- Load injection's cache ---//
- if (getParam('sys_db_cache_enable')) {
- $oDb = BxDolDb::getInstance();
- $oCache = $oDb->getDbCacheObject();
- $sCacheKey = $oDb->genDbCacheKey($this->_sInjectionsCache);
- $aInjections = $oCache->getData($sCacheKey);
- if ($aInjections === null) {
- $aInjections = $this->getInjectionsData();
- $oCache->setData ($sCacheKey, $aInjections);
- }
- }
- else
- $aInjections = $this->getInjectionsData();
- $this->aPage['injections'] = $aInjections;
- bx_import('BxTemplConfig'); // TODO: for some reason autoloader isn't working here....
- $this->_oTemplateConfig = BxTemplConfig::getInstance();
- bx_import('BxTemplFunctions');
- $this->_oTemplateFunctions = BxTemplFunctions::getInstance($this);
- }
- protected function getInjectionsData ()
- {
- $oDb = BxDolDb::getInstance();
- $aInjections = $oDb->getAll("SELECT `page_index`, `name`, `key`, `type`, `data`, `replace` FROM `" . $this->_sInjectionsTable . "` WHERE `active`='1'");
- if (!$aInjections)
- return array();
- foreach ($aInjections as $aInjection)
- $aInjections['page_' . $aInjection['page_index']][$aInjection['key']][] = $aInjection;
- return $aInjections;
- }
- /**
- * Set page name index
- * @param int $i name index
- */
- function setPageNameIndex($i)
- {
- $this->aPage['name_index'] = $i;
- }
- /**
- * Get page name index
- * @return int $i name index
- */
- function getPageNameIndex()
- {
- return isset($this->aPage['name_index']) ? (int)$this->aPage['name_index'] : 0;
- }
- /**
- * Set page type
- * @param int $i page type
- */
- function setPageType($a)
- {
- $this->aPage['type'] = $a;
- }
- /**
- * Get page type
- * @return int $i page type
- */
- function getPageType()
- {
- return isset($this->aPage['type']) ? (int)$this->aPage['type'] : BX_PAGE_TYPE_DEFAULT;
- }
- /**
- * Set page header
- * @param string $s page header
- */
- function setPageHeader($s)
- {
- $this->aPage['header'] = $s;
- }
- /**
- * Get page header
- * @return string $s page header
- */
- function getPageHeader()
- {
- return $this->aPage['header'];
- }
- /**
- * Set page params. Available page params are: name_index, header
- * @param array $a page params
- */
- function setPageParams($a)
- {
- if (!empty($this->aPage))
- $this->aPage = array_merge($this->aPage, $a);
- else
- $this->aPage = $a;
- }
- /**
- * Get page params.
- * @return array $a page params
- */
- function getPageParams()
- {
- return $this->aPage;
- }
- /**
- * Set page description.
- *
- * @param string $sDescription necessary page description.
- */
- function setPageDescription($sDescription)
- {
- $this->aPage['description'] = $sDescription;
- }
- /**
- * Set page meta robots.
- *
- * @param string $s page meta robots.
- */
- function setPageMetaRobots($s)
- {
- $this->aPage['robots'] = $s;
- }
- /**
- * Set page content for some variable.
- * @param string $sVar name of content variable
- * @param string $sContent content for $sVar variable
- * @param int $iIndex optional page index, default is index which was set before with @see setPageNameIndex function, or 0
- */
- function setPageContent($sVar, $sContent, $iIndex = false)
- {
- $i = false !== $iIndex ? $iIndex : $this->getPageNameIndex();
- $this->aPageContent[$i][$sVar] = $sContent;
- }
- /**
- * Get page content for some variable.
- * @param string $sVar name of content variable
- * @param int $iIndex optional page index, default is index which was set before with @see setPageNameIndex function, or 0
- * @return string page content for some variable or for the whole page.
- */
- function getPageContent($sVar = false, $iIndex = false)
- {
- $i = false !== $iIndex ? $iIndex : $this->getPageNameIndex();
- return false !== $sVar ? $this->aPageContent[$i][$sVar] : $this->aPageContent[$i];
- }
- /**
- * Get currently active template name.
- *
- * @return string template's name.
- */
- function getName()
- {
- return $this->_sName;
- }
- /**
- * Get currently active template code.
- *
- * @return string template's code.
- */
- function getCode()
- {
- return $this->_sCode;
- }
- /**
- * Get currently active template mix.
- *
- * @return integer template's mix.
- */
- function getMix()
- {
- return $this->_iMix;
- }
- /**
- * Get currently active template path.
- *
- * @return string template's path.
- */
- function getPath()
- {
- return $this->_sSubPath;
- }
- /**
- * Set page title.
- * @deprecated use setPageHeader
- *
- * @param string $sTitle necessary page title.
- */
- function setPageTitle($sTitle)
- {
- $this->setPageHeader($sTitle);
- }
- /**
- * Set page's main box title.
- * @deprecated use setPageParams
- *
- * @param string $sTitle necessary page's main box title.
- */
- function setPageMainBoxTitle($sTitle)
- {
- $this->setPageParams(array('header_text' => $sTitle));
- }
- /**
- * Check whether location exists or not.
- * @param string $sKey - location's unique key.
- */
- function isLocation($sKey)
- {
- return isset($this->_aLocations[$sKey]);
- }
- /**
- * Add location in array of locations.
- * Note. Location is the path/url to folder where 'templates' folder is stored.
- *
- * @param string $sKey - location's unique key.
- * @param string $sLocationPath - location's path. For modules: '[path_to_script]/modules/[vendor_name]/[module_name]/'
- * @param string $sLocationUrl - location's url. For modules: '[url_to_script]/modules/[vendor_name]/[module_name]/'
- */
- function addLocation($sKey, $sLocationPath, $sLocationUrl)
- {
- $this->_aLocations[$sKey] = array(
- 'path' => $sLocationPath,
- 'url' => $sLocationUrl,
- );
- return $sKey;
- }
- /**
- * Add dynamic location.
- *
- * @param string $sLocationPath - location's path. For modules: '[path_to_script]/modules/[vendor_name]/[module_name]/'
- * @param string $sLocationUrl - location's url. For modules: '[url_to_script]/modules/[vendor_name]/[module_name]/'
- * @return location key. Is needed to remove the location.
- */
- function addDynamicLocation($sLocationPath, $sLocationUrl)
- {
- $sLocationKey = time() . mt_rand();
- $this->addLocation($sLocationKey, $sLocationPath, $sLocationUrl);
- return $sLocationKey;
- }
- /**
- * Remove location from array of locations.
- * Note. Location is the path/url to folder where templates are stored.
- *
- * @param string $sKey - location's unique key.
- */
- function removeLocation($sKey)
- {
- if(isset($this->_aLocations[$sKey]))
- unset($this->_aLocations[$sKey]);
- }
- /**
- * Check whether JS location exists or not.
- * @param string $sKey - JS location's unique key.
- */
- function isLocationJs($sKey)
- {
- return isset($this->_aLocationsJs[$sKey]);
- }
- /**
- * Add JS location in array of JS locations.
- * Note. Location is the path/url to folder where JS files are stored.
- *
- * @param string $sKey - location's unique key.
- * @param string $sLocationPath - location's path. For modules: '[path_to_script]/modules/[vendor_name]/[module_name]/js/'
- * @param string $sLocationUrl - location's url. For modules: '[url_to_script]/modules/[vendor_name]/[module_name]/js/'
- */
- function addLocationJs($sKey, $sLocationPath, $sLocationUrl)
- {
- $this->_aLocationsJs[$sKey] = array(
- 'path' => $sLocationPath,
- 'url' => $sLocationUrl
- );
- return $sKey;
- }
- /**
- * Add dynamic JS location.
- *
- * @param string $sLocationPath - location's path. For modules: '[path_to_script]/modules/[vendor_name]/[module_name]/'
- * @param string $sLocationUrl - location's url. For modules: '[url_to_script]/modules/[vendor_name]/[module_name]/'
- * @return location key. Is needed to remove the location.
- */
- function addDynamicLocationJs($sLocationPath, $sLocationUrl)
- {
- $sLocationKey = time() . mt_rand();
- $this->addLocationJs($sLocationKey, $sLocationPath, $sLocationUrl);
- return $sLocationKey;
- }
- /**
- * Remove JS location from array of locations.
- * Note. Location is the path/url to folder where templates are stored.
- *
- * @param string $sKey - JS location's unique key.
- */
- function removeLocationJs($sKey)
- {
- if(isset($this->_aLocationsJs[$sKey]))
- unset($this->_aLocationsJs[$sKey]);
- }
- /**
- * Add Option in JS output.
- *
- * @param mixed $mixedName option's name or an array of options' names.
- */
- function addJsOption($mixedName)
- {
- if(is_string($mixedName))
- $mixedName = array($mixedName);
- foreach($mixedName as $sName)
- $this->aPage['js_options'][$sName] = getParam($sName);
- }
- /**
- * Add language translation for key in JS output.
- *
- * @param mixed $mixedKey language key or an array of keys.
- */
- function addJsTranslation($mixedKey, $bDynamic = false)
- {
- if(is_string($mixedKey))
- $mixedKey = array($mixedKey);
- foreach($mixedKey as $sKey)
- $this->aPage['js_translations'][$sKey] = _t($sKey, '{0}', '{1}');
- return $bDynamic ? $this->_processJsTranslations() : '';
- }
- /**
- * Add image in JS output.
- *
- * @param array $aImages an array of image descriptors.
- * The descriptor is a key/value pear in the array of descriptors.
- */
- function addJsImage($aImages)
- {
- if(!is_array($aImages))
- return;
- foreach($aImages as $sKey => $sFile) {
- $sUrl = $this->getImageUrl($sFile);
- if(empty($sUrl))
- continue;
- $this->aPage['js_images'][$sKey] = $sUrl;
- }
- }
- /**
- * Add icon in JS output.
- *
- * @param array $aIcons an array of icons descriptors.
- * The descriptor is a key/value pear in the array of descriptors.
- */
- function addJsIcon($aIcons)
- {
- if(!is_array($aIcons))
- return;
- foreach($aIcons as $sKey => $sFile) {
- $sUrl = $this->getIconUrl($sFile);
- if(empty($sUrl))
- continue;
- $this->aPage['js_images'][$sKey] = $sUrl;
- }
- }
- /**
- * Add CSS style.
- *
- * @param string $sName CSS class name.
- * @param string $sContent CSS class styles.
- */
- function addCssStyle($sName, $sContent)
- {
- $this->aPage['css_styles'][$sName] = $sContent;
- }
- /**
- * Set page keywords.
- *
- * @param mixed $mixedKeywords necessary page keywords(string - single keyword, array - an array of keywords).
- * @param string $sDevider - string devider.
- */
- function addPageKeywords($mixedKeywords, $sDevider = ',')
- {
- if(is_string($mixedKeywords))
- $mixedKeywords = strpos($mixedKeywords, $sDevider) !== false ? explode($sDevider, $mixedKeywords) : array($mixedKeywords);
- foreach($mixedKeywords as $iKey => $sValue)
- $mixedKeywords[$iKey] = trim($sValue);
- $this->aPage['keywords'] = isset($this->aPage['keywords']) && is_array($this->aPage['keywords']) ? array_merge($this->aPage['keywords'], $mixedKeywords) : $mixedKeywords;
- }
- /**
- * Set page locatoin coordinates.
- *
- * @param $fLat latitude
- * @param $fLng longitude
- */
- function addPageMetaLocation($fLat, $fLng, $sCountryCode)
- {
- $this->aPage['location'] = array('lat' => $fLat, 'lng' => $fLng, 'country' => $sCountryCode);
- }
- /**
- * Set page meta image.
- *
- * @param $sImageUrl meta image url
- */
- function addPageMetaImage($sImageUrl)
- {
- $this->aPage['image'] = $sImageUrl;
- }
- /**
- * Set page rss link.
- *
- * @param $sTitle - rss feed title
- * @param $sUrl - rss feed URL
- */
- function addPageRssLink($sTitle, $sUrl)
- {
- if (!isset($this->aPage['rss']))
- $this->aPage['rss'] = array('title' => $sTitle, 'url' => $sUrl);
- else
- $this->aPage['rss'] = false;
- }
- /**
- * Returns page meta info, like meta keyword, meta description, location, etc
- */
- function getMetaInfo()
- {
- $sRet = '';
- if (!empty($this->aPage['keywords']) && is_array($this->aPage['keywords']))
- $sRet .= '<meta name="keywords" content="' . bx_html_attribute(implode(',', $this->aPage['keywords'])) . '" />';
- $bDescription = !empty($this->aPage['description']) && is_string($this->aPage['description']);
- if ($bDescription)
- $sRet .= '<meta name="description" content="' . bx_html_attribute($this->aPage['description']) . '" />';
- if (!empty($this->aPage['location']) && isset($this->aPage['location']['lat']) && isset($this->aPage['location']['lng']) && isset($this->aPage['location']['country']))
- $sRet .= '
- <meta name="ICBM" content="' . $this->aPage['location']['lat'] . ';' . $this->aPage['location']['lng'] . '" />
- <meta name="geo.position" content="' . $this->aPage['location']['lat'] . ';' . $this->aPage['location']['lng'] . '" />
- <meta name="geo.region" content="' . bx_html_attribute($this->aPage['location']['country']) . '" />';
- $bPageImage = !empty($this->aPage['image']);
- if ($bPageImage)
- $sRet .= '<meta property="og:image" content="' . $this->aPage['image'] . '" />';
- $sRet .= '<meta name="twitter:card" content="' . ($bPageImage ? 'summary_large_image' : 'summary') . '" />';
- if ($bPageImage)
- $sRet .= '<meta name="twitter:image" content="' . $this->aPage['image'] . '" />';
- $sRet .= '
- <meta name="twitter:title" content="' . (isset($this->aPage['header']) ? bx_html_attribute(strip_tags($this->aPage['header'])) : '') . '" />
- <meta name="twitter:description" content="' . ($bDescription ? bx_html_attribute($this->aPage['description']) : '') . '" />';
- $oFunctions = BxTemplFunctions::getInstance();
- $sRet .= $oFunctions->getManifests();
- $sRet .= $oFunctions->getMetaIcons();
- if (!empty($this->aPage['rss']) && !empty($this->aPage['rss']['url']))
- $sRet .= '<link rel="alternate" type="application/rss+xml" title="' . bx_html_attribute($this->aPage['rss']['title'], BX_ESCAPE_STR_QUOTE) . '" href="' . $this->aPage['rss']['url'] . '" />';
- return $sRet;
- }
- /**
- * Get template, which was loaded earlier.
- * @see method this->loadTemplates and field this->_aTemplates
- *
- * @param string $sName - template name.
- * @return string template's content.
- */
- public function getTemplate($sName)
- {
- return $this->_aTemplates[$sName];
- }
- /**
- * Get template functions object.
- * @see BxBaseFunctions
- */
- public function getTemplateFunctions()
- {
- return $this->_oTemplateFunctions;
- }
- /**
- * Get image MIME type.
- *
- * @param string $sExtension - image file's extension.
- * @return string with MIME type.
- */
- function getImageMimeType($sExtension)
- {
- $sExtension = strtolower($sExtension);
-
- $sResult = '';
- switch($sExtension) {
- case 'svg':
- $sResult = 'svg+xml';
- break;
-
- default:
- $sResult = $sExtension;
- }
-
- return 'data:image/' . $sResult;
- }
- /**
- * Get icon template in dependence of a value, provided in $mixedId.
- *
- * @param mixed $mixedId numeric id from Storage, string with template's file name or string with font icon.
- */
- public function getIcon($mixedId, $aParams = array())
- {
- return $this->_getImage('icon', $mixedId, $aParams);
- }
- /**
- * Get image template in dependence of a value, provided in $mixedId.
- *
- * @param mixed $mixedId numeric id from Storage, string with template's file name or string with font icon.
- */
- public function getImage($mixedId, $aParams = array())
- {
- return $this->_getImage('image', $mixedId, $aParams);
- }
- protected function _getImage($sType, $mixedId, $aParams = array())
- {
- $sUrl = "";
- $aType2Method = array('image' => 'getImageUrl', 'icon' => 'getIconUrl');
- //--- Check in System Storage.
- if(is_numeric($mixedId) && (int)$mixedId > 0) {
- $sStorage = BX_DOL_STORAGE_OBJ_IMAGES;
- if(!empty($aParams['storage'])) {
- $sStorage = $aParams['storage'];
- unset($aParams['storage']);
- }
- if(($sResult = BxDolStorage::getObjectInstance($sStorage)->getFileUrlById((int)$mixedId)) !== false)
- $sUrl = $sResult;
- }
- //--- Check in template folders.
- if($sUrl == "" && is_string($mixedId) && strpos($mixedId, '.') !== false)
- $sUrl = $this->{$aType2Method[$sType]}($mixedId);
- if($sUrl != "")
- return $this->parseImage($sUrl, array(
- 'class' => isset($aParams['class']) && !empty($aParams['class']) ? $aParams['class'] : '',
- 'alt' => isset($aParams['alt']) && !empty($aParams['alt']) ? $aParams['alt'] : ''
- ));
- //--- Use iconic font.
- return $this->parseIcon($mixedId);
- }
- /**
- * Get full URL for the icon.
- *
- * @param string $sName icon's file name.
- * @param string $sCheckIn where the content would be searched(base, template, both)
- * @return string full URL.
- */
- function getIconUrl($sName, $sCheckIn = BX_DOL_TEMPLATE_CHECK_IN_BOTH)
- {
- $sContent = "";
- if(($sContent = $this->_getInlineData('icon', $sName, $sCheckIn)) !== false)
- return $sContent;
- return $this->_getAbsoluteLocation('url', $this->_sFolderIcons, $sName, $sCheckIn);
- }
- /**
- * Get absolute Path for the icon.
- *
- * @param string $sName - icon's file name.
- * @param string $sCheckIn where the content would be searched(base, template, both)
- * @return string absolute path.
- */
- function getIconPath($sName, $sCheckIn = BX_DOL_TEMPLATE_CHECK_IN_BOTH)
- {
- return $this->_getAbsoluteLocation('path', $this->_sFolderIcons, $sName, $sCheckIn);
- }
- /**
- * Get full URL for the image.
- *
- * @param string $sName - images's file name.
- * @param string $sCheckIn where the content would be searched(base, template, both)
- * @return string full URL.
- */
- function getImageUrl($sName, $sCheckIn = BX_DOL_TEMPLATE_CHECK_IN_BOTH)
- {
- $sContent = "";
- if(($sContent = $this->_getInlineData('image', $sName, $sCheckIn)) !== false)
- return $sContent;
- return $this->_getAbsoluteLocation('url', $this->_sFolderImages, $sName, $sCheckIn);
- }
- /**
- * Get absolute Path for the image.
- *
- * @param string $sName - image's file name.
- * @param string $sCheckIn where the content would be searched(base, template, both)
- * @return string absolute path.
- */
- function getImagePath($sName, $sCheckIn = BX_DOL_TEMPLATE_CHECK_IN_BOTH)
- {
- return $this->_getAbsoluteLocation('path', $this->_sFolderImages, $sName, $sCheckIn);
- }
- /**
- * Get full URL of CSS file.
- *
- * @param string $sName - CSS file name.
- * @param string $sCheckIn where the content would be searched(base, template, both)
- * @return string full URL.
- */
- function getCssUrl($sName, $sCheckIn = BX_DOL_TEMPLATE_CHECK_IN_BOTH)
- {
- return $this->_getAbsoluteLocation('url', $this->_sFolderCss, $sName, $sCheckIn);
- }
- /**
- * Get full Path of CSS file.
- *
- * @param string $sName - CSS file name.
- * @param string $sCheckIn where the content would be searched(base, template, both)
- * @return string full URL.
- */
- function getCssPath($sName, $sCheckIn = BX_DOL_TEMPLATE_CHECK_IN_BOTH)
- {
- return $this->_getAbsoluteLocation('path', $this->_sFolderCss, $sName, $sCheckIn);
- }
- /**
- * Get full URL of JS file.
- *
- * @param string $sName - JS file name.
- * @return string full URL.
- */
- function getJsUrl($sName)
- {
- return $this->_getAbsoluteLocationJs('url', $sName);
- }
- /**
- * Get full Path of JS file.
- *
- * @param string $sName - JS file name.
- * @return string full URL.
- */
- function getJsPath($sName)
- {
- return $this->_getAbsoluteLocationJs('path', $sName);
- }
- /**
- * Get full URL of Template (HTML) file.
- *
- * @param string $sName - Template file name.
- * @return string full URL.
- */
- function getTemplateUrl($sName, $sCheckIn = BX_DOL_TEMPLATE_CHECK_IN_BOTH)
- {
- return $this->_getAbsoluteLocation('url', $this->_sFolderHtml, $sName, $sCheckIn);
- }
- /**
- * Get full Path of JS file.
- *
- * @param string $sName - JS file name.
- * @return string full URL.
- */
- function getTemplatePath($sName, $sCheckIn = BX_DOL_TEMPLATE_CHECK_IN_BOTH)
- {
- return $this->_getAbsoluteLocation('path', $this->_sFolderHtml, $sName, $sCheckIn);
- }
- /**
- * Get menu.
- * @param $s menu object name
- * @return html or empty string
- */
- function getMenu ($s)
- {
- $oMenu = BxDolMenu::getObjectInstance($s);
- return $oMenu ? $oMenu->getCode () : '';
- }
- /**
- * Get content of HTML file.
- *
- * @param string $sName - HTML file name.
- * @param string $sCheckIn where the content would be searched(base, template, both)
- * @return string full content of the file and false on failure.
- */
- function getHtml($sName, $sCheckIn = BX_DOL_TEMPLATE_CHECK_IN_BOTH)
- {
- $sAbsolutePath = $this->_getAbsoluteLocation('path', $this->_sFolderHtml, $sName, $sCheckIn);
- return !empty($sAbsolutePath) ? trim(file_get_contents($sAbsolutePath)) : false;
- }
- /**
- * Parse HTML template. Search for the template with accordance to it's file name.
- *
- * @see allows to use cache.
- *
- * @param string $sName - HTML file name.
- * @param array $aVariables - key/value pairs. key should be the same as template's key, but without prefix and postfix.
- * @param mixed $mixedKeyWrapperHtml - key wrapper(string value if left and right parts are the same, array(left, right) otherwise).
- * @param string $sCheckIn where the content would be searched(base, template, both)
- * @return string the result of operation.
- */
- function parseHtmlByName($sName, $aVariables, $mixedKeyWrapperHtml = null, $sCheckIn = BX_DOL_TEMPLATE_CHECK_IN_BOTH)
- {
- if (isset($GLOBALS['bx_profiler'])) $GLOBALS['bx_profiler']->beginTemplate($sName, $sRand = time().rand());
- if (($sContent = $this->getCached($sName, $aVariables, $mixedKeyWrapperHtml, $sCheckIn)) !== false) {
- if (isset($GLOBALS['bx_profiler'])) $GLOBALS['bx_profiler']->endTemplate($sName, $sRand, $sRet, true);
- return $sContent;
- }
- $sRet = '';
- if (($sContent = $this->getHtml($sName, $sCheckIn)) !== false)
- $sRet = $this->_parseContent($sContent, $aVariables, $mixedKeyWrapperHtml);
- if (isset($GLOBALS['bx_profiler'])) $GLOBALS['bx_profiler']->endTemplate($sName, $sRand, $sRet, false);
- return $sRet;
- }
- /**
- * Parse HTML template.
- *
- * @see Doesn't allow to use cache.
- *
- * @param string $sContent - HTML file content.
- * @param array $aVariables - key/value pairs. key should be the same as template's key, but without prefix and postfix.
- * @param mixed $mixedKeyWrapperHtml - key wrapper(string value if left and right parts are the same, array(left, right) otherwise).
- * @return string the result of operation.
- */
- function parseHtmlByContent($sContent, $aVariables, $mixedKeyWrapperHtml = null)
- {
- if(empty($sContent))
- return "";
- return $this->_parseContent($sContent, $aVariables, $mixedKeyWrapperHtml);
- }
- /**
- * Parse earlier loaded HTML template.
- *
- * @see Doesn't allow to use cache.
- *
- * @param string $sName - template name.
- * @param array $aVariables - key/value pairs. Key should be the same as template's key, excluding prefix and postfix.
- * @return string the result of operation.
- * @see $this->_aTemplates
- */
- function parseHtmlByTemplateName($sName, $aVariables, $mixedKeyWrapperHtml = null)
- {
- if(!isset($this->_aTemplates[$sName]) || empty($this->_aTemplates[$sName]))
- return "";
- return $this->_parseContent($this->_aTemplates[$sName], $aVariables, $mixedKeyWrapperHtml);
- }
- /**
- * Parse page HTML template. Search for the page's template with accordance to it's file name.
- *
- * @see allows to use cache.
- *
- * @param string $sName - HTML file name.
- * @param array $aVariables - key/value pairs. key should be the same as template's key, but without prefix and postfix.
- * @return string the result of operation.
- */
- function parsePageByName($sName, $aVariables)
- {
- if (isset($GLOBALS['bx_profiler'])) $GLOBALS['bx_profiler']->beginPage($sName);
- $sContent = $this->parseHtmlByName($sName, $aVariables, $this->_sKeyWrapperHtml, BX_DOL_TEMPLATE_CHECK_IN_BOTH);
- if(empty($sContent)) {
- $aType = BxDolPageQuery::getPageType($this->getPageType());
- if(!empty($aType) && is_array($aType))
- $sContent = $this->parseHtmlByName($aType['template'], $aVariables, $this->_sKeyWrapperHtml, BX_DOL_TEMPLATE_CHECK_IN_BOTH);
- }
- if(empty($sContent))
- $sContent = $this->parseHtmlByName('default.html', $aVariables, $this->_sKeyWrapperHtml, BX_DOL_TEMPLATE_CHECK_IN_BOTH);
- //--- Add CSS and JS at the very last ---//
- if(strpos($sContent, '<bx_include_css_styles />') !== false) {
- $aStyles = array(
- 'display' => 'none !important'
- );
- if(isLogged())
- $this->addCssStyle('.bx-hide-when-logged-in', $aStyles);
- else
- $this->addCssStyle('.bx-hide-when-logged-out', $aStyles);
- $sContent = str_replace('<bx_include_css_styles />', $this->includeCssStyles(), $sContent);
- }
- if(strpos($sContent , '<bx_include_css_system />') !== false) {
- $sContent = str_replace('<bx_include_css_system />', $this->includeFiles('css', true), $sContent);
- }
- if(strpos($sContent , '<bx_include_css />') !== false) {
- if (!empty($this->aPage['css_name']))
- $this->addCss($this->aPage['css_name']);
- $sContent = str_replace('<bx_include_css />', $this->includeFiles('css'), $sContent);
- }
-
- if(strpos($sContent , '<bx_include_js_system />') !== false) {
- $sContent = str_replace('<bx_include_js_system />', $this->includeFiles('js', true), $sContent);
- }
- if(strpos($sContent , '<bx_include_js />') !== false) {
- if (!empty($this->aPage['js_name']))
- $this->addJs($this->aPage['js_name']);
- $sContent = str_replace('<bx_include_js />', $this->includeFiles('js') . $this->includeCssAsync(), $sContent);
- }
- if (isset($GLOBALS['bx_profiler'])) $GLOBALS['bx_profiler']->endPage($sContent);
- return $sContent;
- }
- /**
- * Parse system keys.
- *
- * @param string $sKey key
- * @return string value associated with the key.
- */
- function parseSystemKey($sKey, $mixedKeyWrapperHtml = null, $bProcessInjection = true)
- {
- $aKeyWrappers = $this->_getKeyWrappers($mixedKeyWrapperHtml);
- $sRet = '';
- switch( $sKey ) {
- case 'page_charset':
- $sRet = 'UTF-8';
- break;
- case 'page_robots':
- if(!empty($this->aPage['robots']) && is_string($this->aPage['robots']))
- $sRet = '<meta name="robots" content="' . bx_html_attribute($this->aPage['robots']) . '" />';
- break;
- case 'meta_info':
- $sRet = $this->getMetaInfo();
- break;
- case 'page_header':
- if(isset($this->aPage['header']))
- $sRet = bx_process_output(strip_tags($this->aPage['header']));
- break;
- case 'page_header_text':
- if(isset($this->aPage['header_text']))
- $sRet = bx_process_output($this->aPage['header_text']);
- break;
- case 'page_width':
- if (false === strpos($this->_oTemplateConfig->aLessConfig['bx-page-width'], 'px'))
- $sRet = BX_DOL_PAGE_WIDTH;
- else
- $sRet = $this->_oTemplateConfig->aLessConfig['bx-page-width'];
- break;
- case 'system_injection_head':
- $sRet = $this->_oTemplateFunctions->getInjectionHead();
- break;
- case 'system_injection_header':
- $sRet = $this->_oTemplateFunctions->getInjectionHeader();
- break;
- case 'system_injection_footer':
- $sRet = $this->_oTemplateFunctions->getInjectionFooter();
- break;
- case 'lang':
- $sRet = bx_lang_name();
- break;
- case 'lang_direction':
- $sRet = bx_lang_direction();
- break;
- case 'lang_country':
- if (!($sRet = BxDolLanguages::getInstance()->getLangCountryCode()))
- $sRet = bx_lang_name();
- break;
- case 'main_logo':
- $sRet = BxTemplFunctions::getInstance()->getMainLogo();
- break;
- case 'informer':
- $oInformer = BxDolInformer::getInstance($this);
- $sRet = $oInformer ? $oInformer->display() : '';
- break;
- case 'cover':
- $oCover = BxDolCover::getInstance($this);
- if(!$oCover)
- break;
- $bCover = true;
- $oPage = BxDolPage::getObjectInstanceByURI();
- if($oPage !== false) {
- $bCover = $oPage->isPageCover();
- if($bCover && !$oCover->isCover()) {
- $aCover = $oPage->getPageCoverImage();
- if(!empty($aCover))
- $oCover->setCoverImageUrl($aCover);
- }
- }
- $sRet = $bCover ? $oCover->display() : $oCover->displayEmpty();
- break;
- case 'dol_images':
- $sRet = $this->_processJsImages();
- break;
- case 'dol_lang':
- $sRet = $this->_processJsTranslations();
- break;
- case 'dol_options':
- $sRet = $this->_processJsOptions();
- break;
- case 'copyright':
- $sRet = _t( '_copyright', date('Y') ) . getVersionComment();
- break;
- case 'copyright_attr':
- $sRet = bx_html_attribute(_t('_copyright', date('Y')));
- break;
- case 'extra_js':
- $sRet = empty($this->aPage['extra_js']) ? '' : $this->aPage['extra_js'];
- break;
- case 'is_profile_page':
- $sRet = (defined('BX_PROFILE_PAGE')) ? 'true' : 'false';
- break;
- case 'system_js_requred':
- $sRet = _t('_sys_javascript_requred');
- break;
- default:
- $sRet = ($sTemplAdd = BxTemplFunctions::getInstance()->TemplPageAddComponent($sKey)) !== false ? $sTemplAdd : $aKeyWrappers['left'] . $sKey . $aKeyWrappers['right'];
- }
- if($bProcessInjection)
- $sRet = $this->processInjection($this->getPageNameIndex(), $sKey, $sRet);
- return $sRet;
- }
- /**
- * Parse tag <A>
- *
- * @param string $sLink link URL
- * @param string $sContent link content
- * @param array $aAttrs an array of key => value pairs
- */
- function parseLink($sLink, $sContent, $aAttrs = array())
- {
- $sAttrs = '';
- foreach($aAttrs as $sKey => $sValue)
- $sAttrs .= ' ' . $sKey . '="' . bx_html_attribute($sValue) . '"';
- return '<a href="' . $sLink . '"' . $sAttrs . '>' . $sContent . '</a>';
- }
- /**
- * Parse tag <BUTTON>
- *
- * @param string $sContent link content
- * @param array $aAttrs an array of key => value pairs
- */
- function parseButton($sContent, $aAttrs = array())
- {
- $sAttrs = '';
- foreach($aAttrs as $sKey => $sValue)
- $sAttrs .= ' ' . $sKey . '="' . bx_html_attribute($sValue) . '"';
- return '<button' . $sAttrs . '>' . $sContent . '</button>';
- }
- /**
- * Parse tag <IMG>
- *
- * @param string $sLink URL to image source
- * @param array $aAttrs an array of key => value pairs
- */
- function parseImage($sLink, $aAttrs = array())
- {
- $sAttrs = '';
- foreach($aAttrs as $sKey => $sValue)
- $sAttrs .= ' ' . $sKey . '="' . bx_html_attribute($sValue) . '"';
- return '<img src="' . $sLink . '"' . $sAttrs . ' />';
- }
- /**
- * Parse font based icon in <I> tag
- *
- * @param string $sName font icon name
- * @param array $aAttrs an array of key => value pairs
- */
- function parseIcon($sName, $aAttrs = array())
- {
- if(!empty($aAttrs['class'])) {
- $sName .= ' ' . $aAttrs['class'];
- unset($aAttrs['class']);
- }
- $sAttrs = '';
- foreach($aAttrs as $sKey => $sValue)
- $sAttrs .= ' ' . $sKey . '="' . bx_html_attribute($sValue) . '"';
- return '<i class="sys-icon ' . $sName . '"' . $sAttrs . '></i>';
- }
- function getCacheFilePrefix($sType)
- {
- $sResult = '';
- switch($sType) {
- case 'template':
- $sResult = $this->_sCacheFilePrefix;
- break;
- case 'css':
- $sResult = $this->_sCssCachePrefix;
- break;
- case 'js':
- $sResult = $this->_sJsCachePrefix;
- break;
- }
- return $sResult;
- }
- /**
- * Get cache object for templates
- * @return cache class instance
- */
- function getTemplatesCacheObject ()
- {
- $sCacheEngine = getParam('sys_template_cache_engine');
- $oCacheEngine = bx_instance('BxDolCache' . $sCacheEngine);
- if(!$oCacheEngine->isAvailable())
- $oCacheEngine = bx_instance('BxDolCacheFileHtml');
- return $oCacheEngine;
- }
- /**
- * Get template from cache if it's enabled.
- *
- * @param string $sName template name
- * @param string $aVariables key/value pairs. key should be the same as template's key, but without prefix and postfix.
- * @param mixed $mixedKeyWrapperHtml - key wrapper(string value if left and right parts are the same, array(0 => left, 1 => right) otherwise).
- * @param string $sCheckIn where the content would be searched(base, template, both)
- * @param boolean $bEvaluate need to evaluate the template or not.
- * @return string result of operation or false on failure.
- */
- function getCached($sName, &$aVariables, $mixedKeyWrapperHtml = null, $sCheckIn = BX_DOL_TEMPLATE_CHECK_IN_BOTH, $bEvaluate = true)
- {
- // initialization
- if(!$this->_bCacheEnable)
- return false;
- $sAbsolutePath = $this->_getAbsoluteLocation('path', $this->_sFolderHtml, $sName, $sCheckIn);
- if(empty($sAbsolutePath))
- return false;
- $oCacheEngine = $this->getTemplatesCacheObject ();
- $isFileBasedEngine = $bEvaluate && method_exists($oCacheEngine, 'getDataFilePath');
- // try to get cached content
- $sCacheVariableName = "a";
- $sCacheKey = $this->_getCacheFileName('html', $sAbsolutePath) . '.php';
- if ($isFileBasedEngine)
- $sCacheContent = $oCacheEngine->getDataFilePath($sCacheKey);
- else
- $sCacheContent = $oCacheEngine->getData($sCacheKey);
- // recreate cache if it is empty
- if ($sCacheContent === null && ($sContent = file_get_contents($sAbsolutePath)) !== false && ($sContent = $this->_compileContent($sContent, "\$" . $sCacheVariableName, 1, $aVariables, $mixedKeyWrapperHtml)) !== false) {
- if (false === $oCacheEngine->setData($sCacheKey, trim($sContent)))
- return false;
- if ($isFileBasedEngine)
- $sCacheContent = $oCacheEngine->getDataFilePath($sCacheKey);
- else
- $sCacheContent = $sContent;
- }
- if ($sCacheContent === null)
- return false;
- // return simple cache content
- if(!$bEvaluate)
- return $sCacheContent;
- // return evaluated cache content
- ob_start();
- $$sCacheVariableName = &$aVariables;
- if ($isFileBasedEngine)
- include($sCacheContent);
- else
- eval('?'.'>' . $sCacheContent);
- $sContent = ob_get_clean();
- return $sContent;
- }
- /**
- * Add JS file(s) to global output.
- *
- * @param mixed $mixedFiles string value represents a single JS file name. An array - array of JS file names.
- * @param boolean $bDynamic in the dynamic mode JS file(s) are not included to global output, but are returned from the function directly.
- * @return boolean/string result of operation.
- */
- function addJs($mixedFiles, $bDynamic = false)
- {
- return $this->_processFiles('js', 'add', $mixedFiles, $bDynamic);
- }
- /**
- * get added js files
- */
- function getJs()
- {
- return $this->aPage['js_compiled'];
- }
-
- /**
- * Add System JS file(s) to global output.
- * System JS files are the files which are attached to all pages. They will be cached separately from the others.
- *
- * @param mixed $mixedFiles string value represents a single JS file name. An array - array of JS file names.
- * @param boolean $bDynamic in the dynamic mode JS file(s) are not included to global output, but are returned from the function directly.
- * @return boolean/string result of operation.
- */
- function addJsSystem($mixedFiles)
- {
- return $this->_processFiles('js', 'add', $mixedFiles, false, true);
- }
- /**
- * Delete JS file(s) from global output.
- *
- * @param mixed $mixedFiles string value represents a single JS file name. An array - array of JS file names.
- * @return boolean result of operation.
- */
- function deleteJs($mixedFiles)
- {
- return $this->_processFiles('js', 'delete', $mixedFiles);
- }
- /**
- * Delete System JS file(s) from global output.
- *
- * @param mixed $mixedFiles string value represents a single JS file name. An array - array of JS file names.
- * @return boolean result of operation.
- */
- function deleteJsSystem($mixedFiles)
- {
- return $this->_processFiles('js', 'delete', $mixedFiles, false, true);
- }
- /**
- * Compile JS files in one file.
- *
- * @param string $sAbsolutePath CSS file absolute path(full URL for external CSS/JS files).
- * @param array $aIncluded an array of already included JS files.
- * @return string result of operation.
- */
- function _compileJs($sAbsolutePath, &$aIncluded)
- {
- if(isset($aIncluded[$sAbsolutePath]))
- return '';
- $bExternal = strpos($sAbsolutePath, "http://") !== false || strpos($sAbsolutePath, "https://") !== false;
- if($bExternal) {
- $sPath = $sAbsolutePath;
- $sName = '';
- $sContent = bx_file_get_contents($sAbsolutePath);
- } else {
- $aFileInfo = pathinfo($sAbsolutePath);
- $sPath = $aFileInfo['dirname'] . DIRECTORY_SEPARATOR;
- $sName = $aFileInfo['basename'];
- $sContent = file_get_contents($sPath . $sName);
- }
- if(empty($sContent))
- return '';
- $sUrl = bx_ltrim_str($sPath, realpath(BX_DIRECTORY_PATH_ROOT), BX_DOL_URL_ROOT);
- $sUrl = str_replace(DIRECTORY_SEPARATOR, '/', $sUrl);
- $sContent = "\r\n/*--- BEGIN: " . $sUrl . $sName . "---*/\r\n" . $sContent . ";\r\n/*--- END: " . $sUrl . $sName . "---*/\r\n";
- $sContent = str_replace(array("\n\r", "\r\n", "\r"), "\n", $sContent);
- $aIncluded[$sAbsolutePath] = 1;
- return preg_replace(
- array(
- "'<bx_url_root />'",
- "'\r\n'"
- ),
- array(
- BX_DOL_URL_ROOT,
- "\n"
- ),
- $sContent
- );
- }
- /**
- * Minify JS
- *
- * @param string $s JS string to minify
- * @return string minified JS string.
- */
- function _minifyJs($s)
- {
- // since each JS file is minified separately, it has to be in own scope
- return "\n {\n" . BxDolMinify::getInstance()->minifyJs($s) . "\n }\n";
- }
- /**
- * Wrap an URL to JS file into JS tag.
- *
- * @param string $sFile - URL to JS file.
- * @return string the result of operation.
- */
- function _wrapInTagJs($sFile)
- {
- return "<script language=\"javascript\" type=\"text/javascript\" src=\"" . $sFile . "\"></script>";
- }
- /**
- * Wrap JS code into JS tag.
- *
- * @param string $sCode - JS code.
- * @return string the result of operation.
- */
- function _wrapInTagJsCode($sCode)
- {
- return "<script language=\"javascript\" type=\"text/javascript\">\n<!--\n" . $sCode . "\n-->\n</script>";
- }
- /**
- * Add CSS file(s) to global output.
- *
- * @param mixed $mixedFiles string value represents a single CSS file name. An array - array of CSS file names.
- * @param boolean $bDynamic in the dynamic mode CSS file(s) are not included to global output, but are returned from the function directly.
- * @return boolean/string result of operation
- */
- function addCss($mixedFiles, $bDynamic = false)
- {
- return $this->_processFiles('css', 'add', $mixedFiles, $bDynamic);
- }
- /**
- * get added css files
- */
- function getCss()
- {
- return $this->aPage['css_compiled'];
- }
- /**
- * Add additional heavy css file (not very necessary) to load asynchronously for desktop browsers only
- * @param mixed $mixedFiles string value represents a single CSS file name. An array - array of CSS file names.
- */
- function addCssAsync($mixedFiles)
- {
- if (!is_array($mixedFiles))
- $mixedFiles = array($mixedFiles);
- foreach ($mixedFiles as $sFile)
- $this->aPage['css_async'][] = $this->_getAbsoluteLocationCss('url', $sFile);
- $this->addJs('loadCSS.js');
- }
- /**
- * Return script tag with special code to load async css.
- * This tag is added after js files list
- */
- function includeCssAsync ()
- {
- if (empty($this->aPage['css_async']))
- return '';
- $this->aPage['css_async'] = array_unique($this->aPage['css_async']);
- $sList = '';
- foreach ($this->aPage['css_async'] as $sUrl)
- $sList .= 'loadCSS("' . $sUrl . '", document.getElementById("bx_css_async"));';
- // don't load css for mobile devices
- return '
- <script id="bx_css_async">
- if(!/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) ) {
- ' . $sList . '
- }
- </script>
- ';
- }
- /**
- * Add System CSS file(s) to global output.
- * System CSS files are the files which are attached to all pages. They will be cached separately from the others.
- *
- * @param mixed $mixedFiles string value represents a single CSS file name. An array - array of CSS file names.
- * @return boolean/string result of operation
- */
- function addCssSystem($mixedFiles)
- {
- return $this->_processFiles('css', 'add', $mixedFiles, false, true);
- }
- /**
- * Delete CSS file(s) from global output.
- *
- * @param mixed $mixedFiles string value represents a single CSS file name. An array - array of CSS file names.
- * @return boolean result of operation.
- */
- function deleteCss($mixedFiles)
- {
- return $this->_processFiles('css', 'delete', $mixedFiles);
- }
- /**
- * Delete System CSS file(s) from global output.
- *
- * @param mixed $mixedFiles string value represents a single CSS file name. An array - array of CSS file names.
- * @return boolean result of operation.
- */
- function deleteCssSystem($mixedFiles)
- {
- return $this->_processFiles('css', 'delete', $mixedFiles, false, true);
- }
- /**
- * Compile CSS files' structure(@see \@import css_file_path) in one file.
- *
- * @param string $sAbsolutePath CSS file absolute path(full URL for external CSS/JS files).
- * @param array $aIncluded an array of already included CSS files.
- * @return string result of operation.
- */
- function _compileCss($sAbsolutePath, &$aIncluded)
- {
- if(isset($aIncluded[$sAbsolutePath]))
- return '';
- $bExternal = strpos($sAbsolutePath, "http://") !== false || strpos($sAbsolutePath, "https://") !== false;
- if($bExternal) {
- $sPath = $sAbsolutePath;
- $sName = '';
- $aAPUrl = parse_url($sAbsolutePath);
- if(!empty($aAPUrl['path'])) {
- $aAPPath = pathinfo($aAPUrl['path']);
- if(!empty($aAPPath['basename'])) {
- $sPath = bx_rtrim_str($sAbsolutePath, $aAPPath['basename']);
- $sName = $aAPPath['basename'];
- }
- }
- $sContent = bx_file_get_contents($sAbsolutePath);
- } else {
- $aFileInfo = pathinfo($sAbsolutePath);
- $sPath = $aFileInfo['dirname'] . DIRECTORY_SEPARATOR;
- $sName = $aFileInfo['basename'];
- $sContent = file_get_contents($sPath . $sName);
- }
- if(empty($sContent))
- return '';
- $sUrl = bx_ltrim_str($sPath, realpath(BX_DIRECTORY_PATH_ROOT), BX_DOL_URL_ROOT);
- $sUrl = str_replace(DIRECTORY_SEPARATOR, '/', $sUrl);
- $sContent = "\r\n/*--- BEGIN: " . $sUrl . $sName . "---*/\r\n" . $sContent . "\r\n/*--- END: " . $sUrl . $sName . "---*/\r\n";
- $aIncluded[$sAbsolutePath] = 1;
- $sContent = str_replace(array("\n\r", "\r\n", "\r"), "\n", $sContent);
- if($bExternal) {
- $sContent = preg_replace(
- array(
- "'@import\s+url\s*\(\s*[\'|\"]*\s*([a-zA-Z0-9\.\/_-]+)\s*[\'|\"]*\s*\)\s*;'",
- "'url\s*\(\s*[\'|\"]*\s*([a-zA-Z0-9\.\/\?\#_=-]+)\s*[\'|\"]*\s*\)'"
- ),
- array(
- "",
- "url(" . $sPath . "\\1)"
- ),
- $sContent
- );
- }
- else {
- try {
- $oTemplate = &$this;
- /* Match URL based imports like the following:
- * @import 'http://[domain]/modules/[vendor]/[module]/template/css/view.css';
- * Is mainly needed for CSS files which are gotten from LESS compiler.
- */
- $sContent = preg_replace_callback(
- "'@import\s+[\'|\"]*\s*" . str_replace("/", "\/", BX_DOL_URL_ROOT) . "([a-zA-Z0-9\.\/_-]+)\s*[\'|\"]*\s*;'", function ($aMatches) use($oTemplate, $sPath, $aIncluded) {
- return $oTemplate->_compileCss(realpath(BX_DIRECTORY_PATH_ROOT . $aMatches[1]), $aIncluded);
- }, $sContent);
- /* Match relative path based imports like the following:
- * @import url(../../../../../../base/profile/template/css/main.css);
- * Is mainly needed for default CSS files.
- */
- $sContent = preg_replace_callback(
- "'@import\s+url\s*\(\s*[\'|\"]*\s*([a-zA-Z0-9\.\/_-]+)\s*[\'|\"]*\s*\)\s*;'", function ($aMatches) use($oTemplate, $sPath, $aIncluded) {
- return $oTemplate->_compileCss(realpath($sPath . dirname($aMatches[1])) . DIRECTORY_SEPARATOR . basename($aMatches[1]), $aIncluded);
- }, $sContent);
- $sContent = preg_replace_callback(
- "'url\s*\(\s*[\'|\"]*\s*([a-zA-Z0-9\.\/\?\#_=-]+)\s*[\'|\"]*\s*\)'", function ($aMatches) use($oTemplate, $sPath) {
- $sFile = basename($aMatches[1]);
- $sDirectory = dirname($aMatches[1]);
- $sRootPath = realpath(BX_DIRECTORY_PATH_ROOT);
- $sAbsolutePath = realpath(addslashes($sPath) . $sDirectory) . DIRECTORY_SEPARATOR . $sFile;
- $sRootPath = str_replace(DIRECTORY_SEPARATOR, '/', $sRootPath);
- $sAbsolutePath = str_replace(DIRECTORY_SEPARATOR, '/', $sAbsolutePath);
- return 'url(' . bx_ltrim_str($sAbsolutePath, $sRootPath, BX_DOL_URL_ROOT) . ')';
- }, $sContent);
- }
- catch(Exception $oException) {
- return '';
- }
- }
- return $sContent;
- }
- /**
- * Less CSS
- *
- * @param mixed $mixed CSS string to process with Less compiler or an array with CSS file's Path and URL.
- * @return mixed string or an array with CSS file's Path and URL.
- */
- function _lessCss($mixed)
- {
- require_once(BX_DIRECTORY_PATH_PLUGINS . 'lessphp/Less.php');
- if(is_array($mixed) && isset($mixed['url']) && isset($mixed['path'])) {
- $sPathFile = realpath($mixed['path']);
- $aInfoFile = pathinfo($sPathFile);
- if (!isset($aInfoFile['extension']) || $aInfoFile['extension'] != 'less')
- return $mixed;
- require_once(BX_DIRECTORY_PATH_PLUGINS . 'lessphp/Cache.php');
- $aFiles = array($mixed['path'] => $mixed['url']);
- $aOptions = array('cache_dir' => $this->_sCachePublicFolderPath);
- $sFile = Less_Cache::Get($aFiles, $aOptions, $this->_oTemplateConfig->aLessConfig);
- return array('url' => $this->_sCachePublicFolderUrl . $sFile, 'path' => $this->_sCachePublicFolderPath . $sFile);
- }
- $oLess = new Less_Parser();
- $oLess->ModifyVars($this->_oTemplateConfig->aLessConfig);
- $oLess->parse($mixed);
- return $oLess->getCss();
- }
- /**
- * Minify CSS
- *
- * @param string $s CSS string to minify
- * @return string minified CSS string.
- */
- function _minifyCss($s)
- {
- return BxDolMinify::getInstance()->minifyCss($s);
- }
- /**
- * Wrap an URL to CSS file into CSS tag.
- *
- * @param string $sFile - URL to CSS file.
- * @return string the result of operation.
- */
- function _wrapInTagCss($sFile)
- {
- if (!$sFile)
- return '';
- return "<link href=\"" . $sFile . "\" rel=\"stylesheet\" type=\"text/css\" />";
- }
- /**
- * Wrap CSS code into CSS tag.
- *
- * @param string $sCode - CSS code.
- * @return string the result of operation.
- */
- function _wrapInTagCssCode($sCode)
- {
- return "<style>" . $sCode . "</style>";
- }
- /**
- * Include CSS style(s) in the page's head section.
- */
- function includeCssStyles()
- {
- $sResult = "";
- if(empty($this->aPage['css_styles']) || !is_array($this->aPage['css_styles']))
- return $sResult;
- foreach($this->aPage['css_styles'] as $sName => $aContent) {
- $sContent = "";
- if(!empty($aContent) && is_array($aContent))
- foreach($aContent as $sStyleName => $sStyleValue)
- $sContent .= "\t" . $sStyleName . ": " . $sStyleValue . ";\r\n";
- $sResult .= $sName . " {\r\n" . $sContent . "}\r\n";
- }
- return !empty($sResult) ? $this->_wrapInTagCssCode($sResult) : '';
- }
- /**
- * Include CSS/JS file(s) attached to the page in its head section.
- * @see the method is system and would be called automatically.
- *
- * @param string $sType the type of file('js' or 'css')
- * @return string the result CSS code.
- */
- function includeFiles($sType, $bSystem = false)
- {
- $sUpcaseType = ucfirst($sType);
- $sArrayKey = $sType . ($bSystem ? '_system' : '_compiled');
- $aFiles = isset($this->aPage[$sArrayKey]) ? $this->aPage[$sArrayKey] : array();
- if(empty($aFiles) || !is_array($aFiles))
- return "";
- if(!$this->{'_b' . $sUpcaseType . 'Cache'})
- return $this->_includeFiles($sType, $aFiles);
- //--- If cache already exists, return it ---//
- $sMethodWrap = '_wrapInTag' . $sUpcaseType;
- $sMethodCompile = '_compile' . $sUpcaseType;
- $sMethodLess = '_less' . $sUpcaseType;
- $sMethodMinify = '_minify' . $sUpcaseType;
- ksort($aFiles);
- $sName = "";
- foreach($aFiles as $aFile)
- $sName .= $aFile['url'];
- $sName = $this->_getCacheFileName($sType, $sName);
- $sCacheAbsoluteUrl = $this->_sCachePublicFolderUrl . $sName . '.' . $sType;
- $sCacheAbsolutePath = $this->_sCachePublicFolderPath . $sName . '.' . $sType;
- if(file_exists($sCacheAbsolutePath)) {
- if($this->{'_b' . $sUpcaseType . 'Archive'})
- $sCacheAbsoluteUrl = $this->_getLoaderUrl($sType, $sName);
- return $this->$sMethodWrap($sCacheAbsoluteUrl);
- }
- //--- Collect all attached CSS/JS in one file ---//
- $bLess = $this->_bLessEnable && method_exists($this, $sMethodLess);
- $sResult = "";
- $aIncluded = array();
- foreach($aFiles as $aFile) {
- if($bLess)
- $aFile = $this->$sMethodLess($aFile);
- if(($sContent = $this->$sMethodCompile($aFile['path'], $aIncluded)) === false)
- continue;
- if (!preg_match('/[\.-]min.(js|css)$/i', $aFile['path']) && $this->{'_b' . $sUpcaseType . 'Minify'}) // don't minify minified files
- $sContent = $this->$sMethodMinify($sContent);
-
- $sResult .= $sContent;
- }
- $mixedWriteResult = false;
- if(!empty($sResult) && ($rHandler = fopen($sCacheAbsolutePath, 'w')) !== false) {
- $mixedWriteResult = fwrite($rHandler, $sResult);
- fclose($rHandler);
- @chmod ($sCacheAbsolutePath, BX_DOL_FILE_RIGHTS);
- }
- if($mixedWriteResult === false)
- return $this->_includeFiles($sType, $aFiles);
- if($this->{'_b' . $sUpcaseType . 'Archive'})
- $sCacheAbsoluteUrl = $this->_getLoaderUrl($sType, $sName);
- return $this->$sMethodWrap($sCacheAbsoluteUrl);
- }
- /**
- * Include CSS/JS files without caching.
- *
- * @param string $sType the file type (css or js)
- * @param array $aFiles CSS/JS files to be added to the page.
- * @return string result of operation.
- */
- function _includeFiles($sType, &$aFiles)
- {
- $iRev = (int)getParam('sys_revision');
- $sUpcaseType = ucfirst($sType);
- $sMethodWrap = '_wrapInTag' . $sUpcaseType;
- $sMethodLess = '_less' . $sUpcaseType;
- $sResult = "";
- foreach($aFiles as $aFile) {
- if($this->_bLessEnable && method_exists($this, $sMethodLess))
- $aFile = $this->$sMethodLess($aFile);
- $sFileUrl = $aFile['url'];
- if(!$this->{'_b' . $sUpcaseType . 'Cache'})
- $sFileUrl = bx_append_url_params($sFileUrl, array(
- 'rev' => $iRev
- ));
- $sResult .= $this->$sMethodWrap($sFileUrl);
- }
- return $sResult;
- }
- /**
- * Insert/Delete CSS file from output stack.
- *
- * @param string $sType the file type (css or js)
- * @param string $sAction add/delete
- * @param mixed $mixedFiles string value represents a single CSS file name. An array - array of CSS file names.
- * @return boolean result of operation.
- */
- function _processFiles($sType, $sAction, $mixedFiles, $bDynamic = false, $bSystem = false)
- {
- if(empty($mixedFiles))
- return $bDynamic ? "" : false;
- if(is_string($mixedFiles))
- $mixedFiles = array($mixedFiles);
- $sUpcaseType = ucfirst($sType);
- $sMethodLocate = '_getAbsoluteLocation' . $sUpcaseType;
- $sMethodWrap = '_wrapInTag' . $sUpcaseType;
- $sResult = '';
- foreach($mixedFiles as $sFile) {
- //--- Process 3d Party CSS/JS file ---//
- if(strpos($sFile, "http://") !== false || strpos($sFile, "https://") !== false) {
- $sUrl = $sFile;
- $sPath = $sFile;
- }
- //--- Process Custom CSS/JS file ---//
- else if(strpos($sFile, "|") !== false) {
- $sFile = implode('', explode("|", $sFile));
- $sFile = bx_ltrim_str($sFile, BX_DIRECTORY_PATH_ROOT);
- $sUrl = BX_DOL_URL_ROOT . $sFile;
- $sPath = realpath(BX_DIRECTORY_PATH_ROOT . $sFile);
- }
- //--- Process Common CSS/JS file(check in default locations) ---//
- else {
- $sUrl = $this->$sMethodLocate('url', $sFile);
- $sPath = $this->$sMethodLocate('path', $sFile);
- }
- if(empty($sPath) || empty($sUrl))
- continue;
- $sArrayKey = $sType . ($bSystem ? '_system' : '_compiled');
- switch($sAction) {
- case 'add':
- if($bDynamic)
- $sResult .= $this->$sMethodWrap($sUrl);
- else {
- $bFound = false;
- $aSearchIn = $bSystem ? $this->aPage[$sArrayKey] : array_merge($this->aPage[$sType . '_system'], $this->aPage[$sArrayKey]);
- foreach($aSearchIn as $iKey => $aValue)
- if($aValue['url'] == $sUrl && $aValue['path'] == $sPath) {
- $bFound = true;
- break;
- }
- if(!$bFound)
- $this->aPage[$sArrayKey][] = array('url' => $sUrl, 'path' => $sPath);
- }
- break;
- case 'delete':
- if(!$bDynamic)
- foreach($this->aPage[$sArrayKey] as $iKey => $aValue)
- if($aValue['url'] == $sUrl) {
- unset($this->aPage[$sArrayKey][$iKey]);
- break;
- }
- break;
- }
- }
- return $bDynamic ? $sResult : true;
- }
- /**
- * Parse content.
- *
- * @param string $sContent - HTML file's content.
- * @param array $aVariables - key/value pairs. key should be the same as template's key, but without prefix and postfix.
- * @param mixed $mixedKeyWrapperHtml - key wrapper(string value if left and right parts are the same, array(0 => left, 1 => right) otherwise).
- * @return string the result of operation.
- */
- function _parseContent($sContent, $aVariables, $mixedKeyWrapperHtml = null)
- {
- $aKeysSrc = array_keys($aVariables);
- $aValuesSrc = array_values($aVariables);
- $aKeyWrappers = $this->_getKeyWrappers($mixedKeyWrapperHtml);
- $sKeyIf = 'bx_if:';
- $sKeyRepeat = 'bx_repeat:';
- $iCountKeys = count($aKeysSrc);
- $aKeys = $aValues = array();
- //--- Parse simple keys ---//
- for ($i = 0; $i < $iCountKeys; $i++) {
- if (strncmp($aKeysSrc[$i], $sKeyRepeat, 10) === 0 || strncmp($aKeysSrc[$i], $sKeyIf, 6) === 0)
- continue;
- $aKeys[] = "'" . $aKeyWrappers['left'] . $aKeysSrc[$i] . $aKeyWrappers['right'] . "'s";
- $aValues[] = str_replace('$', '\\$', $aValuesSrc[$i]);
- }
- //--- Parse keys with constructions ---//
- for ($i = 0; $i < $iCountKeys; $i++) {
- if (strncmp($aKeysSrc[$i], $sKeyRepeat, 10) === 0) {
- $sKey = "'<" . $aKeysSrc[$i] . ">(.*)<\/" . $aKeysSrc[$i] . ">'s";
- $aMatches = array();
- preg_match($sKey, $sContent, $aMatches);
- $sValue = '';
- if(isset($aMatches[1]) && !empty($aMatches[1])) {
- if(is_array($aValuesSrc[$i]))
- foreach($aValuesSrc[$i] as $aValue)
- $sValue .= $this->parseHtmlByContent($aMatches[1], $aValue, $mixedKeyWrapperHtml);
- else if(is_string($aValuesSrc[$i]))
- $sValue = $aValuesSrc[$i];
- }
- }
- else if (strncmp($aKeysSrc[$i], $sKeyIf, 6) === 0) {
- $sKey = "'<" . $aKeysSrc[$i] . ">(.*)<\/" . $aKeysSrc[$i] . ">'s";
- $aMatches = array();
- preg_match($sKey, $sContent, $aMatches);
- $sValue = '';
- if(isset($aMatches[1]) && !empty($aMatches[1]))
- if(is_array($aValuesSrc[$i]) && isset($aValuesSrc[$i]['content']) && isset($aValuesSrc[$i]['condition']) && $aValuesSrc[$i]['condition'])
- $sValue .= $this->parseHtmlByContent($aMatches[1], $aValuesSrc[$i]['content'], $mixedKeyWrapperHtml);
- }
- else
- continue;
- $aKeys[] = $sKey;
- $aValues[] = str_replace('$', '\\$', $sValue);
- }
- try {
- $oTemplate = &$this;
- $aCallbackPatterns = array(
- "'<bx_include_auto:([^\s]+) \/>'s" => BX_DOL_TEMPLATE_CHECK_IN_BOTH,
- "'<bx_include_base:([^\s]+) \/>'s" => BX_DOL_TEMPLATE_CHECK_IN_BASE,
- "'<bx_include_tmpl:([^\s]+) \/>'s" => BX_DOL_TEMPLATE_CHECK_IN_TMPL
- );
- foreach($aCallbackPatterns as $sPattern => $sCheckIn)
- $sContent = preg_replace_callback($sPattern, function($aMatches) use($oTemplate, $aVariables, $mixedKeyWrapperHtml, $sCheckIn) {
- return $oTemplate->parseHtmlByName($aMatches[1], $aVariables, $mixedKeyWrapperHtml, $sCheckIn);
- }, $sContent);
- $sContent = $this->_parseContentKeys($sContent, array(
- "'<bx_injection:([^\s]+) />'s" => 'get_injection',
- "'<bx_menu:([^\s]+) \/>'s" => 'get_menu',
- ));
- }
- catch(Exception $oException) {
- return '';
- }
- $aKeys = array_merge($aKeys, array(
- "'<bx_url_root />'",
- "'<bx_url_studio />'",
- ));
- $aValues = array_merge($aValues, array(
- BX_DOL_URL_ROOT,
- BX_DOL_URL_STUDIO,
- ));
- //--- Parse Predefined Keys ---//
- $sContent = preg_replace($aKeys, $aValues, $sContent);
- //--- Parse System Keys ---//
- $sContent = preg_replace_callback("'" . $aKeyWrappers['left'] . "([a-zA-Z0-9_-]+)" . $aKeyWrappers['right'] . "'", function($aMatches) use($oTemplate, $mixedKeyWrapperHtml) {
- return $oTemplate->parseSystemKey($aMatches[1], $mixedKeyWrapperHtml);
- }, $sContent);
- return $sContent;
- }
- /**
- * Compile content
- *
- * @param string $sContent template.
- * @param string $aVarName variable name to be saved in the output file.
- * @param integer $iVarDepth depth is used to process nesting, for example, in cycles.
- * @param array $aVarValues values to be compiled in.
- * @param mixed $mixedKeyWrapperHtml key wrapper(string value if left and right parts are the same, array(0 => left, 1 => right) otherwise).
- * @return string the result of operation.
- */
- function _compileContent($sContent, $aVarName, $iVarDepth, $aVarValues, $mixedKeyWrapperHtml = null)
- {
- $aKeys = array_keys($aVarValues);
- $aValues = array_values($aVarValues);
- $aKeyWrappers = $this->_getKeyWrappers($mixedKeyWrapperHtml);
- for($i = 0; $i < count($aKeys); $i++) {
- if(strpos($aKeys[$i], 'bx_repeat:') === 0) {
- $sKey = "'<" . $aKeys[$i] . ">(.*)<\/" . $aKeys[$i] . ">'s";
- $aMatches = array();
- preg_match($sKey, $sContent, $aMatches);
- $sValue = '';
- if(isset($aMatches[1]) && !empty($aMatches[1])) {
- if(empty($aValues[$i]) || !is_array($aValues[$i]))
- return false;
- $sIndex = "\$" . str_repeat("i", $iVarDepth);
- $sValue .= "<?php if(is_array(" . $aVarName . "['" . $aKeys[$i] . "'])) for(" . $sIndex . "=0; " . $sIndex . "<count(" . $aVarName . "['" . $aKeys[$i] . "']); " . $sIndex . "++){ ?>";
- if(($sInnerValue = $this->_compileContent($aMatches[1], $aVarName . "['" . $aKeys[$i] . "'][" . $sIndex . "]", $iVarDepth + 1, current($aValues[$i]), $mixedKeyWrapperHtml)) === false)
- return false;
- $sValue .= $sInnerValue;
- $sValue .= "<?php } else if(is_string(" . $aVarName . "['" . $aKeys[$i] . "'])) echo " . $aVarName . "['" . $aKeys[$i] . "']; ?>";
- }
- } else if(strpos($aKeys[$i], 'bx_if:') === 0) {
- $sKey = "'<" . $aKeys[$i] . ">(.*)<\/" . $aKeys[$i] . ">'s";
- $aMatches = array();
- preg_match($sKey, $sContent, $aMatches);
- $sValue = '';
- if(isset($aMatches[1]) && !empty($aMatches[1])) {
- if(!is_array($aValues[$i]) || !isset($aValues[$i]['content']) || empty($aValues[$i]['content']) || !is_array($aValues[$i]['content']))
- return false;
- $sValue .= "<?php if(" . $aVarName . "['" . $aKeys[$i] . "']['condition']){ ?>";
- if(($sInnerValue = $this->_compileContent($aMatches[1], $aVarName . "['" . $aKeys[$i] . "']['content']", $iVarDepth, $aValues[$i]['content'], $mixedKeyWrapperHtml)) === false)
- return false;
- $sValue .= $sInnerValue;
- $sValue .= "<?php } ?>";
- }
- } else {
- $sKey = "'" . $aKeyWrappers['left'] . $aKeys[$i] . $aKeyWrappers['right'] . "'s";
- $sValue = "<?php echo " . $aVarName . "['" . $aKeys[$i] . "'];?>";
- }
- $aKeys[$i] = $sKey;
- $aValues[$i] = $sValue;
- }
- try {
- $oTemplate = &$this;
- $aCallbackPatterns = array(
- "'<bx_include_auto:([^\s]+) \/>'s" => BX_DOL_TEMPLATE_CHECK_IN_BOTH,
- "'<bx_include_base:([^\s]+) \/>'s" => BX_DOL_TEMPLATE_CHECK_IN_BASE,
- "'<bx_include_tmpl:([^\s]+) \/>'s" => BX_DOL_TEMPLATE_CHECK_IN_TMPL
- );
- foreach($aCallbackPatterns as $sPattern => $sCheckIn)
- $sContent = preg_replace_callback($sPattern, function($aMatches) use($oTemplate, $aVarValues, $mixedKeyWrapperHtml, $sCheckIn) {
- $mixedResult = $oTemplate->getCached($aMatches[1], $aVarValues, $mixedKeyWrapperHtml, $sCheckIn, false);
- if($mixedResult === false)
- throw new Exception('Unable to create cache file.');
- return $mixedResult;
- }, $sContent);
- $sContent = $this->_parseContentKeys($sContent);
- }
- catch(Exception $oException) {
- return false;
- }
- $aKeys = array_merge($aKeys, array(
- "'<bx_injection:([^\s]+) />'s",
- "'<bx_menu:([^\s]+) \/>'s",
- "'<bx_url_root />'",
- "'<bx_url_studio />'"
- ));
- $aValues = array_merge($aValues, array(
- "<?php echo \$this->processInjection(\$this->aPage['name_index'], '\\1'); ?>",
- "<?php echo \$this->getMenu('\\1'); ?>",
- BX_DOL_URL_ROOT,
- BX_DOL_URL_STUDIO
- ));
- //--- Parse Predefined Keys ---//
- $sContent = preg_replace($aKeys, $aValues, $sContent);
- //--- Parse System Keys ---//
- $sContent = preg_replace( "'" . $aKeyWrappers['left'] . "([a-zA-Z0-9_-]+)" . $aKeyWrappers['right'] . "'", "<?php echo \$this->parseSystemKey('\\1', \$mixedKeyWrapperHtml);?>", $sContent);
- return $sContent;
- }
- protected function _parseContentKeys($sContent, $aCallbackPatterns = array())
- {
- $oTemplate = &$this;
- $aCallbackPatterns = array_merge($aCallbackPatterns, array(
- "'<bx_image_url:([^\s]+) \/>'s" => "get_image_url",
- "'<bx_icon_url:([^\s]+) \/>'s" => "get_icon_url",
- "'<bx_text:([_\{\}\w\d\s]+[^\s]{1}) \/>'s" => "get_text",
- "'<bx_text_js:([^\s]+) \/>'s" => "get_text_js",
- "'<bx_text_attribute:([^\s]+) \/>'s" => "get_text_attribute",
- ));
- foreach($aCallbackPatterns as $sPattern => $sAction)
- $sContent = preg_replace_callback($sPattern, function($aMatches) use($oTemplate, $sAction) {
- $sResult = '';
- switch($sAction) {
- case 'get_image_url':
- $sResult = $oTemplate->getImageUrl($aMatches[1]);
- break;
- case 'get_icon_url':
- $sResult = $oTemplate->getIconUrl($aMatches[1]);
- break;
- case 'get_text':
- $sResult = _t($aMatches[1]);
- break;
- case 'get_text_js':
- $sResult = bx_js_string(_t($aMatches[1]));
- break;
- case 'get_text_attribute':
- $sResult = bx_html_attribute(_t($aMatches[1]));
- break;
- case 'get_injection':
- $sResult = $oTemplate->processInjection($oTemplate->getPageNameIndex(), $aMatches[1]);
- break;
- case 'get_menu':
- $sResult = $oTemplate->getMenu($aMatches[1]);
- break;
- }
- return $sResult;
- }, $sContent);
- return $sContent;
- }
- /**
- * Get absolute location of some template's part.
- *
- * @param string $sType - result type. Available values 'url' and 'path'.
- * @param string $sFolder - folders to be searched in. @see $_sFolderHtml, $_sFolderCss, $_sFolderImages and $_sFolderIcons
- * @param string $sName - requested part name.
- * @param string $sCheckIn where the content would be searched(base, template, both)
- * @return string absolute location (path/url) of the part.
- */
- function _getAbsoluteLocation($sType, $sFolder, $sName, $sCheckIn = BX_DOL_TEMPLATE_CHECK_IN_BOTH)
- {
- $sDirectory = $this->getPath();
- if($sType == 'path') {
- $sDivider = DIRECTORY_SEPARATOR;
- $sRoot = BX_DIRECTORY_PATH_ROOT;
- } else if($sType == 'url') {
- $sDivider = '/';
- $sRoot = BX_DOL_URL_ROOT;
- }
- if(strpos($sName,'|') !== false) {
- $aParts = explode('|', $sName);
- $sName = $aParts[1];
- if(strpos($aParts[0],'@') !== false) {
- $aLocationParts = explode('@', $aParts[0]);
- $sLocationKey = $this->addLocation($aLocationParts[0], BX_DIRECTORY_PATH_ROOT . $aLocationParts[1], BX_DOL_URL_ROOT . $aLocationParts[1]);
- }
- }
- $sResult = '';
- $aLocations = array_reverse($this->_aLocations, true);
- foreach($aLocations as $sKey => $aLocation) {
- if(($sCheckIn == BX_DOL_TEMPLATE_CHECK_IN_BOTH || $sCheckIn == BX_DOL_TEMPLATE_CHECK_IN_TMPL) && extFileExists(BX_DIRECTORY_PATH_MODULES . $this->getPath(). 'data' . DIRECTORY_SEPARATOR . BX_DOL_TEMPLATE_FOLDER_ROOT . DIRECTORY_SEPARATOR . $sKey . DIRECTORY_SEPARATOR . $sFolder . $sName))
- $sResult = $sRoot . 'modules' . $sDivider . $sDirectory. 'data' . $sDivider . BX_DOL_TEMPLATE_FOLDER_ROOT . $sDivider . $sKey . $sDivider . $sFolder . $sName;
- else if(($sCheckIn == BX_DOL_TEMPLATE_CHECK_IN_BOTH || $sCheckIn == BX_DOL_TEMPLATE_CHECK_IN_BASE) && extFileExists($aLocation['path'] . BX_DOL_TEMPLATE_FOLDER_ROOT . DIRECTORY_SEPARATOR . $sFolder . $sName))
- $sResult = $aLocation[$sType] . BX_DOL_TEMPLATE_FOLDER_ROOT . $sDivider . $sFolder . $sName;
- else
- continue;
- break;
- }
- /**
- * try to find from received path
- */
- if(!$sResult && @is_file(BX_DIRECTORY_PATH_ROOT . $aParts[0] . DIRECTORY_SEPARATOR . $aParts[1])) {
- $sResult = $sRoot . $aParts[0] . $sDivider . $aParts[1];
- }
- if(isset($sLocationKey))
- $this->removeLocation($sLocationKey);
- return $sType == 'path' && !empty($sResult) ? realpath($sResult) : $sResult;
- }
- /**
- * Get absolute location of some template's part.
- *
- * @param string $sType result type. Available values 'url' and 'path'.
- * @param string $sName requested part name.
- * @return string absolute location (path/url) of the part.
- */
- function _getAbsoluteLocationJs($sType, $sName)
- {
- $sResult = '';
- $aLocations = array_reverse($this->_aLocationsJs, true);
- foreach($aLocations as $sKey => $aLocation) {
- if(extFileExists($aLocation['path'] . $sName))
- $sResult = $aLocation[$sType] . $sName;
- else
- continue;
- break;
- }
- return $sType == 'path' && !empty($sResult) ? realpath($sResult) : $sResult;
- }
- function _getAbsoluteLocationCss($sType, $sName)
- {
- $sNameLess = str_replace('.css', '.less', $sName);
- $sResult = $this->_getAbsoluteLocation($sType, $this->_sFolderCss, $sNameLess);
- if(!empty($sResult))
- return $sResult;
- return $this->_getAbsoluteLocation($sType, $this->_sFolderCss, $sName);
- }
- /**
- * Get inline data for Images and Icons.
- *
- * @param string $sType image/icon
- * @param string $sName file name
- * @param string $sCheckIn where the content would be searched(base, template, both)
- * @return unknown
- */
- function _getInlineData($sType, $sName, $sCheckIn)
- {
- switch($sType) {
- case 'image':
- $sFolder = $this->_sFolderImages;
- break;
- case 'icon':
- $sFolder = $this->_sFolderIcons;
- break;
- }
- $sPath = $this->_getAbsoluteLocation('path', $sFolder, $sName, $sCheckIn);
- $iFileSize = 0;
- if($this->_bImagesInline && ($iFileSize = filesize($sPath)) !== false && $iFileSize < $this->_iImagesMaxSize) {
- $aFileInfo = pathinfo($sPath);
- return $this->getImageMimeType($aFileInfo['extension']) . ";base64," . base64_encode(file_get_contents($sPath));
- }
- return false;
- }
- /**
- * Get file name where the template would be cached.
- *
- * @param string $sAbsolutePath template's real path.
- * @return string the result of operation.
- */
- function _getCacheFileName($sType, $sAbsolutePath)
- {
- $sResult = bx_site_hash($sAbsolutePath);
- switch($sType) {
- case 'html':
- $sResult = $this->_sCacheFilePrefix . bx_lang_name() . '_' . $this->_sCode . '_' . $sResult;
- break;
- case 'css':
- $sResult = $this->_sCssCachePrefix . (!empty($this->_iMix) ? $this->_iMix . '_' : '') . $sResult;
- break;
- case 'js':
- $sResult = $this->_sJsCachePrefix . $sResult;
- break;
- }
- return $sResult;
- }
- /**
- * Get template key wrappers(left, right)
- *
- * @param mixed $mixedKeyWrapperHtml key wrapper(string value if left and right parts are the same, array(0 => left, 1 => right) otherwise).
- * @return array result of operation.
- */
- function _getKeyWrappers($mixedKeyWrapperHtml)
- {
- $aResult = array();
- if(!empty($mixedKeyWrapperHtml) && is_string($mixedKeyWrapperHtml))
- $aResult = array('left' => $mixedKeyWrapperHtml, 'right' => $mixedKeyWrapperHtml);
- else if(!empty($mixedKeyWrapperHtml) && is_array($mixedKeyWrapperHtml))
- $aResult = array('left' => $mixedKeyWrapperHtml[0], 'right' => $mixedKeyWrapperHtml[1]);
- else
- $aResult = array('left' => $this->_sKeyWrapperHtml, 'right' => $this->_sKeyWrapperHtml);
- return $aResult;
- }
- /**
- * Process all added language translations and return them as a string.
- *
- * @return string with JS code.
- */
- function _processJsTranslations()
- {
- $sReturn = '';
- if(isset($this->aPage['js_translations']) && is_array($this->aPage['js_translations'])) {
- foreach($this->aPage['js_translations'] as $sKey => $sString)
- $sReturn .= "'" . bx_js_string($sKey) . "': '" . bx_js_string($sString) . "',";
- $sReturn = substr($sReturn, 0, -1);
- }
- return '<script type="text/javascript" language="javascript">var aDolLang = {' . $sReturn . '};</script>';
- }
- /**
- * Process all added options and return them as a string.
- *
- * @return string with JS code.
- */
- function _processJsOptions()
- {
- $sReturn = '';
- if(isset($this->aPage['js_options']) && is_array($this->aPage['js_options'])) {
- foreach($this->aPage['js_options'] as $sName => $mixedValue)
- $sReturn .= "'" . bx_js_string($sName) . "': '" . bx_js_string($mixedValue) . "',";
- $sReturn = substr($sReturn, 0, -1);
- }
- return '<script type="text/javascript" language="javascript">var aDolOptions = {' . $sReturn . '};</script>';
- }
- /**
- * Process all added images and return them as a string.
- *
- * @return string with JS code.
- */
- function _processJsImages()
- {
- $sReturn = '';
- if(isset($this->aPage['js_images']) && is_array($this->aPage['js_images'])) {
- foreach($this->aPage['js_images'] as $sKey => $sUrl)
- $sReturn .= "'" . bx_js_string($sKey) . "': '" . bx_js_string($sUrl) . "',";
- $sReturn = substr($sReturn, 0, -1);
- }
- return '<script type="text/javascript" language="javascript">var aDolImages = {' . $sReturn . '};</script>';
- }
- /**
- * Get Gzip loader URL.
- *
- * @param $sType content type CSS/JS
- * @param $sName file name.
- * @return string with URL
- */
- function _getLoaderUrl($sType, $sName)
- {
- return BX_DOL_URL_ROOT . 'gzip_loader.php?file=' . $sName . '.' . $sType;
- }
- /**
- *
- * Functions to display pages with errors, messages and so on.
- *
- */
- function displayAccessDenied ($sMsg = '', $iPage = BX_PAGE_DEFAULT)
- {
- bx_import('BxDolLanguages');
- header("HTTP/1.0 403 Forbidden");
- $this->displayMsg($sMsg ? $sMsg : _t('_Access denied'), false, $iPage);
- }
- function displayNoData ($sMsg = '', $iPage = BX_PAGE_DEFAULT)
- {
- bx_import('BxDolLanguages');
- header("HTTP/1.0 204 No Content");
- $this->displayMsg($sMsg ? $sMsg : _t('_Empty'), false, $iPage);
- }
- function displayErrorOccured ($sMsg = '', $iPage = BX_PAGE_DEFAULT)
- {
- bx_import('BxDolLanguages');
- header("HTTP/1.0 500 Internal Server Error");
- $this->displayMsg($sMsg ? $sMsg : _t('_error occured'), false, $iPage);
- }
- function displayPageNotFound ($sMsg = '', $iPage = BX_PAGE_DEFAULT)
- {
- bx_import('BxDolLanguages');
- header("HTTP/1.0 404 Not Found");
- $this->displayMsg($sMsg ? $sMsg : _t('_sys_request_page_not_found_cpt'), false, $iPage);
- }
- function displayMsg ($s, $bTranslate = false, $iPage = BX_PAGE_DEFAULT)
- {
- $sTitle = $bTranslate ? _t($s) : $s;
- $oTemplate = BxDolTemplate::getInstance();
- $oTemplate->setPageNameIndex ($iPage);
- $oTemplate->setPageHeader (_t('_Error'));
- $s = BX_PAGE_DEFAULT == $iPage ? DesignBoxContent(_t('_Error'), MsgBox($sTitle), BX_DB_PADDING_DEF) : MsgBox($sTitle);
- $oTemplate->setPageContent ('page_main_code', $s);
- $oTemplate->getPageCode();
- exit;
- }
-
- /**
- * * * * Static methods for work with template injections * * *
- *
- * Static method is used to add/replace the content of some key in the template.
- * It's usefull when you don't want to modify existing template but need to add some data to existing template key.
- *
- * @param integer $iPageIndex - page index where injections would processed. Use 0 if you want it to be done on all the pages.
- * @param string $sKey - template key.
- * @param string $sValue - the data to be added.
- * @return string the result of operation.
- */
- function processInjection($iPageIndex, $sKey, $sValue = "")
- {
- if($iPageIndex != 0 && isset($this->aPage['injections']['page_0'][$sKey]) && isset($this->aPage['injections']['page_' . $iPageIndex][$sKey]))
- $aSelection = @array_merge($this->aPage['injections']['page_0'][$sKey], $this->aPage['injections']['page_' . $iPageIndex][$sKey]);
- else if(isset($this->aPage['injections']['page_0'][$sKey]))
- $aSelection = $this->aPage['injections']['page_0'][$sKey];
- else if(isset($this->aPage['injections']['page_' . $iPageIndex][$sKey]))
- $aSelection = $this->aPage['injections']['page_' . $iPageIndex][$sKey];
- else
- $aSelection = array();
- if(is_array($aSelection))
- foreach($aSelection as $aInjection) {
- if (isset($GLOBALS['bx_profiler'])) $GLOBALS['bx_profiler']->beginInjection($sRand = time().rand());
- $sInjData = '';
- switch($aInjection['type']) {
- case 'text':
- $sInjData = $aInjection['data'];
- break;
- case 'service':
- if(BxDolService::isSerializedService($aInjection['data']))
- $sInjData = BxDolService::callSerialized($aInjection['data']);
- break;
- }
- if((int)$aInjection['replace'] == 1)
- $sValue = $sInjData;
- else
- $sValue .= $sInjData;
- if (isset($GLOBALS['bx_profiler'])) $GLOBALS['bx_profiler']->endInjection($sRand, $aInjection);
- }
- return $sValue != '__' . $sKey . '__' ? str_replace('__' . $sKey . '__', '', $sValue) : $sValue;
- }
- /**
- * Static method to add ingection available on the current page only.
- *
- * @param string $sKey - template's key.
- * @param string $sType - injection type(text, php).
- * @param string $sData - the data to be added.
- * @param integer $iReplace - replace already existed data or not.
- */
- function addInjection($sKey, $sType, $sData, $iReplace = 0)
- {
- $this->aPage['injections']['page_0'][$sKey][] = array(
- 'page_index' => 0,
- 'key' => $sKey,
- 'type' => $sType,
- 'data' => $sData,
- 'replace' => $iReplace
- );
- }
- function getPageCode($oTemplate = null)
- {
- if (empty($oTemplate))
- $oTemplate = $this;
- $oZ = new BxDolAlerts('system', 'design_before_output', 0, 0, array('page' => &$this->aPage, 'page_content' => &$this->aPageContent));
- $oZ->alert();
- header( 'Content-type: text/html; charset=utf-8' );
- header( 'X-Frame-Options: sameorigin' );
- echo $oTemplate->parsePageByName('page_' . $oTemplate->getPageNameIndex() . '.html', $oTemplate->getPageContent());
- }
- }
- /** @} */
|