[ Index ]

PHP Cross Reference of moodle-2.8

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       * Finds the last occurrence of a character in a string within another.
 253       * UTF-8 ONLY safe mb_strrchr().
 254       *
 255       * @param string $haystack The string from which to get the last occurrence of needle.
 256       * @param string $needle The string to find in haystack.
 257       * @param boolean $part If true, returns the portion before needle, else return the portion after (including needle).
 258       * @return string|false False when not found.
 259       * @since Moodle 2.4.6, 2.5.2, 2.6
 260       */
 261      public static function strrchr($haystack, $needle, $part = false) {
 262  
 263          if (function_exists('mb_strrchr')) {
 264              return mb_strrchr($haystack, $needle, $part, 'UTF-8');
 265          }
 266  
 267          $pos = self::strrpos($haystack, $needle);
 268          if ($pos === false) {
 269              return false;
 270          }
 271  
 272          $length = null;
 273          if ($part) {
 274              $length = $pos;
 275              $pos = 0;
 276          }
 277  
 278          return self::substr($haystack, $pos, $length, 'utf-8');
 279      }
 280  
 281      /**
 282       * Multibyte safe strlen() function, uses mbstring or iconv for UTF-8, falls back to typo3.
 283       *
 284       * @param string $text input string
 285       * @param string $charset encoding of the text
 286       * @return int number of characters
 287       */
 288      public static function strlen($text, $charset='utf-8') {
 289          $charset = self::parse_charset($charset);
 290  
 291          if ($charset === 'utf-8') {
 292              if (function_exists('mb_strlen')) {
 293                  return mb_strlen($text, 'UTF-8');
 294              } else {
 295                  return iconv_strlen($text, 'UTF-8');
 296              }
 297          }
 298  
 299          $oldlevel = error_reporting(E_PARSE);
 300          $result = self::typo3()->strlen($charset, (string)$text);
 301          error_reporting($oldlevel);
 302  
 303          return $result;
 304      }
 305  
 306      /**
 307       * Multibyte safe strtolower() function, uses mbstring, falls back to typo3.
 308       *
 309       * @param string $text input string
 310       * @param string $charset encoding of the text (may not work for all encodings)
 311       * @return string lower case text
 312       */
 313      public static function strtolower($text, $charset='utf-8') {
 314          $charset = self::parse_charset($charset);
 315  
 316          if ($charset === 'utf-8' and function_exists('mb_strtolower')) {
 317              return mb_strtolower($text, 'UTF-8');
 318          }
 319  
 320          $oldlevel = error_reporting(E_PARSE);
 321          $result = self::typo3()->conv_case($charset, (string)$text, 'toLower');
 322          error_reporting($oldlevel);
 323  
 324          return $result;
 325      }
 326  
 327      /**
 328       * Multibyte safe strtoupper() function, uses mbstring, falls back to typo3.
 329       *
 330       * @param string $text input string
 331       * @param string $charset encoding of the text (may not work for all encodings)
 332       * @return string upper case text
 333       */
 334      public static function strtoupper($text, $charset='utf-8') {
 335          $charset = self::parse_charset($charset);
 336  
 337          if ($charset === 'utf-8' and function_exists('mb_strtoupper')) {
 338              return mb_strtoupper($text, 'UTF-8');
 339          }
 340  
 341          $oldlevel = error_reporting(E_PARSE);
 342          $result = self::typo3()->conv_case($charset, (string)$text, 'toUpper');
 343          error_reporting($oldlevel);
 344  
 345          return $result;
 346      }
 347  
 348      /**
 349       * Find the position of the first occurrence of a substring in a string.
 350       * UTF-8 ONLY safe strpos(), uses mbstring, falls back to iconv.
 351       *
 352       * @param string $haystack the string to search in
 353       * @param string $needle one or more charachters to search for
 354       * @param int $offset offset from begining of string
 355       * @return int the numeric position of the first occurrence of needle in haystack.
 356       */
 357      public static function strpos($haystack, $needle, $offset=0) {
 358          if (function_exists('mb_strpos')) {
 359              return mb_strpos($haystack, $needle, $offset, 'UTF-8');
 360          } else {
 361              return iconv_strpos($haystack, $needle, $offset, 'UTF-8');
 362          }
 363      }
 364  
 365      /**
 366       * Find the position of the last occurrence of a substring in a string
 367       * UTF-8 ONLY safe strrpos(), uses mbstring, falls back to iconv.
 368       *
 369       * @param string $haystack the string to search in
 370       * @param string $needle one or more charachters to search for
 371       * @return int the numeric position of the last occurrence of needle in haystack
 372       */
 373      public static function strrpos($haystack, $needle) {
 374          if (function_exists('mb_strrpos')) {
 375              return mb_strrpos($haystack, $needle, null, 'UTF-8');
 376          } else {
 377              return iconv_strrpos($haystack, $needle, 'UTF-8');
 378          }
 379      }
 380  
 381      /**
 382       * Reverse UTF-8 multibytes character sets (used for RTL languages)
 383       * (We only do this because there is no mb_strrev or iconv_strrev)
 384       *
 385       * @param string $str the multibyte string to reverse
 386       * @return string the reversed multi byte string
 387       */
 388      public static function strrev($str) {
 389          preg_match_all('/./us', $str, $ar);
 390          return join('', array_reverse($ar[0]));
 391      }
 392  
 393      /**
 394       * Try to convert upper unicode characters to plain ascii,
 395       * the returned string may contain unconverted unicode characters.
 396       *
 397       * @param string $text input string
 398       * @param string $charset encoding of the text
 399       * @return string converted ascii string
 400       */
 401      public static function specialtoascii($text, $charset='utf-8') {
 402          $charset = self::parse_charset($charset);
 403          $oldlevel = error_reporting(E_PARSE);
 404          $result = self::typo3()->specCharsToASCII($charset, (string)$text);
 405          error_reporting($oldlevel);
 406          return $result;
 407      }
 408  
 409      /**
 410       * Generate a correct base64 encoded header to be used in MIME mail messages.
 411       * This function seems to be 100% compliant with RFC1342. Credits go to:
 412       * paravoid (http://www.php.net/manual/en/function.mb-encode-mimeheader.php#60283).
 413       *
 414       * @param string $text input string
 415       * @param string $charset encoding of the text
 416       * @return string base64 encoded header
 417       */
 418      public static function encode_mimeheader($text, $charset='utf-8') {
 419          if (empty($text)) {
 420              return (string)$text;
 421          }
 422          // Normalize charset
 423          $charset = self::parse_charset($charset);
 424          // If the text is pure ASCII, we don't need to encode it
 425          if (self::convert($text, $charset, 'ascii') == $text) {
 426              return $text;
 427          }
 428          // Although RFC says that line feed should be \r\n, it seems that
 429          // some mailers double convert \r, so we are going to use \n alone
 430          $linefeed="\n";
 431          // Define start and end of every chunk
 432          $start = "=?$charset?B?";
 433          $end = "?=";
 434          // Accumulate results
 435          $encoded = '';
 436          // Max line length is 75 (including start and end)
 437          $length = 75 - strlen($start) - strlen($end);
 438          // Multi-byte ratio
 439          $multilength = self::strlen($text, $charset);
 440          // Detect if strlen and friends supported
 441          if ($multilength === false) {
 442              if ($charset == 'GB18030' or $charset == 'gb18030') {
 443                  while (strlen($text)) {
 444                      // try to encode first 22 chars - we expect most chars are two bytes long
 445                      if (preg_match('/^(([\x00-\x7f])|([\x81-\xfe][\x40-\x7e])|([\x81-\xfe][\x80-\xfe])|([\x81-\xfe][\x30-\x39]..)){1,22}/m', $text, $matches)) {
 446                          $chunk = $matches[0];
 447                          $encchunk = base64_encode($chunk);
 448                          if (strlen($encchunk) > $length) {
 449                              // find first 11 chars - each char in 4 bytes - worst case scenario
 450                              preg_match('/^(([\x00-\x7f])|([\x81-\xfe][\x40-\x7e])|([\x81-\xfe][\x80-\xfe])|([\x81-\xfe][\x30-\x39]..)){1,11}/m', $text, $matches);
 451                              $chunk = $matches[0];
 452                              $encchunk = base64_encode($chunk);
 453                          }
 454                          $text = substr($text, strlen($chunk));
 455                          $encoded .= ' '.$start.$encchunk.$end.$linefeed;
 456                      } else {
 457                          break;
 458                      }
 459                  }
 460                  $encoded = trim($encoded);
 461                  return $encoded;
 462              } else {
 463                  return false;
 464              }
 465          }
 466          $ratio = $multilength / strlen($text);
 467          // Base64 ratio
 468          $magic = $avglength = floor(3 * $length * $ratio / 4);
 469          // basic infinite loop protection
 470          $maxiterations = strlen($text)*2;
 471          $iteration = 0;
 472          // Iterate over the string in magic chunks
 473          for ($i=0; $i <= $multilength; $i+=$magic) {
 474              if ($iteration++ > $maxiterations) {
 475                  return false; // probably infinite loop
 476              }
 477              $magic = $avglength;
 478              $offset = 0;
 479              // Ensure the chunk fits in length, reducing magic if necessary
 480              do {
 481                  $magic -= $offset;
 482                  $chunk = self::substr($text, $i, $magic, $charset);
 483                  $chunk = base64_encode($chunk);
 484                  $offset++;
 485              } while (strlen($chunk) > $length);
 486              // This chunk doesn't break any multi-byte char. Use it.
 487              if ($chunk)
 488                  $encoded .= ' '.$start.$chunk.$end.$linefeed;
 489          }
 490          // Strip the first space and the last linefeed
 491          $encoded = substr($encoded, 1, -strlen($linefeed));
 492  
 493          return $encoded;
 494      }
 495  
 496      /**
 497       * Returns HTML entity transliteration table.
 498       * @return array with (html entity => utf-8) elements
 499       */
 500      protected static function get_entities_table() {
 501          static $trans_tbl = null;
 502  
 503          // Generate/create $trans_tbl
 504          if (!isset($trans_tbl)) {
 505              if (version_compare(phpversion(), '5.3.4') < 0) {
 506                  $trans_tbl = array();
 507                  foreach (get_html_translation_table(HTML_ENTITIES) as $val=>$key) {
 508                      $trans_tbl[$key] = self::convert($val, 'ISO-8859-1', 'utf-8');
 509                  }
 510  
 511              } else if (version_compare(phpversion(), '5.4.0') < 0) {
 512                  $trans_tbl = get_html_translation_table(HTML_ENTITIES, ENT_COMPAT, 'UTF-8');
 513                  $trans_tbl = array_flip($trans_tbl);
 514  
 515              } else {
 516                  $trans_tbl = get_html_translation_table(HTML_ENTITIES, ENT_COMPAT | ENT_HTML401, 'UTF-8');
 517                  $trans_tbl = array_flip($trans_tbl);
 518              }
 519          }
 520  
 521          return $trans_tbl;
 522      }
 523  
 524      /**
 525       * Converts all the numeric entities &#nnnn; or &#xnnn; to UTF-8
 526       * Original from laurynas dot butkus at gmail at:
 527       * http://php.net/manual/en/function.html-entity-decode.php#75153
 528       * with some custom mods to provide more functionality
 529       *
 530       * @param string $str input string
 531       * @param boolean $htmlent convert also html entities (defaults to true)
 532       * @return string encoded UTF-8 string
 533       */
 534      public static function entities_to_utf8($str, $htmlent=true) {
 535          static $callback1 = null ;
 536          static $callback2 = null ;
 537  
 538          if (!$callback1 or !$callback2) {
 539              $callback1 = create_function('$matches', 'return core_text::code2utf8(hexdec($matches[1]));');
 540              $callback2 = create_function('$matches', 'return core_text::code2utf8($matches[1]);');
 541          }
 542  
 543          $result = (string)$str;
 544          $result = preg_replace_callback('/&#x([0-9a-f]+);/i', $callback1, $result);
 545          $result = preg_replace_callback('/&#([0-9]+);/', $callback2, $result);
 546  
 547          // Replace literal entities (if desired)
 548          if ($htmlent) {
 549              $trans_tbl = self::get_entities_table();
 550              // It should be safe to search for ascii strings and replace them with utf-8 here.
 551              $result = strtr($result, $trans_tbl);
 552          }
 553          // Return utf8-ised string
 554          return $result;
 555      }
 556  
 557      /**
 558       * Converts all Unicode chars > 127 to numeric entities &#nnnn; or &#xnnn;.
 559       *
 560       * @param string $str input string
 561       * @param boolean $dec output decadic only number entities
 562       * @param boolean $nonnum remove all non-numeric entities
 563       * @return string converted string
 564       */
 565      public static function utf8_to_entities($str, $dec=false, $nonnum=false) {
 566          static $callback = null ;
 567  
 568          if ($nonnum) {
 569              $str = self::entities_to_utf8($str, true);
 570          }
 571  
 572          // Avoid some notices from Typo3 code
 573          $oldlevel = error_reporting(E_PARSE);
 574          $result = self::typo3()->utf8_to_entities((string)$str);
 575          error_reporting($oldlevel);
 576  
 577          if ($dec) {
 578              if (!$callback) {
 579                  $callback = create_function('$matches', 'return \'&#\'.(hexdec($matches[1])).\';\';');
 580              }
 581              $result = preg_replace_callback('/&#x([0-9a-f]+);/i', $callback, $result);
 582          }
 583  
 584          return $result;
 585      }
 586  
 587      /**
 588       * Removes the BOM from unicode string {@link http://unicode.org/faq/utf_bom.html}
 589       *
 590       * @param string $str input string
 591       * @return string
 592       */
 593      public static function trim_utf8_bom($str) {
 594          $bom = "\xef\xbb\xbf";
 595          if (strpos($str, $bom) === 0) {
 596              return substr($str, strlen($bom));
 597          }
 598          return $str;
 599      }
 600  
 601      /**
 602       * Returns encoding options for select boxes, utf-8 and platform encoding first
 603       *
 604       * @return array encodings
 605       */
 606      public static function get_encodings() {
 607          $encodings = array();
 608          $encodings['UTF-8'] = 'UTF-8';
 609          $winenc = strtoupper(get_string('localewincharset', 'langconfig'));
 610          if ($winenc != '') {
 611              $encodings[$winenc] = $winenc;
 612          }
 613          $nixenc = strtoupper(get_string('oldcharset', 'langconfig'));
 614          $encodings[$nixenc] = $nixenc;
 615  
 616          foreach (self::typo3()->synonyms as $enc) {
 617              $enc = strtoupper($enc);
 618              $encodings[$enc] = $enc;
 619          }
 620          return $encodings;
 621      }
 622  
 623      /**
 624       * Returns the utf8 string corresponding to the unicode value
 625       * (from php.net, courtesy - [email protected])
 626       *
 627       * @param  int    $num one unicode value
 628       * @return string the UTF-8 char corresponding to the unicode value
 629       */
 630      public static function code2utf8($num) {
 631          if ($num < 128) {
 632              return chr($num);
 633          }
 634          if ($num < 2048) {
 635              return chr(($num >> 6) + 192) . chr(($num & 63) + 128);
 636          }
 637          if ($num < 65536) {
 638              return chr(($num >> 12) + 224) . chr((($num >> 6) & 63) + 128) . chr(($num & 63) + 128);
 639          }
 640          if ($num < 2097152) {
 641              return chr(($num >> 18) + 240) . chr((($num >> 12) & 63) + 128) . chr((($num >> 6) & 63) + 128) . chr(($num & 63) + 128);
 642          }
 643          return '';
 644      }
 645  
 646      /**
 647       * Returns the code of the given UTF-8 character
 648       *
 649       * @param  string $utf8char one UTF-8 character
 650       * @return int    the code of the given character
 651       */
 652      public static function utf8ord($utf8char) {
 653          if ($utf8char == '') {
 654              return 0;
 655          }
 656          $ord0 = ord($utf8char{0});
 657          if ($ord0 >= 0 && $ord0 <= 127) {
 658              return $ord0;
 659          }
 660          $ord1 = ord($utf8char{1});
 661          if ($ord0 >= 192 && $ord0 <= 223) {
 662              return ($ord0 - 192) * 64 + ($ord1 - 128);
 663          }
 664          $ord2 = ord($utf8char{2});
 665          if ($ord0 >= 224 && $ord0 <= 239) {
 666              return ($ord0 - 224) * 4096 + ($ord1 - 128) * 64 + ($ord2 - 128);
 667          }
 668          $ord3 = ord($utf8char{3});
 669          if ($ord0 >= 240 && $ord0 <= 247) {
 670              return ($ord0 - 240) * 262144 + ($ord1 - 128 )* 4096 + ($ord2 - 128) * 64 + ($ord3 - 128);
 671          }
 672          return false;
 673      }
 674  
 675      /**
 676       * Makes first letter of each word capital - words must be separated by spaces.
 677       * Use with care, this function does not work properly in many locales!!!
 678       *
 679       * @param string $text input string
 680       * @return string
 681       */
 682      public static function strtotitle($text) {
 683          if (empty($text)) {
 684              return $text;
 685          }
 686  
 687          if (function_exists('mb_convert_case')) {
 688              return mb_convert_case($text, MB_CASE_TITLE, 'UTF-8');
 689          }
 690  
 691          $text = self::strtolower($text);
 692          $words = explode(' ', $text);
 693          foreach ($words as $i=>$word) {
 694              $length = self::strlen($word);
 695              if (!$length) {
 696                  continue;
 697  
 698              } else if ($length == 1) {
 699                  $words[$i] = self::strtoupper($word);
 700  
 701              } else {
 702                  $letter = self::substr($word, 0, 1);
 703                  $letter = self::strtoupper($letter);
 704                  $rest   = self::substr($word, 1);
 705                  $words[$i] = $letter.$rest;
 706              }
 707          }
 708          return implode(' ', $words);
 709      }
 710  }


Generated: Fri Nov 28 20:29:05 2014 Cross-referenced by PHPXref 0.7.1