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