system.install 89 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175
  1. <?php
  2. /**
  3. * @file
  4. * Install, update and uninstall functions for the system module.
  5. */
  6. use Drupal\Component\Utility\Crypt;
  7. use Drupal\Component\Utility\Environment;
  8. use Drupal\Component\FileSystem\FileSystem;
  9. use Drupal\Component\Utility\OpCodeCache;
  10. use Drupal\Component\Utility\Unicode;
  11. use Drupal\Core\Cache\Cache;
  12. use Drupal\Core\Path\AliasStorage;
  13. use Drupal\Core\Url;
  14. use Drupal\Core\Database\Database;
  15. use Drupal\Core\Entity\ContentEntityTypeInterface;
  16. use Drupal\Core\Entity\EntityTypeInterface;
  17. use Drupal\Core\Entity\FieldableEntityInterface;
  18. use Drupal\Core\DrupalKernel;
  19. use Drupal\Core\Field\BaseFieldDefinition;
  20. use Drupal\Core\Site\Settings;
  21. use Drupal\Core\StreamWrapper\PrivateStream;
  22. use Drupal\Core\StreamWrapper\PublicStream;
  23. use Drupal\system\SystemRequirements;
  24. use Symfony\Component\HttpFoundation\Request;
  25. /**
  26. * Implements hook_requirements().
  27. */
  28. function system_requirements($phase) {
  29. global $install_state;
  30. $requirements = [];
  31. // Report Drupal version
  32. if ($phase == 'runtime') {
  33. $requirements['drupal'] = [
  34. 'title' => t('Drupal'),
  35. 'value' => \Drupal::VERSION,
  36. 'severity' => REQUIREMENT_INFO,
  37. 'weight' => -10,
  38. ];
  39. // Display the currently active installation profile, if the site
  40. // is not running the default installation profile.
  41. $profile = drupal_get_profile();
  42. if ($profile != 'standard') {
  43. $info = system_get_info('module', $profile);
  44. $requirements['install_profile'] = [
  45. 'title' => t('Installation profile'),
  46. 'value' => t('%profile_name (%profile-%version)', [
  47. '%profile_name' => $info['name'],
  48. '%profile' => $profile,
  49. '%version' => $info['version'],
  50. ]),
  51. 'severity' => REQUIREMENT_INFO,
  52. 'weight' => -9,
  53. ];
  54. }
  55. // Warn if any experimental modules are installed.
  56. $experimental = [];
  57. $enabled_modules = \Drupal::moduleHandler()->getModuleList();
  58. foreach ($enabled_modules as $module => $data) {
  59. $info = system_get_info('module', $module);
  60. if (isset($info['package']) && $info['package'] === 'Core (Experimental)') {
  61. $experimental[$module] = $info['name'];
  62. }
  63. }
  64. if (!empty($experimental)) {
  65. $requirements['experimental'] = [
  66. 'title' => t('Experimental modules enabled'),
  67. 'value' => t('Experimental modules found: %module_list. <a href=":url">Experimental modules</a> are provided for testing purposes only. Use at your own risk.', ['%module_list' => implode(', ', $experimental), ':url' => 'https://www.drupal.org/core/experimental']),
  68. 'severity' => REQUIREMENT_WARNING,
  69. ];
  70. }
  71. }
  72. // Web server information.
  73. $request_object = \Drupal::request();
  74. $software = $request_object->server->get('SERVER_SOFTWARE');
  75. $requirements['webserver'] = [
  76. 'title' => t('Web server'),
  77. 'value' => $software,
  78. ];
  79. // Tests clean URL support.
  80. if ($phase == 'install' && $install_state['interactive'] && !$request_object->query->has('rewrite') && strpos($software, 'Apache') !== FALSE) {
  81. // If the Apache rewrite module is not enabled, Apache version must be >=
  82. // 2.2.16 because of the FallbackResource directive in the root .htaccess
  83. // file. Since the Apache version reported by the server is dependent on the
  84. // ServerTokens setting in httpd.conf, we may not be able to determine if a
  85. // given config is valid. Thus we are unable to use version_compare() as we
  86. // need have three possible outcomes: the version of Apache is greater than
  87. // 2.2.16, is less than 2.2.16, or cannot be determined accurately. In the
  88. // first case, we encourage the use of mod_rewrite; in the second case, we
  89. // raise an error regarding the minimum Apache version; in the third case,
  90. // we raise a warning that the current version of Apache may not be
  91. // supported.
  92. $rewrite_warning = FALSE;
  93. $rewrite_error = FALSE;
  94. $apache_version_string = 'Apache';
  95. // Determine the Apache version number: major, minor and revision.
  96. if (preg_match('/Apache\/(\d+)\.?(\d+)?\.?(\d+)?/', $software, $matches)) {
  97. $apache_version_string = $matches[0];
  98. // Major version number
  99. if ($matches[1] < 2) {
  100. $rewrite_error = TRUE;
  101. }
  102. elseif ($matches[1] == 2) {
  103. if (!isset($matches[2])) {
  104. $rewrite_warning = TRUE;
  105. }
  106. elseif ($matches[2] < 2) {
  107. $rewrite_error = TRUE;
  108. }
  109. elseif ($matches[2] == 2) {
  110. if (!isset($matches[3])) {
  111. $rewrite_warning = TRUE;
  112. }
  113. elseif ($matches[3] < 16) {
  114. $rewrite_error = TRUE;
  115. }
  116. }
  117. }
  118. }
  119. else {
  120. $rewrite_warning = TRUE;
  121. }
  122. if ($rewrite_warning) {
  123. $requirements['apache_version'] = [
  124. 'title' => t('Apache version'),
  125. 'value' => $apache_version_string,
  126. 'severity' => REQUIREMENT_WARNING,
  127. 'description' => t('Due to the settings for ServerTokens in httpd.conf, it is impossible to accurately determine the version of Apache running on this server. The reported value is @reported, to run Drupal without mod_rewrite, a minimum version of 2.2.16 is needed.', ['@reported' => $apache_version_string]),
  128. ];
  129. }
  130. if ($rewrite_error) {
  131. $requirements['Apache version'] = [
  132. 'title' => t('Apache version'),
  133. 'value' => $apache_version_string,
  134. 'severity' => REQUIREMENT_ERROR,
  135. 'description' => t('The minimum version of Apache needed to run Drupal without mod_rewrite enabled is 2.2.16. See the <a href=":link">enabling clean URLs</a> page for more information on mod_rewrite.', [':link' => 'http://drupal.org/node/15365']),
  136. ];
  137. }
  138. if (!$rewrite_error && !$rewrite_warning) {
  139. $requirements['rewrite_module'] = [
  140. 'title' => t('Clean URLs'),
  141. 'value' => t('Disabled'),
  142. 'severity' => REQUIREMENT_WARNING,
  143. 'description' => t('Your server is capable of using clean URLs, but it is not enabled. Using clean URLs gives an improved user experience and is recommended. <a href=":link">Enable clean URLs</a>', [':link' => 'http://drupal.org/node/15365']),
  144. ];
  145. }
  146. }
  147. // Verify the user is running a supported PHP version.
  148. // If the site is running a recommended version of PHP, just display it
  149. // as an informational message on the status report. This will be overridden
  150. // with an error or warning if the site is running older PHP versions for
  151. // which Drupal has already or will soon drop support.
  152. $phpversion = $phpversion_label = phpversion();
  153. if (function_exists('phpinfo')) {
  154. if ($phase === 'runtime') {
  155. $phpversion_label = t('@phpversion (<a href=":url">more information</a>)', ['@phpversion' => $phpversion, ':url' => (new Url('system.php'))->toString()]);
  156. }
  157. $requirements['php'] = [
  158. 'title' => t('PHP'),
  159. 'value' => $phpversion_label,
  160. ];
  161. }
  162. else {
  163. // @todo Revisit whether this description makes sense in
  164. // https://www.drupal.org/project/drupal/issues/2927318.
  165. $requirements['php'] = [
  166. 'title' => t('PHP'),
  167. 'value' => $phpversion_label,
  168. 'description' => t('The phpinfo() function has been disabled for security reasons. To see your server\'s phpinfo() information, change your PHP settings or contact your server administrator. For more information, <a href=":phpinfo">Enabling and disabling phpinfo()</a> handbook page.', [':phpinfo' => 'https://www.drupal.org/node/243993']),
  169. 'severity' => REQUIREMENT_INFO,
  170. ];
  171. }
  172. if (version_compare($phpversion, DRUPAL_MINIMUM_PHP) < 0) {
  173. $requirements['php']['description'] = t('Your PHP installation is too old. Drupal requires at least PHP %version.', ['%version' => DRUPAL_MINIMUM_PHP]);
  174. $requirements['php']['severity'] = REQUIREMENT_ERROR;
  175. // If PHP is old, it's not safe to continue with the requirements check.
  176. return $requirements;
  177. }
  178. if ((version_compare($phpversion, DRUPAL_RECOMMENDED_PHP) < 0) && ($phase === 'install' || $phase === 'runtime')) {
  179. // Warn if still on PHP 5. If at least PHP 7.0, relax from "warning" to
  180. // "info", and show it at runtime only, to not scare users while installing.
  181. if (version_compare($phpversion, '7.0') < 0) {
  182. $requirements['php']['description'] = t('Drupal will drop support for this version on March 6, 2019. Upgrade to PHP version %recommended or higher to ensure your site can receive updates and remain secure. See <a href="http://php.net/supported-versions.php">PHP\'s version support documentation</a> and the <a href=":php_requirements">Drupal 8 PHP requirements handbook page</a> for more information.', ['%recommended' => DRUPAL_RECOMMENDED_PHP, ':php_requirements' => 'https://www.drupal.org/docs/8/system-requirements/php']);
  183. $requirements['php']['severity'] = REQUIREMENT_WARNING;
  184. }
  185. else {
  186. if ($phase === 'runtime') {
  187. $requirements['php']['description'] = t('It is recommended to upgrade to PHP version %recommended or higher for the best ongoing support. See <a href="http://php.net/supported-versions.php">PHP\'s version support documentation</a> and the <a href=":php_requirements">Drupal 8 PHP requirements handbook page</a> for more information.', ['%recommended' => DRUPAL_RECOMMENDED_PHP, ':php_requirements' => 'https://www.drupal.org/docs/8/system-requirements/php']);
  188. $requirements['php']['severity'] = REQUIREMENT_INFO;
  189. }
  190. }
  191. }
  192. // Suggest to update to at least 5.5.21 or 5.6.5 for disabling multiple
  193. // statements.
  194. if (($phase === 'install' || \Drupal::database()->driver() === 'mysql') && !SystemRequirements::phpVersionWithPdoDisallowMultipleStatements($phpversion)) {
  195. $requirements['php_multiple_statement'] = [
  196. 'title' => t('PHP (multiple statement disabling)'),
  197. 'value' => $phpversion_label,
  198. 'description' => t('PHP versions higher than 5.6.5 or 5.5.21 provide built-in SQL injection protection for mysql databases. It is recommended to update.'),
  199. 'severity' => REQUIREMENT_INFO,
  200. ];
  201. }
  202. // Test for PHP extensions.
  203. $requirements['php_extensions'] = [
  204. 'title' => t('PHP extensions'),
  205. ];
  206. $missing_extensions = [];
  207. $required_extensions = [
  208. 'date',
  209. 'dom',
  210. 'filter',
  211. 'gd',
  212. 'hash',
  213. 'json',
  214. 'pcre',
  215. 'pdo',
  216. 'session',
  217. 'SimpleXML',
  218. 'SPL',
  219. 'tokenizer',
  220. 'xml',
  221. ];
  222. foreach ($required_extensions as $extension) {
  223. if (!extension_loaded($extension)) {
  224. $missing_extensions[] = $extension;
  225. }
  226. }
  227. if (!empty($missing_extensions)) {
  228. $description = t('Drupal requires you to enable the PHP extensions in the following list (see the <a href=":system_requirements">system requirements page</a> for more information):', [
  229. ':system_requirements' => 'https://www.drupal.org/requirements',
  230. ]);
  231. // We use twig inline_template to avoid twig's autoescape.
  232. $description = [
  233. '#type' => 'inline_template',
  234. '#template' => '{{ description }}{{ missing_extensions }}',
  235. '#context' => [
  236. 'description' => $description,
  237. 'missing_extensions' => [
  238. '#theme' => 'item_list',
  239. '#items' => $missing_extensions,
  240. ],
  241. ],
  242. ];
  243. $requirements['php_extensions']['value'] = t('Disabled');
  244. $requirements['php_extensions']['severity'] = REQUIREMENT_ERROR;
  245. $requirements['php_extensions']['description'] = $description;
  246. }
  247. else {
  248. $requirements['php_extensions']['value'] = t('Enabled');
  249. }
  250. if ($phase == 'install' || $phase == 'runtime') {
  251. // Check to see if OPcache is installed.
  252. if (!OpCodeCache::isEnabled()) {
  253. $requirements['php_opcache'] = [
  254. 'value' => t('Not enabled'),
  255. 'severity' => REQUIREMENT_WARNING,
  256. 'description' => t('PHP OPcode caching can improve your site\'s performance considerably. It is <strong>highly recommended</strong> to have <a href="http://php.net/manual/opcache.installation.php" target="_blank">OPcache</a> installed on your server.'),
  257. ];
  258. }
  259. else {
  260. $requirements['php_opcache']['value'] = t('Enabled');
  261. }
  262. $requirements['php_opcache']['title'] = t('PHP OPcode caching');
  263. }
  264. if ($phase != 'update') {
  265. // Test whether we have a good source of random bytes.
  266. $requirements['php_random_bytes'] = [
  267. 'title' => t('Random number generation'),
  268. ];
  269. try {
  270. $bytes = random_bytes(10);
  271. if (strlen($bytes) != 10) {
  272. throw new \Exception(t('Tried to generate 10 random bytes, generated @count', ['@count' => strlen($bytes)]));
  273. }
  274. $requirements['php_random_bytes']['value'] = t('Successful');
  275. }
  276. catch (\Exception $e) {
  277. // If /dev/urandom is not available on a UNIX-like system, check whether
  278. // open_basedir restrictions are the cause.
  279. $open_basedir_blocks_urandom = FALSE;
  280. if (DIRECTORY_SEPARATOR === '/' && !@is_readable('/dev/urandom')) {
  281. $open_basedir = ini_get('open_basedir');
  282. if ($open_basedir) {
  283. $open_basedir_paths = explode(PATH_SEPARATOR, $open_basedir);
  284. $open_basedir_blocks_urandom = !array_intersect(['/dev', '/dev/', '/dev/urandom'], $open_basedir_paths);
  285. }
  286. }
  287. $args = [
  288. ':drupal-php' => 'https://www.drupal.org/docs/7/system-requirements/php#csprng',
  289. '%exception_message' => $e->getMessage(),
  290. ];
  291. if ($open_basedir_blocks_urandom) {
  292. $requirements['php_random_bytes']['description'] = t('Drupal is unable to generate highly randomized numbers, which means certain security features like password reset URLs are not as secure as they should be. Instead, only a slow, less-secure fallback generator is available. The most likely cause is that open_basedir restrictions are in effect and /dev/urandom is not on the whitelist. See the <a href=":drupal-php">system requirements</a> page for more information. %exception_message', $args);
  293. }
  294. else {
  295. $requirements['php_random_bytes']['description'] = t('Drupal is unable to generate highly randomized numbers, which means certain security features like password reset URLs are not as secure as they should be. Instead, only a slow, less-secure fallback generator is available. See the <a href=":drupal-php">system requirements</a> page for more information. %exception_message', $args);
  296. }
  297. $requirements['php_random_bytes']['value'] = t('Less secure');
  298. $requirements['php_random_bytes']['severity'] = REQUIREMENT_ERROR;
  299. }
  300. }
  301. if ($phase == 'install' || $phase == 'update') {
  302. // Test for PDO (database).
  303. $requirements['database_extensions'] = [
  304. 'title' => t('Database support'),
  305. ];
  306. // Make sure PDO is available.
  307. $database_ok = extension_loaded('pdo');
  308. if (!$database_ok) {
  309. $pdo_message = t('Your web server does not appear to support PDO (PHP Data Objects). Ask your hosting provider if they support the native PDO extension. See the <a href=":link">system requirements</a> page for more information.', [
  310. ':link' => 'https://www.drupal.org/requirements/pdo',
  311. ]);
  312. }
  313. else {
  314. // Make sure at least one supported database driver exists.
  315. $drivers = drupal_detect_database_types();
  316. if (empty($drivers)) {
  317. $database_ok = FALSE;
  318. $pdo_message = t('Your web server does not appear to support any common PDO database extensions. Check with your hosting provider to see if they support PDO (PHP Data Objects) and offer any databases that <a href=":drupal-databases">Drupal supports</a>.', [
  319. ':drupal-databases' => 'https://www.drupal.org/requirements/database',
  320. ]);
  321. }
  322. // Make sure the native PDO extension is available, not the older PEAR
  323. // version. (See install_verify_pdo() for details.)
  324. if (!defined('PDO::ATTR_DEFAULT_FETCH_MODE')) {
  325. $database_ok = FALSE;
  326. $pdo_message = t('Your web server seems to have the wrong version of PDO installed. Drupal requires the PDO extension from PHP core. This system has the older PECL version. See the <a href=":link">system requirements</a> page for more information.', [
  327. ':link' => 'https://www.drupal.org/requirements/pdo#pecl',
  328. ]);
  329. }
  330. }
  331. if (!$database_ok) {
  332. $requirements['database_extensions']['value'] = t('Disabled');
  333. $requirements['database_extensions']['severity'] = REQUIREMENT_ERROR;
  334. $requirements['database_extensions']['description'] = $pdo_message;
  335. }
  336. else {
  337. $requirements['database_extensions']['value'] = t('Enabled');
  338. }
  339. }
  340. else {
  341. // Database information.
  342. $class = Database::getConnection()->getDriverClass('Install\\Tasks');
  343. $tasks = new $class();
  344. $requirements['database_system'] = [
  345. 'title' => t('Database system'),
  346. 'value' => $tasks->name(),
  347. ];
  348. $requirements['database_system_version'] = [
  349. 'title' => t('Database system version'),
  350. 'value' => Database::getConnection()->version(),
  351. ];
  352. }
  353. // Test PHP memory_limit
  354. $memory_limit = ini_get('memory_limit');
  355. $requirements['php_memory_limit'] = [
  356. 'title' => t('PHP memory limit'),
  357. 'value' => $memory_limit == -1 ? t('-1 (Unlimited)') : $memory_limit,
  358. ];
  359. if (!Environment::checkMemoryLimit(DRUPAL_MINIMUM_PHP_MEMORY_LIMIT, $memory_limit)) {
  360. $description = [];
  361. if ($phase == 'install') {
  362. $description['phase'] = t('Consider increasing your PHP memory limit to %memory_minimum_limit to help prevent errors in the installation process.', ['%memory_minimum_limit' => DRUPAL_MINIMUM_PHP_MEMORY_LIMIT]);
  363. }
  364. elseif ($phase == 'update') {
  365. $description['phase'] = t('Consider increasing your PHP memory limit to %memory_minimum_limit to help prevent errors in the update process.', ['%memory_minimum_limit' => DRUPAL_MINIMUM_PHP_MEMORY_LIMIT]);
  366. }
  367. elseif ($phase == 'runtime') {
  368. $description['phase'] = t('Depending on your configuration, Drupal can run with a %memory_limit PHP memory limit. However, a %memory_minimum_limit PHP memory limit or above is recommended, especially if your site uses additional custom or contributed modules.', ['%memory_limit' => $memory_limit, '%memory_minimum_limit' => DRUPAL_MINIMUM_PHP_MEMORY_LIMIT]);
  369. }
  370. if (!empty($description['phase'])) {
  371. if ($php_ini_path = get_cfg_var('cfg_file_path')) {
  372. $description['memory'] = t('Increase the memory limit by editing the memory_limit parameter in the file %configuration-file and then restart your web server (or contact your system administrator or hosting provider for assistance).', ['%configuration-file' => $php_ini_path]);
  373. }
  374. else {
  375. $description['memory'] = t('Contact your system administrator or hosting provider for assistance with increasing your PHP memory limit.');
  376. }
  377. $handbook_link = t('For more information, see the online handbook entry for <a href=":memory-limit">increasing the PHP memory limit</a>.', [':memory-limit' => 'https://www.drupal.org/node/207036']);
  378. $description = [
  379. '#type' => 'inline_template',
  380. '#template' => '{{ description_phase }} {{ description_memory }} {{ handbook }}',
  381. '#context' => [
  382. 'description_phase' => $description['phase'],
  383. 'description_memory' => $description['memory'],
  384. 'handbook' => $handbook_link,
  385. ],
  386. ];
  387. $requirements['php_memory_limit']['description'] = $description;
  388. $requirements['php_memory_limit']['severity'] = REQUIREMENT_WARNING;
  389. }
  390. }
  391. // Test configuration files and directory for writability.
  392. if ($phase == 'runtime') {
  393. $conf_errors = [];
  394. // Find the site path. Kernel service is not always available at this point,
  395. // but is preferred, when available.
  396. if (\Drupal::hasService('kernel')) {
  397. $site_path = \Drupal::service('site.path');
  398. }
  399. else {
  400. $site_path = DrupalKernel::findSitePath(Request::createFromGlobals());
  401. }
  402. // Allow system administrators to disable permissions hardening for the site
  403. // directory. This allows additional files in the site directory to be
  404. // updated when they are managed in a version control system.
  405. if (Settings::get('skip_permissions_hardening')) {
  406. $error_value = t('Protection disabled');
  407. // If permissions hardening is disabled, then only show a warning for a
  408. // writable file, as a reminder, rather than an error.
  409. $file_protection_severity = REQUIREMENT_WARNING;
  410. }
  411. else {
  412. $error_value = t('Not protected');
  413. // In normal operation, writable files or directories are an error.
  414. $file_protection_severity = REQUIREMENT_ERROR;
  415. if (!drupal_verify_install_file($site_path, FILE_NOT_WRITABLE, 'dir')) {
  416. $conf_errors[] = t("The directory %file is not protected from modifications and poses a security risk. You must change the directory's permissions to be non-writable.", ['%file' => $site_path]);
  417. }
  418. }
  419. foreach (['settings.php', 'settings.local.php', 'services.yml'] as $conf_file) {
  420. $full_path = $site_path . '/' . $conf_file;
  421. if (file_exists($full_path) && !drupal_verify_install_file($full_path, FILE_EXIST | FILE_READABLE | FILE_NOT_WRITABLE, 'file', !Settings::get('skip_permissions_hardening'))) {
  422. $conf_errors[] = t("The file %file is not protected from modifications and poses a security risk. You must change the file's permissions to be non-writable.", ['%file' => $full_path]);
  423. }
  424. }
  425. if (!empty($conf_errors)) {
  426. if (count($conf_errors) == 1) {
  427. $description = $conf_errors[0];
  428. }
  429. else {
  430. // We use twig inline_template to avoid double escaping.
  431. $description = [
  432. '#type' => 'inline_template',
  433. '#template' => '{{ configuration_error_list }}',
  434. '#context' => [
  435. 'configuration_error_list' => [
  436. '#theme' => 'item_list',
  437. '#items' => $conf_errors,
  438. ],
  439. ],
  440. ];
  441. }
  442. $requirements['configuration_files'] = [
  443. 'value' => $error_value,
  444. 'severity' => $file_protection_severity,
  445. 'description' => $description,
  446. ];
  447. }
  448. else {
  449. $requirements['configuration_files'] = [
  450. 'value' => t('Protected'),
  451. ];
  452. }
  453. $requirements['configuration_files']['title'] = t('Configuration files');
  454. }
  455. // Test the contents of the .htaccess files.
  456. if ($phase == 'runtime') {
  457. // Try to write the .htaccess files first, to prevent false alarms in case
  458. // (for example) the /tmp directory was wiped.
  459. file_ensure_htaccess();
  460. $file_system = \Drupal::service('file_system');
  461. $htaccess_files['public://.htaccess'] = [
  462. 'title' => t('Public files directory'),
  463. 'directory' => $file_system->realpath('public://'),
  464. ];
  465. if (PrivateStream::basePath()) {
  466. $htaccess_files['private://.htaccess'] = [
  467. 'title' => t('Private files directory'),
  468. 'directory' => $file_system->realpath('private://'),
  469. ];
  470. }
  471. $htaccess_files['temporary://.htaccess'] = [
  472. 'title' => t('Temporary files directory'),
  473. 'directory' => $file_system->realpath('temporary://'),
  474. ];
  475. foreach ($htaccess_files as $htaccess_file => $info) {
  476. // Check for the string which was added to the recommended .htaccess file
  477. // in the latest security update.
  478. if (!file_exists($htaccess_file) || !($contents = @file_get_contents($htaccess_file)) || strpos($contents, 'Drupal_Security_Do_Not_Remove_See_SA_2013_003') === FALSE) {
  479. $url = 'https://www.drupal.org/SA-CORE-2013-003';
  480. $requirements[$htaccess_file] = [
  481. 'title' => $info['title'],
  482. 'value' => t('Not fully protected'),
  483. 'severity' => REQUIREMENT_ERROR,
  484. 'description' => t('See <a href=":url">@url</a> for information about the recommended .htaccess file which should be added to the %directory directory to help protect against arbitrary code execution.', [':url' => $url, '@url' => $url, '%directory' => $info['directory']]),
  485. ];
  486. }
  487. }
  488. }
  489. // Report cron status.
  490. if ($phase == 'runtime') {
  491. $cron_config = \Drupal::config('system.cron');
  492. // Cron warning threshold defaults to two days.
  493. $threshold_warning = $cron_config->get('threshold.requirements_warning');
  494. // Cron error threshold defaults to two weeks.
  495. $threshold_error = $cron_config->get('threshold.requirements_error');
  496. // Determine when cron last ran.
  497. $cron_last = \Drupal::state()->get('system.cron_last');
  498. if (!is_numeric($cron_last)) {
  499. $cron_last = \Drupal::state()->get('install_time', 0);
  500. }
  501. // Determine severity based on time since cron last ran.
  502. $severity = REQUIREMENT_INFO;
  503. if (REQUEST_TIME - $cron_last > $threshold_error) {
  504. $severity = REQUIREMENT_ERROR;
  505. }
  506. elseif (REQUEST_TIME - $cron_last > $threshold_warning) {
  507. $severity = REQUIREMENT_WARNING;
  508. }
  509. // Set summary and description based on values determined above.
  510. $summary = t('Last run @time ago', ['@time' => \Drupal::service('date.formatter')->formatTimeDiffSince($cron_last)]);
  511. $requirements['cron'] = [
  512. 'title' => t('Cron maintenance tasks'),
  513. 'severity' => $severity,
  514. 'value' => $summary,
  515. ];
  516. if ($severity != REQUIREMENT_INFO) {
  517. $requirements['cron']['description'][] = [
  518. [
  519. '#markup' => t('Cron has not run recently.'),
  520. '#suffix' => ' ',
  521. ],
  522. [
  523. '#markup' => t('For more information, see the online handbook entry for <a href=":cron-handbook">configuring cron jobs</a>.', [':cron-handbook' => 'https://www.drupal.org/cron']),
  524. '#suffix' => ' ',
  525. ],
  526. ];
  527. }
  528. $requirements['cron']['description'][] = [
  529. [
  530. '#type' => 'link',
  531. '#prefix' => '(',
  532. '#title' => t('more information'),
  533. '#suffix' => ')',
  534. '#url' => Url::fromRoute('system.cron_settings'),
  535. ],
  536. [
  537. '#prefix' => '<span class="cron-description__run-cron">',
  538. '#suffix' => '</span>',
  539. '#type' => 'link',
  540. '#title' => t('Run cron'),
  541. '#url' => Url::fromRoute('system.run_cron'),
  542. ],
  543. ];
  544. }
  545. if ($phase != 'install') {
  546. $filesystem_config = \Drupal::config('system.file');
  547. $directories = [
  548. PublicStream::basePath(),
  549. // By default no private files directory is configured. For private files
  550. // to be secure the admin needs to provide a path outside the webroot.
  551. PrivateStream::basePath(),
  552. file_directory_temp(),
  553. ];
  554. }
  555. // During an install we need to make assumptions about the file system
  556. // unless overrides are provided in settings.php.
  557. if ($phase == 'install') {
  558. $directories = [];
  559. if ($file_public_path = Settings::get('file_public_path')) {
  560. $directories[] = $file_public_path;
  561. }
  562. else {
  563. // If we are installing Drupal, the settings.php file might not exist yet
  564. // in the intended site directory, so don't require it.
  565. $request = Request::createFromGlobals();
  566. $site_path = DrupalKernel::findSitePath($request);
  567. $directories[] = $site_path . '/files';
  568. }
  569. if ($file_private_path = Settings::get('file_private_path')) {
  570. $directories[] = $file_private_path;
  571. }
  572. if (!empty($GLOBALS['config']['system.file']['path']['temporary'])) {
  573. $directories[] = $GLOBALS['config']['system.file']['path']['temporary'];
  574. }
  575. else {
  576. // If the temporary directory is not overridden use an appropriate
  577. // temporary path for the system.
  578. $directories[] = FileSystem::getOsTemporaryDirectory();
  579. }
  580. }
  581. // Check the config directory if it is defined in settings.php. If it isn't
  582. // defined, the installer will create a valid config directory later, but
  583. // during runtime we must always display an error.
  584. if (!empty($GLOBALS['config_directories'])) {
  585. foreach (array_keys(array_filter($GLOBALS['config_directories'])) as $type) {
  586. $directory = config_get_config_directory($type);
  587. // If we're installing Drupal try and create the config sync directory.
  588. if (!is_dir($directory) && $phase == 'install') {
  589. file_prepare_directory($directory, FILE_CREATE_DIRECTORY | FILE_MODIFY_PERMISSIONS);
  590. }
  591. if (!is_dir($directory)) {
  592. if ($phase == 'install') {
  593. $description = t('An automated attempt to create the directory %directory failed, possibly due to a permissions problem. To proceed with the installation, either create the directory and modify its permissions manually or ensure that the installer has the permissions to create it automatically. For more information, see INSTALL.txt or the <a href=":handbook_url">online handbook</a>.', ['%directory' => $directory, ':handbook_url' => 'https://www.drupal.org/server-permissions']);
  594. }
  595. else {
  596. $description = t('The directory %directory does not exist.', ['%directory' => $directory]);
  597. }
  598. $requirements['config directory ' . $type] = [
  599. 'title' => t('Configuration directory: %type', ['%type' => $type]),
  600. 'description' => $description,
  601. 'severity' => REQUIREMENT_ERROR,
  602. ];
  603. }
  604. }
  605. }
  606. if ($phase != 'install' && (empty($GLOBALS['config_directories']) || empty($GLOBALS['config_directories'][CONFIG_SYNC_DIRECTORY]))) {
  607. $requirements['config directories'] = [
  608. 'title' => t('Configuration directories'),
  609. 'value' => t('Not present'),
  610. 'description' => t('Your %file file must define the $config_directories variable as an array containing the names of directories in which configuration files can be found. It must contain a %sync_key key.', ['%file' => $site_path . '/settings.php', '%sync_key' => CONFIG_SYNC_DIRECTORY]),
  611. 'severity' => REQUIREMENT_ERROR,
  612. ];
  613. }
  614. $requirements['file system'] = [
  615. 'title' => t('File system'),
  616. ];
  617. $error = '';
  618. // For installer, create the directories if possible.
  619. foreach ($directories as $directory) {
  620. if (!$directory) {
  621. continue;
  622. }
  623. if ($phase == 'install') {
  624. file_prepare_directory($directory, FILE_CREATE_DIRECTORY | FILE_MODIFY_PERMISSIONS);
  625. }
  626. $is_writable = is_writable($directory);
  627. $is_directory = is_dir($directory);
  628. if (!$is_writable || !$is_directory) {
  629. $description = '';
  630. $requirements['file system']['value'] = t('Not writable');
  631. if (!$is_directory) {
  632. $error = t('The directory %directory does not exist.', ['%directory' => $directory]);
  633. }
  634. else {
  635. $error = t('The directory %directory is not writable.', ['%directory' => $directory]);
  636. }
  637. // The files directory requirement check is done only during install and runtime.
  638. if ($phase == 'runtime') {
  639. $description = t('You may need to set the correct directory at the <a href=":admin-file-system">file system settings page</a> or change the current directory\'s permissions so that it is writable.', [':admin-file-system' => \Drupal::url('system.file_system_settings')]);
  640. }
  641. elseif ($phase == 'install') {
  642. // For the installer UI, we need different wording. 'value' will
  643. // be treated as version, so provide none there.
  644. $description = t('An automated attempt to create this directory failed, possibly due to a permissions problem. To proceed with the installation, either create the directory and modify its permissions manually or ensure that the installer has the permissions to create it automatically. For more information, see INSTALL.txt or the <a href=":handbook_url">online handbook</a>.', [':handbook_url' => 'https://www.drupal.org/server-permissions']);
  645. $requirements['file system']['value'] = '';
  646. }
  647. if (!empty($description)) {
  648. $description = [
  649. '#type' => 'inline_template',
  650. '#template' => '{{ error }} {{ description }}',
  651. '#context' => [
  652. 'error' => $error,
  653. 'description' => $description,
  654. ],
  655. ];
  656. $requirements['file system']['description'] = $description;
  657. $requirements['file system']['severity'] = REQUIREMENT_ERROR;
  658. }
  659. }
  660. else {
  661. // This function can be called before the config_cache table has been
  662. // created.
  663. if ($phase == 'install' || file_default_scheme() == 'public') {
  664. $requirements['file system']['value'] = t('Writable (<em>public</em> download method)');
  665. }
  666. else {
  667. $requirements['file system']['value'] = t('Writable (<em>private</em> download method)');
  668. }
  669. }
  670. }
  671. // See if updates are available in update.php.
  672. if ($phase == 'runtime') {
  673. $requirements['update'] = [
  674. 'title' => t('Database updates'),
  675. 'value' => t('Up to date'),
  676. ];
  677. // Check installed modules.
  678. $has_pending_updates = FALSE;
  679. foreach (\Drupal::moduleHandler()->getModuleList() as $module => $filename) {
  680. $updates = drupal_get_schema_versions($module);
  681. if ($updates !== FALSE) {
  682. $default = drupal_get_installed_schema_version($module);
  683. if (max($updates) > $default) {
  684. $has_pending_updates = TRUE;
  685. break;
  686. }
  687. }
  688. }
  689. if (!$has_pending_updates) {
  690. /** @var \Drupal\Core\Update\UpdateRegistry $post_update_registry */
  691. $post_update_registry = \Drupal::service('update.post_update_registry');
  692. $missing_post_update_functions = $post_update_registry->getPendingUpdateFunctions();
  693. if (!empty($missing_post_update_functions)) {
  694. $has_pending_updates = TRUE;
  695. }
  696. }
  697. if ($has_pending_updates) {
  698. $requirements['update']['severity'] = REQUIREMENT_ERROR;
  699. $requirements['update']['value'] = t('Out of date');
  700. $requirements['update']['description'] = t('Some modules have database schema updates to install. You should run the <a href=":update">database update script</a> immediately.', [':update' => \Drupal::url('system.db_update')]);
  701. }
  702. $requirements['entity_update'] = [
  703. 'title' => t('Entity/field definitions'),
  704. 'value' => t('Up to date'),
  705. ];
  706. // Verify that no entity updates are pending.
  707. if ($change_list = \Drupal::entityDefinitionUpdateManager()->getChangeSummary()) {
  708. $build = [];
  709. foreach ($change_list as $entity_type_id => $changes) {
  710. $entity_type = \Drupal::entityManager()->getDefinition($entity_type_id);
  711. $build[] = [
  712. '#theme' => 'item_list',
  713. '#title' => $entity_type->getLabel(),
  714. '#items' => $changes,
  715. ];
  716. }
  717. $entity_update_issues = \Drupal::service('renderer')->renderPlain($build);
  718. $requirements['entity_update']['severity'] = REQUIREMENT_ERROR;
  719. $requirements['entity_update']['value'] = t('Mismatched entity and/or field definitions');
  720. $requirements['entity_update']['description'] = t('The following changes were detected in the entity type and field definitions. @updates', ['@updates' => $entity_update_issues]);
  721. }
  722. }
  723. // Verify the update.php access setting
  724. if ($phase == 'runtime') {
  725. if (Settings::get('update_free_access')) {
  726. $requirements['update access'] = [
  727. 'value' => t('Not protected'),
  728. 'severity' => REQUIREMENT_ERROR,
  729. 'description' => t('The update.php script is accessible to everyone without authentication check, which is a security risk. You must change the @settings_name value in your settings.php back to FALSE.', ['@settings_name' => '$settings[\'update_free_access\']']),
  730. ];
  731. }
  732. else {
  733. $requirements['update access'] = [
  734. 'value' => t('Protected'),
  735. ];
  736. }
  737. $requirements['update access']['title'] = t('Access to update.php');
  738. }
  739. // Display an error if a newly introduced dependency in a module is not resolved.
  740. if ($phase == 'update') {
  741. $profile = drupal_get_profile();
  742. $files = system_rebuild_module_data();
  743. foreach ($files as $module => $file) {
  744. // Ignore disabled modules and installation profiles.
  745. if (!$file->status || $module == $profile) {
  746. continue;
  747. }
  748. // Check the module's PHP version.
  749. $name = $file->info['name'];
  750. $php = $file->info['php'];
  751. if (version_compare($php, PHP_VERSION, '>')) {
  752. $requirements['php']['description'] .= t('@name requires at least PHP @version.', ['@name' => $name, '@version' => $php]);
  753. $requirements['php']['severity'] = REQUIREMENT_ERROR;
  754. }
  755. // Check the module's required modules.
  756. foreach ($file->requires as $requirement) {
  757. $required_module = $requirement['name'];
  758. // Check if the module exists.
  759. if (!isset($files[$required_module])) {
  760. $requirements["$module-$required_module"] = [
  761. 'title' => t('Unresolved dependency'),
  762. 'description' => t('@name requires this module.', ['@name' => $name]),
  763. 'value' => t('@required_name (Missing)', ['@required_name' => $required_module]),
  764. 'severity' => REQUIREMENT_ERROR,
  765. ];
  766. continue;
  767. }
  768. // Check for an incompatible version.
  769. $required_file = $files[$required_module];
  770. $required_name = $required_file->info['name'];
  771. $version = str_replace(\Drupal::CORE_COMPATIBILITY . '-', '', $required_file->info['version']);
  772. $compatibility = drupal_check_incompatibility($requirement, $version);
  773. if ($compatibility) {
  774. $compatibility = rtrim(substr($compatibility, 2), ')');
  775. $requirements["$module-$required_module"] = [
  776. 'title' => t('Unresolved dependency'),
  777. 'description' => t('@name requires this module and version. Currently using @required_name version @version', ['@name' => $name, '@required_name' => $required_name, '@version' => $version]),
  778. 'value' => t('@required_name (Version @compatibility required)', ['@required_name' => $required_name, '@compatibility' => $compatibility]),
  779. 'severity' => REQUIREMENT_ERROR,
  780. ];
  781. continue;
  782. }
  783. }
  784. }
  785. }
  786. // Returns Unicode library status and errors.
  787. $libraries = [
  788. Unicode::STATUS_SINGLEBYTE => t('Standard PHP'),
  789. Unicode::STATUS_MULTIBYTE => t('PHP Mbstring Extension'),
  790. Unicode::STATUS_ERROR => t('Error'),
  791. ];
  792. $severities = [
  793. Unicode::STATUS_SINGLEBYTE => REQUIREMENT_WARNING,
  794. Unicode::STATUS_MULTIBYTE => NULL,
  795. Unicode::STATUS_ERROR => REQUIREMENT_ERROR,
  796. ];
  797. $failed_check = Unicode::check();
  798. $library = Unicode::getStatus();
  799. $requirements['unicode'] = [
  800. 'title' => t('Unicode library'),
  801. 'value' => $libraries[$library],
  802. 'severity' => $severities[$library],
  803. ];
  804. switch ($failed_check) {
  805. case 'mb_strlen':
  806. $requirements['unicode']['description'] = t('Operations on Unicode strings are emulated on a best-effort basis. Install the <a href="http://php.net/mbstring">PHP mbstring extension</a> for improved Unicode support.');
  807. break;
  808. case 'mbstring.func_overload':
  809. $requirements['unicode']['description'] = t('Multibyte string function overloading in PHP is active and must be disabled. Check the php.ini <em>mbstring.func_overload</em> setting. Please refer to the <a href="http://php.net/mbstring">PHP mbstring documentation</a> for more information.');
  810. break;
  811. case 'mbstring.encoding_translation':
  812. $requirements['unicode']['description'] = t('Multibyte string input conversion in PHP is active and must be disabled. Check the php.ini <em>mbstring.encoding_translation</em> setting. Please refer to the <a href="http://php.net/mbstring">PHP mbstring documentation</a> for more information.');
  813. break;
  814. case 'mbstring.http_input':
  815. $requirements['unicode']['description'] = t('Multibyte string input conversion in PHP is active and must be disabled. Check the php.ini <em>mbstring.http_input</em> setting. Please refer to the <a href="http://php.net/mbstring">PHP mbstring documentation</a> for more information.');
  816. break;
  817. case 'mbstring.http_output':
  818. $requirements['unicode']['description'] = t('Multibyte string output conversion in PHP is active and must be disabled. Check the php.ini <em>mbstring.http_output</em> setting. Please refer to the <a href="http://php.net/mbstring">PHP mbstring documentation</a> for more information.');
  819. break;
  820. }
  821. if ($phase == 'runtime') {
  822. // Check for update status module.
  823. if (!\Drupal::moduleHandler()->moduleExists('update')) {
  824. $requirements['update status'] = [
  825. 'value' => t('Not enabled'),
  826. 'severity' => REQUIREMENT_WARNING,
  827. 'description' => t('Update notifications are not enabled. It is <strong>highly recommended</strong> that you enable the Update Manager module from the <a href=":module">module administration page</a> in order to stay up-to-date on new releases. For more information, <a href=":update">Update status handbook page</a>.', [
  828. ':update' => 'https://www.drupal.org/documentation/modules/update',
  829. ':module' => \Drupal::url('system.modules_list'),
  830. ]),
  831. ];
  832. }
  833. else {
  834. $requirements['update status'] = [
  835. 'value' => t('Enabled'),
  836. ];
  837. }
  838. $requirements['update status']['title'] = t('Update notifications');
  839. if (Settings::get('rebuild_access')) {
  840. $requirements['rebuild access'] = [
  841. 'title' => t('Rebuild access'),
  842. 'value' => t('Enabled'),
  843. 'severity' => REQUIREMENT_ERROR,
  844. 'description' => t('The rebuild_access setting is enabled in settings.php. It is recommended to have this setting disabled unless you are performing a rebuild.'),
  845. ];
  846. }
  847. }
  848. // See if trusted hostnames have been configured, and warn the user if they
  849. // are not set.
  850. if ($phase == 'runtime') {
  851. $trusted_host_patterns = Settings::get('trusted_host_patterns');
  852. if (empty($trusted_host_patterns)) {
  853. $requirements['trusted_host_patterns'] = [
  854. 'title' => t('Trusted Host Settings'),
  855. 'value' => t('Not enabled'),
  856. 'description' => t('The trusted_host_patterns setting is not configured in settings.php. This can lead to security vulnerabilities. It is <strong>highly recommended</strong> that you configure this. See <a href=":url">Protecting against HTTP HOST Header attacks</a> for more information.', [':url' => 'https://www.drupal.org/node/1992030']),
  857. 'severity' => REQUIREMENT_ERROR,
  858. ];
  859. }
  860. else {
  861. $requirements['trusted_host_patterns'] = [
  862. 'title' => t('Trusted Host Settings'),
  863. 'value' => t('Enabled'),
  864. 'description' => t('The trusted_host_patterns setting is set to allow %trusted_host_patterns', ['%trusted_host_patterns' => implode(', ', $trusted_host_patterns)]),
  865. ];
  866. }
  867. }
  868. // Check xdebug.max_nesting_level, as some pages will not work if it is too
  869. // low.
  870. if (extension_loaded('xdebug')) {
  871. // Setting this value to 256 was considered adequate on Xdebug 2.3
  872. // (see http://bugs.xdebug.org/bug_view_page.php?bug_id=00001100)
  873. $minimum_nesting_level = 256;
  874. $current_nesting_level = ini_get('xdebug.max_nesting_level');
  875. if ($current_nesting_level < $minimum_nesting_level) {
  876. $requirements['xdebug_max_nesting_level'] = [
  877. 'title' => t('Xdebug settings'),
  878. 'value' => t('xdebug.max_nesting_level is set to %value.', ['%value' => $current_nesting_level]),
  879. 'description' => t('Set <code>xdebug.max_nesting_level=@level</code> in your PHP configuration as some pages in your Drupal site will not work when this setting is too low.', ['@level' => $minimum_nesting_level]),
  880. 'severity' => REQUIREMENT_ERROR,
  881. ];
  882. }
  883. }
  884. // Warning for httpoxy on IIS with affected PHP versions
  885. // @see https://www.drupal.org/node/2783079
  886. if (strpos($software, 'Microsoft-IIS') !== FALSE
  887. && (
  888. version_compare(PHP_VERSION, '5.5.38', '<')
  889. || (version_compare(PHP_VERSION, '5.6.0', '>=') && version_compare(PHP_VERSION, '5.6.24', '<'))
  890. || (version_compare(PHP_VERSION, '7.0.0', '>=') && version_compare(PHP_VERSION, '7.0.9', '<'))
  891. )) {
  892. $dom = new \DOMDocument('1.0', 'UTF-8');
  893. $webconfig = file_get_contents('web.config');
  894. // If you are here the web.config file must - of course - be well formed.
  895. // But the PHP DOM component will throw warnings on some XML compliant
  896. // stuff, so silently parse the configuration file.
  897. @$dom->loadHTML($webconfig);
  898. $httpoxy_rewrite = FALSE;
  899. foreach ($dom->getElementsByTagName('rule') as $rule) {
  900. foreach ($rule->attributes as $attr) {
  901. if (@$attr->name == 'name' && @$attr->nodeValue == 'Erase HTTP_PROXY') {
  902. $httpoxy_rewrite = TRUE;
  903. break 2;
  904. }
  905. }
  906. }
  907. if (!$httpoxy_rewrite) {
  908. $requirements['iis_httpoxy_protection'] = [
  909. 'title' => t('IIS httpoxy protection'),
  910. 'value' => t('Your PHP runtime version is affected by the httpoxy vulnerability.'),
  911. 'description' => t('Either update your PHP runtime version or uncomment the "Erase HTTP_PROXY" rule in your web.config file and add HTTP_PROXY to the allowed headers list. See more details in the <a href=":link">security advisory</a>.', [':link' => 'https://www.drupal.org/SA-CORE-2016-003']),
  912. 'severity' => REQUIREMENT_ERROR,
  913. ];
  914. }
  915. }
  916. // Installations on Windows can run into limitations with MAX_PATH if the
  917. // Drupal root directory is too deep in the filesystem. Generally this shows
  918. // up in cached Twig templates and other public files with long directory or
  919. // file names. There is no definite root directory depth below which Drupal is
  920. // guaranteed to function correctly on Windows. Since problems are likely
  921. // with more than 100 characters in the Drupal root path, show an error.
  922. if (substr(PHP_OS, 0, 3) == 'WIN') {
  923. $depth = strlen(realpath(DRUPAL_ROOT . '/' . PublicStream::basePath()));
  924. if ($depth > 120) {
  925. $requirements['max_path_on_windows'] = [
  926. 'title' => t('Windows installation depth'),
  927. 'description' => t('The public files directory path is %depth characters. Paths longer than 120 characters will cause problems on Windows.', ['%depth' => $depth]),
  928. 'severity' => REQUIREMENT_ERROR,
  929. ];
  930. }
  931. }
  932. // Check to see if dates will be limited to 1901-2038.
  933. if (PHP_INT_SIZE <= 4) {
  934. $requirements['limited_date_range'] = [
  935. 'title' => t('Limited date range'),
  936. 'value' => t('Your PHP installation has a limited date range.'),
  937. 'description' => t('You are running on a system where PHP is compiled or limited to using 32-bit integers. This will limit the range of dates and timestamps to the years 1901-2038. Read about the <a href=":url">limitations of 32-bit PHP</a>.', [':url' => 'https://www.drupal.org/docs/8/system-requirements/limitations-of-32-bit-php']),
  938. 'severity' => REQUIREMENT_WARNING,
  939. ];
  940. }
  941. // During installs from configuration don't support install profiles that
  942. // implement hook_install.
  943. if ($phase == 'install' && !empty($install_state['config_install_path'])) {
  944. $install_hook = $install_state['parameters']['profile'] . '_install';
  945. if (function_exists($install_hook)) {
  946. $requirements['config_install'] = [
  947. 'title' => t('Configuration install'),
  948. 'value' => $install_state['parameters']['profile'],
  949. 'description' => t('The selected profile has a hook_install() implementation and therefore can not be installed from configuration.'),
  950. 'severity' => REQUIREMENT_ERROR,
  951. ];
  952. }
  953. }
  954. if ($phase === 'runtime') {
  955. $settings = Settings::getAll();
  956. if (array_key_exists('install_profile', $settings)) {
  957. // The following message is only informational because not all site owners
  958. // have access to edit their settings.php as it may be controlled by their
  959. // hosting provider.
  960. $requirements['install_profile_in_settings'] = [
  961. 'title' => t('Install profile in settings'),
  962. 'value' => t("Drupal 8 no longer uses the \$settings['install_profile'] value in settings.php and it can be removed."),
  963. 'severity' => REQUIREMENT_INFO,
  964. ];
  965. }
  966. }
  967. return $requirements;
  968. }
  969. /**
  970. * Implements hook_install().
  971. */
  972. function system_install() {
  973. // Populate the cron key state variable.
  974. $cron_key = Crypt::randomBytesBase64(55);
  975. \Drupal::state()->set('system.cron_key', $cron_key);
  976. // Populate the site UUID and default name (if not set).
  977. $site = \Drupal::configFactory()->getEditable('system.site');
  978. $site->set('uuid', \Drupal::service('uuid')->generate());
  979. if (!$site->get('name')) {
  980. $site->set('name', 'Drupal');
  981. }
  982. $site->save(TRUE);
  983. }
  984. /**
  985. * Implements hook_schema().
  986. */
  987. function system_schema() {
  988. $schema['key_value'] = [
  989. 'description' => 'Generic key-value storage table. See the state system for an example.',
  990. 'fields' => [
  991. 'collection' => [
  992. 'description' => 'A named collection of key and value pairs.',
  993. 'type' => 'varchar_ascii',
  994. 'length' => 128,
  995. 'not null' => TRUE,
  996. 'default' => '',
  997. ],
  998. 'name' => [
  999. 'description' => 'The key of the key-value pair. As KEY is a SQL reserved keyword, name was chosen instead.',
  1000. 'type' => 'varchar_ascii',
  1001. 'length' => 128,
  1002. 'not null' => TRUE,
  1003. 'default' => '',
  1004. ],
  1005. 'value' => [
  1006. 'description' => 'The value.',
  1007. 'type' => 'blob',
  1008. 'not null' => TRUE,
  1009. 'size' => 'big',
  1010. ],
  1011. ],
  1012. 'primary key' => ['collection', 'name'],
  1013. ];
  1014. $schema['key_value_expire'] = [
  1015. 'description' => 'Generic key/value storage table with an expiration.',
  1016. 'fields' => [
  1017. 'collection' => [
  1018. 'description' => 'A named collection of key and value pairs.',
  1019. 'type' => 'varchar_ascii',
  1020. 'length' => 128,
  1021. 'not null' => TRUE,
  1022. 'default' => '',
  1023. ],
  1024. 'name' => [
  1025. // KEY is an SQL reserved word, so use 'name' as the key's field name.
  1026. 'description' => 'The key of the key/value pair.',
  1027. 'type' => 'varchar_ascii',
  1028. 'length' => 128,
  1029. 'not null' => TRUE,
  1030. 'default' => '',
  1031. ],
  1032. 'value' => [
  1033. 'description' => 'The value of the key/value pair.',
  1034. 'type' => 'blob',
  1035. 'not null' => TRUE,
  1036. 'size' => 'big',
  1037. ],
  1038. 'expire' => [
  1039. 'description' => 'The time since Unix epoch in seconds when this item expires. Defaults to the maximum possible time.',
  1040. 'type' => 'int',
  1041. 'not null' => TRUE,
  1042. 'default' => 2147483647,
  1043. ],
  1044. ],
  1045. 'primary key' => ['collection', 'name'],
  1046. 'indexes' => [
  1047. 'all' => ['name', 'collection', 'expire'],
  1048. 'expire' => ['expire'],
  1049. ],
  1050. ];
  1051. $schema['sequences'] = [
  1052. 'description' => 'Stores IDs.',
  1053. 'fields' => [
  1054. 'value' => [
  1055. 'description' => 'The value of the sequence.',
  1056. 'type' => 'serial',
  1057. 'unsigned' => TRUE,
  1058. 'not null' => TRUE,
  1059. ],
  1060. ],
  1061. 'primary key' => ['value'],
  1062. ];
  1063. $schema['sessions'] = [
  1064. 'description' => "Drupal's session handlers read and write into the sessions table. Each record represents a user session, either anonymous or authenticated.",
  1065. 'fields' => [
  1066. 'uid' => [
  1067. 'description' => 'The {users}.uid corresponding to a session, or 0 for anonymous user.',
  1068. 'type' => 'int',
  1069. 'unsigned' => TRUE,
  1070. 'not null' => TRUE,
  1071. ],
  1072. 'sid' => [
  1073. 'description' => "A session ID (hashed). The value is generated by Drupal's session handlers.",
  1074. 'type' => 'varchar_ascii',
  1075. 'length' => 128,
  1076. 'not null' => TRUE,
  1077. ],
  1078. 'hostname' => [
  1079. 'description' => 'The IP address that last used this session ID (sid).',
  1080. 'type' => 'varchar_ascii',
  1081. 'length' => 128,
  1082. 'not null' => TRUE,
  1083. 'default' => '',
  1084. ],
  1085. 'timestamp' => [
  1086. 'description' => 'The Unix timestamp when this session last requested a page. Old records are purged by PHP automatically.',
  1087. 'type' => 'int',
  1088. 'not null' => TRUE,
  1089. 'default' => 0,
  1090. ],
  1091. 'session' => [
  1092. 'description' => 'The serialized contents of $_SESSION, an array of name/value pairs that persists across page requests by this session ID. Drupal loads $_SESSION from here at the start of each request and saves it at the end.',
  1093. 'type' => 'blob',
  1094. 'not null' => FALSE,
  1095. 'size' => 'big',
  1096. ],
  1097. ],
  1098. 'primary key' => [
  1099. 'sid',
  1100. ],
  1101. 'indexes' => [
  1102. 'timestamp' => ['timestamp'],
  1103. 'uid' => ['uid'],
  1104. ],
  1105. 'foreign keys' => [
  1106. 'session_user' => [
  1107. 'table' => 'users',
  1108. 'columns' => ['uid' => 'uid'],
  1109. ],
  1110. ],
  1111. ];
  1112. // Create the url_alias table. The alias_storage service can auto-create its
  1113. // table, but this relies on exceptions being thrown. These exceptions will be
  1114. // thrown every request until an alias is created.
  1115. $schema['url_alias'] = AliasStorage::schemaDefinition();
  1116. return $schema;
  1117. }
  1118. /**
  1119. * Change two fields on the default menu link storage to be serialized data.
  1120. */
  1121. function system_update_8001(&$sandbox = NULL) {
  1122. $database = \Drupal::database();
  1123. $schema = $database->schema();
  1124. if ($schema->tableExists('menu_tree')) {
  1125. if (!isset($sandbox['current'])) {
  1126. // Converting directly to blob can cause problems with reading out and
  1127. // serializing the string data later on postgres, so rename the existing
  1128. // columns and create replacement ones to hold the serialized objects.
  1129. $old_fields = [
  1130. 'title' => [
  1131. 'description' => 'The text displayed for the link.',
  1132. 'type' => 'varchar',
  1133. 'length' => 255,
  1134. 'not null' => TRUE,
  1135. 'default' => '',
  1136. ],
  1137. 'description' => [
  1138. 'description' => 'The description of this link - used for admin pages and title attribute.',
  1139. 'type' => 'text',
  1140. 'not null' => FALSE,
  1141. ],
  1142. ];
  1143. foreach ($old_fields as $name => $spec) {
  1144. $schema->changeField('menu_tree', $name, 'system_update_8001_' . $name, $spec);
  1145. }
  1146. $spec = [
  1147. 'description' => 'The title for the link. May be a serialized TranslatableMarkup.',
  1148. 'type' => 'blob',
  1149. 'size' => 'big',
  1150. 'not null' => FALSE,
  1151. 'serialize' => TRUE,
  1152. ];
  1153. $schema->addField('menu_tree', 'title', $spec);
  1154. $spec = [
  1155. 'description' => 'The description of this link - used for admin pages and title attribute.',
  1156. 'type' => 'blob',
  1157. 'size' => 'big',
  1158. 'not null' => FALSE,
  1159. 'serialize' => TRUE,
  1160. ];
  1161. $schema->addField('menu_tree', 'description', $spec);
  1162. $sandbox['current'] = 0;
  1163. $sandbox['max'] = $database->query('SELECT COUNT(mlid) FROM {menu_tree}')
  1164. ->fetchField();
  1165. }
  1166. $menu_links = $database->queryRange('SELECT mlid, system_update_8001_title AS title, system_update_8001_description AS description FROM {menu_tree} ORDER BY mlid ASC', $sandbox['current'], $sandbox['current'] + 50)
  1167. ->fetchAllAssoc('mlid');
  1168. foreach ($menu_links as $menu_link) {
  1169. $menu_link = (array) $menu_link;
  1170. // Convert title and description to serialized strings.
  1171. $menu_link['title'] = serialize($menu_link['title']);
  1172. $menu_link['description'] = serialize($menu_link['description']);
  1173. $database->update('menu_tree')
  1174. ->fields($menu_link)
  1175. ->condition('mlid', $menu_link['mlid'])
  1176. ->execute();
  1177. $sandbox['current']++;
  1178. }
  1179. $sandbox['#finished'] = empty($sandbox['max']) ? 1 : ($sandbox['current'] / $sandbox['max']);
  1180. if ($sandbox['#finished'] >= 1) {
  1181. // Drop unnecessary fields from {menu_tree}.
  1182. $schema->dropField('menu_tree', 'system_update_8001_title');
  1183. $schema->dropField('menu_tree', 'title_arguments');
  1184. $schema->dropField('menu_tree', 'title_context');
  1185. $schema->dropField('menu_tree', 'system_update_8001_description');
  1186. }
  1187. return t('Menu links converted');
  1188. }
  1189. else {
  1190. return t('Menu link conversion skipped, because the {menu_tree} table did not exist yet.');
  1191. }
  1192. }
  1193. /**
  1194. * Removes the system.filter configuration.
  1195. */
  1196. function system_update_8002() {
  1197. \Drupal::configFactory()->getEditable('system.filter')->delete();
  1198. return t('The system.filter configuration has been moved to a container parameter, see default.services.yml for more information.');
  1199. }
  1200. /**
  1201. * Change the index on the {router} table.
  1202. */
  1203. function system_update_8003() {
  1204. $database = \Drupal::database();
  1205. $database->schema()->dropIndex('router', 'pattern_outline_fit');
  1206. $database->schema()->addIndex(
  1207. 'router',
  1208. 'pattern_outline_parts',
  1209. ['pattern_outline', 'number_parts'],
  1210. [
  1211. 'fields' => [
  1212. 'pattern_outline' => [
  1213. 'description' => 'The pattern',
  1214. 'type' => 'varchar',
  1215. 'length' => 255,
  1216. 'not null' => TRUE,
  1217. 'default' => '',
  1218. ],
  1219. 'number_parts' => [
  1220. 'description' => 'Number of parts in this router path.',
  1221. 'type' => 'int',
  1222. 'not null' => TRUE,
  1223. 'default' => 0,
  1224. 'size' => 'small',
  1225. ],
  1226. ],
  1227. ]
  1228. );
  1229. }
  1230. /**
  1231. * Add a (id, default_langcode, langcode) composite index to entities.
  1232. */
  1233. function system_update_8004() {
  1234. // \Drupal\Core\Entity\Sql\SqlContentEntityStorageSchema was changed in
  1235. // https://www.drupal.org/node/2261669 to include a (id, default_langcode,
  1236. // langcode) compound index, but this update function wasn't added until
  1237. // https://www.drupal.org/node/2542748. Regenerate the related schemas to
  1238. // ensure they match the currently expected status.
  1239. $manager = \Drupal::entityDefinitionUpdateManager();
  1240. foreach (array_keys(\Drupal::entityManager()
  1241. ->getDefinitions()) as $entity_type_id) {
  1242. // Only update the entity type if it already exists. This condition is
  1243. // needed in case new entity types are introduced after this update.
  1244. if ($entity_type = $manager->getEntityType($entity_type_id)) {
  1245. $manager->updateEntityType($entity_type);
  1246. }
  1247. }
  1248. }
  1249. /**
  1250. * Place local actions and tasks blocks in every theme.
  1251. */
  1252. function system_update_8005() {
  1253. // When block module is not installed, there is nothing that could be done
  1254. // except showing a warning.
  1255. if (!\Drupal::moduleHandler()->moduleExists('block')) {
  1256. return t('Block module is not enabled so local actions and tasks which have been converted to blocks, are not visible anymore.');
  1257. }
  1258. $config_factory = \Drupal::configFactory();
  1259. /** @var \Drupal\Core\Extension\ThemeHandlerInterface $theme_handler */
  1260. $theme_handler = \Drupal::service('theme_handler');
  1261. $custom_themes_installed = FALSE;
  1262. $message = NULL;
  1263. $langcode = \Drupal::service('language_manager')->getCurrentLanguage()->getId();
  1264. $local_actions_default_settings = [
  1265. 'plugin' => 'local_actions_block',
  1266. 'region' => 'content',
  1267. 'settings.label' => 'Primary admin actions',
  1268. 'settings.label_display' => 0,
  1269. 'settings.cache.max_age' => 0,
  1270. 'visibility' => [],
  1271. 'weight' => 0,
  1272. 'langcode' => $langcode,
  1273. ];
  1274. $tabs_default_settings = [
  1275. 'plugin' => 'local_tasks_block',
  1276. 'region' => 'content',
  1277. 'settings.label' => 'Tabs',
  1278. 'settings.label_display' => 0,
  1279. 'settings.cache.max_age' => 0,
  1280. 'visibility' => [],
  1281. 'weight' => 0,
  1282. 'langcode' => $langcode,
  1283. ];
  1284. foreach ($theme_handler->listInfo() as $theme) {
  1285. $theme_name = $theme->getName();
  1286. switch ($theme_name) {
  1287. case 'bartik':
  1288. $name = 'block.block.bartik_local_actions';
  1289. $values = [
  1290. 'id' => 'bartik_local_actions',
  1291. 'weight' => -1,
  1292. ] + $local_actions_default_settings;
  1293. _system_update_create_block($name, $theme_name, $values);
  1294. $name = 'block.block.bartik_local_tasks';
  1295. $values = [
  1296. 'id' => 'bartik_local_tasks',
  1297. 'weight' => -7,
  1298. ] + $tabs_default_settings;
  1299. _system_update_create_block($name, $theme_name, $values);
  1300. // Help region has been removed so all the blocks inside has to be moved
  1301. // to content region.
  1302. $weight = -6;
  1303. $blocks = [];
  1304. foreach ($config_factory->listAll('block.block.') as $block_config) {
  1305. $block = $config_factory->getEditable($block_config);
  1306. if ($block->get('theme') == 'bartik' && $block->get('region') == 'help') {
  1307. $blocks[] = $block;
  1308. }
  1309. }
  1310. // Sort blocks by block weight.
  1311. uasort($blocks, function ($a, $b) {
  1312. return $a->get('weight') - $b->get('weight');
  1313. });
  1314. // Move blocks to content region and set them in right order by their
  1315. // weight.
  1316. foreach ($blocks as $block) {
  1317. $block->set('region', 'content');
  1318. $block->set('weight', $weight++);
  1319. $block->save();
  1320. }
  1321. break;
  1322. case 'seven':
  1323. $name = 'block.block.seven_local_actions';
  1324. $values = [
  1325. 'id' => 'seven_local_actions',
  1326. 'weight' => -10,
  1327. ] + $local_actions_default_settings;
  1328. _system_update_create_block($name, $theme_name, $values);
  1329. $name = 'block.block.seven_primary_local_tasks';
  1330. $values = [
  1331. 'region' => 'header',
  1332. 'id' => 'seven_primary_local_tasks',
  1333. 'settings.label' => 'Primary tabs',
  1334. 'settings.primary' => TRUE,
  1335. 'settings.secondary' => FALSE,
  1336. ] + $tabs_default_settings;
  1337. _system_update_create_block($name, $theme_name, $values);
  1338. $name = 'block.block.seven_secondary_local_tasks';
  1339. $values = [
  1340. 'region' => 'pre_content',
  1341. 'id' => 'seven_secondary_local_tasks',
  1342. 'settings.label' => 'Secondary tabs',
  1343. 'settings.primary' => FALSE,
  1344. 'settings.secondary' => TRUE,
  1345. ] + $tabs_default_settings;
  1346. _system_update_create_block($name, $theme_name, $values);
  1347. break;
  1348. case 'stark':
  1349. $name = 'block.block.stark_local_actions';
  1350. $values = [
  1351. 'id' => 'stark_local_actions',
  1352. ] + $local_actions_default_settings;
  1353. _system_update_create_block($name, $theme_name, $values);
  1354. $name = 'block.block.stark_local_tasks';
  1355. $values = [
  1356. 'id' => 'stark_local_tasks',
  1357. ] + $tabs_default_settings;
  1358. _system_update_create_block($name, $theme_name, $values);
  1359. break;
  1360. case 'classy':
  1361. case 'stable':
  1362. // Don't place any blocks or trigger custom themes installed warning.
  1363. break;
  1364. default:
  1365. $custom_themes_installed = TRUE;
  1366. $name = 'block.block.' . $theme_name . '_local_actions';
  1367. $values = [
  1368. 'id' => $theme_name . '_local_actions',
  1369. 'weight' => -10,
  1370. ] + $local_actions_default_settings;
  1371. _system_update_create_block($name, $theme_name, $values);
  1372. $name = sprintf('block.block.%s_local_tasks', $theme_name);
  1373. $values = [
  1374. 'id' => $theme_name . '_local_tasks',
  1375. 'weight' => -20,
  1376. ] + $tabs_default_settings;
  1377. _system_update_create_block($name, $theme_name, $values);
  1378. break;
  1379. }
  1380. }
  1381. if ($custom_themes_installed) {
  1382. $message = t('Because your site has custom theme(s) installed, we had to set local actions and tasks blocks into the content region. Please manually review the block configurations and remove the removed variables from your templates.');
  1383. }
  1384. return $message;
  1385. }
  1386. /**
  1387. * Place branding blocks in every theme.
  1388. */
  1389. function system_update_8006() {
  1390. // When block module is not installed, there is nothing that could be done
  1391. // except showing a warning.
  1392. if (!\Drupal::moduleHandler()->moduleExists('block')) {
  1393. return t('Block module is not enabled so site branding elements, which have been converted to a block, are not visible anymore.');
  1394. }
  1395. /** @var \Drupal\Core\Extension\ThemeHandlerInterface $theme_handler */
  1396. $theme_handler = \Drupal::service('theme_handler');
  1397. $custom_themes_installed = FALSE;
  1398. $message = NULL;
  1399. $langcode = \Drupal::service('language_manager')->getCurrentLanguage()->getId();
  1400. $site_branding_default_settings = [
  1401. 'plugin' => 'system_branding_block',
  1402. 'region' => 'content',
  1403. 'settings.label' => 'Site branding',
  1404. 'settings.label_display' => 0,
  1405. 'visibility' => [],
  1406. 'weight' => 0,
  1407. 'langcode' => $langcode,
  1408. ];
  1409. foreach ($theme_handler->listInfo() as $theme) {
  1410. $theme_name = $theme->getName();
  1411. switch ($theme_name) {
  1412. case 'bartik':
  1413. $name = 'block.block.bartik_branding';
  1414. $values = [
  1415. 'id' => 'bartik_branding',
  1416. 'region' => 'header',
  1417. ] + $site_branding_default_settings;
  1418. _system_update_create_block($name, $theme_name, $values);
  1419. break;
  1420. case 'stark':
  1421. $name = 'block.block.stark_branding';
  1422. $values = [
  1423. 'id' => 'stark_branding',
  1424. 'region' => 'header',
  1425. ] + $site_branding_default_settings;
  1426. _system_update_create_block($name, $theme_name, $values);
  1427. break;
  1428. case 'seven':
  1429. case 'classy':
  1430. case 'stable':
  1431. // Don't place any blocks or trigger custom themes installed warning.
  1432. break;
  1433. default:
  1434. $custom_themes_installed = TRUE;
  1435. $name = sprintf('block.block.%s_branding', $theme_name);
  1436. $values = [
  1437. 'id' => sprintf('%s_branding', $theme_name),
  1438. 'region' => 'content',
  1439. 'weight' => '-50',
  1440. ] + $site_branding_default_settings;
  1441. _system_update_create_block($name, $theme_name, $values);
  1442. break;
  1443. }
  1444. }
  1445. if ($custom_themes_installed) {
  1446. $message = t('Because your site has custom theme(s) installed, we had to set the branding block into the content region. Please manually review the block configuration and remove the site name, slogan, and logo variables from your templates.');
  1447. }
  1448. return $message;
  1449. }
  1450. /**
  1451. * Helper function to create block configuration objects for an update.
  1452. *
  1453. * @param string $name
  1454. * The name of the config object.
  1455. * @param string $theme_name
  1456. * The name of the theme the block is associated with.
  1457. * @param array $values
  1458. * The block config values.
  1459. */
  1460. function _system_update_create_block($name, $theme_name, array $values) {
  1461. if (!\Drupal::service('config.storage')->exists($name)) {
  1462. $block = \Drupal::configFactory()->getEditable($name);
  1463. $values['uuid'] = \Drupal::service('uuid')->generate();
  1464. $values['theme'] = $theme_name;
  1465. $values['dependencies.theme'] = [$theme_name];
  1466. foreach ($values as $key => $value) {
  1467. $block->set($key, $value);
  1468. }
  1469. $block->save();
  1470. }
  1471. }
  1472. /**
  1473. * Set langcode fields to be ASCII-only.
  1474. */
  1475. function system_update_8007() {
  1476. $database = \Drupal::database();
  1477. $database_schema = $database->schema();
  1478. $entity_types = \Drupal::entityManager()->getDefinitions();
  1479. $schema = \Drupal::keyValue('entity.storage_schema.sql')->getAll();
  1480. $schema_copy = $schema;
  1481. foreach ($schema as $item_name => $item) {
  1482. list($entity_type_id, ,) = explode('.', $item_name);
  1483. if (!isset($entity_types[$entity_type_id])) {
  1484. continue;
  1485. }
  1486. foreach ($item as $table_name => $table_schema) {
  1487. foreach ($table_schema as $schema_key => $schema_data) {
  1488. if ($schema_key == 'fields') {
  1489. foreach ($schema_data as $field_name => $field_data) {
  1490. foreach ($field_data as $field_data_property => $field_data_value) {
  1491. // Langcode fields have the property 'is_ascii' set, instead
  1492. // they should have set the type to 'varchar_ascii'.
  1493. if ($field_data_property == 'is_ascii') {
  1494. unset($schema_copy[$item_name][$table_name]['fields'][$field_name]['is_ascii']);
  1495. $schema_copy[$item_name][$table_name]['fields'][$field_name]['type'] = 'varchar_ascii';
  1496. if ($database->driver() == 'mysql') {
  1497. $database_schema->changeField($table_name, $field_name, $field_name, $schema_copy[$item_name][$table_name]['fields'][$field_name]);
  1498. }
  1499. }
  1500. }
  1501. }
  1502. }
  1503. }
  1504. }
  1505. }
  1506. \Drupal::keyValue('entity.storage_schema.sql')->setMultiple($schema_copy);
  1507. $definitions = \Drupal::keyValue('entity.definitions.installed')->getAll();
  1508. $definitions_copy = $definitions;
  1509. foreach ($definitions as $item_name => $item_value) {
  1510. $suffix = '.field_storage_definitions';
  1511. if (substr($item_name, -strlen($suffix)) == $suffix) {
  1512. foreach ($item_value as $field_name => $field_definition) {
  1513. $reflection = new \ReflectionObject($field_definition);
  1514. $schema_property = $reflection->getProperty('schema');
  1515. $schema_property->setAccessible(TRUE);
  1516. $schema = $schema_property->getValue($field_definition);
  1517. if (isset($schema['columns']['value']['is_ascii'])) {
  1518. $schema['columns']['value']['type'] = 'varchar_ascii';
  1519. unset($schema['columns']['value']['is_ascii']);
  1520. }
  1521. $schema_property->setValue($field_definition, $schema);
  1522. $schema_property->setAccessible(FALSE);
  1523. $definitions_copy[$item_name][$field_name] = $field_definition;
  1524. }
  1525. }
  1526. }
  1527. \Drupal::keyValue('entity.definitions.installed')->setMultiple($definitions_copy);
  1528. }
  1529. /**
  1530. * Purge field schema data for uninstalled entity types.
  1531. */
  1532. function system_update_8008() {
  1533. $entity_types = \Drupal::entityManager()->getDefinitions();
  1534. /** @var \Drupal\Core\KeyValueStore\KeyValueStoreInterface $schema */
  1535. $schema = \Drupal::keyValue('entity.storage_schema.sql');
  1536. foreach ($schema->getAll() as $key => $item) {
  1537. list($entity_type_id, ,) = explode('.', $key);
  1538. if (!isset($entity_types[$entity_type_id])) {
  1539. $schema->delete($key);
  1540. }
  1541. }
  1542. }
  1543. /**
  1544. * Add allowed attributes to existing html filters.
  1545. */
  1546. function system_update_8009() {
  1547. $default_mapping = [
  1548. '<a>' => '<a href hreflang>',
  1549. '<blockquote>' => '<blockquote cite>',
  1550. '<ol>' => '<ol start type>',
  1551. '<ul>' => '<ul type>',
  1552. '<img>' => '<img src alt height width>',
  1553. '<h2>' => '<h2 id>',
  1554. '<h3>' => '<h3 id>',
  1555. '<h4>' => '<h4 id>',
  1556. '<h5>' => '<h5 id>',
  1557. '<h6>' => '<h6 id>',
  1558. ];
  1559. $config_factory = \Drupal::configFactory();
  1560. foreach ($config_factory->listAll('filter.format') as $name) {
  1561. $allowed_html_mapping = $default_mapping;
  1562. $config = $config_factory->getEditable($name);
  1563. // The image alignment filter needs the data-align attribute.
  1564. $align_enabled = $config->get('filters.filter_align.status');
  1565. if ($align_enabled) {
  1566. $allowed_html_mapping['<img>'] = str_replace('>', ' data-align>', $allowed_html_mapping['<img>']);
  1567. }
  1568. // The image caption filter needs the data-caption attribute.
  1569. $caption_enabled = $config->get('filters.filter_caption.status');
  1570. if ($caption_enabled) {
  1571. $allowed_html_mapping['<img>'] = str_replace('>', ' data-caption>', $allowed_html_mapping['<img>']);
  1572. }
  1573. $allowed_html = $config->get('filters.filter_html.settings.allowed_html');
  1574. if (!empty($allowed_html)) {
  1575. $allowed_html = strtr($allowed_html, $allowed_html_mapping);
  1576. $config->set('filters.filter_html.settings.allowed_html', $allowed_html);
  1577. $config->save();
  1578. }
  1579. }
  1580. }
  1581. /**
  1582. * Place page title blocks in every theme.
  1583. */
  1584. function system_update_8010() {
  1585. // When block module is not installed, there is nothing that could be done
  1586. // except showing a warning.
  1587. if (!\Drupal::moduleHandler()->moduleExists('block')) {
  1588. return t('Block module is not enabled. The page title has been converted to a block, but default page title markup will still display at the top of the main content area.');
  1589. }
  1590. /** @var \Drupal\Core\Extension\ThemeHandlerInterface $theme_handler */
  1591. $theme_handler = \Drupal::service('theme_handler');
  1592. $custom_themes_installed = FALSE;
  1593. $message = NULL;
  1594. $langcode = \Drupal::service('language_manager')->getCurrentLanguage()->getId();
  1595. $page_title_default_settings = [
  1596. 'plugin' => 'page_title_block',
  1597. 'region' => 'content',
  1598. 'settings.label' => 'Page title',
  1599. 'settings.label_display' => 0,
  1600. 'visibility' => [],
  1601. 'weight' => -50,
  1602. 'langcode' => $langcode,
  1603. ];
  1604. foreach ($theme_handler->listInfo() as $theme) {
  1605. $theme_name = $theme->getName();
  1606. switch ($theme_name) {
  1607. case 'bartik':
  1608. $name = 'block.block.bartik_page_title';
  1609. $values = [
  1610. 'id' => 'bartik_page_title',
  1611. ] + $page_title_default_settings;
  1612. _system_update_create_block($name, $theme_name, $values);
  1613. break;
  1614. case 'stark':
  1615. $name = 'block.block.stark_page_title';
  1616. $values = [
  1617. 'id' => 'stark_page_title',
  1618. 'region' => 'content',
  1619. ] + $page_title_default_settings;
  1620. _system_update_create_block($name, $theme_name, $values);
  1621. break;
  1622. case 'seven':
  1623. $name = 'block.block.seven_page_title';
  1624. $values = [
  1625. 'id' => 'seven_page_title',
  1626. 'region' => 'header',
  1627. ] + $page_title_default_settings;
  1628. _system_update_create_block($name, $theme_name, $values);
  1629. break;
  1630. case 'classy':
  1631. $name = 'block.block.classy_page_title';
  1632. $values = [
  1633. 'id' => 'classy_page_title',
  1634. 'region' => 'content',
  1635. ] + $page_title_default_settings;
  1636. _system_update_create_block($name, $theme_name, $values);
  1637. break;
  1638. default:
  1639. $custom_themes_installed = TRUE;
  1640. $name = sprintf('block.block.%s_page_title', $theme_name);
  1641. $values = [
  1642. 'id' => sprintf('%s_page_title', $theme_name),
  1643. 'region' => 'content',
  1644. 'weight' => '-50',
  1645. ] + $page_title_default_settings;
  1646. _system_update_create_block($name, $theme_name, $values);
  1647. break;
  1648. }
  1649. }
  1650. if ($custom_themes_installed) {
  1651. $message = t('Because your site has custom theme(s) installed, we have placed the page title block in the content region. Please manually review the block configuration and remove the page title variables from your page templates.');
  1652. }
  1653. return $message;
  1654. }
  1655. /**
  1656. * Add secondary local tasks block to Seven (fixes system_update_8005).
  1657. */
  1658. function system_update_8011() {
  1659. $langcode = \Drupal::service('language_manager')->getCurrentLanguage()->getId();
  1660. $theme_name = 'seven';
  1661. $name = 'block.block.seven_secondary_local_tasks';
  1662. $values = [
  1663. 'plugin' => 'local_tasks_block',
  1664. 'region' => 'pre_content',
  1665. 'id' => 'seven_secondary_local_tasks',
  1666. 'settings.label' => 'Secondary tabs',
  1667. 'settings.label_display' => 0,
  1668. 'settings.primary' => FALSE,
  1669. 'settings.secondary' => TRUE,
  1670. 'visibility' => [],
  1671. 'weight' => 0,
  1672. 'langcode' => $langcode,
  1673. ];
  1674. _system_update_create_block($name, $theme_name, $values);
  1675. }
  1676. /**
  1677. * Enable automated cron module and move the config into it.
  1678. */
  1679. function system_update_8013() {
  1680. $config_factory = \Drupal::configFactory();
  1681. $system_cron_config = $config_factory->getEditable('system.cron');
  1682. if ($autorun = $system_cron_config->get('threshold.autorun')) {
  1683. // Install 'automated_cron' module.
  1684. \Drupal::service('module_installer')->install(['automated_cron'], FALSE);
  1685. // Copy 'autorun' value into the new module's 'interval' setting.
  1686. $config_factory->getEditable('automated_cron.settings')
  1687. ->set('interval', $autorun)
  1688. ->save(TRUE);
  1689. }
  1690. // Remove the 'autorun' key in system module config.
  1691. $system_cron_config
  1692. ->clear('threshold.autorun')
  1693. ->save(TRUE);
  1694. }
  1695. /**
  1696. * Install the Stable base theme if needed.
  1697. */
  1698. function system_update_8014() {
  1699. $theme_handler = \Drupal::service('theme_handler');
  1700. if ($theme_handler->themeExists('stable')) {
  1701. return;
  1702. }
  1703. $theme_handler->refreshInfo();
  1704. foreach ($theme_handler->listInfo() as $theme) {
  1705. // We first check that a base theme is set because if it's set to false then
  1706. // it's unset in \Drupal\Core\Extension\ThemeHandler::rebuildThemeData().
  1707. if (isset($theme->info['base theme']) && $theme->info['base theme'] == 'stable') {
  1708. $theme_handler->install(['stable']);
  1709. return;
  1710. }
  1711. }
  1712. }
  1713. /**
  1714. * Fix configuration overrides to not override non existing keys.
  1715. */
  1716. function system_update_8200(&$sandbox) {
  1717. $config_factory = \Drupal::configFactory();
  1718. if (!array_key_exists('config_names', $sandbox)) {
  1719. $sandbox['config_names'] = $config_factory->listAll();
  1720. $sandbox['max'] = count($sandbox['config_names']);
  1721. }
  1722. // Get a list of 50 to work on at a time.
  1723. $config_names_to_process = array_slice($sandbox['config_names'], 0, 50);
  1724. // Preload in a single query.
  1725. $config_factory->loadMultiple($config_names_to_process);
  1726. foreach ($config_names_to_process as $config_name) {
  1727. $config_factory->getEditable($config_name)->save();
  1728. }
  1729. // Update the list of names to process.
  1730. $sandbox['config_names'] = array_diff($sandbox['config_names'], $config_names_to_process);
  1731. $sandbox['#finished'] = empty($sandbox['config_names']) ? 1 : ($sandbox['max'] - count($sandbox['config_names'])) / $sandbox['max'];
  1732. }
  1733. /**
  1734. * Clear caches due to behavior change in DefaultPluginManager.
  1735. */
  1736. function system_update_8201() {
  1737. // Empty update to cause a cache rebuild.
  1738. // Use hook_post_update_NAME() instead to clear the cache.
  1739. // The use of hook_update_N() to clear the cache has been deprecated
  1740. // see https://www.drupal.org/node/2960601 for more details.
  1741. }
  1742. /**
  1743. * Clear caches due to behavior change in MachineName element.
  1744. */
  1745. function system_update_8202() {
  1746. // Empty update to cause a cache rebuild.
  1747. // Use hook_post_update_NAME() instead to clear the cache.The use
  1748. // of hook_update_N to clear the cache has been deprecated see
  1749. // https://www.drupal.org/node/2960601 for more details.
  1750. }
  1751. /**
  1752. * Add detailed cron logging configuration.
  1753. */
  1754. function system_update_8300() {
  1755. \Drupal::configFactory()->getEditable('system.cron')
  1756. ->set('logging', 1)
  1757. ->save(TRUE);
  1758. }
  1759. /**
  1760. * Add install profile to core.extension configuration.
  1761. */
  1762. function system_update_8301() {
  1763. \Drupal::configFactory()->getEditable('core.extension')
  1764. ->set('profile', \Drupal::installProfile())
  1765. ->save();
  1766. }
  1767. /**
  1768. * Move revision metadata fields to the revision table.
  1769. */
  1770. function system_update_8400(&$sandbox) {
  1771. // Due to the fields from RevisionLogEntityTrait not being explicitly
  1772. // mentioned in the storage they might have been installed wrongly in the base
  1773. // table for revisionable untranslatable entities and in the data and revision
  1774. // data tables for revisionable and translatable entities.
  1775. $entity_definition_update_manager = \Drupal::entityDefinitionUpdateManager();
  1776. $database = \Drupal::database();
  1777. $database_schema = $database->schema();
  1778. if (!isset($sandbox['current'])) {
  1779. // This must be the first run. Initialize the sandbox.
  1780. $sandbox['current'] = 0;
  1781. $definitions = array_filter(\Drupal::entityTypeManager()->getDefinitions(), function (EntityTypeInterface $entity_type) use ($entity_definition_update_manager) {
  1782. if ($entity_type = $entity_definition_update_manager->getEntityType($entity_type->id())) {
  1783. return is_subclass_of($entity_type->getClass(), FieldableEntityInterface::class) && ($entity_type instanceof ContentEntityTypeInterface) && $entity_type->isRevisionable();
  1784. }
  1785. return FALSE;
  1786. });
  1787. $sandbox['entity_type_ids'] = array_keys($definitions);
  1788. $sandbox['max'] = count($sandbox['entity_type_ids']);
  1789. }
  1790. $current_entity_type_key = $sandbox['current'];
  1791. for ($i = $current_entity_type_key; ($i < $current_entity_type_key + 1) && ($i < $sandbox['max']); $i++) {
  1792. $entity_type_id = $sandbox['entity_type_ids'][$i];
  1793. /** @var \Drupal\Core\Entity\ContentEntityTypeInterface $entity_type */
  1794. $entity_type = $entity_definition_update_manager->getEntityType($entity_type_id);
  1795. $base_fields = \Drupal::service('entity_field.manager')->getBaseFieldDefinitions($entity_type_id);
  1796. $revision_metadata_fields = $entity_type->getRevisionMetadataKeys();
  1797. $fields_to_update = array_intersect_key($base_fields, array_flip($revision_metadata_fields));
  1798. if (!empty($fields_to_update)) {
  1799. // Initialize the entity table names.
  1800. // @see \Drupal\Core\Entity\Sql\SqlContentEntityStorage::initTableLayout()
  1801. $base_table = $entity_type->getBaseTable() ?: $entity_type_id;
  1802. $data_table = $entity_type->getDataTable() ?: $entity_type_id . '_field_data';
  1803. $revision_table = $entity_type->getRevisionTable() ?: $entity_type_id . '_revision';
  1804. $revision_data_table = $entity_type->getRevisionDataTable() ?: $entity_type_id . '_field_revision';
  1805. $revision_field = $entity_type->getKey('revision');
  1806. // No data needs to be migrated if the entity type is not translatable.
  1807. if ($entity_type->isTranslatable()) {
  1808. if (!isset($sandbox[$entity_type_id])) {
  1809. // This must be the first run for this entity type. Initialize the
  1810. // sub-sandbox for it.
  1811. // Calculate the number of revisions to process.
  1812. $count = \Drupal::entityQuery($entity_type_id)
  1813. ->allRevisions()
  1814. ->count()
  1815. ->accessCheck(FALSE)
  1816. ->execute();
  1817. $sandbox[$entity_type_id]['current'] = 0;
  1818. $sandbox[$entity_type_id]['max'] = $count;
  1819. }
  1820. // Define the step size.
  1821. $steps = Settings::get('entity_update_batch_size', 50);
  1822. // Collect the revision IDs to process.
  1823. $revisions = \Drupal::entityQuery($entity_type_id)
  1824. ->allRevisions()
  1825. ->range($sandbox[$entity_type_id]['current'], $sandbox[$entity_type_id]['current'] + $steps)
  1826. ->sort($revision_field, 'ASC')
  1827. ->accessCheck(FALSE)
  1828. ->execute();
  1829. $revisions = array_keys($revisions);
  1830. foreach ($fields_to_update as $revision_metadata_field_name => $definition) {
  1831. // If the revision metadata field is present in the data and the
  1832. // revision data table, install its definition again with the updated
  1833. // storage code in order for the field to be installed in the
  1834. // revision table. Afterwards, copy over the field values and remove
  1835. // the field from the data and the revision data tables.
  1836. if ($database_schema->fieldExists($data_table, $revision_metadata_field_name) && $database_schema->fieldExists($revision_data_table, $revision_metadata_field_name)) {
  1837. // Install the field in the revision table.
  1838. if (!isset($sandbox[$entity_type_id]['storage_definition_installed'][$revision_metadata_field_name])) {
  1839. $entity_definition_update_manager->installFieldStorageDefinition($revision_metadata_field_name, $entity_type_id, $entity_type->getProvider(), $definition);
  1840. $sandbox[$entity_type_id]['storage_definition_installed'][$revision_metadata_field_name] = TRUE;
  1841. }
  1842. // Apply the field value from the revision data table to the
  1843. // revision table.
  1844. foreach ($revisions as $rev_id) {
  1845. $field_value = $database->select($revision_data_table, 't')
  1846. ->fields('t', [$revision_metadata_field_name])
  1847. ->condition($revision_field, $rev_id)
  1848. ->execute()
  1849. ->fetchField();
  1850. $database->update($revision_table)
  1851. ->condition($revision_field, $rev_id)
  1852. ->fields([$revision_metadata_field_name => $field_value])
  1853. ->execute();
  1854. }
  1855. }
  1856. }
  1857. $sandbox[$entity_type_id]['current'] += count($revisions);
  1858. $sandbox[$entity_type_id]['finished'] = ($sandbox[$entity_type_id]['current'] == $sandbox[$entity_type_id]['max']) || empty($revisions);
  1859. if ($sandbox[$entity_type_id]['finished']) {
  1860. foreach ($fields_to_update as $revision_metadata_field_name => $definition) {
  1861. // Drop the field from the data and revision data tables.
  1862. $database_schema->dropField($data_table, $revision_metadata_field_name);
  1863. $database_schema->dropField($revision_data_table, $revision_metadata_field_name);
  1864. }
  1865. $sandbox['current']++;
  1866. }
  1867. }
  1868. else {
  1869. foreach ($fields_to_update as $revision_metadata_field_name => $definition) {
  1870. if ($database_schema->fieldExists($base_table, $revision_metadata_field_name)) {
  1871. // Install the field in the revision table.
  1872. $entity_definition_update_manager->installFieldStorageDefinition($revision_metadata_field_name, $entity_type_id, $entity_type->getProvider(), $definition);
  1873. // Drop the field from the base table.
  1874. $database_schema->dropField($base_table, $revision_metadata_field_name);
  1875. }
  1876. }
  1877. $sandbox['current']++;
  1878. }
  1879. }
  1880. else {
  1881. $sandbox['current']++;
  1882. }
  1883. }
  1884. $sandbox['#finished'] = $sandbox['current'] == $sandbox['max'];
  1885. }
  1886. /**
  1887. * Remove response.gzip (and response) from system module configuration.
  1888. */
  1889. function system_update_8401() {
  1890. \Drupal::configFactory()->getEditable('system.performance')
  1891. ->clear('response.gzip')
  1892. ->clear('response')
  1893. ->save();
  1894. }
  1895. /**
  1896. * Add the 'revision_translation_affected' field to all entity types.
  1897. */
  1898. function system_update_8402() {
  1899. $definition_update_manager = \Drupal::entityDefinitionUpdateManager();
  1900. // Clear the cached entity type definitions so we get the new
  1901. // 'revision_translation_affected' entity key.
  1902. \Drupal::entityTypeManager()->clearCachedDefinitions();
  1903. // Get a list of revisionable and translatable entity types.
  1904. /** @var \Drupal\Core\Entity\ContentEntityTypeInterface[] $definitions */
  1905. $definitions = array_filter(\Drupal::entityTypeManager()->getDefinitions(), function (EntityTypeInterface $entity_type) use ($definition_update_manager) {
  1906. if ($entity_type = $definition_update_manager->getEntityType($entity_type->id())) {
  1907. return $entity_type->isRevisionable() && $entity_type->isTranslatable();
  1908. }
  1909. return FALSE;
  1910. });
  1911. foreach ($definitions as $entity_type_id => $entity_type) {
  1912. $field_name = $entity_type->getKey('revision_translation_affected');
  1913. // Install the 'revision_translation_affected' field if needed.
  1914. if (!$definition_update_manager->getFieldStorageDefinition($field_name, $entity_type_id)) {
  1915. $storage_definition = BaseFieldDefinition::create('boolean')
  1916. ->setLabel(t('Revision translation affected'))
  1917. ->setDescription(t('Indicates if the last edit of a translation belongs to current revision.'))
  1918. ->setReadOnly(TRUE)
  1919. ->setRevisionable(TRUE)
  1920. ->setTranslatable(TRUE)
  1921. // Mark all pre-existing revisions as affected in order to be consistent
  1922. // with the previous API return value: if the field was not defined the
  1923. // value returned was always TRUE.
  1924. ->setInitialValue(TRUE);
  1925. $definition_update_manager
  1926. ->installFieldStorageDefinition($field_name, $entity_type_id, $entity_type_id, $storage_definition);
  1927. }
  1928. }
  1929. }
  1930. /**
  1931. * Delete all cache_* tables. They are recreated on demand with the new schema.
  1932. */
  1933. function system_update_8403() {
  1934. foreach (Cache::getBins() as $bin => $cache_backend) {
  1935. // Try to delete the table regardless of which cache backend is handling it.
  1936. // This is to ensure the new schema is used if the configuration for the
  1937. // backend class is changed after the update hook runs.
  1938. $table_name = "cache_$bin";
  1939. $schema = Database::getConnection()->schema();
  1940. if ($schema->tableExists($table_name)) {
  1941. $schema->dropTable($table_name);
  1942. }
  1943. }
  1944. }
  1945. /**
  1946. * Add the 'revision_default' field to all relevant entity types.
  1947. */
  1948. function system_update_8501() {
  1949. $definition_update_manager = \Drupal::entityDefinitionUpdateManager();
  1950. // Clear the cached entity type definitions so we get the new
  1951. // 'revision_default' revision metadata key.
  1952. \Drupal::entityTypeManager()->clearCachedDefinitions();
  1953. // Get a list of revisionable entity types.
  1954. /** @var \Drupal\Core\Entity\ContentEntityTypeInterface[] $definitions */
  1955. $definitions = array_filter(\Drupal::entityTypeManager()->getDefinitions(), function (EntityTypeInterface $entity_type) use ($definition_update_manager) {
  1956. if ($entity_type = $definition_update_manager->getEntityType($entity_type->id())) {
  1957. return $entity_type->isRevisionable();
  1958. }
  1959. return FALSE;
  1960. });
  1961. // Install the 'revision_default' field.
  1962. foreach ($definitions as $entity_type_id => $entity_type) {
  1963. $field_name = $entity_type->getRevisionMetadataKey('revision_default');
  1964. // Install the 'revision_default' field if needed.
  1965. if (!$definition_update_manager->getFieldStorageDefinition($field_name, $entity_type_id)) {
  1966. // Make sure the new "revision_default" revision metadata key is available
  1967. // also to code using the latest installed definition.
  1968. $installed_entity_type = $definition_update_manager->getEntityType($entity_type_id);
  1969. $revision_metadata_keys = $installed_entity_type->get('revision_metadata_keys');
  1970. if (!isset($revision_metadata_keys['revision_default'])) {
  1971. // Update the property holding the required revision metadata keys,
  1972. // which is used by the BC layer for retrieving the revision metadata
  1973. // keys.
  1974. // @see \Drupal\Core\Entity\ContentEntityType::getRevisionMetadataKeys().
  1975. $required_revision_metadata_keys = $installed_entity_type->get('requiredRevisionMetadataKeys');
  1976. $required_revision_metadata_keys['revision_default'] = $field_name;
  1977. $installed_entity_type->set('requiredRevisionMetadataKeys', $required_revision_metadata_keys);
  1978. // Update the revision metadata keys to add the new required revision
  1979. // metadata key "revision_default".
  1980. $revision_metadata_keys['revision_default'] = $required_revision_metadata_keys['revision_default'];
  1981. $installed_entity_type->set('revision_metadata_keys', $revision_metadata_keys);
  1982. $definition_update_manager->updateEntityType($installed_entity_type);
  1983. }
  1984. $storage_definition = BaseFieldDefinition::create('boolean')
  1985. ->setLabel(t('Default revision'))
  1986. ->setDescription(t('A flag indicating whether this was a default revision when it was saved.'))
  1987. ->setStorageRequired(TRUE)
  1988. ->setTranslatable(FALSE)
  1989. ->setRevisionable(TRUE)
  1990. // We cannot tell whether existing revisions were default or not when
  1991. // they were created, but since we did not support creating non-default
  1992. // revisions in any core stable UI so far, we default to TRUE.
  1993. ->setInitialValue(TRUE);
  1994. $definition_update_manager
  1995. ->installFieldStorageDefinition($field_name, $entity_type_id, $entity_type_id, $storage_definition);
  1996. }
  1997. else {
  1998. $variables = ['@entity_type_label' => $entity_type->getLabel()];
  1999. if ($field_name === 'revision_default') {
  2000. \Drupal::logger('system')->error('An existing "Default revision" field was found for the @entity_type_label entity type, but no "revision_default" revision metadata key was found in its definition.', $variables);
  2001. }
  2002. else {
  2003. \Drupal::logger('system')->error('An existing "Default revision" field was found for the @entity_type_label entity type.', $variables);
  2004. }
  2005. }
  2006. }
  2007. }