Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
82.42% covered (warning)
82.42%
150 / 182
55.56% covered (warning)
55.56%
10 / 18
CRAP
0.00% covered (danger)
0.00%
0 / 1
HookContainer
82.42% covered (warning)
82.42%
150 / 182
55.56% covered (warning)
55.56%
10 / 18
101.97
0.00% covered (danger)
0.00%
0 / 1
 __construct
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 salvage
100.00% covered (success)
100.00%
6 / 6
100.00% covered (success)
100.00%
1 / 1
4
 run
70.59% covered (warning)
70.59%
12 / 17
0.00% covered (danger)
0.00%
0 / 1
8.25
 clear
n/a
0 / 0
n/a
0 / 0
2
 scopedRegister
90.00% covered (success)
90.00%
9 / 10
0.00% covered (danger)
0.00%
0 / 1
2.00
 makeExtensionHandlerCallback
100.00% covered (success)
100.00%
14 / 14
100.00% covered (success)
100.00%
1 / 1
5
 normalizeHandler
84.00% covered (warning)
84.00%
21 / 25
0.00% covered (danger)
0.00%
0 / 1
9.33
 isRegistered
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 register
100.00% covered (success)
100.00%
9 / 9
100.00% covered (success)
100.00%
1 / 1
3
 getHandlerCallbacks
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
1
 getHookNames
100.00% covered (success)
100.00%
7 / 7
100.00% covered (success)
100.00%
1 / 1
1
 getHandlers
93.75% covered (success)
93.75%
15 / 16
0.00% covered (danger)
0.00%
0 / 1
4.00
 getHandlerDescriptions
100.00% covered (success)
100.00%
15 / 15
100.00% covered (success)
100.00%
1 / 1
4
 describeHandler
0.00% covered (danger)
0.00%
0 / 10
0.00% covered (danger)
0.00%
0 / 1
42
 emitDeprecationWarnings
100.00% covered (success)
100.00%
15 / 15
100.00% covered (success)
100.00%
1 / 1
7
 checkDeprecation
40.00% covered (danger)
40.00%
4 / 10
0.00% covered (danger)
0.00%
0 / 1
7.46
 callableToString
75.00% covered (warning)
75.00%
12 / 16
0.00% covered (danger)
0.00%
0 / 1
9.00
 getHookMethodName
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
1
 mayBeCallable
