Unicode   C
last analyzed

Complexity

Total Complexity 79

Size/Duplication

Total Lines 715
Duplicated Lines 7.55 %

Coupling/Cohesion

Components 1
Dependencies 0

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 79
lcom 1
cbo 0
dl 54
loc 715
rs 5
c 1
b 0
f 0

20 Methods

Rating   Name   Duplication   Size   Complexity  
D substr() 30 86 27
A strpos() 0 12 2
A getStatus() 0 3 1
A setStatus() 0 6 2
C check() 0 35 7
A encodingFromBOM() 0 21 3
A convertToUtf8() 0 13 4
B truncateBytes() 0 12 7
A strlen() 0 9 2
A strtoupper() 12 12 2
A strtolower() 12 12 2
A ucfirst() 0 3 1
A lcfirst() 0 4 1
A ucwords() 0 6 1
C truncate() 0 48 7
A strcasecmp() 0 3 1
A mimeHeaderEncode() 0 16 3
A mimeHeaderDecode() 0 13 3
A caseFlip() 0 3 1
A validateUtf8() 0 9 2

How to fix   Duplicated Code    Complexity   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

Complex Class

 Tip:   Before tackling complexity, make sure that you eliminate any duplication first. This often can reduce the size of classes significantly.

Complex classes like Unicode often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use Unicode, and based on these observations, apply Extract Interface, too.

1
<?php
2
3
/**
4
 * @file
5
 * Contains \Drupal\Component\Utility\Unicode.
6
 */
7
8
namespace Drupal\Component\Utility;
9
10
/**
11
 * Provides Unicode-related conversions and operations.
12
 *
13
 * @ingroup utility
14
 */
