web.php 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932
  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. //! Wrapper for various HTTP utilities
  16. class Web extends Prefab {
  17. //@{ Error messages
  18. const
  19. E_Request='No suitable HTTP request engine found';
  20. //@}
  21. protected
  22. //! HTTP request engine
  23. $wrapper;
  24. /**
  25. * Detect MIME type using file extension
  26. * @return string
  27. * @param $file string
  28. **/
  29. function mime($file) {
  30. if (preg_match('/\w+$/',$file,$ext)) {
  31. $map=[
  32. 'au'=>'audio/basic',
  33. 'avi'=>'video/avi',
  34. 'bmp'=>'image/bmp',
  35. 'bz2'=>'application/x-bzip2',
  36. 'css'=>'text/css',
  37. 'dtd'=>'application/xml-dtd',
  38. 'doc'=>'application/msword',
  39. 'gif'=>'image/gif',
  40. 'gz'=>'application/x-gzip',
  41. 'hqx'=>'application/mac-binhex40',
  42. 'html?'=>'text/html',
  43. 'jar'=>'application/java-archive',
  44. 'jpe?g|jfif?'=>'image/jpeg',
  45. 'js'=>'application/x-javascript',
  46. 'midi'=>'audio/x-midi',
  47. 'mp3'=>'audio/mpeg',
  48. 'mpe?g'=>'video/mpeg',
  49. 'ogg'=>'audio/vorbis',
  50. 'pdf'=>'application/pdf',
  51. 'png'=>'image/png',
  52. 'ppt'=>'application/vnd.ms-powerpoint',
  53. 'ps'=>'application/postscript',
  54. 'qt'=>'video/quicktime',
  55. 'ram?'=>'audio/x-pn-realaudio',
  56. 'rdf'=>'application/rdf',
  57. 'rtf'=>'application/rtf',
  58. 'sgml?'=>'text/sgml',
  59. 'sit'=>'application/x-stuffit',
  60. 'svg'=>'image/svg+xml',
  61. 'swf'=>'application/x-shockwave-flash',
  62. 'tgz'=>'application/x-tar',
  63. 'tiff'=>'image/tiff',
  64. 'txt'=>'text/plain',
  65. 'wav'=>'audio/wav',
  66. 'xls'=>'application/vnd.ms-excel',
  67. 'xml'=>'application/xml',
  68. 'zip'=>'application/x-zip-compressed'
  69. ];
  70. foreach ($map as $key=>$val)
  71. if (preg_match('/'.$key.'/',strtolower($ext[0])))
  72. return $val;
  73. }
  74. return 'application/octet-stream';
  75. }
  76. /**
  77. * Return the MIME types stated in the HTTP Accept header as an array;
  78. * If a list of MIME types is specified, return the best match; or
  79. * FALSE if none found
  80. * @return array|string|FALSE
  81. * @param $list string|array
  82. **/
  83. function acceptable($list=NULL) {
  84. $accept=[];
  85. foreach (explode(',',str_replace(' ','',@$_SERVER['HTTP_ACCEPT']))
  86. as $mime)
  87. if (preg_match('/(.+?)(?:;q=([\d\.]+)|$)/',$mime,$parts))
  88. $accept[$parts[1]]=isset($parts[2])?$parts[2]:1;
  89. if (!$accept)
  90. $accept['*/*']=1;
  91. else {
  92. krsort($accept);
  93. arsort($accept);
  94. }
  95. if ($list) {
  96. if (is_string($list))
  97. $list=explode(',',$list);
  98. foreach ($accept as $mime=>$q)
  99. if ($q && $out=preg_grep('/'.
  100. str_replace('\*','.*',preg_quote($mime,'/')).'/',$list))
  101. return current($out);
  102. return FALSE;
  103. }
  104. return $accept;
  105. }
  106. /**
  107. * Transmit file to HTTP client; Return file size if successful,
  108. * FALSE otherwise
  109. * @return int|FALSE
  110. * @param $file string
  111. * @param $mime string
  112. * @param $kbps int
  113. * @param $force bool
  114. * @param $name string
  115. * @param $flush bool
  116. **/
  117. function send($file,$mime=NULL,$kbps=0,$force=TRUE,$name=NULL,$flush=TRUE) {
  118. if (!is_file($file))
  119. return FALSE;
  120. $size=filesize($file);
  121. if (PHP_SAPI!='cli') {
  122. header('Content-Type: '.($mime?:$this->mime($file)));
  123. if ($force)
  124. header('Content-Disposition: attachment; '.
  125. 'filename="'.($name!==NULL?$name:basename($file)).'"');
  126. header('Accept-Ranges: bytes');
  127. header('Content-Length: '.$size);
  128. header('X-Powered-By: '.Base::instance()->PACKAGE);
  129. }
  130. if (!$kbps && $flush) {
  131. while (ob_get_level())
  132. ob_end_clean();
  133. readfile($file);
  134. }
  135. else {
  136. $ctr=0;
  137. $handle=fopen($file,'rb');
  138. $start=microtime(TRUE);
  139. while (!feof($handle) &&
  140. ($info=stream_get_meta_data($handle)) &&
  141. !$info['timed_out'] && !connection_aborted()) {
  142. if ($kbps) {
  143. // Throttle output
  144. $ctr++;
  145. if ($ctr/$kbps>$elapsed=microtime(TRUE)-$start)
  146. usleep(1e6*($ctr/$kbps-$elapsed));
  147. }
  148. // Send 1KiB and reset timer
  149. echo fread($handle,1024);
  150. if ($flush) {
  151. ob_flush();
  152. flush();
  153. }
  154. }
  155. fclose($handle);
  156. }
  157. return $size;
  158. }
  159. /**
  160. * Receive file(s) from HTTP client
  161. * @return array|bool
  162. * @param $func callback
  163. * @param $overwrite bool
  164. * @param $slug callback|bool
  165. **/
  166. function receive($func=NULL,$overwrite=FALSE,$slug=TRUE) {
  167. $fw=Base::instance();
  168. $dir=$fw->UPLOADS;
  169. if (!is_dir($dir))
  170. mkdir($dir,Base::MODE,TRUE);
  171. if ($fw->VERB=='PUT') {
  172. $tmp=$fw->TEMP.$fw->SEED.'.'.$fw->hash(uniqid());
  173. if (!$fw->RAW)
  174. $fw->write($tmp,$fw->BODY);
  175. else {
  176. $src=@fopen('php://input','r');
  177. $dst=@fopen($tmp,'w');
  178. if (!$src || !$dst)
  179. return FALSE;
  180. while (!feof($src) &&
  181. ($info=stream_get_meta_data($src)) &&
  182. !$info['timed_out'] && $str=fgets($src,4096))
  183. fputs($dst,$str,strlen($str));
  184. fclose($dst);
  185. fclose($src);
  186. }
  187. $base=basename($fw->URI);
  188. $file=[
  189. 'name'=>$dir.
  190. ($slug && preg_match('/(.+?)(\.\w+)?$/',$base,$parts)?
  191. (is_callable($slug)?
  192. $slug($base):
  193. ($this->slug($parts[1]).
  194. (isset($parts[2])?$parts[2]:''))):
  195. $base),
  196. 'tmp_name'=>$tmp,
  197. 'type'=>$this->mime($base),
  198. 'size'=>filesize($tmp)
  199. ];
  200. return (!file_exists($file['name']) || $overwrite) &&
  201. (!$func || $fw->call($func,[$file])!==FALSE) &&
  202. rename($tmp,$file['name']);
  203. }
  204. $fetch=function($arr) use(&$fetch) {
  205. if (!is_array($arr))
  206. return [$arr];
  207. $data=[];
  208. foreach($arr as $k=>$sub)
  209. $data=array_merge($data,$fetch($sub));
  210. return $data;
  211. };
  212. $out=[];
  213. foreach ($_FILES as $name=>$item) {
  214. $files=[];
  215. foreach ($item as $k=>$mix)
  216. foreach ($fetch($mix) as $i=>$val)
  217. $files[$i][$k]=$val;
  218. foreach ($files as $file) {
  219. if (empty($file['name']))
  220. continue;
  221. $base=basename($file['name']);
  222. $file['name']=$dir.
  223. ($slug && preg_match('/(.+?)(\.\w+)?$/',$base,$parts)?
  224. (is_callable($slug)?
  225. $slug($base,$name):
  226. ($this->slug($parts[1]).
  227. (isset($parts[2])?$parts[2]:''))):
  228. $base);
  229. $out[$file['name']]=!$file['error'] &&
  230. (!file_exists($file['name']) || $overwrite) &&
  231. (!$func || $fw->call($func,[$file,$name])!==FALSE) &&
  232. move_uploaded_file($file['tmp_name'],$file['name']);
  233. }
  234. }
  235. return $out;
  236. }
  237. /**
  238. * Return upload progress in bytes, FALSE on failure
  239. * @return int|FALSE
  240. * @param $id string
  241. **/
  242. function progress($id) {
  243. // ID returned by session.upload_progress.name
  244. return ini_get('session.upload_progress.enabled') &&
  245. isset($_SESSION[$id]['bytes_processed'])?
  246. $_SESSION[$id]['bytes_processed']:FALSE;
  247. }
  248. /**
  249. * HTTP request via cURL
  250. * @return array
  251. * @param $url string
  252. * @param $options array
  253. **/
  254. protected function _curl($url,$options) {
  255. $curl=curl_init($url);
  256. if (!ini_get('open_basedir'))
  257. curl_setopt($curl,CURLOPT_FOLLOWLOCATION,
  258. $options['follow_location']);
  259. curl_setopt($curl,CURLOPT_MAXREDIRS,
  260. $options['max_redirects']);
  261. curl_setopt($curl,CURLOPT_PROTOCOLS,CURLPROTO_HTTP|CURLPROTO_HTTPS);
  262. curl_setopt($curl,CURLOPT_REDIR_PROTOCOLS,CURLPROTO_HTTP|CURLPROTO_HTTPS);
  263. curl_setopt($curl,CURLOPT_CUSTOMREQUEST,$options['method']);
  264. if (isset($options['header']))
  265. curl_setopt($curl,CURLOPT_HTTPHEADER,$options['header']);
  266. if (isset($options['content']))
  267. curl_setopt($curl,CURLOPT_POSTFIELDS,$options['content']);
  268. if (isset($options['proxy']))
  269. curl_setopt($curl,CURLOPT_PROXY,$options['proxy']);
  270. curl_setopt($curl,CURLOPT_ENCODING,'gzip,deflate');
  271. $timeout=isset($options['timeout'])?
  272. $options['timeout']:
  273. ini_get('default_socket_timeout');
  274. curl_setopt($curl,CURLOPT_CONNECTTIMEOUT,$timeout);
  275. curl_setopt($curl,CURLOPT_TIMEOUT,$timeout);
  276. $headers=[];
  277. curl_setopt($curl,CURLOPT_HEADERFUNCTION,
  278. // Callback for response headers
  279. function($curl,$line) use(&$headers) {
  280. if ($trim=trim($line))
  281. $headers[]=$trim;
  282. return strlen($line);
  283. }
  284. );
  285. curl_setopt($curl,CURLOPT_SSL_VERIFYHOST,2);
  286. curl_setopt($curl,CURLOPT_SSL_VERIFYPEER,FALSE);
  287. ob_start();
  288. curl_exec($curl);
  289. $err=curl_error($curl);
  290. curl_close($curl);
  291. $body=ob_get_clean();
  292. if (!$err &&
  293. $options['follow_location'] &&
  294. preg_grep('/HTTP\/1\.\d 3\d{2}/',$headers) &&
  295. preg_match('/^Location: (.+)$/m',implode(PHP_EOL,$headers),$loc)) {
  296. $options['max_redirects']--;
  297. if($loc[1][0] == '/') {
  298. $parts=parse_url($url);
  299. $loc[1]=$parts['scheme'].'://'.$parts['host'].
  300. ((isset($parts['port']) && !in_array($parts['port'],[80,443]))
  301. ?':'.$parts['port']:'').$loc[1];
  302. }
  303. return $this->request($loc[1],$options);
  304. }
  305. return [
  306. 'body'=>$body,
  307. 'headers'=>$headers,
  308. 'engine'=>'cURL',
  309. 'cached'=>FALSE,
  310. 'error'=>$err
  311. ];
  312. }
  313. /**
  314. * HTTP request via PHP stream wrapper
  315. * @return array
  316. * @param $url string
  317. * @param $options array
  318. **/
  319. protected function _stream($url,$options) {
  320. $eol="\r\n";
  321. if (isset($options['proxy'])) {
  322. $options['proxy']=preg_replace('/https?/i','tcp',$options['proxy']);
  323. $options['request_fulluri']=true;
  324. if (preg_match('/socks4?/i',$options['proxy']))
  325. return $this->_socket($url,$options);
  326. }
  327. $options['header']=implode($eol,$options['header']);
  328. $body=@file_get_contents($url,FALSE,
  329. stream_context_create(['http'=>$options]));
  330. $headers=isset($http_response_header)?
  331. $http_response_header:[];
  332. $err='';
  333. if (is_string($body)) {
  334. $match=NULL;
  335. foreach ($headers as $header)
  336. if (preg_match('/Content-Encoding: (.+)/',$header,$match))
  337. break;
  338. if ($match)
  339. switch ($match[1]) {
  340. case 'gzip':
  341. $body=gzdecode($body);
  342. break;
  343. case 'deflate':
  344. $body=gzuncompress($body);
  345. break;
  346. }
  347. }
  348. else {
  349. $tmp=error_get_last();
  350. $err=$tmp['message'];
  351. }
  352. return [
  353. 'body'=>$body,
  354. 'headers'=>$headers,
  355. 'engine'=>'stream',
  356. 'cached'=>FALSE,
  357. 'error'=>$err
  358. ];
  359. }
  360. /**
  361. * HTTP request via low-level TCP/IP socket
  362. * @return array
  363. * @param $url string
  364. * @param $options array
  365. **/
  366. protected function _socket($url,$options) {
  367. $eol="\r\n";
  368. $headers=[];
  369. $body='';
  370. $parts=parse_url($url);
  371. $hostname=$parts['host'];
  372. $proxy=false;
  373. if ($parts['scheme']=='https')
  374. $parts['host']='ssl://'.$parts['host'];
  375. if (empty($parts['port']))
  376. $parts['port']=$parts['scheme']=='https'?443:80;
  377. if (empty($parts['path']))
  378. $parts['path']='/';
  379. if (empty($parts['query']))
  380. $parts['query']='';
  381. if (isset($options['proxy'])) {
  382. $req=$url;
  383. $pp=parse_url($options['proxy']);
  384. $proxy=$pp['scheme'];
  385. if ($pp['scheme']=='https')
  386. $pp['host']='ssl://'.$pp['host'];
  387. if (empty($pp['port']))
  388. $pp['port']=$pp['scheme']=='https'?443:80;
  389. $socket=@fsockopen($pp['host'],$pp['port'],$code,$err);
  390. } else {
  391. $req=$parts['path'].($parts['query']?('?'.$parts['query']):'');
  392. $socket=@fsockopen($parts['host'],$parts['port'],$code,$err);
  393. }
  394. if ($socket) {
  395. stream_set_blocking($socket,TRUE);
  396. stream_set_timeout($socket,isset($options['timeout'])?
  397. $options['timeout']:ini_get('default_socket_timeout'));
  398. if ($proxy=='socks4') {
  399. // SOCKS4; http://en.wikipedia.org/wiki/SOCKS#Protocol
  400. $packet="\x04\x01".pack("n", $parts['port']).
  401. pack("H*",dechex(ip2long(gethostbyname($hostname))))."\0";
  402. fputs($socket, $packet, strlen($packet));
  403. $response=fread($socket, 9);
  404. if (strlen($response)==8 && (ord($response[0])==0 || ord($response[0])==4)
  405. && ord($response[1])==90) {
  406. $options['header'][]='Host: '.$hostname;
  407. } else
  408. $err='Socket Status '.ord($response[1]);
  409. }
  410. fputs($socket,$options['method'].' '.$req.' HTTP/1.0'.$eol);
  411. fputs($socket,implode($eol,$options['header']).$eol.$eol);
  412. if (isset($options['content']))
  413. fputs($socket,$options['content'].$eol);
  414. // Get response
  415. $content='';
  416. while (!feof($socket) &&
  417. ($info=stream_get_meta_data($socket)) &&
  418. !$info['timed_out'] && !connection_aborted() &&
  419. $str=fgets($socket,4096))
  420. $content.=$str;
  421. fclose($socket);
  422. $html=explode($eol.$eol,$content,2);
  423. $body=isset($html[1])?$html[1]:'';
  424. $headers=array_merge($headers,$current=explode($eol,$html[0]));
  425. $match=NULL;
  426. foreach ($current as $header)
  427. if (preg_match('/Content-Encoding: (.+)/',$header,$match))
  428. break;
  429. if ($match)
  430. switch ($match[1]) {
  431. case 'gzip':
  432. $body=gzdecode($body);
  433. break;
  434. case 'deflate':
  435. $body=gzuncompress($body);
  436. break;
  437. }
  438. if ($options['follow_location'] &&
  439. preg_grep('/HTTP\/1\.\d 3\d{2}/',$headers) &&
  440. preg_match('/Location: (.+?)'.preg_quote($eol).'/',
  441. $html[0],$loc)) {
  442. $options['max_redirects']--;
  443. return $this->request($loc[1],$options);
  444. }
  445. }
  446. return [
  447. 'body'=>$body,
  448. 'headers'=>$headers,
  449. 'engine'=>'socket',
  450. 'cached'=>FALSE,
  451. 'error'=>$err
  452. ];
  453. }
  454. /**
  455. * Specify the HTTP request engine to use; If not available,
  456. * fall back to an applicable substitute
  457. * @return string
  458. * @param $arg string
  459. **/
  460. function engine($arg='curl') {
  461. $arg=strtolower($arg);
  462. $flags=[
  463. 'curl'=>extension_loaded('curl'),
  464. 'stream'=>ini_get('allow_url_fopen'),
  465. 'socket'=>function_exists('fsockopen')
  466. ];
  467. if ($flags[$arg])
  468. return $this->wrapper=$arg;
  469. foreach ($flags as $key=>$val)
  470. if ($val)
  471. return $this->wrapper=$key;
  472. user_error(self::E_Request,E_USER_ERROR);
  473. }
  474. /**
  475. * Replace old headers with new elements
  476. * @return NULL
  477. * @param $old array
  478. * @param $new string|array
  479. **/
  480. function subst(array &$old,$new) {
  481. if (is_string($new))
  482. $new=[$new];
  483. foreach ($new as $hdr) {
  484. $old=preg_grep('/'.preg_quote(strstr($hdr,':',TRUE),'/').':.+/',
  485. $old,PREG_GREP_INVERT);
  486. array_push($old,$hdr);
  487. }
  488. }
  489. /**
  490. * Submit HTTP request; Use HTTP context options (described in
  491. * http://www.php.net/manual/en/context.http.php) if specified;
  492. * Cache the page as instructed by remote server
  493. * @return array|FALSE
  494. * @param $url string
  495. * @param $options array
  496. **/
  497. function request($url,array $options=NULL) {
  498. $fw=Base::instance();
  499. $parts=parse_url($url);
  500. if (empty($parts['scheme'])) {
  501. // Local URL
  502. $url=$fw->SCHEME.'://'.$fw->HOST.
  503. (in_array($fw->PORT,[80,443])?'':(':'.$fw->PORT)).
  504. ($url[0]!='/'?($fw->BASE.'/'):'').$url;
  505. $parts=parse_url($url);
  506. }
  507. elseif (!preg_match('/https?/',$parts['scheme']))
  508. return FALSE;
  509. if (!is_array($options))
  510. $options=[];
  511. if (empty($options['header']))
  512. $options['header']=[];
  513. elseif (is_string($options['header']))
  514. $options['header']=[$options['header']];
  515. if (!$this->wrapper)
  516. $this->engine();
  517. if ($this->wrapper!='stream') {
  518. // PHP streams can't cope with redirects when Host header is set
  519. $this->subst($options['header'],'Host: '.$parts['host']);
  520. }
  521. $this->subst($options['header'],
  522. [
  523. 'Accept-Encoding: gzip,deflate',
  524. 'User-Agent: '.(isset($options['user_agent'])?
  525. $options['user_agent']:
  526. 'Mozilla/5.0 (compatible; '.php_uname('s').')'),
  527. 'Connection: close'
  528. ]
  529. );
  530. if (isset($options['content']) && is_string($options['content'])) {
  531. if ($options['method']=='POST' &&
  532. !preg_grep('/^Content-Type:/',$options['header']))
  533. $this->subst($options['header'],
  534. 'Content-Type: application/x-www-form-urlencoded');
  535. $this->subst($options['header'],
  536. 'Content-Length: '.strlen($options['content']));
  537. }
  538. if (isset($parts['user'],$parts['pass']))
  539. $this->subst($options['header'],
  540. 'Authorization: Basic '.
  541. base64_encode($parts['user'].':'.$parts['pass'])
  542. );
  543. $options+=[
  544. 'method'=>'GET',
  545. 'header'=>$options['header'],
  546. 'follow_location'=>TRUE,
  547. 'max_redirects'=>20,
  548. 'ignore_errors'=>FALSE
  549. ];
  550. $eol="\r\n";
  551. if ($fw->CACHE &&
  552. preg_match('/GET|HEAD/',$options['method'])) {
  553. $cache=Cache::instance();
  554. if ($cache->exists(
  555. $hash=$fw->hash($options['method'].' '.$url).'.url',$data)) {
  556. if (preg_match('/Last-Modified: (.+?)'.preg_quote($eol).'/',
  557. implode($eol,$data['headers']),$mod))
  558. $this->subst($options['header'],
  559. 'If-Modified-Since: '.$mod[1]);
  560. }
  561. }
  562. $result=$this->{'_'.$this->wrapper}($url,$options);
  563. if ($result && isset($cache)) {
  564. if (preg_match('/HTTP\/1\.\d 304/',
  565. implode($eol,$result['headers']))) {
  566. $result=$cache->get($hash);
  567. $result['cached']=TRUE;
  568. }
  569. elseif (preg_match('/Cache-Control:(?:.*)max-age=(\d+)(?:,?.*'.
  570. preg_quote($eol).')/',implode($eol,$result['headers']),$exp))
  571. $cache->set($hash,$result,$exp[1]);
  572. }
  573. $req=[$options['method'].' '.$url];
  574. foreach ($options['header'] as $header)
  575. array_push($req,$header);
  576. return array_merge(['request'=>$req],$result);
  577. }
  578. /**
  579. * Strip Javascript/CSS files of extraneous whitespaces and comments;
  580. * Return combined output as a minified string
  581. * @return string
  582. * @param $files string|array
  583. * @param $mime string
  584. * @param $header bool
  585. * @param $path string
  586. **/
  587. function minify($files,$mime=NULL,$header=TRUE,$path=NULL) {
  588. $fw=Base::instance();
  589. if (is_string($files))
  590. $files=$fw->split($files);
  591. if (!$mime)
  592. $mime=$this->mime($files[0]);
  593. preg_match('/\w+$/',$files[0],$ext);
  594. $cache=Cache::instance();
  595. $dst='';
  596. if (!isset($path))
  597. $path=$fw->UI.';./';
  598. foreach ($fw->split($path,FALSE) as $dir)
  599. foreach ($files as $file)
  600. if (is_file($save=$fw->fixslashes($dir.$file)) &&
  601. is_bool(strpos($save,'../')) &&
  602. preg_match('/\.(css|js)$/i',$file)) {
  603. if ($fw->CACHE &&
  604. ($cached=$cache->exists(
  605. $hash=$fw->hash($save).'.'.$ext[0],$data)) &&
  606. $cached[0]>filemtime($save))
  607. $dst.=$data;
  608. else {
  609. $data='';
  610. $src=$fw->read($save);
  611. for ($ptr=0,$len=strlen($src);$ptr<$len;) {
  612. if (preg_match('/^@import\h+url'.
  613. '\(\h*([\'"])((?!(?:https?:)?\/\/).+?)\1\h*\)[^;]*;/',
  614. substr($src,$ptr),$parts)) {
  615. $path=dirname($file);
  616. $data.=$this->minify(
  617. ($path?($path.'/'):'').$parts[2],
  618. $mime,$header
  619. );
  620. $ptr+=strlen($parts[0]);
  621. continue;
  622. }
  623. if ($src[$ptr]=='/') {
  624. if ($src[$ptr+1]=='*') {
  625. // Multiline comment
  626. $str=strstr(
  627. substr($src,$ptr+2),'*/',TRUE);
  628. $ptr+=strlen($str)+4;
  629. }
  630. elseif ($src[$ptr+1]=='/') {
  631. // Single-line comment
  632. $str=strstr(
  633. substr($src,$ptr+2),"\n",TRUE);
  634. $ptr+=(empty($str))?
  635. strlen(substr($src,$ptr)):strlen($str)+2;
  636. }
  637. else {
  638. // Presume it's a regex pattern
  639. $regex=TRUE;
  640. // Backtrack and validate
  641. for ($ofs=$ptr;$ofs;$ofs--) {
  642. // Pattern should be preceded by
  643. // open parenthesis, colon,
  644. // object property or operator
  645. if (preg_match(
  646. '/(return|[(:=!+\-*&|])$/',
  647. substr($src,0,$ofs))) {
  648. $data.='/';
  649. $ptr++;
  650. while ($ptr<$len) {
  651. $data.=$src[$ptr];
  652. $ptr++;
  653. if ($src[$ptr-1]=='\\') {
  654. $data.=$src[$ptr];
  655. $ptr++;
  656. }
  657. elseif ($src[$ptr-1]=='/')
  658. break;
  659. }
  660. break;
  661. }
  662. elseif (!ctype_space($src[$ofs-1])) {
  663. // Not a regex pattern
  664. $regex=FALSE;
  665. break;
  666. }
  667. }
  668. if (!$regex) {
  669. // Division operator
  670. $data.=$src[$ptr];
  671. $ptr++;
  672. }
  673. }
  674. continue;
  675. }
  676. if (in_array($src[$ptr],['\'','"'])) {
  677. $match=$src[$ptr];
  678. $data.=$match;
  679. $ptr++;
  680. // String literal
  681. while ($ptr<$len) {
  682. $data.=$src[$ptr];
  683. $ptr++;
  684. if ($src[$ptr-1]=='\\') {
  685. $data.=$src[$ptr];
  686. $ptr++;
  687. }
  688. elseif ($src[$ptr-1]==$match)
  689. break;
  690. }
  691. continue;
  692. }
  693. if (ctype_space($src[$ptr])) {
  694. if ($ptr+1<strlen($src) &&
  695. preg_match('/[\w'.($ext[0]=='css'?
  696. '#\.%+\-*()\[\]':'\$').']{2}|'.
  697. '[+\-]{2}/',
  698. substr($data,-1).$src[$ptr+1]) ||
  699. ($ext[0]=='css' && $ptr+2<strlen($src) &&
  700. preg_match('/:\w/',substr($src,$ptr+1,2))))
  701. $data.=' ';
  702. $ptr++;
  703. continue;
  704. }
  705. $data.=$src[$ptr];
  706. $ptr++;
  707. }
  708. if ($ext[0]=='css')
  709. $data=str_replace(';}','}',$data);
  710. if ($fw->CACHE)
  711. $cache->set($hash,$data);
  712. $dst.=$data;
  713. }
  714. }
  715. if (PHP_SAPI!='cli' && $header)
  716. header('Content-Type: '.$mime.'; charset='.$fw->ENCODING);
  717. return $dst;
  718. }
  719. /**
  720. * Retrieve RSS feed and return as an array
  721. * @return array|FALSE
  722. * @param $url string
  723. * @param $max int
  724. * @param $tags string
  725. **/
  726. function rss($url,$max=10,$tags=NULL) {
  727. if (!$data=$this->request($url))
  728. return FALSE;
  729. // Suppress errors caused by invalid XML structures
  730. libxml_use_internal_errors(TRUE);
  731. $xml=simplexml_load_string($data['body'],
  732. NULL,LIBXML_NOBLANKS|LIBXML_NOERROR);
  733. if (!is_object($xml))
  734. return FALSE;
  735. $out=[];
  736. if (isset($xml->channel)) {
  737. $out['source']=(string)$xml->channel->title;
  738. $max=min($max,count($xml->channel->item));
  739. for ($i=0;$i<$max;$i++) {
  740. $item=$xml->channel->item[$i];
  741. $list=[''=>NULL]+$item->getnamespaces(TRUE);
  742. $fields=[];
  743. foreach ($list as $ns=>$uri)
  744. foreach ($item->children($uri) as $key=>$val)
  745. $fields[$ns.($ns?':':'').$key]=(string)$val;
  746. $out['feed'][]=$fields;
  747. }
  748. }
  749. else
  750. return FALSE;
  751. Base::instance()->scrub($out,$tags);
  752. return $out;
  753. }
  754. /**
  755. * Retrieve information from whois server
  756. * @return string|FALSE
  757. * @param $addr string
  758. * @param $server string
  759. **/
  760. function whois($addr,$server='whois.internic.net') {
  761. $socket=@fsockopen($server,43,$errno,$errstr);
  762. if (!$socket)
  763. // Can't establish connection
  764. return FALSE;
  765. // Set connection timeout parameters
  766. stream_set_blocking($socket,FALSE);
  767. stream_set_timeout($socket,ini_get('default_socket_timeout'));
  768. // Send request
  769. fputs($socket,$addr."\r\n");
  770. $info=stream_get_meta_data($socket);
  771. // Get response
  772. $response='';
  773. while (!feof($socket) && !$info['timed_out']) {
  774. $response.=fgets($socket,4096); // MDFK97
  775. $info=stream_get_meta_data($socket);
  776. }
  777. fclose($socket);
  778. return $info['timed_out']?FALSE:trim($response);
  779. }
  780. /**
  781. * Return preset diacritics translation table
  782. * @return array
  783. **/
  784. function diacritics() {
  785. return [
  786. 'Ǎ'=>'A','А'=>'A','Ā'=>'A','Ă'=>'A','Ą'=>'A','Å'=>'A',
  787. 'Ǻ'=>'A','Ä'=>'Ae','Á'=>'A','À'=>'A','Ã'=>'A','Â'=>'A',
  788. 'Æ'=>'AE','Ǽ'=>'AE','Б'=>'B','Ç'=>'C','Ć'=>'C','Ĉ'=>'C',
  789. 'Č'=>'C','Ċ'=>'C','Ц'=>'C','Ч'=>'Ch','Ð'=>'Dj','Đ'=>'Dj',
  790. 'Ď'=>'Dj','Д'=>'Dj','É'=>'E','Ę'=>'E','Ё'=>'E','Ė'=>'E',
  791. 'Ê'=>'E','Ě'=>'E','Ē'=>'E','È'=>'E','Е'=>'E','Э'=>'E',
  792. 'Ë'=>'E','Ĕ'=>'E','Ф'=>'F','Г'=>'G','Ģ'=>'G','Ġ'=>'G',
  793. 'Ĝ'=>'G','Ğ'=>'G','Х'=>'H','Ĥ'=>'H','Ħ'=>'H','Ï'=>'I',
  794. 'Ĭ'=>'I','İ'=>'I','Į'=>'I','Ī'=>'I','Í'=>'I','Ì'=>'I',
  795. 'И'=>'I','Ǐ'=>'I','Ĩ'=>'I','Î'=>'I','IJ'=>'IJ','Ĵ'=>'J',
  796. 'Й'=>'J','Я'=>'Ja','Ю'=>'Ju','К'=>'K','Ķ'=>'K','Ĺ'=>'L',
  797. 'Л'=>'L','Ł'=>'L','Ŀ'=>'L','Ļ'=>'L','Ľ'=>'L','М'=>'M',
  798. 'Н'=>'N','Ń'=>'N','Ñ'=>'N','Ņ'=>'N','Ň'=>'N','Ō'=>'O',
  799. 'О'=>'O','Ǿ'=>'O','Ǒ'=>'O','Ơ'=>'O','Ŏ'=>'O','Ő'=>'O',
  800. 'Ø'=>'O','Ö'=>'Oe','Õ'=>'O','Ó'=>'O','Ò'=>'O','Ô'=>'O',
  801. 'Œ'=>'OE','П'=>'P','Ŗ'=>'R','Р'=>'R','Ř'=>'R','Ŕ'=>'R',
  802. 'Ŝ'=>'S','Ş'=>'S','Š'=>'S','Ș'=>'S','Ś'=>'S','С'=>'S',
  803. 'Ш'=>'Sh','Щ'=>'Shch','Ť'=>'T','Ŧ'=>'T','Ţ'=>'T','Ț'=>'T',
  804. 'Т'=>'T','Ů'=>'U','Ű'=>'U','Ŭ'=>'U','Ũ'=>'U','Ų'=>'U',
  805. 'Ū'=>'U','Ǜ'=>'U','Ǚ'=>'U','Ù'=>'U','Ú'=>'U','Ü'=>'Ue',
  806. 'Ǘ'=>'U','Ǖ'=>'U','У'=>'U','Ư'=>'U','Ǔ'=>'U','Û'=>'U',
  807. 'В'=>'V','Ŵ'=>'W','Ы'=>'Y','Ŷ'=>'Y','Ý'=>'Y','Ÿ'=>'Y',
  808. 'Ź'=>'Z','З'=>'Z','Ż'=>'Z','Ž'=>'Z','Ж'=>'Zh','á'=>'a',
  809. 'ă'=>'a','â'=>'a','à'=>'a','ā'=>'a','ǻ'=>'a','å'=>'a',
  810. 'ä'=>'ae','ą'=>'a','ǎ'=>'a','ã'=>'a','а'=>'a','ª'=>'a',
  811. 'æ'=>'ae','ǽ'=>'ae','б'=>'b','č'=>'c','ç'=>'c','ц'=>'c',
  812. 'ċ'=>'c','ĉ'=>'c','ć'=>'c','ч'=>'ch','ð'=>'dj','ď'=>'dj',
  813. 'д'=>'dj','đ'=>'dj','э'=>'e','é'=>'e','ё'=>'e','ë'=>'e',
  814. 'ê'=>'e','е'=>'e','ĕ'=>'e','è'=>'e','ę'=>'e','ě'=>'e',
  815. 'ė'=>'e','ē'=>'e','ƒ'=>'f','ф'=>'f','ġ'=>'g','ĝ'=>'g',
  816. 'ğ'=>'g','г'=>'g','ģ'=>'g','х'=>'h','ĥ'=>'h','ħ'=>'h',
  817. 'ǐ'=>'i','ĭ'=>'i','и'=>'i','ī'=>'i','ĩ'=>'i','į'=>'i',
  818. 'ı'=>'i','ì'=>'i','î'=>'i','í'=>'i','ï'=>'i','ij'=>'ij',
  819. 'ĵ'=>'j','й'=>'j','я'=>'ja','ю'=>'ju','ķ'=>'k','к'=>'k',
  820. 'ľ'=>'l','ł'=>'l','ŀ'=>'l','ĺ'=>'l','ļ'=>'l','л'=>'l',
  821. 'м'=>'m','ņ'=>'n','ñ'=>'n','ń'=>'n','н'=>'n','ň'=>'n',
  822. 'ʼn'=>'n','ó'=>'o','ò'=>'o','ǒ'=>'o','ő'=>'o','о'=>'o',
  823. 'ō'=>'o','º'=>'o','ơ'=>'o','ŏ'=>'o','ô'=>'o','ö'=>'oe',
  824. 'õ'=>'o','ø'=>'o','ǿ'=>'o','œ'=>'oe','п'=>'p','р'=>'r',
  825. 'ř'=>'r','ŕ'=>'r','ŗ'=>'r','ſ'=>'s','ŝ'=>'s','ș'=>'s',
  826. 'š'=>'s','ś'=>'s','с'=>'s','ş'=>'s','ш'=>'sh','щ'=>'shch',
  827. 'ß'=>'ss','ţ'=>'t','т'=>'t','ŧ'=>'t','ť'=>'t','ț'=>'t',
  828. 'у'=>'u','ǘ'=>'u','ŭ'=>'u','û'=>'u','ú'=>'u','ų'=>'u',
  829. 'ù'=>'u','ű'=>'u','ů'=>'u','ư'=>'u','ū'=>'u','ǚ'=>'u',
  830. 'ǜ'=>'u','ǔ'=>'u','ǖ'=>'u','ũ'=>'u','ü'=>'ue','в'=>'v',
  831. 'ŵ'=>'w','ы'=>'y','ÿ'=>'y','ý'=>'y','ŷ'=>'y','ź'=>'z',
  832. 'ž'=>'z','з'=>'z','ż'=>'z','ж'=>'zh','ь'=>'','ъ'=>'',
  833. '\''=>'',
  834. ];
  835. }
  836. /**
  837. * Return a URL/filesystem-friendly version of string
  838. * @return string
  839. * @param $text string
  840. **/
  841. function slug($text) {
  842. return trim(strtolower(preg_replace('/([^\pL\pN])+/u','-',
  843. trim(strtr($text,Base::instance()->DIACRITICS+$this->diacritics())))),'-');
  844. }
  845. /**
  846. * Return chunk of text from standard Lorem Ipsum passage
  847. * @return string
  848. * @param $count int
  849. * @param $max int
  850. * @param $std bool
  851. **/
  852. function filler($count=1,$max=20,$std=TRUE) {
  853. $out='';
  854. if ($std)
  855. $out='Lorem ipsum dolor sit amet, consectetur adipisicing elit, '.
  856. 'sed do eiusmod tempor incididunt ut labore et dolore magna '.
  857. 'aliqua.';
  858. $rnd=explode(' ',
  859. 'a ab ad accusamus adipisci alias aliquam amet animi aperiam '.
  860. 'architecto asperiores aspernatur assumenda at atque aut beatae '.
  861. 'blanditiis cillum commodi consequatur corporis corrupti culpa '.
  862. 'cum cupiditate debitis delectus deleniti deserunt dicta '.
  863. 'dignissimos distinctio dolor ducimus duis ea eaque earum eius '.
  864. 'eligendi enim eos error esse est eum eveniet ex excepteur '.
  865. 'exercitationem expedita explicabo facere facilis fugiat harum '.
  866. 'hic id illum impedit in incidunt ipsa iste itaque iure iusto '.
  867. 'laborum laudantium libero magnam maiores maxime minim minus '.
  868. 'modi molestiae mollitia nam natus necessitatibus nemo neque '.
  869. 'nesciunt nihil nisi nobis non nostrum nulla numquam occaecati '.
  870. 'odio officia omnis optio pariatur perferendis perspiciatis '.
  871. 'placeat porro possimus praesentium proident quae quia quibus '.
  872. 'quo ratione recusandae reiciendis rem repellat reprehenderit '.
  873. 'repudiandae rerum saepe sapiente sequi similique sint soluta '.
  874. 'suscipit tempora tenetur totam ut ullam unde vel veniam vero '.
  875. 'vitae voluptas');
  876. for ($i=0,$add=$count-(int)$std;$i<$add;$i++) {
  877. shuffle($rnd);
  878. $words=array_slice($rnd,0,mt_rand(3,$max));
  879. $out.=' '.ucfirst(implode(' ',$words)).'.';
  880. }
  881. return $out;
  882. }
  883. }
  884. if (!function_exists('gzdecode')) {
  885. /**
  886. * Decode gzip-compressed string
  887. * @param $str string
  888. **/
  889. function gzdecode($str) {
  890. $fw=Base::instance();
  891. if (!is_dir($tmp=$fw->TEMP))
  892. mkdir($tmp,Base::MODE,TRUE);
  893. file_put_contents($file=$tmp.'/'.$fw->SEED.'.'.
  894. $fw->hash(uniqid(NULL,TRUE)).'.gz',$str,LOCK_EX);
  895. ob_start();
  896. readgzfile($file);
  897. $out=ob_get_clean();
  898. @unlink($file);
  899. return $out;
  900. }
  901. }