Dotclear

source: inc/public/lib.tpl.context.php @ 3426:3dde74bd36ee

Revision 3426:3dde74bd36ee, 13.3 KB checked in by Jean-Christian Denis, 9 years ago (diff)

Open template tags to third party filters, addresses #2051

Line 
1<?php
2# -- BEGIN LICENSE BLOCK ---------------------------------------
3#
4# This file is part of Dotclear 2.
5#
6# Copyright (c) 2003-2013 Olivier Meunier & Association Dotclear
7# Licensed under the GPL version 2.0 license.
8# See LICENSE file or
9# http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
10#
11# -- END LICENSE BLOCK -----------------------------------------
12if (!defined('DC_RC_PATH')) { return; }
13
14class context
15{
16     public $stack = array();
17
18     public function __set($name,$var)
19     {
20          if ($var === null) {
21               $this->pop($name);
22          } else {
23               $this->stack[$name][] =& $var;
24               if ($var instanceof record) {
25                    $this->stack['cur_loop'][] =& $var;
26               }
27          }
28     }
29
30     public function __get($name)
31     {
32          if (!isset($this->stack[$name])) {
33               return null;
34          }
35
36          $n = count($this->stack[$name]);
37          if ($n > 0) {
38               return $this->stack[$name][($n-1)];
39          }
40
41          return null;
42     }
43
44     public function exists($name)
45     {
46          return isset($this->stack[$name][0]);
47     }
48
49     public function pop($name)
50     {
51          if (isset($this->stack[$name])) {
52               $v = array_pop($this->stack[$name]);
53               if ($v instanceof record) {
54                    array_pop($this->stack['cur_loop']);
55               }
56               unset($v);
57          }
58     }
59
60     # Loop position tests
61     public function loopPosition($start,$length=null,$even=null,$modulo=null)
62     {
63          if (!$this->cur_loop) {
64               return false;
65          }
66
67          $index = $this->cur_loop->index();
68          $size = $this->cur_loop->count();
69
70          $test = false;
71          if ($start >= 0)
72          {
73               $test = $index >= $start;
74               if ($length !== null) {
75                    if ($length >= 0) {
76                         $test = $test && $index < $start + $length;
77                    } else {
78                         $test = $test && $index < $size + $length;
79                    }
80               }
81          }
82          else
83          {
84               $test = $index >= $size + $start;
85               if ($length !== null) {
86                    if ($length >= 0) {
87                         $test = $test && $index < $size + $start + $length;
88                    } else {
89                         $test = $test && $index < $size + $length;
90                    }
91               }
92          }
93
94          if ($even !== null) {
95               $test = $test && $index%2 == $even;
96          }
97
98          if ($modulo !== null) {
99               $test = $test && ($index % $modulo == 0);
100          }
101
102          return $test;
103     }
104
105     /**
106     @deprecated since version 2.11 , use tpl_context::global_filters instead
107     */
108     public static function global_filter($str,
109          $encode_xml, $remove_html, $cut_string, $lower_case, $upper_case ,$encode_url ,$tag='')
110     {
111          return $str;
112     }
113
114     public static function global_filters($str,$args,$tag='')
115     {
116          $args[0] =& $str;
117
118          # --BEHAVIOR-- publicBeforeContentFilter
119          $res = $GLOBALS['core']->callBehavior('publicBeforeContentFilter',$GLOBALS['core'],$tag,$args);
120
121          if ($args['strip_tags']) {
122               $str = self::strip_tags($str);
123          }
124          elseif ($args['remove_html']) {
125               $str = self::remove_html($str);
126               $str = preg_replace('/\s+/',' ',$str);
127          }
128          elseif ($args['encode_xml'] || $args['encode_html']) {
129               $str = self::encode_xml($str);
130          }
131
132          if ($args['cut_string'] > 0) {
133               $str = self::cut_string($str,(integer) $args['cut_string']);
134          }
135
136          if ($args['lower_case']) {
137               $str = self::lower_case($str);
138          } elseif ($args['capitalize']) {
139               $str = self::capitalize($str);
140          } elseif ($args['upper_case']) {
141               $str = self::upper_case($str);
142          }
143
144          if ($args['encode_url']) {
145               $str = self::encode_url($str);
146          }
147
148          # --BEHAVIOR-- publicAfterContentFilter
149          $res = $GLOBALS['core']->callBehavior('publicAfterContentFilter',$GLOBALS['core'],$tag,$args);
150
151          return $str;
152     }
153
154     public static function encode_url($str)
155     {
156          return urlencode($str);
157     }
158
159     public static function cut_string($str,$l)
160     {
161          return text::cutString($str,$l);
162     }
163
164     public static function encode_xml($str)
165     {
166          return html::escapeHTML($str);
167     }
168
169     public static function remove_html($str)
170     {
171          return html::decodeEntities(html::clean($str));
172     }
173
174     public static function strip_tags($str)
175     {
176          return trim(preg_replace('/ {2,}/',' ',str_replace(array("\r","\n","\t"),' ',html::clean($str))));
177     }
178
179     public static function lower_case($str)
180     {
181          return mb_strtolower($str);
182     }
183
184     public static function upper_case($str)
185     {
186          return mb_strtoupper($str);
187     }
188
189     public static function capitalize($str)
190     {
191          if ($str != '') {
192             $str[0] = mb_strtoupper($str[0]);
193          }
194          return $str;
195     }
196
197     public static function categoryPostParam(&$p)
198     {
199          $not = substr($p['cat_url'],0,1) == '!';
200          if ($not) {
201               $p['cat_url'] = substr($p['cat_url'],1);
202          }
203
204          $p['cat_url'] = preg_split('/\s*,\s*/',$p['cat_url'],-1,PREG_SPLIT_NO_EMPTY);
205
206          foreach ($p['cat_url'] as &$v)
207          {
208               if ($not) {
209                    $v .= ' ?not';
210               }
211               if ($GLOBALS['_ctx']->exists('categories') && preg_match('/#self/',$v)) {
212                    $v = preg_replace('/#self/',$GLOBALS['_ctx']->categories->cat_url,$v);
213               } elseif ($GLOBALS['_ctx']->exists('posts') && preg_match('/#self/',$v)) {
214                    $v = preg_replace('/#self/',$GLOBALS['_ctx']->posts->cat_url,$v);
215               }
216          }
217     }
218
219     # Static methods for pagination
220     public static function PaginationNbPages()
221     {
222          global $_ctx;
223
224          if ($_ctx->pagination === null) {
225               return false;
226          }
227
228          $nb_posts = $_ctx->pagination->f(0);
229          if (($GLOBALS['core']->url->type == 'default') || ($GLOBALS['core']->url->type == 'default-page')) {
230               $nb_pages = ceil(($nb_posts - $_ctx->nb_entry_first_page) / $_ctx->nb_entry_per_page + 1);
231          } else {
232               $nb_pages = ceil($nb_posts / $_ctx->nb_entry_per_page);
233          }
234
235          return $nb_pages;
236     }
237
238     public static function PaginationPosition($offset=0)
239     {
240          if (isset($GLOBALS['_page_number'])) {
241               $p = $GLOBALS['_page_number'];
242          } else {
243               $p = 1;
244          }
245
246          $p = $p+$offset;
247
248          $n = self::PaginationNbPages();
249          if (!$n) {
250               return $p;
251          }
252
253          if ($p > $n || $p <= 0) {
254               return 1;
255          } else {
256               return $p;
257          }
258     }
259
260     public static function PaginationStart()
261     {
262          if (isset($GLOBALS['_page_number'])) {
263               return self::PaginationPosition() == 1;
264          }
265
266          return true;
267     }
268
269     public static function PaginationEnd()
270     {
271          if (isset($GLOBALS['_page_number'])) {
272               return self::PaginationPosition() == self::PaginationNbPages();
273          }
274
275          return false;
276     }
277
278     public static function PaginationURL($offset=0)
279     {
280          $args = $_SERVER['URL_REQUEST_PART'];
281
282          $n = self::PaginationPosition($offset);
283
284          $args = preg_replace('#(^|/)page/([0-9]+)$#','',$args);
285
286          $url = $GLOBALS['core']->blog->url.$args;
287
288          if ($n > 1) {
289               $url = preg_replace('#/$#','',$url);
290               $url .= '/page/'.$n;
291          }
292
293          # If search param
294          if (!empty($_GET['q'])) {
295               $s = strpos($url,'?') !== false ? '&amp;' : '?';
296               $url .= $s.'q='.rawurlencode($_GET['q']);
297          }
298          return $url;
299     }
300
301     # Robots policy
302     public static function robotsPolicy($base,$over)
303     {
304          $pol = array('INDEX' => 'INDEX','FOLLOW' => 'FOLLOW', 'ARCHIVE' => 'ARCHIVE');
305          $base = array_flip(preg_split('/\s*,\s*/',$base));
306          $over = array_flip(preg_split('/\s*,\s*/',$over));
307
308          foreach ($pol as $k => &$v)
309          {
310               if (isset($base[$k]) || isset($base['NO'.$k])) {
311                    $v = isset($base['NO'.$k]) ? 'NO'.$k : $k;
312               }
313               if (isset($over[$k]) || isset($over['NO'.$k])) {
314                    $v = isset($over['NO'.$k]) ? 'NO'.$k : $k;
315               }
316          }
317
318          if ($pol['ARCHIVE'] == 'ARCHIVE') {
319               unset($pol['ARCHIVE']);
320          }
321
322          return implode(', ',$pol);
323     }
324
325     # Smilies static methods
326     public static function getSmilies($blog)
327     {
328          $path = array();
329          if (isset($GLOBALS['__theme'])) {
330               $path[] = $GLOBALS['__theme'];
331               if (isset($GLOBALS['__parent_theme'])) {
332                    $path[] = $GLOBALS['__parent_theme'];
333               }
334          }
335          $path[] = 'default';
336          $definition = $blog->themes_path.'/%s/smilies/smilies.txt';
337          $base_url = $blog->settings->system->themes_url.'/%s/smilies/';
338
339          $res = array();
340
341          foreach ($path as $t)
342          {
343               if (file_exists(sprintf($definition,$t))) {
344                    $base_url = sprintf($base_url,$t);
345                    return self::smiliesDefinition(sprintf($definition,$t),$base_url);
346               }
347          }
348          return false;
349     }
350
351     public static function smiliesDefinition($f,$url)
352     {
353          $def = file($f);
354
355          $res = array();
356          foreach($def as $v)
357          {
358               $v = trim($v);
359               if (preg_match('|^([^\t]*)[\t]+(.*)$|',$v,$matches))
360               {
361                    $r = '/(\A|[\s]+|>)('.preg_quote($matches[1],'/').')([\s]+|[<]|\Z)/ms';
362                    $s = '$1<img src="'.$url.$matches[2].'" '.
363                    'alt="$2" class="smiley" />$3';
364                    $res[$r] = $s;
365               }
366          }
367
368          return $res;
369     }
370
371     public static function addSmilies($str)
372     {
373          if (!isset($GLOBALS['__smilies']) || !is_array($GLOBALS['__smilies'])) {
374               return $str;
375          }
376
377          # Process part adapted from SmartyPants engine (J. Gruber et al.) :
378
379          $tokens = self::tokenizeHTML($str);
380          $result = '';
381          $in_pre = 0;  # Keep track of when we're inside <pre> or <code> tags.
382
383          foreach ($tokens as $cur_token) {
384               if ($cur_token[0] == "tag") {
385                    # Don't mess with quotes inside tags.
386                    $result .= $cur_token[1];
387                    if (preg_match('@<(/?)(?:pre|code|kbd|script|math)[\s>]@', $cur_token[1], $matches)) {
388                         $in_pre = isset($matches[1]) && $matches[1] == '/' ? 0 : 1;
389                    }
390               } else {
391                    $t = $cur_token[1];
392                    if (!$in_pre) {
393                         $t = preg_replace(array_keys($GLOBALS['__smilies']),array_values($GLOBALS['__smilies']),$t);
394                    }
395                    $result .= $t;
396               }
397          }
398
399          return $result;
400     }
401
402     private static function tokenizeHTML($str)
403     {
404          # Function from SmartyPants engine (J. Gruber et al.)
405          #
406          #   Parameter:  String containing HTML markup.
407          #   Returns:    An array of the tokens comprising the input
408          #               string. Each token is either a tag (possibly with nested,
409          #               tags contained therein, such as <a href="<MTFoo>">, or a
410          #               run of text between tags. Each element of the array is a
411          #               two-element array; the first is either 'tag' or 'text';
412          #               the second is the actual value.
413          #
414          #
415          #   Regular expression derived from the _tokenize() subroutine in
416          #   Brad Choate's MTRegex plugin.
417          #   <http://www.bradchoate.com/past/mtregex.php>
418          #
419          $index = 0;
420          $tokens = array();
421
422          $match = '(?s:<!(?:--.*?--\s*)+>)|'.    # comment
423                     '(?s:<\?.*?\?>)|'.                # processing instruction
424                                                            # regular tags
425                     '(?:<[/!$]?[-a-zA-Z0-9:]+\b(?>[^"\'>]+|"[^"]*"|\'[^\']*\')*>)';
426
427          $parts = preg_split("{($match)}", $str, -1, PREG_SPLIT_DELIM_CAPTURE);
428
429          foreach ($parts as $part) {
430               if (++$index % 2 && $part != '')
431                    $tokens[] = array('text', $part);
432               else
433                    $tokens[] = array('tag', $part);
434          }
435          return $tokens;
436     }
437
438
439     # First post image helpers
440     public static function EntryFirstImageHelper($size,$with_category,$class="",$no_tag=false,$content_only=false,$cat_only=false)
441     {
442          global $core, $_ctx;
443
444          try {
445               $media = new dcMedia($core);
446               $sizes = implode('|',array_keys($media->thumb_sizes)).'|o';
447               if (!preg_match('/^'.$sizes.'$/',$size)) {
448                    $size = 's';
449               }
450               $p_url = $core->blog->settings->system->public_url;
451               $p_site = preg_replace('#^(.+?//.+?)/(.*)$#','$1',$core->blog->url);
452               $p_root = $core->blog->public_path;
453
454               $pattern = '(?:'.preg_quote($p_site,'/').')?'.preg_quote($p_url,'/');
455               $pattern = sprintf('/<img.+?src="%s(.*?\.(?:jpg|jpeg|gif|png))"[^>]+/msui',$pattern);
456
457               $src = '';
458               $alt = '';
459
460               # We first look in post content
461               if (!$cat_only && $_ctx->posts)
462               {
463                    $subject = ($content_only ? '' : $_ctx->posts->post_excerpt_xhtml).$_ctx->posts->post_content_xhtml;
464                    if (preg_match_all($pattern,$subject,$m) > 0)
465                    {
466                         foreach ($m[1] as $i => $img) {
467                              if (($src = self::ContentFirstImageLookup($p_root,$img,$size)) !== false) {
468                                   $dirname = str_replace('\\', '/', dirname($img));
469                                   $src = $p_url.($dirname != '/' ? $dirname : '').'/'.$src;
470                                   if (preg_match('/alt="([^"]+)"/',$m[0][$i],$malt)) {
471                                        $alt = $malt[1];
472                                   }
473                                   break;
474                              }
475                         }
476                    }
477               }
478
479               # No src, look in category description if available
480             if (!$src && $with_category && $_ctx->posts->cat_desc)
481             {
482                    if (preg_match_all($pattern,$_ctx->posts->cat_desc,$m) > 0)
483                    {
484                         foreach ($m[1] as $i => $img) {
485                              if (($src = self::ContentFirstImageLookup($p_root,$img,$size)) !== false) {
486                                   $dirname = str_replace('\\', '/', dirname($img));
487                                   $src = $p_url.($dirname != '/' ? $dirname : '').'/'.$src;
488                                   if (preg_match('/alt="([^"]+)"/',$m[0][$i],$malt)) {
489                                        $alt = $malt[1];
490                                   }
491                                   break;
492                              }
493                         }
494                    };
495               }
496
497               if ($src) {
498                    if ($no_tag) {
499                         return $src;
500                    } else {
501                         return '<img alt="'.$alt.'" src="'.$src.'" class="'.$class.'" />';
502                    }
503               }
504
505          } catch (Exception $e) {
506               $core->error->add($e->getMessage());
507          }
508     }
509
510     private static function ContentFirstImageLookup($root,$img,$size)
511     {
512          global $core;
513
514          # Get base name and extension
515          $info = path::info($img);
516          $base = $info['base'];
517
518          try {
519               $media = new dcMedia($core);
520               $sizes = implode('|',array_keys($media->thumb_sizes));
521               if (preg_match('/^\.(.+)_('.$sizes.')$/',$base,$m)) {
522                    $base = $m[1];
523               }
524
525               $res = false;
526               if ($size != 'o' && file_exists($root.'/'.$info['dirname'].'/.'.$base.'_'.$size.'.jpg'))
527               {
528                    $res = '.'.$base.'_'.$size.'.jpg';
529               }
530               elseif ($size != 'o' && file_exists($root.'/'.$info['dirname'].'/.'.$base.'_'.$size.'.png'))
531               {
532                    $res = '.'.$base.'_'.$size.'.png';
533               }
534               else
535               {
536                    $f = $root.'/'.$info['dirname'].'/'.$base;
537                    if (file_exists($f.'.'.$info['extension'])) {
538                         $res = $base.'.'.$info['extension'];
539                    } elseif (file_exists($f.'.jpg')) {
540                         $res = $base.'.jpg';
541                    } elseif (file_exists($f.'.jpeg')) {
542                         $res = $base.'.jpeg';
543                    } elseif (file_exists($f.'.png')) {
544                         $res = $base.'.png';
545                    } elseif (file_exists($f.'.gif')) {
546                         $res = $base.'.gif';
547                    } elseif (file_exists($f.'.JPG')) {
548                         $res = $base.'.JPG';
549                    } elseif (file_exists($f.'.JPEG')) {
550                         $res = $base.'.JPEG';
551                    } elseif (file_exists($f.'.PNG')) {
552                         $res = $base.'.PNG';
553                    } elseif (file_exists($f.'.GIF')) {
554                         $res = $base.'.GIF';
555                    }
556               }
557          } catch (Exception $e) {
558               $core->error->add($e->getMessage());
559          }
560
561          if ($res) {
562               return $res;
563          }
564          return false;
565     }
566}
Note: See TracBrowser for help on using the repository browser.

Sites map