Dotclear

source: inc/public/lib.tpl.context.php @ 2665:2976f191aadb

Revision 2665:2976f191aadb, 13.2 KB checked in by Xavier Mouton-Dubosc <xavier@…>, 11 years ago (diff)

Mise en place de l'attribut générique "encode_url" dans le parser de template
Ajout du filtre encode_url="1" dans le mécanisme de template

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

Sites map