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


Generated: Sat Aug 8 05:10:51 2026 Cross-referenced by PHPXref 0.7.1