base.php 86 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496
  1. <?php
  2. /*
  3. Copyright (c) 2009-2017 F3::Factory/Bong Cosca, All rights reserved.
  4. This file is part of the Fat-Free Framework (http://fatfreeframework.com).
  5. This is free software: you can redistribute it and/or modify it under the
  6. terms of the GNU General Public License as published by the Free Software
  7. Foundation, either version 3 of the License, or later.
  8. Fat-Free Framework is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  11. General Public License for more details.
  12. You should have received a copy of the GNU General Public License along
  13. with Fat-Free Framework. If not, see <http://www.gnu.org/licenses/>.
  14. */
  15. //! Factory class for single-instance objects
  16. abstract class Prefab {
  17. /**
  18. * Return class instance
  19. * @return static
  20. **/
  21. static function instance() {
  22. if (!Registry::exists($class=get_called_class())) {
  23. $ref=new Reflectionclass($class);
  24. $args=func_get_args();
  25. Registry::set($class,
  26. $args?$ref->newinstanceargs($args):new $class);
  27. }
  28. return Registry::get($class);
  29. }
  30. }
  31. //! Base structure
  32. final class Base extends Prefab implements ArrayAccess {
  33. //@{ Framework details
  34. const
  35. PACKAGE='Fat-Free Framework',
  36. VERSION='3.6.5-Release';
  37. //@}
  38. //@{ HTTP status codes (RFC 2616)
  39. const
  40. HTTP_100='Continue',
  41. HTTP_101='Switching Protocols',
  42. HTTP_103='Early Hints',
  43. HTTP_200='OK',
  44. HTTP_201='Created',
  45. HTTP_202='Accepted',
  46. HTTP_203='Non-Authorative Information',
  47. HTTP_204='No Content',
  48. HTTP_205='Reset Content',
  49. HTTP_206='Partial Content',
  50. HTTP_300='Multiple Choices',
  51. HTTP_301='Moved Permanently',
  52. HTTP_302='Found',
  53. HTTP_303='See Other',
  54. HTTP_304='Not Modified',
  55. HTTP_305='Use Proxy',
  56. HTTP_307='Temporary Redirect',
  57. HTTP_400='Bad Request',
  58. HTTP_401='Unauthorized',
  59. HTTP_402='Payment Required',
  60. HTTP_403='Forbidden',
  61. HTTP_404='Not Found',
  62. HTTP_405='Method Not Allowed',
  63. HTTP_406='Not Acceptable',
  64. HTTP_407='Proxy Authentication Required',
  65. HTTP_408='Request Timeout',
  66. HTTP_409='Conflict',
  67. HTTP_410='Gone',
  68. HTTP_411='Length Required',
  69. HTTP_412='Precondition Failed',
  70. HTTP_413='Request Entity Too Large',
  71. HTTP_414='Request-URI Too Long',
  72. HTTP_415='Unsupported Media Type',
  73. HTTP_416='Requested Range Not Satisfiable',
  74. HTTP_417='Expectation Failed',
  75. HTTP_500='Internal Server Error',
  76. HTTP_501='Not Implemented',
  77. HTTP_502='Bad Gateway',
  78. HTTP_503='Service Unavailable',
  79. HTTP_504='Gateway Timeout',
  80. HTTP_505='HTTP Version Not Supported';
  81. //@}
  82. const
  83. //! Mapped PHP globals
  84. GLOBALS='GET|POST|COOKIE|REQUEST|SESSION|FILES|SERVER|ENV',
  85. //! HTTP verbs
  86. VERBS='GET|HEAD|POST|PUT|PATCH|DELETE|CONNECT|OPTIONS',
  87. //! Default directory permissions
  88. MODE=0755,
  89. //! Syntax highlighting stylesheet
  90. CSS='code.css';
  91. //@{ Request types
  92. const
  93. REQ_SYNC=1,
  94. REQ_AJAX=2,
  95. REQ_CLI=4;
  96. //@}
  97. //@{ Error messages
  98. const
  99. E_Pattern='Invalid routing pattern: %s',
  100. E_Named='Named route does not exist: %s',
  101. E_Fatal='Fatal error: %s',
  102. E_Open='Unable to open %s',
  103. E_Routes='No routes specified',
  104. E_Class='Invalid class %s',
  105. E_Method='Invalid method %s',
  106. E_Hive='Invalid hive key %s';
  107. //@}
  108. private
  109. //! Globals
  110. $hive,
  111. //! Initial settings
  112. $init,
  113. //! Language lookup sequence
  114. $languages,
  115. //! Mutex locks
  116. $locks=[],
  117. //! Default fallback language
  118. $fallback='en';
  119. /**
  120. * Sync PHP global with corresponding hive key
  121. * @return array
  122. * @param $key string
  123. **/
  124. function sync($key) {
  125. return $this->hive[$key]=&$GLOBALS['_'.$key];
  126. }
  127. /**
  128. * Return the parts of specified hive key
  129. * @return array
  130. * @param $key string
  131. **/
  132. private function cut($key) {
  133. return preg_split('/\[\h*[\'"]?(.+?)[\'"]?\h*\]|(->)|\./',
  134. $key,NULL,PREG_SPLIT_NO_EMPTY|PREG_SPLIT_DELIM_CAPTURE);
  135. }
  136. /**
  137. * Replace tokenized URL with available token values
  138. * @return string
  139. * @param $url array|string
  140. * @param $args array
  141. **/
  142. function build($url,$args=[]) {
  143. $args+=$this->hive['PARAMS'];
  144. if (is_array($url))
  145. foreach ($url as &$var) {
  146. $var=$this->build($var,$args);
  147. unset($var);
  148. }
  149. else {
  150. $i=0;
  151. $url=preg_replace_callback('/@(\w+)|(\*)/',
  152. function($match) use(&$i,$args) {
  153. if (isset($match[1]) &&
  154. array_key_exists($match[1],$args))
  155. return $args[$match[1]];
  156. if (isset($match[2]) &&
  157. array_key_exists($match[2],$args)) {
  158. if (!is_array($args[$match[2]]))
  159. return $args[$match[2]];
  160. $i++;
  161. return $args[$match[2]][$i-1];
  162. }
  163. return $match[0];
  164. },$url);
  165. }
  166. return $url;
  167. }
  168. /**
  169. * Parse string containing key-value pairs
  170. * @return array
  171. * @param $str string
  172. **/
  173. function parse($str) {
  174. preg_match_all('/(\w+|\*)\h*=\h*(?:\[(.+?)\]|(.+?))(?=,|$)/',
  175. $str,$pairs,PREG_SET_ORDER);
  176. $out=[];
  177. foreach ($pairs as $pair)
  178. if ($pair[2]) {
  179. $out[$pair[1]]=[];
  180. foreach (explode(',',$pair[2]) as $val)
  181. array_push($out[$pair[1]],$val);
  182. }
  183. else
  184. $out[$pair[1]]=trim($pair[3]);
  185. return $out;
  186. }
  187. /**
  188. * Cast string variable to PHP type or constant
  189. * @param $val
  190. * @return mixed
  191. */
  192. function cast($val) {
  193. if (preg_match('/^(?:0x[0-9a-f]+|0[0-7]+|0b[01]+)$/i',$val))
  194. return intval($val,0);
  195. if (is_numeric($val))
  196. return $val+0;
  197. $val=trim($val);
  198. if (preg_match('/^\w+$/i',$val) && defined($val))
  199. return constant($val);
  200. return $val;
  201. }
  202. /**
  203. * Convert JS-style token to PHP expression
  204. * @return string
  205. * @param $str string
  206. **/
  207. function compile($str) {
  208. return preg_replace_callback(
  209. '/(?<!\w)@(\w+(?:(?:\->|::)\w+)?)'.
  210. '((?:\.\w+|\[(?:(?:[^\[\]]*|(?R))*)\]|(?:\->|::)\w+|\()*)/',
  211. function($expr) {
  212. $str='$'.$expr[1];
  213. if (isset($expr[2]))
  214. $str.=preg_replace_callback(
  215. '/\.(\w+)(\()?|\[((?:[^\[\]]*|(?R))*)\]/',
  216. function($sub) {
  217. if (empty($sub[2])) {
  218. if (ctype_digit($sub[1]))
  219. $sub[1]=(int)$sub[1];
  220. $out='['.
  221. (isset($sub[3])?
  222. $this->compile($sub[3]):
  223. $this->export($sub[1])).
  224. ']';
  225. }
  226. else
  227. $out=function_exists($sub[1])?
  228. $sub[0]:
  229. ('['.$this->export($sub[1]).']'.$sub[2]);
  230. return $out;
  231. },
  232. $expr[2]
  233. );
  234. return $str;
  235. },
  236. $str
  237. );
  238. }
  239. /**
  240. * Get hive key reference/contents; Add non-existent hive keys,
  241. * array elements, and object properties by default
  242. * @return mixed
  243. * @param $key string
  244. * @param $add bool
  245. * @param $var mixed
  246. **/
  247. function &ref($key,$add=TRUE,&$var=NULL) {
  248. $null=NULL;
  249. $parts=$this->cut($key);
  250. if ($parts[0]=='SESSION') {
  251. if (!headers_sent() && session_status()!=PHP_SESSION_ACTIVE)
  252. session_start();
  253. $this->sync('SESSION');
  254. }
  255. elseif (!preg_match('/^\w+$/',$parts[0]))
  256. user_error(sprintf(self::E_Hive,$this->stringify($key)),
  257. E_USER_ERROR);
  258. if (is_null($var)) {
  259. if ($add)
  260. $var=&$this->hive;
  261. else
  262. $var=$this->hive;
  263. }
  264. $obj=FALSE;
  265. foreach ($parts as $part)
  266. if ($part=='->')
  267. $obj=TRUE;
  268. elseif ($obj) {
  269. $obj=FALSE;
  270. if (!is_object($var))
  271. $var=new stdclass;
  272. if ($add || property_exists($var,$part))
  273. $var=&$var->$part;
  274. else {
  275. $var=&$null;
  276. break;
  277. }
  278. }
  279. else {
  280. if (!is_array($var))
  281. $var=[];
  282. if ($add || array_key_exists($part,$var))
  283. $var=&$var[$part];
  284. else {
  285. $var=&$null;
  286. break;
  287. }
  288. }
  289. return $var;
  290. }
  291. /**
  292. * Return TRUE if hive key is set
  293. * (or return timestamp and TTL if cached)
  294. * @return bool
  295. * @param $key string
  296. * @param $val mixed
  297. **/
  298. function exists($key,&$val=NULL) {
  299. $val=$this->ref($key,FALSE);
  300. return isset($val)?
  301. TRUE:
  302. (Cache::instance()->exists($this->hash($key).'.var',$val)?:FALSE);
  303. }
  304. /**
  305. * Return TRUE if hive key is empty and not cached
  306. * @param $key string
  307. * @param $val mixed
  308. * @return bool
  309. **/
  310. function devoid($key,&$val=NULL) {
  311. $val=$this->ref($key,FALSE);
  312. return empty($val) &&
  313. (!Cache::instance()->exists($this->hash($key).'.var',$val) ||
  314. !$val);
  315. }
  316. /**
  317. * Bind value to hive key
  318. * @return mixed
  319. * @param $key string
  320. * @param $val mixed
  321. * @param $ttl int
  322. **/
  323. function set($key,$val,$ttl=0) {
  324. $time=(int)$this->hive['TIME'];
  325. if (preg_match('/^(GET|POST|COOKIE)\b(.+)/',$key,$expr)) {
  326. $this->set('REQUEST'.$expr[2],$val);
  327. if ($expr[1]=='COOKIE') {
  328. $parts=$this->cut($key);
  329. $jar=$this->unserialize($this->serialize($this->hive['JAR']));
  330. unset($jar['lifetime']);
  331. if (isset($_COOKIE[$parts[1]]))
  332. call_user_func_array('setcookie',
  333. array_merge([$parts[1],NULL],['expire'=>0]+$jar));
  334. if ($ttl)
  335. $jar['expire']=$time+$ttl;
  336. call_user_func_array('setcookie',[$parts[1],$val]+$jar);
  337. $_COOKIE[$parts[1]]=$val;
  338. return $val;
  339. }
  340. }
  341. else switch ($key) {
  342. case 'CACHE':
  343. $val=Cache::instance()->load($val);
  344. break;
  345. case 'ENCODING':
  346. ini_set('default_charset',$val);
  347. if (extension_loaded('mbstring'))
  348. mb_internal_encoding($val);
  349. break;
  350. case 'FALLBACK':
  351. $this->fallback=$val;
  352. $lang=$this->language($this->hive['LANGUAGE']);
  353. case 'LANGUAGE':
  354. if (!isset($lang))
  355. $val=$this->language($val);
  356. $lex=$this->lexicon($this->hive['LOCALES'],$ttl);
  357. case 'LOCALES':
  358. if (isset($lex) || $lex=$this->lexicon($val,$ttl))
  359. foreach ($lex as $dt=>$dd) {
  360. $ref=&$this->ref($this->hive['PREFIX'].$dt);
  361. $ref=$dd;
  362. unset($ref);
  363. }
  364. break;
  365. case 'TZ':
  366. date_default_timezone_set($val);
  367. break;
  368. }
  369. $ref=&$this->ref($key);
  370. $ref=$val;
  371. if (preg_match('/^JAR\b/',$key)) {
  372. if ($key=='JAR.lifetime')
  373. $this->set('JAR.expire',$val==0?0:
  374. (is_int($val)?$time+$val:strtotime($val)));
  375. else {
  376. if ($key=='JAR.expire')
  377. $this->hive['JAR']['lifetime']=max(0,$val-$time);
  378. $jar=$this->unserialize($this->serialize($this->hive['JAR']));
  379. unset($jar['expire']);
  380. if (!headers_sent() && session_status()!=PHP_SESSION_ACTIVE)
  381. call_user_func_array('session_set_cookie_params',$jar);
  382. }
  383. }
  384. if ($ttl)
  385. // Persist the key-value pair
  386. Cache::instance()->set($this->hash($key).'.var',$val,$ttl);
  387. return $ref;
  388. }
  389. /**
  390. * Retrieve contents of hive key
  391. * @return mixed
  392. * @param $key string
  393. * @param $args string|array
  394. **/
  395. function get($key,$args=NULL) {
  396. if (is_string($val=$this->ref($key,FALSE)) && !is_null($args))
  397. return call_user_func_array(
  398. [$this,'format'],
  399. array_merge([$val],is_array($args)?$args:[$args])
  400. );
  401. if (is_null($val)) {
  402. // Attempt to retrieve from cache
  403. if (Cache::instance()->exists($this->hash($key).'.var',$data))
  404. return $data;
  405. }
  406. return $val;
  407. }
  408. /**
  409. * Unset hive key
  410. * @return NULL
  411. * @param $key string
  412. **/
  413. function clear($key) {
  414. // Normalize array literal
  415. $cache=Cache::instance();
  416. $parts=$this->cut($key);
  417. if ($key=='CACHE')
  418. // Clear cache contents
  419. $cache->reset();
  420. elseif (preg_match('/^(GET|POST|COOKIE)\b(.+)/',$key,$expr)) {
  421. $this->clear('REQUEST'.$expr[2]);
  422. if ($expr[1]=='COOKIE') {
  423. $parts=$this->cut($key);
  424. $jar=$this->hive['JAR'];
  425. unset($jar['lifetime']);
  426. $jar['expire']=0;
  427. call_user_func_array('setcookie',
  428. array_merge([$parts[1],NULL],$jar));
  429. unset($_COOKIE[$parts[1]]);
  430. }
  431. }
  432. elseif ($parts[0]=='SESSION') {
  433. if (!headers_sent() && session_status()!=PHP_SESSION_ACTIVE)
  434. session_start();
  435. if (empty($parts[1])) {
  436. // End session
  437. session_unset();
  438. session_destroy();
  439. $this->clear('COOKIE.'.session_name());
  440. }
  441. $this->sync('SESSION');
  442. }
  443. if (!isset($parts[1]) && array_key_exists($parts[0],$this->init))
  444. // Reset global to default value
  445. $this->hive[$parts[0]]=$this->init[$parts[0]];
  446. else {
  447. eval('unset('.$this->compile('@this->hive.'.$key).');');
  448. if ($parts[0]=='SESSION') {
  449. session_commit();
  450. session_start();
  451. }
  452. if ($cache->exists($hash=$this->hash($key).'.var'))
  453. // Remove from cache
  454. $cache->clear($hash);
  455. }
  456. }
  457. /**
  458. * Return TRUE if hive variable is 'on'
  459. * @return bool
  460. * @param $key string
  461. **/
  462. function checked($key) {
  463. $ref=&$this->ref($key);
  464. return $ref=='on';
  465. }
  466. /**
  467. * Return TRUE if property has public visibility
  468. * @return bool
  469. * @param $obj object
  470. * @param $key string
  471. **/
  472. function visible($obj,$key) {
  473. if (property_exists($obj,$key)) {
  474. $ref=new ReflectionProperty(get_class($obj),$key);
  475. $out=$ref->ispublic();
  476. unset($ref);
  477. return $out;
  478. }
  479. return FALSE;
  480. }
  481. /**
  482. * Multi-variable assignment using associative array
  483. * @return NULL
  484. * @param $vars array
  485. * @param $prefix string
  486. * @param $ttl int
  487. **/
  488. function mset(array $vars,$prefix='',$ttl=0) {
  489. foreach ($vars as $key=>$val)
  490. $this->set($prefix.$key,$val,$ttl);
  491. }
  492. /**
  493. * Publish hive contents
  494. * @return array
  495. **/
  496. function hive() {
  497. return $this->hive;
  498. }
  499. /**
  500. * Copy contents of hive variable to another
  501. * @return mixed
  502. * @param $src string
  503. * @param $dst string
  504. **/
  505. function copy($src,$dst) {
  506. $ref=&$this->ref($dst);
  507. return $ref=$this->ref($src,FALSE);
  508. }
  509. /**
  510. * Concatenate string to hive string variable
  511. * @return string
  512. * @param $key string
  513. * @param $val string
  514. **/
  515. function concat($key,$val) {
  516. $ref=&$this->ref($key);
  517. $ref.=$val;
  518. return $ref;
  519. }
  520. /**
  521. * Swap keys and values of hive array variable
  522. * @return array
  523. * @param $key string
  524. * @public
  525. **/
  526. function flip($key) {
  527. $ref=&$this->ref($key);
  528. return $ref=array_combine(array_values($ref),array_keys($ref));
  529. }
  530. /**
  531. * Add element to the end of hive array variable
  532. * @return mixed
  533. * @param $key string
  534. * @param $val mixed
  535. **/
  536. function push($key,$val) {
  537. $ref=&$this->ref($key);
  538. $ref[]=$val;
  539. return $val;
  540. }
  541. /**
  542. * Remove last element of hive array variable
  543. * @return mixed
  544. * @param $key string
  545. **/
  546. function pop($key) {
  547. $ref=&$this->ref($key);
  548. return array_pop($ref);
  549. }
  550. /**
  551. * Add element to the beginning of hive array variable
  552. * @return mixed
  553. * @param $key string
  554. * @param $val mixed
  555. **/
  556. function unshift($key,$val) {
  557. $ref=&$this->ref($key);
  558. array_unshift($ref,$val);
  559. return $val;
  560. }
  561. /**
  562. * Remove first element of hive array variable
  563. * @return mixed
  564. * @param $key string
  565. **/
  566. function shift($key) {
  567. $ref=&$this->ref($key);
  568. return array_shift($ref);
  569. }
  570. /**
  571. * Merge array with hive array variable
  572. * @return array
  573. * @param $key string
  574. * @param $src string|array
  575. * @param $keep bool
  576. **/
  577. function merge($key,$src,$keep=FALSE) {
  578. $ref=&$this->ref($key);
  579. if (!$ref)
  580. $ref=[];
  581. $out=array_merge($ref,is_string($src)?$this->hive[$src]:$src);
  582. if ($keep)
  583. $ref=$out;
  584. return $out;
  585. }
  586. /**
  587. * Extend hive array variable with default values from $src
  588. * @return array
  589. * @param $key string
  590. * @param $src string|array
  591. * @param $keep bool
  592. **/
  593. function extend($key,$src,$keep=FALSE) {
  594. $ref=&$this->ref($key);
  595. if (!$ref)
  596. $ref=[];
  597. $out=array_replace_recursive(
  598. is_string($src)?$this->hive[$src]:$src,$ref);
  599. if ($keep)
  600. $ref=$out;
  601. return $out;
  602. }
  603. /**
  604. * Convert backslashes to slashes
  605. * @return string
  606. * @param $str string
  607. **/
  608. function fixslashes($str) {
  609. return $str?strtr($str,'\\','/'):$str;
  610. }
  611. /**
  612. * Split comma-, semi-colon, or pipe-separated string
  613. * @return array
  614. * @param $str string
  615. * @param $noempty bool
  616. **/
  617. function split($str,$noempty=TRUE) {
  618. return array_map('trim',
  619. preg_split('/[,;|]/',$str,0,$noempty?PREG_SPLIT_NO_EMPTY:0));
  620. }
  621. /**
  622. * Convert PHP expression/value to compressed exportable string
  623. * @return string
  624. * @param $arg mixed
  625. * @param $stack array
  626. **/
  627. function stringify($arg,array $stack=NULL) {
  628. if ($stack) {
  629. foreach ($stack as $node)
  630. if ($arg===$node)
  631. return '*RECURSION*';
  632. }
  633. else
  634. $stack=[];
  635. switch (gettype($arg)) {
  636. case 'object':
  637. $str='';
  638. foreach (get_object_vars($arg) as $key=>$val)
  639. $str.=($str?',':'').
  640. $this->export($key).'=>'.
  641. $this->stringify($val,
  642. array_merge($stack,[$arg]));
  643. return get_class($arg).'::__set_state(['.$str.'])';
  644. case 'array':
  645. $str='';
  646. $num=isset($arg[0]) &&
  647. ctype_digit(implode('',array_keys($arg)));
  648. foreach ($arg as $key=>$val)
  649. $str.=($str?',':'').
  650. ($num?'':($this->export($key).'=>')).
  651. $this->stringify($val,array_merge($stack,[$arg]));
  652. return '['.$str.']';
  653. default:
  654. return $this->export($arg);
  655. }
  656. }
  657. /**
  658. * Flatten array values and return as CSV string
  659. * @return string
  660. * @param $args array
  661. **/
  662. function csv(array $args) {
  663. return implode(',',array_map('stripcslashes',
  664. array_map([$this,'stringify'],$args)));
  665. }
  666. /**
  667. * Convert snakecase string to camelcase
  668. * @return string
  669. * @param $str string
  670. **/
  671. function camelcase($str) {
  672. return preg_replace_callback(
  673. '/_(\pL)/u',
  674. function($match) {
  675. return strtoupper($match[1]);
  676. },
  677. $str
  678. );
  679. }
  680. /**
  681. * Convert camelcase string to snakecase
  682. * @return string
  683. * @param $str string
  684. **/
  685. function snakecase($str) {
  686. return strtolower(preg_replace('/(?!^)\p{Lu}/u','_\0',$str));
  687. }
  688. /**
  689. * Return -1 if specified number is negative, 0 if zero,
  690. * or 1 if the number is positive
  691. * @return int
  692. * @param $num mixed
  693. **/
  694. function sign($num) {
  695. return $num?($num/abs($num)):0;
  696. }
  697. /**
  698. * Extract values of array whose keys start with the given prefix
  699. * @return array
  700. * @param $arr array
  701. * @param $prefix string
  702. **/
  703. function extract($arr,$prefix) {
  704. $out=[];
  705. foreach (preg_grep('/^'.preg_quote($prefix,'/').'/',array_keys($arr))
  706. as $key)
  707. $out[substr($key,strlen($prefix))]=$arr[$key];
  708. return $out;
  709. }
  710. /**
  711. * Convert class constants to array
  712. * @return array
  713. * @param $class object|string
  714. * @param $prefix string
  715. **/
  716. function constants($class,$prefix='') {
  717. $ref=new ReflectionClass($class);
  718. return $this->extract($ref->getconstants(),$prefix);
  719. }
  720. /**
  721. * Generate 64bit/base36 hash
  722. * @return string
  723. * @param $str
  724. **/
  725. function hash($str) {
  726. return str_pad(base_convert(
  727. substr(sha1($str),-16),16,36),11,'0',STR_PAD_LEFT);
  728. }
  729. /**
  730. * Return Base64-encoded equivalent
  731. * @return string
  732. * @param $data string
  733. * @param $mime string
  734. **/
  735. function base64($data,$mime) {
  736. return 'data:'.$mime.';base64,'.base64_encode($data);
  737. }
  738. /**
  739. * Convert special characters to HTML entities
  740. * @return string
  741. * @param $str string
  742. **/
  743. function encode($str) {
  744. return @htmlspecialchars($str,$this->hive['BITMASK'],
  745. $this->hive['ENCODING'])?:$this->scrub($str);
  746. }
  747. /**
  748. * Convert HTML entities back to characters
  749. * @return string
  750. * @param $str string
  751. **/
  752. function decode($str) {
  753. return htmlspecialchars_decode($str,$this->hive['BITMASK']);
  754. }
  755. /**
  756. * Invoke callback recursively for all data types
  757. * @return mixed
  758. * @param $arg mixed
  759. * @param $func callback
  760. * @param $stack array
  761. **/
  762. function recursive($arg,$func,$stack=[]) {
  763. if ($stack) {
  764. foreach ($stack as $node)
  765. if ($arg===$node)
  766. return $arg;
  767. }
  768. switch (gettype($arg)) {
  769. case 'object':
  770. $ref=new ReflectionClass($arg);
  771. if ($ref->iscloneable()) {
  772. $arg=clone($arg);
  773. $cast=is_a($arg,'IteratorAggregate')?
  774. iterator_to_array($arg):get_object_vars($arg);
  775. foreach ($cast as $key=>$val)
  776. $arg->$key=$this->recursive(
  777. $val,$func,array_merge($stack,[$arg]));
  778. }
  779. return $arg;
  780. case 'array':
  781. $copy=[];
  782. foreach ($arg as $key=>$val)
  783. $copy[$key]=$this->recursive($val,$func,
  784. array_merge($stack,[$arg]));
  785. return $copy;
  786. }
  787. return $func($arg);
  788. }
  789. /**
  790. * Remove HTML tags (except those enumerated) and non-printable
  791. * characters to mitigate XSS/code injection attacks
  792. * @return mixed
  793. * @param $arg mixed
  794. * @param $tags string
  795. **/
  796. function clean($arg,$tags=NULL) {
  797. return $this->recursive($arg,
  798. function($val) use($tags) {
  799. if ($tags!='*')
  800. $val=trim(strip_tags($val,
  801. '<'.implode('><',$this->split($tags)).'>'));
  802. return trim(preg_replace(
  803. '/[\x00-\x08\x0B\x0C\x0E-\x1F]/','',$val));
  804. }
  805. );
  806. }
  807. /**
  808. * Similar to clean(), except that variable is passed by reference
  809. * @return mixed
  810. * @param $var mixed
  811. * @param $tags string
  812. **/
  813. function scrub(&$var,$tags=NULL) {
  814. return $var=$this->clean($var,$tags);
  815. }
  816. /**
  817. * Return locale-aware formatted string
  818. * @return string
  819. **/
  820. function format() {
  821. $args=func_get_args();
  822. $val=array_shift($args);
  823. // Get formatting rules
  824. $conv=localeconv();
  825. return preg_replace_callback(
  826. '/\{\s*(?P<pos>\d+)\s*(?:,\s*(?P<type>\w+)\s*'.
  827. '(?:,\s*(?P<mod>(?:\w+(?:\s*\{.+?\}\s*,?\s*)?)*)'.
  828. '(?:,\s*(?P<prop>.+?))?)?)?\s*\}/',
  829. function($expr) use($args,$conv) {
  830. extract($expr);
  831. extract($conv);
  832. if (!array_key_exists($pos,$args))
  833. return $expr[0];
  834. if (isset($type)) {
  835. if (isset($this->hive['FORMATS'][$type]))
  836. return $this->call(
  837. $this->hive['FORMATS'][$type],
  838. [
  839. $args[$pos],
  840. isset($mod)?$mod:null,
  841. isset($prop)?$prop:null
  842. ]
  843. );
  844. switch ($type) {
  845. case 'plural':
  846. preg_match_all('/(?<tag>\w+)'.
  847. '(?:\s*\{\s*(?<data>.+?)\s*\})/',
  848. $mod,$matches,PREG_SET_ORDER);
  849. $ord=['zero','one','two'];
  850. foreach ($matches as $match) {
  851. extract($match);
  852. if (isset($ord[$args[$pos]]) &&
  853. $tag==$ord[$args[$pos]] || $tag=='other')
  854. return str_replace('#',$args[$pos],$data);
  855. }
  856. case 'number':
  857. if (isset($mod))
  858. switch ($mod) {
  859. case 'integer':
  860. return number_format(
  861. $args[$pos],0,'',$thousands_sep);
  862. case 'currency':
  863. $int=$cstm=FALSE;
  864. if (isset($prop) &&
  865. $cstm=!$int=($prop=='int'))
  866. $currency_symbol=$prop;
  867. if (!$cstm &&
  868. function_exists('money_format'))
  869. return money_format(
  870. '%'.($int?'i':'n'),$args[$pos]);
  871. $fmt=[
  872. 0=>'(nc)',1=>'(n c)',
  873. 2=>'(nc)',10=>'+nc',
  874. 11=>'+n c',12=>'+ nc',
  875. 20=>'nc+',21=>'n c+',
  876. 22=>'nc +',30=>'n+c',
  877. 31=>'n +c',32=>'n+ c',
  878. 40=>'nc+',41=>'n c+',
  879. 42=>'nc +',100=>'(cn)',
  880. 101=>'(c n)',102=>'(cn)',
  881. 110=>'+cn',111=>'+c n',
  882. 112=>'+ cn',120=>'cn+',
  883. 121=>'c n+',122=>'cn +',
  884. 130=>'+cn',131=>'+c n',
  885. 132=>'+ cn',140=>'c+n',
  886. 141=>'c+ n',142=>'c +n'
  887. ];
  888. if ($args[$pos]<0) {
  889. $sgn=$negative_sign;
  890. $pre='n';
  891. }
  892. else {
  893. $sgn=$positive_sign;
  894. $pre='p';
  895. }
  896. return str_replace(
  897. ['+','n','c'],
  898. [$sgn,number_format(
  899. abs($args[$pos]),
  900. $frac_digits,
  901. $decimal_point,
  902. $thousands_sep),
  903. $int?$int_curr_symbol
  904. :$currency_symbol],
  905. $fmt[(int)(
  906. (${$pre.'_cs_precedes'}%2).
  907. (${$pre.'_sign_posn'}%5).
  908. (${$pre.'_sep_by_space'}%3)
  909. )]
  910. );
  911. case 'percent':
  912. return number_format(
  913. $args[$pos]*100,0,$decimal_point,
  914. $thousands_sep).'%';
  915. }
  916. $frac=$args[$pos]-(int)$args[$pos];
  917. return number_format(
  918. $args[$pos],
  919. isset($prop)?
  920. $prop:
  921. $frac?strlen($frac)-2:0,
  922. $decimal_point,$thousands_sep);
  923. case 'date':
  924. $prop='%d %B %Y';
  925. if (empty($mod) || $mod=='short')
  926. $prop='%x';
  927. elseif ($mod=='full')
  928. $prop='%A, '.$prop;
  929. return strftime($prop,$args[$pos]);
  930. case 'time':
  931. $prop='%r';
  932. if (empty($mod) || $mod=='short')
  933. $prop='%X';
  934. return strftime($prop,$args[$pos]);
  935. default:
  936. return $expr[0];
  937. }
  938. }
  939. return $args[$pos];
  940. },
  941. $val
  942. );
  943. }
  944. /**
  945. * Return string representation of expression
  946. * @return string
  947. * @param $expr mixed
  948. **/
  949. function export($expr) {
  950. return var_export($expr,TRUE);
  951. }
  952. /**
  953. * Assign/auto-detect language
  954. * @return string
  955. * @param $code string
  956. **/
  957. function language($code) {
  958. $code=preg_replace('/\h+|;q=[0-9.]+/','',$code);
  959. $code.=($code?',':'').$this->fallback;
  960. $this->languages=[];
  961. foreach (array_reverse(explode(',',$code)) as $lang)
  962. if (preg_match('/^(\w{2})(?:-(\w{2}))?\b/i',$lang,$parts)) {
  963. // Generic language
  964. array_unshift($this->languages,$parts[1]);
  965. if (isset($parts[2])) {
  966. // Specific language
  967. $parts[0]=$parts[1].'-'.($parts[2]=strtoupper($parts[2]));
  968. array_unshift($this->languages,$parts[0]);
  969. }
  970. }
  971. $this->languages=array_unique($this->languages);
  972. $locales=[];
  973. $windows=preg_match('/^win/i',PHP_OS);
  974. // Work around PHP's Turkish locale bug
  975. foreach (preg_grep('/^(?!tr)/i',$this->languages) as $locale) {
  976. if ($windows) {
  977. $parts=explode('-',$locale);
  978. $locale=@constant('ISO::LC_'.$parts[0]);
  979. if (isset($parts[1]) &&
  980. $country=@constant('ISO::CC_'.strtolower($parts[1])))
  981. $locale.='-'.$country;
  982. }
  983. $locale=str_replace('-','_',$locale);
  984. $locales[]=$locale.'.'.ini_get('default_charset');
  985. $locales[]=$locale;
  986. }
  987. setlocale(LC_ALL,$locales);
  988. return $this->hive['LANGUAGE']=implode(',',$this->languages);
  989. }
  990. /**
  991. * Return lexicon entries
  992. * @return array
  993. * @param $path string
  994. * @param $ttl int
  995. **/
  996. function lexicon($path,$ttl=0) {
  997. $languages=$this->languages?:explode(',',$this->fallback);
  998. $cache=Cache::instance();
  999. if ($cache->exists(
  1000. $hash=$this->hash(implode(',',$languages)).'.dic',$lex))
  1001. return $lex;
  1002. $lex=[];
  1003. foreach ($languages as $lang)
  1004. foreach ($this->split($path) as $dir)
  1005. if ((is_file($file=($base=$dir.$lang).'.php') ||
  1006. is_file($file=$base.'.php')) &&
  1007. is_array($dict=require($file)))
  1008. $lex+=$dict;
  1009. elseif (is_file($file=$base.'.ini')) {
  1010. preg_match_all(
  1011. '/(?<=^|\n)(?:'.
  1012. '\[(?<prefix>.+?)\]|'.
  1013. '(?<lval>[^\h\r\n;].*?)\h*=\h*'.
  1014. '(?<rval>(?:\\\\\h*\r?\n|.+?)*)'.
  1015. ')(?=\r?\n|$)/',
  1016. $this->read($file),$matches,PREG_SET_ORDER);
  1017. if ($matches) {
  1018. $prefix='';
  1019. foreach ($matches as $match)
  1020. if ($match['prefix'])
  1021. $prefix=$match['prefix'].'.';
  1022. elseif (!array_key_exists(
  1023. $key=$prefix.$match['lval'],$lex))
  1024. $lex[$key]=trim(preg_replace(
  1025. '/\\\\\h*\r?\n/',"\n",$match['rval']));
  1026. }
  1027. }
  1028. if ($ttl)
  1029. $cache->set($hash,$lex,$ttl);
  1030. return $lex;
  1031. }
  1032. /**
  1033. * Return string representation of PHP value
  1034. * @return string
  1035. * @param $arg mixed
  1036. **/
  1037. function serialize($arg) {
  1038. switch (strtolower($this->hive['SERIALIZER'])) {
  1039. case 'igbinary':
  1040. return igbinary_serialize($arg);
  1041. default:
  1042. return serialize($arg);
  1043. }
  1044. }
  1045. /**
  1046. * Return PHP value derived from string
  1047. * @return string
  1048. * @param $arg mixed
  1049. **/
  1050. function unserialize($arg) {
  1051. switch (strtolower($this->hive['SERIALIZER'])) {
  1052. case 'igbinary':
  1053. return igbinary_unserialize($arg);
  1054. default:
  1055. return unserialize($arg);
  1056. }
  1057. }
  1058. /**
  1059. * Send HTTP status header; Return text equivalent of status code
  1060. * @return string
  1061. * @param $code int
  1062. **/
  1063. function status($code) {
  1064. $reason=@constant('self::HTTP_'.$code);
  1065. if (!$this->hive['CLI'] && !headers_sent())
  1066. header($_SERVER['SERVER_PROTOCOL'].' '.$code.' '.$reason);
  1067. return $reason;
  1068. }
  1069. /**
  1070. * Send cache metadata to HTTP client
  1071. * @return NULL
  1072. * @param $secs int
  1073. **/
  1074. function expire($secs=0) {
  1075. if (!$this->hive['CLI'] && !headers_sent()) {
  1076. $secs=(int)$secs;
  1077. if ($this->hive['PACKAGE'])
  1078. header('X-Powered-By: '.$this->hive['PACKAGE']);
  1079. if ($this->hive['XFRAME'])
  1080. header('X-Frame-Options: '.$this->hive['XFRAME']);
  1081. header('X-XSS-Protection: 1; mode=block');
  1082. header('X-Content-Type-Options: nosniff');
  1083. if ($this->hive['VERB']=='GET' && $secs) {
  1084. $time=microtime(TRUE);
  1085. header_remove('Pragma');
  1086. header('Cache-Control: max-age='.$secs);
  1087. header('Expires: '.gmdate('r',$time+$secs));
  1088. header('Last-Modified: '.gmdate('r'));
  1089. }
  1090. else {
  1091. header('Pragma: no-cache');
  1092. header('Cache-Control: no-cache, no-store, must-revalidate');
  1093. header('Expires: '.gmdate('r',0));
  1094. }
  1095. }
  1096. }
  1097. /**
  1098. * Return HTTP user agent
  1099. * @return string
  1100. **/
  1101. function agent() {
  1102. $headers=$this->hive['HEADERS'];
  1103. return isset($headers['X-Operamini-Phone-UA'])?
  1104. $headers['X-Operamini-Phone-UA']:
  1105. (isset($headers['X-Skyfire-Phone'])?
  1106. $headers['X-Skyfire-Phone']:
  1107. (isset($headers['User-Agent'])?
  1108. $headers['User-Agent']:''));
  1109. }
  1110. /**
  1111. * Return TRUE if XMLHttpRequest detected
  1112. * @return bool
  1113. **/
  1114. function ajax() {
  1115. $headers=$this->hive['HEADERS'];
  1116. return isset($headers['X-Requested-With']) &&
  1117. $headers['X-Requested-With']=='XMLHttpRequest';
  1118. }
  1119. /**
  1120. * Sniff IP address
  1121. * @return string
  1122. **/
  1123. function ip() {
  1124. $headers=$this->hive['HEADERS'];
  1125. return isset($headers['Client-IP'])?
  1126. $headers['Client-IP']:
  1127. (isset($headers['X-Forwarded-For'])?
  1128. explode(',',$headers['X-Forwarded-For'])[0]:
  1129. (isset($_SERVER['REMOTE_ADDR'])?
  1130. $_SERVER['REMOTE_ADDR']:''));
  1131. }
  1132. /**
  1133. * Return filtered stack trace as a formatted string (or array)
  1134. * @return string|array
  1135. * @param $trace array|NULL
  1136. * @param $format bool
  1137. **/
  1138. function trace(array $trace=NULL,$format=TRUE) {
  1139. if (!$trace) {
  1140. $trace=debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
  1141. $frame=$trace[0];
  1142. if (isset($frame['file']) && $frame['file']==__FILE__)
  1143. array_shift($trace);
  1144. }
  1145. $debug=$this->hive['DEBUG'];
  1146. $trace=array_filter(
  1147. $trace,
  1148. function($frame) use($debug) {
  1149. return isset($frame['file']) &&
  1150. ($debug>1 ||
  1151. ($frame['file']!=__FILE__ || $debug) &&
  1152. (empty($frame['function']) ||
  1153. !preg_match('/^(?:(?:trigger|user)_error|'.
  1154. '__call|call_user_func)/',$frame['function'])));
  1155. }
  1156. );
  1157. if (!$format)
  1158. return $trace;
  1159. $out='';
  1160. $eol="\n";
  1161. // Analyze stack trace
  1162. foreach ($trace as $frame) {
  1163. $line='';
  1164. if (isset($frame['class']))
  1165. $line.=$frame['class'].$frame['type'];
  1166. if (isset($frame['function']))
  1167. $line.=$frame['function'].'('.
  1168. ($debug>2 && isset($frame['args'])?
  1169. $this->csv($frame['args']):'').')';
  1170. $src=$this->fixslashes(str_replace($_SERVER['DOCUMENT_ROOT'].
  1171. '/','',$frame['file'])).':'.$frame['line'];
  1172. $out.='['.$src.'] '.$line.$eol;
  1173. }
  1174. return $out;
  1175. }
  1176. /**
  1177. * Log error; Execute ONERROR handler if defined, else display
  1178. * default error page (HTML for synchronous requests, JSON string
  1179. * for AJAX requests)
  1180. * @return NULL
  1181. * @param $code int
  1182. * @param $text string
  1183. * @param $trace array
  1184. * @param $level int
  1185. **/
  1186. function error($code,$text='',array $trace=NULL,$level=0) {
  1187. $prior=$this->hive['ERROR'];
  1188. $header=$this->status($code);
  1189. $req=$this->hive['VERB'].' '.$this->hive['PATH'];
  1190. if ($this->hive['QUERY'])
  1191. $req.='?'.$this->hive['QUERY'];
  1192. if (!$text)
  1193. $text='HTTP '.$code.' ('.$req.')';
  1194. $trace=$this->trace($trace);
  1195. $loggable=$this->hive['LOGGABLE'];
  1196. if (!is_array($loggable))
  1197. $loggable=$this->split($loggable);
  1198. foreach ($loggable as $status)
  1199. if ($status=='*' ||
  1200. preg_match('/^'.preg_replace('/\D/','\d',$status).'$/',$code)) {
  1201. error_log($text);
  1202. foreach (explode("\n",$trace) as $nexus)
  1203. if ($nexus)
  1204. error_log($nexus);
  1205. break;
  1206. }
  1207. if ($highlight=!$this->hive['CLI'] && !$this->hive['AJAX'] &&
  1208. $this->hive['HIGHLIGHT'] && is_file($css=__DIR__.'/'.self::CSS))
  1209. $trace=$this->highlight($trace);
  1210. $this->hive['ERROR']=[
  1211. 'status'=>$header,
  1212. 'code'=>$code,
  1213. 'text'=>$text,
  1214. 'trace'=>$trace,
  1215. 'level'=>$level
  1216. ];
  1217. $this->expire(-1);
  1218. $handler=$this->hive['ONERROR'];
  1219. $this->hive['ONERROR']=NULL;
  1220. $eol="\n";
  1221. if ((!$handler ||
  1222. $this->call($handler,[$this,$this->hive['PARAMS']],
  1223. 'beforeroute,afterroute')===FALSE) &&
  1224. !$prior && !$this->hive['CLI'] && !$this->hive['QUIET'])
  1225. echo $this->hive['AJAX']?
  1226. json_encode(
  1227. array_diff_key(
  1228. $this->hive['ERROR'],
  1229. $this->hive['DEBUG']?
  1230. []:
  1231. ['trace'=>1]
  1232. )
  1233. ):
  1234. ('<!DOCTYPE html>'.$eol.
  1235. '<html>'.$eol.
  1236. '<head>'.
  1237. '<title>'.$code.' '.$header.'</title>'.
  1238. ($highlight?
  1239. ('<style>'.$this->read($css).'</style>'):'').
  1240. '</head>'.$eol.
  1241. '<body>'.$eol.
  1242. '<h1>'.$header.'</h1>'.$eol.
  1243. '<p>'.$this->encode($text?:$req).'</p>'.$eol.
  1244. ($this->hive['DEBUG']?('<pre>'.$trace.'</pre>'.$eol):'').
  1245. '</body>'.$eol.
  1246. '</html>');
  1247. if ($this->hive['HALT'])
  1248. die(1);
  1249. }
  1250. /**
  1251. * Mock HTTP request
  1252. * @return mixed
  1253. * @param $pattern string
  1254. * @param $args array
  1255. * @param $headers array
  1256. * @param $body string
  1257. **/
  1258. function mock($pattern,
  1259. array $args=NULL,array $headers=NULL,$body=NULL) {
  1260. if (!$args)
  1261. $args=[];
  1262. $types=['sync','ajax','cli'];
  1263. preg_match('/([\|\w]+)\h+(?:@(\w+)(?:(\(.+?)\))*|([^\h]+))'.
  1264. '(?:\h+\[('.implode('|',$types).')\])?/',$pattern,$parts);
  1265. $verb=strtoupper($parts[1]);
  1266. if ($parts[2]) {
  1267. if (empty($this->hive['ALIASES'][$parts[2]]))
  1268. user_error(sprintf(self::E_Named,$parts[2]),E_USER_ERROR);
  1269. $parts[4]=$this->hive['ALIASES'][$parts[2]];
  1270. $parts[4]=$this->build($parts[4],
  1271. isset($parts[3])?$this->parse($parts[3]):[]);
  1272. }
  1273. if (empty($parts[4]))
  1274. user_error(sprintf(self::E_Pattern,$pattern),E_USER_ERROR);
  1275. $url=parse_url($parts[4]);
  1276. parse_str(@$url['query'],$GLOBALS['_GET']);
  1277. if (preg_match('/GET|HEAD/',$verb))
  1278. $GLOBALS['_GET']=array_merge($GLOBALS['_GET'],$args);
  1279. $GLOBALS['_POST']=$verb=='POST'?$args:[];
  1280. $GLOBALS['_REQUEST']=array_merge($GLOBALS['_GET'],$GLOBALS['_POST']);
  1281. foreach ($headers?:[] as $key=>$val)
  1282. $_SERVER['HTTP_'.strtr(strtoupper($key),'-','_')]=$val;
  1283. $this->hive['VERB']=$verb;
  1284. $this->hive['PATH']=$url['path'];
  1285. $this->hive['URI']=$this->hive['BASE'].$url['path'];
  1286. if ($GLOBALS['_GET'])
  1287. $this->hive['URI'].='?'.http_build_query($GLOBALS['_GET']);
  1288. $this->hive['BODY']='';
  1289. if (!preg_match('/GET|HEAD/',$verb))
  1290. $this->hive['BODY']=$body?:http_build_query($args);
  1291. $this->hive['AJAX']=isset($parts[5]) &&
  1292. preg_match('/ajax/i',$parts[5]);
  1293. $this->hive['CLI']=isset($parts[5]) &&
  1294. preg_match('/cli/i',$parts[5]);
  1295. return $this->run();
  1296. }
  1297. /**
  1298. * Assemble url from alias name
  1299. * @return string
  1300. * @param $name string
  1301. * @param $params array|string
  1302. * @param $query string|array
  1303. **/
  1304. function alias($name,$params=[],$query=NULL) {
  1305. if (!is_array($params))
  1306. $params=$this->parse($params);
  1307. if (empty($this->hive['ALIASES'][$name]))
  1308. user_error(sprintf(self::E_Named,$name),E_USER_ERROR);
  1309. $url=$this->build($this->hive['ALIASES'][$name],$params);
  1310. if (is_array($query))
  1311. $query=http_build_query($query);
  1312. return $url.($query?('?'.$query):'');
  1313. }
  1314. /**
  1315. * Bind handler to route pattern
  1316. * @return NULL
  1317. * @param $pattern string|array
  1318. * @param $handler callback
  1319. * @param $ttl int
  1320. * @param $kbps int
  1321. **/
  1322. function route($pattern,$handler,$ttl=0,$kbps=0) {
  1323. $types=['sync','ajax','cli'];
  1324. $alias=null;
  1325. if (is_array($pattern)) {
  1326. foreach ($pattern as $item)
  1327. $this->route($item,$handler,$ttl,$kbps);
  1328. return;
  1329. }
  1330. preg_match('/([\|\w]+)\h+(?:(?:@?(.+?)\h*:\h*)?(@(\w+)|[^\h]+))'.
  1331. '(?:\h+\[('.implode('|',$types).')\])?/u',$pattern,$parts);
  1332. if (isset($parts[2]) && $parts[2])
  1333. $this->hive['ALIASES'][$alias=$parts[2]]=$parts[3];
  1334. elseif (!empty($parts[4])) {
  1335. if (empty($this->hive['ALIASES'][$parts[4]]))
  1336. user_error(sprintf(self::E_Named,$parts[4]),E_USER_ERROR);
  1337. $parts[3]=$this->hive['ALIASES'][$alias=$parts[4]];
  1338. }
  1339. if (empty($parts[3]))
  1340. user_error(sprintf(self::E_Pattern,$pattern),E_USER_ERROR);
  1341. $type=empty($parts[5])?0:constant('self::REQ_'.strtoupper($parts[5]));
  1342. foreach ($this->split($parts[1]) as $verb) {
  1343. if (!preg_match('/'.self::VERBS.'/',$verb))
  1344. $this->error(501,$verb.' '.$this->hive['URI']);
  1345. $this->hive['ROUTES'][$parts[3]][$type][strtoupper($verb)]=
  1346. [$handler,$ttl,$kbps,$alias];
  1347. }
  1348. }
  1349. /**
  1350. * Reroute to specified URI
  1351. * @return NULL
  1352. * @param $url array|string
  1353. * @param $permanent bool
  1354. * @param $die bool
  1355. **/
  1356. function reroute($url=NULL,$permanent=FALSE,$die=TRUE) {
  1357. if (!$url)
  1358. $url=$this->hive['REALM'];
  1359. if (is_array($url))
  1360. $url=call_user_func_array([$this,'alias'],$url);
  1361. elseif (preg_match('/^(?:@?([^\/()?]+)(?:(\(.+?)\))*(\?.+)*)/',
  1362. $url,$parts) &&
  1363. isset($this->hive['ALIASES'][$parts[1]]))
  1364. $url=$this->hive['ALIASES'][$parts[1]];
  1365. $url=$this->build($url,isset($parts[2])?$this->parse($parts[2]):[]).
  1366. (isset($parts[3])?$parts[3]:'');
  1367. if (($handler=$this->hive['ONREROUTE']) &&
  1368. $this->call($handler,[$url,$permanent])!==FALSE)
  1369. return;
  1370. if ($url[0]=='/' && (empty($url[1]) || $url[1]!='/')) {
  1371. $port=$this->hive['PORT'];
  1372. $port=in_array($port,[80,443])?'':(':'.$port);
  1373. $url=$this->hive['SCHEME'].'://'.
  1374. $this->hive['HOST'].$port.$this->hive['BASE'].$url;
  1375. }
  1376. if ($this->hive['CLI'])
  1377. $this->mock('GET '.$url.' [cli]');
  1378. else {
  1379. header('Location: '.$url);
  1380. $this->status($permanent?301:302);
  1381. if ($die)
  1382. die;
  1383. }
  1384. }
  1385. /**
  1386. * Provide ReST interface by mapping HTTP verb to class method
  1387. * @return NULL
  1388. * @param $url string
  1389. * @param $class string|object
  1390. * @param $ttl int
  1391. * @param $kbps int
  1392. **/
  1393. function map($url,$class,$ttl=0,$kbps=0) {
  1394. if (is_array($url)) {
  1395. foreach ($url as $item)
  1396. $this->map($item,$class,$ttl,$kbps);
  1397. return;
  1398. }
  1399. foreach (explode('|',self::VERBS) as $method)
  1400. $this->route($method.' '.$url,is_string($class)?
  1401. $class.'->'.$this->hive['PREMAP'].strtolower($method):
  1402. [$class,$this->hive['PREMAP'].strtolower($method)],
  1403. $ttl,$kbps);
  1404. }
  1405. /**
  1406. * Redirect a route to another URL
  1407. * @return NULL
  1408. * @param $pattern string|array
  1409. * @param $url string
  1410. * @param $permanent bool
  1411. */
  1412. function redirect($pattern,$url,$permanent=TRUE) {
  1413. if (is_array($pattern)) {
  1414. foreach ($pattern as $item)
  1415. $this->redirect($item,$url,$permanent);
  1416. return;
  1417. }
  1418. $this->route($pattern,function($fw) use($url,$permanent) {
  1419. $fw->reroute($url,$permanent);
  1420. });
  1421. }
  1422. /**
  1423. * Return TRUE if IPv4 address exists in DNSBL
  1424. * @return bool
  1425. * @param $ip string
  1426. **/
  1427. function blacklisted($ip) {
  1428. if ($this->hive['DNSBL'] &&
  1429. !in_array($ip,
  1430. is_array($this->hive['EXEMPT'])?
  1431. $this->hive['EXEMPT']:
  1432. $this->split($this->hive['EXEMPT']))) {
  1433. // Reverse IPv4 dotted quad
  1434. $rev=implode('.',array_reverse(explode('.',$ip)));
  1435. foreach (is_array($this->hive['DNSBL'])?
  1436. $this->hive['DNSBL']:
  1437. $this->split($this->hive['DNSBL']) as $server)
  1438. // DNSBL lookup
  1439. if (checkdnsrr($rev.'.'.$server,'A'))
  1440. return TRUE;
  1441. }
  1442. return FALSE;
  1443. }
  1444. /**
  1445. * Applies the specified URL mask and returns parameterized matches
  1446. * @return $args array
  1447. * @param $pattern string
  1448. * @param $url string|NULL
  1449. **/
  1450. function mask($pattern,$url=NULL) {
  1451. if (!$url)
  1452. $url=$this->rel($this->hive['URI']);
  1453. $case=$this->hive['CASELESS']?'i':'';
  1454. $wild=preg_quote($pattern,'/');
  1455. $i=0;
  1456. while (is_int($pos=strpos($wild,'\*'))) {
  1457. $wild=substr_replace($wild,'(?P<_'.$i.'>[^\?]*)',$pos,2);
  1458. $i++;
  1459. }
  1460. preg_match('/^'.
  1461. preg_replace(
  1462. '/((\\\{)?@(\w+\b)(?(2)\\\}))/',
  1463. '(?P<\3>[^\/\?]+)',
  1464. $wild).'\/?$/'.$case.'um',$url,$args);
  1465. foreach (array_keys($args) as $key) {
  1466. if (preg_match('/^_\d+$/',$key)) {
  1467. if (empty($args['*']))
  1468. $args['*']=$args[$key];
  1469. else {
  1470. if (is_string($args['*']))
  1471. $args['*']=[$args['*']];
  1472. array_push($args['*'],$args[$key]);
  1473. }
  1474. unset($args[$key]);
  1475. }
  1476. elseif (is_numeric($key) && $key)
  1477. unset($args[$key]);
  1478. }
  1479. return $args;
  1480. }
  1481. /**
  1482. * Match routes against incoming URI
  1483. * @return mixed
  1484. **/
  1485. function run() {
  1486. if ($this->blacklisted($this->hive['IP']))
  1487. // Spammer detected
  1488. $this->error(403);
  1489. if (!$this->hive['ROUTES'])
  1490. // No routes defined
  1491. user_error(self::E_Routes,E_USER_ERROR);
  1492. // Match specific routes first
  1493. $paths=[];
  1494. foreach ($keys=array_keys($this->hive['ROUTES']) as $key) {
  1495. $path=preg_replace('/@\w+/','*@',$key);
  1496. if (substr($path,-1)!='*')
  1497. $path.='+';
  1498. $paths[]=$path;
  1499. }
  1500. $vals=array_values($this->hive['ROUTES']);
  1501. array_multisort($paths,SORT_DESC,$keys,$vals);
  1502. $this->hive['ROUTES']=array_combine($keys,$vals);
  1503. // Convert to BASE-relative URL
  1504. $req=urldecode($this->hive['PATH']);
  1505. $preflight=FALSE;
  1506. if ($cors=(isset($this->hive['HEADERS']['Origin']) &&
  1507. $this->hive['CORS']['origin'])) {
  1508. $cors=$this->hive['CORS'];
  1509. header('Access-Control-Allow-Origin: '.$cors['origin']);
  1510. header('Access-Control-Allow-Credentials: '.
  1511. $this->export($cors['credentials']));
  1512. $preflight=
  1513. isset($this->hive['HEADERS']['Access-Control-Request-Method']);
  1514. }
  1515. $allowed=[];
  1516. foreach ($this->hive['ROUTES'] as $pattern=>$routes) {
  1517. if (!$args=$this->mask($pattern,$req))
  1518. continue;
  1519. ksort($args);
  1520. $route=NULL;
  1521. $ptr=$this->hive['CLI']?self::REQ_CLI:$this->hive['AJAX']+1;
  1522. if (isset($routes[$ptr][$this->hive['VERB']]) ||
  1523. isset($routes[$ptr=0]))
  1524. $route=$routes[$ptr];
  1525. if (!$route)
  1526. continue;
  1527. if (isset($route[$this->hive['VERB']]) && !$preflight) {
  1528. if ($this->hive['VERB']=='GET' &&
  1529. preg_match('/.+\/$/',$this->hive['PATH']))
  1530. $this->reroute(substr($this->hive['PATH'],0,-1).
  1531. ($this->hive['QUERY']?('?'.$this->hive['QUERY']):''));
  1532. list($handler,$ttl,$kbps,$alias)=$route[$this->hive['VERB']];
  1533. // Capture values of route pattern tokens
  1534. $this->hive['PARAMS']=$args;
  1535. // Save matching route
  1536. $this->hive['ALIAS']=$alias;
  1537. $this->hive['PATTERN']=$pattern;
  1538. if ($cors && $cors['expose'])
  1539. header('Access-Control-Expose-Headers: '.
  1540. (is_array($cors['expose'])?
  1541. implode(',',$cors['expose']):$cors['expose']));
  1542. if (is_string($handler)) {
  1543. // Replace route pattern tokens in handler if any
  1544. $handler=preg_replace_callback('/({)?@(\w+\b)(?(1)})/',
  1545. function($id) use($args) {
  1546. $pid=count($id)>2?2:1;
  1547. return isset($args[$id[$pid]])?
  1548. $args[$id[$pid]]:
  1549. $id[0];
  1550. },
  1551. $handler
  1552. );
  1553. if (preg_match('/(.+)\h*(?:->|::)/',$handler,$match) &&
  1554. !class_exists($match[1]))
  1555. $this->error(404);
  1556. }
  1557. // Process request
  1558. $result=NULL;
  1559. $body='';
  1560. $now=microtime(TRUE);
  1561. if (preg_match('/GET|HEAD/',$this->hive['VERB']) && $ttl) {
  1562. // Only GET and HEAD requests are cacheable
  1563. $headers=$this->hive['HEADERS'];
  1564. $cache=Cache::instance();
  1565. $cached=$cache->exists(
  1566. $hash=$this->hash($this->hive['VERB'].' '.
  1567. $this->hive['URI']).'.url',$data);
  1568. if ($cached) {
  1569. if (isset($headers['If-Modified-Since']) &&
  1570. strtotime($headers['If-Modified-Since'])+
  1571. $ttl>$now) {
  1572. $this->status(304);
  1573. die;
  1574. }
  1575. // Retrieve from cache backend
  1576. list($headers,$body,$result)=$data;
  1577. if (!$this->hive['CLI'])
  1578. array_walk($headers,'header');
  1579. $this->expire($cached[0]+$ttl-$now);
  1580. }
  1581. else
  1582. // Expire HTTP client-cached page
  1583. $this->expire($ttl);
  1584. }
  1585. else
  1586. $this->expire(0);
  1587. if (!strlen($body)) {
  1588. if (!$this->hive['RAW'] && !$this->hive['BODY'])
  1589. $this->hive['BODY']=file_get_contents('php://input');
  1590. ob_start();
  1591. // Call route handler
  1592. $result=$this->call($handler,[$this,$args,$handler],
  1593. 'beforeroute,afterroute');
  1594. $body=ob_get_clean();
  1595. if (isset($cache) && !error_get_last()) {
  1596. // Save to cache backend
  1597. $cache->set($hash,[
  1598. // Remove cookies
  1599. preg_grep('/Set-Cookie\:/',headers_list(),
  1600. PREG_GREP_INVERT),$body,$result],$ttl);
  1601. }
  1602. }
  1603. $this->hive['RESPONSE']=$body;
  1604. if (!$this->hive['QUIET']) {
  1605. if ($kbps) {
  1606. $ctr=0;
  1607. foreach (str_split($body,1024) as $part) {
  1608. // Throttle output
  1609. $ctr++;
  1610. if ($ctr/$kbps>($elapsed=microtime(TRUE)-$now) &&
  1611. !connection_aborted())
  1612. usleep(1e6*($ctr/$kbps-$elapsed));
  1613. echo $part;
  1614. }
  1615. }
  1616. else
  1617. echo $body;
  1618. }
  1619. if ($result || $this->hive['VERB']!='OPTIONS')
  1620. return $result;
  1621. }
  1622. $allowed=array_merge($allowed,array_keys($route));
  1623. }
  1624. if (!$allowed)
  1625. // URL doesn't match any route
  1626. $this->error(404);
  1627. elseif (!$this->hive['CLI']) {
  1628. if (!preg_grep('/Allow:/',$headers_send=headers_list()))
  1629. // Unhandled HTTP method
  1630. header('Allow: '.implode(',',array_unique($allowed)));
  1631. if ($cors) {
  1632. if (!preg_grep('/Access-Control-Allow-Methods:/',$headers_send))
  1633. header('Access-Control-Allow-Methods: OPTIONS,'.
  1634. implode(',',$allowed));
  1635. if ($cors['headers'] &&
  1636. !preg_grep('/Access-Control-Allow-Headers:/',$headers_send))
  1637. header('Access-Control-Allow-Headers: '.
  1638. (is_array($cors['headers'])?
  1639. implode(',',$cors['headers']):
  1640. $cors['headers']));
  1641. if ($cors['ttl']>0)
  1642. header('Access-Control-Max-Age: '.$cors['ttl']);
  1643. }
  1644. if ($this->hive['VERB']!='OPTIONS')
  1645. $this->error(405);
  1646. }
  1647. return FALSE;
  1648. }
  1649. /**
  1650. * Loop until callback returns TRUE (for long polling)
  1651. * @return mixed
  1652. * @param $func callback
  1653. * @param $args array
  1654. * @param $timeout int
  1655. **/
  1656. function until($func,$args=NULL,$timeout=60) {
  1657. if (!$args)
  1658. $args=[];
  1659. $time=time();
  1660. $max=ini_get('max_execution_time');
  1661. $limit=max(0,($max?min($timeout,$max):$timeout)-1);
  1662. $out='';
  1663. // Turn output buffering on
  1664. ob_start();
  1665. // Not for the weak of heart
  1666. while (
  1667. // No error occurred
  1668. !$this->hive['ERROR'] &&
  1669. // Got time left?
  1670. time()-$time+1<$limit &&
  1671. // Still alive?
  1672. !connection_aborted() &&
  1673. // Restart session
  1674. !headers_sent() &&
  1675. (session_status()==PHP_SESSION_ACTIVE || session_start()) &&
  1676. // CAUTION: Callback will kill host if it never becomes truthy!
  1677. !$out=$this->call($func,$args)) {
  1678. if (!$this->hive['CLI'])
  1679. session_commit();
  1680. // Hush down
  1681. sleep(1);
  1682. }
  1683. ob_flush();
  1684. flush();
  1685. return $out;
  1686. }
  1687. /**
  1688. * Disconnect HTTP client;
  1689. * Set FcgidOutputBufferSize to zero if server uses mod_fcgid;
  1690. * Disable mod_deflate when rendering text/html output
  1691. **/
  1692. function abort() {
  1693. if (!headers_sent() && session_status()!=PHP_SESSION_ACTIVE)
  1694. session_start();
  1695. $out='';
  1696. while (ob_get_level())
  1697. $out=ob_get_clean().$out;
  1698. if (!headers_sent()) {
  1699. header('Content-Length: '.strlen($out));
  1700. header('Connection: close');
  1701. }
  1702. session_commit();
  1703. echo $out;
  1704. flush();
  1705. if (function_exists('fastcgi_finish_request'))
  1706. fastcgi_finish_request();
  1707. }
  1708. /**
  1709. * Grab the real route handler behind the string expression
  1710. * @return string|array
  1711. * @param $func string
  1712. * @param $args array
  1713. **/
  1714. function grab($func,$args=NULL) {
  1715. if (preg_match('/(.+)\h*(->|::)\h*(.+)/s',$func,$parts)) {
  1716. // Convert string to executable PHP callback
  1717. if (!class_exists($parts[1]))
  1718. user_error(sprintf(self::E_Class,$parts[1]),E_USER_ERROR);
  1719. if ($parts[2]=='->') {
  1720. if (is_subclass_of($parts[1],'Prefab'))
  1721. $parts[1]=call_user_func($parts[1].'::instance');
  1722. elseif ($container=$this->get('CONTAINER')) {
  1723. if (is_object($container) && is_callable([$container,'has'])
  1724. && $container->has($parts[1])) // PSR11
  1725. $parts[1]=call_user_func([$container,'get'],$parts[1]);
  1726. elseif (is_callable($container))
  1727. $parts[1]=call_user_func($container,$parts[1],$args);
  1728. elseif (is_string($container) &&
  1729. is_subclass_of($container,'Prefab'))
  1730. $parts[1]=call_user_func($container.'::instance')->
  1731. get($parts[1]);
  1732. else
  1733. user_error(sprintf(self::E_Class,
  1734. $this->stringify($parts[1])),
  1735. E_USER_ERROR);
  1736. }
  1737. else {
  1738. $ref=new ReflectionClass($parts[1]);
  1739. $parts[1]=method_exists($parts[1],'__construct') && $args?
  1740. $ref->newinstanceargs($args):
  1741. $ref->newinstance();
  1742. }
  1743. }
  1744. $func=[$parts[1],$parts[3]];
  1745. }
  1746. return $func;
  1747. }
  1748. /**
  1749. * Execute callback/hooks (supports 'class->method' format)
  1750. * @return mixed|FALSE
  1751. * @param $func callback
  1752. * @param $args mixed
  1753. * @param $hooks string
  1754. **/
  1755. function call($func,$args=NULL,$hooks='') {
  1756. if (!is_array($args))
  1757. $args=[$args];
  1758. // Grab the real handler behind the string representation
  1759. if (is_string($func))
  1760. $func=$this->grab($func,$args);
  1761. // Execute function; abort if callback/hook returns FALSE
  1762. if (!is_callable($func))
  1763. // No route handler
  1764. if ($hooks=='beforeroute,afterroute') {
  1765. $allowed=[];
  1766. if (is_array($func))
  1767. $allowed=array_intersect(
  1768. array_map('strtoupper',get_class_methods($func[0])),
  1769. explode('|',self::VERBS)
  1770. );
  1771. header('Allow: '.implode(',',$allowed));
  1772. $this->error(405);
  1773. }
  1774. else
  1775. user_error(sprintf(self::E_Method,
  1776. is_string($func)?$func:$this->stringify($func)),
  1777. E_USER_ERROR);
  1778. $obj=FALSE;
  1779. if (is_array($func)) {
  1780. $hooks=$this->split($hooks);
  1781. $obj=TRUE;
  1782. }
  1783. // Execute pre-route hook if any
  1784. if ($obj && $hooks && in_array($hook='beforeroute',$hooks) &&
  1785. method_exists($func[0],$hook) &&
  1786. call_user_func_array([$func[0],$hook],$args)===FALSE)
  1787. return FALSE;
  1788. // Execute callback
  1789. $out=call_user_func_array($func,$args?:[]);
  1790. if ($out===FALSE)
  1791. return FALSE;
  1792. // Execute post-route hook if any
  1793. if ($obj && $hooks && in_array($hook='afterroute',$hooks) &&
  1794. method_exists($func[0],$hook) &&
  1795. call_user_func_array([$func[0],$hook],$args)===FALSE)
  1796. return FALSE;
  1797. return $out;
  1798. }
  1799. /**
  1800. * Execute specified callbacks in succession; Apply same arguments
  1801. * to all callbacks
  1802. * @return array
  1803. * @param $funcs array|string
  1804. * @param $args mixed
  1805. **/
  1806. function chain($funcs,$args=NULL) {
  1807. $out=[];
  1808. foreach (is_array($funcs)?$funcs:$this->split($funcs) as $func)
  1809. $out[]=$this->call($func,$args);
  1810. return $out;
  1811. }
  1812. /**
  1813. * Execute specified callbacks in succession; Relay result of
  1814. * previous callback as argument to the next callback
  1815. * @return array
  1816. * @param $funcs array|string
  1817. * @param $args mixed
  1818. **/
  1819. function relay($funcs,$args=NULL) {
  1820. foreach (is_array($funcs)?$funcs:$this->split($funcs) as $func)
  1821. $args=[$this->call($func,$args)];
  1822. return array_shift($args);
  1823. }
  1824. /**
  1825. * Configure framework according to .ini-style file settings;
  1826. * If optional 2nd arg is provided, template strings are interpreted
  1827. * @return object
  1828. * @param $source string|array
  1829. * @param $allow bool
  1830. **/
  1831. function config($source,$allow=FALSE) {
  1832. if (is_string($source))
  1833. $source=$this->split($source);
  1834. if ($allow)
  1835. $preview=Preview::instance();
  1836. foreach ($source as $file) {
  1837. preg_match_all(
  1838. '/(?<=^|\n)(?:'.
  1839. '\[(?<section>.+?)\]|'.
  1840. '(?<lval>[^\h\r\n;].*?)\h*=\h*'.
  1841. '(?<rval>(?:\\\\\h*\r?\n|.+?)*)'.
  1842. ')(?=\r?\n|$)/',
  1843. $this->read($file),
  1844. $matches,PREG_SET_ORDER);
  1845. if ($matches) {
  1846. $sec='globals';
  1847. $cmd=[];
  1848. foreach ($matches as $match) {
  1849. if ($match['section']) {
  1850. $sec=$match['section'];
  1851. if (preg_match(
  1852. '/^(?!(?:global|config|route|map|redirect)s\b)'.
  1853. '((?:\.?\w)+)/i',$sec,$msec) &&
  1854. !$this->exists($msec[0]))
  1855. $this->set($msec[0],NULL);
  1856. preg_match('/^(config|route|map|redirect)s\b|'.
  1857. '^((?:\.?\w)+)\s*\>\s*(.*)/i',$sec,$cmd);
  1858. continue;
  1859. }
  1860. if ($allow)
  1861. foreach (['lval','rval'] as $ndx)
  1862. $match[$ndx]=$preview->
  1863. resolve($match[$ndx],NULL,0,FALSE,FALSE);
  1864. if (!empty($cmd)) {
  1865. isset($cmd[3])?
  1866. $this->call($cmd[3],
  1867. [$match['lval'],$match['rval'],$cmd[2]]):
  1868. call_user_func_array(
  1869. [$this,$cmd[1]],
  1870. array_merge([$match['lval']],
  1871. str_getcsv($cmd[1]=='config'?
  1872. $this->cast($match['rval']):
  1873. $match['rval']))
  1874. );
  1875. }
  1876. else {
  1877. $rval=preg_replace(
  1878. '/\\\\\h*(\r?\n)/','\1',$match['rval']);
  1879. $ttl=NULL;
  1880. if (preg_match('/^(.+)\|\h*(\d+)$/',$rval,$tmp)) {
  1881. array_shift($tmp);
  1882. list($rval,$ttl)=$tmp;
  1883. }
  1884. $args=array_map(
  1885. function($val) {
  1886. $val=$this->cast($val);
  1887. if (is_string($val))
  1888. $val=strlen($val)?
  1889. preg_replace('/\\\\"/','"',$val):
  1890. NULL;
  1891. return $val;
  1892. },
  1893. // Mark quoted strings with 0x00 whitespace
  1894. str_getcsv(preg_replace(
  1895. '/(?<!\\\\)(")(.*?)\1/',
  1896. "\\1\x00\\2\\1",trim($rval)))
  1897. );
  1898. preg_match('/^(?<section>[^:]+)(?:\:(?<func>.+))?/',
  1899. $sec,$parts);
  1900. $func=isset($parts['func'])?$parts['func']:NULL;
  1901. $custom=(strtolower($parts['section'])!='globals');
  1902. if ($func)
  1903. $args=[$this->call($func,$args)];
  1904. if (count($args)>1)
  1905. $args=[$args];
  1906. if (isset($ttl))
  1907. $args=array_merge($args,[$ttl]);
  1908. call_user_func_array(
  1909. [$this,'set'],
  1910. array_merge(
  1911. [
  1912. ($custom?($parts['section'].'.'):'').
  1913. $match['lval']
  1914. ],
  1915. $args
  1916. )
  1917. );
  1918. }
  1919. }
  1920. }
  1921. }
  1922. return $this;
  1923. }
  1924. /**
  1925. * Create mutex, invoke callback then drop ownership when done
  1926. * @return mixed
  1927. * @param $id string
  1928. * @param $func callback
  1929. * @param $args mixed
  1930. **/
  1931. function mutex($id,$func,$args=NULL) {
  1932. if (!is_dir($tmp=$this->hive['TEMP']))
  1933. mkdir($tmp,self::MODE,TRUE);
  1934. // Use filesystem lock
  1935. if (is_file($lock=$tmp.
  1936. $this->get('SEED').'.'.$this->hash($id).'.lock') &&
  1937. filemtime($lock)+ini_get('max_execution_time')<microtime(TRUE))
  1938. // Stale lock
  1939. @unlink($lock);
  1940. while (!($handle=@fopen($lock,'x')) && !connection_aborted())
  1941. usleep(mt_rand(0,100));
  1942. $this->locks[$id]=$lock;
  1943. $out=$this->call($func,$args);
  1944. fclose($handle);
  1945. @unlink($lock);
  1946. unset($this->locks[$id]);
  1947. return $out;
  1948. }
  1949. /**
  1950. * Read file (with option to apply Unix LF as standard line ending)
  1951. * @return string
  1952. * @param $file string
  1953. * @param $lf bool
  1954. **/
  1955. function read($file,$lf=FALSE) {
  1956. $out=@file_get_contents($file);
  1957. return $lf?preg_replace('/\r\n|\r/',"\n",$out):$out;
  1958. }
  1959. /**
  1960. * Exclusive file write
  1961. * @return int|FALSE
  1962. * @param $file string
  1963. * @param $data mixed
  1964. * @param $append bool
  1965. **/
  1966. function write($file,$data,$append=FALSE) {
  1967. return file_put_contents($file,$data,LOCK_EX|($append?FILE_APPEND:0));
  1968. }
  1969. /**
  1970. * Apply syntax highlighting
  1971. * @return string
  1972. * @param $text string
  1973. **/
  1974. function highlight($text) {
  1975. $out='';
  1976. $pre=FALSE;
  1977. $text=trim($text);
  1978. if ($text && !preg_match('/^<\?php/',$text)) {
  1979. $text='<?php '.$text;
  1980. $pre=TRUE;
  1981. }
  1982. foreach (token_get_all($text) as $token)
  1983. if ($pre)
  1984. $pre=FALSE;
  1985. else
  1986. $out.='<span'.
  1987. (is_array($token)?
  1988. (' class="'.
  1989. substr(strtolower(token_name($token[0])),2).'">'.
  1990. $this->encode($token[1]).''):
  1991. ('>'.$this->encode($token))).
  1992. '</span>';
  1993. return $out?('<code>'.$out.'</code>'):$text;
  1994. }
  1995. /**
  1996. * Dump expression with syntax highlighting
  1997. * @return NULL
  1998. * @param $expr mixed
  1999. **/
  2000. function dump($expr) {
  2001. echo $this->highlight($this->stringify($expr));
  2002. }
  2003. /**
  2004. * Return path (and query parameters) relative to the base directory
  2005. * @return string
  2006. * @param $url string
  2007. **/
  2008. function rel($url) {
  2009. return preg_replace('/^(?:https?:\/\/)?'.
  2010. preg_quote($this->hive['BASE'],'/').'(\/.*|$)/','\1',$url);
  2011. }
  2012. /**
  2013. * Namespace-aware class autoloader
  2014. * @return mixed
  2015. * @param $class string
  2016. **/
  2017. protected function autoload($class) {
  2018. $class=$this->fixslashes(ltrim($class,'\\'));
  2019. $func=NULL;
  2020. if (is_array($path=$this->hive['AUTOLOAD']) &&
  2021. isset($path[1]) && is_callable($path[1]))
  2022. list($path,$func)=$path;
  2023. foreach ($this->split($this->hive['PLUGINS'].';'.$path) as $auto)
  2024. if ($func && is_file($file=$func($auto.$class).'.php') ||
  2025. is_file($file=$auto.$class.'.php') ||
  2026. is_file($file=$auto.strtolower($class).'.php') ||
  2027. is_file($file=strtolower($auto.$class).'.php'))
  2028. return require($file);
  2029. }
  2030. /**
  2031. * Execute framework/application shutdown sequence
  2032. * @param $cwd string
  2033. **/
  2034. function unload($cwd) {
  2035. chdir($cwd);
  2036. if (!($error=error_get_last()) &&
  2037. session_status()==PHP_SESSION_ACTIVE)
  2038. session_commit();
  2039. foreach ($this->locks as $lock)
  2040. @unlink($lock);
  2041. $handler=$this->hive['UNLOAD'];
  2042. if ((!$handler || $this->call($handler,$this)===FALSE) &&
  2043. $error && in_array($error['type'],
  2044. [E_ERROR,E_PARSE,E_CORE_ERROR,E_COMPILE_ERROR]))
  2045. // Fatal error detected
  2046. $this->error(500,
  2047. sprintf(self::E_Fatal,$error['message']),[$error]);
  2048. }
  2049. /**
  2050. * Convenience method for checking hive key
  2051. * @return mixed
  2052. * @param $key string
  2053. **/
  2054. function offsetexists($key) {
  2055. return $this->exists($key);
  2056. }
  2057. /**
  2058. * Convenience method for assigning hive value
  2059. * @return mixed
  2060. * @param $key string
  2061. * @param $val scalar
  2062. **/
  2063. function offsetset($key,$val) {
  2064. return $this->set($key,$val);
  2065. }
  2066. /**
  2067. * Convenience method for retrieving hive value
  2068. * @return mixed
  2069. * @param $key string
  2070. **/
  2071. function &offsetget($key) {
  2072. $val=&$this->ref($key);
  2073. return $val;
  2074. }
  2075. /**
  2076. * Convenience method for removing hive key
  2077. * @return NULL
  2078. * @param $key string
  2079. **/
  2080. function offsetunset($key) {
  2081. $this->clear($key);
  2082. }
  2083. /**
  2084. * Alias for offsetexists()
  2085. * @return mixed
  2086. * @param $key string
  2087. **/
  2088. function __isset($key) {
  2089. return $this->offsetexists($key);
  2090. }
  2091. /**
  2092. * Alias for offsetset()
  2093. * @return mixed
  2094. * @param $key string
  2095. * @param $val mixed
  2096. **/
  2097. function __set($key,$val) {
  2098. return $this->offsetset($key,$val);
  2099. }
  2100. /**
  2101. * Alias for offsetget()
  2102. * @return mixed
  2103. * @param $key string
  2104. **/
  2105. function &__get($key) {
  2106. $val=&$this->offsetget($key);
  2107. return $val;
  2108. }
  2109. /**
  2110. * Alias for offsetunset()
  2111. * @return mixed
  2112. * @param $key string
  2113. **/
  2114. function __unset($key) {
  2115. $this->offsetunset($key);
  2116. }
  2117. /**
  2118. * Call function identified by hive key
  2119. * @return mixed
  2120. * @param $key string
  2121. * @param $args array
  2122. **/
  2123. function __call($key,array $args) {
  2124. if ($this->exists($key,$val))
  2125. return call_user_func_array($val,$args);
  2126. user_error(sprintf(self::E_Method,$key),E_USER_ERROR);
  2127. }
  2128. //! Prohibit cloning
  2129. private function __clone() {
  2130. }
  2131. //! Bootstrap
  2132. function __construct() {
  2133. // Managed directives
  2134. ini_set('default_charset',$charset='UTF-8');
  2135. if (extension_loaded('mbstring'))
  2136. mb_internal_encoding($charset);
  2137. ini_set('display_errors',0);
  2138. // Deprecated directives
  2139. @ini_set('magic_quotes_gpc',0);
  2140. @ini_set('register_globals',0);
  2141. // Intercept errors/exceptions; PHP5.3-compatible
  2142. $check=error_reporting((E_ALL|E_STRICT)&~(E_NOTICE|E_USER_NOTICE));
  2143. set_exception_handler(
  2144. function($obj) {
  2145. $this->hive['EXCEPTION']=$obj;
  2146. $this->error(500,
  2147. $obj->getmessage().' '.
  2148. '['.$obj->getFile().':'.$obj->getLine().']',
  2149. $obj->gettrace());
  2150. }
  2151. );
  2152. set_error_handler(
  2153. function($level,$text,$file,$line) {
  2154. if ($level & error_reporting())
  2155. $this->error(500,$text,NULL,$level);
  2156. }
  2157. );
  2158. if (!isset($_SERVER['SERVER_NAME']) || $_SERVER['SERVER_NAME']==='')
  2159. $_SERVER['SERVER_NAME']=gethostname();
  2160. $headers=[];
  2161. if ($cli=PHP_SAPI=='cli') {
  2162. // Emulate HTTP request
  2163. $_SERVER['REQUEST_METHOD']='GET';
  2164. if (!isset($_SERVER['argv'][1])) {
  2165. $_SERVER['argc']++;
  2166. $_SERVER['argv'][1]='/';
  2167. }
  2168. $req=$query='';
  2169. if (substr($_SERVER['argv'][1],0,1)=='/') {
  2170. $req=$_SERVER['argv'][1];
  2171. $query=parse_url($req,PHP_URL_QUERY);
  2172. } else {
  2173. foreach($_SERVER['argv'] as $i=>$arg) {
  2174. if (!$i) continue;
  2175. if (preg_match('/^\-(\-)?(\w+)(?:\=(.*))?$/',$arg,$m)) {
  2176. foreach($m[1]?[$m[2]]:str_split($m[2]) as $k)
  2177. $query.=($query?'&':'').urlencode($k).'=';
  2178. if (isset($m[3]))
  2179. $query.=urlencode($m[3]);
  2180. } else
  2181. $req.='/'.$arg;
  2182. }
  2183. if (!$req)
  2184. $req='/';
  2185. if ($query)
  2186. $req.='?'.$query;
  2187. }
  2188. $_SERVER['REQUEST_URI']=$req;
  2189. parse_str($query,$GLOBALS['_GET']);
  2190. }
  2191. elseif (function_exists('getallheaders')) {
  2192. foreach (getallheaders() as $key=>$val) {
  2193. $tmp=strtoupper(strtr($key,'-','_'));
  2194. // TODO: use ucwords delimiters for php 5.4.32+ & 5.5.16+
  2195. $key=strtr(ucwords(strtolower(strtr($key,'-',' '))),' ','-');
  2196. $headers[$key]=$val;
  2197. if (isset($_SERVER['HTTP_'.$tmp]))
  2198. $headers[$key]=&$_SERVER['HTTP_'.$tmp];
  2199. }
  2200. }
  2201. else {
  2202. if (isset($_SERVER['CONTENT_LENGTH']))
  2203. $headers['Content-Length']=&$_SERVER['CONTENT_LENGTH'];
  2204. if (isset($_SERVER['CONTENT_TYPE']))
  2205. $headers['Content-Type']=&$_SERVER['CONTENT_TYPE'];
  2206. foreach (array_keys($_SERVER) as $key)
  2207. if (substr($key,0,5)=='HTTP_')
  2208. $headers[strtr(ucwords(strtolower(strtr(
  2209. substr($key,5),'_',' '))),' ','-')]=&$_SERVER[$key];
  2210. }
  2211. if (isset($headers['X-HTTP-Method-Override']))
  2212. $_SERVER['REQUEST_METHOD']=$headers['X-HTTP-Method-Override'];
  2213. elseif ($_SERVER['REQUEST_METHOD']=='POST' && isset($_POST['_method']))
  2214. $_SERVER['REQUEST_METHOD']=strtoupper($_POST['_method']);
  2215. $scheme=isset($_SERVER['HTTPS']) && $_SERVER['HTTPS']=='on' ||
  2216. isset($headers['X-Forwarded-Proto']) &&
  2217. $headers['X-Forwarded-Proto']=='https'?'https':'http';
  2218. // Create hive early on to expose header methods
  2219. $this->hive=['HEADERS'=>&$headers];
  2220. if (function_exists('apache_setenv')) {
  2221. // Work around Apache pre-2.4 VirtualDocumentRoot bug
  2222. $_SERVER['DOCUMENT_ROOT']=str_replace($_SERVER['SCRIPT_NAME'],'',
  2223. $_SERVER['SCRIPT_FILENAME']);
  2224. apache_setenv("DOCUMENT_ROOT",$_SERVER['DOCUMENT_ROOT']);
  2225. }
  2226. $_SERVER['DOCUMENT_ROOT']=realpath($_SERVER['DOCUMENT_ROOT']);
  2227. $base='';
  2228. if (!$cli)
  2229. $base=rtrim($this->fixslashes(
  2230. dirname($_SERVER['SCRIPT_NAME'])),'/');
  2231. $uri=parse_url((preg_match('/^\w+:\/\//',$_SERVER['REQUEST_URI'])?'':
  2232. $scheme.'://'.$_SERVER['SERVER_NAME']).$_SERVER['REQUEST_URI']);
  2233. $_SERVER['REQUEST_URI']=$uri['path'].
  2234. (isset($uri['query'])?'?'.$uri['query']:'').
  2235. (isset($uri['fragment'])?'#'.$uri['fragment']:'');
  2236. $path=preg_replace('/^'.preg_quote($base,'/').'/','',$uri['path']);
  2237. $jar=[
  2238. 'expire'=>0,
  2239. 'lifetime'=>0,
  2240. 'path'=>$base?:'/',
  2241. 'domain'=>is_int(strpos($_SERVER['SERVER_NAME'],'.')) &&
  2242. !filter_var($_SERVER['SERVER_NAME'],FILTER_VALIDATE_IP)?
  2243. $_SERVER['SERVER_NAME']:'',
  2244. 'secure'=>($scheme=='https'),
  2245. 'httponly'=>TRUE
  2246. ];
  2247. $port=80;
  2248. if (isset($headers['X-Forwarded-Port']))
  2249. $port=$headers['X-Forwarded-Port'];
  2250. elseif (isset($_SERVER['SERVER_PORT']))
  2251. $port=$_SERVER['SERVER_PORT'];
  2252. // Default configuration
  2253. $this->hive+=[
  2254. 'AGENT'=>$this->agent(),
  2255. 'AJAX'=>$this->ajax(),
  2256. 'ALIAS'=>NULL,
  2257. 'ALIASES'=>[],
  2258. 'AUTOLOAD'=>'./',
  2259. 'BASE'=>$base,
  2260. 'BITMASK'=>ENT_COMPAT,
  2261. 'BODY'=>NULL,
  2262. 'CACHE'=>FALSE,
  2263. 'CASELESS'=>TRUE,
  2264. 'CLI'=>$cli,
  2265. 'CORS'=>[
  2266. 'headers'=>'',
  2267. 'origin'=>FALSE,
  2268. 'credentials'=>FALSE,
  2269. 'expose'=>FALSE,
  2270. 'ttl'=>0
  2271. ],
  2272. 'DEBUG'=>0,
  2273. 'DIACRITICS'=>[],
  2274. 'DNSBL'=>'',
  2275. 'EMOJI'=>[],
  2276. 'ENCODING'=>$charset,
  2277. 'ERROR'=>NULL,
  2278. 'ESCAPE'=>TRUE,
  2279. 'EXCEPTION'=>NULL,
  2280. 'EXEMPT'=>NULL,
  2281. 'FALLBACK'=>$this->fallback,
  2282. 'FORMATS'=>[],
  2283. 'FRAGMENT'=>isset($uri['fragment'])?$uri['fragment']:'',
  2284. 'HALT'=>TRUE,
  2285. 'HIGHLIGHT'=>FALSE,
  2286. 'HOST'=>$_SERVER['SERVER_NAME'],
  2287. 'IP'=>$this->ip(),
  2288. 'JAR'=>$jar,
  2289. 'LANGUAGE'=>isset($headers['Accept-Language'])?
  2290. $this->language($headers['Accept-Language']):
  2291. $this->fallback,
  2292. 'LOCALES'=>'./',
  2293. 'LOGGABLE'=>'*',
  2294. 'LOGS'=>'./',
  2295. 'MB'=>extension_loaded('mbstring'),
  2296. 'ONERROR'=>NULL,
  2297. 'ONREROUTE'=>NULL,
  2298. 'PACKAGE'=>self::PACKAGE,
  2299. 'PARAMS'=>[],
  2300. 'PATH'=>$path,
  2301. 'PATTERN'=>NULL,
  2302. 'PLUGINS'=>$this->fixslashes(__DIR__).'/',
  2303. 'PORT'=>$port,
  2304. 'PREFIX'=>NULL,
  2305. 'PREMAP'=>'',
  2306. 'QUERY'=>isset($uri['query'])?$uri['query']:'',
  2307. 'QUIET'=>FALSE,
  2308. 'RAW'=>FALSE,
  2309. 'REALM'=>$scheme.'://'.$_SERVER['SERVER_NAME'].
  2310. ($port && !in_array($port,[80,443])?(':'.$port):'').
  2311. $_SERVER['REQUEST_URI'],
  2312. 'RESPONSE'=>'',
  2313. 'ROOT'=>$_SERVER['DOCUMENT_ROOT'],
  2314. 'ROUTES'=>[],
  2315. 'SCHEME'=>$scheme,
  2316. 'SEED'=>$this->hash($_SERVER['SERVER_NAME'].$base),
  2317. 'SERIALIZER'=>extension_loaded($ext='igbinary')?$ext:'php',
  2318. 'TEMP'=>'tmp/',
  2319. 'TIME'=>&$_SERVER['REQUEST_TIME_FLOAT'],
  2320. 'TZ'=>@date_default_timezone_get(),
  2321. 'UI'=>'./',
  2322. 'UNLOAD'=>NULL,
  2323. 'UPLOADS'=>'./',
  2324. 'URI'=>&$_SERVER['REQUEST_URI'],
  2325. 'VERB'=>&$_SERVER['REQUEST_METHOD'],
  2326. 'VERSION'=>self::VERSION,
  2327. 'XFRAME'=>'SAMEORIGIN'
  2328. ];
  2329. if (!headers_sent() && session_status()!=PHP_SESSION_ACTIVE) {
  2330. unset($jar['expire']);
  2331. session_cache_limiter('');
  2332. call_user_func_array('session_set_cookie_params',$jar);
  2333. }
  2334. if (PHP_SAPI=='cli-server' &&
  2335. preg_match('/^'.preg_quote($base,'/').'$/',$this->hive['URI']))
  2336. $this->reroute('/');
  2337. if (ini_get('auto_globals_jit'))
  2338. // Override setting
  2339. $GLOBALS+=['_ENV'=>$_ENV,'_REQUEST'=>$_REQUEST];
  2340. // Sync PHP globals with corresponding hive keys
  2341. $this->init=$this->hive;
  2342. foreach (explode('|',self::GLOBALS) as $global) {
  2343. $sync=$this->sync($global);
  2344. $this->init+=[
  2345. $global=>preg_match('/SERVER|ENV/',$global)?$sync:[]
  2346. ];
  2347. }
  2348. if ($check && $error=error_get_last())
  2349. // Error detected
  2350. $this->error(500,
  2351. sprintf(self::E_Fatal,$error['message']),[$error]);
  2352. date_default_timezone_set($this->hive['TZ']);
  2353. // Register framework autoloader
  2354. spl_autoload_register([$this,'autoload']);
  2355. // Register shutdown handler
  2356. register_shutdown_function([$this,'unload'],getcwd());
  2357. }
  2358. }
  2359. //! Cache engine
  2360. class Cache extends Prefab {
  2361. protected
  2362. //! Cache DSN
  2363. $dsn,
  2364. //! Prefix for cache entries
  2365. $prefix,
  2366. //! MemCache or Redis object
  2367. $ref;
  2368. /**
  2369. * Return timestamp and TTL of cache entry or FALSE if not found
  2370. * @return array|FALSE
  2371. * @param $key string
  2372. * @param $val mixed
  2373. **/
  2374. function exists($key,&$val=NULL) {
  2375. $fw=Base::instance();
  2376. if (!$this->dsn)
  2377. return FALSE;
  2378. $ndx=$this->prefix.'.'.$key;
  2379. $parts=explode('=',$this->dsn,2);
  2380. switch ($parts[0]) {
  2381. case 'apc':
  2382. case 'apcu':
  2383. $raw=call_user_func($parts[0].'_fetch',$ndx);
  2384. break;
  2385. case 'redis':
  2386. $raw=$this->ref->get($ndx);
  2387. break;
  2388. case 'memcache':
  2389. $raw=memcache_get($this->ref,$ndx);
  2390. break;
  2391. case 'memcached':
  2392. $raw=$this->ref->get($ndx);
  2393. break;
  2394. case 'wincache':
  2395. $raw=wincache_ucache_get($ndx);
  2396. break;
  2397. case 'xcache':
  2398. $raw=xcache_get($ndx);
  2399. break;
  2400. case 'folder':
  2401. $raw=$fw->read($parts[1].$ndx);
  2402. break;
  2403. }
  2404. if (!empty($raw)) {
  2405. list($val,$time,$ttl)=(array)$fw->unserialize($raw);
  2406. if ($ttl===0 || $time+$ttl>microtime(TRUE))
  2407. return [$time,$ttl];
  2408. $val=null;
  2409. $this->clear($key);
  2410. }
  2411. return FALSE;
  2412. }
  2413. /**
  2414. * Store value in cache
  2415. * @return mixed|FALSE
  2416. * @param $key string
  2417. * @param $val mixed
  2418. * @param $ttl int
  2419. **/
  2420. function set($key,$val,$ttl=0) {
  2421. $fw=Base::instance();
  2422. if (!$this->dsn)
  2423. return TRUE;
  2424. $ndx=$this->prefix.'.'.$key;
  2425. if ($cached=$this->exists($key))
  2426. $ttl=$cached[1];
  2427. $data=$fw->serialize([$val,microtime(TRUE),$ttl]);
  2428. $parts=explode('=',$this->dsn,2);
  2429. switch ($parts[0]) {
  2430. case 'apc':
  2431. case 'apcu':
  2432. return call_user_func($parts[0].'_store',$ndx,$data,$ttl);
  2433. case 'redis':
  2434. return $this->ref->set($ndx,$data,$ttl?['ex'=>$ttl]:[]);
  2435. case 'memcache':
  2436. return memcache_set($this->ref,$ndx,$data,0,$ttl);
  2437. case 'memcached':
  2438. return $this->ref->set($ndx,$data,$ttl);
  2439. case 'wincache':
  2440. return wincache_ucache_set($ndx,$data,$ttl);
  2441. case 'xcache':
  2442. return xcache_set($ndx,$data,$ttl);
  2443. case 'folder':
  2444. return $fw->write($parts[1].
  2445. str_replace(['/','\\'],'',$ndx),$data);
  2446. }
  2447. return FALSE;
  2448. }
  2449. /**
  2450. * Retrieve value of cache entry
  2451. * @return mixed|FALSE
  2452. * @param $key string
  2453. **/
  2454. function get($key) {
  2455. return $this->dsn && $this->exists($key,$data)?$data:FALSE;
  2456. }
  2457. /**
  2458. * Delete cache entry
  2459. * @return bool
  2460. * @param $key string
  2461. **/
  2462. function clear($key) {
  2463. if (!$this->dsn)
  2464. return;
  2465. $ndx=$this->prefix.'.'.$key;
  2466. $parts=explode('=',$this->dsn,2);
  2467. switch ($parts[0]) {
  2468. case 'apc':
  2469. case 'apcu':
  2470. return call_user_func($parts[0].'_delete',$ndx);
  2471. case 'redis':
  2472. return $this->ref->del($ndx);
  2473. case 'memcache':
  2474. return memcache_delete($this->ref,$ndx);
  2475. case 'memcached':
  2476. return $this->ref->delete($ndx);
  2477. case 'wincache':
  2478. return wincache_ucache_delete($ndx);
  2479. case 'xcache':
  2480. return xcache_unset($ndx);
  2481. case 'folder':
  2482. return @unlink($parts[1].$ndx);
  2483. }
  2484. return FALSE;
  2485. }
  2486. /**
  2487. * Clear contents of cache backend
  2488. * @return bool
  2489. * @param $suffix string
  2490. **/
  2491. function reset($suffix=NULL) {
  2492. if (!$this->dsn)
  2493. return TRUE;
  2494. $regex='/'.preg_quote($this->prefix.'.','/').'.*'.
  2495. preg_quote($suffix,'/').'/';
  2496. $parts=explode('=',$this->dsn,2);
  2497. switch ($parts[0]) {
  2498. case 'apc':
  2499. case 'apcu':
  2500. $info=call_user_func($parts[0].'_cache_info',
  2501. $parts[0]=='apcu'?FALSE:'user');
  2502. if (!empty($info['cache_list'])) {
  2503. $key=array_key_exists('info',
  2504. $info['cache_list'][0])?'info':'key';
  2505. foreach ($info['cache_list'] as $item)
  2506. if (preg_match($regex,$item[$key]))
  2507. call_user_func($parts[0].'_delete',$item[$key]);
  2508. }
  2509. return TRUE;
  2510. case 'redis':
  2511. $keys=$this->ref->keys($this->prefix.'.*'.$suffix);
  2512. foreach($keys as $key)
  2513. $this->ref->del($key);
  2514. return TRUE;
  2515. case 'memcache':
  2516. foreach (memcache_get_extended_stats(
  2517. $this->ref,'slabs') as $slabs)
  2518. foreach (array_filter(array_keys($slabs),'is_numeric')
  2519. as $id)
  2520. foreach (memcache_get_extended_stats(
  2521. $this->ref,'cachedump',$id) as $data)
  2522. if (is_array($data))
  2523. foreach (array_keys($data) as $key)
  2524. if (preg_match($regex,$key))
  2525. memcache_delete($this->ref,$key);
  2526. return TRUE;
  2527. case 'memcached':
  2528. foreach ($this->ref->getallkeys()?:[] as $key)
  2529. if (preg_match($regex,$key))
  2530. $this->ref->delete($key);
  2531. return TRUE;
  2532. case 'wincache':
  2533. $info=wincache_ucache_info();
  2534. foreach ($info['ucache_entries'] as $item)
  2535. if (preg_match($regex,$item['key_name']))
  2536. wincache_ucache_delete($item['key_name']);
  2537. return TRUE;
  2538. case 'xcache':
  2539. if ($suffix && !ini_get('xcache.admin.enable_auth')) {
  2540. $cnt=xcache_count(XC_TYPE_VAR);
  2541. for ($i=0;$i<$cnt;$i++) {
  2542. $list=xcache_list(XC_TYPE_VAR,$i);
  2543. foreach ($list['cache_list'] as $item)
  2544. if (preg_match($regex,$item['name']))
  2545. xcache_unset($item['name']);
  2546. }
  2547. } else
  2548. xcache_unset_by_prefix($this->prefix.'.');
  2549. return TRUE;
  2550. case 'folder':
  2551. if ($glob=@glob($parts[1].'*'))
  2552. foreach ($glob as $file)
  2553. if (preg_match($regex,basename($file)))
  2554. @unlink($file);
  2555. return TRUE;
  2556. }
  2557. return FALSE;
  2558. }
  2559. /**
  2560. * Load/auto-detect cache backend
  2561. * @return string
  2562. * @param $dsn bool|string
  2563. * @param $seed bool|string
  2564. **/
  2565. function load($dsn,$seed=NULL) {
  2566. $fw=Base::instance();
  2567. if ($dsn=trim($dsn)) {
  2568. if (preg_match('/^redis=(.+)/',$dsn,$parts) &&
  2569. extension_loaded('redis')) {
  2570. list($host,$port,$db)=explode(':',$parts[1])+[1=>6379,2=>NULL];
  2571. $this->ref=new Redis;
  2572. if(!$this->ref->connect($host,$port,2))
  2573. $this->ref=NULL;
  2574. if(isset($db))
  2575. $this->ref->select($db);
  2576. }
  2577. elseif (preg_match('/^memcache=(.+)/',$dsn,$parts) &&
  2578. extension_loaded('memcache'))
  2579. foreach ($fw->split($parts[1]) as $server) {
  2580. list($host,$port)=explode(':',$server)+[1=>11211];
  2581. if (empty($this->ref))
  2582. $this->ref=@memcache_connect($host,$port)?:NULL;
  2583. else
  2584. memcache_add_server($this->ref,$host,$port);
  2585. }
  2586. elseif (preg_match('/^memcached=(.+)/',$dsn,$parts) &&
  2587. extension_loaded('memcached'))
  2588. foreach ($fw->split($parts[1]) as $server) {
  2589. list($host,$port)=explode(':',$server)+[1=>11211];
  2590. if (empty($this->ref))
  2591. $this->ref=new Memcached();
  2592. $this->ref->addServer($host,$port);
  2593. }
  2594. if (empty($this->ref) && !preg_match('/^folder\h*=/',$dsn))
  2595. $dsn=($grep=preg_grep('/^(apc|wincache|xcache)/',
  2596. array_map('strtolower',get_loaded_extensions())))?
  2597. // Auto-detect
  2598. current($grep):
  2599. // Use filesystem as fallback
  2600. ('folder='.$fw->TEMP.'cache/');
  2601. if (preg_match('/^folder\h*=\h*(.+)/',$dsn,$parts) &&
  2602. !is_dir($parts[1]))
  2603. mkdir($parts[1],Base::MODE,TRUE);
  2604. }
  2605. $this->prefix=$seed?:$fw->SEED;
  2606. return $this->dsn=$dsn;
  2607. }
  2608. /**
  2609. * Class constructor
  2610. * @param $dsn bool|string
  2611. **/
  2612. function __construct($dsn=FALSE) {
  2613. if ($dsn)
  2614. $this->load($dsn);
  2615. }
  2616. }
  2617. //! View handler
  2618. class View extends Prefab {
  2619. private
  2620. //! Temporary hive
  2621. $temp;
  2622. protected
  2623. //! Template file
  2624. $file,
  2625. //! Post-rendering handler
  2626. $trigger,
  2627. //! Nesting level
  2628. $level=0;
  2629. /** @var \Base Framework instance */
  2630. protected $fw;
  2631. function __construct() {
  2632. $this->fw=\Base::instance();
  2633. }
  2634. /**
  2635. * Encode characters to equivalent HTML entities
  2636. * @return string
  2637. * @param $arg mixed
  2638. **/
  2639. function esc($arg) {
  2640. return $this->fw->recursive($arg,
  2641. function($val) {
  2642. return is_string($val)?$this->fw->encode($val):$val;
  2643. }
  2644. );
  2645. }
  2646. /**
  2647. * Decode HTML entities to equivalent characters
  2648. * @return string
  2649. * @param $arg mixed
  2650. **/
  2651. function raw($arg) {
  2652. return $this->fw->recursive($arg,
  2653. function($val) {
  2654. return is_string($val)?$this->fw->decode($val):$val;
  2655. }
  2656. );
  2657. }
  2658. /**
  2659. * Create sandbox for template execution
  2660. * @return string
  2661. * @param $hive array
  2662. * @param $mime string
  2663. **/
  2664. protected function sandbox(array $hive=NULL,$mime=NULL) {
  2665. $fw=$this->fw;
  2666. $implicit=FALSE;
  2667. if (is_null($hive)) {
  2668. $implicit=TRUE;
  2669. $hive=$fw->hive();
  2670. }
  2671. if ($this->level<1 || $implicit) {
  2672. if (!$fw->CLI && $mime && !headers_sent() &&
  2673. !preg_grep ('/^Content-Type:/',headers_list()))
  2674. header('Content-Type: '.$mime.'; '.
  2675. 'charset='.$fw->ENCODING);
  2676. if ($fw->ESCAPE)
  2677. $hive=$this->esc($hive);
  2678. if (isset($hive['ALIASES']))
  2679. $hive['ALIASES']=$fw->build($hive['ALIASES']);
  2680. }
  2681. $this->temp=$hive;
  2682. unset($fw,$hive,$implicit,$mime);
  2683. extract($this->temp);
  2684. $this->temp=NULL;
  2685. $this->level++;
  2686. ob_start();
  2687. require($this->file);
  2688. $this->level--;
  2689. return ob_get_clean();
  2690. }
  2691. /**
  2692. * Render template
  2693. * @return string
  2694. * @param $file string
  2695. * @param $mime string
  2696. * @param $hive array
  2697. * @param $ttl int
  2698. **/
  2699. function render($file,$mime='text/html',array $hive=NULL,$ttl=0) {
  2700. $fw=$this->fw;
  2701. $cache=Cache::instance();
  2702. foreach ($fw->split($fw->UI) as $dir) {
  2703. if ($cache->exists($hash=$fw->hash($dir.$file),$data))
  2704. return $data;
  2705. if (is_file($this->file=$fw->fixslashes($dir.$file))) {
  2706. if (isset($_COOKIE[session_name()]) &&
  2707. !headers_sent() && session_status()!=PHP_SESSION_ACTIVE)
  2708. session_start();
  2709. $fw->sync('SESSION');
  2710. $data=$this->sandbox($hive,$mime);
  2711. if (isset($this->trigger['afterrender']))
  2712. foreach($this->trigger['afterrender'] as $func)
  2713. $data=$fw->call($func,[$data, $dir.$file]);
  2714. if ($ttl)
  2715. $cache->set($hash,$data,$ttl);
  2716. return $data;
  2717. }
  2718. }
  2719. user_error(sprintf(Base::E_Open,$file),E_USER_ERROR);
  2720. }
  2721. /**
  2722. * post rendering handler
  2723. * @param $func callback
  2724. */
  2725. function afterrender($func) {
  2726. $this->trigger['afterrender'][]=$func;
  2727. }
  2728. }
  2729. //! Lightweight template engine
  2730. class Preview extends View {
  2731. protected
  2732. //! token filter
  2733. $filter=[
  2734. 'c'=>'$this->c',
  2735. 'esc'=>'$this->esc',
  2736. 'raw'=>'$this->raw',
  2737. 'export'=>'Base::instance()->export',
  2738. 'alias'=>'Base::instance()->alias',
  2739. 'format'=>'Base::instance()->format'
  2740. ];
  2741. protected
  2742. //! newline interpolation
  2743. $interpolation=true;
  2744. /**
  2745. * Enable/disable markup parsing interpolation
  2746. * mainly used for adding appropriate newlines
  2747. * @param $bool bool
  2748. */
  2749. function interpolation($bool) {
  2750. $this->interpolation=$bool;
  2751. }
  2752. /**
  2753. * Return C-locale equivalent of number
  2754. * @return string
  2755. * @param $val int|float
  2756. **/
  2757. function c($val) {
  2758. $locale=setlocale(LC_NUMERIC,0);
  2759. setlocale(LC_NUMERIC,'C');
  2760. $out=(string)(float)$val;
  2761. $locale=setlocale(LC_NUMERIC,$locale);
  2762. return $out;
  2763. }
  2764. /**
  2765. * Convert token to variable
  2766. * @return string
  2767. * @param $str string
  2768. **/
  2769. function token($str) {
  2770. $fw=$this->fw;
  2771. $str=trim(preg_replace('/\{\{(.+?)\}\}/s',trim('\1'),
  2772. $fw->compile($str)));
  2773. if (preg_match('/^(.+)(?<!\|)\|((?:\h*\w+(?:\h*[,;]?))+)$/s',
  2774. $str,$parts)) {
  2775. $str=trim($parts[1]);
  2776. foreach ($fw->split(trim($parts[2],"\xC2\xA0")) as $func)
  2777. $str=((empty($this->filter[$cmd=$func]) &&
  2778. function_exists($cmd)) ||
  2779. is_string($cmd=$this->filter($func)))?
  2780. $cmd.'('.$str.')':
  2781. 'Base::instance()->'.
  2782. 'call($this->filter(\''.$func.'\'),['.$str.'])';
  2783. }
  2784. return $str;
  2785. }
  2786. /**
  2787. * Register or get (one specific or all) token filters
  2788. * @param string $key
  2789. * @param string|closure $func
  2790. * @return array|closure|string
  2791. */
  2792. function filter($key=NULL,$func=NULL) {
  2793. if (!$key)
  2794. return array_keys($this->filter);
  2795. $key=strtolower($key);
  2796. if (!$func)
  2797. return $this->filter[$key];
  2798. $this->filter[$key]=$func;
  2799. }
  2800. /**
  2801. * Assemble markup
  2802. * @return string
  2803. * @param $node string
  2804. **/
  2805. protected function build($node) {
  2806. return preg_replace_callback(
  2807. '/\{~(.+?)~\}|\{\*(.+?)\*\}|\{\-(.+?)\-\}|'.
  2808. '\{\{(.+?)\}\}((\r?\n)*)/s',
  2809. function($expr) {
  2810. if ($expr[1])
  2811. $str='<?php '.$this->token($expr[1]).' ?>';
  2812. elseif ($expr[2])
  2813. return '';
  2814. elseif ($expr[3])
  2815. $str=$expr[3];
  2816. else {
  2817. $str='<?= ('.trim($this->token($expr[4])).')'.
  2818. ($this->interpolation?
  2819. (!empty($expr[6])?'."'.$expr[6].'"':''):'').' ?>';
  2820. if (isset($expr[5]))
  2821. $str.=$expr[5];
  2822. }
  2823. return $str;
  2824. },
  2825. $node
  2826. );
  2827. }
  2828. /**
  2829. * Render template string
  2830. * @return string
  2831. * @param $node string|array
  2832. * @param $hive array
  2833. * @param $ttl int
  2834. * @param $persist bool
  2835. * @param $escape bool
  2836. **/
  2837. function resolve($node,array $hive=NULL,$ttl=0,$persist=FALSE,$escape=NULL) {
  2838. $fw=$this->fw;
  2839. $cache=Cache::instance();
  2840. if ($escape!==NULL) {
  2841. $esc=$fw->ESCAPE;
  2842. $fw->ESCAPE=$escape;
  2843. }
  2844. if ($ttl || $persist)
  2845. $hash=$fw->hash($fw->serialize($node));
  2846. if ($ttl && $cache->exists($hash,$data))
  2847. return $data;
  2848. if ($persist) {
  2849. if (!is_dir($tmp=$fw->TEMP))
  2850. mkdir($tmp,Base::MODE,TRUE);
  2851. if (!is_file($this->file=($tmp.
  2852. $fw->SEED.'.'.$hash.'.php')))
  2853. $fw->write($this->file,$this->build($node));
  2854. if (isset($_COOKIE[session_name()]) &&
  2855. !headers_sent() && session_status()!=PHP_SESSION_ACTIVE)
  2856. session_start();
  2857. $fw->sync('SESSION');
  2858. $data=$this->sandbox($hive);
  2859. }
  2860. else {
  2861. if (!$hive)
  2862. $hive=$fw->hive();
  2863. if ($fw->ESCAPE)
  2864. $hive=$this->esc($hive);
  2865. extract($hive);
  2866. unset($hive);
  2867. ob_start();
  2868. eval(' ?>'.$this->build($node).'<?php ');
  2869. $data=ob_get_clean();
  2870. }
  2871. if ($ttl)
  2872. $cache->set($hash,$data,$ttl);
  2873. if ($escape!==NULL)
  2874. $fw->ESCAPE=$esc;
  2875. return $data;
  2876. }
  2877. /**
  2878. * Parse template string
  2879. * @return string
  2880. * @param $text string
  2881. **/
  2882. function parse($text) {
  2883. // Remove PHP code and comments
  2884. return preg_replace(
  2885. '/\h*<\?(?!xml)(?:php|\s*=)?.+?\?>\h*|'.
  2886. '\{\*.+?\*\}/is','', $text);
  2887. }
  2888. /**
  2889. * Render template
  2890. * @return string
  2891. * @param $file string
  2892. * @param $mime string
  2893. * @param $hive array
  2894. * @param $ttl int
  2895. **/
  2896. function render($file,$mime='text/html',array $hive=NULL,$ttl=0) {
  2897. $fw=$this->fw;
  2898. $cache=Cache::instance();
  2899. if (!is_dir($tmp=$fw->TEMP))
  2900. mkdir($tmp,Base::MODE,TRUE);
  2901. foreach ($fw->split($fw->UI) as $dir) {
  2902. if ($cache->exists($hash=$fw->hash($dir.$file),$data))
  2903. return $data;
  2904. if (is_file($view=$fw->fixslashes($dir.$file))) {
  2905. if (!is_file($this->file=($tmp.
  2906. $fw->SEED.'.'.$fw->hash($view).'.php')) ||
  2907. filemtime($this->file)<filemtime($view)) {
  2908. $contents=$fw->read($view);
  2909. if (isset($this->trigger['beforerender']))
  2910. foreach ($this->trigger['beforerender'] as $func)
  2911. $contents=$fw->call($func, [$contents, $view]);
  2912. $text=$this->parse($contents);
  2913. $fw->write($this->file,$this->build($text));
  2914. }
  2915. if (isset($_COOKIE[session_name()]) &&
  2916. !headers_sent() && session_status()!=PHP_SESSION_ACTIVE)
  2917. session_start();
  2918. $fw->sync('SESSION');
  2919. $data=$this->sandbox($hive,$mime);
  2920. if(isset($this->trigger['afterrender']))
  2921. foreach ($this->trigger['afterrender'] as $func)
  2922. $data=$fw->call($func, [$data, $view]);
  2923. if ($ttl)
  2924. $cache->set($hash,$data,$ttl);
  2925. return $data;
  2926. }
  2927. }
  2928. user_error(sprintf(Base::E_Open,$file),E_USER_ERROR);
  2929. }
  2930. /**
  2931. * post rendering handler
  2932. * @param $func callback
  2933. */
  2934. function beforerender($func) {
  2935. $this->trigger['beforerender'][]=$func;
  2936. }
  2937. }
  2938. //! ISO language/country codes
  2939. class ISO extends Prefab {
  2940. //@{ ISO 3166-1 country codes
  2941. const
  2942. CC_af='Afghanistan',
  2943. CC_ax='Åland Islands',
  2944. CC_al='Albania',
  2945. CC_dz='Algeria',
  2946. CC_as='American Samoa',
  2947. CC_ad='Andorra',
  2948. CC_ao='Angola',
  2949. CC_ai='Anguilla',
  2950. CC_aq='Antarctica',
  2951. CC_ag='Antigua and Barbuda',
  2952. CC_ar='Argentina',
  2953. CC_am='Armenia',
  2954. CC_aw='Aruba',
  2955. CC_au='Australia',
  2956. CC_at='Austria',
  2957. CC_az='Azerbaijan',
  2958. CC_bs='Bahamas',
  2959. CC_bh='Bahrain',
  2960. CC_bd='Bangladesh',
  2961. CC_bb='Barbados',
  2962. CC_by='Belarus',
  2963. CC_be='Belgium',
  2964. CC_bz='Belize',
  2965. CC_bj='Benin',
  2966. CC_bm='Bermuda',
  2967. CC_bt='Bhutan',
  2968. CC_bo='Bolivia',
  2969. CC_bq='Bonaire, Sint Eustatius and Saba',
  2970. CC_ba='Bosnia and Herzegovina',
  2971. CC_bw='Botswana',
  2972. CC_bv='Bouvet Island',
  2973. CC_br='Brazil',
  2974. CC_io='British Indian Ocean Territory',
  2975. CC_bn='Brunei Darussalam',
  2976. CC_bg='Bulgaria',
  2977. CC_bf='Burkina Faso',
  2978. CC_bi='Burundi',
  2979. CC_kh='Cambodia',
  2980. CC_cm='Cameroon',
  2981. CC_ca='Canada',
  2982. CC_cv='Cape Verde',
  2983. CC_ky='Cayman Islands',
  2984. CC_cf='Central African Republic',
  2985. CC_td='Chad',
  2986. CC_cl='Chile',
  2987. CC_cn='China',
  2988. CC_cx='Christmas Island',
  2989. CC_cc='Cocos (Keeling) Islands',
  2990. CC_co='Colombia',
  2991. CC_km='Comoros',
  2992. CC_cg='Congo',
  2993. CC_cd='Congo, The Democratic Republic of',
  2994. CC_ck='Cook Islands',
  2995. CC_cr='Costa Rica',
  2996. CC_ci='Côte d\'ivoire',
  2997. CC_hr='Croatia',
  2998. CC_cu='Cuba',
  2999. CC_cw='Curaçao',
  3000. CC_cy='Cyprus',
  3001. CC_cz='Czech Republic',
  3002. CC_dk='Denmark',
  3003. CC_dj='Djibouti',
  3004. CC_dm='Dominica',
  3005. CC_do='Dominican Republic',
  3006. CC_ec='Ecuador',
  3007. CC_eg='Egypt',
  3008. CC_sv='El Salvador',
  3009. CC_gq='Equatorial Guinea',
  3010. CC_er='Eritrea',
  3011. CC_ee='Estonia',
  3012. CC_et='Ethiopia',
  3013. CC_fk='Falkland Islands (Malvinas)',
  3014. CC_fo='Faroe Islands',
  3015. CC_fj='Fiji',
  3016. CC_fi='Finland',
  3017. CC_fr='France',
  3018. CC_gf='French Guiana',
  3019. CC_pf='French Polynesia',
  3020. CC_tf='French Southern Territories',
  3021. CC_ga='Gabon',
  3022. CC_gm='Gambia',
  3023. CC_ge='Georgia',
  3024. CC_de='Germany',
  3025. CC_gh='Ghana',
  3026. CC_gi='Gibraltar',
  3027. CC_gr='Greece',
  3028. CC_gl='Greenland',
  3029. CC_gd='Grenada',
  3030. CC_gp='Guadeloupe',
  3031. CC_gu='Guam',
  3032. CC_gt='Guatemala',
  3033. CC_gg='Guernsey',
  3034. CC_gn='Guinea',
  3035. CC_gw='Guinea-Bissau',
  3036. CC_gy='Guyana',
  3037. CC_ht='Haiti',
  3038. CC_hm='Heard Island and McDonald Islands',
  3039. CC_va='Holy See (Vatican City State)',
  3040. CC_hn='Honduras',
  3041. CC_hk='Hong Kong',
  3042. CC_hu='Hungary',
  3043. CC_is='Iceland',
  3044. CC_in='India',
  3045. CC_id='Indonesia',
  3046. CC_ir='Iran, Islamic Republic of',
  3047. CC_iq='Iraq',
  3048. CC_ie='Ireland',
  3049. CC_im='Isle of Man',
  3050. CC_il='Israel',
  3051. CC_it='Italy',
  3052. CC_jm='Jamaica',
  3053. CC_jp='Japan',
  3054. CC_je='Jersey',
  3055. CC_jo='Jordan',
  3056. CC_kz='Kazakhstan',
  3057. CC_ke='Kenya',
  3058. CC_ki='Kiribati',
  3059. CC_kp='Korea, Democratic People\'s Republic of',
  3060. CC_kr='Korea, Republic of',
  3061. CC_kw='Kuwait',
  3062. CC_kg='Kyrgyzstan',
  3063. CC_la='Lao People\'s Democratic Republic',
  3064. CC_lv='Latvia',
  3065. CC_lb='Lebanon',
  3066. CC_ls='Lesotho',
  3067. CC_lr='Liberia',
  3068. CC_ly='Libya',
  3069. CC_li='Liechtenstein',
  3070. CC_lt='Lithuania',
  3071. CC_lu='Luxembourg',
  3072. CC_mo='Macao',
  3073. CC_mk='Macedonia, The Former Yugoslav Republic of',
  3074. CC_mg='Madagascar',
  3075. CC_mw='Malawi',
  3076. CC_my='Malaysia',
  3077. CC_mv='Maldives',
  3078. CC_ml='Mali',
  3079. CC_mt='Malta',
  3080. CC_mh='Marshall Islands',
  3081. CC_mq='Martinique',
  3082. CC_mr='Mauritania',
  3083. CC_mu='Mauritius',
  3084. CC_yt='Mayotte',
  3085. CC_mx='Mexico',
  3086. CC_fm='Micronesia, Federated States of',
  3087. CC_md='Moldova, Republic of',
  3088. CC_mc='Monaco',
  3089. CC_mn='Mongolia',
  3090. CC_me='Montenegro',
  3091. CC_ms='Montserrat',
  3092. CC_ma='Morocco',
  3093. CC_mz='Mozambique',
  3094. CC_mm='Myanmar',
  3095. CC_na='Namibia',
  3096. CC_nr='Nauru',
  3097. CC_np='Nepal',
  3098. CC_nl='Netherlands',
  3099. CC_nc='New Caledonia',
  3100. CC_nz='New Zealand',
  3101. CC_ni='Nicaragua',
  3102. CC_ne='Niger',
  3103. CC_ng='Nigeria',
  3104. CC_nu='Niue',
  3105. CC_nf='Norfolk Island',
  3106. CC_mp='Northern Mariana Islands',
  3107. CC_no='Norway',
  3108. CC_om='Oman',
  3109. CC_pk='Pakistan',
  3110. CC_pw='Palau',
  3111. CC_ps='Palestinian Territory, Occupied',
  3112. CC_pa='Panama',
  3113. CC_pg='Papua New Guinea',
  3114. CC_py='Paraguay',
  3115. CC_pe='Peru',
  3116. CC_ph='Philippines',
  3117. CC_pn='Pitcairn',
  3118. CC_pl='Poland',
  3119. CC_pt='Portugal',
  3120. CC_pr='Puerto Rico',
  3121. CC_qa='Qatar',
  3122. CC_re='Réunion',
  3123. CC_ro='Romania',
  3124. CC_ru='Russian Federation',
  3125. CC_rw='Rwanda',
  3126. CC_bl='Saint Barthélemy',
  3127. CC_sh='Saint Helena, Ascension and Tristan da Cunha',
  3128. CC_kn='Saint Kitts and Nevis',
  3129. CC_lc='Saint Lucia',
  3130. CC_mf='Saint Martin (French Part)',
  3131. CC_pm='Saint Pierre and Miquelon',
  3132. CC_vc='Saint Vincent and The Grenadines',
  3133. CC_ws='Samoa',
  3134. CC_sm='San Marino',
  3135. CC_st='Sao Tome and Principe',
  3136. CC_sa='Saudi Arabia',
  3137. CC_sn='Senegal',
  3138. CC_rs='Serbia',
  3139. CC_sc='Seychelles',
  3140. CC_sl='Sierra Leone',
  3141. CC_sg='Singapore',
  3142. CC_sk='Slovakia',
  3143. CC_sx='Sint Maarten (Dutch Part)',
  3144. CC_si='Slovenia',
  3145. CC_sb='Solomon Islands',
  3146. CC_so='Somalia',
  3147. CC_za='South Africa',
  3148. CC_gs='South Georgia and The South Sandwich Islands',
  3149. CC_ss='South Sudan',
  3150. CC_es='Spain',
  3151. CC_lk='Sri Lanka',
  3152. CC_sd='Sudan',
  3153. CC_sr='Suriname',
  3154. CC_sj='Svalbard and Jan Mayen',
  3155. CC_sz='Swaziland',
  3156. CC_se='Sweden',
  3157. CC_ch='Switzerland',
  3158. CC_sy='Syrian Arab Republic',
  3159. CC_tw='Taiwan, Province of China',
  3160. CC_tj='Tajikistan',
  3161. CC_tz='Tanzania, United Republic of',
  3162. CC_th='Thailand',
  3163. CC_tl='Timor-Leste',
  3164. CC_tg='Togo',
  3165. CC_tk='Tokelau',
  3166. CC_to='Tonga',
  3167. CC_tt='Trinidad and Tobago',
  3168. CC_tn='Tunisia',
  3169. CC_tr='Turkey',
  3170. CC_tm='Turkmenistan',
  3171. CC_tc='Turks and Caicos Islands',
  3172. CC_tv='Tuvalu',
  3173. CC_ug='Uganda',
  3174. CC_ua='Ukraine',
  3175. CC_ae='United Arab Emirates',
  3176. CC_gb='United Kingdom',
  3177. CC_us='United States',
  3178. CC_um='United States Minor Outlying Islands',
  3179. CC_uy='Uruguay',
  3180. CC_uz='Uzbekistan',
  3181. CC_vu='Vanuatu',
  3182. CC_ve='Venezuela',
  3183. CC_vn='Viet Nam',
  3184. CC_vg='Virgin Islands, British',
  3185. CC_vi='Virgin Islands, U.S.',
  3186. CC_wf='Wallis and Futuna',
  3187. CC_eh='Western Sahara',
  3188. CC_ye='Yemen',
  3189. CC_zm='Zambia',
  3190. CC_zw='Zimbabwe';
  3191. //@}
  3192. //@{ ISO 639-1 language codes (Windows-compatibility subset)
  3193. const
  3194. LC_af='Afrikaans',
  3195. LC_am='Amharic',
  3196. LC_ar='Arabic',
  3197. LC_as='Assamese',
  3198. LC_ba='Bashkir',
  3199. LC_be='Belarusian',
  3200. LC_bg='Bulgarian',
  3201. LC_bn='Bengali',
  3202. LC_bo='Tibetan',
  3203. LC_br='Breton',
  3204. LC_ca='Catalan',
  3205. LC_co='Corsican',
  3206. LC_cs='Czech',
  3207. LC_cy='Welsh',
  3208. LC_da='Danish',
  3209. LC_de='German',
  3210. LC_dv='Divehi',
  3211. LC_el='Greek',
  3212. LC_en='English',
  3213. LC_es='Spanish',
  3214. LC_et='Estonian',
  3215. LC_eu='Basque',
  3216. LC_fa='Persian',
  3217. LC_fi='Finnish',
  3218. LC_fo='Faroese',
  3219. LC_fr='French',
  3220. LC_gd='Scottish Gaelic',
  3221. LC_gl='Galician',
  3222. LC_gu='Gujarati',
  3223. LC_he='Hebrew',
  3224. LC_hi='Hindi',
  3225. LC_hr='Croatian',
  3226. LC_hu='Hungarian',
  3227. LC_hy='Armenian',
  3228. LC_id='Indonesian',
  3229. LC_ig='Igbo',
  3230. LC_is='Icelandic',
  3231. LC_it='Italian',
  3232. LC_ja='Japanese',
  3233. LC_ka='Georgian',
  3234. LC_kk='Kazakh',
  3235. LC_km='Khmer',
  3236. LC_kn='Kannada',
  3237. LC_ko='Korean',
  3238. LC_lb='Luxembourgish',
  3239. LC_lo='Lao',
  3240. LC_lt='Lithuanian',
  3241. LC_lv='Latvian',
  3242. LC_mi='Maori',
  3243. LC_ml='Malayalam',
  3244. LC_mr='Marathi',
  3245. LC_ms='Malay',
  3246. LC_mt='Maltese',
  3247. LC_ne='Nepali',
  3248. LC_nl='Dutch',
  3249. LC_no='Norwegian',
  3250. LC_oc='Occitan',
  3251. LC_or='Oriya',
  3252. LC_pl='Polish',
  3253. LC_ps='Pashto',
  3254. LC_pt='Portuguese',
  3255. LC_qu='Quechua',
  3256. LC_ro='Romanian',
  3257. LC_ru='Russian',
  3258. LC_rw='Kinyarwanda',
  3259. LC_sa='Sanskrit',
  3260. LC_si='Sinhala',
  3261. LC_sk='Slovak',
  3262. LC_sl='Slovenian',
  3263. LC_sq='Albanian',
  3264. LC_sv='Swedish',
  3265. LC_ta='Tamil',
  3266. LC_te='Telugu',
  3267. LC_th='Thai',
  3268. LC_tk='Turkmen',
  3269. LC_tr='Turkish',
  3270. LC_tt='Tatar',
  3271. LC_uk='Ukrainian',
  3272. LC_ur='Urdu',
  3273. LC_vi='Vietnamese',
  3274. LC_wo='Wolof',
  3275. LC_yo='Yoruba',
  3276. LC_zh='Chinese';
  3277. //@}
  3278. /**
  3279. * Return list of languages indexed by ISO 639-1 language code
  3280. * @return array
  3281. **/
  3282. function languages() {
  3283. return \Base::instance()->constants($this,'LC_');
  3284. }
  3285. /**
  3286. * Return list of countries indexed by ISO 3166-1 country code
  3287. * @return array
  3288. **/
  3289. function countries() {
  3290. return \Base::instance()->constants($this,'CC_');
  3291. }
  3292. }
  3293. //! Container for singular object instances
  3294. final class Registry {
  3295. private static
  3296. //! Object catalog
  3297. $table;
  3298. /**
  3299. * Return TRUE if object exists in catalog
  3300. * @return bool
  3301. * @param $key string
  3302. **/
  3303. static function exists($key) {
  3304. return isset(self::$table[$key]);
  3305. }
  3306. /**
  3307. * Add object to catalog
  3308. * @return object
  3309. * @param $key string
  3310. * @param $obj object
  3311. **/
  3312. static function set($key,$obj) {
  3313. return self::$table[$key]=$obj;
  3314. }
  3315. /**
  3316. * Retrieve object from catalog
  3317. * @return object
  3318. * @param $key string
  3319. **/
  3320. static function get($key) {
  3321. return self::$table[$key];
  3322. }
  3323. /**
  3324. * Delete object from catalog
  3325. * @return NULL
  3326. * @param $key string
  3327. **/
  3328. static function clear($key) {
  3329. self::$table[$key]=NULL;
  3330. unset(self::$table[$key]);
  3331. }
  3332. //! Prohibit cloning
  3333. private function __clone() {
  3334. }
  3335. //! Prohibit instantiation
  3336. private function __construct() {
  3337. }
  3338. }
  3339. return Base::instance();