15
class Unicode {
16
17
  /**
18
   * Matches Unicode characters that are word boundaries.
19
   *
20
   * Characters with the following General_category (gc) property values are used
21
   * as word boundaries. While this does not fully conform to the Word Boundaries
22
   * algorithm described in http://unicode.org/reports/tr29, as PCRE does not
23
   * contain the Word_Break property table, this simpler algorithm has to do.
24
   * - Cc, Cf, Cn, Co, Cs: Other.
25
   * - Pc, Pd, Pe, Pf, Pi, Po, Ps: Punctuation.
26
   * - Sc, Sk, Sm, So: Symbols.
27
   * - Zl, Zp, Zs: Separators.
28
   *
29
   * Non-boundary characters include the following General_category (gc) property
30
   * values:
31
   * - Ll, Lm, Lo, Lt, Lu: Letters.
32
   * - Mc, Me, Mn: Combining Marks.
33
   * - Nd, Nl, No: Numbers.
34
   *
35
   * Note that the PCRE property matcher is not used because we wanted to be
36
   * compatible with Unicode 5.2.0 regardless of the PCRE version used (and any
37
   * bugs in PCRE property tables).
38
   *
39
   * @see http://unicode.org/glossary
40
   */
41
  const PREG_CLASS_WORD_BOUNDARY = <<<'EOD'
42
\x{0}-\x{2F}\x{3A}-\x{40}\x{5B}-\x{60}\x{7B}-\x{A9}\x{AB}-\x{B1}\x{B4}
43
\x{B6}-\x{B8}\x{BB}\x{BF}\x{D7}\x{F7}\x{2C2}-\x{2C5}\x{2D2}-\x{2DF}
44
\x{2E5}-\x{2EB}\x{2ED}\x{2EF}-\x{2FF}\x{375}\x{37E}-\x{385}\x{387}\x{3F6}
45
\x{482}\x{55A}-\x{55F}\x{589}-\x{58A}\x{5BE}\x{5C0}\x{5C3}\x{5C6}
46
\x{5F3}-\x{60F}\x{61B}-\x{61F}\x{66A}-\x{66D}\x{6D4}\x{6DD}\x{6E9}
47
\x{6FD}-\x{6FE}\x{700}-\x{70F}\x{7F6}-\x{7F9}\x{830}-\x{83E}
48
\x{964}-\x{965}\x{970}\x{9F2}-\x{9F3}\x{9FA}-\x{9FB}\x{AF1}\x{B70}
49
\x{BF3}-\x{BFA}\x{C7F}\x{CF1}-\x{CF2}\x{D79}\x{DF4}\x{E3F}\x{E4F}
50
\x{E5A}-\x{E5B}\x{F01}-\x{F17}\x{F1A}-\x{F1F}\x{F34}\x{F36}\x{F38}
51
\x{F3A}-\x{F3D}\x{F85}\x{FBE}-\x{FC5}\x{FC7}-\x{FD8}\x{104A}-\x{104F}
52
\x{109E}-\x{109F}\x{10FB}\x{1360}-\x{1368}\x{1390}-\x{1399}\x{1400}
53
\x{166D}-\x{166E}\x{1680}\x{169B}-\x{169C}\x{16EB}-\x{16ED}
54
\x{1735}-\x{1736}\x{17B4}-\x{17B5}\x{17D4}-\x{17D6}\x{17D8}-\x{17DB}
55
\x{1800}-\x{180A}\x{180E}\x{1940}-\x{1945}\x{19DE}-\x{19FF}
56
\x{1A1E}-\x{1A1F}\x{1AA0}-\x{1AA6}\x{1AA8}-\x{1AAD}\x{1B5A}-\x{1B6A}
57
\x{1B74}-\x{1B7C}\x{1C3B}-\x{1C3F}\x{1C7E}-\x{1C7F}\x{1CD3}\x{1FBD}
58
\x{1FBF}-\x{1FC1}\x{1FCD}-\x{1FCF}\x{1FDD}-\x{1FDF}\x{1FED}-\x{1FEF}
59
\x{1FFD}-\x{206F}\x{207A}-\x{207E}\x{208A}-\x{208E}\x{20A0}-\x{20B8}
60
\x{2100}-\x{2101}\x{2103}-\x{2106}\x{2108}-\x{2109}\x{2114}
61
\x{2116}-\x{2118}\x{211E}-\x{2123}\x{2125}\x{2127}\x{2129}\x{212E}
62
\x{213A}-\x{213B}\x{2140}-\x{2144}\x{214A}-\x{214D}\x{214F}
63
\x{2190}-\x{244A}\x{249C}-\x{24E9}\x{2500}-\x{2775}\x{2794}-\x{2B59}
64
\x{2CE5}-\x{2CEA}\x{2CF9}-\x{2CFC}\x{2CFE}-\x{2CFF}\x{2E00}-\x{2E2E}
65
\x{2E30}-\x{3004}\x{3008}-\x{3020}\x{3030}\x{3036}-\x{3037}
66
\x{303D}-\x{303F}\x{309B}-\x{309C}\x{30A0}\x{30FB}\x{3190}-\x{3191}
67
\x{3196}-\x{319F}\x{31C0}-\x{31E3}\x{3200}-\x{321E}\x{322A}-\x{3250}
68
\x{3260}-\x{327F}\x{328A}-\x{32B0}\x{32C0}-\x{33FF}\x{4DC0}-\x{4DFF}
69
\x{A490}-\x{A4C6}\x{A4FE}-\x{A4FF}\x{A60D}-\x{A60F}\x{A673}\x{A67E}
70
\x{A6F2}-\x{A716}\x{A720}-\x{A721}\x{A789}-\x{A78A}\x{A828}-\x{A82B}
71
\x{A836}-\x{A839}\x{A874}-\x{A877}\x{A8CE}-\x{A8CF}\x{A8F8}-\x{A8FA}
72
\x{A92E}-\x{A92F}\x{A95F}\x{A9C1}-\x{A9CD}\x{A9DE}-\x{A9DF}
73
\x{AA5C}-\x{AA5F}\x{AA77}-\x{AA79}\x{AADE}-\x{AADF}\x{ABEB}
74
\x{E000}-\x{F8FF}\x{FB29}\x{FD3E}-\x{FD3F}\x{FDFC}-\x{FDFD}
75
\x{FE10}-\x{FE19}\x{FE30}-\x{FE6B}\x{FEFF}-\x{FF0F}\x{FF1A}-\x{FF20}
76
\x{FF3B}-\x{FF40}\x{FF5B}-\x{FF65}\x{FFE0}-\x{FFFD}
77
EOD;
78
79
  /**
80
   * Indicates that standard PHP (emulated) unicode support is being used.
81
   */
82
  const STATUS_SINGLEBYTE = 0;
83
84
  /**
85
   * Indicates that full unicode support with the PHP mbstring extension is
86
   * being used.
87
   */
88
  const STATUS_MULTIBYTE = 1;
89
90
  /**
91
   * Indicates an error during check for PHP unicode support.
92
   */
93
  const STATUS_ERROR = -1;
94
95
  /**
96
   * Holds the multibyte capabilities of the current environment.
97
   *
98
   * @var int
99
   */
100
  protected static $status = 0;
101
102
  /**
103
   * Gets the current status of unicode/multibyte support on this environment.
104
   *
105
   * @return int
106
   *   The status of multibyte support. It can be one of:
107
   *   - \Drupal\Component\Utility\Unicode::STATUS_MULTIBYTE
108
   *     Full unicode support using an extension.
109
   *   - \Drupal\Component\Utility\Unicode::STATUS_SINGLEBYTE
110
   *     Standard PHP (emulated) unicode support.
111
   *   - \Drupal\Component\Utility\Unicode::STATUS_ERROR
112
   *     An error occurred. No unicode support.
113
   */
114
  public static function getStatus() {
115
    return static::$status;
116
  }
117
118
  /**
119
   * Sets the value for multibyte support status for the current environment.
120
   *
121
   * The following status keys are supported:
122
   *   - \Drupal\Component\Utility\Unicode::STATUS_MULTIBYTE
123
   *     Full unicode support using an extension.
124
   *   - \Drupal\Component\Utility\Unicode::STATUS_SINGLEBYTE
125
   *     Standard PHP (emulated) unicode support.
126
   *   - \Drupal\Component\Utility\Unicode::STATUS_ERROR
127
   *     An error occurred. No unicode support.
128
   *
129
   * @param int $status
130
   *   The new status of multibyte support.
131
   */
132
  public static function setStatus($status) {
133
    if (!in_array($status, array(static::STATUS_SINGLEBYTE, static::STATUS_MULTIBYTE, static::STATUS_ERROR))) {
134
      throw new \InvalidArgumentException('Invalid status value for unicode support.');
135
    }
136
    static::$status = $status;
137
  }
138
139
  /**
140
   * Checks for Unicode support in PHP and sets the proper settings if possible.
141
   *
142
   * Because of the need to be able to handle text in various encodings, we do
143
   * not support mbstring function overloading. HTTP input/output conversion
144
   * must be disabled for similar reasons.
145
   *
146
   * @return string
147
   *   A string identifier of a failed multibyte extension check, if any.
148
   *   Otherwise, an empty string.
149
   */
150
  public static function check() {
151
    // Check for mbstring extension.
152
    if (!function_exists('mb_strlen')) {
153
      static::$status = static::STATUS_SINGLEBYTE;
154
      return 'mb_strlen';
155
    }
156
157
    // Check mbstring configuration.
158
    if (ini_get('mbstring.func_overload') != 0) {
159
      static::$status = static::STATUS_ERROR;
160
      return 'mbstring.func_overload';
161
    }
162
    if (ini_get('mbstring.encoding_translation') != 0) {
163
      static::$status = static::STATUS_ERROR;
164
      return 'mbstring.encoding_translation';
165
    }
166
    // mbstring.http_input and mbstring.http_output are deprecated and empty by
167
    // default in PHP 5.6.
168
    if (version_compare(PHP_VERSION, '5.6.0') == -1) {
169
      if (ini_get('mbstring.http_input') != 'pass') {
170
        static::$status = static::STATUS_ERROR;
171
        return 'mbstring.http_input';
172
      }
173
      if (ini_get('mbstring.http_output') != 'pass') {
174
        static::$status = static::STATUS_ERROR;
175
        return 'mbstring.http_output';
176
      }
177
    }
178
179
    // Set appropriate configuration.
180
    mb_internal_encoding('utf-8');
181
    mb_language('uni');
182
    static::$status = static::STATUS_MULTIBYTE;
183
    return '';
184
  }
185
186
  /**
187
   * Decodes UTF byte-order mark (BOM) into the encoding's name.
188
   *
189
   * @param string $data
190
   *   The data possibly containing a BOM. This can be the entire contents of
191
   *   a file, or just a fragment containing at least the first five bytes.
192
   *
193
   * @return string|bool
194
   *   The name of the encoding, or FALSE if no byte order mark was present.
195
   */
196
  public static function encodingFromBOM($data) {
197
    static $bomMap = array(
198
      "\xEF\xBB\xBF" => 'UTF-8',
199
      "\xFE\xFF" => 'UTF-16BE',
200
      "\xFF\xFE" => 'UTF-16LE',
201
      "\x00\x00\xFE\xFF" => 'UTF-32BE',
202
      "\xFF\xFE\x00\x00" => 'UTF-32LE',
203
      "\x2B\x2F\x76\x38" => 'UTF-7',
204
      "\x2B\x2F\x76\x39" => 'UTF-7',
205
      "\x2B\x2F\x76\x2B" => 'UTF-7',
206
      "\x2B\x2F\x76\x2F" => 'UTF-7',
207
      "\x2B\x2F\x76\x38\x2D" => 'UTF-7',
208
    );
209
210
    foreach ($bomMap as $bom => $encoding) {
211
      if (strpos($data, $bom) === 0) {
212
        return $encoding;
213
      }
214
    }
215
    return FALSE;
216
  }
217
218
  /**
219
   * Converts data to UTF-8.
220
   *
221
   * Requires the iconv, GNU recode or mbstring PHP extension.
222
   *
223
   * @param string $data
224
   *   The data to be converted.
225
   * @param string $encoding
226
   *   The encoding that the data is in.
227
   *
228
   * @return string|bool
229
   *   Converted data or FALSE.
230
   */
231
  public static function convertToUtf8($data, $encoding) {
232
    if (function_exists('iconv')) {
233
      return @iconv($encoding, 'utf-8', $data);
234
    }
235
    elseif (function_exists('mb_convert_encoding')) {
236
      return @mb_convert_encoding($data, 'utf-8', $encoding);
237
    }
238
    elseif (function_exists('recode_string')) {
239
      return @recode_string($encoding . '..utf-8', $data);
240
    }
241
    // Cannot convert.
242
    return FALSE;
243
  }
244
245
  /**
246
   * Truncates a UTF-8-encoded string safely to a number of bytes.
247
   *
248
   * If the end position is in the middle of a UTF-8 sequence, it scans backwards
249
   * until the beginning of the byte sequence.
250
   *
251
   * Use this function whenever you want to chop off a string at an unsure
252
   * location. On the other hand, if you're sure that you're splitting on a
253
   * character boundary (e.g. after using strpos() or similar), you can safely
254
   * use substr() instead.
255
   *
256
   * @param string $string
257
   *   The string to truncate.
258
   * @param int $len
259
   *   An upper limit on the returned string length.
260
   *
261
   * @return string
262
   *   The truncated string.
263
   */
264
  public static function truncateBytes($string, $len) {
265
    if (strlen($string) <= $len) {
266
      return $string;
267
    }
268
    if ((ord($string[$len]) < 0x80) || (ord($string[$len]) >= 0xC0)) {
269
      return substr($string, 0, $len);
270
    }
271
    // Scan backwards to beginning of the byte sequence.
272
    while (--$len >= 0 && ord($string[$len]) >= 0x80 && ord($string[$len]) < 0xC0);
273
274
    return substr($string, 0, $len);
275
  }
276
277
  /**
278
   * Counts the number of characters in a UTF-8 string.
279
   *
280
   * This is less than or equal to the byte count.
281
   *
282
   * @param string $text
283
   *   The string to run the operation on.
284
   *
285
   * @return int
286
   *   The length of the string.
287
   */
288
  public static function strlen($text) {
289
    if (static::getStatus() == static::STATUS_MULTIBYTE) {
290
      return mb_strlen($text);
291
    }
292
    else {
293
      // Do not count UTF-8 continuation bytes.
294
      return strlen(preg_replace("/[\x80-\xBF]/", '', $text));
295
    }
296
  }
297
298
  /**
299
   * Converts a UTF-8 string to uppercase.
300
   *
301
   * @param string $text
302
   *   The string to run the operation on.
303
   *
304
   * @return string
305
   *   The string in uppercase.
306
   */
307 View Code Duplication
  public static function strtoupper($text) {
308
    if (static::getStatus() == static::STATUS_MULTIBYTE) {
309
      return mb_strtoupper($text);
310
    }
311
    else {
312
      // Use C-locale for ASCII-only uppercase.
313
      $text = strtoupper($text);
314
      // Case flip Latin-1 accented letters.
315
      $text = preg_replace_callback('/\xC3[\xA0-\xB6\xB8-\xBE]/', '\Drupal\Component\Utility\Unicode::caseFlip', $text);
316
      return $text;
317
    }
318
  }
319
320
  /**
321
   * Converts a UTF-8 string to lowercase.
322
   *
323
   * @param string $text
324
   *   The string to run the operation on.
325
   *
326
   * @return string
327
   *   The string in lowercase.
328
   */
329 View Code Duplication
  public static function strtolower($text) {
330
    if (static::getStatus() == static::STATUS_MULTIBYTE) {
331
      return mb_strtolower($text);
332
    }
333
    else {
334
      // Use C-locale for ASCII-only lowercase.
335
      $text = strtolower($text);
336
      // Case flip Latin-1 accented letters.
337
      $text = preg_replace_callback('/\xC3[\x80-\x96\x98-\x9E]/', '\Drupal\Component\Utility\Unicode::caseFlip', $text);
338
      return $text;
339
    }
340
  }
341
342
  /**
343
   * Capitalizes the first character of a UTF-8 string.
344
   *
345
   * @param string $text
346
   *   The string to convert.
347
   *
348
   * @return string
349
   *   The string with the first character as uppercase.
350
   */
351
  public static function ucfirst($text) {
352
    return static::strtoupper(static::substr($text, 0, 1)) . static::substr($text, 1);
353
  }
354
355
  /**
356
   * Converts the first character of a UTF-8 string to lowercase.
357
   *
358
   * @param string $text
359
   *   The string that will be converted.
360
   *
361
   * @return string
362
   *   The string with the first character as lowercase.
363
   *
364
   * @ingroup php_wrappers
365
   */
366
  public static function lcfirst($text) {
367
    // Note: no mbstring equivalent!
368
    return static::strtolower(static::substr($text, 0, 1)) . static::substr($text, 1);
369
  }
370
371
  /**
372
   * Capitalizes the first character of each word in a UTF-8 string.
373
   *
374
   * @param string $text
375
   *   The text that will be converted.
376
   *
377
   * @return string
378
   *   The input $text with each word capitalized.
379
   *
380
   * @ingroup php_wrappers
381
   */
382
  public static function ucwords($text) {
383
    $regex = '/(^|[' . static::PREG_CLASS_WORD_BOUNDARY . '])([^' . static::PREG_CLASS_WORD_BOUNDARY . '])/u';
384
    return preg_replace_callback($regex, function(array $matches) {
385
      return $matches[1] . Unicode::strtoupper($matches[2]);
386
    }, $text);
387
  }
388
389
  /**
390
   * Cuts off a piece of a string based on character indices and counts.
391
   *
392
   * Follows the same behavior as PHP's own substr() function. Note that for
393
   * cutting off a string at a known character/substring location, the usage of
394
   * PHP's normal strpos/substr is safe and much faster.
395
   *
396
   * @param string $text
397
   *   The input string.
398
   * @param int $start
399
   *   The position at which to start reading.
400
   * @param int $length
401
   *   The number of characters to read.
402
   *
403
   * @return string
404
   *   The shortened string.
405
   */
406
  public static function substr($text, $start, $length = NULL) {
407
    if (static::getStatus() == static::STATUS_MULTIBYTE) {
408
      return $length === NULL ? mb_substr($text, $start) : mb_substr($text, $start, $length);
409
    }
410
    else {
411
      $strlen = strlen($text);
412
      // Find the starting byte offset.
413
      $bytes = 0;
414
      if ($start > 0) {
415
        // Count all the characters except continuation bytes from the start
416
        // until we have found $start characters or the end of the string.
417
        $bytes = -1; $chars = -1;
418
        while ($bytes < $strlen - 1 && $chars < $start) {
419
          $bytes++;
420
          $c = ord($text[$bytes]);
421
          if ($c < 0x80 || $c >= 0xC0) {
422
            $chars++;
423
          }
424
        }
425
      }
426 View Code Duplication
      elseif ($start < 0) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
427
        // Count all the characters except continuation bytes from the end
428
        // until we have found abs($start) characters.
429
        $start = abs($start);
430
        $bytes = $strlen; $chars = 0;
431
        while ($bytes > 0 && $chars < $start) {
432
          $bytes--;
433
          $c = ord($text[$bytes]);
434
          if ($c < 0x80 || $c >= 0xC0) {
435
            $chars++;
436
          }
437
        }
438
      }
439
      $istart = $bytes;
440
441
      // Find the ending byte offset.
442
      if ($length === NULL) {
443
        $iend = $strlen;
444
      }
445
      elseif ($length > 0) {
446
        // Count all the characters except continuation bytes from the starting
447
        // index until we have found $length characters or reached the end of
448
        // the string, then backtrace one byte.
449
        $iend = $istart - 1;
450
        $chars = -1;
451
        $last_real = FALSE;
452
        while ($iend < $strlen - 1 && $chars < $length) {
453
          $iend++;
454
          $c = ord($text[$iend]);
455
          $last_real = FALSE;
456
          if ($c < 0x80 || $c >= 0xC0) {
457
            $chars++;
458
            $last_real = TRUE;
459
          }
460
        }
461
        // Backtrace one byte if the last character we found was a real
462
        // character and we don't need it.
463
        if ($last_real && $chars >= $length) {
464
          $iend--;
465
        }
466
      }
467 View Code Duplication
      elseif ($length < 0) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
468
        // Count all the characters except continuation bytes from the end
469
        // until we have found abs($start) characters, then backtrace one byte.
470
        $length = abs($length);
471
        $iend = $strlen; $chars = 0;
472
        while ($iend > 0 && $chars < $length) {
473
          $iend--;
474
          $c = ord($text[$iend]);
475
          if ($c < 0x80 || $c >= 0xC0) {
476
            $chars++;
477
          }
478
        }
479
        // Backtrace one byte if we are not at the beginning of the string.
480
        if ($iend > 0) {
481
          $iend--;
482
        }
483
      }
484
      else {
485
        // $length == 0, return an empty string.
486
        return '';
487
      }
488
489
      return substr($text, $istart, max(0, $iend - $istart + 1));
490
    }
