Dotclear

source: inc/public/lib.tpl.context.php @ 3830:f37739d615bc

Revision 3830:f37739d615bc, 17.2 KB checked in by franck <carnet.franck.paul@…>, 7 years ago (diff)

Back to the original global_filters() function as the current seems to be buggy on some installations

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

Sites map