Subversion-Projekte lars-tiefland.ci

Revision

Revision 2049 | Zur aktuellen Revision | Details | Letzte Änderung | Log anzeigen | RSS feed

Revision Autor Zeilennr. Zeile
68 lars 1
<?php
2
/**
3
 * CodeIgniter
4
 *
5
 * An open source application development framework for PHP
6
 *
7
 * This content is released under the MIT License (MIT)
8
 *
9
 * Copyright (c) 2014 - 2016, British Columbia Institute of Technology
10
 *
11
 * Permission is hereby granted, free of charge, to any person obtaining a copy
12
 * of this software and associated documentation files (the "Software"), to deal
13
 * in the Software without restriction, including without limitation the rights
14
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
15
 * copies of the Software, and to permit persons to whom the Software is
16
 * furnished to do so, subject to the following conditions:
17
 *
18
 * The above copyright notice and this permission notice shall be included in
19
 * all copies or substantial portions of the Software.
20
 *
21
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
22
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
23
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
24
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
25
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
26
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
27
 * THE SOFTWARE.
28
 *
29
 * @package	CodeIgniter
30
 * @author	EllisLab Dev Team
31
 * @copyright	Copyright (c) 2008 - 2014, EllisLab, Inc. (https://ellislab.com/)
32
 * @copyright	Copyright (c) 2014 - 2016, British Columbia Institute of Technology (http://bcit.ca/)
33
 * @license	http://opensource.org/licenses/MIT	MIT License
34
 * @link	https://codeigniter.com
35
 * @since	Version 1.0.0
36
 * @filesource
37
 */
38
defined('BASEPATH') OR exit('No direct script access allowed');
39
 
40
/**
41
 * CodeIgniter Text Helpers
42
 *
43
 * @package		CodeIgniter
44
 * @subpackage	Helpers
45
 * @category	Helpers
46
 * @author		EllisLab Dev Team
47
 * @link		https://codeigniter.com/user_guide/helpers/text_helper.html
48
 */
49
 
50
// ------------------------------------------------------------------------
51
 
52
if ( ! function_exists('word_limiter'))
53
{
54
	/**
55
	 * Word Limiter
56
	 *
57
	 * Limits a string to X number of words.
58
	 *
59
	 * @param	string
60
	 * @param	int
61
	 * @param	string	the end character. Usually an ellipsis
62
	 * @return	string
63
	 */
64
	function word_limiter($str, $limit = 100, $end_char = '&#8230;')
65
	{
66
		if (trim($str) === '')
67
		{
68
			return $str;
69
		}
70
 
71
		preg_match('/^\s*+(?:\S++\s*+){1,'.(int) $limit.'}/', $str, $matches);
72
 
73
		if (strlen($str) === strlen($matches[0]))
74
		{
75
			$end_char = '';
76
		}
77
 
78
		return rtrim($matches[0]).$end_char;
79
	}
80
}
81
 
82
// ------------------------------------------------------------------------
83
 
84
if ( ! function_exists('character_limiter'))
85
{
86
	/**
87
	 * Character Limiter
88
	 *
89
	 * Limits the string based on the character count.  Preserves complete words
90
	 * so the character count may not be exactly as specified.
91
	 *
92
	 * @param	string
93
	 * @param	int
94
	 * @param	string	the end character. Usually an ellipsis
95
	 * @return	string
96
	 */
97
	function character_limiter($str, $n = 500, $end_char = '&#8230;')
98
	{
99
		if (mb_strlen($str) < $n)
100
		{
101
			return $str;
102
		}
103
 
104
		// a bit complicated, but faster than preg_replace with \s+
105
		$str = preg_replace('/ {2,}/', ' ', str_replace(array("\r", "\n", "\t", "\x0B", "\x0C"), ' ', $str));
106
 
107
		if (mb_strlen($str) <= $n)
108
		{
109
			return $str;
110
		}
111
 
112
		$out = '';
113
		foreach (explode(' ', trim($str)) as $val)
114
		{
115
			$out .= $val.' ';
116
 
117
			if (mb_strlen($out) >= $n)
118
			{
119
				$out = trim($out);
120
				return (mb_strlen($out) === mb_strlen($str)) ? $out : $out.$end_char;
121
			}
122
		}
123
	}
124
}
125
 
126
// ------------------------------------------------------------------------
127
 