491
  }
492
493
  /**
494
   * Truncates a UTF-8-encoded string safely to a number of characters.
495
   *
496
   * @param string $string
497
   *   The string to truncate.
498
   * @param int $max_length
499
   *   An upper limit on the returned string length, including trailing ellipsis
500
   *   if $add_ellipsis is TRUE.
501
   * @param bool $wordsafe
502
   *   If TRUE, attempt to truncate on a word boundary. Word boundaries are
503
   *   spaces, punctuation, and Unicode characters used as word boundaries in
504
   *   non-Latin languages; see Unicode::PREG_CLASS_WORD_BOUNDARY for more
505
   *   information. If a word boundary cannot be found that would make the length
506
   *   of the returned string fall within length guidelines (see parameters
507
   *   $max_length and $min_wordsafe_length), word boundaries are ignored.
508
   * @param bool $add_ellipsis
509
   *   If TRUE, add '...' to the end of the truncated string (defaults to
510
   *   FALSE). The string length will still fall within $max_length.
511
   * @param int $min_wordsafe_length
512
   *   If $wordsafe is TRUE, the minimum acceptable length for truncation (before
513
   *   adding an ellipsis, if $add_ellipsis is TRUE). Has no effect if $wordsafe
514
   *   is FALSE. This can be used to prevent having a very short resulting string
515
   *   that will not be understandable. For instance, if you are truncating the
516
   *   string "See myverylongurlexample.com for more information" to a word-safe
517
   *   return length of 20, the only available word boundary within 20 characters
518
   *   is after the word "See", which wouldn't leave a very informative string. If
519
   *   you had set $min_wordsafe_length to 10, though, the function would realise
520
   *   that "See" alone is too short, and would then just truncate ignoring word
521
   *   boundaries, giving you "See myverylongurl..." (assuming you had set
522
   *   $add_ellipses to TRUE).
523
   *
524
   * @return string
525
   *   The truncated string.
526
   */
