Aleksander Machniak
2015-09-15 c91d4975ffa3bb4e6da907855b77296f34823aa4
commit | author | age
aa055c 1 <?php
T 2
3 /*
4  +-----------------------------------------------------------------------+
e019f2 5  | This file is part of the Roundcube Webmail client                     |
60226a 6  | Copyright (C) 2009-2012, The Roundcube Dev Team                       |
7fe381 7  |                                                                       |
T 8  | Licensed under the GNU General Public License version 3 or            |
9  | any later version with exceptions for skins & plugins.                |
10  | See the README file for a full license statement.                     |
aa055c 11  |                                                                       |
T 12  | PURPOSE:                                                              |
13  |   Handle string replacements based on preg_replace_callback           |
14  +-----------------------------------------------------------------------+
15  | Author: Thomas Bruederli <roundcube@gmail.com>                        |
16  +-----------------------------------------------------------------------+
17 */
18
19 /**
20  * Helper class for string replacements based on preg_replace_callback
21  *
9ab346 22  * @package    Framework
AM 23  * @subpackage Utils
aa055c 24  */
T 25 class rcube_string_replacer
26 {
d1abd8 27     public static $pattern = '/##str_replacement_(\d+)##/';
0d2144 28     public $mailto_pattern;
AM 29     public $link_pattern;
c856b7 30     public $linkref_index;
TB 31     public $linkref_pattern;
e480ca 32
c91d49 33     protected $values   = array();
AM 34     protected $options  = array();
35     protected $linkrefs = array();
36     protected $urls     = array();
aa055c 37
88ed23 38
1e3254 39     function __construct($options = array())
0d2144 40     {
AM 41         // Simplified domain expression for UTF8 characters handling
42         // Support unicode/punycode in top-level domain part
16915e 43         $utf_domain = '[^?&@"\'\\/()<>\s\r\t\n]+\\.?([^\\x00-\\x2f\\x3b-\\x40\\x5b-\\x60\\x7b-\\x7f]{2,}|xn--[a-zA-Z0-9]{2,})';
0d2144 44         $url1       = '.:;,';
001d33 45         $url2       = 'a-zA-Z0-9%=#$@+?|!&\\/_~\\[\\]\\(\\){}\*\x80-\xFE-';
88ed23 46
c91d49 47         $this->options         = $options;
AM 48         $this->linkref_index   = '/\[([^\]#]+)\](:?\s*##str_replacement_(\d+)##)/';
49         $this->linkref_pattern = '/\[([^\]#]+)\]/';
50         $this->link_pattern    = "/([\w]+:\/\/|\W[Ww][Ww][Ww]\.|^[Ww][Ww][Ww]\.)($utf_domain([$url1]*[$url2]+)*)/";
51         $this->mailto_pattern  = "/("
0d2144 52             ."[-\w!\#\$%&\'*+~\/^`|{}=]+(?:\.[-\w!\#\$%&\'*+~\/^`|{}=]+)*"  // local-part
AM 53             ."@$utf_domain"                                                 // domain-part
54             ."(\?[$url1$url2]+)?"                                           // e.g. ?subject=test...
55             .")/";
aa055c 56     }
0ff554 57
0d2144 58     /**
AM 59      * Add a string to the internal list
60      *
61      * @param string String value 
62      * @return int Index of value for retrieval
63      */
64     public function add($str)
65     {
66         $i = count($this->values);
67         $this->values[$i] = $str;
68         return $i;
a1013c 69     }
aa055c 70
0d2144 71     /**
AM 72      * Build replacement string
73      */
74     public function get_replacement($i)
75     {
d1abd8 76         return '##str_replacement_' . $i . '##';
0d2144 77     }
aa055c 78
0d2144 79     /**
AM 80      * Callback function used to build HTML links around URL strings
81      *
82      * @param array Matches result from preg_replace_callback
83      * @return int Index of saved string value
84      */
85     public function link_callback($matches)
86     {
87         $i = -1;
88         $scheme = strtolower($matches[1]);
aa055c 89
0d2144 90         if (preg_match('!^(http|ftp|file)s?://!i', $scheme)) {
AM 91             $url = $matches[1] . $matches[2];
0ff554 92         }
0d2144 93         else if (preg_match('/^(\W*)(www\.)$/i', $matches[1], $m)) {
AM 94             $url        = $m[2] . $matches[2];
95             $url_prefix = 'http://';
96             $prefix     = $m[1];
0ff554 97         }
A 98
0d2144 99         if ($url) {
AM 100             $suffix = $this->parse_url_brackets($url);
1e3254 101             $attrib = (array)$this->options['link_attribs'];
AM 102             $attrib['href'] = $url_prefix . $url;
103
70229c 104             $i = $this->add(html::a($attrib, rcube::Q($url)) . $suffix);
e480ca 105             $this->urls[$i] = $attrib['href'];
0d2144 106         }
AM 107
108         // Return valid link for recognized schemes, otherwise
109         // return the unmodified string for unrecognized schemes.
70229c 110         return $i >= 0 ? $prefix . $this->get_replacement($i) : $matches[0];
e480ca 111     }
TB 112
113     /**
114      * Callback to add an entry to the link index
115      */
116     public function linkref_addindex($matches)
117     {
118         $key = $matches[1];
c856b7 119         $this->linkrefs[$key] = $this->urls[$matches[3]];
e480ca 120
c856b7 121         return $this->get_replacement($this->add('['.$key.']')) . $matches[2];
e480ca 122     }
TB 123
124     /**
125      * Callback to replace link references with real links
126      */
127     public function linkref_callback($matches)
128     {
129         $i = 0;
c856b7 130         if ($url = $this->linkrefs[$matches[1]]) {
e480ca 131             $attrib = (array)$this->options['link_attribs'];
TB 132             $attrib['href'] = $url;
133             $i = $this->add(html::a($attrib, rcube::Q($matches[1])));
134         }
135
136         return $i > 0 ? '['.$this->get_replacement($i).']' : $matches[0];
0ff554 137     }
A 138
0d2144 139     /**
AM 140      * Callback function used to build mailto: links around e-mail strings
141      *
142      * @param array Matches result from preg_replace_callback
143      * @return int Index of saved string value
144      */
145     public function mailto_callback($matches)
146     {
147         $href   = $matches[1];
148         $suffix = $this->parse_url_brackets($href);
149         $i = $this->add(html::a('mailto:' . $href, rcube::Q($href)) . $suffix);
0ff554 150
0d2144 151         return $i >= 0 ? $this->get_replacement($i) : '';
AM 152     }
153
154     /**
155      * Look up the index from the preg_replace matches array
156      * and return the substitution value.
157      *
158      * @param array Matches result from preg_replace_callback
159      * @return string Value at index $matches[1]
160      */
161     public function replace_callback($matches)
162     {
163         return $this->values[$matches[1]];
164     }
165
166     /**
167      * Replace all defined (link|mailto) patterns with replacement string
168      *
169      * @param string $str Text
170      *
171      * @return string Text
172      */
173     public function replace($str)
174     {
175         // search for patterns like links and e-mail addresses
176         $str = preg_replace_callback($this->link_pattern, array($this, 'link_callback'), $str);
177         $str = preg_replace_callback($this->mailto_pattern, array($this, 'mailto_callback'), $str);
e480ca 178         // resolve link references
TB 179         $str = preg_replace_callback($this->linkref_index, array($this, 'linkref_addindex'), $str);
180         $str = preg_replace_callback($this->linkref_pattern, array($this, 'linkref_callback'), $str);
0d2144 181
AM 182         return $str;
183     }
184
185     /**
186      * Replace substituted strings with original values
187      */
188     public function resolve($str)
189     {
190         return preg_replace_callback(self::$pattern, array($this, 'replace_callback'), $str);
191     }
192
193     /**
194      * Fixes bracket characters in URL handling
195      */
196     public static function parse_url_brackets(&$url)
197     {
198         // #1487672: special handling of square brackets,
199         // URL regexp allows [] characters in URL, for example:
200         // "http://example.com/?a[b]=c". However we need to handle
201         // properly situation when a bracket is placed at the end
202         // of the link e.g. "[http://example.com]"
0931a9 203         // Yes, this is not perfect handles correctly only paired characters
AM 204         // but it should work for common cases
205
0d2144 206         if (preg_match('/(\\[|\\])/', $url)) {
AM 207             $in = false;
208             for ($i=0, $len=strlen($url); $i<$len; $i++) {
209                 if ($url[$i] == '[') {
210                     if ($in)
211                         break;
212                     $in = true;
213                 }
214                 else if ($url[$i] == ']') {
215                     if (!$in)
216                         break;
217                     $in = false;
218                 }
219             }
220
221             if ($i < $len) {
222                 $suffix = substr($url, $i);
223                 $url    = substr($url, 0, $i);
224             }
225         }
226
0931a9 227         // Do the same for parentheses
AM 228         if (preg_match('/(\\(|\\))/', $url)) {
229             $in = false;
230             for ($i=0, $len=strlen($url); $i<$len; $i++) {
231                 if ($url[$i] == '(') {
232                     if ($in)
233                         break;
234                     $in = true;
235                 }
236                 else if ($url[$i] == ')') {
237                     if (!$in)
238                         break;
239                     $in = false;
240                 }
241             }
242
243             if ($i < $len) {
244                 $suffix = substr($url, $i);
245                 $url    = substr($url, 0, $i);
246             }
247         }
248
0d2144 249         return $suffix;
AM 250     }
0ff554 251 }