Dotclear

source: inc/public/lib.tpl.context.php @ 2639:88d6f1d5de52

Revision 2639:88d6f1d5de52, 12.5 KB checked in by franck <carnet.franck.paul@…>, 12 years ago (diff)

ContentFirstImageLookup? should search also for .png thumbnail, thank's to Guillaume Kulakowski ( http://www.llaumgui.com/) for reporting.

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

Sites map