527
  public static function truncate($string, $max_length, $wordsafe = FALSE, $add_ellipsis = FALSE, $min_wordsafe_length = 1) {
528
    $ellipsis = '';
529
    $max_length = max($max_length, 0);
530
    $min_wordsafe_length = max($min_wordsafe_length, 0);
531
532
    if (static::strlen($string) <= $max_length) {
533
      // No truncation needed, so don't add ellipsis, just return.
534
      return $string;
535
    }
536
537
    if ($add_ellipsis) {
538
      // Truncate ellipsis in case $max_length is small.
539
      $ellipsis = static::substr('…', 0, $max_length);
540
      $max_length -= static::strlen($ellipsis);
541
      $max_length = max($max_length, 0);
542
    }
543
544
    if ($max_length <= $min_wordsafe_length) {
545
      // Do not attempt word-safe if lengths are bad.
546
      $wordsafe = FALSE;
547
    }
548
549
    if ($wordsafe) {
550
      $matches = array();
551
      // Find the last word boundary, if there is one within $min_wordsafe_length
552
      // to $max_length characters. preg_match() is always greedy, so it will
553
      // find the longest string possible.
554
      $found = preg_match('/^(.{' . $min_wordsafe_length . ',' . $max_length . '})[' . Unicode::PREG_CLASS_WORD_BOUNDARY . ']/u', $string, $matches);
555
      if ($found) {
556
        $string = $matches[1];
557
      }
558
      else {
559
        $string = static::substr($string, 0, $max_length);
560
      }
561
    }
562
    else {
563
      $string = static::substr($string, 0, $max_length);
564
    }
565
566
    if ($add_ellipsis) {
567
      // If we're adding an ellipsis, remove any trailing periods.
568
      $string = rtrim($string, '.');
569
570
      $string .= $ellipsis;
571
    }
572
573
    return $string;
574
  }