80.00% covered (warning)
80.00%
4 / 5
0.00% covered (danger)
0.00%
0 / 1
3.07
1<?php
2/**
3 * @license GPL-2.0-or-later
4 * @file
5 * @ingroup Hooks
6 * @defgroup Hooks Hooks
7 * Hooks allow custom code to be executed when an event occurs; this module
8 * includes all hooks provided by MediaWiki Core; for more information, see
9 * https://www.mediawiki.org/wiki/Manual:Hooks.
10 */
11
12namespace MediaWiki\HookContainer;
13
14use Closure;
15use Error;
16use InvalidArgumentException;
17use LogicException;
18use MediaWiki\Debug\MWDebug;
19use ReflectionFunction;
20use UnexpectedValueException;
21use Wikimedia\Assert\Assert;
22use Wikimedia\NonSerializable\NonSerializableTrait;
23use Wikimedia\ObjectFactory\ObjectFactory;
24use Wikimedia\ScopedCallback;
25use Wikimedia\Services\SalvageableService;
26use function array_filter;
27use function array_keys;
28use function array_merge;
29use function array_unique;
30use function is_array;
31use function is_object;
32use function is_string;
33use function strtr;
34
35/**
36 * HookContainer class.
37 *
38 * Main class for managing hooks
39 *
40 * @since 1.35
41 */
42class HookContainer implements SalvageableService {
43    use NonSerializableTrait;
44
45    public const NOOP = '*no-op*';
46
47    /**
48     * Normalized hook handlers, as a 3D array:
49     * - the first level maps hook names to lists of handlers
50     * - the second is a list of handlers
51     * - each handler is an associative array with some well known keys, as returned by normalizeHandler()
52     * @var array<array>
53     * @phan-var array<string,array<string|int,array{callback:callable,functionName:string}>>
54     */
55    private $handlers = [];
56
57    /** @var array<object> handler name and their handler objects */
58    private $handlerObjects = [];
59
60    /**
61     * Handlers registered by calling register().
62     * @var array
63     */
64    private $extraHandlers = [];
65
66    /** @var int The next ID to be used by scopedRegister() */
67    private $nextScopedRegisterId = 0;
68
69    public function __construct(
70        private readonly HookRegistry $hookRegistry,
71        private readonly ObjectFactory $objectFactory,
72    ) {
73    }
74
75    /**
76     * Salvage the state of HookContainer by retaining existing handler objects
77     * and hooks registered via HookContainer::register(). Necessary in the event
78     * that MediaWikiServices::resetGlobalInstance() is called after hooks have already
79     * been registered.
80     *
81     * @param HookContainer|SalvageableService $other The object to salvage state from. $other be
82     * of type HookContainer
83     */
84    public function salvage( SalvageableService $other ) {
85        Assert::parameterType( self::class, $other, '$other' );
86        if ( $this->handlers || $this->handlerObjects || $this->extraHandlers ) {
87            throw new LogicException( 'salvage() must be called immediately after construction' );
88        }
89        $this->handlerObjects = $other->handlerObjects;
90        $this->handlers = $other->handlers;
91        $this->extraHandlers = $other->extraHandlers;
92    }
93
94    /**
95     * Call registered hook functions through either the legacy $wgHooks or extension.json
96     *
97     * For the given hook, fetch the array of handler objects and
98     * process them. Determine the proper callback for each hook and
99     * then call the actual hook using the appropriate arguments.
100     * Finally, process the return value and return/throw accordingly.
101     *
102     * @param string $hook Name of the hook
103     * @param array $args Arguments to pass to hook handler
104     * @param array $options options map:
105     *   - abortable: (bool) If false, handlers will not be allowed to abort the call sequence.
106     *     An exception will be raised if a handler returns anything other than true or null.
107     *   - deprecatedVersion: (string) Version of MediaWiki this hook was deprecated in. For supporting
108     *     Hooks::run() legacy $deprecatedVersion parameter. New core code should add deprecated
109     *     hooks to the DeprecatedHooks::$deprecatedHooks array literal. New extension code should
110     *     use the DeprecatedHooks attribute.
111     *   - silent: (bool) If true, do not raise a deprecation warning
112     *   - noServices: (bool) If true, do not allow hook handlers with service dependencies
113     * @return bool True if no handler aborted the hook
114     * @throws UnexpectedValueException if handlers return an invalid value
115     */
116    public function run( string $hook, array $args = [], array $options = [] ): bool {
117        $checkDeprecation = isset( $options['deprecatedVersion'] );
118
119        $abortable = $options['abortable'] ?? true;
120        foreach ( $this->getHandlers( $hook, $options ) as $handler ) {
121            if ( $checkDeprecation ) {
122                $this->checkDeprecation( $hook, $handler, $options );
123            }
124
125            // Call the handler.
126            $callback = $handler['callback'];
127            $return = $callback( ...$args );
128
129            // Handler returned false, signal abort to caller
130            if ( $return === false ) {
131                if ( !$abortable ) {
132                    throw new UnexpectedValueException( "Handler {$handler['functionName']}" .
133                        " return false for unabortable $hook." );
134                }
135
136                return false;
137            } elseif ( $return !== null && $return !== true ) {
138                throw new UnexpectedValueException(
139                    "Hook handlers can only return null or a boolean. Got an unexpected value from " .
140                    "handler {$handler['functionName']} for $hook" );
141            }
142        }
143
144        return true;
145    }
146
147    /**
148     * Clear handlers of the given hook.
149     * This is intended for use while testing and will fail if MW_PHPUNIT_TEST
150     * is not defined.
151     *
152     * @param string $hook Name of hook to clear
153     *
154     * @internal For testing only
155     * @codeCoverageIgnore
156     */
157    public function clear( string $hook ): void {
158        if ( !defined( 'MW_PHPUNIT_TEST' ) ) {
159            throw new LogicException( 'Cannot reset hooks in operation.' );
160        }
161
162        $this->handlers[$hook] = [];
163    }
164
165    /**
166     * Register hook and handler, allowing for easy removal.
167     * Intended for use in temporary registration e.g. testing
168     *
169     * @param string $hook Name of hook
170     * @param callable|string|array $handler Handler to attach
171     */
172    #[\NoDiscard]
173    public function scopedRegister( string $hook, $handler ): ScopedCallback {
174        $handler = $this->normalizeHandler( $hook, $handler );
175        if ( !$handler ) {
176            throw new InvalidArgumentException( 'Bad hook handler!' );
177        }
178
179        $this->checkDeprecation( $hook, $handler );
180
181        $id = 'TemporaryHook_' . $this->nextScopedRegisterId++;
182
183        $this->getHandlers( $hook );
184
185        $this->handlers[$hook][$id] = $handler;
186
187        return new ScopedCallback( function () use ( $hook, $id ) {
188            unset( $this->handlers[$hook][$id] );
189        } );
190    }
191
192    /**
193     * Returns a callable array based on the handler specification provided.
194     * This will find the appropriate handler object to call a method on,
195     * This will find the appropriate handler object to call a method on,
196     * instantiating it if it doesn't exist yet.
197     *
198     * @param string $hook The name of the hook the handler was registered for
199     * @param array $handler A hook handler specification as given in an extension.json file.
200     * @param array $options Options to apply. If the 'noServices' option is set and the
201     *              handler requires service injection, this method will throw an
202     *              UnexpectedValueException.
203     *
204     * @return callable-array
205     */
206    private function makeExtensionHandlerCallback( string $hook, array $handler, array $options = [] ): array {
207        $spec = $handler['handler'];
208        $name = $spec['name'];
209
210        if (
211            !empty( $options['noServices'] ) && (
212                !empty( $spec['services'] ) ||
213                !empty( $spec['optional_services'] )
214            )
215        ) {
216            throw new UnexpectedValueException(
217                "The handler for the hook $hook registered in " .
218                "{$handler['extensionPath']} has a service dependency, " .
219                "but this hook does not allow it." );
220        }
221
222        if ( !isset( $this->handlerObjects[$name] ) ) {
223            $this->handlerObjects[$name] = $this->objectFactory->createObject( $spec );
224        }
225
226        $obj = $this->handlerObjects[$name];
227        $method = $this->getHookMethodName( $hook );
228
229        return [ $obj, $method ];
230    }
231
232    /**
233     * Normalize/clean up format of argument passed as hook handler
234     *
235     * @param string $hook Hook name
236     * @param string|callable|array{handler:array} $handler Executable handler function. See {@link self::register()}
237     * for supported structures.
238     * @param array $options see makeExtensionHandlerCallback()
239     *
240     * @return array|false
241     *  - callback: (callable) Executable handler function
242     *  - functionName: (string) Handler name for passing to wfDeprecated() or Exceptions thrown
243     * @phan-return array{callback:callable,functionName:string}|false
244     */
245    private function normalizeHandler( string $hook, $handler, array $options = [] ) {
246        // 1 - Class instance with `on$hook` method.
247        if ( is_object( $handler ) && !$handler instanceof Closure ) {
248            $handler = [ $handler, $this->getHookMethodName( $hook ) ];
249        }
250
251        // 2 - No-op
252        if ( $handler === self::NOOP ) {
253            return [
254                'callback' => static function () {
255                    // no-op
256                },
257                'functionName' => self::NOOP,
258            ];
259        }
260
261        // 3 - Plain callback
262        if ( self::mayBeCallable( $handler ) ) {
263            return [
264                'callback' => $handler,
265                'functionName' => self::callableToString( $handler ),
266            ];
267        }
268
269        // 4 - ExtensionRegistry style handler
270        if ( is_array( $handler ) && !empty( $handler['handler'] ) ) {
271            // Skip hooks that both acknowledge deprecation and are deprecated in core
272            if ( $handler['deprecated'] ?? false ) {
273                $deprecatedHooks = $this->hookRegistry->getDeprecatedHooks();
274                $deprecated = $deprecatedHooks->isHookDeprecated( $hook );
275                if ( $deprecated ) {
276                    return false;
277                }
278            }
279
280            $callback = $this->makeExtensionHandlerCallback( $hook, $handler, $options );
281            return [
282                'callback' => $callback,
283                'functionName' => self::callableToString( $callback ),
284            ];
285        }
286
287        // Something invalid
288        return false;
289    }
290
291    /**
292     * Return whether hook has any handlers registered to it.
293     * The function may have been registered via Hooks::register or in extension.json
294     *
295     * @param string $hook Name of hook
296     * @return bool Whether the hook has a handler registered to it
297     */
298    public function isRegistered( string $hook ): bool {
299        return (bool)$this->getHandlers( $hook );
300    }
301
302    /**
303     * Attach an event handler to a given hook.
304     *
305     * The handler should be given in one of the following forms:
306     *
307     * 1) A callable (string, array, or closure)
308     * 2) An extension hook handler spec in the form returned by
309     *    HookRegistry::getExtensionHooks
310     * 3) A class instance with an `on$hook` method (see {@link self::getHookMethodName} for normalizations applied)
311     * 4) {@link self::NOOP} as a no-op handler
312     *
313     * Several other forms are supported for backwards compatibility, but
314     * should not be used when calling this method directly.
315     *
316     * @note This method accepts "broken callables", that is, callable
317     * structures that reference classes that could not be found or could
318     * not be loaded, e.g. because they implement an interface that cannot
319     * be loaded. This situation may legitimately arise when implementing
320     * hooks defined by extensions that are not present.
321     * In that case, the hook will never fire and registering the "broken"
322     * handlers is harmless. If a broken hook handler is registered for a
323     * hook that is indeed called, it will cause an error. This is
324     * intentional: we don't want to silently ignore mistakes like mistyped
325     * class names in a hook handler registration.
326     *
327     * @param string $hook Name of hook
328     * @param string|array|callable $handler handler
329     */
330    public function register( string $hook, $handler ) {
331        $this->checkDeprecation( $hook, $handler );
332
333        if ( !isset( $this->handlers[$hook] ) ) {
334            // Just remember the handler for later.
335            // NOTE: It would be nice to normalize immediately. But since some extensions make extensive
336            //       use of this method for registering hooks on every call, that could be a performance
337            //       issue. This is particularly true if the hook is declared in a way that would require
338            //       service objects to be instantiated.
339            $this->extraHandlers[$hook][] = $handler;
340            return;
341        }
342
343        $normalized = $this->normalizeHandler( $hook, $handler );
344        if ( !$normalized ) {
345            throw new InvalidArgumentException( 'Bad hook handler!' );
346        }
347
348        $this->getHandlers( $hook );
349        $this->handlers[$hook][] = $normalized;
350    }
351
352    /**
353     * Get handler callbacks.
354     *
355     * @deprecated since 1.41.
356     * @internal For use by HookContainerTest. Delete when no longer needed.
357     * @param string $hook Name of hook
358     * @return callable[]
359     */
360    public function getHandlerCallbacks( string $hook ): array {
361        wfDeprecated( __METHOD__, '1.41' );
362        $handlers = $this->getHandlers( $hook );
363        return array_column( $handlers, 'callback' );
364    }
365
366    /**
367     * Returns the names of all hooks that have at least one handler registered.
368     * @return string[]
369     */
370    public function getHookNames(): array {
371        $names = array_merge(
372            array_keys( array_filter( $this->handlers ) ),
373            array_keys( array_filter( $this->extraHandlers ) ),
374            array_keys( array_filter( $this->hookRegistry->getGlobalHooks() ) ),
375            array_keys( array_filter( $this->hookRegistry->getExtensionHooks() ) )
376        );
377
378        return array_unique( $names );
379    }
380
381    /**
382     * Return the array of handlers for the given hook.
383     *
384     * @param string $hook Name of the hook
385     * @param array $options Handler options, which may include:
386     *   - noServices: Do not allow hook handlers with service dependencies
387     * @return array[] A list of handler entries
388     * @phan-return array<string|int,array{callback:callable,functionName:string}>
389     */
390    private function getHandlers( string $hook, array $options = [] ): array {
391        if ( !isset( $this->handlers[$hook] ) ) {
392            $handlers = [];
393            $registeredHooks = $this->hookRegistry->getExtensionHooks();
394            $configuredHooks = $this->hookRegistry->getGlobalHooks();
395
396            $rawHandlers = array_merge(
397                $configuredHooks[ $hook ] ?? [],
398                $registeredHooks[ $hook ] ?? [],
399                $this->extraHandlers[ $hook ] ?? [],
400            );
401
402            foreach ( $rawHandlers as $raw ) {
403                $handler = $this->normalizeHandler( $hook, $raw, $options );
404                if ( !$handler ) {
405                    // XXX: log this?!
406                    // NOTE: also happens for deprecated hooks, which is fine!
407                    continue;
408                }
409
410                $handlers[] = $handler;
411            }
412
413            $this->handlers[ $hook ] = $handlers;
414        }
415
416        return $this->handlers[ $hook ];
417    }
418
419    /**
420     * Return the array of strings that describe the handler registered with the given hook.
421     *
422     * @internal Only public for use by ApiQuerySiteInfo.php and SpecialVersion.php
423     * @param string $hook Name of the hook
424     * @return string[] A list of handler descriptions
425     */
426    public function getHandlerDescriptions( string $hook ): array {
427        $descriptions = [];
428
429        if ( isset( $this->handlers[ $hook ] ) ) {
430            $rawHandlers = $this->handlers[ $hook ];
431        } else {
432            $registeredHooks = $this->hookRegistry->getExtensionHooks();
433            $configuredHooks = $this->hookRegistry->getGlobalHooks();
434
435            $rawHandlers = array_merge(
436                $configuredHooks[ $hook ] ?? [],
437                $registeredHooks[ $hook ] ?? [],
438                $this->extraHandlers[ $hook ] ?? [],
439            );
440        }
441
442        foreach ( $rawHandlers as $raw ) {
443            $descr = $this->describeHandler( $hook, $raw );
444
445            if ( $descr ) {
446                $descriptions[] = $descr;
447            }
448        }
449
450        return $descriptions;
451    }
452
453    /**
454     * Returns a human-readable description of the given handler.
455     *
456     * @param string $hook
457     * @param string|array|callable $handler
458     *
459     * @return ?string
460     */
461    private function describeHandler( string $hook, $handler ): ?string {
462        if ( is_array( $handler ) ) {
463            // already normalized
464            if ( isset( $handler['functionName'] ) ) {
465                return $handler['functionName'];
466            }
467
468            if ( isset( $handler['callback'] ) ) {
469                return self::callableToString( $handler['callback'] );
470            }
471
472            if ( isset( $handler['handler']['class'] ) ) {
473                // New style hook. Avoid instantiating the handler object
474                $method = $this->getHookMethodName( $hook );
475                return $handler['handler']['class'] . '::' . $method;
476            }
477        }
478
479        $handler = $this->normalizeHandler( $hook, $handler );
480        return $handler ? $handler['functionName'] : null;
481    }
482
483    /**
484     * For each hook handler of each hook, this will log a deprecation if:
485     * 1. the hook is marked deprecated and
486     * 2. the "silent" flag is absent or false, and
487     * 3. an extension registers a handler in the new way but does not acknowledge deprecation
488     */
489    public function emitDeprecationWarnings() {
490        $deprecatedHooks = $this->hookRegistry->getDeprecatedHooks();
491        $extensionHooks = $this->hookRegistry->getExtensionHooks();
492
493        foreach ( $extensionHooks as $name => $handlers ) {
494            if ( $deprecatedHooks->isHookDeprecated( $name ) ) {
495                $deprecationInfo = $deprecatedHooks->getDeprecationInfo( $name );
496                if ( !empty( $deprecationInfo['silent'] ) ) {
497                    continue;
498                }
499                $version = $deprecationInfo['deprecatedVersion'] ?? '';
500                $component = $deprecationInfo['component'] ?? 'MediaWiki';
501                foreach ( $handlers as $handler ) {
502                    if ( !isset( $handler['deprecated'] ) || !$handler['deprecated'] ) {
503                        MWDebug::sendRawDeprecated(
504                            "Hook $name was deprecated in $component $version " .
505                            "but is registered in " . $handler['extensionPath']
506                        );
507                    }
508                }
509            }
510        }
511    }
512
513    /**
514     * Will trigger a deprecation warning if the given hook is deprecated and the deprecation
515     * is not marked as silent.
516     *
517     * @param string $hook The name of the hook.
518     * @param array|callable|string $handler A handler spec
519     * @param array|null $deprecationInfo Deprecation info if the caller already knows it.
520     *        If not given, it will be looked up from the hook registry.
521     *
522     * @return void
523     */
524    private function checkDeprecation( string $hook, $handler, ?array $deprecationInfo = null ): void {
525        if ( !$deprecationInfo ) {
526            $deprecatedHooks = $this->hookRegistry->getDeprecatedHooks();
527            $deprecationInfo = $deprecatedHooks->getDeprecationInfo( $hook );
528        }
529
530        if ( $deprecationInfo && empty( $deprecationInfo['silent'] ) ) {
531            $description = $this->describeHandler( $hook, $handler );
532            wfDeprecated(
533                "$hook hook (used in $description)",
534                $deprecationInfo['deprecatedVersion'] ?? false,
535                $deprecationInfo['component'] ?? false
536            );
537        }
538    }
539
540    /**
541     * Returns a human-readable representation of the given callable.
542     *
543     * @param callable $callable
544     *
545     * @return string
546     */
547    private static function callableToString( $callable ): string {
548        if ( is_string( $callable ) ) {
549            return $callable;
550        }
551
552        if ( $callable instanceof Closure ) {
553            $func = new ReflectionFunction( $callable );
554            $cls = $func->getClosureCalledClass();
555            if ( $func->getClosureThis() && $cls ) {
556                return "({$cls->getName()})->{$func->getName()}(...)";
557            } elseif ( $cls ) {
558                return "{$cls->getName()}::{$func->getName()}(...)";
559            } else {
560                return "{$func->getName()}(...)";
561            }
562        }
563
564        if ( is_array( $callable ) ) {
565            [ $on, $func ] = $callable;
566
567            if ( is_object( $on ) ) {
568                $on = get_class( $on );
569            }
570
571            return "$on::$func";
572        }
573
574        throw new InvalidArgumentException( 'Unexpected kind of callable' );
575    }
576
577    /**
578     * Returns the default handler method name for the given hook.
579     *
580     * @param string $hook
581     *
582     * @return string
583     */
584    private function getHookMethodName( string $hook ): string {
585        $hook = strtr( $hook, ':\\-', '___' );
586        return "on$hook";
587    }
588
589    /**
590     * Replacement for is_callable that will also return true when the callable uses a class
591     * that cannot be loaded.
592     *
593     * This may legitimately happen when a hook handler uses a hook interfaces that is defined
594     * in another extension. In that case, the hook itself is also defined in the other extension,
595     * so the hook will never be called and no problem arises.
596     *
597     * However, it is entirely possible to register broken handlers for hooks that will indeed
598     * be called, causing an error. This is intentional: we don't want to silently ignore
599     * mistakes like mistyped class names in a hook handler registration.
600     *
601     * @param mixed $v
602     *
603     * @return bool
604     */
605    private static function mayBeCallable( $v ): bool {
606        try {
607            return is_callable( $v );
608        } catch ( Error $error ) {
609            // If the callable uses a class that can't be loaded because it extends an unknown base class.
610            // Continue as if is_callable had returned true, to allow the handler to be registered.
611            if ( preg_match( '/Class.*not found/', $error->getMessage() ) ) {
612                return true;
613            }
614
615            throw $error;
616        }
617    }
618}