Subversion-Projekte lars-tiefland.ci

Revision

Revision 2257 | Details | Vergleich mit vorheriger | 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
 *
2414 lars 9
 * Copyright (c) 2014 - 2019, British Columbia Institute of Technology
68 lars 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/)
2414 lars 32
 * @copyright	Copyright (c) 2014 - 2019, British Columbia Institute of Technology (https://bcit.ca/)
33
 * @license	https://opensource.org/licenses/MIT	MIT License
68 lars 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+
2049 lars 105
		$str = preg_replace('/ {2,}/', ' ', str_replace(array("\r", "\n", "\t", "\v", "\f"), ' ', $str));
68 lars 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 = '';
2107 lars 141
		$length = defined('MB_OVERLOAD_STRING')
142
			? mb_strlen($str, '8bit') - 1
143
			: strlen($str) - 1;
144
		for ($i = 0, $count = 1, $temp = array(); $i <= $length; $i++)
68 lars 145
		{
146
			$ordinal = ord($str[$i]);
147
 
148
			if ($ordinal < 128)
149
			{
150
				/*
151
					If the $temp array has a value but we have moved on, then it seems only
152
					fair that we output that entity and restart $temp before continuing. -Paul
153
				*/
154
				if (count($temp) === 1)
155
				{
156
					$out .= '&#'.array_shift($temp).';';
157
					$count = 1;
158
				}
159
 
160
				$out .= $str[$i];
161
			}
162
			else
163
			{
164
				if (count($temp) === 0)
165
				{
166
					$count = ($ordinal < 224) ? 2 : 3;
167
				}
168
 
169
				$temp[] = $ordinal;
170
 
171
				if (count($temp) === $count)
172
				{
173
					$number = ($count === 3)
174
						? (($temp[0] % 16) * 4096) + (($temp[1] % 64) * 64) + ($temp[2] % 64)
175
						: (($temp[0] % 32) * 64) + ($temp[1] % 64);
176
 
177
					$out .= '&#'.$number.';';
178
					$count = 1;
179
					$temp = array();
180
				}
181
				// If this is the last iteration, just output whatever we have
2107 lars 182
				elseif ($i === $length)
68 lars 183
				{
184
					$out .= '&#'.implode(';', $temp).';';
185
				}
186
			}
187
		}
188
 
189
		return $out;
190
	}
191
}
192
 
193
// ------------------------------------------------------------------------
194
 
195
if ( ! function_exists('entities_to_ascii'))
196
{
197
	/**
198
	 * Entities to ASCII
199
	 *
200
	 * Converts character entities back to ASCII
201
	 *
202
	 * @param	string
203
	 * @param	bool
204
	 * @return	string
205
	 */
206
	function entities_to_ascii($str, $all = TRUE)
207
	{
208
		if (preg_match_all('/\&#(\d+)\;/', $str, $matches))
209
		{
210
			for ($i = 0, $s = count($matches[0]); $i < $s; $i++)
211
			{
212
				$digits = $matches[1][$i];
213
				$out = '';
214
 
215
				if ($digits < 128)
216
				{
217
					$out .= chr($digits);
218
 
219
				}
220
				elseif ($digits < 2048)
221
				{
222
					$out .= chr(192 + (($digits - ($digits % 64)) / 64)).chr(128 + ($digits % 64));
223
				}
224
				else
225
				{
226
					$out .= chr(224 + (($digits - ($digits % 4096)) / 4096))
227
						.chr(128 + ((($digits % 4096) - ($digits % 64)) / 64))
228
						.chr(128 + ($digits % 64));
229
				}
230
 
231
				$str = str_replace($matches[0][$i], $out, $str);
232
			}
233
		}
234
 
235
		if ($all)
236
		{
237
			return str_replace(
238
				array('&amp;', '&lt;', '&gt;', '&quot;', '&apos;', '&#45;'),
239
				array('&', '<', '>', '"', "'", '-'),
240
				$str
241
			);
242
		}
243
 
244
		return $str;
245
	}
246
}
247
 
248
// ------------------------------------------------------------------------
249
 
