[ Index ]

PHP Cross Reference of Unnamed Project

title

Body

[close]

/lib/classes/ -> text.php (source)

   1  <?php
   2  // This file is part of Moodle - http://moodle.org/
   3  //
   4  // Moodle is free software: you can redistribute it and/or modify
   5  // it under the terms of the GNU General Public License as published by
   6  // the Free Software Foundation, either version 3 of the License, or
   7  // (at your option) any later version.
   8  //
   9  // Moodle is distributed in the hope that it will be useful,
  10  // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  12  // GNU General Public License for more details.
  13  //
  14  // You should have received a copy of the GNU General Public License
  15  // along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
  16  
  17  /**
  18   * Defines string apis
  19   *
  20   * @package    core
  21   * @copyright  (C) 2001-3001 Eloy Lafuente (stronk7) {@link http://contiento.com}
  22   * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  23   */
  24  
  25  defined('MOODLE_INTERNAL') || die();
  26  
  27  /**
  28   * defines string api's for manipulating strings
  29   *
  30   * This class is used to manipulate strings under Moodle 1.6 an later. As
  31   * utf-8 text become mandatory a pool of safe functions under this encoding
  32   * become necessary. The name of the methods is exactly the
  33   * same than their PHP originals.
  34   *
  35   * A big part of this class acts as a wrapper over the Typo3 charset library,
  36   * really a cool group of utilities to handle texts and encoding conversion.
  37   *
  38   * Take a look to its own copyright and license details.
  39   *
  40   * IMPORTANT Note: Typo3 libraries always expect lowercase charsets to use 100%
  41   * its capabilities so, don't forget to make the conversion
  42   * from every wrapper function!
  43   *
  44   * @package   core
  45   * @category  string
  46   * @copyright 1999 onwards Martin Dougiamas  {@link http://moodle.com}
  47   * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  48   */
  49  class core_text {
  50  
  51      /**
  52       * Return t3lib helper class, which is used for conversion between charsets
  53       *
  54       * @param bool $reset
  55       * @return t3lib_cs
  56       */
  57      protected static function typo3($reset = false) {
  58          static $typo3cs = null;
  59  
  60          if ($reset) {
  61              $typo3cs = null;
  62              return null;
  63          }
  64  
  65          if (isset($typo3cs)) {
  66              return $typo3cs;
  67          }
  68  
  69          global $CFG;
  70  
  71          // Required files
  72          require_once($CFG->libdir.'/typo3/class.t3lib_cs.php');
  73          require_once($CFG->libdir.'/typo3/class.t3lib_div.php');
  74          require_once($CFG->libdir.'/typo3/interface.t3lib_singleton.php');
  75          require_once($CFG->libdir.'/typo3/class.t3lib_l10n_locales.php');
  76  
  77          // do not use mbstring or recode because it may return invalid results in some corner cases
  78          $GLOBALS['TYPO3_CONF_VARS']['SYS']['t3lib_cs_convMethod'] = 'iconv';
  79          $GLOBALS['TYPO3_CONF_VARS']['SYS']['t3lib_cs_utils'] = 'iconv';
  80  
  81          // Tell Typo3 we are curl enabled always (mandatory since 2.0)
  82          $GLOBALS['TYPO3_CONF_VARS']['SYS']['curlUse'] = '1';
  83  
  84          // And this directory must exist to allow Typo to cache conversion
  85          // tables when using internal functions
  86          make_temp_directory('typo3temp/cs');
  87  
  88          // Make sure typo is using our dir permissions
  89          $GLOBALS['TYPO3_CONF_VARS']['BE']['folderCreateMask'] = decoct($CFG->directorypermissions);
  90  
  91          // Default mask for Typo
  92          $GLOBALS['TYPO3_CONF_VARS']['BE']['fileCreateMask'] = $CFG->directorypermissions;
  93  
  94          // This full path constants must be defined too, transforming backslashes
  95          // to forward slashed because Typo3 requires it.
  96          if (!defined('PATH_t3lib')) {
  97              define('PATH_t3lib', str_replace('\\','/',$CFG->libdir.'/typo3/'));
  98              define('PATH_typo3', str_replace('\\','/',$CFG->libdir.'/typo3/'));
  99              define('PATH_site', str_replace('\\','/',$CFG->tempdir.'/'));
 100              define('TYPO3_OS', stristr(PHP_OS,'win')&&!stristr(PHP_OS,'darwin')?'WIN':'');
 101          }
 102  
 103          $typo3cs = new t3lib_cs();
 104  
 105          return $typo3cs;
 106      }
 107  
 108      /**
 109       * Reset internal textlib caches.
 110       * @static
 111       */
 112      public static function reset_caches() {
 113          self::typo3(true);
 114      }
 115  
 116      /**
 117       * Standardise charset name
 118       *
 119       * Please note it does not mean the returned charset is actually supported.
 120       *
 121       * @static
 122       * @param string $charset raw charset name
 123       * @return string normalised lowercase charset name
 124       */
 125      public static function parse_charset($charset) {
 126          $charset = strtolower($charset);
 127  
 128          // shortcuts so that we do not have to load typo3 on every page
 129  
 130          if ($charset === 'utf8' or $charset === 'utf-8') {
 131              return 'utf-8';
 132          }
 133  
 134          if (preg_match('/^(cp|win|windows)-?(12[0-9]{2})$/', $charset, $matches)) {
 135              return 'windows-'.$matches[2];
 136          }
 137  
 138          if (preg_match('/^iso-8859-[0-9]+$/', $charset, $matches)) {
 139              return $charset;
 140          }
 141  
 142          if ($charset === 'euc-jp') {
 143              return 'euc-jp';
 144          }
 145          if ($charset === 'iso-2022-jp') {
 146              return 'iso-2022-jp';
 147          }
 148          if ($charset === 'shift-jis' or $charset === 'shift_jis') {
 149              return 'shift_jis';
 150          }
 151          if ($charset === 'gb2312') {
 152              return 'gb2312';
 153          }
 154          if ($charset === 'gb18030') {
 155              return 'gb18030';
 156          }
 157  
 158          // fallback to typo3
 159          return self::typo3()->parse_charset($charset);
 160      }
 161  
 162      /**
 163       * Converts the text between different encodings. It uses iconv extension with //TRANSLIT parameter,
 164       * falls back to typo3. If both source and target are utf-8 it tries to fix invalid characters only.
 165       *
 166       * @param string $text
 167       * @param string $fromCS source encoding
 168       * @param string $toCS result encoding
 169       * @return string|bool converted string or false on error
 170       */
 171      public static function convert($text, $fromCS, $toCS='utf-8') {
 172          $fromCS = self::parse_charset($fromCS);
 173          $toCS   = self::parse_charset($toCS);
 174  
 175          $text = (string)$text; // we can work only with strings
 176  
 177          if ($text === '') {
 178              return '';
 179          }
 180  
 181          if ($fromCS === 'utf-8') {
 182              $text = fix_utf8($text);
 183              if ($toCS === 'utf-8') {
 184                  return $text;
 185              }
 186          }
 187  
 188          if ($toCS === 'ascii') {
 189              // Try to normalize the conversion a bit.
 190              $text = self::specialtoascii($text, $fromCS);
 191          }
 192  
 193          // Prevent any error notices, do not use //IGNORE so that we get
 194          // consistent result from Typo3 if iconv fails.
 195          $result = @iconv($fromCS, $toCS.'//TRANSLIT', $text);
 196  
 197          if ($result === false or $result === '') {
 198              // note: iconv is prone to return empty string when invalid char encountered, or false if encoding unsupported
 199              $oldlevel = error_reporting(E_PARSE);
 200              $result = self::typo3()->conv((string)$text, $fromCS, $toCS);
 201              error_reporting($oldlevel);
 202          }
 203  
 204          return $result;
 205      }
 206  
 207      /**
 208       * Multibyte safe substr() function, uses mbstring or iconv for UTF-8, falls back to typo3.
 209       *
 210       * @param string $text string to truncate
 211       * @param int $start negative value means from end
 212       * @param int $len maximum length of characters beginning from start
 213       * @param string $charset encoding of the text
 214       * @return string portion of string specified by the $start and $len
 215       */
 216      public static function substr($text, $start, $len=null, $charset='utf-8') {
 217          $charset = self::parse_charset($charset);
 218  
 219          if ($charset === 'utf-8') {
 220              if (function_exists('mb_substr')) {
 221                  // this is much faster than iconv - see MDL-31142
 222                  if ($len === null) {
 223                      $oldcharset = mb_internal_encoding();
 224                      mb_internal_encoding('UTF-8');
 225                      $result = mb_substr($text, $start);
 226                      mb_internal_encoding($oldcharset);
 227                      return $result;
 228                  } else {
 229                      return mb_substr($text, $start, $len, 'UTF-8');
 230                  }
 231  
 232              } else {
 233                  if ($len === null) {
 234                      $len = iconv_strlen($text, 'UTF-8');
 235                  }
 236                  return iconv_substr($text, $start, $len, 'UTF-8');
 237              }
 238          }
 239  
 240          $oldlevel = error_reporting(E_PARSE);
 241          if ($len === null) {
 242              $result = self::typo3()->substr($charset, (string)$text, $start);
 243          } else {
 244              $result = self::typo3()->substr($charset, (string)$text, $start, $len);
 245          }
 246          error_reporting($oldlevel);
 247  
 248          return $result;
 249      }
 250  
 251      /**
 252       * Truncates a string to no more than a certain number of bytes in a multi-byte safe manner.
 253       * UTF-8 only!
 254       *
 255       * Many of the other charsets we test for (like ISO-2022-JP and EUC-JP) are not supported
 256       * by typo3, and will give invalid results, so we are supporting UTF-8 only.
 257       *
 258       * @param string $string String to truncate
 259       * @param int $bytes Maximum length of bytes in the result
 260       * @return string Portion of string specified by $bytes
 261       * @since Moodle 3.1
 262       */
 263      public static function str_max_bytes($string, $bytes) {
 264          if (function_exists('mb_strcut')) {
 265              return mb_strcut($string, 0, $bytes, 'UTF-8');
 266          }
 267  
 268          $oldlevel = error_reporting(E_PARSE);
 269          $result = self::typo3()->strtrunc('utf-8', $string, $bytes);
 270          error_reporting($oldlevel);
 271  
 272          return $result;
 273      }
 274  
 275      /**
 276       * Finds the last occurrence of a character in a string within another.
 277       * UTF-8 ONLY safe mb_strrchr().
 278       *
 279       * @param string $haystack The string from which to get the last occurrence of needle.
 280       * @param string $needle The string to find in haystack.
 281       * @param boolean $part If true, returns the portion before needle, else return the portion after (including needle).
 282       * @return string|false False when not found.
 283       * @since Moodle 2.4.6, 2.5.2, 2.6
 284       */
 285      public static function strrchr($haystack, $needle, $part = false) {
 286  
 287          if (function_exists('mb_strrchr')) {
 288              return mb_strrchr($haystack, $needle, $part, 'UTF-8');
 289          }
 290  
 291          $pos = self::strrpos($haystack, $needle);
 292          if ($pos === false) {
 293              return false;
 294          }
 295  
 296          $length = null;
 297          if ($part) {
 298              $length = $pos;
 299              $pos = 0;
 300          }
 301  
 302          return self::substr($haystack, $pos, $length, 'utf-8');
 303      }
 304  
 305      /**
 306       * Multibyte safe strlen() function, uses mbstring or iconv for UTF-8, falls back to typo3.
 307       *
 308       * @param string $text input string
 309       * @param string $charset encoding of the text
 310       * @return int number of characters
 311       */
 312      public static function strlen($text, $charset='utf-8') {
 313          $charset = self::parse_charset($charset);
 314  
 315          if ($charset === 'utf-8') {
 316              if (function_exists('mb_strlen')) {
 317                  return mb_strlen($text, 'UTF-8');
 318              } else {
 319                  return iconv_strlen($text, 'UTF-8');
 320              }
 321          }
 322  
 323          $oldlevel = error_reporting(E_PARSE);
 324          $result = self::typo3()->strlen($charset, (string)$text);
 325          error_reporting($oldlevel);
 326  
 327          return $result;
 328      }
 329  
 330      /**
 331       * Multibyte safe strtolower() function, uses mbstring, falls back to typo3.
 332       *
 333       * @param string $text input string
 334       * @param string $charset encoding of the text (may not work for all encodings)
 335       * @return string lower case text
 336       */
 337      public static function strtolower($text, $charset='utf-8') {
 338          $charset = self::parse_charset($charset);
 339  
 340          if ($charset === 'utf-8' and function_exists('mb_strtolower')) {
 341              return mb_strtolower($text, 'UTF-8');
 342          }
 343  
 344          $oldlevel = error_reporting(E_PARSE);
 345          $result = self::typo3()->conv_case($charset, (string)$text, 'toLower');
 346          error_reporting($oldlevel);
 347  
 348          return $result;
 349      }
 350  
 351      /**
 352       * Multibyte safe strtoupper() function, uses mbstring, falls back to typo3.
 353       *
 354       * @param string $text input string
 355       * @param string $charset encoding of the text (may not work for all encodings)
 356       * @return string upper case text
 357       */
 358      public static function strtoupper($text, $charset='utf-8') {
 359          $charset = self::parse_charset($charset);
 360  
 361          if ($charset === 'utf-8' and function_exists('mb_strtoupper')) {
 362              return mb_strtoupper($text, 'UTF-8');
 363          }
 364  
 365          $oldlevel = error_reporting(E_PARSE);
 366          $result = self::typo3()->conv_case($charset, (string)$text, 'toUpper');
 367          error_reporting($oldlevel);
 368  
 369          return $result;
 370      }
 371  
 372      /**
 373       * Find the position of the first occurrence of a substring in a string.
 374       * UTF-8 ONLY safe strpos(), uses mbstring, falls back to iconv.
 375       *
 376       * @param string $haystack the string to search in
 377       * @param string $needle one or more charachters to search for
 378       * @param int $offset offset from begining of string
 379       * @return int the numeric position of the first occurrence of needle in haystack.
 380       */
 381      public static function strpos($haystack, $needle, $offset=0) {
 382          if (function_exists('mb_strpos')) {
 383              return mb_strpos($haystack, $needle, $offset, 'UTF-8');
 384          } else {
 385              return iconv_strpos($haystack, $needle, $offset, 'UTF-8');
 386          }
 387      }
 388  
 389      /**
 390       * Find the position of the last occurrence of a substring in a string
 391       * UTF-8 ONLY safe strrpos(), uses mbstring, falls back to iconv.
 392       *
 393       * @param string $haystack the string to search in
 394       * @param string $needle one or more charachters to search for
 395       * @return int the numeric position of the last occurrence of needle in haystack
 396       */
 397      public static function strrpos($haystack, $needle) {
 398          if (function_exists('mb_strrpos')) {
 399              return mb_strrpos($haystack, $needle, null, 'UTF-8');
 400          } else {
 401              return iconv_strrpos($haystack, $needle, 'UTF-8');
 402          }
 403      }
 404  
 405      /**
 406       * Reverse UTF-8 multibytes character sets (used for RTL languages)
 407       * (We only do this because there is no mb_strrev or iconv_strrev)
 408       *
 409       * @param string $str the multibyte string to reverse
 410       * @return string the reversed multi byte string
 411       */
 412      public static function strrev($str) {
 413          preg_match_all('/./us', $str, $ar);
 414          return join('', array_reverse($ar[0]));
 415      }
 416  
 417      /**
 418       * Try to convert upper unicode characters to plain ascii,
 419       * the returned string may contain unconverted unicode characters.
 420       *
 421       * @param string $text input string
 422       * @param string $charset encoding of the text
 423       * @return string converted ascii string
 424       */
 425      public static function specialtoascii($text, $charset='utf-8') {
 426          $charset = self::parse_charset($charset);
 427          $oldlevel = error_reporting(E_PARSE);
 428          $result = self::typo3()->specCharsToASCII($charset, (string)$text);
 429          error_reporting($oldlevel);
 430          return $result;
 431      }
 432  
 433      /**
 434       * Generate a correct base64 encoded header to be used in MIME mail messages.
 435       * This function seems to be 100% compliant with RFC1342. Credits go to:
 436       * paravoid (http://www.php.net/manual/en/function.mb-encode-mimeheader.php#60283).
 437       *
 438       * @param string $text input string
 439       * @param string $charset encoding of the text
 440       * @return string base64 encoded header
 441       */
 442      public static function encode_mimeheader($text, $charset='utf-8') {
 443          if (empty($text)) {
 444              return (string)$text;
 445          }
 446          // Normalize charset
 447          $charset = self::parse_charset($charset);
 448          // If the text is pure ASCII, we don't need to encode it
 449          if (self::convert($text, $charset, 'ascii') == $text) {
 450              return $text;
 451          }
 452          // Although RFC says that line feed should be \r\n, it seems that
 453          // some mailers double convert \r, so we are going to use \n alone
 454          $linefeed="\n";
 455          // Define start and end of every chunk
 456          $start = "=?$charset?B?";
 457          $end = "?=";
 458          // Accumulate results
 459          $encoded = '';
 460          // Max line length is 75 (including start and end)
 461          $length = 75 - strlen($start) - strlen($end);
 462          // Multi-byte ratio
 463          $multilength = self::strlen($text, $charset);
 464          // Detect if strlen and friends supported
 465          if ($multilength === false) {
 466              if ($charset == 'GB18030' or $charset == 'gb18030') {
 467                  while (strlen($text)) {
 468                      // try to encode first 22 chars - we expect most chars are two bytes long
 469                      if (preg_match('/^(([\x00-\x7f])|([\x81-\xfe][\x40-\x7e])|([\x81-\xfe][\x80-\xfe])|([\x81-\xfe][\x30-\x39]..)){1,22}/m', $text, $matches)) {
 470                          $chunk = $matches[0];
 471                          $encchunk = base64_encode($chunk);
 472                          if (strlen($encchunk) > $length) {
 473                              // find first 11 chars - each char in 4 bytes - worst case scenario
 474                              preg_match('/^(([\x00-\x7f])|([\x81-\xfe][\x40-\x7e])|([\x81-\xfe][\x80-\xfe])|([\x81-\xfe][\x30-\x39]..)){1,11}/m', $text, $matches);
 475                              $chunk = $matches[0];
 476                              $encchunk = base64_encode($chunk);
 477                          }
 478                          $text = substr($text, strlen($chunk));
 479                          $encoded .= ' '.$start.$encchunk.$end.$linefeed;
 480                      } else {
 481                          break;
 482                      }
 483                  }
 484                  $encoded = trim($encoded);
 485                  return $encoded;
 486              } else {
 487                  return false;
 488              }
 489          }
 490          $ratio = $multilength / strlen($text);
 491          // Base64 ratio
 492          $magic = $avglength = floor(3 * $length * $ratio / 4);
 493          // basic infinite loop protection
 494          $maxiterations = strlen($text)*2;
 495          $iteration = 0;
 496          // Iterate over the string in magic chunks
 497          for ($i=0; $i <= $multilength; $i+=$magic) {
 498              if ($iteration++ > $maxiterations) {
 499                  return false; // probably infinite loop
 500              }
 501              $magic = $avglength;
 502              $offset = 0;
 503              // Ensure the chunk fits in length, reducing magic if necessary
 504              do {
 505                  $magic -= $offset;
 506                  $chunk = self::substr($text, $i, $magic, $charset);
 507                  $chunk = base64_encode($chunk);
 508                  $offset++;
 509              } while (strlen($chunk) > $length);
 510              // This chunk doesn't break any multi-byte char. Use it.
 511              if ($chunk)
 512                  $encoded .= ' '.$start.$chunk.$end.$linefeed;
 513          }
 514          // Strip the first space and the last linefeed
 515          $encoded = substr($encoded, 1, -strlen($linefeed));
 516  
 517          return $encoded;
 518      }
 519  
 520      /**
 521       * Returns HTML entity transliteration table.
 522       * @return array with (html entity => utf-8) elements
 523       */
 524      protected static function get_entities_table() {
 525          static $trans_tbl = null;
 526  
 527          // Generate/create $trans_tbl
 528          if (!isset($trans_tbl)) {
 529              if (version_compare(phpversion(), '5.3.4') < 0) {
 530                  $trans_tbl = array();
 531                  foreach (get_html_translation_table(HTML_ENTITIES) as $val=>$key) {
 532                      $trans_tbl[$key] = self::convert($val, 'ISO-8859-1', 'utf-8');
 533                  }
 534  
 535              } else if (version_compare(phpversion(), '5.4.0') < 0) {
 536                  $trans_tbl = get_html_translation_table(HTML_ENTITIES, ENT_COMPAT, 'UTF-8');
 537                  $trans_tbl = array_flip($trans_tbl);
 538  
 539              } else {
 540                  $trans_tbl = get_html_translation_table(HTML_ENTITIES, ENT_COMPAT | ENT_HTML401, 'UTF-8');
 541                  $trans_tbl = array_flip($trans_tbl);
 542              }
 543          }
 544  
 545          return $trans_tbl;
 546      }
 547  
 548      /**
 549       * Converts all the numeric entities &#nnnn; or &#xnnn; to UTF-8
 550       * Original from laurynas dot butkus at gmail at:
 551       * http://php.net/manual/en/function.html-entity-decode.php#75153
 552       * with some custom mods to provide more functionality
 553       *
 554       * @param string $str input string
 555       * @param boolean $htmlent convert also html entities (defaults to true)
 556       * @return string encoded UTF-8 string
 557       */
 558      public static function entities_to_utf8($str, $htmlent=true) {
 559          static $callback1 = null ;
 560          static $callback2 = null ;
 561  
 562          if (!$callback1 or !$callback2) {
 563              $callback1 = create_function('$matches', 'return core_text::code2utf8(hexdec($matches[1]));');
 564              $callback2 = create_function('$matches', 'return core_text::code2utf8($matches[1]);');
 565          }
 566  
 567          $result = (string)$str;
 568          $result = preg_replace_callback('/&#x([0-9a-f]+);/i', $callback1, $result);
 569          $result = preg_replace_callback('/&#([0-9]+);/', $callback2, $result);
 570  
 571          // Replace literal entities (if desired)
 572          if ($htmlent) {
 573              $trans_tbl = self::get_entities_table();
 574              // It should be safe to search for ascii strings and replace them with utf-8 here.
 575              $result = strtr($result, $trans_tbl);
 576          }
 577          // Return utf8-ised string
 578          return $result;
 579      }
 580  
 581      /**
 582       * Converts all Unicode chars > 127 to numeric entities &#nnnn; or &#xnnn;.
 583       *
 584       * @param string $str input string
 585       * @param boolean $dec output decadic only number entities
 586       * @param boolean $nonnum remove all non-numeric entities
 587       * @return string converted string
 588       */
 589      public static function utf8_to_entities($str, $dec=false, $nonnum=false) {
 590          static $callback = null ;
 591  
 592          if ($nonnum) {
 593              $str = self::entities_to_utf8($str, true);
 594          }
 595  
 596          // Avoid some notices from Typo3 code
 597          $oldlevel = error_reporting(E_PARSE);
 598          $result = self::typo3()->utf8_to_entities((string)$str);
 599          error_reporting($oldlevel);
 600  
 601          if ($dec) {
 602              if (!$callback) {
 603                  $callback = create_function('$matches', 'return \'&#\'.(hexdec($matches[1])).\';\';');
 604              }
 605              $result = preg_replace_callback('/&#x([0-9a-f]+);/i', $callback, $result);
 606          }
 607  
 608          return $result;
 609      }
 610  
 611      /**
 612       * Removes the BOM from unicode string {@link http://unicode.org/faq/utf_bom.html}
 613       *
 614       * @param string $str input string
 615       * @return string
 616       */
 617      public static function trim_utf8_bom($str) {
 618          $bom = "\xef\xbb\xbf";
 619          if (strpos($str, $bom) === 0) {
 620              return substr($str, strlen($bom));
 621          }
 622          return $str;
 623      }
 624  
 625      /**
 626       * Returns encoding options for select boxes, utf-8 and platform encoding first
 627       *
 628       * @return array encodings
 629       */
 630      public static function get_encodings() {
 631          $encodings = array();
 632          $encodings['UTF-8'] = 'UTF-8';
 633          $winenc = strtoupper(get_string('localewincharset', 'langconfig'));
 634          if ($winenc != '') {
 635              $encodings[$winenc] = $winenc;
 636          }
 637          $nixenc = strtoupper(get_string('oldcharset', 'langconfig'));
 638          $encodings[$nixenc] = $nixenc;
 639  
 640          foreach (self::typo3()->synonyms as $enc) {
 641              $enc = strtoupper($enc);
 642              $encodings[$enc] = $enc;
 643          }
 644          return $encodings;
 645      }
 646  
 647      /**
 648       * Returns the utf8 string corresponding to the unicode value
 649       * (from php.net, courtesy - romans@void.lv)
 650       *
 651       * @param  int    $num one unicode value
 652       * @return string the UTF-8 char corresponding to the unicode value
 653       */
 654      public static function code2utf8($num) {
 655          if ($num < 128) {
 656              return chr($num);
 657          }
 658          if ($num < 2048) {
 659              return chr(($num >> 6) + 192) . chr(($num & 63) + 128);
 660          }
 661          if ($num < 65536) {
 662              return chr(($num >> 12) + 224) . chr((($num >> 6) & 63) + 128) . chr(($num & 63) + 128);
 663          }
 664          if ($num < 2097152) {
 665              return chr(($num >> 18) + 240) . chr((($num >> 12) & 63) + 128) . chr((($num >> 6) & 63) + 128) . chr(($num & 63) + 128);
 666          }
 667          return '';
 668      }
 669  
 670      /**
 671       * Returns the code of the given UTF-8 character
 672       *
 673       * @param  string $utf8char one UTF-8 character
 674       * @return int    the code of the given character
 675       */
 676      public static function utf8ord($utf8char) {
 677          if ($utf8char == '') {
 678              return 0;
 679          }
 680          $ord0 = ord($utf8char{0});
 681          if ($ord0 >= 0 && $ord0 <= 127) {
 682              return $ord0;
 683          }
 684          $ord1 = ord($utf8char{1});
 685          if ($ord0 >= 192 && $ord0 <= 223) {
 686              return ($ord0 - 192) * 64 + ($ord1 - 128);
 687          }
 688          $ord2 = ord($utf8char{2});
 689          if ($ord0 >= 224 && $ord0 <= 239) {
 690              return ($ord0 - 224) * 4096 + ($ord1 - 128) * 64 + ($ord2 - 128);
 691          }
 692          $ord3 = ord($utf8char{3});
 693          if ($ord0 >= 240 && $ord0 <= 247) {
 694              return ($ord0 - 240) * 262144 + ($ord1 - 128 )* 4096 + ($ord2 - 128) * 64 + ($ord3 - 128);
 695          }
 696          return false;
 697      }
 698  
 699      /**
 700       * Makes first letter of each word capital - words must be separated by spaces.
 701       * Use with care, this function does not work properly in many locales!!!
 702       *
 703       * @param string $text input string
 704       * @return string
 705       */
 706      public static function strtotitle($text) {
 707          if (empty($text)) {
 708              return $text;
 709          }
 710  
 711          if (function_exists('mb_convert_case')) {
 712              return mb_convert_case($text, MB_CASE_TITLE, 'UTF-8');
 713          }
 714  
 715          $text = self::strtolower($text);
 716          $words = explode(' ', $text);
 717          foreach ($words as $i=>$word) {
 718              $length = self::strlen($word);
 719              if (!$length) {
 720                  continue;
 721  
 722              } else if ($length == 1) {
 723                  $words[$i] = self::strtoupper($word);
 724  
 725              } else {
 726                  $letter = self::substr($word, 0, 1);
 727                  $letter = self::strtoupper($letter);
 728                  $rest   = self::substr($word, 1);
 729                  $words[$i] = $letter.$rest;
 730              }
 731          }
 732          return implode(' ', $words);
 733      }
 734  }


Generated: Thu Aug 11 10:00:09 2016 Cross-referenced by PHPXref 0.7.1