PageRenderTime 62ms CodeModel.GetById 30ms RepoModel.GetById 0ms app.codeStats 0ms

/php/lib/doc.php

https://gitlab.com/BillRocha/plim
PHP | 438 lines | 305 code | 58 blank | 75 comment | 51 complexity | 87434f6f72ff4f4d11ddca65c63a120f MD5 | raw file
Possible License(s): CC0-1.0
  1. <?php
  2. /**
  3. * Doc Factory for HTML
  4. * @copyright Bill Rocha - http://plus.google.com/+BillRocha
  5. * @license MIT & GLP2
  6. * @author Bill Rocha - prbr@ymail.com
  7. * @version 0.0.1
  8. * @package Qzumba\Doc
  9. * @access public
  10. * @since 0.0.1
  11. */
  12. namespace Lib;
  13. class Doc{
  14. private $name = '';
  15. private $cached = true;
  16. private $pathHtml = '';
  17. private $pathStyle = '';
  18. private $pathScript = '';
  19. private $header = null;
  20. private $body = null;
  21. private $footer = null;
  22. private $styles = [];
  23. private $scripts = [];
  24. private $forceCompress = false;
  25. private $values = [];
  26. private $content = '';
  27. private $tag = 'x:';
  28. /* Construct
  29. *
  30. */
  31. function __construct($name = 'default', $cached = true){
  32. $this->name = $name;
  33. $this->cached = $cached;
  34. $this->pathHtml = Q::html();
  35. $this->pathStyle = Q::style();
  36. $this->pathScript = Q::script();
  37. $this->header = $this->pathHtml.'header.html';
  38. $this->footer = $this->pathHtml.'footer.html';
  39. }
  40. function body($v = null){
  41. if($v === null) return $thi->body;
  42. $this->body = $this->pathHtml.$v.'.html';
  43. return $this;
  44. }
  45. function header($v = null){
  46. if($v === null) return $this->header;
  47. $this->header = $this->pathHtml.$v.'.html';
  48. return $this;
  49. }
  50. function footer($v = null){
  51. if($v === null) return $this->footer;
  52. $this->footer = $this->pathHtml.$v.'.html';
  53. return $this;
  54. }
  55. function cached($b = true){
  56. $this->cached = $b;
  57. return $this;
  58. }
  59. function render(){
  60. $this->content = file_get_contents($this->header);
  61. $this->content .= file_get_contents($this->body);
  62. $this->content .= file_get_contents($this->footer);
  63. if(QMODE == 'dev') $this->assets();
  64. if(QMODE == 'pro') {
  65. $this->assetsComp();
  66. $this->setContent(str_replace(["\r","\n","\t",' '], '', $this->getContent()));
  67. }
  68. $this->produce();
  69. if($this->cached) file_put_contents($this->pathHtml.$this->name.'_cache.html', $this->getContent());
  70. return $this;
  71. }
  72. /* Style list insert
  73. */
  74. function insertStyles($list){
  75. if(!is_array($list)) $list = [$list];
  76. $this->styles = $list;
  77. return $this;
  78. }
  79. /* Javascript list insert
  80. */
  81. function insertScripts($list){
  82. if(!is_array($list)) $list = [$list];
  83. $this->scripts = $list;
  84. return $this;
  85. }
  86. /* Força a compressão dos arquivos CSS e JS
  87. * -- para facilitar durante o desenvolvimento e testes.
  88. */
  89. function forceCompress($b = true){
  90. $this->forceCompress = $b;
  91. return $this;
  92. }
  93. private function assetsComp(){
  94. //CSS STYLES
  95. if(file_exists($this->pathStyle.$this->name.'_all.css') && !$this->forceCompress)
  96. $content = file_get_contents($this->pathStyle.$this->name.'_all.css');
  97. else {
  98. $content = '';
  99. foreach ($this->styles as $file) {
  100. $content .= exec('java -jar '.__DIR__.'/yc.jar "'.$this->pathStyle.$file.'.css"');
  101. }
  102. file_put_contents($this->pathStyle.$this->name.'_all.css', $content);
  103. $content = exec('java -jar '.__DIR__.'/yc.jar "'.$this->pathStyle.$this->name.'_all.css"');
  104. file_put_contents($this->pathStyle.$this->name.'_all.css', $content);
  105. }
  106. $this->val('style', '<style>'.$content.'</style>');
  107. //JAVASCRIPTS
  108. if(file_exists($this->pathScript.$this->name.'_all.js') && !$this->forceCompress)
  109. $content = file_get_contents($this->pathScript.$this->name.'_all.js');
  110. else {
  111. $content = ';';
  112. foreach ($this->scripts as $file) {
  113. $content .= exec('java -jar '.__DIR__.'/yc.jar "'.$this->pathScript.$file.'.js"');
  114. }
  115. file_put_contents($this->pathScript.$this->name.'_all.js', $content);
  116. $content = exec('java -jar '.__DIR__.'/yc.jar "'.$this->pathScript.$this->name.'_all.js"');
  117. file_put_contents($this->pathScript.$this->name.'_all.js', $content);
  118. }
  119. $this->val('script', '<script>var URL="'.URL.'",wsUri="'.Q::val('ws').'",upURL="'.Q::val('up').'";'.$content.'</script>');
  120. }
  121. /* Produção dos links ou arquivos compactados.
  122. * para Style e Javascript
  123. *
  124. * Em modo 'dev' gera somente os links;
  125. * Em modo 'pro' compacta e obfusca os arquivos e insere diretamente no HTML.
  126. */
  127. private function assets(){
  128. $s = '';
  129. foreach($this->styles as $f){
  130. $s .= '<link rel="stylesheet" href="'.URL.'css/'.$f.'.css">'."\n\t";
  131. }
  132. $this->val('style', $s);
  133. $s = '<script>var URL="'.URL.'",
  134. wsUri="'.Q::val('ws').'",
  135. upURL="'.Q::val('up').'"</script>';
  136. foreach($this->scripts as $f){
  137. $s .= "\n\t".'<script src="'.URL.'js/'.$f.'.js"></script>';
  138. }
  139. $this->val('script', $s);
  140. }
  141. /* SEND
  142. * Send headers & Output tris content
  143. *
  144. */
  145. function send() {
  146. ob_end_clean();
  147. ob_start('ob_gzhandler');
  148. header('Expires: ' . gmdate('D, d M Y H:i:s', time() + 31536000) . ' GMT');
  149. header('Cache-Control: must_revalidate, public, max-age=31536000');
  150. header('Server: Qzumba/BETA 0.0.8');//for safety ...
  151. header('X-Powered-By: START/1.3.0');//for safety ...
  152. exit($this->content);
  153. }
  154. /* Send cached version of compilation
  155. *
  156. */
  157. function sendCache(){
  158. $this->setContent(file_get_contents($this->pathHtml.$this->name.'_cache.html'));
  159. $this->send();
  160. }
  161. //Insere o conteúdo processado Html
  162. protected function setContent($content) {
  163. $this->content = $content;
  164. return $this;
  165. }
  166. //Pega o conteúdo processado Html
  167. protected function getContent() {
  168. return $this->content;
  169. }
  170. //Pega uma variável ou todas
  171. protected function getVar($var = null) {
  172. return ($var == null) ? $this->values : (isset($this->values[$var]) ? $this->values[$var] : false);
  173. }
  174. //Registra uma variável para o Layout
  175. function value($name, $value = null) { return $this->val($name, $value = null);}
  176. function val($name, $value = null) {
  177. if(is_string($name)) $this->values[$name] = $value;
  178. if(is_array($name)) $this->values = array_merge($this->values, $name);
  179. return $this;
  180. }
  181. /**
  182. * Renderiza o arquivo html.
  183. * Retorna um array com o produto da renderização ou 'ecoa' o resultado.
  184. *
  185. * @param bool $get Retorna o produto da renderização para um pós-tratamento
  186. * @return array|void
  187. */
  188. function produce($php = false, $brade = false, $sTag = true){
  189. //With blade ???
  190. if($brade) $this->setContent($this->blade($this->getContent()));
  191. //With ©sTag ???
  192. if($sTag) {
  193. $ponteiro = -1;
  194. $content = $this->getContent();
  195. //Loop de varredura para o arquivo HTML
  196. while($ret = $this->sTag($content, $ponteiro)){
  197. $ponteiro = 0 + $ret['-final-'];
  198. $vartemp = '';
  199. //constant URL
  200. if($ret['-tipo-'] == 'var' && $ret['var'] == 'url') $vartemp = URL;
  201. elseif($ret['-tipo-'] == 'var' && $ret['var'] == 'root') $vartemp = ROOT;
  202. elseif (method_exists($this, '_' . $ret['-tipo-'])) $vartemp = $this->{'_' . $ret['-tipo-']}($ret);
  203. //Incluindo o bloco gerado pelas ©sTags
  204. $content = substr_replace($this->getContent(), $vartemp, $ret['-inicio-'], $ret['-tamanho-']);
  205. $this->setContent($content);
  206. //RE-setando o ponteiro depois de adicionar os dados acima
  207. $ponteiro = strlen($vartemp) + $ret['-inicio-'] -1;
  208. }//end while
  209. }//end ©sTag
  210. //Eval PHP in HTML
  211. if($php) $this->evalPHP();
  212. //returns the processed contents
  213. return $this->getContent();
  214. }
  215. /**
  216. * Scaner for ©sTag
  217. * Scans the file to find a ©STAG - returns an array with the data found ©sTag
  218. *
  219. * @param string $arquivo file content
  220. * @param string $ponteiro file pointer
  221. * @param string $tag ©sTag to scan
  222. * @return array|false array with the data found ©sTag or false (not ©sTag)
  223. */
  224. function sTag(&$arquivo, $ponteiro = -1, $tag = null){
  225. if($tag == null) $tag = $this->tag;
  226. $inicio = strpos($arquivo, '<'.$tag, $ponteiro + 1);
  227. if($inicio !== false){
  228. //get the type (<s:tipo ... )
  229. $x = substr($arquivo, $inicio, 25);
  230. preg_match('/(?<tag>\w+):(?<type>\w+|[\:]\w+)/', $x, $m);
  231. if(!isset($m[0])) return false;
  232. $ntag = $m[0];
  233. //the final ...
  234. $ftag = strpos($arquivo, '</' . $ntag . '>', $inicio);
  235. $fnTag = strpos($arquivo, '/>', $inicio);
  236. $fn = strpos($arquivo, '>', $inicio);
  237. //not /> or </s:xxx> = error
  238. if($fnTag === false && $ftag === false) return false;
  239. if($ftag !== false ) {
  240. if($fn !== false && $fn < $ftag){
  241. $a['-content-'] = substr($arquivo, $fn+1, ($ftag - $fn)-1);
  242. $finTag = $fn;
  243. $a['-final-'] = $ftag + strlen('</'.$ntag.'>');
  244. } else return false;
  245. } elseif($fnTag !== false) {
  246. $a['-content-'] = '';
  247. $finTag = $fnTag;
  248. $a['-final-'] = $fnTag + 2;
  249. } else return false;
  250. //catching attributes
  251. preg_match_all('/(?<att>\w+)="(?<val>.*?)"/', substr($arquivo, $inicio, $finTag - $inicio), $atb);
  252. if(isset($atb['att'])){
  253. foreach ($atb['att'] as $k=>$v){
  254. $a[$v] = $atb['val'][$k];
  255. }
  256. }
  257. //block data
  258. $a['-inicio-'] = $inicio;
  259. $a['-tamanho-'] = ($a['-final-'] - $inicio);
  260. $a['-tipo-'] = 'var';
  261. if(strpos($m['type'], ':') !== false) $a['-tipo-'] = str_replace (':', '', $m['type']);
  262. else $a['var'] = $m['type'];
  263. return $a;
  264. }
  265. return false;
  266. }
  267. /**
  268. * Scaner para Blade.
  269. * Retorna o conteúdo substituindo variáveis BLADE (@var_name).
  270. *
  271. * @param string $arquivo Conteúdo do arquivo a ser 'scaneado'
  272. * @return string O mesmo conteudo com variáveis BLADE substituídas
  273. */
  274. function blade($arquivo){
  275. $t = strlen($arquivo) - 1;
  276. $ini = '';
  277. $o = '';
  278. for($i =0; $i <= $t; $i++){
  279. if($ini != '' && $ini < $i){
  280. if($arquivo[$i] == '@' && ($i - $ini) < 2) {
  281. $o .= '@';
  282. $ini = '';
  283. continue;
  284. }
  285. if(!preg_match("/[a-zA-Z0-9\.:\[\]\-_()\/'$+,\\\]/",$arquivo[$i])){
  286. $out1 = substr($arquivo, $ini+1, $i-$ini-1);
  287. $out = rtrim($out1, ',.:');
  288. $i += (strlen($out) - strlen($out1));
  289. if($this->getVar($out)) $out = $this->getVar($out);
  290. else {
  291. restore_error_handler();
  292. ob_start();
  293. $ret = eval('return '.$out.';');
  294. if(ob_get_clean() === '') $out = $ret;
  295. else $out = '';
  296. }
  297. $o .= $out; //exit($o);
  298. $ini = '';
  299. if($arquivo[$i] != ' ') $i --;//retirando espaço em branco...
  300. }
  301. } elseif($ini == '' && $arquivo[$i] == '@') $ini = $i;
  302. else $o .= $arquivo[$i];
  303. }//end FOR
  304. return $o;
  305. }
  306. /**
  307. * _var
  308. * Insert variable data assigned in view
  309. * Parameter "tag" is the tag type indicator (ex.: <s:variable . . . tag="span" />)
  310. *
  311. * @param array $ret ©sTag data array
  312. * @return string Renderized Html
  313. */
  314. function _var($ret) {
  315. $v = $this->getVar(trim($ret['var']));
  316. if(!$v) return '';
  317. //List type
  318. if(is_array($v)) return $this->_list($ret);
  319. $tag = isset($ret['tag']) ? $ret['tag'] : '';
  320. $ret = $this->clearData($ret);
  321. //Var span (with class, id, etc);
  322. if(count($ret) > 0) {
  323. if($tag == '') $tag = 'span';
  324. $d = '<'.$tag;
  325. foreach ($ret as $k=>$val){
  326. $d .= ' '.trim($k).'="'.trim($val).'"';
  327. }
  328. $v = $d.'>'.$v.'</'.$tag.'>';
  329. }elseif($tag != '') {
  330. $v = '<'.$tag.'>'.$v.'</'.$tag.'>';
  331. }
  332. return $v;
  333. }
  334. /**
  335. * _list :: Create ul html tag
  336. * Parameter "tag" is the list type indicator (ex.: <s:_list . . . tag="li" />)
  337. *
  338. * @param array $ret ©sTag data array
  339. * @return string|html
  340. */
  341. function _list($ret){
  342. if(!isset($ret['var'])) return '';
  343. $v = $this->getVar(trim($ret['var']));
  344. if(!$v || !is_array($v)) return '';
  345. $tag = isset($ret['tag']) ? $ret['tag'] : 'li';
  346. $ret = $this->clearData($ret);
  347. //Tag UL and params. (class, id, etc)
  348. $o = '<ul';
  349. foreach($ret as $k=>$val){
  350. $o .= ' '.trim($k).'="'.trim($val).'"';
  351. }
  352. $o .= '>';
  353. //create list
  354. foreach ($v as $k=>$val){
  355. $o .= '<'.$tag.'>'.$val.'</'.$tag.'>';
  356. }
  357. return $o . '</ul>';
  358. }
  359. /**
  360. * ClearData :: Clear all extra data.
  361. *
  362. * @param array $ret Starttag data array.
  363. * @return array Data array cleared.
  364. */
  365. function clearData($ret){
  366. unset($ret['var'], $ret['-inicio-'], $ret['-tamanho-'], $ret['-final-'], $ret['-tipo-'], $ret['-content-'], $ret['tag']);
  367. return $ret;
  368. }
  369. }