[ 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   * Examples:
 238   * 'omgmysql-5.5-ubuntu-4.20' => '5.5'
 239   * 'mysql5.5-ubuntu-4.20'     => '5.5'
 240   * '5.5-ubuntu-4.20'          => '5.5'
 241   * '5.5-beta2'                => '5.5'
 242   * '5.5'                      => '5.5'
 243   *
 244   * @since 1.4.1
 245   * @param  string $version  Version number
 246   * @return string           Sanitized version number
 247   */
 248  function yourls_sanitize_version( $version ) {
 249      preg_match( '/([0-9]+\.[0-9.]+).*$/', $version, $matches );
 250      $version = isset($matches[1]) ? trim($matches[1], '.') : '';
 251  
 252      return $version;
 253  }
 254  
 255  /**
 256   * Sanitize a filename (no Win32 stuff)
 257   *
 258   * @param string $file  File name
 259   * @return string|null  Sanitized file name (or null if it's just backslashes, ok...)
 260   */
 261  function yourls_sanitize_filename($file) {
 262      $file = str_replace( '\\', '/', $file ); // sanitize for Win32 installs
 263      $file = preg_replace( '|/+|' ,'/', $file ); // remove any duplicate slash
 264      return $file;
 265  }
 266  
 267  /**
 268   * Check if a string seems to be UTF-8. Stolen from WP.
 269   *
 270   * @param string $str  String to check
 271   * @return bool        Whether string seems valid UTF-8
 272   */
 273  function yourls_seems_utf8($str) {
 274      $length = strlen( $str );
 275      for ( $i=0; $i < $length; $i++ ) {
 276          $c = ord( $str[ $i ] );
 277          if ( $c < 0x80 ) $n = 0; # 0bbbbbbb
 278          elseif (($c & 0xE0) == 0xC0) $n=1; # 110bbbbb
 279          elseif (($c & 0xF0) == 0xE0) $n=2; # 1110bbbb
 280          elseif (($c & 0xF8) == 0xF0) $n=3; # 11110bbb
 281          elseif (($c & 0xFC) == 0xF8) $n=4; # 111110bb
 282          elseif (($c & 0xFE) == 0xFC) $n=5; # 1111110b
 283          else return false; # Does not match any model
 284          for ($j=0; $j<$n; $j++) { # n bytes matching 10bbbbbb follow ?
 285              if ((++$i == $length) || ((ord($str[$i]) & 0xC0) != 0x80))
 286                  return false;
 287          }
 288      }
 289      return true;
 290  }
 291  
 292  
 293  /**
 294   * Check for PCRE /u modifier support. Stolen from WP.
 295   *
 296   * Just in case "PCRE is not compiled with PCRE_UTF8" which seems to happen
 297   * on some distros
 298   *
 299   * @since 1.7.1
 300   *
 301   * @return bool whether there's /u support or not
 302   */
 303  function yourls_supports_pcre_u() {
 304      static $utf8_pcre;
 305      if( !isset( $utf8_pcre ) ) {
 306          $utf8_pcre = (bool) @preg_match( '/^./u', 'a' );
 307      }
 308      return $utf8_pcre;
 309  }
 310  
 311  /**
 312   * Checks for invalid UTF8 in a string. Stolen from WP
 313   *
 314   * @since 1.6
 315   *
 316   * @param string $string The text which is to be checked.
 317   * @param boolean $strip Optional. Whether to attempt to strip out invalid UTF8. Default is false.
 318   * @return string The checked text.
 319   */
 320  function yourls_check_invalid_utf8( $string, $strip = false ) {
 321      $string = (string) $string;
 322  
 323      if ( 0 === strlen( $string ) ) {
 324          return '';
 325      }
 326  
 327      // We can't demand utf8 in the PCRE installation, so just return the string in those cases
 328      if ( ! yourls_supports_pcre_u() ) {
 329          return $string;
 330      }
 331  
 332      // preg_match fails when it encounters invalid UTF8 in $string
 333      if ( 1 === @preg_match( '/^./us', $string ) ) {
 334          return $string;
 335      }
 336  
 337      // Attempt to strip the bad chars if requested (not recommended)
 338      if ( $strip && function_exists( 'iconv' ) ) {
 339          return iconv( 'utf-8', 'utf-8', $string );
 340      }
 341  
 342      return '';
 343  }
 344  
 345  /**
 346   * Converts a number of special characters into their HTML entities. Stolen from WP.
 347   *
 348   * Specifically deals with: &, <, >, ", and '.
 349   *
 350   * $quote_style can be set to ENT_COMPAT to encode " to
 351   * &quot;, or ENT_QUOTES to do both. Default is ENT_NOQUOTES where no quotes are encoded.
 352   *
 353   * @since 1.6
 354   *
 355   * @param string $string The text which is to be encoded.
 356   * @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.
 357   * @param boolean $double_encode Optional. Whether to encode existing html entities. Default is false.
 358   * @return string The encoded text with HTML entities.
 359   */
 360  function yourls_specialchars( $string, $quote_style = ENT_NOQUOTES, $double_encode = false ) {
 361      $string = (string) $string;
 362  
 363      if ( 0 === strlen( $string ) )
 364          return '';
 365  
 366      // Don't bother if there are no specialchars - saves some processing
 367      if ( ! preg_match( '/[&<>"\']/', $string ) )
 368          return $string;
 369  
 370      // Account for the previous behaviour of the function when the $quote_style is not an accepted value
 371      if ( empty( $quote_style ) )
 372          $quote_style = ENT_NOQUOTES;
 373      elseif ( ! in_array( $quote_style, array( 0, 2, 3, 'single', 'double' ), true ) )
 374          $quote_style = ENT_QUOTES;
 375  
 376      $charset = 'UTF-8';
 377  
 378      $_quote_style = $quote_style;
 379  
 380      if ( $quote_style === 'double' ) {
 381          $quote_style = ENT_COMPAT;
 382          $_quote_style = ENT_COMPAT;
 383      } elseif ( $quote_style === 'single' ) {
 384          $quote_style = ENT_NOQUOTES;
 385      }
 386  
 387      // Handle double encoding ourselves
 388      if ( $double_encode ) {
 389          $string = @htmlspecialchars( $string, $quote_style, $charset );
 390      } else {
 391          // Decode &amp; into &
 392          $string = yourls_specialchars_decode( $string, $_quote_style );
 393  
 394          // Guarantee every &entity; is valid or re-encode the &
 395          $string = yourls_kses_normalize_entities( $string );
 396  
 397          // Now re-encode everything except &entity;
 398          $string = preg_split( '/(&#?x?[0-9a-z]+;)/i', $string, -1, PREG_SPLIT_DELIM_CAPTURE );
 399  
 400          for ( $i = 0; $i < count( $string ); $i += 2 )
 401              $string[$i] = @htmlspecialchars( $string[$i], $quote_style, $charset );
 402  
 403          $string = implode( '', $string );
 404      }
 405  
 406      // Backwards compatibility
 407      if ( 'single' === $_quote_style )
 408          $string = str_replace( "'", '&#039;', $string );
 409  
 410      return $string;
 411  }
 412  
 413  /**
 414   * Converts a number of HTML entities into their special characters. Stolen from WP.
 415   *
 416   * Specifically deals with: &, <, >, ", and '.
 417   *
 418   * $quote_style can be set to ENT_COMPAT to decode " entities,
 419   * or ENT_QUOTES to do both " and '. Default is ENT_NOQUOTES where no quotes are decoded.
 420   *
 421   * @since 1.6
 422   *
 423   * @param string $string The text which is to be decoded.
 424   * @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.
 425   * @return string The decoded text without HTML entities.
 426   */
 427  function yourls_specialchars_decode( $string, $quote_style = ENT_NOQUOTES ) {
 428      $string = (string) $string;
 429  
 430      if ( 0 === strlen( $string ) ) {
 431          return '';
 432      }
 433  
 434      // Don't bother if there are no entities - saves a lot of processing
 435      if ( strpos( $string, '&' ) === false ) {
 436          return $string;
 437      }
 438  
 439      // Match the previous behaviour of _wp_specialchars() when the $quote_style is not an accepted value
 440      if ( empty( $quote_style ) ) {
 441          $quote_style = ENT_NOQUOTES;
 442      } elseif ( !in_array( $quote_style, array( 0, 2, 3, 'single', 'double' ), true ) ) {
 443          $quote_style = ENT_QUOTES;
 444      }
 445  
 446      // More complete than get_html_translation_table( HTML_SPECIALCHARS )
 447      $single = array( '&#039;'  => '\'', '&#x27;' => '\'' );
 448      $single_preg = array( '/&#0*39;/'  => '&#039;', '/&#x0*27;/i' => '&#x27;' );
 449      $double = array( '&quot;' => '"', '&#034;'  => '"', '&#x22;' => '"' );
 450      $double_preg = array( '/&#0*34;/'  => '&#034;', '/&#x0*22;/i' => '&#x22;' );
 451      $others = array( '&lt;'   => '<', '&#060;'  => '<', '&gt;'   => '>', '&#062;'  => '>', '&amp;'  => '&', '&#038;'  => '&', '&#x26;' => '&' );
 452      $others_preg = array( '/&#0*60;/'  => '&#060;', '/&#0*62;/'  => '&#062;', '/&#0*38;/'  => '&#038;', '/&#x0*26;/i' => '&#x26;' );
 453  
 454      $translation = $translation_preg = [];
 455  
 456      if ( $quote_style === ENT_QUOTES ) {
 457          $translation = array_merge( $single, $double, $others );
 458          $translation_preg = array_merge( $single_preg, $double_preg, $others_preg );
 459      } elseif ( $quote_style === ENT_COMPAT || $quote_style === 'double' ) {
 460          $translation = array_merge( $double, $others );
 461          $translation_preg = array_merge( $double_preg, $others_preg );
 462      } elseif ( $quote_style === 'single' ) {
 463          $translation = array_merge( $single, $others );
 464          $translation_preg = array_merge( $single_preg, $others_preg );
 465      } elseif ( $quote_style === ENT_NOQUOTES ) {
 466          $translation = $others;
 467          $translation_preg = $others_preg;
 468      }
 469  
 470      // Remove zero padding on numeric entities
 471      $string = preg_replace( array_keys( $translation_preg ), array_values( $translation_preg ), $string );
 472  
 473      // Replace characters according to translation table
 474      return strtr( $string, $translation );
 475  }
 476  
 477  
 478  /**
 479   * Escaping for HTML blocks. Stolen from WP
 480   *
 481   * @since 1.6
 482   *
 483   * @param string $text
 484   * @return string
 485   */
 486  function yourls_esc_html( $text ) {
 487      $safe_text = yourls_check_invalid_utf8( $text );
 488      $safe_text = yourls_specialchars( $safe_text, ENT_QUOTES );
 489      return yourls_apply_filter( 'esc_html', $safe_text, $text );
 490  }
 491  
 492  /**
 493   * Escaping for HTML attributes.  Stolen from WP
 494   *
 495   * @since 1.6
 496   *
 497   * @param string $text
 498   * @return string
 499   */
 500  function yourls_esc_attr( $text ) {
 501      $safe_text = yourls_check_invalid_utf8( $text );
 502      $safe_text = yourls_specialchars( $safe_text, ENT_QUOTES );
 503      return yourls_apply_filter( 'esc_attr', $safe_text, $text );
 504  }
 505  
 506  /**
 507   * Checks and cleans a URL before printing it. Stolen from WP.
 508   *
 509   * A number of characters are removed from the URL. If the URL is for displaying
 510   * (the default behaviour) ampersands are also replaced.
 511   *
 512   * This function by default "escapes" URL for display purpose (param $context = 'display') but can
 513   * take extra steps in URL sanitization. See yourls_sanitize_url() and yourls_sanitize_url_safe()
 514   *
 515   * @since 1.6
 516   *
 517   * @param string $url The URL to be cleaned.
 518   * @param string $context 'display' or something else. Use yourls_sanitize_url() for database or redirection usage.
 519   * @param array $protocols Optional. Array of allowed protocols, defaults to global $yourls_allowedprotocols
 520   * @return string The cleaned $url
 521   */
 522  function yourls_esc_url( $url, $context = 'display', $protocols = array() ) {
 523      // trim first -- see #1931
 524      $url = trim( $url );
 525  
 526      // make sure there's only one 'http://' at the beginning (prevents pasting a URL right after the default 'http://')
 527      $url = str_replace(
 528          array( 'http://http://', 'http://https://' ),
 529          array( 'http://',        'https://'        ),
 530          $url
 531      );
 532  
 533      if ( '' == $url )
 534          return $url;
 535  
 536      $original_url = $url;
 537  
 538      // force scheme and domain to lowercase - see issues 591 and 1630
 539      $url = yourls_normalize_uri( $url );
 540  
 541      $url = preg_replace( '|[^a-z0-9-~+_.?#=!&;,/:%@$\|*\'()\[\]\\x80-\\xff]|i', '', $url );
 542      // Previous regexp in YOURLS was '|[^a-z0-9-~+_.?\[\]\^#=!&;,/:%@$\|*`\'<>"()\\x80-\\xff\{\}]|i'
 543      // TODO: check if that was it too destructive
 544  
 545      // If $context is 'safe', an extra step is taken to make sure no CRLF injection is possible.
 546      // To be used when $url can be forged by evil user (eg it's from a $_SERVER variable, a query string, etc..)
 547      if ( 'safe' == $context ) {
 548          $strip = array( '%0d', '%0a', '%0D', '%0A' );
 549          $url = yourls_deep_replace( $strip, $url );
 550      }
 551  
 552      // Replace ampersands and single quotes only when displaying.
 553      if ( 'display' == $context ) {
 554          $url = yourls_kses_normalize_entities( $url );
 555          $url = str_replace( '&amp;', '&#038;', $url );
 556          $url = str_replace( "'", '&#039;', $url );
 557      }
 558  
 559      // If there's a protocol, make sure it's OK
 560      if( yourls_get_protocol($url) !== '' ) {
 561          if ( ! is_array( $protocols ) or ! $protocols ) {
 562              global $yourls_allowedprotocols;
 563              $protocols = yourls_apply_filter( 'esc_url_protocols', $yourls_allowedprotocols );
 564              // Note: $yourls_allowedprotocols is also globally filterable in functions-kses.php/yourls_kses_init()
 565          }
 566  
 567          if ( !yourls_is_allowed_protocol( $url, $protocols ) )
 568              return '';
 569  
 570          // I didn't use KSES function kses_bad_protocol() because it doesn't work the way I liked (returns //blah from illegal://blah)
 571      }
 572  
 573      return yourls_apply_filter( 'esc_url', $url, $original_url, $context );
 574  }
 575  
 576  
 577  /**
 578   * Normalize a URI : lowercase scheme and domain, convert IDN to UTF8
 579   *
 580   * All in one example: 'HTTP://XN--mgbuq0c.Com/AbCd' -> 'http://طارق.com/AbCd'
 581   * See issues 591, 1630, 1889, 2691
 582   *
 583   * This function is trickier than what seems to be needed at first
 584   *
 585   * First, we need to handle several URI types: http://example.com, mailto:[email protected], facetime:[email protected], and so on, see
 586   * yourls_kses_allowed_protocols() in functions-kses.php
 587   * The general rule is that the scheme ("stuff://" or "stuff:") is case insensitive and should be lowercase. But then, depending on the
 588   * scheme, parts of what follows the scheme may or may not be case sensitive.
 589   *
 590   * Second, simply using parse_url() and its opposite http_build_url() is a pretty unsafe process:
 591   *  - parse_url() can easily trip up on malformed or weird URLs
 592   *  - exploding a URL with parse_url(), lowercasing some stuff, and glueing things back with http_build_url() does not handle well
 593   *    "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
 594   *    what is supposed to be lowercased.
 595   *
 596   * So, to be conservative, this function:
 597   *  - lowercases the scheme
 598   *  - does not lowercase anything else on "stuff:" URI
 599   *  - tries to lowercase only scheme and domain of "stuff://" URI
 600   *
 601   * [1] http_build_url(parse_url("mailto:ozh")) == "mailto:///ozh"
 602   * [2] http_build_url(parse_url("http://blah#omg")) == "http://blah/#omg"
 603   * [3] http_build_url(parse_url("http://blah?#")) == "http://blah/"
 604   *
 605   * @since 1.7.1
 606   * @param string $url URL
 607   * @return string URL with lowercase scheme and protocol
 608   */
 609  function yourls_normalize_uri( $url ) {
 610      $scheme = yourls_get_protocol( $url );
 611  
 612      if ('' == $scheme) {
 613          // Scheme not found, malformed URL? Something else? Not sure.
 614          return $url;
 615      }
 616  
 617      /**
 618       * Case 1 : scheme like "stuff:", as opposed to "stuff://"
 619       * Examples: "mailto:[email protected]" or "bitcoin:15p1o8vnWqNkJBJGgwafNgR1GCCd6EGtQR?amount=1&label=Ozh"
 620       * In this case, we only lowercase the scheme, because depending on it, things after should or should not be lowercased
 621       */
 622      if (substr($scheme, -2, 2) != '//') {
 623          $url = str_replace( $scheme, strtolower( $scheme ), $url );
 624          return $url;
 625      }
 626  
 627      /**
 628       * Case 2 : scheme like "stuff://" (eg "http://example.com/" or "ssh://[email protected]")
 629       * Here we lowercase the scheme and domain parts
 630       */
 631      $parts = parse_url($url);
 632  
 633      // Most likely malformed stuff, could not parse : we'll just lowercase the scheme and leave the rest untouched
 634      if (false == $parts) {
 635          $url = str_replace( $scheme, strtolower( $scheme ), $url );
 636          return $url;
 637      }
 638  
 639      // URL seems parsable, let's do the best we can
 640      $lower = array();
 641      $lower['scheme'] = strtolower( $parts['scheme'] );
 642      if( isset( $parts['host'] ) ) {
 643          // Convert domain to lowercase, with mb_ to preserve UTF8
 644          $lower['host'] = mb_strtolower($parts['host']);
 645          /**
 646           * Convert IDN domains to their UTF8 form so that طارق.net and xn--mgbuq0c.net
 647           * are considered the same. Explicitly mention option and variant to avoid notice
 648           * on PHP 7.2 and 7.3
 649           */
 650           $lower['host'] = idn_to_utf8($lower['host'], IDNA_DEFAULT, INTL_IDNA_VARIANT_UTS46);
 651      }
 652  
 653      $url = http_build_url($url, $lower);
 654  
 655      return $url;
 656  }
 657  
 658  
 659  /**
 660   * Escape single quotes, htmlspecialchar " < > &, and fix line endings. Stolen from WP.
 661   *
 662   * Escapes text strings for echoing in JS. It is intended to be used for inline JS
 663   * (in a tag attribute, for example onclick="..."). Note that the strings have to
 664   * be in single quotes. The filter 'js_escape' is also applied here.
 665   *
 666   * @since 1.6
 667   *
 668   * @param string $text The text to be escaped.
 669   * @return string Escaped text.
 670   */
 671  function yourls_esc_js( $text ) {
 672      $safe_text = yourls_check_invalid_utf8( $text );
 673      $safe_text = yourls_specialchars( $safe_text, ENT_COMPAT );
 674      $safe_text = preg_replace( '/&#(x)?0*(?(1)27|39);?/i', "'", stripslashes( $safe_text ) );
 675      $safe_text = str_replace( "\r", '', $safe_text );
 676      $safe_text = str_replace( "\n", '\\n', addslashes( $safe_text ) );
 677      return yourls_apply_filter( 'esc_js', $safe_text, $text );
 678  }
 679  
 680  /**
 681   * Escaping for textarea values. Stolen from WP.
 682   *
 683   * @since 1.6
 684   *
 685   * @param string $text
 686   * @return string
 687   */
 688  function yourls_esc_textarea( $text ) {
 689      $safe_text = htmlspecialchars( $text, ENT_QUOTES );
 690      return yourls_apply_filter( 'esc_textarea', $safe_text, $text );
 691  }
 692  
 693  /**
 694   * Adds backslashes before letters and before a number at the start of a string. Stolen from WP.
 695   *
 696   * @since 1.6
 697   * @param string $string Value to which backslashes will be added.
 698   * @return string String with backslashes inserted.
 699   */
 700  function yourls_backslashit($string) {
 701      $string = preg_replace('/^([0-9])/', '\\\\\\\\\1', (string)$string);
 702      $string = preg_replace('/([a-z])/i', '\\\\\1', (string)$string);
 703      return $string;
 704  }
 705  
 706  /**
 707   * Check if a string seems to be urlencoded
 708   *
 709   * We use rawurlencode instead of urlencode to avoid messing with '+'
 710   *
 711   * @since 1.7
 712   * @param string $string
 713   * @return bool
 714   */
 715  function yourls_is_rawurlencoded( $string ) {
 716      return rawurldecode( $string ) != $string;
 717  }
 718  
 719  /**
 720   * rawurldecode a string till it's not encoded anymore
 721   *
 722   * Deals with multiple encoding (eg "%2521" => "%21" => "!").
 723   * See https://github.com/YOURLS/YOURLS/issues/1303
 724   *
 725   * @since 1.7
 726   * @param string $string
 727   * @return string
 728   */
 729  function yourls_rawurldecode_while_encoded( $string ) {
 730      $string = rawurldecode( $string );
 731      if( yourls_is_rawurlencoded( $string ) ) {
 732          $string = yourls_rawurldecode_while_encoded( $string );
 733      }
 734      return $string;
 735  }
 736  
 737  /**
 738   * Converts readable Javascript code into a valid bookmarklet link
 739   *
 740   * Uses https://github.com/ozh/bookmarkletgen
 741   *
 742   * @since 1.7.1
 743   * @param  string $code  Javascript code
 744   * @return string        Bookmarklet link
 745   */
 746  function yourls_make_bookmarklet( $code ) {
 747      $book = new \Ozh\Bookmarkletgen\Bookmarkletgen;
 748      return $book->crunch( $code );
 749  }
 750  
 751  /**
 752   * Return a timestamp, plus or minus the time offset if defined
 753   *
 754   * @since 1.7.10
 755   * @param  string|int $timestamp  a timestamp
 756   * @return int                    a timestamp, plus or minus offset if defined
 757   */
 758  function yourls_get_timestamp( $timestamp ) {
 759      $offset = yourls_get_time_offset();
 760      $timestamp_offset = (int)$timestamp + ($offset * 3600);
 761  
 762      return yourls_apply_filter( 'get_timestamp', $timestamp_offset, $timestamp, $offset );
 763  }
 764  
 765  /**
 766   * Get time offset, as defined in config, filtered
 767   *
 768   * @since 1.7.10
 769   * @return int       Time offset
 770   */
 771  function yourls_get_time_offset() {
 772      $offset = defined('YOURLS_HOURS_OFFSET') ? (int)YOURLS_HOURS_OFFSET : 0;
 773      return yourls_apply_filter( 'get_time_offset', $offset );
 774  }
 775  
 776  /**
 777   * Return a date() format for a full date + time, filtered
 778   *
 779   * @since 1.7.10
 780   * @param  string $format  Date format string
 781   * @return string          Date format string
 782   */
 783  function yourls_get_datetime_format( $format ) {
 784      return yourls_apply_filter( 'get_datetime_format', (string)$format );
 785  }
 786  
 787  /**
 788   * Return a date() format for date (no time), filtered
 789   *
 790   * @since 1.7.10
 791   * @param  string $format  Date format string
 792   * @return string          Date format string
 793   */
 794  function yourls_get_date_format( $format ) {
 795      return yourls_apply_filter( 'get_date_format', (string)$format );
 796  }
 797  
 798  /**
 799   * Return a date() format for a time (no date), filtered
 800   *
 801   * @since 1.7.10
 802   * @param  string $format  Date format string
 803   * @return string          Date format string
 804   */
 805  function yourls_get_time_format( $format ) {
 806      return yourls_apply_filter( 'get_time_format', (string)$format );
 807  }


Generated: Wed Oct 15 05:10:31 2025 Cross-referenced by PHPXref 0.7.1