128
if ( ! function_exists('ascii_to_entities'))
129
{
130
	/**
131
	 * High ASCII to Entities
132
	 *
133
	 * Converts high ASCII text and MS Word special characters to character entities
134
	 *
135
	 * @param	string	$str
136
	 * @return	string
137
	 */
138
	function ascii_to_entities($str)
139
	{
140
		$out = '';
141
		for ($i = 0, $s = strlen($str) - 1, $count = 1, $temp = array(); $i <= $s; $i++)
142
		{
143
			$ordinal = ord($str[$i]);
144
 
145
			if ($ordinal < 128)
146
			{
147
				/*
148
					If the $temp array has a value but we have moved on, then it seems only
149
					fair that we output that entity and restart $temp before continuing. -Paul
150
				*/
151
				if (count($temp) === 1)
152
				{
153
					$out .= '&#'.array_shift($temp).';';
154
					$count = 1;
155
				}
156
 
157
				$out .= $str[$i];
158
			}
159
			else
160
			{
161
				if (count($temp) === 0)
162
				{
163
					$count = ($ordinal < 224) ? 2 : 3;
164
				}
165
 
166
				$temp[] = $ordinal;
167
 
168
				if (count($temp) === $count)
169
				{
170
					$number = ($count === 3)
171
						? (($temp[0] % 16) * 4096) + (($temp[1] % 64) * 64) + ($temp[2] % 64)
172
						: (($temp[0] % 32) * 64) + ($temp[1] % 64);
173
 
174
					$out .= '&#'.$number.';';
175
					$count = 1;
176
					$temp = array();
177
				}
178
				// If this is the last iteration, just output whatever we have
179
				elseif ($i === $s)
180
				{
181
					$out .= '&#'.implode(';', $temp).';';
182
				}
183
			}
184
		}
185
 
186
		return $out;
187
	}
188
}
189
 
190
// ------------------------------------------------------------------------
191
 
192
if ( ! function_exists('entities_to_ascii'))
193
{
194
	/**
195
	 * Entities to ASCII
196
	 *
197
	 * Converts character entities back to ASCII
198
	 *
199
	 * @param	string
200
	 * @param	bool
201
	 * @return	string
202
	 */
203
	function entities_to_ascii($str, $all = TRUE)
204
	{
205
		if (preg_match_all('/\&#(\d+)\;/', $str, $matches))
206
		{
207
			for ($i = 0, $s = count($matches[0]); $i < $s; $i++)
208
			{
209
				$digits = $matches[1][$i];
210
				$out = '';
211
 
212
				if ($digits < 128)
213
				{
214
					$out .= chr($digits);
215
 
216
				}
217
				elseif ($digits < 2048)
218
				{
219
					$out .= chr(192 + (($digits - ($digits % 64)) / 64)).chr(128 + ($digits % 64));
220
				}
221
				else
222
				{
223
					$out .= chr(224 + (($digits - ($digits % 4096)) / 4096))
224
						.chr(128 + ((($digits % 4096) - ($digits % 64)) / 64))
225
						.chr(128 + ($digits % 64));
226
				}
227
 
228
				$str = str_replace($matches[0][$i], $out, $str);
229
			}
230
		}
231
 
232
		if ($all)
233
		{
234
			return str_replace(
235
				array('&amp;', '&lt;', '&gt;', '&quot;', '&apos;', '&#45;'),
236
				array('&', '<', '>', '"', "'", '-'),
237
				$str
238
			);
239
		}
240
 
241
		return $str;
242
	}
243
}
244
 
245
// ------------------------------------------------------------------------
246
 
247
if ( ! function_exists('word_censor'))
248
{
249
	/**
250
	 * Word Censoring Function
251
	 *
252
	 * Supply a string and an array of disallowed words and any
253
	 * matched words will be converted to #### or to the replacement
254
	 * word you've submitted.
255
	 *
256
	 * @param	string	the text string
257
	 * @param	string	the array of censored words
258
	 * @param	string	the optional replacement value
259
	 * @return	string
260
	 */
261
	function word_censor($str, $censored, $replacement = '')
262
	{
263
		if ( ! is_array($censored))
264
		{
265
			return $str;
266
		}
267
 
268
		$str = ' '.$str.' ';
269
 
270
		// \w, \b and a few others do not match on a unicode character
271
		// set for performance reasons. As a result words like über
272
		// will not match on a word boundary. Instead, we'll assume that
273
		// a bad word will be bookeneded by any of these characters.
274
		$delim = '[-_\'\"`(){}<>\[\]|!?@#%&,.:;^~*+=\/ 0-9\n\r\t]';
275
 
276
		foreach ($censored as $badword)
277
		{
278
			$badword = str_replace('\*', '\w*?', preg_quote($badword, '/'));
279
			if ($replacement !== '')
280
			{
281
				$str = preg_replace(
282
					"/({$delim})(".$badword.")({$delim})/i",
283
					"\\1{$replacement}\\3",
284
					$str
285
				);
286
			}
287
			elseif (preg_match_all("/{$delim}(".$badword."){$delim}/i", $str, $matches, PREG_PATTERN_ORDER | PREG_OFFSET_CAPTURE))
288
			{
289
				$matches = $matches[1];
290
				for ($i = count($matches) - 1; $i >= 0; $i--)
291
				{
292
					$length = strlen($matches[$i][0]);
293
					$str = substr_replace(
294
						$str,
295
						str_repeat('#', $length),
296
						$matches[$i][1],
297
						$length
298
					);
299
				}
300
			}
301
		}
302
 
303
		return trim($str);
304
	}
305
}
306
 
