web.php 31 KB

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