Version 1
[yaffs-website] / web / core / lib / Drupal / Core / Extension / module.api.php
1 <?php
2
3 /**
4  * @file
5  * Hooks related to module and update systems.
6  */
7
8 use Drupal\Core\Database\Database;
9 use Drupal\Core\Url;
10 use Drupal\Core\Utility\UpdateException;
11
12
13 /**
14  * @defgroup update_api Update API
15  * @{
16  * Updating minor versions of modules
17  *
18  * When you update code in a module, you may need to update stored data so that
19  * the stored data is compatible with the new code. If this update is between
20  * two minor versions of your module within the same major version of Drupal,
21  * you can use the Update API to update the data. This API is described in brief
22  * here; for more details, see https://www.drupal.org/node/2535316. If you are
23  * updating your module for a major version of Drupal (for instance, Drupal 7 to
24  * Drupal 8), updates will not run and you will need to use the
25  * @link migrate Migrate API @endlink instead.
26  *
27  * @section sec_when When to write update code
28  * You need to provide code that performs an update to stored data whenever your
29  * module makes a change to its data model. A data model change is any change
30  * that makes stored data on an existing site incompatible with that site's
31  * updated codebase. Examples:
32  * - Configuration changes: adding/removing/renaming a config key, changing the
33  *   expected data type or value structure, changing dependencies, schema
34  *   changes, etc.
35  * - Database schema changes: adding, changing, or removing a database table or
36  *   field; moving stored data to different fields or tables; changing the
37  *   format of stored data.
38  * - Content entity or field changes: adding, changing, or removing a field
39  *   definition, entity definition, or any of their properties.
40  *
41  * @section sec_how How to write update code
42  * Update code for a module is put into an implementation of hook_update_N(),
43  * which goes into file mymodule.install (if your module's machine name is
44  * mymodule). See the documentation of hook_update_N() and
45  * https://www.drupal.org/node/2535316 for details and examples.
46  *
47  * @section sec_test Testing update code
48  * Update code should be tested both manually and by writing an automated test.
49  * Automated tests for update code extend
50  * \Drupal\system\Tests\Update\UpdatePathTestBase -- see that class for details,
51  * and find classes that extend it for examples.
52  *
53  * @see migration
54  * @}
55  */
56
57 /**
58  * @addtogroup hooks
59  * @{
60  */
61
62 /**
63  * Defines one or more hooks that are exposed by a module.
64  *
65  * Normally hooks do not need to be explicitly defined. However, by declaring a
66  * hook explicitly, a module may define a "group" for it. Modules that implement
67  * a hook may then place their implementation in either $module.module or in
68  * $module.$group.inc. If the hook is located in $module.$group.inc, then that
69  * file will be automatically loaded when needed.
70  * In general, hooks that are rarely invoked and/or are very large should be
71  * placed in a separate include file, while hooks that are very short or very
72  * frequently called should be left in the main module file so that they are
73  * always available.
74  *
75  * See system_hook_info() for all hook groups defined by Drupal core.
76  *
77  * @return
78  *   An associative array whose keys are hook names and whose values are an
79  *   associative array containing:
80  *   - group: A string defining the group to which the hook belongs. The module
81  *     system will determine whether a file with the name $module.$group.inc
82  *     exists, and automatically load it when required.
83  *
84  * @see hook_hook_info_alter()
85  */
86 function hook_hook_info() {
87   $hooks['token_info'] = [
88     'group' => 'tokens',
89   ];
90   $hooks['tokens'] = [
91     'group' => 'tokens',
92   ];
93   return $hooks;
94 }
95
96 /**
97  * Alter the registry of modules implementing a hook.
98  *
99  * This hook is invoked during \Drupal::moduleHandler()->getImplementations().
100  * A module may implement this hook in order to reorder the implementing
101  * modules, which are otherwise ordered by the module's system weight.
102  *
103  * Note that hooks invoked using \Drupal::moduleHandler->alter() can have
104  * multiple variations(such as hook_form_alter() and hook_form_FORM_ID_alter()).
105  * \Drupal::moduleHandler->alter() will call all such variants defined by a
106  * single module in turn. For the purposes of hook_module_implements_alter(),
107  * these variants are treated as a single hook. Thus, to ensure that your
108  * implementation of hook_form_FORM_ID_alter() is called at the right time,
109  * you will have to change the order of hook_form_alter() implementation in
110  * hook_module_implements_alter().
111  *
112  * @param $implementations
113  *   An array keyed by the module's name. The value of each item corresponds
114  *   to a $group, which is usually FALSE, unless the implementation is in a
115  *   file named $module.$group.inc.
116  * @param $hook
117  *   The name of the module hook being implemented.
118  */
119 function hook_module_implements_alter(&$implementations, $hook) {
120   if ($hook == 'form_alter') {
121     // Move my_module_form_alter() to the end of the list.
122     // \Drupal::moduleHandler()->getImplementations()
123     // iterates through $implementations with a foreach loop which PHP iterates
124     // in the order that the items were added, so to move an item to the end of
125     // the array, we remove it and then add it.
126     $group = $implementations['my_module'];
127     unset($implementations['my_module']);
128     $implementations['my_module'] = $group;
129   }
130 }
131
132 /**
133  * Alter the information parsed from module and theme .info.yml files.
134  *
135  * This hook is invoked in _system_rebuild_module_data() and in
136  * \Drupal\Core\Extension\ThemeHandlerInterface::rebuildThemeData(). A module
137  * may implement this hook in order to add to or alter the data generated by
138  * reading the .info.yml file with \Drupal\Core\Extension\InfoParser.
139  *
140  * Using implementations of this hook to make modules required by setting the
141  * $info['required'] key is discouraged. Doing so will slow down the module
142  * installation and uninstallation process. Instead, use
143  * \Drupal\Core\Extension\ModuleUninstallValidatorInterface.
144  *
145  * @param array $info
146  *   The .info.yml file contents, passed by reference so that it can be altered.
147  * @param \Drupal\Core\Extension\Extension $file
148  *   Full information about the module or theme.
149  * @param string $type
150  *   Either 'module' or 'theme', depending on the type of .info.yml file that
151  *   was passed.
152  *
153  * @see \Drupal\Core\Extension\ModuleUninstallValidatorInterface
154  */
155 function hook_system_info_alter(array &$info, \Drupal\Core\Extension\Extension $file, $type) {
156   // Only fill this in if the .info.yml file does not define a 'datestamp'.
157   if (empty($info['datestamp'])) {
158     $info['datestamp'] = $file->getMTime();
159   }
160 }
161
162 /**
163  * Perform necessary actions before a module is installed.
164  *
165  * @param string $module
166  *   The name of the module about to be installed.
167  */
168 function hook_module_preinstall($module) {
169   mymodule_cache_clear();
170 }
171
172 /**
173  * Perform necessary actions after modules are installed.
174  *
175  * This function differs from hook_install() in that it gives all other modules
176  * a chance to perform actions when a module is installed, whereas
177  * hook_install() is only called on the module actually being installed. See
178  * \Drupal\Core\Extension\ModuleInstaller::install() for a detailed description of
179  * the order in which install hooks are invoked.
180  *
181  * This hook should be implemented in a .module file, not in an .install file.
182  *
183  * @param $modules
184  *   An array of the modules that were installed.
185  *
186  * @see \Drupal\Core\Extension\ModuleInstaller::install()
187  * @see hook_install()
188  */
189 function hook_modules_installed($modules) {
190   if (in_array('lousy_module', $modules)) {
191     \Drupal::state()->set('mymodule.lousy_module_compatibility', TRUE);
192   }
193 }
194
195 /**
196  * Perform setup tasks when the module is installed.
197  *
198  * If the module implements hook_schema(), the database tables will
199  * be created before this hook is fired.
200  *
201  * If the module provides a MODULE.routing.yml or alters routing information
202  * these changes will not be available when this hook is fired. If up-to-date
203  * router information is required, for example to use \Drupal\Core\Url, then
204  * (preferably) use hook_modules_installed() or rebuild the router in the
205  * hook_install() implementation.
206  *
207  * Implementations of this hook are by convention declared in the module's
208  * .install file. The implementation can rely on the .module file being loaded.
209  * The hook will only be called when a module is installed. The module's schema
210  * version will be set to the module's greatest numbered update hook. Because of
211  * this, any time a hook_update_N() is added to the module, this function needs
212  * to be updated to reflect the current version of the database schema.
213  *
214  * See the @link https://www.drupal.org/node/146843 Schema API documentation
215  * @endlink for details on hook_schema and how database tables are defined.
216  *
217  * Note that since this function is called from a full bootstrap, all functions
218  * (including those in modules enabled by the current page request) are
219  * available when this hook is called. Use cases could be displaying a user
220  * message, or calling a module function necessary for initial setup, etc.
221  *
222  * Please be sure that anything added or modified in this function that can
223  * be removed during uninstall should be removed with hook_uninstall().
224  *
225  * @see hook_schema()
226  * @see \Drupal\Core\Extension\ModuleInstaller::install()
227  * @see hook_uninstall()
228  * @see hook_modules_installed()
229  */
230 function hook_install() {
231   // Create the styles directory and ensure it's writable.
232   $directory = file_default_scheme() . '://styles';
233   $mode = isset($GLOBALS['install_state']['mode']) ? $GLOBALS['install_state']['mode'] : NULL;
234   file_prepare_directory($directory, FILE_CREATE_DIRECTORY | FILE_MODIFY_PERMISSIONS, $mode);
235 }
236
237 /**
238  * Perform necessary actions before a module is uninstalled.
239  *
240  * @param string $module
241  *   The name of the module about to be uninstalled.
242  */
243 function hook_module_preuninstall($module) {
244   mymodule_cache_clear();
245 }
246
247 /**
248  * Perform necessary actions after modules are uninstalled.
249  *
250  * This function differs from hook_uninstall() in that it gives all other
251  * modules a chance to perform actions when a module is uninstalled, whereas
252  * hook_uninstall() is only called on the module actually being uninstalled.
253  *
254  * It is recommended that you implement this hook if your module stores
255  * data that may have been set by other modules.
256  *
257  * @param $modules
258  *   An array of the modules that were uninstalled.
259  *
260  * @see hook_uninstall()
261  */
262 function hook_modules_uninstalled($modules) {
263   if (in_array('lousy_module', $modules)) {
264     \Drupal::state()->delete('mymodule.lousy_module_compatibility');
265   }
266   mymodule_cache_rebuild();
267 }
268
269 /**
270  * Remove any information that the module sets.
271  *
272  * The information that the module should remove includes:
273  * - state that the module has set using \Drupal::state()
274  * - modifications to existing tables
275  *
276  * The module should not remove its entry from the module configuration.
277  * Database tables defined by hook_schema() will be removed automatically.
278  *
279  * The uninstall hook must be implemented in the module's .install file. It
280  * will fire when the module gets uninstalled but before the module's database
281  * tables are removed, allowing your module to query its own tables during
282  * this routine.
283  *
284  * @see hook_install()
285  * @see hook_schema()
286  * @see hook_modules_uninstalled()
287  */
288 function hook_uninstall() {
289   // Remove the styles directory and generated images.
290   file_unmanaged_delete_recursive(file_default_scheme() . '://styles');
291 }
292
293 /**
294  * Return an array of tasks to be performed by an installation profile.
295  *
296  * Any tasks you define here will be run, in order, after the installer has
297  * finished the site configuration step but before it has moved on to the
298  * final import of languages and the end of the installation. This is invoked
299  * by install_tasks(). You can have any number of custom tasks to perform
300  * during this phase.
301  *
302  * Each task you define here corresponds to a callback function which you must
303  * separately define and which is called when your task is run. This function
304  * will receive the global installation state variable, $install_state, as
305  * input, and has the opportunity to access or modify any of its settings. See
306  * the install_state_defaults() function in the installer for the list of
307  * $install_state settings used by Drupal core.
308  *
309  * At the end of your task function, you can indicate that you want the
310  * installer to pause and display a page to the user by returning any themed
311  * output that should be displayed on that page (but see below for tasks that
312  * use the form API or batch API; the return values of these task functions are
313  * handled differently). You should also use #title within the task
314  * callback function to set a custom page title. For some tasks, however, you
315  * may want to simply do some processing and pass control to the next task
316  * without ending the page request; to indicate this, simply do not send back
317  * a return value from your task function at all. This can be used, for
318  * example, by installation profiles that need to configure certain site
319  * settings in the database without obtaining any input from the user.
320  *
321  * The task function is treated specially if it defines a form or requires
322  * batch processing; in that case, you should return either the form API
323  * definition or batch API array, as appropriate. See below for more
324  * information on the 'type' key that you must define in the task definition
325  * to inform the installer that your task falls into one of those two
326  * categories. It is important to use these APIs directly, since the installer
327  * may be run non-interactively (for example, via a command line script), all
328  * in one page request; in that case, the installer will automatically take
329  * care of submitting forms and processing batches correctly for both types of
330  * installations. You can inspect the $install_state['interactive'] boolean to
331  * see whether or not the current installation is interactive, if you need
332  * access to this information.
333  *
334  * Remember that a user installing Drupal interactively will be able to reload
335  * an installation page multiple times, so you should use \Drupal::state() to
336  * store any data that you may need later in the installation process. Any
337  * temporary state must be removed using \Drupal::state()->delete() before
338  * your last task has completed and control is handed back to the installer.
339  *
340  * @param array $install_state
341  *   An array of information about the current installation state.
342  *
343  * @return array
344  *   A keyed array of tasks the profile will perform during the final stage of
345  *   the installation. Each key represents the name of a function (usually a
346  *   function defined by this profile, although that is not strictly required)
347  *   that is called when that task is run. The values are associative arrays
348  *   containing the following key-value pairs (all of which are optional):
349  *   - display_name: The human-readable name of the task. This will be
350  *     displayed to the user while the installer is running, along with a list
351  *     of other tasks that are being run. Leave this unset to prevent the task
352  *     from appearing in the list.
353  *   - display: This is a boolean which can be used to provide finer-grained
354  *     control over whether or not the task will display. This is mostly useful
355  *     for tasks that are intended to display only under certain conditions;
356  *     for these tasks, you can set 'display_name' to the name that you want to
357  *     display, but then use this boolean to hide the task only when certain
358  *     conditions apply.
359  *   - type: A string representing the type of task. This parameter has three
360  *     possible values:
361  *     - normal: (default) This indicates that the task will be treated as a
362  *       regular callback function, which does its processing and optionally
363  *       returns HTML output.
364  *     - batch: This indicates that the task function will return a batch API
365  *       definition suitable for batch_set() or an array of batch definitions
366  *       suitable for consecutive batch_set() calls. The installer will then
367  *       take care of automatically running the task via batch processing.
368  *     - form: This indicates that the task function will return a standard
369  *       form API definition (and separately define validation and submit
370  *       handlers, as appropriate). The installer will then take care of
371  *       automatically directing the user through the form submission process.
372  *   - run: A constant representing the manner in which the task will be run.
373  *     This parameter has three possible values:
374  *     - INSTALL_TASK_RUN_IF_NOT_COMPLETED: (default) This indicates that the
375  *       task will run once during the installation of the profile.
376  *     - INSTALL_TASK_SKIP: This indicates that the task will not run during
377  *       the current installation page request. It can be used to skip running
378  *       an installation task when certain conditions are met, even though the
379  *       task may still show on the list of installation tasks presented to the
380  *       user.
381  *     - INSTALL_TASK_RUN_IF_REACHED: This indicates that the task will run on
382  *       each installation page request that reaches it. This is rarely
383  *       necessary for an installation profile to use; it is primarily used by
384  *       the Drupal installer for bootstrap-related tasks.
385  *   - function: Normally this does not need to be set, but it can be used to
386  *     force the installer to call a different function when the task is run
387  *     (rather than the function whose name is given by the array key). This
388  *     could be used, for example, to allow the same function to be called by
389  *     two different tasks.
390  *
391  * @see install_state_defaults()
392  * @see batch_set()
393  * @see hook_install_tasks_alter()
394  * @see install_tasks()
395  */
396 function hook_install_tasks(&$install_state) {
397   // Here, we define a variable to allow tasks to indicate that a particular,
398   // processor-intensive batch process needs to be triggered later on in the
399   // installation.
400   $myprofile_needs_batch_processing = \Drupal::state()->get('myprofile.needs_batch_processing', FALSE);
401   $tasks = [
402     // This is an example of a task that defines a form which the user who is
403     // installing the site will be asked to fill out. To implement this task,
404     // your profile would define a function named myprofile_data_import_form()
405     // as a normal form API callback function, with associated validation and
406     // submit handlers. In the submit handler, in addition to saving whatever
407     // other data you have collected from the user, you might also call
408     // \Drupal::state()->set('myprofile.needs_batch_processing', TRUE) if the
409     // user has entered data which requires that batch processing will need to
410     // occur later on.
411     'myprofile_data_import_form' => [
412       'display_name' => t('Data import options'),
413       'type' => 'form',
414     ],
415     // Similarly, to implement this task, your profile would define a function
416     // named myprofile_settings_form() with associated validation and submit
417     // handlers. This form might be used to collect and save additional
418     // information from the user that your profile needs. There are no extra
419     // steps required for your profile to act as an "installation wizard"; you
420     // can simply define as many tasks of type 'form' as you wish to execute,
421     // and the forms will be presented to the user, one after another.
422     'myprofile_settings_form' => [
423       'display_name' => t('Additional options'),
424       'type' => 'form',
425     ],
426     // This is an example of a task that performs batch operations. To
427     // implement this task, your profile would define a function named
428     // myprofile_batch_processing() which returns a batch API array definition
429     // that the installer will use to execute your batch operations. Due to the
430     // 'myprofile.needs_batch_processing' variable used here, this task will be
431     // hidden and skipped unless your profile set it to TRUE in one of the
432     // previous tasks.
433     'myprofile_batch_processing' => [
434       'display_name' => t('Import additional data'),
435       'display' => $myprofile_needs_batch_processing,
436       'type' => 'batch',
437       'run' => $myprofile_needs_batch_processing ? INSTALL_TASK_RUN_IF_NOT_COMPLETED : INSTALL_TASK_SKIP,
438     ],
439     // This is an example of a task that will not be displayed in the list that
440     // the user sees. To implement this task, your profile would define a
441     // function named myprofile_final_site_setup(), in which additional,
442     // automated site setup operations would be performed. Since this is the
443     // last task defined by your profile, you should also use this function to
444     // call \Drupal::state()->delete('myprofile.needs_batch_processing') and
445     // clean up the state that was used above. If you want the user to pass
446     // to the final Drupal installation tasks uninterrupted, return no output
447     // from this function. Otherwise, return themed output that the user will
448     // see (for example, a confirmation page explaining that your profile's
449     // tasks are complete, with a link to reload the current page and therefore
450     // pass on to the final Drupal installation tasks when the user is ready to
451     // do so).
452     'myprofile_final_site_setup' => [
453     ],
454   ];
455   return $tasks;
456 }
457
458 /**
459  * Alter the full list of installation tasks.
460  *
461  * You can use this hook to change or replace any part of the Drupal
462  * installation process that occurs after the installation profile is selected.
463  *
464  * This hook is invoked on the install profile in install_tasks().
465  *
466  * @param $tasks
467  *   An array of all available installation tasks, including those provided by
468  *   Drupal core. You can modify this array to change or replace individual
469  *   steps within the installation process.
470  * @param $install_state
471  *   An array of information about the current installation state.
472  *
473  * @see hook_install_tasks()
474  * @see install_tasks()
475  */
476 function hook_install_tasks_alter(&$tasks, $install_state) {
477   // Replace the entire site configuration form provided by Drupal core
478   // with a custom callback function defined by this installation profile.
479   $tasks['install_configure_form']['function'] = 'myprofile_install_configure_form';
480 }
481
482 /**
483  * Perform a single update between minor versions.
484  *
485  * hook_update_N() can only be used to update between minor versions of a
486  * module. To upgrade between major versions of Drupal (for example, between
487  * Drupal 7 and 8), use the @link migrate Migrate API @endlink instead.
488  *
489  * @section sec_naming Naming and documenting your function
490  * For each change in a module that requires one or more actions to be performed
491  * when updating a site, add a new implementation of hook_update_N() to your
492  * mymodule.install file (assuming mymodule is the machine name of your module).
493  * Implementations of hook_update_N() are named (module name)_update_(number).
494  * The numbers are normally composed of three parts:
495  * - 1 or 2 digits for Drupal core compatibility (Drupal 8, 9, 10, etc.). This
496  *   convention must be followed.
497  * - 1 digit for your module's major release version; for example, for 8.x-1.*
498  *   use 1, for 8.x-2.* use 2, for Core 8.0.x use 0, and for Core 8.1.x use 1.
499  *   This convention is optional but suggested for clarity.
500  * - 2 digits for sequential counting, starting with 01. Note that the x000
501  *   number can never be used: the lowest update number that will be recognized
502  *   and run for major version x is x001.
503  * Examples:
504  * - node_update_8001(): The first update for the Drupal 8.0.x version of the
505  *   Drupal Core node module.
506  * - mymodule_update_8101(): The first update for your custom or contributed
507  *   module's 8.x-1.x versions.
508  * - mymodule_update_8201(): The first update for the 8.x-2.x versions.
509  *
510  * Never renumber update functions. The numeric part of the hook implementation
511  * function is stored in the database to keep track of which updates have run,
512  * so it is important to maintain this information consistently.
513  *
514  * The documentation block preceding this function is stripped of newlines and
515  * used as the description for the update on the pending updates task list,
516  * which users will see when they run the update.php script.
517  *
518  * @section sec_notes Notes about the function body
519  * Writing hook_update_N() functions is tricky. There are several reasons why
520  * this is the case:
521  * - You do not know when updates will be run: someone could be keeping up with
522  *   every update and run them when the database and code are in the same state
523  *   as when you wrote your update function, or they could have waited until a
524  *   few more updates have come out, and run several at the same time.
525  * - You do not know the state of other modules' updates either.
526  * - Other modules can use hook_update_dependencies() to run updates between
527  *   your module's updates, so you also cannot count on your functions running
528  *   right after one another.
529  * - You do not know what environment your update will run in (which modules
530  *   are installed, whether certain hooks are implemented or not, whether
531  *   services are overridden, etc.).
532  *
533  * Because of these reasons, you'll need to use care in writing your update
534  * function. Some things to think about:
535  * - Never assume that the database schema is the same when the update will run
536  *   as it is when you wrote the update function. So, when updating a database
537  *   table or field, put the schema information you want to update to directly
538  *   into your function instead of calling your hook_schema() function to
539  *   retrieve it (this is one case where the right thing to do is copy and paste
540  *   the code).
541  * - Never assume that the configuration schema is the same when the update will
542  *   run as it is when you wrote the update function. So, when saving
543  *   configuration, use the $has_trusted_data = TRUE parameter so that schema is
544  *   ignored, and make sure that the configuration data you are saving matches
545  *   the configuration schema at the time when you write the update function
546  *   (later updates may change it again to match new schema changes).
547  * - Never assume your field or entity type definitions are the same when the
548  *   update will run as they are when you wrote the update function. Always
549  *   retrieve the correct version via
550  *   \Drupal::entityDefinitionUpdateManager()::getEntityType() or
551  *   \Drupal::entityDefinitionUpdateManager()::getFieldStorageDefinition(). When
552  *   adding a new definition always replicate it in the update function body as
553  *   you would do with a schema definition.
554  * - Never call \Drupal::entityDefinitionUpdateManager()::applyUpdates() in an
555  *   update function, as it will apply updates for any module not only yours,
556  *   which will lead to unpredictable results.
557  * - Be careful about API functions and especially CRUD operations that you use
558  *   in your update function. If they invoke hooks or use services, they may
559  *   not behave as expected, and it may actually not be appropriate to use the
560  *   normal API functions that invoke all the hooks, use the database schema,
561  *   and/or use services in an update function -- you may need to switch to
562  *   using a more direct method (database query, etc.).
563  * - In particular, loading, saving, or performing any other CRUD operation on
564  *   an entity is never safe to do (they always involve hooks and services).
565  * - Never rebuild the router during an update function.
566  *
567  * The following actions are examples of things that are safe to do during
568  * updates:
569  * - Cache invalidation.
570  * - Using \Drupal::configFactory()->getEditable() and \Drupal::config(), as
571  *   long as you make sure that your update data matches the schema, and you
572  *   use the $has_trusted_data argument in the save operation.
573  * - Marking a container for rebuild.
574  * - Using the API provided by \Drupal::entityDefinitionUpdateManager() to
575  *   update the entity schema based on changes in entity type or field
576  *   definitions provided by your module.
577  *
578  * See https://www.drupal.org/node/2535316 for more on writing update functions.
579  *
580  * @section sec_bulk Batch updates
581  * If running your update all at once could possibly cause PHP to time out, use
582  * the $sandbox parameter to indicate that the Batch API should be used for your
583  * update. In this case, your update function acts as an implementation of
584  * callback_batch_operation(), and $sandbox acts as the batch context
585  * parameter. In your function, read the state information from the previous
586  * run from $sandbox (or initialize), run a chunk of updates, save the state in
587  * $sandbox, and set $sandbox['#finished'] to a value between 0 and 1 to
588  * indicate the percent completed, or 1 if it is finished (you need to do this
589  * explicitly in each pass).
590  *
591  * See the @link batch Batch operations topic @endlink for more information on
592  * how to use the Batch API.
593  *
594  * @param array $sandbox
595  *   Stores information for batch updates. See above for more information.
596  *
597  * @return string|null
598  *   Optionally, update hooks may return a translated string that will be
599  *   displayed to the user after the update has completed. If no message is
600  *   returned, no message will be presented to the user.
601  *
602  * @throws \Drupal\Core\Utility\UpdateException|PDOException
603  *   In case of error, update hooks should throw an instance of
604  *   Drupal\Core\Utility\UpdateException with a meaningful message for the user.
605  *   If a database query fails for whatever reason, it will throw a
606  *   PDOException.
607  *
608  * @ingroup update_api
609  *
610  * @see batch
611  * @see schemaapi
612  * @see hook_update_last_removed()
613  * @see update_get_update_list()
614  * @see \Drupal\Core\Entity\EntityDefinitionUpdateManagerInterface
615  * @see node_update_8001
616  * @see system_update_8004
617  * @see https://www.drupal.org/node/2535316
618  */
619 function hook_update_N(&$sandbox) {
620   // For non-batch updates, the signature can simply be:
621   // function hook_update_N() {
622
623   // Example function body for adding a field to a database table, which does
624   // not require a batch operation:
625   $spec = [
626     'type' => 'varchar',
627     'description' => "New Col",
628     'length' => 20,
629     'not null' => FALSE,
630   ];
631   $schema = Database::getConnection()->schema();
632   $schema->addField('mytable1', 'newcol', $spec);
633
634   // Example of what to do if there is an error during your update.
635   if ($some_error_condition_met) {
636     throw new UpdateException('Something went wrong; here is what you should do.');
637   }
638
639   // Example function body for a batch update. In this example, the values in
640   // a database field are updated.
641   if (!isset($sandbox['progress'])) {
642     // This must be the first run. Initialize the sandbox.
643     $sandbox['progress'] = 0;
644     $sandbox['current_pk'] = 0;
645     $sandbox['max'] = Database::getConnection()->query('SELECT COUNT(myprimarykey) FROM {mytable1}')->fetchField() - 1;
646   }
647
648   // Update in chunks of 20.
649   $records = Database::getConnection()->select('mytable1', 'm')
650     ->fields('m', ['myprimarykey', 'otherfield'])
651     ->condition('myprimarykey', $sandbox['current_pk'], '>')
652     ->range(0, 20)
653     ->orderBy('myprimarykey', 'ASC')
654     ->execute();
655   foreach ($records as $record) {
656     // Here, you would make an update something related to this record. In this
657     // example, some text is added to the other field.
658     Database::getConnection()->update('mytable1')
659       ->fields(['otherfield' => $record->otherfield . '-suffix'])
660       ->condition('myprimarykey', $record->myprimarykey)
661       ->execute();
662
663     $sandbox['progress']++;
664     $sandbox['current_pk'] = $record->myprimarykey;
665   }
666
667   $sandbox['#finished'] = empty($sandbox['max']) ? 1 : ($sandbox['progress'] / $sandbox['max']);
668
669   // To display a message to the user when the update is completed, return it.
670   // If you do not want to display a completion message, return nothing.
671   return t('All foo bars were updated with the new suffix');
672 }
673
674 /**
675  * Executes an update which is intended to update data, like entities.
676  *
677  * These implementations have to be placed in a MODULE.post_update.php file.
678  *
679  * These updates are executed after all hook_update_N() implementations. At this
680  * stage Drupal is already fully repaired so you can use any API as you wish.
681  *
682  * NAME can be arbitrary machine names. In contrast to hook_update_N() the order
683  * of functions in the file is the only thing which ensures the execution order
684  * of those functions.
685  *
686  * Drupal also ensures to not execute the same hook_post_update_NAME() function
687  * twice.
688  *
689  * @param array $sandbox
690  *   Stores information for batch updates. See above for more information.
691  *
692  * @return string|null
693  *   Optionally, hook_post_update_NAME() hooks may return a translated string
694  *   that will be displayed to the user after the update has completed. If no
695  *   message is returned, no message will be presented to the user.
696  *
697  * @throws \Drupal\Core\Utility\UpdateException|PDOException
698  *   In case of error, update hooks should throw an instance of
699  *   \Drupal\Core\Utility\UpdateException with a meaningful message for the
700  *   user. If a database query fails for whatever reason, it will throw a
701  *   PDOException.
702  *
703  * @ingroup update_api
704  *
705  * @see hook_update_N()
706  */
707 function hook_post_update_NAME(&$sandbox) {
708   // Example of updating some content.
709   $node = \Drupal\node\Entity\Node::load(123);
710   $node->setTitle('foo');
711   $node->save();
712
713   $result = t('Node %nid saved', ['%nid' => $node->id()]);
714
715   // Example of disabling blocks with missing condition contexts. Note: The
716   // block itself is in a state which is valid at that point.
717   // @see block_update_8001()
718   // @see block_post_update_disable_blocks_with_missing_contexts()
719   $block_update_8001 = \Drupal::keyValue('update_backup')->get('block_update_8001', []);
720
721   $block_ids = array_keys($block_update_8001);
722   $block_storage = \Drupal::entityManager()->getStorage('block');
723   $blocks = $block_storage->loadMultiple($block_ids);
724   /** @var $blocks \Drupal\block\BlockInterface[] */
725   foreach ($blocks as $block) {
726     // This block has had conditions removed due to an inability to resolve
727     // contexts in block_update_8001() so disable it.
728
729     // Disable currently enabled blocks.
730     if ($block_update_8001[$block->id()]['status']) {
731       $block->setStatus(FALSE);
732       $block->save();
733     }
734   }
735
736   return $result;
737 }
738
739 /**
740  * Return an array of information about module update dependencies.
741  *
742  * This can be used to indicate update functions from other modules that your
743  * module's update functions depend on, or vice versa. It is used by the update
744  * system to determine the appropriate order in which updates should be run, as
745  * well as to search for missing dependencies.
746  *
747  * Implementations of this hook should be placed in a mymodule.install file in
748  * the same directory as mymodule.module.
749  *
750  * @return
751  *   A multidimensional array containing information about the module update
752  *   dependencies. The first two levels of keys represent the module and update
753  *   number (respectively) for which information is being returned, and the
754  *   value is an array of information about that update's dependencies. Within
755  *   this array, each key represents a module, and each value represents the
756  *   number of an update function within that module. In the event that your
757  *   update function depends on more than one update from a particular module,
758  *   you should always list the highest numbered one here (since updates within
759  *   a given module always run in numerical order).
760  *
761  * @ingroup update_api
762  *
763  * @see update_resolve_dependencies()
764  * @see hook_update_N()
765  */
766 function hook_update_dependencies() {
767   // Indicate that the mymodule_update_8001() function provided by this module
768   // must run after the another_module_update_8003() function provided by the
769   // 'another_module' module.
770   $dependencies['mymodule'][8001] = [
771     'another_module' => 8003,
772   ];
773   // Indicate that the mymodule_update_8002() function provided by this module
774   // must run before the yet_another_module_update_8005() function provided by
775   // the 'yet_another_module' module. (Note that declaring dependencies in this
776   // direction should be done only in rare situations, since it can lead to the
777   // following problem: If a site has already run the yet_another_module
778   // module's database updates before it updates its codebase to pick up the
779   // newest mymodule code, then the dependency declared here will be ignored.)
780   $dependencies['yet_another_module'][8005] = [
781     'mymodule' => 8002,
782   ];
783   return $dependencies;
784 }
785
786 /**
787  * Return a number which is no longer available as hook_update_N().
788  *
789  * If you remove some update functions from your mymodule.install file, you
790  * should notify Drupal of those missing functions. This way, Drupal can
791  * ensure that no update is accidentally skipped.
792  *
793  * Implementations of this hook should be placed in a mymodule.install file in
794  * the same directory as mymodule.module.
795  *
796  * @return
797  *   An integer, corresponding to hook_update_N() which has been removed from
798  *   mymodule.install.
799  *
800  * @ingroup update_api
801  *
802  * @see hook_update_N()
803  */
804 function hook_update_last_removed() {
805   // We've removed the 8.x-1.x version of mymodule, including database updates.
806   // The next update function is mymodule_update_8200().
807   return 8103;
808 }
809
810 /**
811  * Provide information on Updaters (classes that can update Drupal).
812  *
813  * Drupal\Core\Updater\Updater is a class that knows how to update various parts
814  * of the Drupal file system, for example to update modules that have newer
815  * releases, or to install a new theme.
816  *
817  * @return
818  *   An associative array of information about the updater(s) being provided.
819  *   This array is keyed by a unique identifier for each updater, and the
820  *   values are subarrays that can contain the following keys:
821  *   - class: The name of the PHP class which implements this updater.
822  *   - name: Human-readable name of this updater.
823  *   - weight: Controls what order the Updater classes are consulted to decide
824  *     which one should handle a given task. When an update task is being run,
825  *     the system will loop through all the Updater classes defined in this
826  *     registry in weight order and let each class respond to the task and
827  *     decide if each Updater wants to handle the task. In general, this
828  *     doesn't matter, but if you need to override an existing Updater, make
829  *     sure your Updater has a lighter weight so that it comes first.
830  *
831  * @ingroup update_api
832  *
833  * @see drupal_get_updaters()
834  * @see hook_updater_info_alter()
835  */
836 function hook_updater_info() {
837   return [
838     'module' => [
839       'class' => 'Drupal\Core\Updater\Module',
840       'name' => t('Update modules'),
841       'weight' => 0,
842     ],
843     'theme' => [
844       'class' => 'Drupal\Core\Updater\Theme',
845       'name' => t('Update themes'),
846       'weight' => 0,
847     ],
848   ];
849 }
850
851 /**
852  * Alter the Updater information array.
853  *
854  * An Updater is a class that knows how to update various parts of the Drupal
855  * file system, for example to update modules that have newer releases, or to
856  * install a new theme.
857  *
858  * @param array $updaters
859  *   Associative array of updaters as defined through hook_updater_info().
860  *   Alter this array directly.
861  *
862  * @ingroup update_api
863  *
864  * @see drupal_get_updaters()
865  * @see hook_updater_info()
866  */
867 function hook_updater_info_alter(&$updaters) {
868   // Adjust weight so that the theme Updater gets a chance to handle a given
869   // update task before module updaters.
870   $updaters['theme']['weight'] = -1;
871 }
872
873 /**
874  * Check installation requirements and do status reporting.
875  *
876  * This hook has three closely related uses, determined by the $phase argument:
877  * - Checking installation requirements ($phase == 'install').
878  * - Checking update requirements ($phase == 'update').
879  * - Status reporting ($phase == 'runtime').
880  *
881  * Note that this hook, like all others dealing with installation and updates,
882  * must reside in a module_name.install file, or it will not properly abort
883  * the installation of the module if a critical requirement is missing.
884  *
885  * During the 'install' phase, modules can for example assert that
886  * library or server versions are available or sufficient.
887  * Note that the installation of a module can happen during installation of
888  * Drupal itself (by install.php) with an installation profile or later by hand.
889  * As a consequence, install-time requirements must be checked without access
890  * to the full Drupal API, because it is not available during install.php.
891  * If a requirement has a severity of REQUIREMENT_ERROR, install.php will abort
892  * or at least the module will not install.
893  * Other severity levels have no effect on the installation.
894  * Module dependencies do not belong to these installation requirements,
895  * but should be defined in the module's .info.yml file.
896  *
897  * During installation (when $phase == 'install'), if you need to load a class
898  * from your module, you'll need to include the class file directly.
899  *
900  * The 'runtime' phase is not limited to pure installation requirements
901  * but can also be used for more general status information like maintenance
902  * tasks and security issues.
903  * The returned 'requirements' will be listed on the status report in the
904  * administration section, with indication of the severity level.
905  * Moreover, any requirement with a severity of REQUIREMENT_ERROR severity will
906  * result in a notice on the administration configuration page.
907  *
908  * @param $phase
909  *   The phase in which requirements are checked:
910  *   - install: The module is being installed.
911  *   - update: The module is enabled and update.php is run.
912  *   - runtime: The runtime requirements are being checked and shown on the
913  *     status report page.
914  *
915  * @return
916  *   An associative array where the keys are arbitrary but must be unique (it
917  *   is suggested to use the module short name as a prefix) and the values are
918  *   themselves associative arrays with the following elements:
919  *   - title: The name of the requirement.
920  *   - value: The current value (e.g., version, time, level, etc). During
921  *     install phase, this should only be used for version numbers, do not set
922  *     it if not applicable.
923  *   - description: The description of the requirement/status.
924  *   - severity: The requirement's result/severity level, one of:
925  *     - REQUIREMENT_INFO: For info only.
926  *     - REQUIREMENT_OK: The requirement is satisfied.
927  *     - REQUIREMENT_WARNING: The requirement failed with a warning.
928  *     - REQUIREMENT_ERROR: The requirement failed with an error.
929  */
930 function hook_requirements($phase) {
931   $requirements = [];
932
933   // Report Drupal version
934   if ($phase == 'runtime') {
935     $requirements['drupal'] = [
936       'title' => t('Drupal'),
937       'value' => \Drupal::VERSION,
938       'severity' => REQUIREMENT_INFO
939     ];
940   }
941
942   // Test PHP version
943   $requirements['php'] = [
944     'title' => t('PHP'),
945     'value' => ($phase == 'runtime') ? \Drupal::l(phpversion(), new Url('system.php')) : phpversion(),
946   ];
947   if (version_compare(phpversion(), DRUPAL_MINIMUM_PHP) < 0) {
948     $requirements['php']['description'] = t('Your PHP installation is too old. Drupal requires at least PHP %version.', ['%version' => DRUPAL_MINIMUM_PHP]);
949     $requirements['php']['severity'] = REQUIREMENT_ERROR;
950   }
951
952   // Report cron status
953   if ($phase == 'runtime') {
954     $cron_last = \Drupal::state()->get('system.cron_last');
955
956     if (is_numeric($cron_last)) {
957       $requirements['cron']['value'] = t('Last run @time ago', ['@time' => \Drupal::service('date.formatter')->formatTimeDiffSince($cron_last)]);
958     }
959     else {
960       $requirements['cron'] = [
961         'description' => t('Cron has not run. It appears cron jobs have not been setup on your system. Check the help pages for <a href=":url">configuring cron jobs</a>.', [':url' => 'https://www.drupal.org/cron']),
962         'severity' => REQUIREMENT_ERROR,
963         'value' => t('Never run'),
964       ];
965     }
966
967     $requirements['cron']['description'] .= ' ' . t('You can <a href=":cron">run cron manually</a>.', [':cron' => \Drupal::url('system.run_cron')]);
968
969     $requirements['cron']['title'] = t('Cron maintenance tasks');
970   }
971
972   return $requirements;
973 }
974
975 /**
976  * @} End of "addtogroup hooks".
977  */