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


Generated : Wed Sep 9 08:20:27 2026 Cross-referenced by PHPXref