class-wpseo-meta.php 36 KB

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