Dotclear

source: inc/public/lib.tpl.context.php @ 975:8d003494d2f5

Revision 975:8d003494d2f5, 12.2 KB checked in by franck <carnet.franck.paul@…>, 13 years ago (diff)

Smileys are not more converted in image in pre,code,kbd,script and math contents, fixes #1029

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

Sites map