575
576
  /**
577
   * Compares UTF-8-encoded strings in a binary safe case-insensitive manner.
578
   *
579
   * @param string $str1
580
   *   The first string.
581
   * @param string $str2
582
   *   The second string.
583
   *
584
   * @return int
585
   *   Returns < 0 if $str1 is less than $str2; > 0 if $str1 is greater than
586
   *   $str2, and 0 if they are equal.
587
   */
588
  public static function strcasecmp($str1 , $str2) {
589
    return strcmp(static::strtoupper($str1), static::strtoupper($str2));
590
  }
591
592
  /**
593
   * Encodes MIME/HTTP headers that contain incorrectly encoded characters.
594
   *
595
   * For example, Unicode::mimeHeaderEncode('tést.txt') returns
596
   * "=?UTF-8?B?dMOpc3QudHh0?=".
597
   *
598
   * See http://www.rfc-editor.org/rfc/rfc2047.txt for more information.
599
   *
600
   * Notes:
601
   * - Only encode strings that contain non-ASCII characters.
602
   * - We progressively cut-off a chunk with self::truncateBytes(). This ensures
603
   *   each chunk starts and ends on a character boundary.
604
   * - Using \n as the chunk separator may cause problems on some systems and
605
   *   may have to be changed to \r\n or \r.
606
   *
607
   * @param string $string
608
   *   The header to encode.
609
   *
610
   * @return string
611
   *   The mime-encoded header.
612
   */