307
// ------------------------------------------------------------------------
308
 
309
if ( ! function_exists('highlight_code'))
310
{
311
	/**
312
	 * Code Highlighter
313
	 *
314
	 * Colorizes code strings
315
	 *
316
	 * @param	string	the text string
317
	 * @return	string
318
	 */
319
	function highlight_code($str)
320
	{
321
		/* The highlight string function encodes and highlights
322
		 * brackets so we need them to start raw.
323
		 *
324
		 * Also replace any existing PHP tags to temporary markers
325
		 * so they don't accidentally break the string out of PHP,
326
		 * and thus, thwart the highlighting.
327
		 */
328
		$str = str_replace(
329
			array('&lt;', '&gt;', '<?', '?>', '<%', '%>', '\\', '</script>'),
330
			array('<', '>', 'phptagopen', 'phptagclose', 'asptagopen', 'asptagclose', 'backslashtmp', 'scriptclose'),
331
			$str
332
		);
333
 
334
		// The highlight_string function requires that the text be surrounded
335
		// by PHP tags, which we will remove later
336
		$str = highlight_string('<?php '.$str.' ?>', TRUE);
337
 
338
		// Remove our artificially added PHP, and the syntax highlighting that came with it
339
		$str = preg_replace(
340
			array(
341
				'/<span style="color: #([A-Z0-9]+)">&lt;\?php(&nbsp;| )/i',
342
				'/(<span style="color: #[A-Z0-9]+">.*?)\?&gt;<\/span>\n<\/span>\n<\/code>/is',
343
				'/<span style="color: #[A-Z0-9]+"\><\/span>/i'
344
			),
345
			array(
346
				'<span style="color: #$1">',
347
				"$1</span>\n</span>\n</code>",
348
				''
349
			),
350
			$str
351
		);
352
 
353
		// Replace our markers back to PHP tags.
354
		return str_replace(
355
			array('phptagopen', 'phptagclose', 'asptagopen', 'asptagclose', 'backslashtmp', 'scriptclose'),
356
			array('&lt;?', '?&gt;', '&lt;%', '%&gt;', '\\', '&lt;/script&gt;'),
357
			$str
358
		);
359
	}
360
}
361
 
362
// ------------------------------------------------------------------------
363
 
364
if ( ! function_exists('highlight_phrase'))
365
{
366
	/**
367
	 * Phrase Highlighter
368
	 *
369
	 * Highlights a phrase within a text string
370
	 *
371
	 * @param	string	$str		the text string
372
	 * @param	string	$phrase		the phrase you'd like to highlight
373
	 * @param	string	$tag_open	the openging tag to precede the phrase with
374
	 * @param	string	$tag_close	the closing tag to end the phrase with
375
	 * @return	string
376
	 */
377
	function highlight_phrase($str, $phrase, $tag_open = '<mark>', $tag_close = '</mark>')
378
	{
379
		return ($str !== '' && $phrase !== '')
380
			? preg_replace('/('.preg_quote($phrase, '/').')/i'.(UTF8_ENABLED ? 'u' : ''), $tag_open.'\\1'.$tag_close, $str)
381
			: $str;
382
	}
383
}
384
 
385
// ------------------------------------------------------------------------
386
 
387
if ( ! function_exists('convert_accented_characters'))
388
{
389
	/**
390
	 * Convert Accented Foreign Characters to ASCII
391
	 *
392
	 * @param	string	$str	Input string
393
	 * @return	string
394
	 */
395
	function convert_accented_characters($str)
396
	{
397
		static $array_from, $array_to;
398
 
399
		if ( ! is_array($array_from))
400
		{
401
			if (file_exists(APPPATH.'config/foreign_chars.php'))
402
			{
403
				include(APPPATH.'config/foreign_chars.php');
404
			}
405
 
406
			if (file_exists(APPPATH.'config/'.ENVIRONMENT.'/foreign_chars.php'))
407
			{
408
				include(APPPATH.'config/'.ENVIRONMENT.'/foreign_chars.php');
409
			}
410
 
411
			if (empty($foreign_characters) OR ! is_array($foreign_characters))
412
			{
413
				$array_from = array();
414
				$array_to = array();
415
 
416
				return $str;
417
			}
418
 
419
			$array_from = array_keys($foreign_characters);
420
			$array_to = array_values($foreign_characters);
421
		}
422
 
423
		return preg_replace($array_from, $array_to, $str);
424
	}
425
}
426
 
