[ Index ]

PHP Cross Reference of WordPress Trunk (Updated Daily)

Search

title

Body

[close]

/wp-includes/ -> bookmark.php (source)

   1  <?php
   2  /**
   3   * Link/Bookmark API
   4   *
   5   * @package WordPress
   6   * @subpackage Bookmark
   7   */
   8  
   9  /**
  10   * Retrieves bookmark data.
  11   *
  12   * @since 2.1.0
  13   *
  14   * @global object $link Current link object.
  15   * @global wpdb   $wpdb WordPress database abstraction object.
  16   *
  17   * @param int|stdClass $bookmark
  18   * @param string       $output   Optional. The required return type. One of OBJECT, ARRAY_A, or ARRAY_N, which
  19   *                               correspond to an stdClass object, an associative array, or a numeric array,
  20   *                               respectively. Default OBJECT.
  21   * @param string       $filter   Optional. How to sanitize bookmark fields. Default 'raw'.
  22   * @return array|object|null Type returned depends on $output value.
  23   *
  24   * @phpstan-param 'OBJECT'|'ARRAY_A'|'ARRAY_N' $output
  25   * @phpstan-return null|(
  26   *     $output is 'ARRAY_A' ? array<string, mixed> : (
  27   *         $output is 'ARRAY_N' ? array<int, mixed> : stdClass
  28   *     )
  29   * )
  30   */
  31  function get_bookmark( $bookmark, $output = OBJECT, $filter = 'raw' ) {
  32      global $wpdb;
  33  
  34      if ( empty( $bookmark ) ) {
  35          if ( isset( $GLOBALS['link'] ) ) {
  36              $_bookmark = & $GLOBALS['link'];
  37          } else {
  38              $_bookmark = null;
  39          }
  40      } elseif ( is_object( $bookmark ) ) {
  41          wp_cache_add( $bookmark->link_id, $bookmark, 'bookmark' );
  42          $_bookmark = $bookmark;
  43      } else {
  44          if ( isset( $GLOBALS['link'] ) && ( $GLOBALS['link']->link_id === $bookmark ) ) {
  45              $_bookmark = & $GLOBALS['link'];
  46          } else {
  47              $_bookmark = wp_cache_get( $bookmark, 'bookmark' );
  48              if ( ! $_bookmark ) {
  49                  $_bookmark = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM $wpdb->links WHERE link_id = %d LIMIT 1", $bookmark ) );
  50                  if ( $_bookmark ) {
  51                      $_bookmark->link_category = array_unique( wp_get_object_terms( $_bookmark->link_id, 'link_category', array( 'fields' => 'ids' ) ) );
  52                      wp_cache_add( $_bookmark->link_id, $_bookmark, 'bookmark' );
  53                  }
  54              }
  55          }
  56      }
  57  
  58      if ( ! $_bookmark ) {
  59          return $_bookmark;
  60      }
  61  
  62      $_bookmark = sanitize_bookmark( $_bookmark, $filter );
  63  
  64      if ( OBJECT === $output ) {
  65          return $_bookmark;
  66      } elseif ( ARRAY_A === $output ) {
  67          return get_object_vars( $_bookmark );
  68      } elseif ( ARRAY_N === $output ) {
  69          return array_values( get_object_vars( $_bookmark ) );
  70      } else {
  71          return $_bookmark;
  72      }
  73  }
  74  
  75  /**
  76   * Retrieves single bookmark data item or field.
  77   *
  78   * @since 2.3.0
  79   *
  80   * @param string $field    The name of the data field to return.
  81   * @param int    $bookmark The bookmark ID to get field.
  82   * @param string $context  Optional. The context of how the field will be used. Default 'display'.
  83   * @return string|WP_Error
  84   */
  85  function get_bookmark_field( $field, $bookmark, $context = 'display' ) {
  86      $bookmark = (int) $bookmark;
  87      $bookmark = get_bookmark( $bookmark );
  88  
  89      if ( is_wp_error( $bookmark ) ) {
  90          return $bookmark;
  91      }
  92  
  93      if ( ! is_object( $bookmark ) ) {
  94          return '';
  95      }
  96  
  97      if ( ! isset( $bookmark->$field ) ) {
  98          return '';
  99      }
 100  
 101      return sanitize_bookmark_field( $field, $bookmark->$field, $bookmark->link_id, $context );
 102  }
 103  
 104  /**
 105   * Retrieves the list of bookmarks.
 106   *
 107   * Attempts to retrieve from the cache first based on MD5 hash of arguments. If
 108   * that fails, then the query will be built from the arguments and executed. The
 109   * results will be stored to the cache.
 110   *
 111   * @since 2.1.0
 112   *
 113   * @global wpdb $wpdb WordPress database abstraction object.
 114   *
 115   * @param string|array $args {
 116   *     Optional. String or array of arguments to retrieve bookmarks.
 117   *
 118   *     @type string     $orderby        How to order the links by. Accepts 'id', 'link_id', 'name', 'link_name',
 119   *                                      'url', 'link_url', 'visible', 'link_visible', 'rating', 'link_rating',
 120   *                                      'owner', 'link_owner', 'updated', 'link_updated', 'notes', 'link_notes',
 121   *                                      'description', 'link_description', 'length' and 'rand'.
 122   *                                      When `$orderby` is 'length', orders by the character length of
 123   *                                      'link_name'. Default 'name'.
 124   *     @type string     $order          Whether to order bookmarks in ascending or descending order.
 125   *                                      Accepts 'ASC' (ascending) or 'DESC' (descending). Default 'ASC'.
 126   *     @type int        $limit          Amount of bookmarks to display. Accepts any positive number or
 127   *                                      -1 for all.  Default -1.
 128   *     @type int|string $category       A category ID, or a comma-separated list of category IDs to include
 129   *                                      links from. Ignored if `$category_name` is passed. Default empty.
 130   *     @type string     $category_name  Category to retrieve links for by name. Takes precedence over
 131   *                                      `$category`. Default empty.
 132   *     @type int|bool   $hide_invisible Whether to show or hide links marked as 'invisible'. Accepts
 133   *                                      1|true or 0|false. Default 1|true.
 134   *     @type int|bool   $show_updated   Whether to display the time the bookmark was last updated.
 135   *                                      Accepts 1|true or 0|false. Default 0|false.
 136   *     @type string     $include        Comma-separated list of bookmark IDs to include. Default empty.
 137   *     @type string     $exclude        Comma-separated list of bookmark IDs to exclude. Default empty.
 138   *     @type string     $search         Search terms. Will be SQL-formatted with wildcards before and after
 139   *                                      and searched in 'link_url', 'link_name' and 'link_description'.
 140   *                                      Default empty.
 141   * }
 142   * @return object[] List of bookmark row objects.
 143   */
 144  function get_bookmarks( $args = '' ) {
 145      global $wpdb;
 146  
 147      $defaults = array(
 148          'orderby'        => 'name',
 149          'order'          => 'ASC',
 150          'limit'          => -1,
 151          'category'       => '',
 152          'category_name'  => '',
 153          'hide_invisible' => 1,
 154          'show_updated'   => 0,
 155          'include'        => '',
 156          'exclude'        => '',
 157          'search'         => '',
 158      );
 159  
 160      $parsed_args = wp_parse_args( $args, $defaults );
 161  
 162      $key   = md5( serialize( $parsed_args ) );
 163      $cache = wp_cache_get( 'get_bookmarks', 'bookmark' );
 164  
 165      if ( 'rand' !== $parsed_args['orderby'] && $cache ) {
 166          if ( is_array( $cache ) && isset( $cache[ $key ] ) ) {
 167              $bookmarks = $cache[ $key ];
 168              /**
 169               * Filters the returned list of bookmarks.
 170               *
 171               * The first time the hook is evaluated in this file, it returns the cached
 172               * bookmarks list. The second evaluation returns a cached bookmarks list if the
 173               * link category is passed but does not exist. The third evaluation returns
 174               * the full cached results.
 175               *
 176               * @since 2.1.0
 177               *
 178               * @see get_bookmarks()
 179               *
 180               * @param array $bookmarks   List of the cached bookmarks.
 181               * @param array $parsed_args An array of bookmark query arguments.
 182               */
 183              return apply_filters( 'get_bookmarks', $bookmarks, $parsed_args );
 184          }
 185      }
 186  
 187      if ( ! is_array( $cache ) ) {
 188          $cache = array();
 189      }
 190  
 191      $inclusions = '';
 192      if ( ! empty( $parsed_args['include'] ) ) {
 193          $parsed_args['exclude']       = '';  // Ignore exclude, category, and category_name params if using include.
 194          $parsed_args['category']      = '';
 195          $parsed_args['category_name'] = '';
 196  
 197          $inclinks = wp_parse_id_list( $parsed_args['include'] );
 198          if ( count( $inclinks ) ) {
 199              foreach ( $inclinks as $inclink ) {
 200                  if ( empty( $inclusions ) ) {
 201                      $inclusions = ' AND ( link_id = ' . $inclink . ' ';
 202                  } else {
 203                      $inclusions .= ' OR link_id = ' . $inclink . ' ';
 204                  }
 205              }
 206          }
 207      }
 208      if ( ! empty( $inclusions ) ) {
 209          $inclusions .= ')';
 210      }
 211  
 212      $exclusions = '';
 213      if ( ! empty( $parsed_args['exclude'] ) ) {
 214          $exlinks = wp_parse_id_list( $parsed_args['exclude'] );
 215          if ( count( $exlinks ) ) {
 216              foreach ( $exlinks as $exlink ) {
 217                  if ( empty( $exclusions ) ) {
 218                      $exclusions = ' AND ( link_id <> ' . $exlink . ' ';
 219                  } else {
 220                      $exclusions .= ' AND link_id <> ' . $exlink . ' ';
 221                  }
 222              }
 223          }
 224      }
 225      if ( ! empty( $exclusions ) ) {
 226          $exclusions .= ')';
 227      }
 228  
 229      if ( ! empty( $parsed_args['category_name'] ) ) {
 230          $parsed_args['category'] = get_term_by( 'name', $parsed_args['category_name'], 'link_category' );
 231          if ( $parsed_args['category'] ) {
 232              $parsed_args['category'] = $parsed_args['category']->term_id;
 233          } else {
 234              $cache[ $key ] = array();
 235              wp_cache_set( 'get_bookmarks', $cache, 'bookmark' );
 236              /** This filter is documented in wp-includes/bookmark.php */
 237              return apply_filters( 'get_bookmarks', array(), $parsed_args );
 238          }
 239      }
 240  
 241      $search = '';
 242      if ( ! empty( $parsed_args['search'] ) ) {
 243          $like   = '%' . $wpdb->esc_like( $parsed_args['search'] ) . '%';
 244          $search = $wpdb->prepare( ' AND ( (link_url LIKE %s) OR (link_name LIKE %s) OR (link_description LIKE %s) ) ', $like, $like, $like );
 245      }
 246  
 247      $category_query = '';
 248      $join           = '';
 249      if ( ! empty( $parsed_args['category'] ) ) {
 250          $incategories = wp_parse_id_list( $parsed_args['category'] );
 251          if ( count( $incategories ) ) {
 252              foreach ( $incategories as $incat ) {
 253                  if ( empty( $category_query ) ) {
 254                      $category_query = ' AND ( tt.term_id = ' . $incat . ' ';
 255                  } else {
 256                      $category_query .= ' OR tt.term_id = ' . $incat . ' ';
 257                  }
 258              }
 259          }
 260      }
 261      if ( ! empty( $category_query ) ) {
 262          $category_query .= ") AND taxonomy = 'link_category'";
 263          $join            = " INNER JOIN $wpdb->term_relationships AS tr ON ($wpdb->links.link_id = tr.object_id) INNER JOIN $wpdb->term_taxonomy as tt ON tt.term_taxonomy_id = tr.term_taxonomy_id";
 264      }
 265  
 266      if ( $parsed_args['show_updated'] ) {
 267          $recently_updated_test = ', IF (DATE_ADD(link_updated, INTERVAL 120 MINUTE) >= NOW(), 1,0) as recently_updated ';
 268      } else {
 269          $recently_updated_test = '';
 270      }
 271  
 272      $get_updated = ( $parsed_args['show_updated'] ) ? ', UNIX_TIMESTAMP(link_updated) AS link_updated_f ' : '';
 273  
 274      $orderby = strtolower( $parsed_args['orderby'] );
 275      $length  = '';
 276      switch ( $orderby ) {
 277          case 'length':
 278              $length = ', CHAR_LENGTH(link_name) AS length';
 279              break;
 280          case 'rand':
 281              $orderby = 'rand()';
 282              break;
 283          case 'link_id':
 284              $orderby = "$wpdb->links.link_id";
 285              break;
 286          default:
 287              $orderparams = array();
 288              $keys        = array( 'link_id', 'link_name', 'link_url', 'link_visible', 'link_rating', 'link_owner', 'link_updated', 'link_notes', 'link_description' );
 289              foreach ( explode( ',', $orderby ) as $ordparam ) {
 290                  $ordparam = trim( $ordparam );
 291  
 292                  if ( in_array( 'link_' . $ordparam, $keys, true ) ) {
 293                      $orderparams[] = 'link_' . $ordparam;
 294                  } elseif ( in_array( $ordparam, $keys, true ) ) {
 295                      $orderparams[] = $ordparam;
 296                  }
 297              }
 298              $orderby = implode( ',', $orderparams );
 299      }
 300  
 301      if ( empty( $orderby ) ) {
 302          $orderby = 'link_name';
 303      }
 304  
 305      $order = strtoupper( $parsed_args['order'] );
 306      if ( '' !== $order && ! in_array( $order, array( 'ASC', 'DESC' ), true ) ) {
 307          $order = 'ASC';
 308      }
 309  
 310      $visible = '';
 311      if ( $parsed_args['hide_invisible'] ) {
 312          $visible = "AND link_visible = 'Y'";
 313      }
 314  
 315      $query  = "SELECT * $length $recently_updated_test $get_updated FROM $wpdb->links $join WHERE 1=1 $visible $category_query";
 316      $query .= " $exclusions $inclusions $search";
 317      $query .= " ORDER BY $orderby $order";
 318      if ( -1 !== $parsed_args['limit'] ) {
 319          $query .= ' LIMIT ' . absint( $parsed_args['limit'] );
 320      }
 321  
 322      $results = $wpdb->get_results( $query );
 323  
 324      if ( 'rand()' !== $orderby ) {
 325          $cache[ $key ] = $results;
 326          wp_cache_set( 'get_bookmarks', $cache, 'bookmark' );
 327      }
 328  
 329      /** This filter is documented in wp-includes/bookmark.php */
 330      return apply_filters( 'get_bookmarks', $results, $parsed_args );
 331  }
 332  
 333  /**
 334   * Sanitizes all bookmark fields.
 335   *
 336   * @since 2.3.0
 337   *
 338   * @param stdClass|array $bookmark Bookmark row.
 339   * @param string         $context  Optional. How to filter the fields. Default 'display'.
 340   * @return stdClass|array Same type as $bookmark but with fields sanitized.
 341   */
 342  function sanitize_bookmark( $bookmark, $context = 'display' ) {
 343      $fields = array(
 344          'link_id',
 345          'link_url',
 346          'link_name',
 347          'link_image',
 348          'link_target',
 349          'link_category',
 350          'link_description',
 351          'link_visible',
 352          'link_owner',
 353          'link_rating',
 354          'link_updated',
 355          'link_rel',
 356          'link_notes',
 357          'link_rss',
 358      );
 359  
 360      if ( is_object( $bookmark ) ) {
 361          $do_object = true;
 362          $link_id   = $bookmark->link_id;
 363      } else {
 364          $do_object = false;
 365          $link_id   = $bookmark['link_id'];
 366      }
 367  
 368      foreach ( $fields as $field ) {
 369          if ( $do_object ) {
 370              if ( isset( $bookmark->$field ) ) {
 371                  $bookmark->$field = sanitize_bookmark_field( $field, $bookmark->$field, $link_id, $context );
 372              }
 373          } else {
 374              if ( isset( $bookmark[ $field ] ) ) {
 375                  $bookmark[ $field ] = sanitize_bookmark_field( $field, $bookmark[ $field ], $link_id, $context );
 376              }
 377          }
 378      }
 379  
 380      return $bookmark;
 381  }
 382  
 383  /**
 384   * Sanitizes a bookmark field.
 385   *
 386   * Sanitizes the bookmark fields based on what the field name is. If the field
 387   * has a strict value set, then it will be tested for that, else a more generic
 388   * filtering is applied. After the more strict filter is applied, if the `$context`
 389   * is 'raw' then the value is immediately return.
 390   *
 391   * Hooks exist for the more generic cases. With the 'edit' context, the {@see 'edit_$field'}
 392   * filter will be called and passed the `$value` and `$bookmark_id` respectively.
 393   *
 394   * With the 'db' context, the {@see 'pre_$field'} filter is called and passed the value.
 395   * The 'display' context is the final context and has the `$field` has the filter name
 396   * and is passed the `$value`, `$bookmark_id`, and `$context`, respectively.
 397   *
 398   * @since 2.3.0
 399   *
 400   * @param string $field       The bookmark field.
 401   * @param mixed  $value       The bookmark field value.
 402   * @param int    $bookmark_id Bookmark ID.
 403   * @param string $context     How to filter the field value. Accepts 'raw', 'edit', 'db',
 404   *                            'display', 'attribute', or 'js'. Default 'display'.
 405   * @return mixed The filtered value.
 406   */
 407  function sanitize_bookmark_field( $field, $value, $bookmark_id, $context ) {
 408      $int_fields = array( 'link_id', 'link_rating' );
 409      if ( in_array( $field, $int_fields, true ) ) {
 410          $value = (int) $value;
 411      }
 412  
 413      switch ( $field ) {
 414          case 'link_category': // array( ints )
 415              $value = array_map( 'absint', (array) $value );
 416              /*
 417               * We return here so that the categories aren't filtered.
 418               * The 'link_category' filter is for the name of a link category, not an array of a link's link categories.
 419               */
 420              return $value;
 421  
 422          case 'link_visible': // bool stored as Y|N
 423              $value = preg_replace( '/[^YNyn]/', '', $value );
 424              break;
 425          case 'link_target': // "enum"
 426              $targets = array( '_top', '_blank' );
 427              if ( ! in_array( $value, $targets, true ) ) {
 428                  $value = '';
 429              }
 430              break;
 431      }
 432  
 433      if ( 'raw' === $context ) {
 434          return $value;
 435      }
 436  
 437      if ( 'edit' === $context ) {
 438          /** This filter is documented in wp-includes/post.php */
 439          $value = apply_filters( "edit_{$field}", $value, $bookmark_id );
 440  
 441          if ( 'link_notes' === $field ) {
 442              $value = esc_html( $value ); // textarea_escaped
 443          } else {
 444              $value = esc_attr( $value );
 445          }
 446      } elseif ( 'db' === $context ) {
 447          /** This filter is documented in wp-includes/post.php */
 448          $value = apply_filters( "pre_{$field}", $value );
 449      } else {
 450          /** This filter is documented in wp-includes/post.php */
 451          $value = apply_filters( "{$field}", $value, $bookmark_id, $context );
 452  
 453          if ( 'attribute' === $context ) {
 454              $value = esc_attr( $value );
 455          } elseif ( 'js' === $context ) {
 456              $value = esc_js( $value );
 457          }
 458      }
 459  
 460      // Restore the type for integer fields after esc_attr().
 461      if ( in_array( $field, $int_fields, true ) ) {
 462          $value = (int) $value;
 463      }
 464  
 465      return $value;
 466  }
 467  
 468  /**
 469   * Deletes the bookmark cache.
 470   *
 471   * @since 2.7.0
 472   *
 473   * @param int $bookmark_id Bookmark ID.
 474   */
 475  function clean_bookmark_cache( $bookmark_id ) {
 476      wp_cache_delete( $bookmark_id, 'bookmark' );
 477      wp_cache_delete( 'get_bookmarks', 'bookmark' );
 478      clean_object_term_cache( $bookmark_id, 'link' );
 479  }


Generated : Fri Oct 9 08:20:33 2026 Cross-referenced by PHPXref