613
  public static function mimeHeaderEncode($string) {
614
    if (preg_match('/[^\x20-\x7E]/', $string)) {
615
      $chunk_size = 47; // floor((75 - strlen("=?UTF-8?B??=")) * 0.75);
616
      $len = strlen($string);
617
      $output = '';
618
      while ($len > 0) {
619
        $chunk = static::truncateBytes($string, $chunk_size);
620
        $output .= ' =?UTF-8?B?' . base64_encode($chunk) . "?=\n";
621
        $c = strlen($chunk);
622
        $string = substr($string, $c);
623
        $len -= $c;
624
      }
625
      return trim($output);
626
    }
627
    return $string;
628
  }
629
630
  /**
631
   * Decodes MIME/HTTP encoded header values.
632
   *
633
   * @param string $header
634
   *   The header to decode.
635
   *
636
   * @return string
637
   *   The mime-decoded header.
638
   */
639
  public static function mimeHeaderDecode($header) {
640
    $callback = function ($matches) {
641
      $data = ($matches[2] == 'B') ? base64_decode($matches[3]) : str_replace('_', ' ', quoted_printable_decode($matches[3]));
642
      if (strtolower($matches[1]) != 'utf-8') {
643
        $data = static::convertToUtf8($data, $matches[1]);
644
      }
645
      return $data;
646
    };
647
    // First step: encoded chunks followed by other encoded chunks (need to collapse whitespace)
648
    $header = preg_replace_callback('/=\?([^?]+)\?(Q|B)\?([^?]+|\?(?!=))\?=\s+(?==\?)/', $callback, $header);
649
    // Second step: remaining chunks (do not collapse whitespace)
650
    return preg_replace_callback('/=\?([^?]+)\?(Q|B)\?([^?]+|\?(?!=))\?=/', $callback, $header);
651
  }
