class-wpseo-meta.php 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997
  1. <?php
  2. /**
  3. * WPSEO plugin file.
  4. *
  5. * @package WPSEO\Internals
  6. * @since 1.5.0
  7. */
  8. /**
  9. * This class implements defaults and value validation for all WPSEO Post Meta values.
  10. *
  11. * Some guidelines:
  12. * - To update a meta value, you can just use update_post_meta() with the full (prefixed) meta key
  13. * or the convenience method WPSEO_Meta::set_value() with the internal key.
  14. * All updates will be automatically validated.
  15. * Meta values will only be saved to the database if they are *not* the same as the default to
  16. * keep database load low.
  17. * - To retrieve a WPSEO meta value, you **must** use WPSEO_Meta::get_value() which will always return a
  18. * string value, either the saved value or the default.
  19. * This method can also retrieve a complete set of WPSEO meta values for one specific post, see
  20. * the method documentation for the parameters.
  21. *
  22. * {@internal Unfortunately there isn't a filter available to hook into before returning the results
  23. * for get_post_meta(), get_post_custom() and the likes. That would have been the
  24. * preferred solution.}}
  25. *
  26. * {@internal All WP native get_meta() results get cached internally, so no need to cache locally.}}
  27. * {@internal Use $key when the key is the WPSEO internal name (without prefix), $meta_key when it
  28. * includes the prefix.}}
  29. */
  30. class WPSEO_Meta {
  31. /**
  32. * Prefix for all WPSEO meta values in the database.
  33. *
  34. * {@internal If at any point this would change, quite apart from an upgrade routine,
  35. * this also will need to be changed in the wpml-config.xml file.}}
  36. *
  37. * @var string
  38. */
  39. public static $meta_prefix = '_yoast_wpseo_';
  40. /**
  41. * Prefix for all WPSEO meta value form field names and ids.
  42. *
  43. * @var string
  44. */
  45. public static $form_prefix = 'yoast_wpseo_';
  46. /**
  47. * Allowed length of the meta description.
  48. *
  49. * @var int
  50. */
  51. public static $meta_length = 156;
  52. /**
  53. * Reason the meta description is not the default length.
  54. *
  55. * @var string
  56. */
  57. public static $meta_length_reason = '';
  58. /**
  59. * Meta box field definitions for the meta box form.
  60. *
  61. * {@internal
  62. * - Titles, help texts, description text and option labels are added via a translate_meta_boxes() method
  63. * in the relevant child classes (WPSEO_Metabox and WPSEO_Social_admin) as they are only needed there.
  64. * - Beware: even though the meta keys are divided into subsets, they still have to be uniquely named!}}
  65. *
  66. * @var array $meta_fields
  67. * Array format:
  68. * (required) 'type' => (string) field type. i.e. text / textarea / checkbox /
  69. * radio / select / multiselect / upload etc.
  70. * (required) 'title' => (string) table row title.
  71. * (recommended) 'default_value' => (string|array) default value for the field.
  72. * IMPORTANT:
  73. * - if the field has options, the default has to be the
  74. * key of one of the options.
  75. * - if the field is a text field, the default **has** to be
  76. * an empty string as otherwise the user can't save
  77. * an empty value/delete the meta value.
  78. * - if the field is a checkbox, the only valid values
  79. * are 'on' or 'off'.
  80. * (semi-required) 'options' => (array) options for used with (multi-)select and radio
  81. * fields, required if that's the field type.
  82. * key = (string) value which will be saved to db.
  83. * value = (string) text label for the option.
  84. * (optional) 'autocomplete' => (bool) whether autocomplete is on for text fields,
  85. * defaults to true.
  86. * (optional) 'class' => (string) classname(s) to add to the actual <input> tag.
  87. * (optional) 'description' => (string) description to show underneath the field.
  88. * (optional) 'expl' => (string) label for a checkbox.
  89. * (optional) 'help' => (string) help text to show on mouse over ? image.
  90. * (optional) 'rows' => (int) number of rows for a textarea, defaults to 3.
  91. * (optional) 'placeholder' => (string) Currently only used by add-on plugins.
  92. * (optional) 'serialized' => (bool) whether the value is expected to be serialized,
  93. * i.e. an array or object, defaults to false.
  94. * Currently only used by add-on plugins.
  95. */
  96. public static $meta_fields = [
  97. 'general' => [
  98. 'focuskw' => [
  99. 'type' => 'hidden',
  100. 'title' => '',
  101. ],
  102. 'title' => [
  103. 'type' => 'hidden',
  104. 'title' => '', // Translation added later.
  105. 'default_value' => '',
  106. 'description' => '', // Translation added later.
  107. 'help' => '', // Translation added later.
  108. ],
  109. 'metadesc' => [
  110. 'type' => 'hidden',
  111. 'title' => '', // Translation added later.
  112. 'default_value' => '',
  113. 'class' => 'metadesc',
  114. 'rows' => 2,
  115. 'description' => '', // Translation added later.
  116. 'help' => '', // Translation added later.
  117. ],
  118. 'linkdex' => [
  119. 'type' => 'hidden',
  120. 'title' => 'linkdex',
  121. 'default_value' => '0',
  122. 'description' => '',
  123. ],
  124. 'content_score' => [
  125. 'type' => 'hidden',
  126. 'title' => 'content_score',
  127. 'default_value' => '0',
  128. 'description' => '',
  129. ],
  130. 'is_cornerstone' => [
  131. 'type' => 'hidden',
  132. 'title' => 'is_cornerstone',
  133. 'default_value' => 'false',
  134. 'description' => '',
  135. ],
  136. ],
  137. 'advanced' => [
  138. 'meta-robots-noindex' => [
  139. 'type' => 'select',
  140. 'title' => '', // Translation added later.
  141. 'default_value' => '0', // = post-type default.
  142. 'options' => [
  143. '0' => '', // Post type default - translation added later.
  144. '2' => '', // Index - translation added later.
  145. '1' => '', // No-index - translation added later.
  146. ],
  147. ],
  148. 'meta-robots-nofollow' => [
  149. 'type' => 'radio',
  150. 'title' => '', // Translation added later.
  151. 'default_value' => '0', // = follow.
  152. 'options' => [
  153. '0' => '', // Follow - translation added later.
  154. '1' => '', // No-follow - translation added later.
  155. ],
  156. ],
  157. 'meta-robots-adv' => [
  158. 'type' => 'multiselect',
  159. 'title' => '', // Translation added later.
  160. 'default_value' => '',
  161. 'description' => '', // Translation added later.
  162. 'options' => [
  163. 'noimageindex' => '', // Translation added later.
  164. 'noarchive' => '', // Translation added later.
  165. 'nosnippet' => '', // Translation added later.
  166. ],
  167. ],
  168. 'bctitle' => [
  169. 'type' => 'text',
  170. 'title' => '', // Translation added later.
  171. 'default_value' => '',
  172. 'description' => '', // Translation added later.
  173. ],
  174. 'canonical' => [
  175. 'type' => 'text',
  176. 'title' => '', // Translation added later.
  177. 'default_value' => '',
  178. 'description' => '', // Translation added later.
  179. ],
  180. 'redirect' => [
  181. 'type' => 'text',
  182. 'title' => '', // Translation added later.
  183. 'default_value' => '',
  184. 'description' => '', // Translation added later.
  185. ],
  186. ],
  187. 'social' => [],
  188. /* Fields we should validate & save, but not show on any form. */
  189. 'non_form' => [
  190. 'linkdex' => [
  191. 'type' => null,
  192. 'default_value' => '0',
  193. ],
  194. ],
  195. ];
  196. /**
  197. * Helper property - reverse index of the definition array.
  198. *
  199. * Format: [full meta key including prefix] => array
  200. * ['subset'] => (string) primary index
  201. * ['key'] => (string) internal key
  202. *
  203. * @var array
  204. */
  205. public static $fields_index = [];
  206. /**
  207. * Helper property - array containing only the defaults in the format:
  208. * [full meta key including prefix] => (string) default value
  209. *
  210. * @var array
  211. */
  212. public static $defaults = [];
  213. /**
  214. * Helper property to define the social network meta field definitions - networks.
  215. *
  216. * @var array
  217. */
  218. private static $social_networks = [
  219. 'opengraph' => 'opengraph',
  220. 'twitter' => 'twitter',
  221. ];
  222. /**
  223. * Helper property to define the social network meta field definitions - fields and their type.
  224. *
  225. * @var array
  226. */
  227. private static $social_fields = [
  228. 'title' => 'text',
  229. 'description' => 'textarea',
  230. 'image' => 'upload',
  231. 'image-id' => 'hidden',
  232. ];
  233. /**
  234. * Register our actions and filters.
  235. *
  236. * @return void
  237. */
  238. public static function init() {
  239. foreach ( self::$social_networks as $option => $network ) {
  240. if ( true === WPSEO_Options::get( $option, false ) ) {
  241. foreach ( self::$social_fields as $box => $type ) {
  242. self::$meta_fields['social'][ $network . '-' . $box ] = [
  243. 'type' => $type,
  244. 'title' => '', // Translation added later.
  245. 'default_value' => '',
  246. 'description' => '', // Translation added later.
  247. ];
  248. }
  249. }
  250. }
  251. unset( $option, $network, $box, $type );
  252. /**
  253. * Allow add-on plugins to register their meta fields for management by this class.
  254. * Calls to add_filter() must be made before plugins_loaded prio 14.
  255. */
  256. $extra_fields = apply_filters( 'add_extra_wpseo_meta_fields', [] );
  257. if ( is_array( $extra_fields ) ) {
  258. self::$meta_fields = self::array_merge_recursive_distinct( $extra_fields, self::$meta_fields );
  259. }
  260. unset( $extra_fields );
  261. foreach ( self::$meta_fields as $subset => $field_group ) {
  262. foreach ( $field_group as $key => $field_def ) {
  263. register_meta(
  264. 'post',
  265. self::$meta_prefix . $key,
  266. [ 'sanitize_callback' => [ __CLASS__, 'sanitize_post_meta' ] ]
  267. );
  268. // Set the $fields_index property for efficiency.
  269. self::$fields_index[ self::$meta_prefix . $key ] = [
  270. 'subset' => $subset,
  271. 'key' => $key,
  272. ];
  273. // Set the $defaults property for efficiency.
  274. if ( isset( $field_def['default_value'] ) ) {
  275. self::$defaults[ self::$meta_prefix . $key ] = $field_def['default_value'];
  276. }
  277. else {
  278. // Meta will always be a string, so let's make the meta meta default also a string.
  279. self::$defaults[ self::$meta_prefix . $key ] = '';
  280. }
  281. }
  282. }
  283. unset( $subset, $field_group, $key, $field_def );
  284. add_filter( 'update_post_metadata', [ __CLASS__, 'remove_meta_if_default' ], 10, 5 );
  285. add_filter( 'add_post_metadata', [ __CLASS__, 'dont_save_meta_if_default' ], 10, 4 );
  286. }
  287. /**
  288. * Retrieve the meta box form field definitions for the given tab and post type.
  289. *
  290. * @param string $tab Tab for which to retrieve the field definitions.
  291. * @param string $post_type Post type of the current post.
  292. *
  293. * @return array Array containing the meta box field definitions.
  294. */
  295. public static function get_meta_field_defs( $tab, $post_type = 'post' ) {
  296. if ( ! isset( self::$meta_fields[ $tab ] ) ) {
  297. return [];
  298. }
  299. $field_defs = self::$meta_fields[ $tab ];
  300. switch ( $tab ) {
  301. case 'non-form':
  302. // Prevent non-form fields from being passed to forms.
  303. $field_defs = [];
  304. break;
  305. case 'advanced':
  306. global $post;
  307. if ( ! WPSEO_Capability_Utils::current_user_can( 'wpseo_edit_advanced_metadata' ) && WPSEO_Options::get( 'disableadvanced_meta' ) ) {
  308. return [];
  309. }
  310. $post_type = '';
  311. if ( isset( $post->post_type ) ) {
  312. $post_type = $post->post_type;
  313. }
  314. elseif ( ! isset( $post->post_type ) && isset( $_GET['post_type'] ) ) {
  315. $post_type = sanitize_text_field( $_GET['post_type'] );
  316. }
  317. if ( $post_type === '' ) {
  318. return [];
  319. }
  320. /* Adjust the no-index text strings based on the post type. */
  321. $post_type_object = get_post_type_object( $post_type );
  322. $field_defs['meta-robots-noindex']['title'] = sprintf( $field_defs['meta-robots-noindex']['title'], $post_type_object->labels->singular_name );
  323. $field_defs['meta-robots-noindex']['options']['0'] = sprintf( $field_defs['meta-robots-noindex']['options']['0'], ( ( WPSEO_Options::get( 'noindex-' . $post_type, false ) === true ) ? $field_defs['meta-robots-noindex']['options']['1'] : $field_defs['meta-robots-noindex']['options']['2'] ), $post_type_object->label );
  324. $field_defs['meta-robots-nofollow']['title'] = sprintf( $field_defs['meta-robots-nofollow']['title'], $post_type_object->labels->singular_name );
  325. /* Don't show the breadcrumb title field if breadcrumbs aren't enabled. */
  326. if ( WPSEO_Options::get( 'breadcrumbs-enable', false ) !== true && ! current_theme_supports( 'yoast-seo-breadcrumbs' ) ) {
  327. unset( $field_defs['bctitle'] );
  328. }
  329. global $post;
  330. if ( empty( $post->ID ) || ( ! empty( $post->ID ) && self::get_value( 'redirect', $post->ID ) === '' ) ) {
  331. unset( $field_defs['redirect'] );
  332. }
  333. break;
  334. }
  335. /**
  336. * Filter the WPSEO metabox form field definitions for a tab.
  337. * {tab} can be 'general', 'advanced' or 'social'.
  338. *
  339. * @param array $field_defs Metabox form field definitions.
  340. * @param string $post_type Post type of the post the metabox is for, defaults to 'post'.
  341. *
  342. * @return array
  343. */
  344. return apply_filters( 'wpseo_metabox_entries_' . $tab, $field_defs, $post_type );
  345. }
  346. /**
  347. * Validate the post meta values.
  348. *
  349. * @param mixed $meta_value The new value.
  350. * @param string $meta_key The full meta key (including prefix).
  351. *
  352. * @return string Validated meta value.
  353. */
  354. public static function sanitize_post_meta( $meta_value, $meta_key ) {
  355. $field_def = self::$meta_fields[ self::$fields_index[ $meta_key ]['subset'] ][ self::$fields_index[ $meta_key ]['key'] ];
  356. $clean = self::$defaults[ $meta_key ];
  357. switch ( true ) {
  358. case ( $meta_key === self::$meta_prefix . 'linkdex' ):
  359. $int = WPSEO_Utils::validate_int( $meta_value );
  360. if ( $int !== false && $int >= 0 ) {
  361. $clean = strval( $int ); // Convert to string to make sure default check works.
  362. }
  363. break;
  364. case ( $field_def['type'] === 'checkbox' ):
  365. // Only allow value if it's one of the predefined options.
  366. if ( in_array( $meta_value, [ 'on', 'off' ], true ) ) {
  367. $clean = $meta_value;
  368. }
  369. break;
  370. case ( $field_def['type'] === 'select' || $field_def['type'] === 'radio' ):
  371. // Only allow value if it's one of the predefined options.
  372. if ( isset( $field_def['options'][ $meta_value ] ) ) {
  373. $clean = $meta_value;
  374. }
  375. break;
  376. case ( $field_def['type'] === 'multiselect' && $meta_key === self::$meta_prefix . 'meta-robots-adv' ):
  377. $clean = self::validate_meta_robots_adv( $meta_value );
  378. break;
  379. case ( $field_def['type'] === 'text' && $meta_key === self::$meta_prefix . 'canonical' ):
  380. case ( $field_def['type'] === 'text' && $meta_key === self::$meta_prefix . 'redirect' ):
  381. // Validate as url(-part).
  382. $url = WPSEO_Utils::sanitize_url( $meta_value );
  383. if ( $url !== '' ) {
  384. $clean = $url;
  385. }
  386. break;
  387. case ( $field_def['type'] === 'upload' && in_array( $meta_key, [ self::$meta_prefix . 'opengraph-image', self::$meta_prefix . 'twitter-image' ], true ) ):
  388. // Validate as url.
  389. $url = WPSEO_Utils::sanitize_url( $meta_value, [ 'http', 'https', 'ftp', 'ftps' ] );
  390. if ( $url !== '' ) {
  391. $clean = $url;
  392. }
  393. break;
  394. case ( $field_def['type'] === 'hidden' && $meta_key === self::$meta_prefix . 'is_cornerstone' ):
  395. $clean = $meta_value;
  396. /*
  397. * This used to be a checkbox, then became a hidden input.
  398. * To make sure the value remains consistent, we cast 'true' to '1'.
  399. */
  400. if ( $meta_value === 'true' ) {
  401. $clean = '1';
  402. }
  403. break;
  404. case ( $field_def['type'] === 'textarea' ):
  405. if ( is_string( $meta_value ) ) {
  406. // Remove line breaks and tabs.
  407. // @todo [JRF => Yoast] Verify that line breaks and the likes aren't allowed/recommended in meta header fields.
  408. $meta_value = str_replace( [ "\n", "\r", "\t", ' ' ], ' ', $meta_value );
  409. $clean = WPSEO_Utils::sanitize_text_field( trim( $meta_value ) );
  410. }
  411. break;
  412. case ( 'multiselect' === $field_def['type'] ):
  413. $clean = $meta_value;
  414. break;
  415. case ( $field_def['type'] === 'text' ):
  416. default:
  417. if ( is_string( $meta_value ) ) {
  418. $clean = WPSEO_Utils::sanitize_text_field( trim( $meta_value ) );
  419. }
  420. break;
  421. }
  422. $clean = apply_filters( 'wpseo_sanitize_post_meta_' . $meta_key, $clean, $meta_value, $field_def, $meta_key );
  423. return $clean;
  424. }
  425. /**
  426. * Validate a meta-robots-adv meta value.
  427. *
  428. * @todo [JRF => Yoast] Verify that this logic for the prioritisation is correct.
  429. *
  430. * @param array|string $meta_value The value to validate.
  431. *
  432. * @return string Clean value.
  433. */
  434. public static function validate_meta_robots_adv( $meta_value ) {
  435. $clean = self::$meta_fields['advanced']['meta-robots-adv']['default_value'];
  436. $options = self::$meta_fields['advanced']['meta-robots-adv']['options'];
  437. if ( is_string( $meta_value ) ) {
  438. $meta_value = explode( ',', $meta_value );
  439. }
  440. if ( is_array( $meta_value ) && $meta_value !== [] ) {
  441. $meta_value = array_map( 'trim', $meta_value );
  442. // Individual selected entries.
  443. $cleaning = [];
  444. foreach ( $meta_value as $value ) {
  445. if ( isset( $options[ $value ] ) ) {
  446. $cleaning[] = $value;
  447. }
  448. }
  449. if ( $cleaning !== [] ) {
  450. $clean = implode( ',', $cleaning );
  451. }
  452. unset( $cleaning, $value );
  453. }
  454. return $clean;
  455. }
  456. /**
  457. * Prevent saving of default values and remove potential old value from the database if replaced by a default.
  458. *
  459. * @param bool $check The current status to allow updating metadata for the given type.
  460. * @param int $object_id ID of the current object for which the meta is being updated.
  461. * @param string $meta_key The full meta key (including prefix).
  462. * @param string $meta_value New meta value.
  463. * @param string $prev_value The old meta value.
  464. *
  465. * @return null|bool True = stop saving, null = continue saving.
  466. */
  467. public static function remove_meta_if_default( $check, $object_id, $meta_key, $meta_value, $prev_value = '' ) {
  468. /* If it's one of our meta fields, check against default. */
  469. if ( isset( self::$fields_index[ $meta_key ] ) && self::meta_value_is_default( $meta_key, $meta_value ) === true ) {
  470. if ( $prev_value !== '' ) {
  471. delete_post_meta( $object_id, $meta_key, $prev_value );
  472. }
  473. else {
  474. delete_post_meta( $object_id, $meta_key );
  475. }
  476. return true; // Stop saving the value.
  477. }
  478. return $check; // Go on with the normal execution (update) in meta.php.
  479. }
  480. /**
  481. * Prevent adding of default values to the database.
  482. *
  483. * @param bool $check The current status to allow adding metadata for the given type.
  484. * @param int $object_id ID of the current object for which the meta is being added.
  485. * @param string $meta_key The full meta key (including prefix).
  486. * @param string $meta_value New meta value.
  487. *
  488. * @return null|bool True = stop saving, null = continue saving.
  489. */
  490. public static function dont_save_meta_if_default( $check, $object_id, $meta_key, $meta_value ) {
  491. /* If it's one of our meta fields, check against default. */
  492. if ( isset( self::$fields_index[ $meta_key ] ) && self::meta_value_is_default( $meta_key, $meta_value ) === true ) {
  493. return true; // Stop saving the value.
  494. }
  495. return $check; // Go on with the normal execution (add) in meta.php.
  496. }
  497. /**
  498. * Is the given meta value the same as the default value ?
  499. *
  500. * @param string $meta_key The full meta key (including prefix).
  501. * @param mixed $meta_value The value to check.
  502. *
  503. * @return bool
  504. */
  505. public static function meta_value_is_default( $meta_key, $meta_value ) {
  506. return ( isset( self::$defaults[ $meta_key ] ) && $meta_value === self::$defaults[ $meta_key ] );
  507. }
  508. /**
  509. * Get a custom post meta value.
  510. *
  511. * Returns the default value if the meta value has not been set.
  512. *
  513. * {@internal Unfortunately there isn't a filter available to hook into before returning
  514. * the results for get_post_meta(), get_post_custom() and the likes. That
  515. * would have been the preferred solution.}}
  516. *
  517. * @param string $key Internal key of the value to get (without prefix).
  518. * @param int $postid Post ID of the post to get the value for.
  519. *
  520. * @return string All 'normal' values returned from get_post_meta() are strings.
  521. * Objects and arrays are possible, but not used by this plugin
  522. * and therefore discarted (except when the special 'serialized' field def
  523. * value is set to true - only used by add-on plugins for now).
  524. * Will return the default value if no value was found.
  525. * Will return empty string if no default was found (not one of our keys) or
  526. * if the post does not exist.
  527. */
  528. public static function get_value( $key, $postid = 0 ) {
  529. global $post;
  530. $postid = absint( $postid );
  531. if ( $postid === 0 ) {
  532. if ( ( isset( $post ) && is_object( $post ) ) && ( isset( $post->post_status ) && $post->post_status !== 'auto-draft' ) ) {
  533. $postid = $post->ID;
  534. }
  535. else {
  536. return '';
  537. }
  538. }
  539. $custom = get_post_custom( $postid ); // Array of strings or empty array.
  540. if ( isset( $custom[ self::$meta_prefix . $key ][0] ) ) {
  541. $unserialized = maybe_unserialize( $custom[ self::$meta_prefix . $key ][0] );
  542. if ( $custom[ self::$meta_prefix . $key ][0] === $unserialized ) {
  543. return $custom[ self::$meta_prefix . $key ][0];
  544. }
  545. if ( isset( self::$fields_index[ self::$meta_prefix . $key ] ) ) {
  546. $field_def = self::$meta_fields[ self::$fields_index[ self::$meta_prefix . $key ]['subset'] ][ self::$fields_index[ self::$meta_prefix . $key ]['key'] ];
  547. if ( isset( $field_def['serialized'] ) && $field_def['serialized'] === true ) {
  548. // Ok, serialize value expected/allowed.
  549. return $unserialized;
  550. }
  551. }
  552. }
  553. // Meta was either not found or found, but object/array while not allowed to be.
  554. if ( isset( self::$defaults[ self::$meta_prefix . $key ] ) ) {
  555. return self::$defaults[ self::$meta_prefix . $key ];
  556. }
  557. /*
  558. * Shouldn't ever happen, means not one of our keys as there will always be a default available
  559. * for all our keys.
  560. */
  561. return '';
  562. }
  563. /**
  564. * Update a meta value for a post.
  565. *
  566. * @param string $key The internal key of the meta value to change (without prefix).
  567. * @param mixed $meta_value The value to set the meta to.
  568. * @param int $post_id The ID of the post to change the meta for.
  569. *
  570. * @return bool Whether the value was changed.
  571. */
  572. public static function set_value( $key, $meta_value, $post_id ) {
  573. /*
  574. * Slash the data, because `update_metadata` will unslash it and we have already unslashed it.
  575. * Related issue: https://github.com/Yoast/YoastSEO.js/issues/2158
  576. */
  577. $meta_value = wp_slash( $meta_value );
  578. return update_post_meta( $post_id, self::$meta_prefix . $key, $meta_value );
  579. }
  580. /**
  581. * Deletes a meta value for a post.
  582. *
  583. * @param string $key The internal key of the meta value to change (without prefix).
  584. * @param int $post_id The ID of the post to change the meta for.
  585. *
  586. * @return bool Whether the value was changed.
  587. */
  588. public static function delete( $key, $post_id ) {
  589. return delete_post_meta( $post_id, self::$meta_prefix . $key );
  590. }
  591. /**
  592. * Used for imports, this functions imports the value of $old_metakey into $new_metakey for those post
  593. * where no WPSEO meta data has been set.
  594. * Optionally deletes the $old_metakey values.
  595. *
  596. * @param string $old_metakey The old key of the meta value.
  597. * @param string $new_metakey The new key, usually the WPSEO meta key (including prefix).
  598. * @param bool $delete_old Whether to delete the old meta key/value-sets.
  599. *
  600. * @return void
  601. */
  602. public static function replace_meta( $old_metakey, $new_metakey, $delete_old = false ) {
  603. global $wpdb;
  604. /*
  605. * Get only those rows where no wpseo meta values exist for the same post
  606. * (with the exception of linkdex as that will be set independently of whether the post has been edited).
  607. *
  608. * {@internal Query is pretty well optimized this way.}}
  609. */
  610. $query = $wpdb->prepare(
  611. "
  612. SELECT `a`.*
  613. FROM {$wpdb->postmeta} AS a
  614. WHERE `a`.`meta_key` = %s
  615. AND NOT EXISTS (
  616. SELECT DISTINCT `post_id` , count( `meta_id` ) AS count
  617. FROM {$wpdb->postmeta} AS b
  618. WHERE `a`.`post_id` = `b`.`post_id`
  619. AND `meta_key` LIKE %s
  620. AND `meta_key` <> %s
  621. GROUP BY `post_id`
  622. )
  623. ;",
  624. $old_metakey,
  625. $wpdb->esc_like( self::$meta_prefix . '%' ),
  626. self::$meta_prefix . 'linkdex'
  627. );
  628. $oldies = $wpdb->get_results( $query );
  629. if ( is_array( $oldies ) && $oldies !== [] ) {
  630. foreach ( $oldies as $old ) {
  631. update_post_meta( $old->post_id, $new_metakey, $old->meta_value );
  632. }
  633. }
  634. // Delete old keys.
  635. if ( $delete_old === true ) {
  636. delete_post_meta_by_key( $old_metakey );
  637. }
  638. }
  639. /**
  640. * General clean-up of the saved meta values.
  641. * - Remove potentially lingering old meta keys;
  642. * - Remove all default and invalid values.
  643. *
  644. * @return void
  645. */
  646. public static function clean_up() {
  647. global $wpdb;
  648. /*
  649. * Clean up '_yoast_wpseo_meta-robots'.
  650. *
  651. * Retrieve all '_yoast_wpseo_meta-robots' meta values and convert if no new values found.
  652. *
  653. * {@internal Query is pretty well optimized this way.}}
  654. *
  655. * @todo [JRF => Yoast] Find out all possible values which the old '_yoast_wpseo_meta-robots' could contain
  656. * to convert the data correctly.
  657. */
  658. $query = $wpdb->prepare(
  659. "
  660. SELECT `a`.*
  661. FROM {$wpdb->postmeta} AS a
  662. WHERE `a`.`meta_key` = %s
  663. AND NOT EXISTS (
  664. SELECT DISTINCT `post_id` , count( `meta_id` ) AS count
  665. FROM {$wpdb->postmeta} AS b
  666. WHERE `a`.`post_id` = `b`.`post_id`
  667. AND ( `meta_key` = %s
  668. OR `meta_key` = %s )
  669. GROUP BY `post_id`
  670. )
  671. ;",
  672. self::$meta_prefix . 'meta-robots',
  673. self::$meta_prefix . 'meta-robots-noindex',
  674. self::$meta_prefix . 'meta-robots-nofollow'
  675. );
  676. $oldies = $wpdb->get_results( $query );
  677. if ( is_array( $oldies ) && $oldies !== [] ) {
  678. foreach ( $oldies as $old ) {
  679. $old_values = explode( ',', $old->meta_value );
  680. foreach ( $old_values as $value ) {
  681. if ( $value === 'noindex' ) {
  682. update_post_meta( $old->post_id, self::$meta_prefix . 'meta-robots-noindex', 1 );
  683. }
  684. elseif ( $value === 'nofollow' ) {
  685. update_post_meta( $old->post_id, self::$meta_prefix . 'meta-robots-nofollow', 1 );
  686. }
  687. }
  688. }
  689. }
  690. unset( $query, $oldies, $old, $old_values, $value );
  691. // Delete old keys.
  692. delete_post_meta_by_key( self::$meta_prefix . 'meta-robots' );
  693. /*
  694. * Remove all default values and (most) invalid option values.
  695. * Invalid option values for the multiselect (meta-robots-adv) field will be dealt with seperately.
  696. *
  697. * {@internal Some of the defaults have changed in v1.5, but as the defaults will
  698. * be removed and new defaults will now automatically be passed when no
  699. * data found, this update is automatic (as long as we remove the old
  700. * values which we do in the below routine).}}
  701. *
  702. * {@internal Unfortunately we can't use the normal delete_meta() with key/value combination
  703. * as '' (empty string) values will be ignored and would result in all metas
  704. * with that key being deleted, not just the empty fields.
  705. * Still, the below implementation is largely based on the delete_meta() function.}}
  706. */
  707. $query = [];
  708. foreach ( self::$meta_fields as $subset => $field_group ) {
  709. foreach ( $field_group as $key => $field_def ) {
  710. if ( ! isset( $field_def['default_value'] ) ) {
  711. continue;
  712. }
  713. if ( isset( $field_def['options'] ) && is_array( $field_def['options'] ) && $field_def['options'] !== [] ) {
  714. $valid = $field_def['options'];
  715. // Remove the default value from the valid options.
  716. unset( $valid[ $field_def['default_value'] ] );
  717. $valid = array_keys( $valid );
  718. $query[] = $wpdb->prepare(
  719. "( meta_key = %s AND meta_value NOT IN ( '" . implode( "','", esc_sql( $valid ) ) . "' ) )",
  720. self::$meta_prefix . $key
  721. );
  722. unset( $valid );
  723. }
  724. elseif ( is_string( $field_def['default_value'] ) && $field_def['default_value'] !== '' ) {
  725. $query[] = $wpdb->prepare(
  726. '( meta_key = %s AND meta_value = %s )',
  727. self::$meta_prefix . $key,
  728. $field_def['default_value']
  729. );
  730. }
  731. else {
  732. $query[] = $wpdb->prepare(
  733. "( meta_key = %s AND meta_value = '' )",
  734. self::$meta_prefix . $key
  735. );
  736. }
  737. }
  738. }
  739. unset( $subset, $field_group, $key, $field_def );
  740. $query = "SELECT meta_id FROM {$wpdb->postmeta} WHERE " . implode( ' OR ', $query ) . ';';
  741. $meta_ids = $wpdb->get_col( $query );
  742. if ( is_array( $meta_ids ) && $meta_ids !== [] ) {
  743. // WP native action.
  744. do_action( 'delete_post_meta', $meta_ids, null, null, null );
  745. $query = "DELETE FROM {$wpdb->postmeta} WHERE meta_id IN( " . implode( ',', $meta_ids ) . ' )';
  746. $count = $wpdb->query( $query );
  747. if ( $count ) {
  748. foreach ( $meta_ids as $object_id ) {
  749. wp_cache_delete( $object_id, 'post_meta' );
  750. }
  751. // WP native action.
  752. do_action( 'deleted_post_meta', $meta_ids, null, null, null );
  753. }
  754. }
  755. unset( $query, $meta_ids, $count, $object_id );
  756. /*
  757. * Deal with the multiselect (meta-robots-adv) field.
  758. *
  759. * Removes invalid option combinations, such as 'none,noarchive'.
  760. *
  761. * Default values have already been removed, so we should have a small result set and
  762. * (hopefully) even smaller set of invalid results.
  763. */
  764. $query = $wpdb->prepare(
  765. "SELECT meta_id, meta_value FROM {$wpdb->postmeta} WHERE meta_key = %s",
  766. self::$meta_prefix . 'meta-robots-adv'
  767. );
  768. $oldies = $wpdb->get_results( $query );
  769. if ( is_array( $oldies ) && $oldies !== [] ) {
  770. foreach ( $oldies as $old ) {
  771. $clean = self::validate_meta_robots_adv( $old->meta_value );
  772. if ( $clean !== $old->meta_value ) {
  773. if ( $clean !== self::$meta_fields['advanced']['meta-robots-adv']['default_value'] ) {
  774. update_metadata_by_mid( 'post', $old->meta_id, $clean );
  775. }
  776. else {
  777. delete_metadata_by_mid( 'post', $old->meta_id );
  778. }
  779. }
  780. }
  781. }
  782. unset( $query, $oldies, $old, $clean );
  783. do_action( 'wpseo_meta_clean_up' );
  784. }
  785. /**
  786. * Recursively merge a variable number of arrays, using the left array as base,
  787. * giving priority to the right array.
  788. *
  789. * Difference with native array_merge_recursive():
  790. * array_merge_recursive converts values with duplicate keys to arrays rather than
  791. * overwriting the value in the first array with the duplicate value in the second array.
  792. *
  793. * array_merge_recursive_distinct does not change the data types of the values in the arrays.
  794. * Matching keys' values in the second array overwrite those in the first array, as is the
  795. * case with array_merge.
  796. *
  797. * Freely based on information found on http://www.php.net/manual/en/function.array-merge-recursive.php
  798. *
  799. * {@internal Should be moved to a general utility class.}}
  800. *
  801. * @return array
  802. */
  803. public static function array_merge_recursive_distinct() {
  804. $arrays = func_get_args();
  805. if ( count( $arrays ) < 2 ) {
  806. if ( $arrays === [] ) {
  807. return [];
  808. }
  809. else {
  810. return $arrays[0];
  811. }
  812. }
  813. $merged = array_shift( $arrays );
  814. foreach ( $arrays as $array ) {
  815. foreach ( $array as $key => $value ) {
  816. if ( is_array( $value ) && ( isset( $merged[ $key ] ) && is_array( $merged[ $key ] ) ) ) {
  817. $merged[ $key ] = self::array_merge_recursive_distinct( $merged[ $key ], $value );
  818. }
  819. else {
  820. $merged[ $key ] = $value;
  821. }
  822. }
  823. unset( $key, $value );
  824. }
  825. return $merged;
  826. }
  827. /**
  828. * Counts the total of all the keywords being used for posts except the given one.
  829. *
  830. * @param string $keyword The keyword to be counted.
  831. * @param integer $post_id The is of the post to which the keyword belongs.
  832. *
  833. * @return array
  834. */
  835. public static function keyword_usage( $keyword, $post_id ) {
  836. if ( empty( $keyword ) ) {
  837. return [];
  838. }
  839. $query = [
  840. 'meta_query' => [
  841. 'relation' => 'OR',
  842. [
  843. 'key' => '_yoast_wpseo_focuskw',
  844. 'value' => $keyword,
  845. ],
  846. ],
  847. 'post__not_in' => [ $post_id ],
  848. 'fields' => 'ids',
  849. 'post_type' => 'any',
  850. /*
  851. * We only need to return zero, one or two results:
  852. * - Zero: keyword hasn't been used before
  853. * - One: Keyword has been used once before
  854. * - Two or more: Keyword has been used twice before
  855. */
  856. 'posts_per_page' => 2,
  857. ];
  858. // If Yoast SEO Premium is active, get the additional keywords as well.
  859. if ( WPSEO_Utils::is_yoast_seo_premium() ) {
  860. $query['meta_query'][] = [
  861. 'key' => '_yoast_wpseo_focuskeywords',
  862. 'value' => sprintf( '"keyword":"%s"', $keyword ),
  863. 'compare' => 'LIKE',
  864. ];
  865. }
  866. $get_posts = new WP_Query( $query );
  867. return $get_posts->posts;
  868. }
  869. /* ********************* DEPRECATED METHODS ********************* */
  870. /**
  871. * Get a value from $_POST for a given key.
  872. *
  873. * Returns the $_POST value if exists, returns an empty string if key does not exist.
  874. *
  875. * @deprecated 9.6
  876. * @codeCoverageIgnore
  877. *
  878. * @param string $key Key of the value to get from $_POST.
  879. *
  880. * @return string Returns $_POST value, which will be a string the majority of the time.
  881. * Will return empty string if key does not exists in $_POST.
  882. */
  883. public static function get_post_value( $key ) {
  884. _deprecated_function( __METHOD__, 'WPSEO 9.6' );
  885. // @codingStandardsIgnoreLine
  886. return ( array_key_exists( $key, $_POST ) ) ? $_POST[ $key ] : '';
  887. }
  888. } /* End of class */