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


Generated: Wed Sep 28 05:10:02 2022 Cross-referenced by PHPXref 0.7.1