250
if ( ! function_exists('word_censor'))
251
{
252
	/**
253
	 * Word Censoring Function
254
	 *
255
	 * Supply a string and an array of disallowed words and any
256
	 * matched words will be converted to #### or to the replacement
257
	 * word you've submitted.
258
	 *
259
	 * @param	string	the text string
260
	 * @param	string	the array of censored words
261
	 * @param	string	the optional replacement value
262
	 * @return	string
263
	 */
264
	function word_censor($str, $censored, $replacement = '')
265
	{
266
		if ( ! is_array($censored))
267
		{
268
			return $str;
269
		}
270
 
271
		$str = ' '.$str.' ';
272
 
273
		// \w, \b and a few others do not match on a unicode character
274
		// set for performance reasons. As a result words like über
275
		// will not match on a word boundary. Instead, we'll assume that
276
		// a bad word will be bookeneded by any of these characters.
277
		$delim = '[-_\'\"`(){}<>\[\]|!?@#%&,.:;^~*+=\/ 0-9\n\r\t]';
278
 
279
		foreach ($censored as $badword)
280
		{
281
			$badword = str_replace('\*', '\w*?', preg_quote($badword, '/'));
282
			if ($replacement !== '')
283
			{
284
				$str = preg_replace(
285
					"/({$delim})(".$badword.")({$delim})/i",
286
					"\\1{$replacement}\\3",
287
					$str
288
				);
289
			}
290
			elseif (preg_match_all("/{$delim}(".$badword."){$delim}/i", $str, $matches, PREG_PATTERN_ORDER | PREG_OFFSET_CAPTURE))
291
			{
292
				$matches = $matches[1];
293
				for ($i = count($matches) - 1; $i >= 0; $i--)
294
				{
295
					$length = strlen($matches[$i][0]);
296
					$str = substr_replace(
297
						$str,
298
						str_repeat('#', $length),
299
						$matches[$i][1],
300
						$length
301
					);
302
				}
303
			}
304
		}
305
 
306
		return trim($str);
307
	}
308
}
309
 
310
// ------------------------------------------------------------------------
311
 
312
if ( ! function_exists('highlight_code'))
313
{
314
	/**
315
	 * Code Highlighter
316
	 *
317
	 * Colorizes code strings
318
	 *
319
	 * @param	string	the text string
320
	 * @return	string
321
	 */
322
	function highlight_code($str)
323
	{
324
		/* The highlight string function encodes and highlights
325
		 * brackets so we need them to start raw.
326
		 *
327
		 * Also replace any existing PHP tags to temporary markers
328
		 * so they don't accidentally break the string out of PHP,
329
		 * and thus, thwart the highlighting.
330
		 */
331
		$str = str_replace(
332
			array('&lt;', '&gt;', '<?', '?>', '<%', '%>', '\\', '</script>'),
333
			array('<', '>', 'phptagopen', 'phptagclose', 'asptagopen', 'asptagclose', 'backslashtmp', 'scriptclose'),
334
			$str
335
		);
336
 
337
		// The highlight_string function requires that the text be surrounded
338
		// by PHP tags, which we will remove later
339
		$str = highlight_string('<?php '.$str.' ?>', TRUE);
340
 
341
		// Remove our artificially added PHP, and the syntax highlighting that came with it
342
		$str = preg_replace(
343
			array(
344
				'/<span style="color: #([A-Z0-9]+)">&lt;\?php(&nbsp;| )/i',
345
				'/(<span style="color: #[A-Z0-9]+">.*?)\?&gt;<\/span>\n<\/span>\n<\/code>/is',
346
				'/<span style="color: #[A-Z0-9]+"\><\/span>/i'
347
			),
348
			array(
349
				'<span style="color: #$1">',
350
				"$1</span>\n</span>\n</code>",
351
				''
352
			),
353
			$str
354
		);
355
 
356
		// Replace our markers back to PHP tags.
357
		return str_replace(
358
			array('phptagopen', 'phptagclose', 'asptagopen', 'asptagclose', 'backslashtmp', 'scriptclose'),
359
			array('&lt;?', '?&gt;', '&lt;%', '%&gt;', '\\', '&lt;/script&gt;'),
360
			$str
361
		);
362
	}
363
}
364
 
365
// ------------------------------------------------------------------------
366
 
367
if ( ! function_exists('highlight_phrase'))
368
{
369
	/**
370
	 * Phrase Highlighter
371
	 *
372
	 * Highlights a phrase within a text string
373
	 *
374
	 * @param	string	$str		the text string
375
	 * @param	string	$phrase		the phrase you'd like to highlight
376
	 * @param	string	$tag_open	the openging tag to precede the phrase with
377
	 * @param	string	$tag_close	the closing tag to end the phrase with
378
	 * @return	string
379
	 */
380
	function highlight_phrase($str, $phrase, $tag_open = '<mark>', $tag_close = '</mark>')
381
	{
382
		return ($str !== '' && $phrase !== '')
383
			? preg_replace('/('.preg_quote($phrase, '/').')/i'.(UTF8_ENABLED ? 'u' : ''), $tag_open.'\\1'.$tag_close, $str)
384
			: $str;
385
	}
386
}
387
 
388
// ------------------------------------------------------------------------
389
 
390
if ( ! function_exists('convert_accented_characters'))
391
{
392
	/**
393
	 * Convert Accented Foreign Characters to ASCII
394
	 *
395
	 * @param	string	$str	Input string
396
	 * @return	string
397
	 */
398
	function convert_accented_characters($str)
399
	{
400
		static $array_from, $array_to;
401
 
402
		if ( ! is_array($array_from))
403
		{
404
			if (file_exists(APPPATH.'config/foreign_chars.php'))
405
			{
406
				include(APPPATH.'config/foreign_chars.php');
407
			}
408
 
409
			if (file_exists(APPPATH.'config/'.ENVIRONMENT.'/foreign_chars.php'))
410
			{
411
				include(APPPATH.'config/'.ENVIRONMENT.'/foreign_chars.php');
412
			}
413
 
414
			if (empty($foreign_characters) OR ! is_array($foreign_characters))
415
			{
416
				$array_from = array();
417
				$array_to = array();
418
 
419
				return $str;
420
			}
421
 
422
			$array_from = array_keys($foreign_characters);
423
			$array_to = array_values($foreign_characters);
424
		}
425
 
426
		return preg_replace($array_from, $array_to, $str);
427
	}
428
}
429
 