652
653
  /**
654
   * Flip U+C0-U+DE to U+E0-U+FD and back. Can be used as preg_replace callback.
655
   *
656
   * @param array $matches
657
   *   An array of matches by preg_replace_callback().
658
   *
659
   * @return string
660
   *   The flipped text.
661
   */
662
  public static function caseFlip($matches) {
663
    return $matches[0][0] . chr(ord($matches[0][1]) ^ 32);
664
  }
665
666
  /**
667
   * Checks whether a string is valid UTF-8.
668
   *
669
   * All functions designed to filter input should use drupal_validate_utf8
670
   * to ensure they operate on valid UTF-8 strings to prevent bypass of the
671
   * filter.
672
   *
673
   * When text containing an invalid UTF-8 lead byte (0xC0 - 0xFF) is presented
674
   * as UTF-8 to Internet Explorer 6, the program may misinterpret subsequent
675
   * bytes. When these subsequent bytes are HTML control characters such as
676
   * quotes or angle brackets, parts of the text that were deemed safe by filters
677
   * end up in locations that are potentially unsafe; An onerror attribute that
678
   * is outside of a tag, and thus deemed safe by a filter, can be interpreted
679
   * by the browser as if it were inside the tag.
680
   *
681
   * The function does not return FALSE for strings containing character codes
682
   * above U+10FFFF, even though these are prohibited by RFC 3629.
683
   *
684
   * @param string $text
685
   *   The text to check.
686
   *
687
   * @return bool
688
   *   TRUE if the text is valid UTF-8, FALSE if not.
689
   */