427
// ------------------------------------------------------------------------
428
 
429
if ( ! function_exists('word_wrap'))
430
{
431
	/**
432
	 * Word Wrap
433
	 *
434
	 * Wraps text at the specified character. Maintains the integrity of words.
435
	 * Anything placed between {unwrap}{/unwrap} will not be word wrapped, nor
436
	 * will URLs.
437
	 *
438
	 * @param	string	$str		the text string
439
	 * @param	int	$charlim = 76	the number of characters to wrap at
440
	 * @return	string
441
	 */
442
	function word_wrap($str, $charlim = 76)
443
	{
444
		// Set the character limit
445
		is_numeric($charlim) OR $charlim = 76;
446
 
447
		// Reduce multiple spaces
448
		$str = preg_replace('| +|', ' ', $str);
449
 
450
		// Standardize newlines
451
		if (strpos($str, "\r") !== FALSE)
452
		{
453
			$str = str_replace(array("\r\n", "\r"), "\n", $str);
454
		}
455
 
456
		// If the current word is surrounded by {unwrap} tags we'll
457
		// strip the entire chunk and replace it with a marker.
458
		$unwrap = array();
459
		if (preg_match_all('|\{unwrap\}(.+?)\{/unwrap\}|s', $str, $matches))
460
		{
461
			for ($i = 0, $c = count($matches[0]); $i < $c; $i++)
462
			{
463
				$unwrap[] = $matches[1][$i];
464
				$str = str_replace($matches[0][$i], '{{unwrapped'.$i.'}}', $str);
465
			}
466
		}
467
 
468
		// Use PHP's native function to do the initial wordwrap.
469
		// We set the cut flag to FALSE so that any individual words that are
470
		// too long get left alone. In the next step we'll deal with them.
471
		$str = wordwrap($str, $charlim, "\n", FALSE);
472
 
473
		// Split the string into individual lines of text and cycle through them
474
		$output = '';
475
		foreach (explode("\n", $str) as $line)
476
		{
477
			// Is the line within the allowed character count?
478
			// If so we'll join it to the output and continue
479
			if (mb_strlen($line) <= $charlim)
480
			{
481
				$output .= $line."\n";
482
				continue;
483
			}
484
 
485
			$temp = '';
486
			while (mb_strlen($line) > $charlim)
487
			{
488
				// If the over-length word is a URL we won't wrap it
489
				if (preg_match('!\[url.+\]|://|www\.!', $line))
490
				{
491
					break;
492
				}
493
 
494
				// Trim the word down
495
				$temp .= mb_substr($line, 0, $charlim - 1);
496
				$line = mb_substr($line, $charlim - 1);
497
			}
498
 
499
			// If $temp contains data it means we had to split up an over-length
500
			// word into smaller chunks so we'll add it back to our current line
501
			if ($temp !== '')
502
			{
503
				$output .= $temp."\n".$line."\n";
504
			}
505
			else
506
			{
507
				$output .= $line."\n";
508
			}
509
		}
510
 
511
		// Put our markers back
512
		if (count($unwrap) > 0)
513
		{
514
			foreach ($unwrap as $key => $val)
515
			{
516
				$output = str_replace('{{unwrapped'.$key.'}}', $val, $output);
517
			}
518
		}
519
 
520
		return $output;
521
	}
522
}
523
 
524
// ------------------------------------------------------------------------
525
 
526
if ( ! function_exists('ellipsize'))
527
{
528
	/**
529
	 * Ellipsize String
530
	 *
531
	 * This function will strip tags from a string, split it at its max_length and ellipsize
532
	 *
533
	 * @param	string	string to ellipsize
534
	 * @param	int	max length of string
535
	 * @param	mixed	int (1|0) or float, .5, .2, etc for position to split
536
	 * @param	string	ellipsis ; Default '...'
537
	 * @return	string	ellipsized string
538
	 */
539
	function ellipsize($str, $max_length, $position = 1, $ellipsis = '&hellip;')
540
	{
541
		// Strip tags
542
		$str = trim(strip_tags($str));
543
 
544
		// Is the string long enough to ellipsize?
545
		if (mb_strlen($str) <= $max_length)
546
		{
547
			return $str;
548
		}
549
 
550
		$beg = mb_substr($str, 0, floor($max_length * $position));
551
		$position = ($position > 1) ? 1 : $position;
552
 
553
		if ($position === 1)
554
		{
555
			$end = mb_substr($str, 0, -($max_length - mb_strlen($beg)));
556
		}
557
		else
558
		{
559
			$end = mb_substr($str, -($max_length - mb_strlen($beg)));
560
		}
561
 
562
		return $beg.$ellipsis.$end;
563
	}
564
}