430
// ------------------------------------------------------------------------
431
 
432
if ( ! function_exists('word_wrap'))
433
{
434
	/**
435
	 * Word Wrap
436
	 *
437
	 * Wraps text at the specified character. Maintains the integrity of words.
438
	 * Anything placed between {unwrap}{/unwrap} will not be word wrapped, nor
439
	 * will URLs.
440
	 *
441
	 * @param	string	$str		the text string
442
	 * @param	int	$charlim = 76	the number of characters to wrap at
443
	 * @return	string
444
	 */
445
	function word_wrap($str, $charlim = 76)
446
	{
447
		// Set the character limit
448
		is_numeric($charlim) OR $charlim = 76;
449
 
450
		// Reduce multiple spaces
451
		$str = preg_replace('| +|', ' ', $str);
452
 
453
		// Standardize newlines
454
		if (strpos($str, "\r") !== FALSE)
455
		{
456
			$str = str_replace(array("\r\n", "\r"), "\n", $str);
457
		}
458
 
459
		// If the current word is surrounded by {unwrap} tags we'll
460
		// strip the entire chunk and replace it with a marker.
461
		$unwrap = array();
462
		if (preg_match_all('|\{unwrap\}(.+?)\{/unwrap\}|s', $str, $matches))
463
		{
464
			for ($i = 0, $c = count($matches[0]); $i < $c; $i++)
465
			{
466
				$unwrap[] = $matches[1][$i];
467
				$str = str_replace($matches[0][$i], '{{unwrapped'.$i.'}}', $str);
468
			}
469
		}
470
 
471
		// Use PHP's native function to do the initial wordwrap.
472
		// We set the cut flag to FALSE so that any individual words that are
473
		// too long get left alone. In the next step we'll deal with them.
474
		$str = wordwrap($str, $charlim, "\n", FALSE);
475
 
476
		// Split the string into individual lines of text and cycle through them
477
		$output = '';
478
		foreach (explode("\n", $str) as $line)
479
		{
480
			// Is the line within the allowed character count?
481
			// If so we'll join it to the output and continue
482
			if (mb_strlen($line) <= $charlim)
483
			{
484
				$output .= $line."\n";
485
				continue;
486
			}
487
 
488
			$temp = '';
489
			while (mb_strlen($line) > $charlim)
490
			{
491
				// If the over-length word is a URL we won't wrap it
492
				if (preg_match('!\[url.+\]|://|www\.!', $line))
493
				{
494
					break;
495
				}
496
 
497
				// Trim the word down
498
				$temp .= mb_substr($line, 0, $charlim - 1);
499
				$line = mb_substr($line, $charlim - 1);
500
			}
501
 
502
			// If $temp contains data it means we had to split up an over-length
503
			// word into smaller chunks so we'll add it back to our current line
504
			if ($temp !== '')
505
			{
506
				$output .= $temp."\n".$line."\n";
507
			}
508
			else
509
			{
510
				$output .= $line."\n";
511
			}
512
		}
513
 
514
		// Put our markers back
515
		if (count($unwrap) > 0)
516
		{
517
			foreach ($unwrap as $key => $val)
518
			{
519
				$output = str_replace('{{unwrapped'.$key.'}}', $val, $output);
520
			}
521
		}
522
 
523
		return $output;
524
	}
525
}
526
 
527
// ------------------------------------------------------------------------
528
 
529
if ( ! function_exists('ellipsize'))
530
{
531
	/**
532
	 * Ellipsize String
533
	 *
534
	 * This function will strip tags from a string, split it at its max_length and ellipsize
535
	 *
536
	 * @param	string	string to ellipsize
537
	 * @param	int	max length of string
538
	 * @param	mixed	int (1|0) or float, .5, .2, etc for position to split
539
	 * @param	string	ellipsis ; Default '...'
540
	 * @return	string	ellipsized string
541
	 */
542
	function ellipsize($str, $max_length, $position = 1, $ellipsis = '&hellip;')
543
	{
544
		// Strip tags
545
		$str = trim(strip_tags($str));
546
 
547
		// Is the string long enough to ellipsize?
548
		if (mb_strlen($str) <= $max_length)
549
		{
550
			return $str;
551
		}
552
 
553
		$beg = mb_substr($str, 0, floor($max_length * $position));
554
		$position = ($position > 1) ? 1 : $position;
555
 
556
		if ($position === 1)
557
		{
558
			$end = mb_substr($str, 0, -($max_length - mb_strlen($beg)));
559
		}
560
		else
561
		{
562
			$end = mb_substr($str, -($max_length - mb_strlen($beg)));
563
		}
564
 
565
		return $beg.$ellipsis.$end;
566
	}
567
}