Dotclear

source: inc/public/lib.tpl.context.php @ 3507:d53a2c58fb79

Revision 3507:d53a2c58fb79, 13.7 KB checked in by franck <carnet.franck.paul@…>, 9 years ago (diff)

Let ArrayObject? doing it’s job (better than mine) ;-) should fix #2236

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

Sites map