class-wp-hook.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566
  1. <?php
  2. /**
  3. * Plugin API: WP_Hook class
  4. *
  5. * @package WordPress
  6. * @subpackage Plugin
  7. * @since 4.7.0
  8. */
  9. /**
  10. * Core class used to implement action and filter hook functionality.
  11. *
  12. * @since 4.7.0
  13. *
  14. * @see Iterator
  15. * @see ArrayAccess
  16. */
  17. #[AllowDynamicProperties]
  18. final class WP_Hook implements Iterator, ArrayAccess {
  19. /**
  20. * Hook callbacks.
  21. *
  22. * @since 4.7.0
  23. * @var array
  24. */
  25. public $callbacks = array();
  26. /**
  27. * The priority keys of actively running iterations of a hook.
  28. *
  29. * @since 4.7.0
  30. * @var array
  31. */
  32. private $iterations = array();
  33. /**
  34. * The current priority of actively running iterations of a hook.
  35. *
  36. * @since 4.7.0
  37. * @var array
  38. */
  39. private $current_priority = array();
  40. /**
  41. * Number of levels this hook can be recursively called.
  42. *
  43. * @since 4.7.0
  44. * @var int
  45. */
  46. private $nesting_level = 0;
  47. /**
  48. * Flag for if we're currently doing an action, rather than a filter.
  49. *
  50. * @since 4.7.0
  51. * @var bool
  52. */
  53. private $doing_action = false;
  54. /**
  55. * Adds a callback function to a filter hook.
  56. *
  57. * @since 4.7.0
  58. *
  59. * @param string $hook_name The name of the filter to add the callback to.
  60. * @param callable $callback The callback to be run when the filter is applied.
  61. * @param int $priority The order in which the functions associated with a particular filter
  62. * are executed. Lower numbers correspond with earlier execution,
  63. * and functions with the same priority are executed in the order
  64. * in which they were added to the filter.
  65. * @param int $accepted_args The number of arguments the function accepts.
  66. */
  67. public function add_filter( $hook_name, $callback, $priority, $accepted_args ) {
  68. $idx = _wp_filter_build_unique_id( $hook_name, $callback, $priority );
  69. $priority_existed = isset( $this->callbacks[ $priority ] );
  70. $this->callbacks[ $priority ][ $idx ] = array(
  71. 'function' => $callback,
  72. 'accepted_args' => $accepted_args,
  73. );
  74. // If we're adding a new priority to the list, put them back in sorted order.
  75. if ( ! $priority_existed && count( $this->callbacks ) > 1 ) {
  76. ksort( $this->callbacks, SORT_NUMERIC );
  77. }
  78. if ( $this->nesting_level > 0 ) {
  79. $this->resort_active_iterations( $priority, $priority_existed );
  80. }
  81. }
  82. /**
  83. * Handles resetting callback priority keys mid-iteration.
  84. *
  85. * @since 4.7.0
  86. *
  87. * @param false|int $new_priority Optional. The priority of the new filter being added. Default false,
  88. * for no priority being added.
  89. * @param bool $priority_existed Optional. Flag for whether the priority already existed before the new
  90. * filter was added. Default false.
  91. */
  92. private function resort_active_iterations( $new_priority = false, $priority_existed = false ) {
  93. $new_priorities = array_keys( $this->callbacks );
  94. // If there are no remaining hooks, clear out all running iterations.
  95. if ( ! $new_priorities ) {
  96. foreach ( $this->iterations as $index => $iteration ) {
  97. $this->iterations[ $index ] = $new_priorities;
  98. }
  99. return;
  100. }
  101. $min = min( $new_priorities );
  102. foreach ( $this->iterations as $index => &$iteration ) {
  103. $current = current( $iteration );
  104. // If we're already at the end of this iteration, just leave the array pointer where it is.
  105. if ( false === $current ) {
  106. continue;
  107. }
  108. $iteration = $new_priorities;
  109. if ( $current < $min ) {
  110. array_unshift( $iteration, $current );
  111. continue;
  112. }
  113. while ( current( $iteration ) < $current ) {
  114. if ( false === next( $iteration ) ) {
  115. break;
  116. }
  117. }
  118. // If we have a new priority that didn't exist, but ::apply_filters() or ::do_action() thinks it's the current priority...
  119. if ( $new_priority === $this->current_priority[ $index ] && ! $priority_existed ) {
  120. /*
  121. * ...and the new priority is the same as what $this->iterations thinks is the previous
  122. * priority, we need to move back to it.
  123. */
  124. if ( false === current( $iteration ) ) {
  125. // If we've already moved off the end of the array, go back to the last element.
  126. $prev = end( $iteration );
  127. } else {
  128. // Otherwise, just go back to the previous element.
  129. $prev = prev( $iteration );
  130. }
  131. if ( false === $prev ) {
  132. // Start of the array. Reset, and go about our day.
  133. reset( $iteration );
  134. } elseif ( $new_priority !== $prev ) {
  135. // Previous wasn't the same. Move forward again.
  136. next( $iteration );
  137. }
  138. }
  139. }
  140. unset( $iteration );
  141. }
  142. /**
  143. * Removes a callback function from a filter hook.
  144. *
  145. * @since 4.7.0
  146. *
  147. * @param string $hook_name The filter hook to which the function to be removed is hooked.
  148. * @param callable|string|array $callback The callback to be removed from running when the filter is applied.
  149. * This method can be called unconditionally to speculatively remove
  150. * a callback that may or may not exist.
  151. * @param int $priority The exact priority used when adding the original filter callback.
  152. * @return bool Whether the callback existed before it was removed.
  153. */
  154. public function remove_filter( $hook_name, $callback, $priority ) {
  155. $function_key = _wp_filter_build_unique_id( $hook_name, $callback, $priority );
  156. $exists = isset( $this->callbacks[ $priority ][ $function_key ] );
  157. if ( $exists ) {
  158. unset( $this->callbacks[ $priority ][ $function_key ] );
  159. if ( ! $this->callbacks[ $priority ] ) {
  160. unset( $this->callbacks[ $priority ] );
  161. if ( $this->nesting_level > 0 ) {
  162. $this->resort_active_iterations();
  163. }
  164. }
  165. }
  166. return $exists;
  167. }
  168. /**
  169. * Checks if a specific callback has been registered for this hook.
  170. *
  171. * When using the `$callback` argument, this function may return a non-boolean value
  172. * that evaluates to false (e.g. 0), so use the `===` operator for testing the return value.
  173. *
  174. * @since 4.7.0
  175. *
  176. * @param string $hook_name Optional. The name of the filter hook. Default empty.
  177. * @param callable|string|array|false $callback Optional. The callback to check for.
  178. * This method can be called unconditionally to speculatively check
  179. * a callback that may or may not exist. Default false.
  180. * @return bool|int If `$callback` is omitted, returns boolean for whether the hook has
  181. * anything registered. When checking a specific function, the priority
  182. * of that hook is returned, or false if the function is not attached.
  183. */
  184. public function has_filter( $hook_name = '', $callback = false ) {
  185. if ( false === $callback ) {
  186. return $this->has_filters();
  187. }
  188. $function_key = _wp_filter_build_unique_id( $hook_name, $callback, false );
  189. if ( ! $function_key ) {
  190. return false;
  191. }
  192. foreach ( $this->callbacks as $priority => $callbacks ) {
  193. if ( isset( $callbacks[ $function_key ] ) ) {
  194. return $priority;
  195. }
  196. }
  197. return false;
  198. }
  199. /**
  200. * Checks if any callbacks have been registered for this hook.
  201. *
  202. * @since 4.7.0
  203. *
  204. * @return bool True if callbacks have been registered for the current hook, otherwise false.
  205. */
  206. public function has_filters() {
  207. foreach ( $this->callbacks as $callbacks ) {
  208. if ( $callbacks ) {
  209. return true;
  210. }
  211. }
  212. return false;
  213. }
  214. /**
  215. * Removes all callbacks from the current filter.
  216. *
  217. * @since 4.7.0
  218. *
  219. * @param int|false $priority Optional. The priority number to remove. Default false.
  220. */
  221. public function remove_all_filters( $priority = false ) {
  222. if ( ! $this->callbacks ) {
  223. return;
  224. }
  225. if ( false === $priority ) {
  226. $this->callbacks = array();
  227. } elseif ( isset( $this->callbacks[ $priority ] ) ) {
  228. unset( $this->callbacks[ $priority ] );
  229. }
  230. if ( $this->nesting_level > 0 ) {
  231. $this->resort_active_iterations();
  232. }
  233. }
  234. /**
  235. * Calls the callback functions that have been added to a filter hook.
  236. *
  237. * @since 4.7.0
  238. *
  239. * @param mixed $value The value to filter.
  240. * @param array $args Additional parameters to pass to the callback functions.
  241. * This array is expected to include $value at index 0.
  242. * @return mixed The filtered value after all hooked functions are applied to it.
  243. */
  244. public function apply_filters( $value, $args ) {
  245. if ( ! $this->callbacks ) {
  246. return $value;
  247. }
  248. $nesting_level = $this->nesting_level++;
  249. $this->iterations[ $nesting_level ] = array_keys( $this->callbacks );
  250. $num_args = count( $args );
  251. do {
  252. $this->current_priority[ $nesting_level ] = current( $this->iterations[ $nesting_level ] );
  253. $priority = $this->current_priority[ $nesting_level ];
  254. foreach ( $this->callbacks[ $priority ] as $the_ ) {
  255. if ( ! $this->doing_action ) {
  256. $args[0] = $value;
  257. }
  258. // Avoid the array_slice() if possible.
  259. if ( 0 == $the_['accepted_args'] ) {
  260. $value = call_user_func( $the_['function'] );
  261. } elseif ( $the_['accepted_args'] >= $num_args ) {
  262. $value = call_user_func_array( $the_['function'], $args );
  263. } else {
  264. $value = call_user_func_array( $the_['function'], array_slice( $args, 0, (int) $the_['accepted_args'] ) );
  265. }
  266. }
  267. } while ( false !== next( $this->iterations[ $nesting_level ] ) );
  268. unset( $this->iterations[ $nesting_level ] );
  269. unset( $this->current_priority[ $nesting_level ] );
  270. $this->nesting_level--;
  271. return $value;
  272. }
  273. /**
  274. * Calls the callback functions that have been added to an action hook.
  275. *
  276. * @since 4.7.0
  277. *
  278. * @param array $args Parameters to pass to the callback functions.
  279. */
  280. public function do_action( $args ) {
  281. $this->doing_action = true;
  282. $this->apply_filters( '', $args );
  283. // If there are recursive calls to the current action, we haven't finished it until we get to the last one.
  284. if ( ! $this->nesting_level ) {
  285. $this->doing_action = false;
  286. }
  287. }
  288. /**
  289. * Processes the functions hooked into the 'all' hook.
  290. *
  291. * @since 4.7.0
  292. *
  293. * @param array $args Arguments to pass to the hook callbacks. Passed by reference.
  294. */
  295. public function do_all_hook( &$args ) {
  296. $nesting_level = $this->nesting_level++;
  297. $this->iterations[ $nesting_level ] = array_keys( $this->callbacks );
  298. do {
  299. $priority = current( $this->iterations[ $nesting_level ] );
  300. foreach ( $this->callbacks[ $priority ] as $the_ ) {
  301. call_user_func_array( $the_['function'], $args );
  302. }
  303. } while ( false !== next( $this->iterations[ $nesting_level ] ) );
  304. unset( $this->iterations[ $nesting_level ] );
  305. $this->nesting_level--;
  306. }
  307. /**
  308. * Return the current priority level of the currently running iteration of the hook.
  309. *
  310. * @since 4.7.0
  311. *
  312. * @return int|false If the hook is running, return the current priority level.
  313. * If it isn't running, return false.
  314. */
  315. public function current_priority() {
  316. if ( false === current( $this->iterations ) ) {
  317. return false;
  318. }
  319. return current( current( $this->iterations ) );
  320. }
  321. /**
  322. * Normalizes filters set up before WordPress has initialized to WP_Hook objects.
  323. *
  324. * The `$filters` parameter should be an array keyed by hook name, with values
  325. * containing either:
  326. *
  327. * - A `WP_Hook` instance
  328. * - An array of callbacks keyed by their priorities
  329. *
  330. * Examples:
  331. *
  332. * $filters = array(
  333. * 'wp_fatal_error_handler_enabled' => array(
  334. * 10 => array(
  335. * array(
  336. * 'accepted_args' => 0,
  337. * 'function' => function() {
  338. * return false;
  339. * },
  340. * ),
  341. * ),
  342. * ),
  343. * );
  344. *
  345. * @since 4.7.0
  346. *
  347. * @param array $filters Filters to normalize. See documentation above for details.
  348. * @return WP_Hook[] Array of normalized filters.
  349. */
  350. public static function build_preinitialized_hooks( $filters ) {
  351. /** @var WP_Hook[] $normalized */
  352. $normalized = array();
  353. foreach ( $filters as $hook_name => $callback_groups ) {
  354. if ( is_object( $callback_groups ) && $callback_groups instanceof WP_Hook ) {
  355. $normalized[ $hook_name ] = $callback_groups;
  356. continue;
  357. }
  358. $hook = new WP_Hook();
  359. // Loop through callback groups.
  360. foreach ( $callback_groups as $priority => $callbacks ) {
  361. // Loop through callbacks.
  362. foreach ( $callbacks as $cb ) {
  363. $hook->add_filter( $hook_name, $cb['function'], $priority, $cb['accepted_args'] );
  364. }
  365. }
  366. $normalized[ $hook_name ] = $hook;
  367. }
  368. return $normalized;
  369. }
  370. /**
  371. * Determines whether an offset value exists.
  372. *
  373. * @since 4.7.0
  374. *
  375. * @link https://www.php.net/manual/en/arrayaccess.offsetexists.php
  376. *
  377. * @param mixed $offset An offset to check for.
  378. * @return bool True if the offset exists, false otherwise.
  379. */
  380. #[ReturnTypeWillChange]
  381. public function offsetExists( $offset ) {
  382. return isset( $this->callbacks[ $offset ] );
  383. }
  384. /**
  385. * Retrieves a value at a specified offset.
  386. *
  387. * @since 4.7.0
  388. *
  389. * @link https://www.php.net/manual/en/arrayaccess.offsetget.php
  390. *
  391. * @param mixed $offset The offset to retrieve.
  392. * @return mixed If set, the value at the specified offset, null otherwise.
  393. */
  394. #[ReturnTypeWillChange]
  395. public function offsetGet( $offset ) {
  396. return isset( $this->callbacks[ $offset ] ) ? $this->callbacks[ $offset ] : null;
  397. }
  398. /**
  399. * Sets a value at a specified offset.
  400. *
  401. * @since 4.7.0
  402. *
  403. * @link https://www.php.net/manual/en/arrayaccess.offsetset.php
  404. *
  405. * @param mixed $offset The offset to assign the value to.
  406. * @param mixed $value The value to set.
  407. */
  408. #[ReturnTypeWillChange]
  409. public function offsetSet( $offset, $value ) {
  410. if ( is_null( $offset ) ) {
  411. $this->callbacks[] = $value;
  412. } else {
  413. $this->callbacks[ $offset ] = $value;
  414. }
  415. }
  416. /**
  417. * Unsets a specified offset.
  418. *
  419. * @since 4.7.0
  420. *
  421. * @link https://www.php.net/manual/en/arrayaccess.offsetunset.php
  422. *
  423. * @param mixed $offset The offset to unset.
  424. */
  425. #[ReturnTypeWillChange]
  426. public function offsetUnset( $offset ) {
  427. unset( $this->callbacks[ $offset ] );
  428. }
  429. /**
  430. * Returns the current element.
  431. *
  432. * @since 4.7.0
  433. *
  434. * @link https://www.php.net/manual/en/iterator.current.php
  435. *
  436. * @return array Of callbacks at current priority.
  437. */
  438. #[ReturnTypeWillChange]
  439. public function current() {
  440. return current( $this->callbacks );
  441. }
  442. /**
  443. * Moves forward to the next element.
  444. *
  445. * @since 4.7.0
  446. *
  447. * @link https://www.php.net/manual/en/iterator.next.php
  448. *
  449. * @return array Of callbacks at next priority.
  450. */
  451. #[ReturnTypeWillChange]
  452. public function next() {
  453. return next( $this->callbacks );
  454. }
  455. /**
  456. * Returns the key of the current element.
  457. *
  458. * @since 4.7.0
  459. *
  460. * @link https://www.php.net/manual/en/iterator.key.php
  461. *
  462. * @return mixed Returns current priority on success, or NULL on failure
  463. */
  464. #[ReturnTypeWillChange]
  465. public function key() {
  466. return key( $this->callbacks );
  467. }
  468. /**
  469. * Checks if current position is valid.
  470. *
  471. * @since 4.7.0
  472. *
  473. * @link https://www.php.net/manual/en/iterator.valid.php
  474. *
  475. * @return bool Whether the current position is valid.
  476. */
  477. #[ReturnTypeWillChange]
  478. public function valid() {
  479. return key( $this->callbacks ) !== null;
  480. }
  481. /**
  482. * Rewinds the Iterator to the first element.
  483. *
  484. * @since 4.7.0
  485. *
  486. * @link https://www.php.net/manual/en/iterator.rewind.php
  487. */
  488. #[ReturnTypeWillChange]
  489. public function rewind() {
  490. reset( $this->callbacks );
  491. }
  492. }