690
  public static function validateUtf8($text) {
691
    if (strlen($text) == 0) {
692
      return TRUE;
693
    }
694
    // With the PCRE_UTF8 modifier 'u', preg_match() fails silently on strings
695
    // containing invalid UTF-8 byte sequences. It does not reject character
696
    // codes above U+10FFFF (represented by 4 or more octets), though.
697
    return (preg_match('/^./us', $text) == 1);
698
  }
699
700
  /**
701
   * Finds the position of the first occurrence of a string in another string.
702
   *
703
   * @param string $haystack
704
   *   The string to search in.
705
   * @param string $needle
706
   *   The string to find in $haystack.
707
   * @param int $offset
708
   *   If specified, start the search at this number of characters from the
709
   *   beginning (default 0).
710
   *
711
   * @return int|false
712
   *   The position where $needle occurs in $haystack, always relative to the
713
   *   beginning (independent of $offset), or FALSE if not found. Note that
714
   *   a return value of 0 is not the same as FALSE.
715
   */
716
  public static function strpos($haystack, $needle, $offset = 0) {
717
    if (static::getStatus() == static::STATUS_MULTIBYTE) {
718
      return mb_strpos($haystack, $needle, $offset);
719
    }
720
    else {
721
      // Remove Unicode continuation characters, to be compatible with
722
      // Unicode::strlen() and Unicode::substr().
723
      $haystack = preg_replace("/[\x80-\xBF]/", '', $haystack);
724
      $needle = preg_replace("/[\x80-\xBF]/", '', $needle);
725
      return strpos($haystack, $needle, $offset);
726
    }
727
  }
728
729
}
730