[ Index ]

PHP Cross Reference of YOURLS

title

Body

[close]

/includes/ -> functions-formatting.php (source)

   1  <?php
   2  /*
   3   * YOURLS
   4   * Function library for anything related to formatting / validating / sanitizing
   5   */
   6  
   7  /**
   8   * Convert an integer (1337) to a string (3jk).
   9   *
  10   * @param int $num       Number to convert
  11   * @param string $chars  Characters to use for conversion
  12   * @return string        Converted number
  13   */
  14  function yourls_int2string($num, $chars = null) {
  15      if( $chars == null )
  16          $chars = yourls_get_shorturl_charset();
  17      $string = '';
  18      $len = strlen( $chars );
  19      while( $num >= $len ) {
  20          $mod = bcmod( (string)$num, (string)$len );
  21          $num = bcdiv( (string)$num, (string)$len );
  22          $string = $chars[ $mod ] . $string;
  23      }
  24      $string = $chars[ intval( $num ) ] . $string;
  25  
  26      return yourls_apply_filter( 'int2string', $string, $num, $chars );
  27  }
  28  
  29  /**
  30   * Convert a string (3jk) to an integer (1337)
  31   *
  32   * @param string $string  String to convert
  33   * @param string $chars   Characters to use for conversion
  34   * @return string         Number (as a string)
  35   */
  36  function yourls_string2int($string, $chars = null) {
  37      if( $chars == null )
  38          $chars = yourls_get_shorturl_charset();
  39      $integer = 0;
  40      $string = strrev( $string  );
  41      $baselen = strlen( $chars );
  42      $inputlen = strlen( $string );
  43      for ($i = 0; $i < $inputlen; $i++) {
  44          $index = strpos( $chars, $string[$i] );
  45          $integer = bcadd( (string)$integer, bcmul( (string)$index, bcpow( (string)$baselen, (string)$i ) ) );
  46      }
  47  
  48      return yourls_apply_filter( 'string2int', $integer, $string, $chars );
  49  }
  50  
  51  /**
  52   * Return a unique string to be used as a valid HTML id
  53   *
  54   * @since   1.8.3
  55   * @param  string $prefix      Optional prefix
  56   * @param  int    $initial_val The initial counter value (defaults to one)
  57   * @return string              The unique string
  58   */
  59  function yourls_unique_element_id($prefix = 'yid', $initial_val = 1) {
  60      static $id_counter = 1;
  61      if ($initial_val > 1) {
  62          $id_counter = (int) $initial_val;
  63      }
  64      return yourls_apply_filter( 'unique_element_id', $prefix . (string) $id_counter++ );
  65  }
  66  
  67  /**
  68   * Make sure a link keyword (ie "1fv" as in "http://sho.rt/1fv") is acceptable
  69   *
  70   * If we are ADDING or EDITING a short URL, the keyword must comply to the short URL charset: every
  71   * character that doesn't belong to it will be removed.
  72   * But otherwise we must have a more conservative approach: we could be checking for a keyword that
  73   * was once valid but now the short URL charset has changed. In such a case, we are treating the keyword for what
  74   * it is: just a part of a URL, hence sanitize it as a URL.
  75   *
  76   * @param  string $keyword                        short URL keyword
  77   * @param  bool   $restrict_to_shorturl_charset   Optional, default false. True if we want the keyword to comply to short URL charset
  78   * @return string                                 The sanitized keyword
  79   */
  80  function yourls_sanitize_keyword( $keyword, $restrict_to_shorturl_charset = false ) {
  81      if( $restrict_to_shorturl_charset === true ) {
  82          // make a regexp pattern with the shorturl charset, and remove everything but this
  83          $pattern = yourls_make_regexp_pattern( yourls_get_shorturl_charset() );
  84          $valid = (string) substr( preg_replace( '![^'.$pattern.']!', '', $keyword ), 0, 199 );
  85      } else {
  86          $valid = yourls_sanitize_url( $keyword );
  87      }
  88  
  89      return yourls_apply_filter( 'sanitize_string', $valid, $keyword, $restrict_to_shorturl_charset );
  90  }
  91  
  92  /**
  93   * Sanitize a page title. No HTML per W3C http://www.w3.org/TR/html401/struct/global.html#h-7.4.2
  94   *
  95   *
  96   * @since 1.5
  97   * @param string $unsafe_title  Title, potentially unsafe
  98   * @param string $fallback      Optional fallback if after sanitization nothing remains
  99   * @return string               Safe title
 100   */
 101  function yourls_sanitize_title( $unsafe_title, $fallback = '' ) {
 102      $title = $unsafe_title;
 103      $title = strip_tags( $title );
 104      $title = preg_replace( "/\s+/", ' ', trim( $title ) );
 105  
 106      if ( '' === $title || false === $title ) {
 107          $title = $fallback;
 108      }
 109  
 110      return yourls_apply_filter( 'sanitize_title', $title, $unsafe_title, $fallback );
 111  }
 112  
 113  /**
 114   * A few sanity checks on the URL. Used for redirection or DB.
 115   * For redirection when you don't trust the URL ($_SERVER variable, query string), see yourls_sanitize_url_safe()
 116   * For display purpose, see yourls_esc_url()
 117   *
 118   * @param string $unsafe_url unsafe URL
 119   * @param array $protocols Optional allowed protocols, default to global $yourls_allowedprotocols
 120   * @return string Safe URL
 121   */
 122  function yourls_sanitize_url( $unsafe_url, $protocols = array() ) {
 123      $url = yourls_esc_url( $unsafe_url, 'redirection', $protocols );
 124      return yourls_apply_filter( 'sanitize_url', $url, $unsafe_url );
 125  }
 126  
 127  /**
 128   * A few sanity checks on the URL, including CRLF. Used for redirection when URL to be sanitized is critical and cannot be trusted.
 129   *
 130   * Use when critical URL comes from user input or environment variable. In such a case, this function will sanitize
 131   * it like yourls_sanitize_url() but will also remove %0A and %0D to prevent CRLF injection.
 132   * Still, some legit URLs contain %0A or %0D (see issue 2056, and for extra fun 1694, 1707, 2030, and maybe others)
 133   * so we're not using this function unless it's used for internal redirection when the target location isn't
 134   * hardcoded, to avoid XSS via CRLF
 135   *
 136   * @since 1.7.2
 137   * @param string $unsafe_url unsafe URL
 138   * @param array $protocols Optional allowed protocols, default to global $yourls_allowedprotocols
 139   * @return string Safe URL
 140   */
 141  function yourls_sanitize_url_safe( $unsafe_url, $protocols = array() ) {
 142      $url = yourls_esc_url( $unsafe_url, 'safe', $protocols );
 143      return yourls_apply_filter( 'sanitize_url_safe', $url, $unsafe_url );
 144  }
 145  
 146  /**
 147   * Perform a replacement while a string is found, eg $subject = '%0%0%0DDD', $search ='%0D' -> $result =''
 148   *
 149   * Stolen from WP's _deep_replace
 150   *
 151   * @param string|array $search   Needle, or array of needles.
 152   * @param string       $subject  Haystack.
 153   * @return string                The string with the replaced values.
 154   */
 155  function yourls_deep_replace($search, $subject ){
 156      $found = true;
 157      while($found) {
 158          $found = false;
 159          foreach( (array) $search as $val ) {
 160              while( strpos( $subject, $val ) !== false ) {
 161                  $found = true;
 162                  $subject = str_replace( $val, '', $subject );
 163              }
 164          }
 165      }
 166  
 167      return $subject;
 168  }
 169  
 170  /**
 171   * Make sure an integer is a valid integer (PHP's intval() limits to too small numbers)
 172   *
 173   * @param int $int  Integer to check
 174   * @return string   Integer as a string
 175   */
 176  function yourls_sanitize_int($int ) {
 177      return ( substr( preg_replace( '/[^0-9]/', '', strval( $int ) ), 0, 20 ) );
 178  }
 179  
 180  /**
 181   * Sanitize an IP address
 182   * No check on validity, just return a sanitized string
 183   *
 184   * @param string $ip  IP address
 185   * @return string     IP address
 186   */
 187  function yourls_sanitize_ip($ip ) {
 188      return preg_replace( '/[^0-9a-fA-F:., ]/', '', $ip );
 189  }
 190  
 191  /**
 192   * Make sure a date is m(m)/d(d)/yyyy, return false otherwise
 193   *
 194   * @param string $date  Date to check
 195   * @return false|mixed  Date in format m(m)/d(d)/yyyy or false if invalid
 196   */
 197  function yourls_sanitize_date($date ) {
 198      if( !preg_match( '!^\d{1,2}/\d{1,2}/\d{4}$!' , $date ) ) {
 199          return false;
 200      }
 201      return $date;
 202  }
 203  
 204  /**
 205   * Sanitize a date for SQL search. Return false if malformed input.
 206   *
 207   * @param string $date   Date
 208   * @return false|string  String in Y-m-d format for SQL search or false if malformed input
 209   */
 210  function yourls_sanitize_date_for_sql($date) {
 211      if( !yourls_sanitize_date( $date ) )
 212          return false;
 213      return date( 'Y-m-d', strtotime( $date ) );
 214  }
 215  
 216  /**
 217   * Return trimmed string, optionally append '[...]' if string is too long
 218   *
 219   * @param string $string  String to trim
 220   * @param int $length     Maximum length of string
 221   * @param string $append  String to append if trimmed
 222   * @return string         Trimmed string
 223   */
 224  function yourls_trim_long_string($string, $length = 60, $append = '[...]') {
 225      $newstring = $string;
 226      if ( mb_strlen( $newstring ) > $length ) {
 227          $newstring = mb_substr( $newstring, 0, $length - mb_strlen( $append ), 'UTF-8' ) . $append;
 228      }
 229      return yourls_apply_filter( 'trim_long_string', $newstring, $string, $length, $append );
 230  }
 231  
 232  /**
 233   * Sanitize a version number (1.4.1-whatever-RC1 -> 1.4.1)
 234   *
 235   * The regexp searches for the first digits, then a period, then more digits and periods, and discards
 236   * all the rest.
 237   * For instance, 'mysql-5.5-beta' and '5.5-RC1' return '5.5'
 238   *
 239   * @since 1.4.1
 240   * @param  string $version  Version number
 241   * @return string           Sanitized version number
 242   */
 243  function yourls_sanitize_version( $version ) {
 244      preg_match( '/([0-9]+\.[0-9.]+).*$/', $version, $matches );
 245      $version = isset($matches[1]) ? trim($matches[1], '.') : '';
 246  
 247      return $version;
 248  }
 249  
 250  /**
 251   * Sanitize a filename (no Win32 stuff)
 252   *
 253   * @param string $file  File name
 254   * @return string|null  Sanitized file name (or null if it's just backslashes, ok...)
 255   */
 256  function yourls_sanitize_filename($file) {
 257      $file = str_replace( '\\', '/', $file ); // sanitize for Win32 installs
 258      $file = preg_replace( '|/+|' ,'/', $file ); // remove any duplicate slash
 259      return $file;
 260  }
 261  
 262  /**
 263   * Check if a string seems to be UTF-8. Stolen from WP.
 264   *
 265   * @param string $str  String to check
 266   * @return bool        Whether string seems valid UTF-8
 267   */
 268  function yourls_seems_utf8($str) {
 269      $length = strlen( $str );
 270      for ( $i=0; $i < $length; $i++ ) {
 271          $c = ord( $str[ $i ] );
 272          if ( $c < 0x80 ) $n = 0; # 0bbbbbbb
 273          elseif (($c & 0xE0) == 0xC0) $n=1; # 110bbbbb
 274          elseif (($c & 0xF0) == 0xE0) $n=2; # 1110bbbb
 275          elseif (($c & 0xF8) == 0xF0) $n=3; # 11110bbb
 276          elseif (($c & 0xFC) == 0xF8) $n=4; # 111110bb
 277          elseif (($c & 0xFE) == 0xFC) $n=5; # 1111110b
 278          else return false; # Does not match any model
 279          for ($j=0; $j<$n; $j++) { # n bytes matching 10bbbbbb follow ?
 280              if ((++$i == $length) || ((ord($str[$i]) & 0xC0) != 0x80))
 281                  return false;
 282          }
 283      }
 284      return true;
 285  }
 286  
 287  
 288  /**
 289   * Check for PCRE /u modifier support. Stolen from WP.
 290   *
 291   * Just in case "PCRE is not compiled with PCRE_UTF8" which seems to happen
 292   * on some distros
 293   *
 294   * @since 1.7.1
 295   *
 296   * @return bool whether there's /u support or not
 297   */
 298  function yourls_supports_pcre_u() {
 299      static $utf8_pcre;
 300      if( !isset( $utf8_pcre ) ) {
 301          $utf8_pcre = (bool) @preg_match( '/^./u', 'a' );
 302      }
 303      return $utf8_pcre;
 304  }
 305  
 306  /**
 307   * Checks for invalid UTF8 in a string. Stolen from WP
 308   *
 309   * @since 1.6
 310   *
 311   * @param string $string The text which is to be checked.
 312   * @param boolean $strip Optional. Whether to attempt to strip out invalid UTF8. Default is false.
 313   * @return string The checked text.
 314   */
 315  function yourls_check_invalid_utf8( $string, $strip = false ) {
 316      $string = (string) $string;
 317  
 318      if ( 0 === strlen( $string ) ) {
 319          return '';
 320      }
 321  
 322      // We can't demand utf8 in the PCRE installation, so just return the string in those cases
 323      if ( ! yourls_supports_pcre_u() ) {
 324          return $string;
 325      }
 326  
 327      // preg_match fails when it encounters invalid UTF8 in $string
 328      if ( 1 === @preg_match( '/^./us', $string ) ) {
 329          return $string;
 330      }
 331  
 332      // Attempt to strip the bad chars if requested (not recommended)
 333      if ( $strip && function_exists( 'iconv' ) ) {
 334          return iconv( 'utf-8', 'utf-8', $string );
 335      }
 336  
 337      return '';
 338  }
 339  
 340  /**
 341   * Converts a number of special characters into their HTML entities. Stolen from WP.
 342   *
 343   * Specifically deals with: &, <, >, ", and '.
 344   *
 345   * $quote_style can be set to ENT_COMPAT to encode " to
 346   * &quot;, or ENT_QUOTES to do both. Default is ENT_NOQUOTES where no quotes are encoded.
 347   *
 348   * @since 1.6
 349   *
 350   * @param string $string The text which is to be encoded.
 351   * @param mixed $quote_style Optional. Converts double quotes if set to ENT_COMPAT, both single and double if set to ENT_QUOTES or none if set to ENT_NOQUOTES. Also compatible with old values; converting single quotes if set to 'single', double if set to 'double' or both if otherwise set. Default is ENT_NOQUOTES.
 352   * @param boolean $double_encode Optional. Whether to encode existing html entities. Default is false.
 353   * @return string The encoded text with HTML entities.
 354   */
 355  function yourls_specialchars( $string, $quote_style = ENT_NOQUOTES, $double_encode = false ) {
 356      $string = (string) $string;
 357  
 358      if ( 0 === strlen( $string ) )
 359          return '';
 360  
 361      // Don't bother if there are no specialchars - saves some processing
 362      if ( ! preg_match( '/[&<>"\']/', $string ) )
 363          return $string;
 364  
 365      // Account for the previous behaviour of the function when the $quote_style is not an accepted value
 366      if ( empty( $quote_style ) )
 367          $quote_style = ENT_NOQUOTES;
 368      elseif ( ! in_array( $quote_style, array( 0, 2, 3, 'single', 'double' ), true ) )
 369          $quote_style = ENT_QUOTES;
 370  
 371      $charset = 'UTF-8';
 372  
 373      $_quote_style = $quote_style;
 374  
 375      if ( $quote_style === 'double' ) {
 376          $quote_style = ENT_COMPAT;
 377          $_quote_style = ENT_COMPAT;
 378      } elseif ( $quote_style === 'single' ) {
 379          $quote_style = ENT_NOQUOTES;
 380      }
 381  
 382      // Handle double encoding ourselves
 383      if ( $double_encode ) {
 384          $string = @htmlspecialchars( $string, $quote_style, $charset );
 385      } else {
 386          // Decode &amp; into &
 387          $string = yourls_specialchars_decode( $string, $_quote_style );
 388  
 389          // Guarantee every &entity; is valid or re-encode the &
 390          $string = yourls_kses_normalize_entities( $string );
 391  
 392          // Now re-encode everything except &entity;
 393          $string = preg_split( '/(&#?x?[0-9a-z]+;)/i', $string, -1, PREG_SPLIT_DELIM_CAPTURE );
 394  
 395          for ( $i = 0; $i < count( $string ); $i += 2 )
 396              $string[$i] = @htmlspecialchars( $string[$i], $quote_style, $charset );
 397  
 398          $string = implode( '', $string );
 399      }
 400  
 401      // Backwards compatibility
 402      if ( 'single' === $_quote_style )
 403          $string = str_replace( "'", '&#039;', $string );
 404  
 405      return $string;
 406  }
 407  
 408  /**
 409   * Converts a number of HTML entities into their special characters. Stolen from WP.
 410   *
 411   * Specifically deals with: &, <, >, ", and '.
 412   *
 413   * $quote_style can be set to ENT_COMPAT to decode " entities,
 414   * or ENT_QUOTES to do both " and '. Default is ENT_NOQUOTES where no quotes are decoded.
 415   *
 416   * @since 1.6
 417   *
 418   * @param string $string The text which is to be decoded.
 419   * @param mixed $quote_style Optional. Converts double quotes if set to ENT_COMPAT, both single and double if set to ENT_QUOTES or none if set to ENT_NOQUOTES. Also compatible with old _wp_specialchars() values; converting single quotes if set to 'single', double if set to 'double' or both if otherwise set. Default is ENT_NOQUOTES.
 420   * @return string The decoded text without HTML entities.
 421   */
 422  function yourls_specialchars_decode( $string, $quote_style = ENT_NOQUOTES ) {
 423      $string = (string) $string;
 424  
 425      if ( 0 === strlen( $string ) ) {
 426          return '';
 427      }
 428  
 429      // Don't bother if there are no entities - saves a lot of processing
 430      if ( strpos( $string, '&' ) === false ) {
 431          return $string;
 432      }
 433  
 434      // Match the previous behaviour of _wp_specialchars() when the $quote_style is not an accepted value
 435      if ( empty( $quote_style ) ) {
 436          $quote_style = ENT_NOQUOTES;
 437      } elseif ( !in_array( $quote_style, array( 0, 2, 3, 'single', 'double' ), true ) ) {
 438          $quote_style = ENT_QUOTES;
 439      }
 440  
 441      // More complete than get_html_translation_table( HTML_SPECIALCHARS )
 442      $single = array( '&#039;'  => '\'', '&#x27;' => '\'' );
 443      $single_preg = array( '/&#0*39;/'  => '&#039;', '/&#x0*27;/i' => '&#x27;' );
 444      $double = array( '&quot;' => '"', '&#034;'  => '"', '&#x22;' => '"' );
 445      $double_preg = array( '/&#0*34;/'  => '&#034;', '/&#x0*22;/i' => '&#x22;' );
 446      $others = array( '&lt;'   => '<', '&#060;'  => '<', '&gt;'   => '>', '&#062;'  => '>', '&amp;'  => '&', '&#038;'  => '&', '&#x26;' => '&' );
 447      $others_preg = array( '/&#0*60;/'  => '&#060;', '/&#0*62;/'  => '&#062;', '/&#0*38;/'  => '&#038;', '/&#x0*26;/i' => '&#x26;' );
 448  
 449      $translation = $translation_preg = [];
 450  
 451      if ( $quote_style === ENT_QUOTES ) {
 452          $translation = array_merge( $single, $double, $others );
 453          $translation_preg = array_merge( $single_preg, $double_preg, $others_preg );
 454      } elseif ( $quote_style === ENT_COMPAT || $quote_style === 'double' ) {
 455          $translation = array_merge( $double, $others );
 456          $translation_preg = array_merge( $double_preg, $others_preg );
 457      } elseif ( $quote_style === 'single' ) {
 458          $translation = array_merge( $single, $others );
 459          $translation_preg = array_merge( $single_preg, $others_preg );
 460      } elseif ( $quote_style === ENT_NOQUOTES ) {
 461          $translation = $others;
 462          $translation_preg = $others_preg;
 463      }
 464  
 465      // Remove zero padding on numeric entities
 466      $string = preg_replace( array_keys( $translation_preg ), array_values( $translation_preg ), $string );
 467  
 468      // Replace characters according to translation table
 469      return strtr( $string, $translation );
 470  }
 471  
 472  
 473  /**
 474   * Escaping for HTML blocks. Stolen from WP
 475   *
 476   * @since 1.6
 477   *
 478   * @param string $text
 479   * @return string
 480   */
 481  function yourls_esc_html( $text ) {
 482      $safe_text = yourls_check_invalid_utf8( $text );
 483      $safe_text = yourls_specialchars( $safe_text, ENT_QUOTES );
 484      return yourls_apply_filter( 'esc_html', $safe_text, $text );
 485  }
 486  
 487  /**
 488   * Escaping for HTML attributes.  Stolen from WP
 489   *
 490   * @since 1.6
 491   *
 492   * @param string $text
 493   * @return string
 494   */
 495  function yourls_esc_attr( $text ) {
 496      $safe_text = yourls_check_invalid_utf8( $text );
 497      $safe_text = yourls_specialchars( $safe_text, ENT_QUOTES );
 498      return yourls_apply_filter( 'esc_attr', $safe_text, $text );
 499  }
 500  
 501  /**
 502   * Checks and cleans a URL before printing it. Stolen from WP.
 503   *
 504   * A number of characters are removed from the URL. If the URL is for displaying
 505   * (the default behaviour) ampersands are also replaced.
 506   *
 507   * This function by default "escapes" URL for display purpose (param $context = 'display') but can
 508   * take extra steps in URL sanitization. See yourls_sanitize_url() and yourls_sanitize_url_safe()
 509   *
 510   * @since 1.6
 511   *
 512   * @param string $url The URL to be cleaned.
 513   * @param string $context 'display' or something else. Use yourls_sanitize_url() for database or redirection usage.
 514   * @param array $protocols Optional. Array of allowed protocols, defaults to global $yourls_allowedprotocols
 515   * @return string The cleaned $url
 516   */
 517  function yourls_esc_url( $url, $context = 'display', $protocols = array() ) {
 518      // trim first -- see #1931
 519      $url = trim( $url );
 520  
 521      // make sure there's only one 'http://' at the beginning (prevents pasting a URL right after the default 'http://')
 522      $url = str_replace(
 523          array( 'http://http://', 'http://https://' ),
 524          array( 'http://',        'https://'        ),
 525          $url
 526      );
 527  
 528      if ( '' == $url )
 529          return $url;
 530  
 531      $original_url = $url;
 532  
 533      // force scheme and domain to lowercase - see issues 591 and 1630
 534      $url = yourls_normalize_uri( $url );
 535  
 536      $url = preg_replace( '|[^a-z0-9-~+_.?#=!&;,/:%@$\|*\'()\[\]\\x80-\\xff]|i', '', $url );
 537      // Previous regexp in YOURLS was '|[^a-z0-9-~+_.?\[\]\^#=!&;,/:%@$\|*`\'<>"()\\x80-\\xff\{\}]|i'
 538      // TODO: check if that was it too destructive
 539  
 540      // If $context is 'safe', an extra step is taken to make sure no CRLF injection is possible.
 541      // To be used when $url can be forged by evil user (eg it's from a $_SERVER variable, a query string, etc..)
 542      if ( 'safe' == $context ) {
 543          $strip = array( '%0d', '%0a', '%0D', '%0A' );
 544          $url = yourls_deep_replace( $strip, $url );
 545      }
 546  
 547      // Replace ampersands and single quotes only when displaying.
 548      if ( 'display' == $context ) {
 549          $url = yourls_kses_normalize_entities( $url );
 550          $url = str_replace( '&amp;', '&#038;', $url );
 551          $url = str_replace( "'", '&#039;', $url );
 552      }
 553  
 554      // If there's a protocol, make sure it's OK
 555      if( yourls_get_protocol($url) !== '' ) {
 556          if ( ! is_array( $protocols ) or ! $protocols ) {
 557              global $yourls_allowedprotocols;
 558              $protocols = yourls_apply_filter( 'esc_url_protocols', $yourls_allowedprotocols );
 559              // Note: $yourls_allowedprotocols is also globally filterable in functions-kses.php/yourls_kses_init()
 560          }
 561  
 562          if ( !yourls_is_allowed_protocol( $url, $protocols ) )
 563              return '';
 564  
 565          // I didn't use KSES function kses_bad_protocol() because it doesn't work the way I liked (returns //blah from illegal://blah)
 566      }
 567  
 568      return yourls_apply_filter( 'esc_url', $url, $original_url, $context );
 569  }
 570  
 571  
 572  /**
 573   * Normalize a URI : lowercase scheme and domain, convert IDN to UTF8
 574   *
 575   * All in one example: 'HTTP://XN--mgbuq0c.Com/AbCd' -> 'http://طارق.com/AbCd'
 576   * See issues 591, 1630, 1889, 2691
 577   *
 578   * This function is trickier than what seems to be needed at first
 579   *
 580   * First, we need to handle several URI types: http://example.com, mailto:[email protected], facetime:[email protected], and so on, see
 581   * yourls_kses_allowed_protocols() in functions-kses.php
 582   * The general rule is that the scheme ("stuff://" or "stuff:") is case insensitive and should be lowercase. But then, depending on the
 583   * scheme, parts of what follows the scheme may or may not be case sensitive.
 584   *
 585   * Second, simply using parse_url() and its opposite http_build_url() is a pretty unsafe process:
 586   *  - parse_url() can easily trip up on malformed or weird URLs
 587   *  - exploding a URL with parse_url(), lowercasing some stuff, and glueing things back with http_build_url() does not handle well
 588   *    "stuff:"-like URI [1] and can result in URLs ending modified [2][3]. We don't want to *validate* URI, we just want to lowercase
 589   *    what is supposed to be lowercased.
 590   *
 591   * So, to be conservative, this function:
 592   *  - lowercases the scheme
 593   *  - does not lowercase anything else on "stuff:" URI
 594   *  - tries to lowercase only scheme and domain of "stuff://" URI
 595   *
 596   * [1] http_build_url(parse_url("mailto:ozh")) == "mailto:///ozh"
 597   * [2] http_build_url(parse_url("http://blah#omg")) == "http://blah/#omg"
 598   * [3] http_build_url(parse_url("http://blah?#")) == "http://blah/"
 599   *
 600   * @since 1.7.1
 601   * @param string $url URL
 602   * @return string URL with lowercase scheme and protocol
 603   */
 604  function yourls_normalize_uri( $url ) {
 605      $scheme = yourls_get_protocol( $url );
 606  
 607      if ('' == $scheme) {
 608          // Scheme not found, malformed URL? Something else? Not sure.
 609          return $url;
 610      }
 611  
 612      /**
 613       * Case 1 : scheme like "stuff:", as opposed to "stuff://"
 614       * Examples: "mailto:[email protected]" or "bitcoin:15p1o8vnWqNkJBJGgwafNgR1GCCd6EGtQR?amount=1&label=Ozh"
 615       * In this case, we only lowercase the scheme, because depending on it, things after should or should not be lowercased
 616       */
 617      if (substr($scheme, -2, 2) != '//') {
 618          $url = str_replace( $scheme, strtolower( $scheme ), $url );
 619          return $url;
 620      }
 621  
 622      /**
 623       * Case 2 : scheme like "stuff://" (eg "http://example.com/" or "ssh://[email protected]")
 624       * Here we lowercase the scheme and domain parts
 625       */
 626      $parts = parse_url($url);
 627  
 628      // Most likely malformed stuff, could not parse : we'll just lowercase the scheme and leave the rest untouched
 629      if (false == $parts) {
 630          $url = str_replace( $scheme, strtolower( $scheme ), $url );
 631          return $url;
 632      }
 633  
 634      // URL seems parsable, let's do the best we can
 635      $lower = array();
 636      $lower['scheme'] = strtolower( $parts['scheme'] );
 637      if( isset( $parts['host'] ) ) {
 638          // Convert domain to lowercase, with mb_ to preserve UTF8
 639          $lower['host'] = mb_strtolower($parts['host']);
 640          /**
 641           * Convert IDN domains to their UTF8 form so that طارق.net and xn--mgbuq0c.net
 642           * are considered the same. Explicitly mention option and variant to avoid notice
 643           * on PHP 7.2 and 7.3
 644           */
 645           $lower['host'] = idn_to_utf8($lower['host'], IDNA_DEFAULT, INTL_IDNA_VARIANT_UTS46);
 646      }
 647  
 648      $url = http_build_url($url, $lower);
 649  
 650      return $url;
 651  }
 652  
 653  
 654  /**
 655   * Escape single quotes, htmlspecialchar " < > &, and fix line endings. Stolen from WP.
 656   *
 657   * Escapes text strings for echoing in JS. It is intended to be used for inline JS
 658   * (in a tag attribute, for example onclick="..."). Note that the strings have to
 659   * be in single quotes. The filter 'js_escape' is also applied here.
 660   *
 661   * @since 1.6
 662   *
 663   * @param string $text The text to be escaped.
 664   * @return string Escaped text.
 665   */
 666  function yourls_esc_js( $text ) {
 667      $safe_text = yourls_check_invalid_utf8( $text );
 668      $safe_text = yourls_specialchars( $safe_text, ENT_COMPAT );
 669      $safe_text = preg_replace( '/&#(x)?0*(?(1)27|39);?/i', "'", stripslashes( $safe_text ) );
 670      $safe_text = str_replace( "\r", '', $safe_text );
 671      $safe_text = str_replace( "\n", '\\n', addslashes( $safe_text ) );
 672      return yourls_apply_filter( 'esc_js', $safe_text, $text );
 673  }
 674  
 675  /**
 676   * Escaping for textarea values. Stolen from WP.
 677   *
 678   * @since 1.6
 679   *
 680   * @param string $text
 681   * @return string
 682   */
 683  function yourls_esc_textarea( $text ) {
 684      $safe_text = htmlspecialchars( $text, ENT_QUOTES );
 685      return yourls_apply_filter( 'esc_textarea', $safe_text, $text );
 686  }
 687  
 688  /**
 689   * Adds backslashes before letters and before a number at the start of a string. Stolen from WP.
 690   *
 691   * @since 1.6
 692   * @param string $string Value to which backslashes will be added.
 693   * @return string String with backslashes inserted.
 694   */
 695  function yourls_backslashit($string) {
 696      $string = preg_replace('/^([0-9])/', '\\\\\\\\\1', (string)$string);
 697      $string = preg_replace('/([a-z])/i', '\\\\\1', (string)$string);
 698      return $string;
 699  }
 700  
 701  /**
 702   * Check if a string seems to be urlencoded
 703   *
 704   * We use rawurlencode instead of urlencode to avoid messing with '+'
 705   *
 706   * @since 1.7
 707   * @param string $string
 708   * @return bool
 709   */
 710  function yourls_is_rawurlencoded( $string ) {
 711      return rawurldecode( $string ) != $string;
 712  }
 713  
 714  /**
 715   * rawurldecode a string till it's not encoded anymore
 716   *
 717   * Deals with multiple encoding (eg "%2521" => "%21" => "!").
 718   * See https://github.com/YOURLS/YOURLS/issues/1303
 719   *
 720   * @since 1.7
 721   * @param string $string
 722   * @return string
 723   */
 724  function yourls_rawurldecode_while_encoded( $string ) {
 725      $string = rawurldecode( $string );
 726      if( yourls_is_rawurlencoded( $string ) ) {
 727          $string = yourls_rawurldecode_while_encoded( $string );
 728      }
 729      return $string;
 730  }
 731  
 732  /**
 733   * Converts readable Javascript code into a valid bookmarklet link
 734   *
 735   * Uses https://github.com/ozh/bookmarkletgen
 736   *
 737   * @since 1.7.1
 738   * @param  string $code  Javascript code
 739   * @return string        Bookmarklet link
 740   */
 741  function yourls_make_bookmarklet( $code ) {
 742      $book = new \Ozh\Bookmarkletgen\Bookmarkletgen;
 743      return $book->crunch( $code );
 744  }
 745  
 746  /**
 747   * Return a timestamp, plus or minus the time offset if defined
 748   *
 749   * @since 1.7.10
 750   * @param  string|int $timestamp  a timestamp
 751   * @return int                    a timestamp, plus or minus offset if defined
 752   */
 753  function yourls_get_timestamp( $timestamp ) {
 754      $offset = yourls_get_time_offset();
 755      $timestamp_offset = (int)$timestamp + ($offset * 3600);
 756  
 757      return yourls_apply_filter( 'get_timestamp', $timestamp_offset, $timestamp, $offset );
 758  }
 759  
 760  /**
 761   * Get time offset, as defined in config, filtered
 762   *
 763   * @since 1.7.10
 764   * @return int       Time offset
 765   */
 766  function yourls_get_time_offset() {
 767      $offset = defined('YOURLS_HOURS_OFFSET') ? (int)YOURLS_HOURS_OFFSET : 0;
 768      return yourls_apply_filter( 'get_time_offset', $offset );
 769  }
 770  
 771  /**
 772   * Return a date() format for a full date + time, filtered
 773   *
 774   * @since 1.7.10
 775   * @param  string $format  Date format string
 776   * @return string          Date format string
 777   */
 778  function yourls_get_datetime_format( $format ) {
 779      return yourls_apply_filter( 'get_datetime_format', (string)$format );
 780  }
 781  
 782  /**
 783   * Return a date() format for date (no time), filtered
 784   *
 785   * @since 1.7.10
 786   * @param  string $format  Date format string
 787   * @return string          Date format string
 788   */
 789  function yourls_get_date_format( $format ) {
 790      return yourls_apply_filter( 'get_date_format', (string)$format );
 791  }
 792  
 793  /**
 794   * Return a date() format for a time (no date), filtered
 795   *
 796   * @since 1.7.10
 797   * @param  string $format  Date format string
 798   * @return string          Date format string
 799   */
 800  function yourls_get_time_format( $format ) {
 801      return yourls_apply_filter( 'get_time_format', (string)$format );
 802  }


Generated: Sat Feb 22 05:10:06 2025 Cross-referenced by PHPXref 0.7.1