PluginProbe
s2Member – Excellent for All Kinds of Memberships, Content Restriction Paywalls & Member Access Subscriptions / 111017
s2Member – Excellent for All Kinds of Memberships, Content Restriction Paywalls & Member Access Subscriptions v111017
260917 260913 260909 260829 260814 260805 110710 110731 110812 110815 110912 110913 110915 110926 110927 111002 111003 111011 111017 111029 111105 111206 111216 111220 120213 All 189 releases
s2member / includes / classes / utils-strings.inc.php

utils-strings.inc.php in s2Member – Excellent for All Kinds of Memberships, Content Restriction Paywalls & Member Access Subscriptions 111017, at includes/classes/utils-strings.inc.php

456 lines 21.1 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2 /**
3 * String utilities.
4 *
5 * Copyright: © 2009-2011
6 * {@link http://www.websharks-inc.com/ WebSharks, Inc.}
7 * ( coded in the USA )
8 *
9 * Released under the terms of the GNU General Public License.
10 * You should have received a copy of the GNU General Public License,
11 * along with this software. In the main directory, see: /licensing/
12 * If not, see: {@link http://www.gnu.org/licenses/}.
13 *
14 * @package s2Member\Utilities
15 * @since 3.5
16 */
17 if (realpath (__FILE__) === realpath ($_SERVER["SCRIPT_FILENAME"]))
18 exit ("Do not access this file directly.");
19 /**/
20 if (!class_exists ("c_ws_plugin__s2member_utils_strings"))
21 {
22 /**
23 * String utilities.
24 *
25 * @package s2Member\Utilities
26 * @since 3.5
27 */
28 class c_ws_plugin__s2member_utils_strings
29 {
30 /**
31 * Escapes double quotes.
32 *
33 * @package s2Member\Utilities
34 * @since 3.5
35 *
36 * @param str $string Input string.
37 * @param int $times Mumber of escapes. Defaults to 1.
38 * @return str Output string after double quotes are escaped.
39 */
40 public static function esc_dq ($string = FALSE, $times = FALSE)
41 {
42 $times = (is_numeric ($times) && $times >= 0) ? (int)$times : 1;
43 return str_replace ('"', str_repeat ("\\", $times) . '"', (string)$string);
44 }
45 /**
46 * Escapes single quotes.
47 *
48 * @package s2Member\Utilities
49 * @since 3.5
50 *
51 * @param str $string Input string.
52 * @param int $times Mumber of escapes. Defaults to 1.
53 * @return str Output string after single quotes are escaped.
54 */
55 public static function esc_sq ($string = FALSE, $times = FALSE)
56 {
57 $times = (is_numeric ($times) && $times >= 0) ? (int)$times : 1;
58 return str_replace ("'", str_repeat ("\\", $times) . "'", (string)$string);
59 }
60 /**
61 * Escapes JavaScript and single quotes.
62 *
63 * @package s2Member\Utilities
64 * @since 110901
65 *
66 * @param str $string Input string.
67 * @param int $times Mumber of escapes. Defaults to 1.
68 * @return str Output string after JavaScript and single quotes are escaped.
69 */
70 public static function esc_js_sq ($string = FALSE, $times = FALSE)
71 {
72 $times = (is_numeric ($times) && $times >= 0) ? (int)$times : 1;
73 return str_replace ("'", str_repeat ("\\", $times) . "'", str_replace (array ("\r", "\n"), array ("", '\\n'), str_replace ("\'", "'", (string)$string)));
74 }
75 /**
76 * Escapes dollars signs ( for regex patterns ).
77 *
78 * @package s2Member\Utilities
79 * @since 3.5
80 *
81 * @param str $string Input string.
82 * @param int $times Mumber of escapes. Defaults to 1.
83 * @return str Output string after dollar signs are escaped.
84 */
85 public static function esc_ds ($string = FALSE, $times = FALSE)
86 {
87 $times = (is_numeric ($times) && $times >= 0) ? (int)$times : 1;
88 return str_replace ('$', str_repeat ("\\", $times) . '$', (string)$string);
89 }
90 /**
91 * Sanitizes a string; by removing non-standard characters.
92 *
93 * This allows all characters that appears on a standard U.S. keyboard.
94 *
95 * @package s2Member\Utilities
96 * @since 3.5
97 *
98 * @param str $string Input string.
99 * @return str Output string after non-keyboard chars are removed.
100 */
101 public static function keyboard_chars_only ($string = FALSE)
102 {
103 return preg_replace ("/[^0-9A-Z\r\n\t\s`\=\[\]\\\;',\.\/~\!@#\$%\^&\*\(\)_\+\|\}\{\:\"\?\>\<\-]/i", "", remove_accents ((string)$string));
104 }
105 /**
106 * Trims deeply.
107 *
108 * @package s2Member\Utilities
109 * @since 3.5
110 *
111 * @param str|array $value Either a string, an array, or a multi-dimensional array, filled with integer and/or string values.
112 * @return str|array Either the input string, or the input array; after all data is trimmed up.
113 */
114 public static function trim_deep ($value = FALSE)
115 {
116 return is_array ($value) ? array_map ("c_ws_plugin__s2member_utils_strings::trim_deep", $value) : trim ((string)$value);
117 }
118 /**
119 * Trims all single/double quote entity variations deeply.
120 *
121 * This is useful on Shortcode attributes mangled by a Visual Editor.
122 *
123 * @package s2Member\Utilities
124 * @since 111011
125 *
126 * @param str|array $value Either a string, an array, or a multi-dimensional array, filled with integer and/or string values.
127 * @return str|array Either the input string, or the input array; after all data is trimmed up.
128 */
129 public static function trim_qts_deep ($value = FALSE)
130 {
131 $qts = implode ("|", array_keys /* Keys are regex patterns. */ (array ("&apos;" => "&apos;", "&#0*39;" => "&#39;", "&#[xX]0*27;" => "&#x27;"/**/, "&lsquo;" => "&lsquo;", "&#0*8216;" => "&#8216;", "&#[xX]0*2018;" => "&#x2018;"/**/, "&rsquo;" => "&rsquo;", "&#0*8217;" => "&#8217;", "&#[xX]0*2019;" => "&#x2019;"/**/, "&quot;" => "&quot;", "&#0*34;" => "&#34;", "&#[xX]0*22;" => "&#x22;"/**/, "&ldquo;" => "&ldquo;", "&#0*8220;" => "&#8220;", "&#[xX]0*201[cC];" => "&#x201C;"/**/, "&rdquo;" => "&rdquo;", "&#0*8221;" => "&#8221;", "&#[xX]0*201[dD];" => "&#x201D;")));
132 return is_array ($value) ? array_map ("c_ws_plugin__s2member_utils_strings::trim_qts_deep", $value) : preg_replace ("/^(?:" . $qts . ")+|(?:" . $qts . ")+$/", "", (string)$value);
133 }
134 /**
135 * Trims double quotes deeply.
136 *
137 * This is useful on CSV data that is encapsulated by double quotes.
138 *
139 * @package s2Member\Utilities
140 * @since 3.5
141 *
142 * @param str|array $value Either a string, an array, or a multi-dimensional array, filled with integer and/or string values.
143 * @return str|array Either the input string, or the input array; after all data is trimmed up.
144 */
145 public static function trim_dq_deep ($value = FALSE)
146 {
147 return is_array ($value) ? array_map ("c_ws_plugin__s2member_utils_strings::trim_dq_deep", $value) : trim ((string)$value, "\" \t\n\r\0\x0B");
148 }
149 /**
150 * Wraps a string with the characters provided.
151 *
152 * This is useful when preparing an input array for ``c_ws_plugin__s2member_utils_arrays::in_regex_array()``.
153 *
154 * @package s2Member\Utilities
155 * @since 3.5
156 *
157 * @param str|array $value Either a string, an array, or a multi-dimensional array, filled with integer and/or string values.
158 * @param str $beg Optional. A string value to wrap at the beginning of each value.
159 * @param str $end Optional. A string value to wrap at the ending of each value.
160 * @return str|array Either the input string, or the input array; after all data is wrapped up.
161 */
162 public static function wrap_deep ($value = FALSE, $beg = FALSE, $end = FALSE)
163 {
164 if (is_array ($value)) /* Handles all types of arrays.
165 Note, we do NOT use ``array_map()`` here, because multiple args to ``array_map()`` causes a loss of string keys.
166 For further details, see: <http://php.net/manual/en/function.array-map.php>. */
167 {
168 foreach ($value as &$r) /* Reference. */
169 $r = c_ws_plugin__s2member_utils_strings::wrap_deep ($r, $beg, $end);
170 return $value; /* Return modified array. */
171 }
172 return (strlen ((string)$value)) ? (string)$beg . (string)$value . (string)$end : (string)$value;
173 }
174 /**
175 * Escapes meta characters with ``preg_quote()`` deeply.
176 *
177 * @package s2Member\Utilities
178 * @since 110926
179 *
180 * @param str|array $value Either a string, an array, or a multi-dimensional array, filled with integer and/or string values.
181 * @param str $delimiter Optional. If a delimiting character is specified, it will also be escaped via ``preg_quote()``.
182 * @return str|array Either the input string, or the input array; after all data is escaped with ``preg_quote()``.
183 */
184 public static function preg_quote_deep ($value = FALSE, $delimiter = FALSE)
185 {
186 if (is_array ($value)) /* Handles all types of arrays.
187 Note, we do NOT use ``array_map()`` here, because multiple args to ``array_map()`` causes a loss of string keys.
188 For further details, see: <http://php.net/manual/en/function.array-map.php>. */
189 {
190 foreach ($value as &$r) /* Reference. */
191 $r = c_ws_plugin__s2member_utils_strings::preg_quote_deep ($r, $delimiter);
192 return $value; /* Return modified array. */
193 }
194 return preg_quote ((string)$value, (string)$delimiter);
195 }
196 /**
197 * Generates a random string with letters/numbers/symbols.
198 *
199 * @package s2Member\Utilities
200 * @since 3.5
201 *
202 * @param int $length Length of the randomly generated string.
203 * @param bool $special_chars Defaults to true. If false, special chars are NOT included.
204 * @param bool $extra_special_chars Defaults to false. If true, extra special chars are included.
205 * @return str A randomly generated string, based on parameter configuration.
206 */
207 public static function random_str_gen ($length = 12, $special_chars = TRUE, $extra_special_chars = FALSE)
208 {
209 $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
210 $chars .= ($extra_special_chars) ? "-_ []{}<>~`+=,.;:/?|" : "";
211 $chars .= ($special_chars) ? "!@#$%^&*()" : "";
212 /**/
213 for ($i = 0, $random_str = ""; $i < $length; $i++)
214 $random_str .= substr ($chars, mt_rand (0, strlen ($chars) - 1), 1);
215 /**/
216 return $random_str;
217 }
218 /**
219 * Highlights PHP, and also Shortcodes.
220 *
221 * @package s2Member\Utilities
222 * @since 3.5
223 *
224 * @param str $str Input string to be highlighted.
225 * @return str The highlighted string.
226 */
227 public static function highlight_php ($string = FALSE)
228 {
229 $string = highlight_string ((string)$string, true); /* Start with PHP syntax highlighting first. */
230 /**/
231 return preg_replace_callback ("/(\[)(\/?)(_*s2If|s2Get|s2Member-[A-z_0-9\-]+)(.*?)(\])/i", "c_ws_plugin__s2member_utils_strings::_highlight_php", $string);
232 }
233 /**
234 * Highlights Shortcodes.
235 *
236 * @package s2Member\Utilities
237 * @since 3.5
238 *
239 * @param array $m Array passed in from `preg_replace_callback()`.
240 * @return str The highlighted string.
241 */
242 public static function _highlight_php ($m = FALSE)
243 {
244 return '<span style="color:#164A61;">' . $m[0] . '</span>';
245 }
246 /**
247 * Parses email addresses from a string or array.
248 *
249 * @package s2Member\Utilities
250 * @since 111009
251 *
252 * @param str|array $value Input string or an array is also fine.
253 * @return array Array of parsed email addresses.
254 */
255 public static function parse_emails ($value = FALSE)
256 {
257 if (is_array ($value)) /* Handles all types of arrays.
258 Note, we do NOT use ``array_map()`` here, because multiple args to ``array_map()`` causes a loss of string keys.
259 For further details, see: <http://php.net/manual/en/function.array-map.php>. */
260 {
261 $emails = array (); /* Initialize array of emails. */
262 foreach ($value as $_value) /* Loop through array. */
263 $emails = array_merge ($emails, c_ws_plugin__s2member_utils_strings::parse_emails ($_value));
264 return $emails; /* Return array of parsed email addresses. */
265 }
266 /**/
267 $delimiter = (strpos ((string)$value, ";") !== false) ? ";" : ",";
268 foreach (($sections = c_ws_plugin__s2member_utils_strings::trim_deep (preg_split ("/" . preg_quote ($delimiter, "/") . "+/", (string)$value))) as $section)
269 {
270 if (preg_match ("/\<(.+?)\>/", $section, $m) && strpos ($m[1], "@") !== false)
271 $emails[] = $m[1]; /* Email inside brackets. */
272 /**/
273 else if (strpos ($section, "@") !== false)
274 $emails[] = $section;
275 }
276 /**/
277 return (!empty ($emails)) ? $emails : array ();
278 }
279 /**
280 * Base64 URL-safe encoding.
281 *
282 * @package s2Member\Utilities
283 * @since 110913
284 *
285 * @param str $string Input string to be base64 encoded.
286 * @param array $url_unsafe_chars Optional. An array of un-safe characters. Defaults to: ``array("+", "/")``.
287 * @param array $url_safe_chars Optional. An array of safe character replacements. Defaults to: ``array("-", "_")``.
288 * @param str $trim_padding_chars Optional. A string of padding chars to rtrim. Defaults to: `=~.`.
289 * @return str The base64 URL-safe encoded string.
290 */
291 public static function base64_url_safe_encode ($string = FALSE, $url_unsafe_chars = array ("+", "/"), $url_safe_chars = array ("-", "_"), $trim_padding_chars = "=~.")
292 {
293 $string = (string)$string; /* Force string values here. String MUST be a string. */
294 $trim_padding_chars = (string)$trim_padding_chars; /* And force this one too. */
295 /**/
296 $base64_url_safe = str_replace ((array)$url_unsafe_chars, (array)$url_safe_chars, base64_encode ($string));
297 $base64_url_safe = (strlen ($trim_padding_chars)) ? rtrim ($base64_url_safe, $trim_padding_chars) : $base64_url_safe;
298 /**/
299 return $base64_url_safe; /* Base64 encoded, with URL-safe replacements. */
300 }
301 /**
302 * Base64 URL-safe decoding.
303 *
304 * Note, this function is backward compatible with routines supplied by s2Member in the past;
305 * where padding characters were replaced with `~` or `.`, instead of being stripped completely.
306 *
307 * @package s2Member\Utilities
308 * @since 110913
309 *
310 * @param str $base64_url_safe Input string to be base64 decoded.
311 * @param array $url_unsafe_chars Optional. An array of un-safe character replacements. Defaults to: ``array("+", "/")``.
312 * @param array $url_safe_chars Optional. An array of safe characters. Defaults to: ``array("-", "_")``.
313 * @param str $trim_padding_chars Optional. A string of padding chars to rtrim. Defaults to: `=~.`.
314 * @return str The decoded string.
315 */
316 public static function base64_url_safe_decode ($base64_url_safe = FALSE, $url_unsafe_chars = array ("+", "/"), $url_safe_chars = array ("-", "_"), $trim_padding_chars = "=~.")
317 {
318 $base64_url_safe = (string)$base64_url_safe; /* Force string values here. This MUST be a string. */
319 $trim_padding_chars = (string)$trim_padding_chars; /* And force this one too. */
320 /**/
321 $string = (strlen ($trim_padding_chars)) ? rtrim ($base64_url_safe, $trim_padding_chars) : $base64_url_safe;
322 $string = (strlen ($trim_padding_chars)) ? str_pad ($string, strlen ($string) % 4, "=", STR_PAD_RIGHT) : $string;
323 $string = base64_decode (str_replace ((array)$url_safe_chars, (array)$url_unsafe_chars, $string));
324 /**/
325 return $string; /* Base64 decoded, with URL-safe replacements. */
326 }
327 /**
328 * Generates an RSA-SHA1 signature.
329 *
330 * @package s2Member\Utilities
331 * @since 111017
332 *
333 * @param str $string Input string/data, to be signed by this routine.
334 * @param str $key The secret key that will be used in this signature.
335 * @return str|bool An RSA-SHA1 signature string, or false on failure.
336 */
337 public static function rsa_sha1_sign ($string = FALSE, $key = FALSE)
338 {
339 $key = /* Fixes key wrappers. */ c_ws_plugin__s2member_utils_strings::_rsa_sha1_key_fix_wrappers ((string)$key);
340 /**/
341 $signature = /* Command line. */ c_ws_plugin__s2member_utils_strings::_rsa_sha1_shell_sign ((string)$string, (string)$key);
342 /**/
343 if (empty ($signature) && stripos (PHP_OS, "win") === 0 && file_exists (($openssl = "c:\openssl-win32\bin\openssl.exe")))
344 $signature = c_ws_plugin__s2member_utils_strings::_rsa_sha1_shell_sign ((string)$string, (string)$key, /* Specific location. */ $openssl);
345 /**/
346 if (empty ($signature) && stripos (PHP_OS, "win") === 0 && file_exists (($openssl = "c:\openssl-win64\bin\openssl.exe")))
347 $signature = c_ws_plugin__s2member_utils_strings::_rsa_sha1_shell_sign ((string)$string, (string)$key, /* Specific location. */ $openssl);
348 /**/
349 if (empty ($signature) && function_exists ("openssl_get_privatekey") && function_exists ("openssl_sign") && is_resource ($private_key = openssl_get_privatekey ((string)$key)))
350 openssl_sign ((string)$string, $signature, $private_key, OPENSSL_ALGO_SHA1) . openssl_free_key ($private_key);
351 /**/
352 if (empty ($signature)) /* Now, if we're still empty, trigger an error here. */
353 trigger_error ("s2Member was unable to generate an RSA-SHA1 signature." .
354 " Please make sure your installation of PHP is compiled with OpenSSL: `openssl_sign()`." .
355 " See: http://php.net/manual/en/function.openssl-sign.php", E_USER_ERROR);
356 /**/
357 return (!empty ($signature)) ? $signature : false;
358 }
359 /**
360 * Generates an RSA-SHA1 signature from the command line.
361 *
362 * Used by {@link s2Member\Utilities\c_ws_plugin__s2member_utils_strings::rsa_sha1_sign()}.
363 *
364 * @package s2Member\Utilities
365 * @since 111017
366 *
367 * @param str $string Input string/data, to be signed by this routine.
368 * @param str $key The secret key that will be used in this signature.
369 * @param str $openssl Optional. Defaults to `openssl`. Path to OpenSSL executable.
370 * @return str|bool An RSA-SHA1 signature string, or false on failure.
371 */
372 public static function _rsa_sha1_shell_sign ($string = FALSE, $key = FALSE, $openssl = FALSE)
373 {
374 if (function_exists ("shell_exec") && ($esa = "escapeshellarg") && ($openssl = (($openssl && is_string ($openssl)) ? $openssl : "openssl")) && ($temp_dir = c_ws_plugin__s2member_utils_dirs::get_temp_dir ()))
375 {
376 file_put_contents (($string_file = $temp_dir . "/" . md5 (uniqid ("", true) . "rsa-sha1-string") . ".tmp"), (string)$string);
377 file_put_contents (($private_key_file = $temp_dir . "/" . md5 (uniqid ("", true) . "rsa-sha1-private-key") . ".tmp"), (string)$key);
378 file_put_contents (($rsa_sha1_sig_file = $temp_dir . "/" . md5 (uniqid ("", true) . "rsa-sha1-sig") . ".tmp"), "");
379 /**/
380 @shell_exec ($esa ($openssl) . " sha1 -sign " . $esa ($private_key_file) . " -out " . $esa ($rsa_sha1_sig_file) . " " . $esa ($string_file));
381 $signature = /* Do NOT trim here. */ file_get_contents ($rsa_sha1_sig_file); /* Was the signature was written? */
382 unlink ($rsa_sha1_sig_file) . unlink ($private_key_file) . unlink ($string_file); /* Cleanup. */
383 }
384 /**/
385 return (!empty ($signature)) ? $signature : false;
386 }
387 /**
388 * Fixes incomplete private key wrappers for RSA-SHA1 signing.
389 *
390 * Used by {@link s2Member\Utilities\c_ws_plugin__s2member_utils_strings::rsa_sha1_sign()}.
391 *
392 * @package s2Member\Utilities
393 * @since 111017
394 *
395 * @param str $key The secret key to be used in an RSA-SHA1 signature.
396 * @return str Key with incomplete wrappers corrected, when/if possible.
397 *
398 * @see http://www.faqs.org/qa/qa-14736.html
399 */
400 public static function _rsa_sha1_key_fix_wrappers ($key = FALSE)
401 {
402 if (($key = trim ((string)$key)) && (strpos ($key, "-----BEGIN RSA PRIVATE KEY-----") === false || strpos ($key, "-----END RSA PRIVATE KEY-----") === false))
403 {
404 foreach (($lines = c_ws_plugin__s2member_utils_strings::trim_deep (preg_split ("/[\r\n]+/", $key))) as $line => $value)
405 if (strpos ($value, "-") === 0) /* Begins with a boundary identifying character ( a hyphen `-` )? */
406 {
407 $boundaries = (empty ($boundaries)) ? 1 : $boundaries + 1; /* Counter. */
408 unset ($lines[$line]); /* Remove this boundary line. We'll fix these below. */
409 }
410 if (empty ($boundaries) || $boundaries <= 2) /* Do NOT modify keys with more than 2 boundaries. */
411 $key = "-----BEGIN RSA PRIVATE KEY-----\n" . implode ("\n", $lines) . "\n-----END RSA PRIVATE KEY-----";
412 }
413 return $key; /* Always a trimmed string here. */
414 }
415 /**
416 * Generates an HMAC-SHA1 signature.
417 *
418 * @package s2Member\Utilities
419 * @since 111017
420 *
421 * @param str $string Input string/data, to be signed by this routine.
422 * @param str $key The secret key that will be used in this signature.
423 * @return str An HMAC-SHA1 signature string.
424 */
425 public static function hmac_sha1_sign ($string = FALSE, $key = FALSE)
426 {
427 $key_64 = str_pad (((strlen ((string)$key) > 64) ? pack ('H*', sha1 ((string)$key)) : (string)$key), 64, chr (0x00));
428 /**/
429 return pack ('H*', sha1 (($key_64 ^ str_repeat (chr (0x5c), 64)) . pack ('H*', sha1 (($key_64 ^ str_repeat (chr (0x36), 64)) . (string)$string))));
430 }
431 /**
432 * Decodes unreserved chars encoded by PHP's ``urlencode()``, deeply.
433 *
434 * For further details regarding unreserved chars, see: {@link http://www.faqs.org/rfcs/rfc3986.html}.
435 *
436 * @package s2Member\Utilities
437 * @since 111017
438 *
439 * @param str|array $value Either a string, an array, or a multi-dimensional array, filled with integer and/or string values.
440 * @return str|array Either the input string, or the input array; after all unreserved chars are decoded properly.
441 */
442 public static function urldecode_ur_chars_deep ($value = array ())
443 {
444 if (is_array ($value)) /* Handles all types of arrays.
445 Note, we do NOT use ``array_map()`` here, because multiple args to ``array_map()`` causes a loss of string keys.
446 For further details, see: <http://php.net/manual/en/function.array-map.php>. */
447 {
448 foreach ($value as &$r) /* Reference. */
449 $r = c_ws_plugin__s2member_utils_strings::urldecode_ur_chars_deep ($r);
450 return $value; /* Return modified array. */
451 }
452 return str_replace (array ("%2D", "%2E", "%5F", "%7E"), array ("-", ".", "_", "~"), (string)$value);
453 }
454 }
455 }
456 ?>