Dotclear

source: inc/public/lib.tpl.context.php @ 2676:aa8469b8cc6c

Revision 2676:aa8469b8cc6c, 13.2 KB checked in by franck <carnet.franck.paul@…>, 11 years ago (diff)

Cope with parent theme, if any for smileys, fixes #1496

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               if (isset($GLOBALS['__parent_theme'])) {
314                    $path[] = $GLOBALS['__parent_theme'];
315               }
316          }
317          $path[] = 'default';
318          $definition = $blog->themes_path.'/%s/smilies/smilies.txt';
319          $base_url = $blog->settings->system->themes_url.'/%s/smilies/';
320
321          $res = array();
322
323          foreach ($path as $t)
324          {
325               if (file_exists(sprintf($definition,$t))) {
326                    $base_url = sprintf($base_url,$t);
327                    return self::smiliesDefinition(sprintf($definition,$t),$base_url);
328               }
329          }
330          return false;
331     }
332
333     public static function smiliesDefinition($f,$url)
334     {
335          $def = file($f);
336
337          $res = array();
338          foreach($def as $v)
339          {
340               $v = trim($v);
341               if (preg_match('|^([^\t]*)[\t]+(.*)$|',$v,$matches))
342               {
343                    $r = '/(\A|[\s]+|>)('.preg_quote($matches[1],'/').')([\s]+|[<]|\Z)/ms';
344                    $s = '$1<img src="'.$url.$matches[2].'" '.
345                    'alt="$2" class="smiley" />$3';
346                    $res[$r] = $s;
347               }
348          }
349
350          return $res;
351     }
352
353     public static function addSmilies($str)
354     {
355          if (!isset($GLOBALS['__smilies']) || !is_array($GLOBALS['__smilies'])) {
356               return $str;
357          }
358
359          # Process part adapted from SmartyPants engine (J. Gruber et al.) :
360
361          $tokens = self::tokenizeHTML($str);
362          $result = '';
363          $in_pre = 0;  # Keep track of when we're inside <pre> or <code> tags.
364
365          foreach ($tokens as $cur_token) {
366               if ($cur_token[0] == "tag") {
367                    # Don't mess with quotes inside tags.
368                    $result .= $cur_token[1];
369                    if (preg_match('@<(/?)(?:pre|code|kbd|script|math)[\s>]@', $cur_token[1], $matches)) {
370                         $in_pre = isset($matches[1]) && $matches[1] == '/' ? 0 : 1;
371                    }
372               } else {
373                    $t = $cur_token[1];
374                    if (!$in_pre) {
375                         $t = preg_replace(array_keys($GLOBALS['__smilies']),array_values($GLOBALS['__smilies']),$t);
376                    }
377                    $result .= $t;
378               }
379          }
380
381          return $result;
382     }
383
384     private static function tokenizeHTML($str)
385     {
386          # Function from SmartyPants engine (J. Gruber et al.)
387          #
388          #   Parameter:  String containing HTML markup.
389          #   Returns:    An array of the tokens comprising the input
390          #               string. Each token is either a tag (possibly with nested,
391          #               tags contained therein, such as <a href="<MTFoo>">, or a
392          #               run of text between tags. Each element of the array is a
393          #               two-element array; the first is either 'tag' or 'text';
394          #               the second is the actual value.
395          #
396          #
397          #   Regular expression derived from the _tokenize() subroutine in
398          #   Brad Choate's MTRegex plugin.
399          #   <http://www.bradchoate.com/past/mtregex.php>
400          #
401          $index = 0;
402          $tokens = array();
403
404          $match = '(?s:<!(?:--.*?--\s*)+>)|'.    # comment
405                     '(?s:<\?.*?\?>)|'.                # processing instruction
406                                                            # regular tags
407                     '(?:<[/!$]?[-a-zA-Z0-9:]+\b(?>[^"\'>]+|"[^"]*"|\'[^\']*\')*>)';
408
409          $parts = preg_split("{($match)}", $str, -1, PREG_SPLIT_DELIM_CAPTURE);
410
411          foreach ($parts as $part) {
412               if (++$index % 2 && $part != '')
413                    $tokens[] = array('text', $part);
414               else
415                    $tokens[] = array('tag', $part);
416          }
417          return $tokens;
418     }
419
420
421     # First post image helpers
422     public static function EntryFirstImageHelper($size,$with_category,$class="",$no_tag=false,$content_only=false,$cat_only=false)
423     {
424          global $core, $_ctx;
425
426          try {
427               $media = new dcMedia($core);
428               $sizes = implode('|',array_keys($media->thumb_sizes)).'|o';
429               if (!preg_match('/^'.$sizes.'$/',$size)) {
430                    $size = 's';
431               }
432               $p_url = $core->blog->settings->system->public_url;
433               $p_site = preg_replace('#^(.+?//.+?)/(.*)$#','$1',$core->blog->url);
434               $p_root = $core->blog->public_path;
435
436               $pattern = '(?:'.preg_quote($p_site,'/').')?'.preg_quote($p_url,'/');
437               $pattern = sprintf('/<img.+?src="%s(.*?\.(?:jpg|jpeg|gif|png))"[^>]+/msui',$pattern);
438
439               $src = '';
440               $alt = '';
441
442               # We first look in post content
443               if (!$cat_only && $_ctx->posts)
444               {
445                    $subject = ($content_only ? '' : $_ctx->posts->post_excerpt_xhtml).$_ctx->posts->post_content_xhtml;
446                    if (preg_match_all($pattern,$subject,$m) > 0)
447                    {
448                         foreach ($m[1] as $i => $img) {
449                              if (($src = self::ContentFirstImageLookup($p_root,$img,$size)) !== false) {
450                                   $dirname = str_replace('\\', '/', dirname($img));
451                                   $src = $p_url.($dirname != '/' ? $dirname : '').'/'.$src;
452                                   if (preg_match('/alt="([^"]+)"/',$m[0][$i],$malt)) {
453                                        $alt = $malt[1];
454                                   }
455                                   break;
456                              }
457                         }
458                    }
459               }
460
461               # No src, look in category description if available
462             if (!$src && $with_category && $_ctx->posts->cat_desc)
463             {
464                    if (preg_match_all($pattern,$_ctx->posts->cat_desc,$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               if ($src) {
480                    if ($no_tag) {
481                         return $src;
482                    } else {
483                         return '<img alt="'.$alt.'" src="'.$src.'" class="'.$class.'" />';
484                    }
485               }
486
487          } catch (Exception $e) {
488               $core->error->add($e->getMessage());
489          }
490     }
491
492     private static function ContentFirstImageLookup($root,$img,$size)
493     {
494          global $core;
495
496          # Get base name and extension
497          $info = path::info($img);
498          $base = $info['base'];
499
500          try {
501               $media = new dcMedia($core);
502               $sizes = implode('|',array_keys($media->thumb_sizes));
503               if (preg_match('/^\.(.+)_('.$sizes.')$/',$base,$m)) {
504                    $base = $m[1];
505               }
506
507               $res = false;
508               if ($size != 'o' && file_exists($root.'/'.$info['dirname'].'/.'.$base.'_'.$size.'.jpg'))
509               {
510                    $res = '.'.$base.'_'.$size.'.jpg';
511               }
512               elseif ($size != 'o' && file_exists($root.'/'.$info['dirname'].'/.'.$base.'_'.$size.'.png'))
513               {
514                    $res = '.'.$base.'_'.$size.'.png';
515               }
516               else
517               {
518                    $f = $root.'/'.$info['dirname'].'/'.$base;
519                    if (file_exists($f.'.'.$info['extension'])) {
520                         $res = $base.'.'.$info['extension'];
521                    } elseif (file_exists($f.'.jpg')) {
522                         $res = $base.'.jpg';
523                    } elseif (file_exists($f.'.jpeg')) {
524                         $res = $base.'.jpeg';
525                    } elseif (file_exists($f.'.png')) {
526                         $res = $base.'.png';
527                    } elseif (file_exists($f.'.gif')) {
528                         $res = $base.'.gif';
529                    } elseif (file_exists($f.'.JPG')) {
530                         $res = $base.'.JPG';
531                    } elseif (file_exists($f.'.JPEG')) {
532                         $res = $base.'.JPEG';
533                    } elseif (file_exists($f.'.PNG')) {
534                         $res = $base.'.PNG';
535                    } elseif (file_exists($f.'.GIF')) {
536                         $res = $base.'.GIF';
537                    }
538               }
539          } catch (Exception $e) {
540               $core->error->add($e->getMessage());
541          }
542
543          if ($res) {
544               return $res;
545          }
546          return false;
547     }
548}
Note: See TracBrowser for help on using the repository browser.

Sites map