system.install 119 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850
  1. <?php
  2. /**
  3. * @file
  4. * Install, update and uninstall functions for the system module.
  5. */
  6. use Drupal\Component\FileSystem\FileSystem as FileSystemComponent;
  7. use Drupal\Component\Utility\Bytes;
  8. use Drupal\Component\Utility\Crypt;
  9. use Drupal\Component\Utility\Environment;
  10. use Drupal\Component\Utility\OpCodeCache;
  11. use Drupal\Component\Utility\Unicode;
  12. use Drupal\Core\Cache\Cache;
  13. use Drupal\Core\Database\Database;
  14. use Drupal\Core\DrupalKernel;
  15. use Drupal\Core\Entity\ContentEntityTypeInterface;
  16. use Drupal\Core\Entity\EntityTypeInterface;
  17. use Drupal\Core\Entity\FieldableEntityInterface;
  18. use Drupal\Core\Entity\Sql\SqlContentEntityStorage;
  19. use Drupal\Core\Entity\Sql\SqlContentEntityStorageSchema;
  20. use Drupal\Core\Extension\Extension;
  21. use Drupal\Core\Field\BaseFieldDefinition;
  22. use Drupal\Core\File\FileSystemInterface;
  23. use Drupal\Core\StringTranslation\PluralTranslatableMarkup;
  24. use Drupal\path_alias\Entity\PathAlias;
  25. use Drupal\path_alias\PathAliasStorage;
  26. use Drupal\Core\Site\Settings;
  27. use Drupal\Core\StreamWrapper\PrivateStream;
  28. use Drupal\Core\StreamWrapper\PublicStream;
  29. use Drupal\Core\StringTranslation\TranslatableMarkup;
  30. use Drupal\Core\Url;
  31. use Symfony\Component\HttpFoundation\Request;
  32. /**
  33. * Implements hook_requirements().
  34. */
  35. function system_requirements($phase) {
  36. global $install_state;
  37. // Reset the extension lists.
  38. \Drupal::service('extension.list.module')->reset();
  39. \Drupal::service('extension.list.theme')->reset();
  40. $requirements = [];
  41. // Report Drupal version
  42. if ($phase == 'runtime') {
  43. $requirements['drupal'] = [
  44. 'title' => t('Drupal'),
  45. 'value' => \Drupal::VERSION,
  46. 'severity' => REQUIREMENT_INFO,
  47. 'weight' => -10,
  48. ];
  49. // Display the currently active installation profile, if the site
  50. // is not running the default installation profile.
  51. $profile = \Drupal::installProfile();
  52. if ($profile != 'standard') {
  53. $info = \Drupal::service('extension.list.module')->getExtensionInfo($profile);
  54. $requirements['install_profile'] = [
  55. 'title' => t('Installation profile'),
  56. 'value' => t('%profile_name (%profile-%version)', [
  57. '%profile_name' => $info['name'],
  58. '%profile' => $profile,
  59. '%version' => $info['version'],
  60. ]),
  61. 'severity' => REQUIREMENT_INFO,
  62. 'weight' => -9,
  63. ];
  64. }
  65. // Warn if any experimental modules are installed.
  66. $experimental_modules = [];
  67. $enabled_modules = \Drupal::moduleHandler()->getModuleList();
  68. foreach ($enabled_modules as $module => $data) {
  69. $info = \Drupal::service('extension.list.module')->getExtensionInfo($module);
  70. if (isset($info['package']) && $info['package'] === 'Core (Experimental)') {
  71. $experimental_modules[$module] = $info['name'];
  72. }
  73. }
  74. if (!empty($experimental_modules)) {
  75. $requirements['experimental_modules'] = [
  76. 'title' => t('Experimental modules enabled'),
  77. '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_modules), ':url' => 'https://www.drupal.org/core/experimental']),
  78. 'severity' => REQUIREMENT_WARNING,
  79. ];
  80. }
  81. // Warn if any experimental themes are installed.
  82. $experimental_themes = [];
  83. $installed_themes = \Drupal::service('theme_handler')->listInfo();
  84. foreach ($installed_themes as $theme => $data) {
  85. if (isset($data->info['experimental']) && $data->info['experimental']) {
  86. $experimental_themes[$theme] = $data->info['name'];
  87. }
  88. }
  89. if (!empty($experimental_themes)) {
  90. $requirements['experimental_themes'] = [
  91. 'title' => t('Experimental themes enabled'),
  92. 'value' => t('Experimental themes found: %theme_list. Experimental themes are provided for testing purposes only. Use at your own risk.', ['%theme_list' => implode(', ', $experimental_themes)]),
  93. 'severity' => REQUIREMENT_WARNING,
  94. ];
  95. }
  96. }
  97. // Web server information.
  98. $request_object = \Drupal::request();
  99. $software = $request_object->server->get('SERVER_SOFTWARE');
  100. $requirements['webserver'] = [
  101. 'title' => t('Web server'),
  102. 'value' => $software,
  103. ];
  104. // Tests clean URL support.
  105. if ($phase == 'install' && $install_state['interactive'] && !$request_object->query->has('rewrite') && strpos($software, 'Apache') !== FALSE) {
  106. // If the Apache rewrite module is not enabled, Apache version must be >=
  107. // 2.2.16 because of the FallbackResource directive in the root .htaccess
  108. // file. Since the Apache version reported by the server is dependent on the
  109. // ServerTokens setting in httpd.conf, we may not be able to determine if a
  110. // given config is valid. Thus we are unable to use version_compare() as we
  111. // need have three possible outcomes: the version of Apache is greater than
  112. // 2.2.16, is less than 2.2.16, or cannot be determined accurately. In the
  113. // first case, we encourage the use of mod_rewrite; in the second case, we
  114. // raise an error regarding the minimum Apache version; in the third case,
  115. // we raise a warning that the current version of Apache may not be
  116. // supported.
  117. $rewrite_warning = FALSE;
  118. $rewrite_error = FALSE;
  119. $apache_version_string = 'Apache';
  120. // Determine the Apache version number: major, minor and revision.
  121. if (preg_match('/Apache\/(\d+)\.?(\d+)?\.?(\d+)?/', $software, $matches)) {
  122. $apache_version_string = $matches[0];
  123. // Major version number
  124. if ($matches[1] < 2) {
  125. $rewrite_error = TRUE;
  126. }
  127. elseif ($matches[1] == 2) {
  128. if (!isset($matches[2])) {
  129. $rewrite_warning = TRUE;
  130. }
  131. elseif ($matches[2] < 2) {
  132. $rewrite_error = TRUE;
  133. }
  134. elseif ($matches[2] == 2) {
  135. if (!isset($matches[3])) {
  136. $rewrite_warning = TRUE;
  137. }
  138. elseif ($matches[3] < 16) {
  139. $rewrite_error = TRUE;
  140. }
  141. }
  142. }
  143. }
  144. else {
  145. $rewrite_warning = TRUE;
  146. }
  147. if ($rewrite_warning) {
  148. $requirements['apache_version'] = [
  149. 'title' => t('Apache version'),
  150. 'value' => $apache_version_string,
  151. 'severity' => REQUIREMENT_WARNING,
  152. '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]),
  153. ];
  154. }
  155. if ($rewrite_error) {
  156. $requirements['Apache version'] = [
  157. 'title' => t('Apache version'),
  158. 'value' => $apache_version_string,
  159. 'severity' => REQUIREMENT_ERROR,
  160. '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/docs/8/clean-urls-in-drupal-8']),
  161. ];
  162. }
  163. if (!$rewrite_error && !$rewrite_warning) {
  164. $requirements['rewrite_module'] = [
  165. 'title' => t('Clean URLs'),
  166. 'value' => t('Disabled'),
  167. 'severity' => REQUIREMENT_WARNING,
  168. '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/docs/8/clean-urls-in-drupal-8']),
  169. ];
  170. }
  171. }
  172. // Verify the user is running a supported PHP version.
  173. // If the site is running a recommended version of PHP, just display it
  174. // as an informational message on the status report. This will be overridden
  175. // with an error or warning if the site is running older PHP versions for
  176. // which Drupal has already or will soon drop support.
  177. $phpversion = $phpversion_label = phpversion();
  178. if (function_exists('phpinfo')) {
  179. if ($phase === 'runtime') {
  180. $phpversion_label = t('@phpversion (<a href=":url">more information</a>)', ['@phpversion' => $phpversion, ':url' => (new Url('system.php'))->toString()]);
  181. }
  182. $requirements['php'] = [
  183. 'title' => t('PHP'),
  184. 'value' => $phpversion_label,
  185. ];
  186. }
  187. else {
  188. // @todo Revisit whether this description makes sense in
  189. // https://www.drupal.org/project/drupal/issues/2927318.
  190. $requirements['php'] = [
  191. 'title' => t('PHP'),
  192. 'value' => $phpversion_label,
  193. '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']),
  194. 'severity' => REQUIREMENT_INFO,
  195. ];
  196. }
  197. // Check if the PHP version is below what Drupal supports.
  198. if (version_compare($phpversion, DRUPAL_MINIMUM_SUPPORTED_PHP) < 0) {
  199. $requirements['php']['description'] = t('Your PHP installation is too old. Drupal requires at least PHP %version. 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.',
  200. [
  201. '%version' => DRUPAL_MINIMUM_SUPPORTED_PHP,
  202. '%recommended' => DRUPAL_RECOMMENDED_PHP,
  203. ':php_requirements' => 'https://www.drupal.org/docs/8/system-requirements/php',
  204. ]
  205. );
  206. $requirements['php']['severity'] = REQUIREMENT_ERROR;
  207. // If the PHP version is also below the absolute minimum allowed, it's not
  208. // safe to continue with the requirements check.
  209. if (version_compare($phpversion, DRUPAL_MINIMUM_PHP) < 0) {
  210. return $requirements;
  211. }
  212. // Otherwise downgrade the error to a warning during updates. Even if there
  213. // are some problems with the site's PHP version, it's still better for the
  214. // site to keep its Drupal codebase up to date.
  215. elseif ($phase === 'update') {
  216. $requirements['php']['severity'] = REQUIREMENT_WARNING;
  217. }
  218. // Since we allow sites with unsupported PHP versions to still run Drupal
  219. // updates, we also need to be able to run tests with those PHP versions,
  220. // which requires the ability to install test sites. Not all tests are
  221. // required to pass on these PHP versions, but we want to monitor which
  222. // ones do and don't.
  223. elseif ($phase === 'install' && drupal_valid_test_ua()) {
  224. $requirements['php']['severity'] = REQUIREMENT_INFO;
  225. }
  226. }
  227. // For PHP versions that are still supported but no longer recommended,
  228. // inform users of what's recommended, allowing them to take action before it
  229. // becomes urgent.
  230. elseif ($phase === 'runtime' && version_compare($phpversion, DRUPAL_RECOMMENDED_PHP) < 0) {
  231. $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']);
  232. $requirements['php']['severity'] = REQUIREMENT_INFO;
  233. }
  234. // Test for PHP extensions.
  235. $requirements['php_extensions'] = [
  236. 'title' => t('PHP extensions'),
  237. ];
  238. $missing_extensions = [];
  239. $required_extensions = [
  240. 'date',
  241. 'dom',
  242. 'filter',
  243. 'gd',
  244. 'hash',
  245. 'json',
  246. 'pcre',
  247. 'pdo',
  248. 'session',
  249. 'SimpleXML',
  250. 'SPL',
  251. 'tokenizer',
  252. 'xml',
  253. ];
  254. foreach ($required_extensions as $extension) {
  255. if (!extension_loaded($extension)) {
  256. $missing_extensions[] = $extension;
  257. }
  258. }
  259. if (!empty($missing_extensions)) {
  260. $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):', [
  261. ':system_requirements' => 'https://www.drupal.org/requirements',
  262. ]);
  263. // We use twig inline_template to avoid twig's autoescape.
  264. $description = [
  265. '#type' => 'inline_template',
  266. '#template' => '{{ description }}{{ missing_extensions }}',
  267. '#context' => [
  268. 'description' => $description,
  269. 'missing_extensions' => [
  270. '#theme' => 'item_list',
  271. '#items' => $missing_extensions,
  272. ],
  273. ],
  274. ];
  275. $requirements['php_extensions']['value'] = t('Disabled');
  276. $requirements['php_extensions']['severity'] = REQUIREMENT_ERROR;
  277. $requirements['php_extensions']['description'] = $description;
  278. }
  279. else {
  280. $requirements['php_extensions']['value'] = t('Enabled');
  281. }
  282. if ($phase == 'install' || $phase == 'runtime') {
  283. // Check to see if OPcache is installed.
  284. if (!OpCodeCache::isEnabled()) {
  285. $requirements['php_opcache'] = [
  286. 'value' => t('Not enabled'),
  287. 'severity' => REQUIREMENT_WARNING,
  288. '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.'),
  289. ];
  290. }
  291. else {
  292. $requirements['php_opcache']['value'] = t('Enabled');
  293. }
  294. $requirements['php_opcache']['title'] = t('PHP OPcode caching');
  295. }
  296. // Check to see if APCu is installed and configured correctly.
  297. if ($phase == 'runtime' && PHP_SAPI != 'cli') {
  298. $requirements['php_apcu']['title'] = t('PHP APCu caching');
  299. if (extension_loaded('apcu') && filter_var(ini_get('apc.enabled'), FILTER_VALIDATE_BOOLEAN)) {
  300. $memory_info = apcu_sma_info(TRUE);
  301. $apcu_actual_size = format_size($memory_info['seg_size']);
  302. $apcu_recommended_size = '32 MB';
  303. $requirements['php_apcu']['value'] = t('Enabled (@size)', ['@size' => $apcu_actual_size]);
  304. if (Bytes::toInt($apcu_actual_size) < Bytes::toInt($apcu_recommended_size)) {
  305. $requirements['php_apcu']['severity'] = REQUIREMENT_WARNING;
  306. $requirements['php_apcu']['description'] = t('Depending on your configuration, Drupal can run with a @apcu_size APCu limit. However, a @apcu_default_size APCu limit (the default) or above is recommended, especially if your site uses additional custom or contributed modules.', [
  307. '@apcu_size' => $apcu_actual_size,
  308. '@apcu_default_size' => $apcu_recommended_size,
  309. ]);
  310. }
  311. else {
  312. $memory_available = $memory_info['avail_mem'] / $memory_info['seg_size'];
  313. if ($memory_available < 0.1) {
  314. $requirements['php_apcu']['severity'] = REQUIREMENT_ERROR;
  315. }
  316. elseif ($memory_available < 0.25) {
  317. $requirements['php_apcu']['severity'] = REQUIREMENT_WARNING;
  318. }
  319. else {
  320. $requirements['php_apcu']['severity'] = REQUIREMENT_OK;
  321. }
  322. $requirements['php_apcu']['description'] = t('Memory available: @available.', [
  323. '@available' => format_size($memory_info['avail_mem']),
  324. ]);
  325. }
  326. }
  327. else {
  328. $requirements['php_apcu'] += [
  329. 'value' => t('Not enabled'),
  330. 'severity' => REQUIREMENT_INFO,
  331. 'description' => t('PHP APCu caching can improve your site\'s performance considerably. It is <strong>highly recommended</strong> to have <a href="https://www.php.net/manual/apcu.installation.php" target="_blank">APCu</a> installed on your server.'),
  332. ];
  333. }
  334. }
  335. if ($phase != 'update') {
  336. // Test whether we have a good source of random bytes.
  337. $requirements['php_random_bytes'] = [
  338. 'title' => t('Random number generation'),
  339. ];
  340. try {
  341. $bytes = random_bytes(10);
  342. if (strlen($bytes) != 10) {
  343. throw new \Exception("Tried to generate 10 random bytes, generated '" . strlen($bytes) . "'");
  344. }
  345. $requirements['php_random_bytes']['value'] = t('Successful');
  346. }
  347. catch (\Exception $e) {
  348. // If /dev/urandom is not available on a UNIX-like system, check whether
  349. // open_basedir restrictions are the cause.
  350. $open_basedir_blocks_urandom = FALSE;
  351. if (DIRECTORY_SEPARATOR === '/' && !@is_readable('/dev/urandom')) {
  352. $open_basedir = ini_get('open_basedir');
  353. if ($open_basedir) {
  354. $open_basedir_paths = explode(PATH_SEPARATOR, $open_basedir);
  355. $open_basedir_blocks_urandom = !array_intersect(['/dev', '/dev/', '/dev/urandom'], $open_basedir_paths);
  356. }
  357. }
  358. $args = [
  359. ':drupal-php' => 'https://www.drupal.org/docs/8/system-requirements/php-requirements',
  360. '%exception_message' => $e->getMessage(),
  361. ];
  362. if ($open_basedir_blocks_urandom) {
  363. $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);
  364. }
  365. else {
  366. $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);
  367. }
  368. $requirements['php_random_bytes']['value'] = t('Less secure');
  369. $requirements['php_random_bytes']['severity'] = REQUIREMENT_ERROR;
  370. }
  371. }
  372. if ($phase == 'install' || $phase == 'update') {
  373. // Test for PDO (database).
  374. $requirements['database_extensions'] = [
  375. 'title' => t('Database support'),
  376. ];
  377. // Make sure PDO is available.
  378. $database_ok = extension_loaded('pdo');
  379. if (!$database_ok) {
  380. $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.', [
  381. ':link' => 'https://www.drupal.org/requirements/pdo',
  382. ]);
  383. }
  384. else {
  385. // Make sure at least one supported database driver exists.
  386. $drivers = drupal_detect_database_types();
  387. if (empty($drivers)) {
  388. $database_ok = FALSE;
  389. $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>.', [
  390. ':drupal-databases' => 'https://www.drupal.org/requirements/database',
  391. ]);
  392. }
  393. // Make sure the native PDO extension is available, not the older PEAR
  394. // version. (See install_verify_pdo() for details.)
  395. if (!defined('PDO::ATTR_DEFAULT_FETCH_MODE')) {
  396. $database_ok = FALSE;
  397. $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.', [
  398. ':link' => 'https://www.drupal.org/requirements/pdo#pecl',
  399. ]);
  400. }
  401. }
  402. if (!$database_ok) {
  403. $requirements['database_extensions']['value'] = t('Disabled');
  404. $requirements['database_extensions']['severity'] = REQUIREMENT_ERROR;
  405. $requirements['database_extensions']['description'] = $pdo_message;
  406. }
  407. else {
  408. $requirements['database_extensions']['value'] = t('Enabled');
  409. }
  410. }
  411. if ($phase === 'runtime' || $phase === 'update') {
  412. // Database information.
  413. $class = Database::getConnection()->getDriverClass('Install\\Tasks');
  414. /** @var \Drupal\Core\Database\Install\Tasks $tasks */
  415. $tasks = new $class();
  416. $requirements['database_system'] = [
  417. 'title' => t('Database system'),
  418. 'value' => $tasks->name(),
  419. ];
  420. $requirements['database_system_version'] = [
  421. 'title' => t('Database system version'),
  422. 'value' => Database::getConnection()->version(),
  423. ];
  424. $errors = $tasks->engineVersionRequirementsCheck();
  425. $error_count = count($errors);
  426. if ($error_count > 0) {
  427. $error_message = [
  428. '#theme' => 'item_list',
  429. '#items' => $errors,
  430. // Use the comma-list style to display a single error without bullets.
  431. '#context' => ['list_style' => $error_count === 1 ? 'comma-list' : ''],
  432. ];
  433. $requirements['database_system_version']['severity'] = REQUIREMENT_ERROR;
  434. $requirements['database_system_version']['description'] = $error_message;
  435. }
  436. }
  437. // Test PHP memory_limit
  438. $memory_limit = ini_get('memory_limit');
  439. $requirements['php_memory_limit'] = [
  440. 'title' => t('PHP memory limit'),
  441. 'value' => $memory_limit == -1 ? t('-1 (Unlimited)') : $memory_limit,
  442. ];
  443. if (!Environment::checkMemoryLimit(DRUPAL_MINIMUM_PHP_MEMORY_LIMIT, $memory_limit)) {
  444. $description = [];
  445. if ($phase == 'install') {
  446. $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]);
  447. }
  448. elseif ($phase == 'update') {
  449. $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]);
  450. }
  451. elseif ($phase == 'runtime') {
  452. $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]);
  453. }
  454. if (!empty($description['phase'])) {
  455. if ($php_ini_path = get_cfg_var('cfg_file_path')) {
  456. $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]);
  457. }
  458. else {
  459. $description['memory'] = t('Contact your system administrator or hosting provider for assistance with increasing your PHP memory limit.');
  460. }
  461. $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']);
  462. $description = [
  463. '#type' => 'inline_template',
  464. '#template' => '{{ description_phase }} {{ description_memory }} {{ handbook }}',
  465. '#context' => [
  466. 'description_phase' => $description['phase'],
  467. 'description_memory' => $description['memory'],
  468. 'handbook' => $handbook_link,
  469. ],
  470. ];
  471. $requirements['php_memory_limit']['description'] = $description;
  472. $requirements['php_memory_limit']['severity'] = REQUIREMENT_WARNING;
  473. }
  474. }
  475. // Test configuration files and directory for writability.
  476. if ($phase == 'runtime') {
  477. $conf_errors = [];
  478. // Find the site path. Kernel service is not always available at this point,
  479. // but is preferred, when available.
  480. if (\Drupal::hasService('kernel')) {
  481. $site_path = \Drupal::service('site.path');
  482. }
  483. else {
  484. $site_path = DrupalKernel::findSitePath(Request::createFromGlobals());
  485. }
  486. // Allow system administrators to disable permissions hardening for the site
  487. // directory. This allows additional files in the site directory to be
  488. // updated when they are managed in a version control system.
  489. if (Settings::get('skip_permissions_hardening')) {
  490. $error_value = t('Protection disabled');
  491. // If permissions hardening is disabled, then only show a warning for a
  492. // writable file, as a reminder, rather than an error.
  493. $file_protection_severity = REQUIREMENT_WARNING;
  494. }
  495. else {
  496. $error_value = t('Not protected');
  497. // In normal operation, writable files or directories are an error.
  498. $file_protection_severity = REQUIREMENT_ERROR;
  499. if (!drupal_verify_install_file($site_path, FILE_NOT_WRITABLE, 'dir')) {
  500. $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]);
  501. }
  502. }
  503. foreach (['settings.php', 'settings.local.php', 'services.yml'] as $conf_file) {
  504. $full_path = $site_path . '/' . $conf_file;
  505. if (file_exists($full_path) && !drupal_verify_install_file($full_path, FILE_EXIST | FILE_READABLE | FILE_NOT_WRITABLE, 'file', !Settings::get('skip_permissions_hardening'))) {
  506. $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]);
  507. }
  508. }
  509. if (!empty($conf_errors)) {
  510. if (count($conf_errors) == 1) {
  511. $description = $conf_errors[0];
  512. }
  513. else {
  514. // We use twig inline_template to avoid double escaping.
  515. $description = [
  516. '#type' => 'inline_template',
  517. '#template' => '{{ configuration_error_list }}',
  518. '#context' => [
  519. 'configuration_error_list' => [
  520. '#theme' => 'item_list',
  521. '#items' => $conf_errors,
  522. ],
  523. ],
  524. ];
  525. }
  526. $requirements['configuration_files'] = [
  527. 'value' => $error_value,
  528. 'severity' => $file_protection_severity,
  529. 'description' => $description,
  530. ];
  531. }
  532. else {
  533. $requirements['configuration_files'] = [
  534. 'value' => t('Protected'),
  535. ];
  536. }
  537. $requirements['configuration_files']['title'] = t('Configuration files');
  538. }
  539. // Test the contents of the .htaccess files.
  540. if ($phase == 'runtime') {
  541. // Try to write the .htaccess files first, to prevent false alarms in case
  542. // (for example) the /tmp directory was wiped.
  543. /** @var \Drupal\Core\File\HtaccessWriterInterface $htaccessWriter */
  544. $htaccessWriter = \Drupal::service("file.htaccess_writer");
  545. $htaccessWriter->ensure();
  546. foreach ($htaccessWriter->defaultProtectedDirs() as $protected_dir) {
  547. $htaccess_file = $protected_dir->getPath() . '/.htaccess';
  548. // Check for the string which was added to the recommended .htaccess file
  549. // in the latest security update.
  550. if (!file_exists($htaccess_file) || !($contents = @file_get_contents($htaccess_file)) || strpos($contents, 'Drupal_Security_Do_Not_Remove_See_SA_2013_003') === FALSE) {
  551. $url = 'https://www.drupal.org/SA-CORE-2013-003';
  552. $requirements[$htaccess_file] = [
  553. 'title' => new TranslatableMarkup($protected_dir->getTitle()),
  554. 'value' => t('Not fully protected'),
  555. 'severity' => REQUIREMENT_ERROR,
  556. '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' => $protected_dir->getPath()]),
  557. ];
  558. }
  559. }
  560. }
  561. // Test that path.temporary config is not set.
  562. if ($phase == 'runtime') {
  563. if (!Settings::get('file_temp_path')) {
  564. $filesystem_config = \Drupal::config('system.file');
  565. if ($temp_path = $filesystem_config->get('path.temporary')) {
  566. $requirements['temp_directory'] = [
  567. 'title' => t('Temporary Directory'),
  568. 'severity' => REQUIREMENT_WARNING,
  569. 'value' => 'Deprecated configuration',
  570. 'description' => [
  571. [
  572. '#markup' => t('You are using deprecated configuration for the temporary files path.'),
  573. '#suffix' => ' ',
  574. ],
  575. ],
  576. ];
  577. if ($temp_path === FileSystemComponent::getOsTemporaryDirectory()) {
  578. $requirements['temp_directory']['description'][] = [
  579. '#markup' => t('Your temporary directory configuration matches the OS default and can be safely removed.'),
  580. '#suffix' => ' ',
  581. ];
  582. }
  583. else {
  584. $requirements['temp_directory']['description'][] = [
  585. '#markup' => t('Remove the configuration and add the following to <code>settings.php</code>. <code>$settings["file_temp_path"] = "%temp_path"</code>', ['%temp_path' => $temp_path]),
  586. '#suffix' => ' ',
  587. ];
  588. }
  589. }
  590. }
  591. }
  592. // Report cron status.
  593. if ($phase == 'runtime') {
  594. $cron_config = \Drupal::config('system.cron');
  595. // Cron warning threshold defaults to two days.
  596. $threshold_warning = $cron_config->get('threshold.requirements_warning');
  597. // Cron error threshold defaults to two weeks.
  598. $threshold_error = $cron_config->get('threshold.requirements_error');
  599. // Determine when cron last ran.
  600. $cron_last = \Drupal::state()->get('system.cron_last');
  601. if (!is_numeric($cron_last)) {
  602. $cron_last = \Drupal::state()->get('install_time', 0);
  603. }
  604. // Determine severity based on time since cron last ran.
  605. $severity = REQUIREMENT_INFO;
  606. if (REQUEST_TIME - $cron_last > $threshold_error) {
  607. $severity = REQUIREMENT_ERROR;
  608. }
  609. elseif (REQUEST_TIME - $cron_last > $threshold_warning) {
  610. $severity = REQUIREMENT_WARNING;
  611. }
  612. // Set summary and description based on values determined above.
  613. $summary = t('Last run @time ago', ['@time' => \Drupal::service('date.formatter')->formatTimeDiffSince($cron_last)]);
  614. $requirements['cron'] = [
  615. 'title' => t('Cron maintenance tasks'),
  616. 'severity' => $severity,
  617. 'value' => $summary,
  618. ];
  619. if ($severity != REQUIREMENT_INFO) {
  620. $requirements['cron']['description'][] = [
  621. [
  622. '#markup' => t('Cron has not run recently.'),
  623. '#suffix' => ' ',
  624. ],
  625. [
  626. '#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']),
  627. '#suffix' => ' ',
  628. ],
  629. ];
  630. }
  631. $requirements['cron']['description'][] = [
  632. [
  633. '#type' => 'link',
  634. '#prefix' => '(',
  635. '#title' => t('more information'),
  636. '#suffix' => ')',
  637. '#url' => Url::fromRoute('system.cron_settings'),
  638. ],
  639. [
  640. '#prefix' => '<span class="cron-description__run-cron">',
  641. '#suffix' => '</span>',
  642. '#type' => 'link',
  643. '#title' => t('Run cron'),
  644. '#url' => Url::fromRoute('system.run_cron'),
  645. ],
  646. ];
  647. }
  648. if ($phase != 'install') {
  649. $filesystem_config = \Drupal::config('system.file');
  650. $directories = [
  651. PublicStream::basePath(),
  652. // By default no private files directory is configured. For private files
  653. // to be secure the admin needs to provide a path outside the webroot.
  654. PrivateStream::basePath(),
  655. \Drupal::service('file_system')->getTempDirectory(),
  656. ];
  657. }
  658. // During an install we need to make assumptions about the file system
  659. // unless overrides are provided in settings.php.
  660. if ($phase == 'install') {
  661. $directories = [];
  662. if ($file_public_path = Settings::get('file_public_path')) {
  663. $directories[] = $file_public_path;
  664. }
  665. else {
  666. // If we are installing Drupal, the settings.php file might not exist yet
  667. // in the intended site directory, so don't require it.
  668. $request = Request::createFromGlobals();
  669. $site_path = DrupalKernel::findSitePath($request);
  670. $directories[] = $site_path . '/files';
  671. }
  672. if ($file_private_path = Settings::get('file_private_path')) {
  673. $directories[] = $file_private_path;
  674. }
  675. if (Settings::get('file_temp_path')) {
  676. $directories[] = Settings::get('file_temp_path');
  677. }
  678. else {
  679. // If the temporary directory is not overridden use an appropriate
  680. // temporary path for the system.
  681. $directories[] = FileSystemComponent::getOsTemporaryDirectory();
  682. }
  683. }
  684. // Check the config directory if it is defined in settings.php. If it isn't
  685. // defined, the installer will create a valid config directory later, but
  686. // during runtime we must always display an error.
  687. $config_sync_directory = Settings::get('config_sync_directory');
  688. if (!empty($config_sync_directory)) {
  689. // If we're installing Drupal try and create the config sync directory.
  690. if (!is_dir($config_sync_directory) && $phase == 'install') {
  691. \Drupal::service('file_system')->prepareDirectory($config_sync_directory, FileSystemInterface::CREATE_DIRECTORY | FileSystemInterface::MODIFY_PERMISSIONS);
  692. }
  693. if (!is_dir($config_sync_directory)) {
  694. if ($phase == 'install') {
  695. $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' => $config_sync_directory, ':handbook_url' => 'https://www.drupal.org/server-permissions']);
  696. }
  697. else {
  698. $description = t('The directory %directory does not exist.', ['%directory' => $config_sync_directory]);
  699. }
  700. $requirements['config sync directory'] = [
  701. 'title' => t('Configuration sync directory'),
  702. 'description' => $description,
  703. 'severity' => REQUIREMENT_ERROR,
  704. ];
  705. }
  706. }
  707. if ($phase != 'install' && empty($config_sync_directory)) {
  708. $requirements['config sync directory'] = [
  709. 'title' => t('Configuration sync directory'),
  710. 'value' => t('Not present'),
  711. 'description' => t("Your %file file must define the %setting setting as a string containing the directory in which configuration files can be found.", ['%file' => $site_path . '/settings.php', '%setting' => "\$settings['config_sync_directory']"]),
  712. 'severity' => REQUIREMENT_ERROR,
  713. ];
  714. }
  715. // Handle other configuration directories. This will be removed in Drupal 9.
  716. // See https://www.drupal.org/node/3018145.
  717. $bc_config_directories = isset($GLOBALS['config_directories']) ? $GLOBALS['config_directories'] : [];
  718. unset($bc_config_directories['sync']);
  719. foreach (array_keys(array_filter($bc_config_directories)) as $type) {
  720. @trigger_error("Automatic creation of '$type' configuration directory will be removed from drupal:9.0.0. See https://www.drupal.org/node/3018145.", E_USER_DEPRECATED);
  721. $directory = config_get_config_directory($type);
  722. // If we're installing Drupal try and create the config sync directory.
  723. if (!is_dir($directory) && $phase == 'install') {
  724. \Drupal::service('file_system')->prepareDirectory($directory, FileSystemInterface::CREATE_DIRECTORY | FileSystemInterface::MODIFY_PERMISSIONS);
  725. }
  726. if (!is_dir($directory)) {
  727. if ($phase == 'install') {
  728. $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']);
  729. }
  730. else {
  731. $description = t('The directory %directory does not exist.', ['%directory' => $directory]);
  732. }
  733. $requirements['config directory ' . $type] = [
  734. 'title' => t('Configuration directory: %type', ['%type' => $type]),
  735. 'description' => $description,
  736. 'severity' => REQUIREMENT_ERROR,
  737. ];
  738. }
  739. }
  740. $requirements['file system'] = [
  741. 'title' => t('File system'),
  742. ];
  743. $error = '';
  744. // For installer, create the directories if possible.
  745. foreach ($directories as $directory) {
  746. if (!$directory) {
  747. continue;
  748. }
  749. if ($phase == 'install') {
  750. \Drupal::service('file_system')->prepareDirectory($directory, FileSystemInterface::CREATE_DIRECTORY | FileSystemInterface::MODIFY_PERMISSIONS);
  751. }
  752. $is_writable = is_writable($directory);
  753. $is_directory = is_dir($directory);
  754. if (!$is_writable || !$is_directory) {
  755. $description = '';
  756. $requirements['file system']['value'] = t('Not writable');
  757. if (!$is_directory) {
  758. $error = t('The directory %directory does not exist.', ['%directory' => $directory]);
  759. }
  760. else {
  761. $error = t('The directory %directory is not writable.', ['%directory' => $directory]);
  762. }
  763. // The files directory requirement check is done only during install and runtime.
  764. if ($phase == 'runtime') {
  765. $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' => Url::fromRoute('system.file_system_settings')->toString()]);
  766. }
  767. elseif ($phase == 'install') {
  768. // For the installer UI, we need different wording. 'value' will
  769. // be treated as version, so provide none there.
  770. $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']);
  771. $requirements['file system']['value'] = '';
  772. }
  773. if (!empty($description)) {
  774. $description = [
  775. '#type' => 'inline_template',
  776. '#template' => '{{ error }} {{ description }}',
  777. '#context' => [
  778. 'error' => $error,
  779. 'description' => $description,
  780. ],
  781. ];
  782. $requirements['file system']['description'] = $description;
  783. $requirements['file system']['severity'] = REQUIREMENT_ERROR;
  784. }
  785. }
  786. else {
  787. // This function can be called before the config_cache table has been
  788. // created.
  789. if ($phase == 'install' || \Drupal::config('system.file')->get('default_scheme') == 'public') {
  790. $requirements['file system']['value'] = t('Writable (<em>public</em> download method)');
  791. }
  792. else {
  793. $requirements['file system']['value'] = t('Writable (<em>private</em> download method)');
  794. }
  795. }
  796. }
  797. // See if updates are available in update.php.
  798. if ($phase == 'runtime') {
  799. $requirements['update'] = [
  800. 'title' => t('Database updates'),
  801. 'value' => t('Up to date'),
  802. ];
  803. // Check installed modules.
  804. $has_pending_updates = FALSE;
  805. foreach (\Drupal::moduleHandler()->getModuleList() as $module => $filename) {
  806. $updates = drupal_get_schema_versions($module);
  807. if ($updates !== FALSE) {
  808. $default = drupal_get_installed_schema_version($module);
  809. if (max($updates) > $default) {
  810. $has_pending_updates = TRUE;
  811. break;
  812. }
  813. }
  814. }
  815. if (!$has_pending_updates) {
  816. /** @var \Drupal\Core\Update\UpdateRegistry $post_update_registry */
  817. $post_update_registry = \Drupal::service('update.post_update_registry');
  818. $missing_post_update_functions = $post_update_registry->getPendingUpdateFunctions();
  819. if (!empty($missing_post_update_functions)) {
  820. $has_pending_updates = TRUE;
  821. }
  822. }
  823. if ($has_pending_updates) {
  824. $requirements['update']['severity'] = REQUIREMENT_ERROR;
  825. $requirements['update']['value'] = t('Out of date');
  826. $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' => Url::fromRoute('system.db_update')->toString()]);
  827. }
  828. $requirements['entity_update'] = [
  829. 'title' => t('Entity/field definitions'),
  830. 'value' => t('Up to date'),
  831. ];
  832. // Verify that no entity updates are pending.
  833. if ($change_list = \Drupal::entityDefinitionUpdateManager()->getChangeSummary()) {
  834. $build = [];
  835. foreach ($change_list as $entity_type_id => $changes) {
  836. $entity_type = \Drupal::entityTypeManager()->getDefinition($entity_type_id);
  837. $build[] = [
  838. '#theme' => 'item_list',
  839. '#title' => $entity_type->getLabel(),
  840. '#items' => $changes,
  841. ];
  842. }
  843. $entity_update_issues = \Drupal::service('renderer')->renderPlain($build);
  844. $requirements['entity_update']['severity'] = REQUIREMENT_ERROR;
  845. $requirements['entity_update']['value'] = t('Mismatched entity and/or field definitions');
  846. $requirements['entity_update']['description'] = t('The following changes were detected in the entity type and field definitions. @updates', ['@updates' => $entity_update_issues]);
  847. }
  848. }
  849. // Verify the update.php access setting
  850. if ($phase == 'runtime') {
  851. if (Settings::get('update_free_access')) {
  852. $requirements['update access'] = [
  853. 'value' => t('Not protected'),
  854. 'severity' => REQUIREMENT_ERROR,
  855. '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\']']),
  856. ];
  857. }
  858. else {
  859. $requirements['update access'] = [
  860. 'value' => t('Protected'),
  861. ];
  862. }
  863. $requirements['update access']['title'] = t('Access to update.php');
  864. }
  865. // Display an error if a newly introduced dependency in a module is not resolved.
  866. if ($phase === 'update' || $phase === 'runtime') {
  867. $create_extension_incompatibility_list = function ($extension_names, $description, $title) {
  868. // Use an inline twig template to:
  869. // - Concatenate two MarkupInterface objects and preserve safeness.
  870. // - Use the item_list theme for the extension list.
  871. $template = [
  872. '#type' => 'inline_template',
  873. '#template' => '{{ description }}{{ extensions }}',
  874. '#context' => [
  875. 'extensions' => [
  876. '#theme' => 'item_list',
  877. ],
  878. ],
  879. ];
  880. $template['#context']['extensions']['#items'] = $extension_names;
  881. $template['#context']['description'] = $description;
  882. return [
  883. 'title' => $title,
  884. 'value' => [
  885. 'list' => $template,
  886. 'handbook_link' => [
  887. '#markup' => t(
  888. 'Review the <a href=":url"> suggestions for resolving this incompatibility</a> to repair your installation, and then re-run update.php.',
  889. [':url' => 'https://www.drupal.org/docs/8/update/troubleshooting-database-updates']
  890. ),
  891. ],
  892. ],
  893. 'severity' => REQUIREMENT_ERROR,
  894. ];
  895. };
  896. $profile = \Drupal::installProfile();
  897. $files = \Drupal::service('extension.list.module')->getList();
  898. $files += \Drupal::service('extension.list.theme')->getList();
  899. $core_incompatible_extensions = [];
  900. $php_incompatible_extensions = [];
  901. foreach ($files as $extension_name => $file) {
  902. // Ignore uninstalled extensions and installation profiles.
  903. if (!$file->status || $extension_name == $profile) {
  904. continue;
  905. }
  906. $name = $file->info['name'];
  907. if (!empty($file->info['core_incompatible'])) {
  908. $core_incompatible_extensions[$file->info['type']][] = $name;
  909. }
  910. // Check the extension's PHP version.
  911. $php = $file->info['php'];
  912. if (version_compare($php, PHP_VERSION, '>')) {
  913. $php_incompatible_extensions[$file->info['type']][] = $name;
  914. }
  915. // Check the module's required modules.
  916. /** @var \Drupal\Core\Extension\Dependency $requirement */
  917. foreach ($file->requires as $requirement) {
  918. $required_module = $requirement->getName();
  919. // Check if the module exists.
  920. if (!isset($files[$required_module])) {
  921. $requirements["$extension_name-$required_module"] = [
  922. 'title' => t('Unresolved dependency'),
  923. 'description' => t('@name requires this module.', ['@name' => $name]),
  924. 'value' => t('@required_name (Missing)', ['@required_name' => $required_module]),
  925. 'severity' => REQUIREMENT_ERROR,
  926. ];
  927. continue;
  928. }
  929. // Check for an incompatible version.
  930. $required_file = $files[$required_module];
  931. $required_name = $required_file->info['name'];
  932. $version = str_replace(\Drupal::CORE_COMPATIBILITY . '-', '', $required_file->info['version']);
  933. if (!$requirement->isCompatible($version)) {
  934. $requirements["$extension_name-$required_module"] = [
  935. 'title' => t('Unresolved dependency'),
  936. 'description' => t('@name requires this module and version. Currently using @required_name version @version', ['@name' => $name, '@required_name' => $required_name, '@version' => $version]),
  937. 'value' => t('@required_name (Version @compatibility required)', ['@required_name' => $required_name, '@compatibility' => $requirement->getConstraintString()]),
  938. 'severity' => REQUIREMENT_ERROR,
  939. ];
  940. continue;
  941. }
  942. }
  943. }
  944. if (!empty($core_incompatible_extensions['module'])) {
  945. $requirements['module_core_incompatible'] = $create_extension_incompatibility_list(
  946. $core_incompatible_extensions['module'],
  947. new PluralTranslatableMarkup(
  948. count($core_incompatible_extensions['module']),
  949. 'The following module is installed, but it is incompatible with Drupal @version:',
  950. 'The following modules are installed, but they are incompatible with Drupal @version:',
  951. ['@version' => \Drupal::VERSION]
  952. ),
  953. new PluralTranslatableMarkup(
  954. count($core_incompatible_extensions['module']),
  955. 'Incompatible module',
  956. 'Incompatible modules'
  957. )
  958. );
  959. }
  960. if (!empty($core_incompatible_extensions['theme'])) {
  961. $requirements['theme_core_incompatible'] = $create_extension_incompatibility_list(
  962. $core_incompatible_extensions['theme'],
  963. new PluralTranslatableMarkup(
  964. count($core_incompatible_extensions['theme']),
  965. 'The following theme is installed, but it is incompatible with Drupal @version:',
  966. 'The following themes are installed, but they are incompatible with Drupal @version:',
  967. ['@version' => \Drupal::VERSION]
  968. ),
  969. new PluralTranslatableMarkup(
  970. count($core_incompatible_extensions['theme']),
  971. 'Incompatible theme',
  972. 'Incompatible themes'
  973. )
  974. );
  975. }
  976. if (!empty($php_incompatible_extensions['module'])) {
  977. $requirements['module_php_incompatible'] = $create_extension_incompatibility_list(
  978. $php_incompatible_extensions['module'],
  979. new PluralTranslatableMarkup(
  980. count($php_incompatible_extensions['module']),
  981. 'The following module is installed, but it is incompatible with PHP @version:',
  982. 'The following modules are installed, but they are incompatible with PHP @version:',
  983. ['@version' => phpversion()]
  984. ),
  985. new PluralTranslatableMarkup(
  986. count($php_incompatible_extensions['module']),
  987. 'Incompatible module',
  988. 'Incompatible modules'
  989. )
  990. );
  991. }
  992. if (!empty($php_incompatible_extensions['theme'])) {
  993. $requirements['theme_php_incompatible'] = $create_extension_incompatibility_list(
  994. $php_incompatible_extensions['theme'],
  995. new PluralTranslatableMarkup(
  996. count($php_incompatible_extensions['theme']),
  997. 'The following theme is installed, but it is incompatible with PHP @version:',
  998. 'The following themes are installed, but they are incompatible with PHP @version:',
  999. ['@version' => phpversion()]
  1000. ),
  1001. new PluralTranslatableMarkup(
  1002. count($php_incompatible_extensions['theme']),
  1003. 'Incompatible theme',
  1004. 'Incompatible themes'
  1005. )
  1006. );
  1007. }
  1008. // Look for invalid modules.
  1009. $extension_config = \Drupal::configFactory()->get('core.extension');
  1010. /** @var \Drupal\Core\Extension\ExtensionList $extension_list */
  1011. $extension_list = \Drupal::service('extension.list.module');
  1012. $is_missing_extension = function ($extension_name) use (&$extension_list) {
  1013. return !$extension_list->exists($extension_name);
  1014. };
  1015. $invalid_modules = array_filter(array_keys($extension_config->get('module')), $is_missing_extension);
  1016. if (!empty($invalid_modules)) {
  1017. $requirements['invalid_module'] = $create_extension_incompatibility_list(
  1018. $invalid_modules,
  1019. new PluralTranslatableMarkup(
  1020. count($invalid_modules),
  1021. 'The following module is marked as installed in the core.extension configuration, but it is missing:',
  1022. 'The following modules are marked as installed in the core.extension configuration, but they are missing:'
  1023. ),
  1024. new PluralTranslatableMarkup(
  1025. count($invalid_modules),
  1026. 'Missing or invalid module',
  1027. 'Missing or invalid modules'
  1028. )
  1029. );
  1030. }
  1031. // Look for invalid themes.
  1032. $extension_list = \Drupal::service('extension.list.theme');
  1033. $invalid_themes = array_filter(array_keys($extension_config->get('theme')), $is_missing_extension);
  1034. if (!empty($invalid_themes)) {
  1035. $requirements['invalid_theme'] = $create_extension_incompatibility_list(
  1036. $invalid_themes,
  1037. new PluralTranslatableMarkup(
  1038. count($invalid_themes),
  1039. 'The following theme is marked as installed in the core.extension configuration, but it is missing:',
  1040. 'The following themes are marked as installed in the core.extension configuration, but they are missing:'
  1041. ),
  1042. new PluralTranslatableMarkup(
  1043. count($invalid_themes),
  1044. 'Missing or invalid theme',
  1045. 'Missing or invalid themes'
  1046. )
  1047. );
  1048. }
  1049. }
  1050. // Returns Unicode library status and errors.
  1051. $libraries = [
  1052. Unicode::STATUS_SINGLEBYTE => t('Standard PHP'),
  1053. Unicode::STATUS_MULTIBYTE => t('PHP Mbstring Extension'),
  1054. Unicode::STATUS_ERROR => t('Error'),
  1055. ];
  1056. $severities = [
  1057. Unicode::STATUS_SINGLEBYTE => REQUIREMENT_WARNING,
  1058. Unicode::STATUS_MULTIBYTE => NULL,
  1059. Unicode::STATUS_ERROR => REQUIREMENT_ERROR,
  1060. ];
  1061. $failed_check = Unicode::check();
  1062. $library = Unicode::getStatus();
  1063. $requirements['unicode'] = [
  1064. 'title' => t('Unicode library'),
  1065. 'value' => $libraries[$library],
  1066. 'severity' => $severities[$library],
  1067. ];
  1068. switch ($failed_check) {
  1069. case 'mb_strlen':
  1070. $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.');
  1071. break;
  1072. case 'mbstring.func_overload':
  1073. $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.');
  1074. break;
  1075. case 'mbstring.encoding_translation':
  1076. $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.');
  1077. break;
  1078. case 'mbstring.http_input':
  1079. $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.');
  1080. break;
  1081. case 'mbstring.http_output':
  1082. $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.');
  1083. break;
  1084. }
  1085. if ($phase == 'runtime') {
  1086. // Check for update status module.
  1087. if (!\Drupal::moduleHandler()->moduleExists('update')) {
  1088. $requirements['update status'] = [
  1089. 'value' => t('Not enabled'),
  1090. 'severity' => REQUIREMENT_WARNING,
  1091. '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>.', [
  1092. ':update' => 'https://www.drupal.org/documentation/modules/update',
  1093. ':module' => Url::fromRoute('system.modules_list')->toString(),
  1094. ]),
  1095. ];
  1096. }
  1097. else {
  1098. $requirements['update status'] = [
  1099. 'value' => t('Enabled'),
  1100. ];
  1101. }
  1102. $requirements['update status']['title'] = t('Update notifications');
  1103. if (Settings::get('rebuild_access')) {
  1104. $requirements['rebuild access'] = [
  1105. 'title' => t('Rebuild access'),
  1106. 'value' => t('Enabled'),
  1107. 'severity' => REQUIREMENT_ERROR,
  1108. '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.'),
  1109. ];
  1110. }
  1111. }
  1112. // See if trusted hostnames have been configured, and warn the user if they
  1113. // are not set.
  1114. if ($phase == 'runtime') {
  1115. $trusted_host_patterns = Settings::get('trusted_host_patterns');
  1116. if (empty($trusted_host_patterns)) {
  1117. $requirements['trusted_host_patterns'] = [
  1118. 'title' => t('Trusted Host Settings'),
  1119. 'value' => t('Not enabled'),
  1120. '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/docs/8/install/trusted-host-settings']),
  1121. 'severity' => REQUIREMENT_ERROR,
  1122. ];
  1123. }
  1124. else {
  1125. $requirements['trusted_host_patterns'] = [
  1126. 'title' => t('Trusted Host Settings'),
  1127. 'value' => t('Enabled'),
  1128. 'description' => t('The trusted_host_patterns setting is set to allow %trusted_host_patterns', ['%trusted_host_patterns' => implode(', ', $trusted_host_patterns)]),
  1129. ];
  1130. }
  1131. }
  1132. // Check xdebug.max_nesting_level, as some pages will not work if it is too
  1133. // low.
  1134. if (extension_loaded('xdebug')) {
  1135. // Setting this value to 256 was considered adequate on Xdebug 2.3
  1136. // (see http://bugs.xdebug.org/bug_view_page.php?bug_id=00001100)
  1137. $minimum_nesting_level = 256;
  1138. $current_nesting_level = ini_get('xdebug.max_nesting_level');
  1139. if ($current_nesting_level < $minimum_nesting_level) {
  1140. $requirements['xdebug_max_nesting_level'] = [
  1141. 'title' => t('Xdebug settings'),
  1142. 'value' => t('xdebug.max_nesting_level is set to %value.', ['%value' => $current_nesting_level]),
  1143. '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]),
  1144. 'severity' => REQUIREMENT_ERROR,
  1145. ];
  1146. }
  1147. }
  1148. // Warning for httpoxy on IIS with affected PHP versions
  1149. // @see https://www.drupal.org/node/2783079
  1150. if (strpos($software, 'Microsoft-IIS') !== FALSE && version_compare(PHP_VERSION, '7.0.9', '<')) {
  1151. $dom = new \DOMDocument('1.0', 'UTF-8');
  1152. $webconfig = file_get_contents('web.config');
  1153. // If you are here the web.config file must - of course - be well formed.
  1154. // But the PHP DOM component will throw warnings on some XML compliant
  1155. // stuff, so silently parse the configuration file.
  1156. @$dom->loadHTML($webconfig);
  1157. $httpoxy_rewrite = FALSE;
  1158. foreach ($dom->getElementsByTagName('rule') as $rule) {
  1159. foreach ($rule->attributes as $attr) {
  1160. if (@$attr->name == 'name' && @$attr->nodeValue == 'Erase HTTP_PROXY') {
  1161. $httpoxy_rewrite = TRUE;
  1162. break 2;
  1163. }
  1164. }
  1165. }
  1166. if (!$httpoxy_rewrite) {
  1167. $requirements['iis_httpoxy_protection'] = [
  1168. 'title' => t('IIS httpoxy protection'),
  1169. 'value' => t('Your PHP runtime version is affected by the httpoxy vulnerability.'),
  1170. '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']),
  1171. 'severity' => REQUIREMENT_ERROR,
  1172. ];
  1173. }
  1174. }
  1175. // Installations on Windows can run into limitations with MAX_PATH if the
  1176. // Drupal root directory is too deep in the filesystem. Generally this shows
  1177. // up in cached Twig templates and other public files with long directory or
  1178. // file names. There is no definite root directory depth below which Drupal is
  1179. // guaranteed to function correctly on Windows. Since problems are likely
  1180. // with more than 100 characters in the Drupal root path, show an error.
  1181. if (substr(PHP_OS, 0, 3) == 'WIN') {
  1182. $depth = strlen(realpath(DRUPAL_ROOT . '/' . PublicStream::basePath()));
  1183. if ($depth > 120) {
  1184. $requirements['max_path_on_windows'] = [
  1185. 'title' => t('Windows installation depth'),
  1186. 'description' => t('The public files directory path is %depth characters. Paths longer than 120 characters will cause problems on Windows.', ['%depth' => $depth]),
  1187. 'severity' => REQUIREMENT_ERROR,
  1188. ];
  1189. }
  1190. }
  1191. // Check to see if dates will be limited to 1901-2038.
  1192. if (PHP_INT_SIZE <= 4) {
  1193. $requirements['limited_date_range'] = [
  1194. 'title' => t('Limited date range'),
  1195. 'value' => t('Your PHP installation has a limited date range.'),
  1196. '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']),
  1197. 'severity' => REQUIREMENT_WARNING,
  1198. ];
  1199. }
  1200. // During installs from configuration don't support install profiles that
  1201. // implement hook_install.
  1202. if ($phase == 'install' && !empty($install_state['config_install_path'])) {
  1203. $install_hook = $install_state['parameters']['profile'] . '_install';
  1204. if (function_exists($install_hook)) {
  1205. $requirements['config_install'] = [
  1206. 'title' => t('Configuration install'),
  1207. 'value' => $install_state['parameters']['profile'],
  1208. 'description' => t('The selected profile has a hook_install() implementation and therefore can not be installed from configuration.'),
  1209. 'severity' => REQUIREMENT_ERROR,
  1210. ];
  1211. }
  1212. }
  1213. if ($phase === 'runtime') {
  1214. $settings = Settings::getAll();
  1215. if (array_key_exists('install_profile', $settings)) {
  1216. // The following message is only informational because not all site owners
  1217. // have access to edit their settings.php as it may be controlled by their
  1218. // hosting provider.
  1219. $requirements['install_profile_in_settings'] = [
  1220. 'title' => t('Install profile in settings'),
  1221. 'value' => t("Drupal 8 no longer uses the \$settings['install_profile'] value in settings.php and it can be removed."),
  1222. 'severity' => REQUIREMENT_INFO,
  1223. ];
  1224. }
  1225. }
  1226. // Prevent installation or update if the Pathauto module is installed and its
  1227. // version is less than 1.6.
  1228. if ($phase === 'install' || $phase === 'update') {
  1229. if (\Drupal::moduleHandler()->moduleExists('pathauto')) {
  1230. $info = \Drupal::service('extension.list.module')->getExtensionInfo('pathauto');
  1231. if ($info['version'] && version_compare($info['version'], '8.x-1.5') <= 0) {
  1232. $requirements['pathauto_module_incompatibility'] = [
  1233. 'title' => t('Pathauto'),
  1234. 'description' => t('The Pathauto module is not compatible with the current version of Drupal core. Update the <a href=":url">Pathauto</a> module to 8.x-1.6 or later.', [
  1235. ':url' => 'https://drupal.org/project/pathauto',
  1236. ]),
  1237. 'severity' => REQUIREMENT_ERROR,
  1238. ];
  1239. }
  1240. }
  1241. }
  1242. // Ensure that no module has a current schema version that is lower than the
  1243. // one that was last removed.
  1244. if ($phase == 'update') {
  1245. $module_handler = \Drupal::moduleHandler();
  1246. $module_list = [];
  1247. foreach ($module_handler->getImplementations('update_last_removed') as $module) {
  1248. $last_removed = $module_handler->invoke($module, 'update_last_removed');
  1249. if ($last_removed && $last_removed > drupal_get_installed_schema_version($module)) {
  1250. /** @var \Drupal\Core\Extension\Extension $module_info */
  1251. $module_info = \Drupal::service('extension.list.module')->get($module);
  1252. $module_list[$module_info->info['package']][$module] = [
  1253. 'info' => $module_info,
  1254. 'last_removed' => $last_removed,
  1255. 'installed_version' => drupal_get_installed_schema_version($module),
  1256. ];
  1257. }
  1258. }
  1259. foreach ($module_list as $package => $package_modules) {
  1260. foreach ($package_modules as $module => $data) {
  1261. $requirements[$module . '_update_last_removed'] = [
  1262. 'title' => t('Unsupported schema version: @module', ['@module' => $data['info']->info['name']]),
  1263. 'description' => t('The installed version of the %module module is too old to update. Update to an intermediate version first (last removed version: @last_removed_version, installed version: @installed_version).', [
  1264. '%module' => $data['info']->info['name'],
  1265. '@last_removed_version' => $data['last_removed'],
  1266. '@installed_version' => $data['installed_version'],
  1267. ]),
  1268. 'severity' => REQUIREMENT_ERROR,
  1269. ];
  1270. }
  1271. }
  1272. // Also check post-updates. Only do this if we're not already showing an
  1273. // error for hook_update_N().
  1274. if (empty($module_list)) {
  1275. $existing_updates = \Drupal::service('keyvalue')->get('post_update')->get('existing_updates', []);
  1276. $post_update_registry = \Drupal::service('update.post_update_registry');
  1277. $modules = \Drupal::moduleHandler()->getModuleList();
  1278. $module_extension_list = \Drupal::service('extension.list.module');
  1279. foreach ($modules as $module => $extension) {
  1280. $module_info = $module_extension_list->get($module);
  1281. $removed_post_updates = $post_update_registry->getRemovedPostUpdates($module);
  1282. if ($missing_updates = array_diff(array_keys($removed_post_updates), $existing_updates)) {
  1283. $versions = array_unique(array_intersect_key($removed_post_updates, array_flip($missing_updates)));
  1284. $description = new PluralTranslatableMarkup(count($versions),
  1285. 'The installed version of the %module module is too old to update. Update to a version prior to @versions first (missing updates: @missing_updates).',
  1286. 'The installed version of the %module module is too old to update. Update first to a version prior to all of the following: @versions (missing updates: @missing_updates).',
  1287. [
  1288. '%module' => $module_info->info['name'],
  1289. '@missing_updates' => implode(', ', $missing_updates),
  1290. '@versions' => implode(', ', $versions),
  1291. ]
  1292. );
  1293. $requirements[$module . '_post_update_removed'] = [
  1294. 'title' => t('Missing updates for: @module', ['@module' => $module_info->info['name']]),
  1295. 'description' => $description,
  1296. 'severity' => REQUIREMENT_ERROR,
  1297. ];
  1298. }
  1299. }
  1300. }
  1301. }
  1302. return $requirements;
  1303. }
  1304. /**
  1305. * Implements hook_install().
  1306. */
  1307. function system_install() {
  1308. // Populate the cron key state variable.
  1309. $cron_key = Crypt::randomBytesBase64(55);
  1310. \Drupal::state()->set('system.cron_key', $cron_key);
  1311. // Populate the site UUID and default name (if not set).
  1312. $site = \Drupal::configFactory()->getEditable('system.site');
  1313. $site->set('uuid', \Drupal::service('uuid')->generate());
  1314. if (!$site->get('name')) {
  1315. $site->set('name', 'Drupal');
  1316. }
  1317. $site->save(TRUE);
  1318. }
  1319. /**
  1320. * Implements hook_schema().
  1321. */
  1322. function system_schema() {
  1323. $schema['key_value'] = [
  1324. 'description' => 'Generic key-value storage table. See the state system for an example.',
  1325. 'fields' => [
  1326. 'collection' => [
  1327. 'description' => 'A named collection of key and value pairs.',
  1328. 'type' => 'varchar_ascii',
  1329. 'length' => 128,
  1330. 'not null' => TRUE,
  1331. 'default' => '',
  1332. ],
  1333. 'name' => [
  1334. 'description' => 'The key of the key-value pair. As KEY is a SQL reserved keyword, name was chosen instead.',
  1335. 'type' => 'varchar_ascii',
  1336. 'length' => 128,
  1337. 'not null' => TRUE,
  1338. 'default' => '',
  1339. ],
  1340. 'value' => [
  1341. 'description' => 'The value.',
  1342. 'type' => 'blob',
  1343. 'not null' => TRUE,
  1344. 'size' => 'big',
  1345. ],
  1346. ],
  1347. 'primary key' => ['collection', 'name'],
  1348. ];
  1349. $schema['key_value_expire'] = [
  1350. 'description' => 'Generic key/value storage table with an expiration.',
  1351. 'fields' => [
  1352. 'collection' => [
  1353. 'description' => 'A named collection of key and value pairs.',
  1354. 'type' => 'varchar_ascii',
  1355. 'length' => 128,
  1356. 'not null' => TRUE,
  1357. 'default' => '',
  1358. ],
  1359. 'name' => [
  1360. // KEY is an SQL reserved word, so use 'name' as the key's field name.
  1361. 'description' => 'The key of the key/value pair.',
  1362. 'type' => 'varchar_ascii',
  1363. 'length' => 128,
  1364. 'not null' => TRUE,
  1365. 'default' => '',
  1366. ],
  1367. 'value' => [
  1368. 'description' => 'The value of the key/value pair.',
  1369. 'type' => 'blob',
  1370. 'not null' => TRUE,
  1371. 'size' => 'big',
  1372. ],
  1373. 'expire' => [
  1374. 'description' => 'The time since Unix epoch in seconds when this item expires. Defaults to the maximum possible time.',
  1375. 'type' => 'int',
  1376. 'not null' => TRUE,
  1377. 'default' => 2147483647,
  1378. ],
  1379. ],
  1380. 'primary key' => ['collection', 'name'],
  1381. 'indexes' => [
  1382. 'all' => ['name', 'collection', 'expire'],
  1383. 'expire' => ['expire'],
  1384. ],
  1385. ];
  1386. $schema['sequences'] = [
  1387. 'description' => 'Stores IDs.',
  1388. 'fields' => [
  1389. 'value' => [
  1390. 'description' => 'The value of the sequence.',
  1391. 'type' => 'serial',
  1392. 'unsigned' => TRUE,
  1393. 'not null' => TRUE,
  1394. ],
  1395. ],
  1396. 'primary key' => ['value'],
  1397. ];
  1398. $schema['sessions'] = [
  1399. 'description' => "Drupal's session handlers read and write into the sessions table. Each record represents a user session, either anonymous or authenticated.",
  1400. 'fields' => [
  1401. 'uid' => [
  1402. 'description' => 'The {users}.uid corresponding to a session, or 0 for anonymous user.',
  1403. 'type' => 'int',
  1404. 'unsigned' => TRUE,
  1405. 'not null' => TRUE,
  1406. ],
  1407. 'sid' => [
  1408. 'description' => "A session ID (hashed). The value is generated by Drupal's session handlers.",
  1409. 'type' => 'varchar_ascii',
  1410. 'length' => 128,
  1411. 'not null' => TRUE,
  1412. ],
  1413. 'hostname' => [
  1414. 'description' => 'The IP address that last used this session ID (sid).',
  1415. 'type' => 'varchar_ascii',
  1416. 'length' => 128,
  1417. 'not null' => TRUE,
  1418. 'default' => '',
  1419. ],
  1420. 'timestamp' => [
  1421. 'description' => 'The Unix timestamp when this session last requested a page. Old records are purged by PHP automatically.',
  1422. 'type' => 'int',
  1423. 'not null' => TRUE,
  1424. 'default' => 0,
  1425. ],
  1426. 'session' => [
  1427. '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.',
  1428. 'type' => 'blob',
  1429. 'not null' => FALSE,
  1430. 'size' => 'big',
  1431. ],
  1432. ],
  1433. 'primary key' => [
  1434. 'sid',
  1435. ],
  1436. 'indexes' => [
  1437. 'timestamp' => ['timestamp'],
  1438. 'uid' => ['uid'],
  1439. ],
  1440. 'foreign keys' => [
  1441. 'session_user' => [
  1442. 'table' => 'users',
  1443. 'columns' => ['uid' => 'uid'],
  1444. ],
  1445. ],
  1446. ];
  1447. return $schema;
  1448. }
  1449. /**
  1450. * Change two fields on the default menu link storage to be serialized data.
  1451. */
  1452. function system_update_8001(&$sandbox = NULL) {
  1453. $database = \Drupal::database();
  1454. $schema = $database->schema();
  1455. if ($schema->tableExists('menu_tree')) {
  1456. if (!isset($sandbox['current'])) {
  1457. // Converting directly to blob can cause problems with reading out and
  1458. // serializing the string data later on postgres, so rename the existing
  1459. // columns and create replacement ones to hold the serialized objects.
  1460. $old_fields = [
  1461. 'title' => [
  1462. 'description' => 'The text displayed for the link.',
  1463. 'type' => 'varchar',
  1464. 'length' => 255,
  1465. 'not null' => TRUE,
  1466. 'default' => '',
  1467. ],
  1468. 'description' => [
  1469. 'description' => 'The description of this link - used for admin pages and title attribute.',
  1470. 'type' => 'text',
  1471. 'not null' => FALSE,
  1472. ],
  1473. ];
  1474. foreach ($old_fields as $name => $spec) {
  1475. $schema->changeField('menu_tree', $name, 'system_update_8001_' . $name, $spec);
  1476. }
  1477. $spec = [
  1478. 'description' => 'The title for the link. May be a serialized TranslatableMarkup.',
  1479. 'type' => 'blob',
  1480. 'size' => 'big',
  1481. 'not null' => FALSE,
  1482. 'serialize' => TRUE,
  1483. ];
  1484. $schema->addField('menu_tree', 'title', $spec);
  1485. $spec = [
  1486. 'description' => 'The description of this link - used for admin pages and title attribute.',
  1487. 'type' => 'blob',
  1488. 'size' => 'big',
  1489. 'not null' => FALSE,
  1490. 'serialize' => TRUE,
  1491. ];
  1492. $schema->addField('menu_tree', 'description', $spec);
  1493. $sandbox['current'] = 0;
  1494. $sandbox['max'] = $database->query('SELECT COUNT(mlid) FROM {menu_tree}')
  1495. ->fetchField();
  1496. }
  1497. $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)
  1498. ->fetchAllAssoc('mlid');
  1499. foreach ($menu_links as $menu_link) {
  1500. $menu_link = (array) $menu_link;
  1501. // Convert title and description to serialized strings.
  1502. $menu_link['title'] = serialize($menu_link['title']);
  1503. $menu_link['description'] = serialize($menu_link['description']);
  1504. $database->update('menu_tree')
  1505. ->fields($menu_link)
  1506. ->condition('mlid', $menu_link['mlid'])
  1507. ->execute();
  1508. $sandbox['current']++;
  1509. }
  1510. $sandbox['#finished'] = empty($sandbox['max']) ? 1 : ($sandbox['current'] / $sandbox['max']);
  1511. if ($sandbox['#finished'] >= 1) {
  1512. // Drop unnecessary fields from {menu_tree}.
  1513. $schema->dropField('menu_tree', 'system_update_8001_title');
  1514. $schema->dropField('menu_tree', 'title_arguments');
  1515. $schema->dropField('menu_tree', 'title_context');
  1516. $schema->dropField('menu_tree', 'system_update_8001_description');
  1517. }
  1518. return t('Menu links converted');
  1519. }
  1520. else {
  1521. return t('Menu link conversion skipped, because the {menu_tree} table did not exist yet.');
  1522. }
  1523. }
  1524. /**
  1525. * Removes the system.filter configuration.
  1526. */
  1527. function system_update_8002() {
  1528. \Drupal::configFactory()->getEditable('system.filter')->delete();
  1529. return t('The system.filter configuration has been moved to a container parameter, see default.services.yml for more information.');
  1530. }
  1531. /**
  1532. * Change the index on the {router} table.
  1533. */
  1534. function system_update_8003() {
  1535. $database = \Drupal::database();
  1536. $database->schema()->dropIndex('router', 'pattern_outline_fit');
  1537. $database->schema()->addIndex(
  1538. 'router',
  1539. 'pattern_outline_parts',
  1540. ['pattern_outline', 'number_parts'],
  1541. [
  1542. 'fields' => [
  1543. 'pattern_outline' => [
  1544. 'description' => 'The pattern',
  1545. 'type' => 'varchar',
  1546. 'length' => 255,
  1547. 'not null' => TRUE,
  1548. 'default' => '',
  1549. ],
  1550. 'number_parts' => [
  1551. 'description' => 'Number of parts in this router path.',
  1552. 'type' => 'int',
  1553. 'not null' => TRUE,
  1554. 'default' => 0,
  1555. 'size' => 'small',
  1556. ],
  1557. ],
  1558. ]
  1559. );
  1560. }
  1561. /**
  1562. * Add a (id, default_langcode, langcode) composite index to entities.
  1563. */
  1564. function system_update_8004() {
  1565. // \Drupal\Core\Entity\Sql\SqlContentEntityStorageSchema was changed in
  1566. // https://www.drupal.org/node/2261669 to include a (id, default_langcode,
  1567. // langcode) compound index, but this update function wasn't added until
  1568. // https://www.drupal.org/node/2542748. Regenerate the related schemas to
  1569. // ensure they match the currently expected status.
  1570. $manager = \Drupal::entityDefinitionUpdateManager();
  1571. foreach (array_keys(\Drupal::entityTypeManager()
  1572. ->getDefinitions()) as $entity_type_id) {
  1573. // Only update the entity type if it already exists. This condition is
  1574. // needed in case new entity types are introduced after this update.
  1575. if ($entity_type = $manager->getEntityType($entity_type_id)) {
  1576. $manager->updateEntityType($entity_type);
  1577. }
  1578. }
  1579. }
  1580. /**
  1581. * Place local actions and tasks blocks in every theme.
  1582. */
  1583. function system_update_8005() {
  1584. // When block module is not installed, there is nothing that could be done
  1585. // except showing a warning.
  1586. if (!\Drupal::moduleHandler()->moduleExists('block')) {
  1587. return t('Block module is not enabled so local actions and tasks which have been converted to blocks, are not visible anymore.');
  1588. }
  1589. $config_factory = \Drupal::configFactory();
  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. $local_actions_default_settings = [
  1596. 'plugin' => 'local_actions_block',
  1597. 'region' => 'content',
  1598. 'settings.label' => 'Primary admin actions',
  1599. 'settings.label_display' => 0,
  1600. 'settings.cache.max_age' => 0,
  1601. 'visibility' => [],
  1602. 'weight' => 0,
  1603. 'langcode' => $langcode,
  1604. ];
  1605. $tabs_default_settings = [
  1606. 'plugin' => 'local_tasks_block',
  1607. 'region' => 'content',
  1608. 'settings.label' => 'Tabs',
  1609. 'settings.label_display' => 0,
  1610. 'settings.cache.max_age' => 0,
  1611. 'visibility' => [],
  1612. 'weight' => 0,
  1613. 'langcode' => $langcode,
  1614. ];
  1615. foreach ($theme_handler->listInfo() as $theme) {
  1616. $theme_name = $theme->getName();
  1617. switch ($theme_name) {
  1618. case 'bartik':
  1619. $name = 'block.block.bartik_local_actions';
  1620. $values = [
  1621. 'id' => 'bartik_local_actions',
  1622. 'weight' => -1,
  1623. ] + $local_actions_default_settings;
  1624. _system_update_create_block($name, $theme_name, $values);
  1625. $name = 'block.block.bartik_local_tasks';
  1626. $values = [
  1627. 'id' => 'bartik_local_tasks',
  1628. 'weight' => -7,
  1629. ] + $tabs_default_settings;
  1630. _system_update_create_block($name, $theme_name, $values);
  1631. // Help region has been removed so all the blocks inside has to be moved
  1632. // to content region.
  1633. $weight = -6;
  1634. $blocks = [];
  1635. foreach ($config_factory->listAll('block.block.') as $block_config) {
  1636. $block = $config_factory->getEditable($block_config);
  1637. if ($block->get('theme') == 'bartik' && $block->get('region') == 'help') {
  1638. $blocks[] = $block;
  1639. }
  1640. }
  1641. // Sort blocks by block weight.
  1642. uasort($blocks, function ($a, $b) {
  1643. return $a->get('weight') - $b->get('weight');
  1644. });
  1645. // Move blocks to content region and set them in right order by their
  1646. // weight.
  1647. foreach ($blocks as $block) {
  1648. $block->set('region', 'content');
  1649. $block->set('weight', $weight++);
  1650. $block->save();
  1651. }
  1652. break;
  1653. case 'seven':
  1654. $name = 'block.block.seven_local_actions';
  1655. $values = [
  1656. 'id' => 'seven_local_actions',
  1657. 'weight' => -10,
  1658. ] + $local_actions_default_settings;
  1659. _system_update_create_block($name, $theme_name, $values);
  1660. $name = 'block.block.seven_primary_local_tasks';
  1661. $values = [
  1662. 'region' => 'header',
  1663. 'id' => 'seven_primary_local_tasks',
  1664. 'settings.label' => 'Primary tabs',
  1665. 'settings.primary' => TRUE,
  1666. 'settings.secondary' => FALSE,
  1667. ] + $tabs_default_settings;
  1668. _system_update_create_block($name, $theme_name, $values);
  1669. $name = 'block.block.seven_secondary_local_tasks';
  1670. $values = [
  1671. 'region' => 'pre_content',
  1672. 'id' => 'seven_secondary_local_tasks',
  1673. 'settings.label' => 'Secondary tabs',
  1674. 'settings.primary' => FALSE,
  1675. 'settings.secondary' => TRUE,
  1676. ] + $tabs_default_settings;
  1677. _system_update_create_block($name, $theme_name, $values);
  1678. break;
  1679. case 'stark':
  1680. $name = 'block.block.stark_local_actions';
  1681. $values = [
  1682. 'id' => 'stark_local_actions',
  1683. ] + $local_actions_default_settings;
  1684. _system_update_create_block($name, $theme_name, $values);
  1685. $name = 'block.block.stark_local_tasks';
  1686. $values = [
  1687. 'id' => 'stark_local_tasks',
  1688. ] + $tabs_default_settings;
  1689. _system_update_create_block($name, $theme_name, $values);
  1690. break;
  1691. case 'classy':
  1692. case 'stable':
  1693. // Don't place any blocks or trigger custom themes installed warning.
  1694. break;
  1695. default:
  1696. $custom_themes_installed = TRUE;
  1697. $name = 'block.block.' . $theme_name . '_local_actions';
  1698. $values = [
  1699. 'id' => $theme_name . '_local_actions',
  1700. 'weight' => -10,
  1701. ] + $local_actions_default_settings;
  1702. _system_update_create_block($name, $theme_name, $values);
  1703. $name = sprintf('block.block.%s_local_tasks', $theme_name);
  1704. $values = [
  1705. 'id' => $theme_name . '_local_tasks',
  1706. 'weight' => -20,
  1707. ] + $tabs_default_settings;
  1708. _system_update_create_block($name, $theme_name, $values);
  1709. break;
  1710. }
  1711. }
  1712. if ($custom_themes_installed) {
  1713. $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.');
  1714. }
  1715. return $message;
  1716. }
  1717. /**
  1718. * Place branding blocks in every theme.
  1719. */
  1720. function system_update_8006() {
  1721. // When block module is not installed, there is nothing that could be done
  1722. // except showing a warning.
  1723. if (!\Drupal::moduleHandler()->moduleExists('block')) {
  1724. return t('Block module is not enabled so site branding elements, which have been converted to a block, are not visible anymore.');
  1725. }
  1726. /** @var \Drupal\Core\Extension\ThemeHandlerInterface $theme_handler */
  1727. $theme_handler = \Drupal::service('theme_handler');
  1728. $custom_themes_installed = FALSE;
  1729. $message = NULL;
  1730. $langcode = \Drupal::service('language_manager')->getCurrentLanguage()->getId();
  1731. $site_branding_default_settings = [
  1732. 'plugin' => 'system_branding_block',
  1733. 'region' => 'content',
  1734. 'settings.label' => 'Site branding',
  1735. 'settings.label_display' => 0,
  1736. 'visibility' => [],
  1737. 'weight' => 0,
  1738. 'langcode' => $langcode,
  1739. ];
  1740. foreach ($theme_handler->listInfo() as $theme) {
  1741. $theme_name = $theme->getName();
  1742. switch ($theme_name) {
  1743. case 'bartik':
  1744. $name = 'block.block.bartik_branding';
  1745. $values = [
  1746. 'id' => 'bartik_branding',
  1747. 'region' => 'header',
  1748. ] + $site_branding_default_settings;
  1749. _system_update_create_block($name, $theme_name, $values);
  1750. break;
  1751. case 'stark':
  1752. $name = 'block.block.stark_branding';
  1753. $values = [
  1754. 'id' => 'stark_branding',
  1755. 'region' => 'header',
  1756. ] + $site_branding_default_settings;
  1757. _system_update_create_block($name, $theme_name, $values);
  1758. break;
  1759. case 'seven':
  1760. case 'classy':
  1761. case 'stable':
  1762. // Don't place any blocks or trigger custom themes installed warning.
  1763. break;
  1764. default:
  1765. $custom_themes_installed = TRUE;
  1766. $name = sprintf('block.block.%s_branding', $theme_name);
  1767. $values = [
  1768. 'id' => sprintf('%s_branding', $theme_name),
  1769. 'region' => 'content',
  1770. 'weight' => '-50',
  1771. ] + $site_branding_default_settings;
  1772. _system_update_create_block($name, $theme_name, $values);
  1773. break;
  1774. }
  1775. }
  1776. if ($custom_themes_installed) {
  1777. $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.');
  1778. }
  1779. return $message;
  1780. }
  1781. /**
  1782. * Helper function to create block configuration objects for an update.
  1783. *
  1784. * @param string $name
  1785. * The name of the config object.
  1786. * @param string $theme_name
  1787. * The name of the theme the block is associated with.
  1788. * @param array $values
  1789. * The block config values.
  1790. */
  1791. function _system_update_create_block($name, $theme_name, array $values) {
  1792. if (!\Drupal::service('config.storage')->exists($name)) {
  1793. $block = \Drupal::configFactory()->getEditable($name);
  1794. $values['uuid'] = \Drupal::service('uuid')->generate();
  1795. $values['theme'] = $theme_name;
  1796. $values['dependencies.theme'] = [$theme_name];
  1797. foreach ($values as $key => $value) {
  1798. $block->set($key, $value);
  1799. }
  1800. $block->save();
  1801. }
  1802. }
  1803. /**
  1804. * Set langcode fields to be ASCII-only.
  1805. */
  1806. function system_update_8007() {
  1807. $database = \Drupal::database();
  1808. $database_schema = $database->schema();
  1809. $entity_types = \Drupal::entityTypeManager()->getDefinitions();
  1810. $schema = \Drupal::keyValue('entity.storage_schema.sql')->getAll();
  1811. $schema_copy = $schema;
  1812. foreach ($schema as $item_name => $item) {
  1813. list($entity_type_id, ,) = explode('.', $item_name);
  1814. if (!isset($entity_types[$entity_type_id])) {
  1815. continue;
  1816. }
  1817. foreach ($item as $table_name => $table_schema) {
  1818. foreach ($table_schema as $schema_key => $schema_data) {
  1819. if ($schema_key == 'fields') {
  1820. foreach ($schema_data as $field_name => $field_data) {
  1821. foreach ($field_data as $field_data_property => $field_data_value) {
  1822. // Langcode fields have the property 'is_ascii' set, instead
  1823. // they should have set the type to 'varchar_ascii'.
  1824. if ($field_data_property == 'is_ascii') {
  1825. unset($schema_copy[$item_name][$table_name]['fields'][$field_name]['is_ascii']);
  1826. $schema_copy[$item_name][$table_name]['fields'][$field_name]['type'] = 'varchar_ascii';
  1827. if ($database->driver() == 'mysql') {
  1828. $database_schema->changeField($table_name, $field_name, $field_name, $schema_copy[$item_name][$table_name]['fields'][$field_name]);
  1829. }
  1830. }
  1831. }
  1832. }
  1833. }
  1834. }
  1835. }
  1836. }
  1837. \Drupal::keyValue('entity.storage_schema.sql')->setMultiple($schema_copy);
  1838. $definitions = \Drupal::keyValue('entity.definitions.installed')->getAll();
  1839. $definitions_copy = $definitions;
  1840. foreach ($definitions as $item_name => $item_value) {
  1841. $suffix = '.field_storage_definitions';
  1842. if (substr($item_name, -strlen($suffix)) == $suffix) {
  1843. foreach ($item_value as $field_name => $field_definition) {
  1844. $reflection = new \ReflectionObject($field_definition);
  1845. $schema_property = $reflection->getProperty('schema');
  1846. $schema_property->setAccessible(TRUE);
  1847. $schema = $schema_property->getValue($field_definition);
  1848. if (isset($schema['columns']['value']['is_ascii'])) {
  1849. $schema['columns']['value']['type'] = 'varchar_ascii';
  1850. unset($schema['columns']['value']['is_ascii']);
  1851. }
  1852. $schema_property->setValue($field_definition, $schema);
  1853. $schema_property->setAccessible(FALSE);
  1854. $definitions_copy[$item_name][$field_name] = $field_definition;
  1855. }
  1856. }
  1857. }
  1858. \Drupal::keyValue('entity.definitions.installed')->setMultiple($definitions_copy);
  1859. }
  1860. /**
  1861. * Purge field schema data for uninstalled entity types.
  1862. */
  1863. function system_update_8008() {
  1864. $entity_types = \Drupal::entityTypeManager()->getDefinitions();
  1865. /** @var \Drupal\Core\KeyValueStore\KeyValueStoreInterface $schema */
  1866. $schema = \Drupal::keyValue('entity.storage_schema.sql');
  1867. foreach ($schema->getAll() as $key => $item) {
  1868. list($entity_type_id, ,) = explode('.', $key);
  1869. if (!isset($entity_types[$entity_type_id])) {
  1870. $schema->delete($key);
  1871. }
  1872. }
  1873. }
  1874. /**
  1875. * Add allowed attributes to existing html filters.
  1876. */
  1877. function system_update_8009() {
  1878. $default_mapping = [
  1879. '<a>' => '<a href hreflang>',
  1880. '<blockquote>' => '<blockquote cite>',
  1881. '<ol>' => '<ol start type>',
  1882. '<ul>' => '<ul type>',
  1883. '<img>' => '<img src alt height width>',
  1884. '<h2>' => '<h2 id>',
  1885. '<h3>' => '<h3 id>',
  1886. '<h4>' => '<h4 id>',
  1887. '<h5>' => '<h5 id>',
  1888. '<h6>' => '<h6 id>',
  1889. ];
  1890. $config_factory = \Drupal::configFactory();
  1891. foreach ($config_factory->listAll('filter.format') as $name) {
  1892. $allowed_html_mapping = $default_mapping;
  1893. $config = $config_factory->getEditable($name);
  1894. // The image alignment filter needs the data-align attribute.
  1895. $align_enabled = $config->get('filters.filter_align.status');
  1896. if ($align_enabled) {
  1897. $allowed_html_mapping['<img>'] = str_replace('>', ' data-align>', $allowed_html_mapping['<img>']);
  1898. }
  1899. // The image caption filter needs the data-caption attribute.
  1900. $caption_enabled = $config->get('filters.filter_caption.status');
  1901. if ($caption_enabled) {
  1902. $allowed_html_mapping['<img>'] = str_replace('>', ' data-caption>', $allowed_html_mapping['<img>']);
  1903. }
  1904. $allowed_html = $config->get('filters.filter_html.settings.allowed_html');
  1905. if (!empty($allowed_html)) {
  1906. $allowed_html = strtr($allowed_html, $allowed_html_mapping);
  1907. $config->set('filters.filter_html.settings.allowed_html', $allowed_html);
  1908. $config->save();
  1909. }
  1910. }
  1911. }
  1912. /**
  1913. * Place page title blocks in every theme.
  1914. */
  1915. function system_update_8010() {
  1916. // When block module is not installed, there is nothing that could be done
  1917. // except showing a warning.
  1918. if (!\Drupal::moduleHandler()->moduleExists('block')) {
  1919. 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.');
  1920. }
  1921. /** @var \Drupal\Core\Extension\ThemeHandlerInterface $theme_handler */
  1922. $theme_handler = \Drupal::service('theme_handler');
  1923. $custom_themes_installed = FALSE;
  1924. $message = NULL;
  1925. $langcode = \Drupal::service('language_manager')->getCurrentLanguage()->getId();
  1926. $page_title_default_settings = [
  1927. 'plugin' => 'page_title_block',
  1928. 'region' => 'content',
  1929. 'settings.label' => 'Page title',
  1930. 'settings.label_display' => 0,
  1931. 'visibility' => [],
  1932. 'weight' => -50,
  1933. 'langcode' => $langcode,
  1934. ];
  1935. foreach ($theme_handler->listInfo() as $theme) {
  1936. $theme_name = $theme->getName();
  1937. switch ($theme_name) {
  1938. case 'bartik':
  1939. $name = 'block.block.bartik_page_title';
  1940. $values = [
  1941. 'id' => 'bartik_page_title',
  1942. ] + $page_title_default_settings;
  1943. _system_update_create_block($name, $theme_name, $values);
  1944. break;
  1945. case 'stark':
  1946. $name = 'block.block.stark_page_title';
  1947. $values = [
  1948. 'id' => 'stark_page_title',
  1949. 'region' => 'content',
  1950. ] + $page_title_default_settings;
  1951. _system_update_create_block($name, $theme_name, $values);
  1952. break;
  1953. case 'seven':
  1954. $name = 'block.block.seven_page_title';
  1955. $values = [
  1956. 'id' => 'seven_page_title',
  1957. 'region' => 'header',
  1958. ] + $page_title_default_settings;
  1959. _system_update_create_block($name, $theme_name, $values);
  1960. break;
  1961. case 'classy':
  1962. $name = 'block.block.classy_page_title';
  1963. $values = [
  1964. 'id' => 'classy_page_title',
  1965. 'region' => 'content',
  1966. ] + $page_title_default_settings;
  1967. _system_update_create_block($name, $theme_name, $values);
  1968. break;
  1969. default:
  1970. $custom_themes_installed = TRUE;
  1971. $name = sprintf('block.block.%s_page_title', $theme_name);
  1972. $values = [
  1973. 'id' => sprintf('%s_page_title', $theme_name),
  1974. 'region' => 'content',
  1975. 'weight' => '-50',
  1976. ] + $page_title_default_settings;
  1977. _system_update_create_block($name, $theme_name, $values);
  1978. break;
  1979. }
  1980. }
  1981. if ($custom_themes_installed) {
  1982. $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.');
  1983. }
  1984. return $message;
  1985. }
  1986. /**
  1987. * Add secondary local tasks block to Seven (fixes system_update_8005).
  1988. */
  1989. function system_update_8011() {
  1990. $langcode = \Drupal::service('language_manager')->getCurrentLanguage()->getId();
  1991. $theme_name = 'seven';
  1992. $name = 'block.block.seven_secondary_local_tasks';
  1993. $values = [
  1994. 'plugin' => 'local_tasks_block',
  1995. 'region' => 'pre_content',
  1996. 'id' => 'seven_secondary_local_tasks',
  1997. 'settings.label' => 'Secondary tabs',
  1998. 'settings.label_display' => 0,
  1999. 'settings.primary' => FALSE,
  2000. 'settings.secondary' => TRUE,
  2001. 'visibility' => [],
  2002. 'weight' => 0,
  2003. 'langcode' => $langcode,
  2004. ];
  2005. _system_update_create_block($name, $theme_name, $values);
  2006. }
  2007. /**
  2008. * Enable automated cron module and move the config into it.
  2009. */
  2010. function system_update_8013() {
  2011. $autorun = \Drupal::configFactory()->getEditable('system.cron')->get('threshold.autorun');
  2012. if ($autorun) {
  2013. // Install 'automated_cron' module.
  2014. \Drupal::service('module_installer')->install(['automated_cron'], FALSE);
  2015. // Copy 'autorun' value into the new module's 'interval' setting.
  2016. \Drupal::configFactory()->getEditable('automated_cron.settings')
  2017. ->set('interval', $autorun)
  2018. ->save(TRUE);
  2019. }
  2020. // Remove the 'autorun' key in system module config.
  2021. \Drupal::configFactory()
  2022. ->getEditable('system.cron')
  2023. ->clear('threshold.autorun')
  2024. ->save(TRUE);
  2025. }
  2026. /**
  2027. * Install the Stable base theme if needed.
  2028. */
  2029. function system_update_8014() {
  2030. $theme_handler = \Drupal::service('theme_handler');
  2031. if ($theme_handler->themeExists('stable')) {
  2032. return;
  2033. }
  2034. $theme_handler->refreshInfo();
  2035. $theme_installer = \Drupal::service('theme_installer');
  2036. foreach ($theme_handler->listInfo() as $theme) {
  2037. // We first check that a base theme is set because if it's set to false then
  2038. // it's unset in
  2039. // \Drupal\Core\Extension\ThemeExtensionList::createExtensionInfo().
  2040. if (isset($theme->info['base theme']) && $theme->info['base theme'] == 'stable') {
  2041. $theme_installer->install(['stable']);
  2042. return;
  2043. }
  2044. }
  2045. }
  2046. /**
  2047. * Fix configuration overrides to not override non existing keys.
  2048. */
  2049. function system_update_8200(&$sandbox) {
  2050. $config_factory = \Drupal::configFactory();
  2051. if (!array_key_exists('config_names', $sandbox)) {
  2052. $sandbox['config_names'] = $config_factory->listAll();
  2053. $sandbox['max'] = count($sandbox['config_names']);
  2054. }
  2055. // Get a list of 50 to work on at a time.
  2056. $config_names_to_process = array_slice($sandbox['config_names'], 0, 50);
  2057. // Preload in a single query.
  2058. $config_factory->loadMultiple($config_names_to_process);
  2059. foreach ($config_names_to_process as $config_name) {
  2060. $config_factory->getEditable($config_name)->save();
  2061. }
  2062. // Update the list of names to process.
  2063. $sandbox['config_names'] = array_diff($sandbox['config_names'], $config_names_to_process);
  2064. $sandbox['#finished'] = empty($sandbox['config_names']) ? 1 : ($sandbox['max'] - count($sandbox['config_names'])) / $sandbox['max'];
  2065. }
  2066. /**
  2067. * Clear caches due to behavior change in DefaultPluginManager.
  2068. */
  2069. function system_update_8201() {
  2070. // Empty update to cause a cache rebuild.
  2071. // Use hook_post_update_NAME() instead to clear the cache.
  2072. // The use of hook_update_N() to clear the cache has been deprecated
  2073. // see https://www.drupal.org/node/2960601 for more details.
  2074. }
  2075. /**
  2076. * Clear caches due to behavior change in MachineName element.
  2077. */
  2078. function system_update_8202() {
  2079. // Empty update to cause a cache rebuild.
  2080. // Use hook_post_update_NAME() instead to clear the cache.The use
  2081. // of hook_update_N to clear the cache has been deprecated see
  2082. // https://www.drupal.org/node/2960601 for more details.
  2083. }
  2084. /**
  2085. * Add detailed cron logging configuration.
  2086. */
  2087. function system_update_8300() {
  2088. \Drupal::configFactory()->getEditable('system.cron')
  2089. ->set('logging', 1)
  2090. ->save(TRUE);
  2091. }
  2092. /**
  2093. * Add install profile to core.extension configuration.
  2094. */
  2095. function system_update_8301() {
  2096. \Drupal::configFactory()->getEditable('core.extension')
  2097. ->set('profile', \Drupal::installProfile())
  2098. ->save();
  2099. }
  2100. /**
  2101. * Move revision metadata fields to the revision table.
  2102. */
  2103. function system_update_8400(&$sandbox) {
  2104. // Due to the fields from RevisionLogEntityTrait not being explicitly
  2105. // mentioned in the storage they might have been installed wrongly in the base
  2106. // table for revisionable untranslatable entities and in the data and revision
  2107. // data tables for revisionable and translatable entities.
  2108. $entity_definition_update_manager = \Drupal::entityDefinitionUpdateManager();
  2109. $database = \Drupal::database();
  2110. $database_schema = $database->schema();
  2111. if (!isset($sandbox['current'])) {
  2112. // This must be the first run. Initialize the sandbox.
  2113. $sandbox['current'] = 0;
  2114. $definitions = array_filter(\Drupal::entityTypeManager()->getDefinitions(), function (EntityTypeInterface $entity_type) use ($entity_definition_update_manager) {
  2115. if ($entity_type = $entity_definition_update_manager->getEntityType($entity_type->id())) {
  2116. return is_subclass_of($entity_type->getClass(), FieldableEntityInterface::class) && ($entity_type instanceof ContentEntityTypeInterface) && $entity_type->isRevisionable();
  2117. }
  2118. return FALSE;
  2119. });
  2120. $sandbox['entity_type_ids'] = array_keys($definitions);
  2121. $sandbox['max'] = count($sandbox['entity_type_ids']);
  2122. }
  2123. $current_entity_type_key = $sandbox['current'];
  2124. for ($i = $current_entity_type_key; ($i < $current_entity_type_key + 1) && ($i < $sandbox['max']); $i++) {
  2125. $entity_type_id = $sandbox['entity_type_ids'][$i];
  2126. /** @var \Drupal\Core\Entity\ContentEntityTypeInterface $entity_type */
  2127. $entity_type = $entity_definition_update_manager->getEntityType($entity_type_id);
  2128. $base_fields = \Drupal::service('entity_field.manager')->getBaseFieldDefinitions($entity_type_id);
  2129. $revision_metadata_fields = $entity_type->getRevisionMetadataKeys();
  2130. $fields_to_update = array_intersect_key($base_fields, array_flip($revision_metadata_fields));
  2131. if (!empty($fields_to_update)) {
  2132. // Initialize the entity table names.
  2133. // @see \Drupal\Core\Entity\Sql\SqlContentEntityStorage::initTableLayout()
  2134. $base_table = $entity_type->getBaseTable() ?: $entity_type_id;
  2135. $data_table = $entity_type->getDataTable() ?: $entity_type_id . '_field_data';
  2136. $revision_table = $entity_type->getRevisionTable() ?: $entity_type_id . '_revision';
  2137. $revision_data_table = $entity_type->getRevisionDataTable() ?: $entity_type_id . '_field_revision';
  2138. $revision_field = $entity_type->getKey('revision');
  2139. // No data needs to be migrated if the entity type is not translatable.
  2140. if ($entity_type->isTranslatable()) {
  2141. if (!isset($sandbox[$entity_type_id])) {
  2142. // This must be the first run for this entity type. Initialize the
  2143. // sub-sandbox for it.
  2144. // Calculate the number of revisions to process.
  2145. $count = \Drupal::entityQuery($entity_type_id)
  2146. ->allRevisions()
  2147. ->count()
  2148. ->accessCheck(FALSE)
  2149. ->execute();
  2150. $sandbox[$entity_type_id]['current'] = 0;
  2151. $sandbox[$entity_type_id]['max'] = $count;
  2152. }
  2153. // Define the step size.
  2154. $steps = Settings::get('entity_update_batch_size', 50);
  2155. // Collect the revision IDs to process.
  2156. $revisions = \Drupal::entityQuery($entity_type_id)
  2157. ->allRevisions()
  2158. ->range($sandbox[$entity_type_id]['current'], $sandbox[$entity_type_id]['current'] + $steps)
  2159. ->sort($revision_field, 'ASC')
  2160. ->accessCheck(FALSE)
  2161. ->execute();
  2162. $revisions = array_keys($revisions);
  2163. foreach ($fields_to_update as $revision_metadata_field_name => $definition) {
  2164. // If the revision metadata field is present in the data and the
  2165. // revision data table, install its definition again with the updated
  2166. // storage code in order for the field to be installed in the
  2167. // revision table. Afterwards, copy over the field values and remove
  2168. // the field from the data and the revision data tables.
  2169. if ($database_schema->fieldExists($data_table, $revision_metadata_field_name) && $database_schema->fieldExists($revision_data_table, $revision_metadata_field_name)) {
  2170. // Install the field in the revision table.
  2171. if (!isset($sandbox[$entity_type_id]['storage_definition_installed'][$revision_metadata_field_name])) {
  2172. $entity_definition_update_manager->installFieldStorageDefinition($revision_metadata_field_name, $entity_type_id, $entity_type->getProvider(), $definition);
  2173. $sandbox[$entity_type_id]['storage_definition_installed'][$revision_metadata_field_name] = TRUE;
  2174. }
  2175. // Apply the field value from the revision data table to the
  2176. // revision table.
  2177. foreach ($revisions as $rev_id) {
  2178. $field_value = $database->select($revision_data_table, 't')
  2179. ->fields('t', [$revision_metadata_field_name])
  2180. ->condition($revision_field, $rev_id)
  2181. ->execute()
  2182. ->fetchField();
  2183. $database->update($revision_table)
  2184. ->condition($revision_field, $rev_id)
  2185. ->fields([$revision_metadata_field_name => $field_value])
  2186. ->execute();
  2187. }
  2188. }
  2189. }
  2190. $sandbox[$entity_type_id]['current'] += count($revisions);
  2191. $sandbox[$entity_type_id]['finished'] = ($sandbox[$entity_type_id]['current'] == $sandbox[$entity_type_id]['max']) || empty($revisions);
  2192. if ($sandbox[$entity_type_id]['finished']) {
  2193. foreach ($fields_to_update as $revision_metadata_field_name => $definition) {
  2194. // Drop the field from the data and revision data tables.
  2195. $database_schema->dropField($data_table, $revision_metadata_field_name);
  2196. $database_schema->dropField($revision_data_table, $revision_metadata_field_name);
  2197. }
  2198. $sandbox['current']++;
  2199. }
  2200. }
  2201. else {
  2202. foreach ($fields_to_update as $revision_metadata_field_name => $definition) {
  2203. if ($database_schema->fieldExists($base_table, $revision_metadata_field_name)) {
  2204. // Install the field in the revision table.
  2205. $entity_definition_update_manager->installFieldStorageDefinition($revision_metadata_field_name, $entity_type_id, $entity_type->getProvider(), $definition);
  2206. // Drop the field from the base table.
  2207. $database_schema->dropField($base_table, $revision_metadata_field_name);
  2208. }
  2209. }
  2210. $sandbox['current']++;
  2211. }
  2212. }
  2213. else {
  2214. $sandbox['current']++;
  2215. }
  2216. }
  2217. $sandbox['#finished'] = $sandbox['current'] == $sandbox['max'];
  2218. }
  2219. /**
  2220. * Remove response.gzip (and response) from system module configuration.
  2221. */
  2222. function system_update_8401() {
  2223. \Drupal::configFactory()->getEditable('system.performance')
  2224. ->clear('response.gzip')
  2225. ->clear('response')
  2226. ->save();
  2227. }
  2228. /**
  2229. * Add the 'revision_translation_affected' field to all entity types.
  2230. */
  2231. function system_update_8402() {
  2232. $definition_update_manager = \Drupal::entityDefinitionUpdateManager();
  2233. // Clear the cached entity type definitions so we get the new
  2234. // 'revision_translation_affected' entity key.
  2235. \Drupal::entityTypeManager()->clearCachedDefinitions();
  2236. // Get a list of revisionable and translatable entity types.
  2237. /** @var \Drupal\Core\Entity\ContentEntityTypeInterface[] $definitions */
  2238. $definitions = array_filter(\Drupal::entityTypeManager()->getDefinitions(), function (EntityTypeInterface $entity_type) use ($definition_update_manager) {
  2239. if ($entity_type = $definition_update_manager->getEntityType($entity_type->id())) {
  2240. return $entity_type->isRevisionable() && $entity_type->isTranslatable();
  2241. }
  2242. return FALSE;
  2243. });
  2244. foreach ($definitions as $entity_type_id => $entity_type) {
  2245. $field_name = $entity_type->getKey('revision_translation_affected');
  2246. // Install the 'revision_translation_affected' field if needed.
  2247. if (!$definition_update_manager->getFieldStorageDefinition($field_name, $entity_type_id)) {
  2248. $storage_definition = BaseFieldDefinition::create('boolean')
  2249. ->setLabel(t('Revision translation affected'))
  2250. ->setDescription(t('Indicates if the last edit of a translation belongs to current revision.'))
  2251. ->setReadOnly(TRUE)
  2252. ->setRevisionable(TRUE)
  2253. ->setTranslatable(TRUE)
  2254. // Mark all pre-existing revisions as affected in order to be consistent
  2255. // with the previous API return value: if the field was not defined the
  2256. // value returned was always TRUE.
  2257. ->setInitialValue(TRUE);
  2258. $definition_update_manager
  2259. ->installFieldStorageDefinition($field_name, $entity_type_id, $entity_type_id, $storage_definition);
  2260. }
  2261. }
  2262. }
  2263. /**
  2264. * Delete all cache_* tables. They are recreated on demand with the new schema.
  2265. */
  2266. function system_update_8403() {
  2267. foreach (Cache::getBins() as $bin => $cache_backend) {
  2268. // Try to delete the table regardless of which cache backend is handling it.
  2269. // This is to ensure the new schema is used if the configuration for the
  2270. // backend class is changed after the update hook runs.
  2271. $table_name = "cache_$bin";
  2272. $schema = Database::getConnection()->schema();
  2273. if ($schema->tableExists($table_name)) {
  2274. $schema->dropTable($table_name);
  2275. }
  2276. }
  2277. }
  2278. /**
  2279. * Add the 'revision_default' field to all relevant entity types.
  2280. */
  2281. function system_update_8501() {
  2282. $definition_update_manager = \Drupal::entityDefinitionUpdateManager();
  2283. // Clear the cached entity type definitions so we get the new
  2284. // 'revision_default' revision metadata key.
  2285. \Drupal::entityTypeManager()->clearCachedDefinitions();
  2286. // Get a list of revisionable entity types.
  2287. /** @var \Drupal\Core\Entity\ContentEntityTypeInterface[] $definitions */
  2288. $definitions = array_filter(\Drupal::entityTypeManager()->getDefinitions(), function (EntityTypeInterface $entity_type) use ($definition_update_manager) {
  2289. if ($entity_type = $definition_update_manager->getEntityType($entity_type->id())) {
  2290. return $entity_type->isRevisionable();
  2291. }
  2292. return FALSE;
  2293. });
  2294. // Install the 'revision_default' field.
  2295. foreach ($definitions as $entity_type_id => $entity_type) {
  2296. $field_name = $entity_type->getRevisionMetadataKey('revision_default');
  2297. // Install the 'revision_default' field if needed.
  2298. if (!$definition_update_manager->getFieldStorageDefinition($field_name, $entity_type_id)) {
  2299. // Make sure the new "revision_default" revision metadata key is available
  2300. // also to code using the latest installed definition.
  2301. $installed_entity_type = $definition_update_manager->getEntityType($entity_type_id);
  2302. $revision_metadata_keys = $installed_entity_type->get('revision_metadata_keys');
  2303. if (!isset($revision_metadata_keys['revision_default'])) {
  2304. // Update the property holding the required revision metadata keys,
  2305. // which is used by the BC layer for retrieving the revision metadata
  2306. // keys.
  2307. // @see \Drupal\Core\Entity\ContentEntityType::getRevisionMetadataKeys().
  2308. $required_revision_metadata_keys = $installed_entity_type->get('requiredRevisionMetadataKeys');
  2309. $required_revision_metadata_keys['revision_default'] = $field_name;
  2310. $installed_entity_type->set('requiredRevisionMetadataKeys', $required_revision_metadata_keys);
  2311. // Update the revision metadata keys to add the new required revision
  2312. // metadata key "revision_default".
  2313. $revision_metadata_keys['revision_default'] = $required_revision_metadata_keys['revision_default'];
  2314. $installed_entity_type->set('revision_metadata_keys', $revision_metadata_keys);
  2315. $definition_update_manager->updateEntityType($installed_entity_type);
  2316. }
  2317. $storage_definition = BaseFieldDefinition::create('boolean')
  2318. ->setLabel(t('Default revision'))
  2319. ->setDescription(t('A flag indicating whether this was a default revision when it was saved.'))
  2320. ->setStorageRequired(TRUE)
  2321. ->setTranslatable(FALSE)
  2322. ->setRevisionable(TRUE)
  2323. // We cannot tell whether existing revisions were default or not when
  2324. // they were created, but since we did not support creating non-default
  2325. // revisions in any core stable UI so far, we default to TRUE.
  2326. ->setInitialValue(TRUE);
  2327. $definition_update_manager
  2328. ->installFieldStorageDefinition($field_name, $entity_type_id, $entity_type_id, $storage_definition);
  2329. }
  2330. else {
  2331. $variables = ['@entity_type_label' => $entity_type->getLabel()];
  2332. if ($field_name === 'revision_default') {
  2333. \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);
  2334. }
  2335. else {
  2336. \Drupal::logger('system')->error('An existing "Default revision" field was found for the @entity_type_label entity type.', $variables);
  2337. }
  2338. }
  2339. }
  2340. }
  2341. /**
  2342. * Fix missing install profile after updating to Drupal 8.6.9 with Drush 8.
  2343. */
  2344. function system_update_8601() {
  2345. $extension_config = \Drupal::configFactory()->getEditable('core.extension');
  2346. $install_profile = $extension_config->get('profile');
  2347. if (!$install_profile) {
  2348. // There's no install profile configured.
  2349. return;
  2350. }
  2351. $modules = $extension_config->get('module');
  2352. if (isset($modules[$install_profile])) {
  2353. // The install profile is already in the installed module list.
  2354. return;
  2355. }
  2356. // Ensure the install profile is available.
  2357. if (!\Drupal::service('extension.list.module')->exists($install_profile)) {
  2358. return t('The %install_profile install profile configured in core.extension is not available.', ['%install_profile' => $install_profile]);
  2359. }
  2360. // Add the install profile to the list of enabled modules.
  2361. $modules[$install_profile] = 1000;
  2362. $modules = module_config_sort($modules);
  2363. $extension_config
  2364. ->set('module', $modules)
  2365. ->save(TRUE);
  2366. // Build a module list from the updated extension configuration.
  2367. $current_module_filenames = \Drupal::moduleHandler()->getModuleList();
  2368. $current_modules = array_fill_keys(array_keys($current_module_filenames), 0);
  2369. $current_modules = module_config_sort(array_merge($current_modules, $extension_config->get('module')));
  2370. $module_filenames = [];
  2371. foreach ($current_modules as $name => $weight) {
  2372. if (isset($current_module_filenames[$name])) {
  2373. $module_filenames[$name] = $current_module_filenames[$name];
  2374. }
  2375. else {
  2376. $module_path = \Drupal::service('extension.list.module')->getPath($name);
  2377. $pathname = "$module_path/$name.info.yml";
  2378. $filename = file_exists($module_path . "/$name.module") ? "$name.module" : NULL;
  2379. $module_filenames[$name] = new Extension(\Drupal::root(), 'module', $pathname, $filename);
  2380. }
  2381. }
  2382. // Update the module handler list to contain the missing install profile.
  2383. \Drupal::moduleHandler()->setModuleList($module_filenames);
  2384. \Drupal::moduleHandler()->load($install_profile);
  2385. // Clear the static cache of the "extension.list.module" service to pick
  2386. // up the new install profile correctly.
  2387. \Drupal::service('extension.list.profile')->reset();
  2388. // Clear the static cache of the "extension.list.module" service to pick
  2389. // up the new module, since it merges the installation status of modules
  2390. // into its statically cached list.
  2391. \Drupal::service('extension.list.module')->reset();
  2392. // Update the kernel to include the missing profile.
  2393. \Drupal::service('kernel')->updateModules($module_filenames, $module_filenames);
  2394. return t('The %install_profile install profile has been added to the installed module list.', ['%install_profile' => $install_profile]);
  2395. }
  2396. /**
  2397. * Remove the unused 'system.theme.data' from state.
  2398. */
  2399. function system_update_8701() {
  2400. // The system.theme.data key is no longer used in Drupal 8.7.x.
  2401. \Drupal::state()->delete('system.theme.data');
  2402. }
  2403. /**
  2404. * Add the 'revision_translation_affected' entity key.
  2405. */
  2406. function system_update_8702() {
  2407. $entity_definition_update_manager = \Drupal::entityDefinitionUpdateManager();
  2408. // Get a list of revisionable and translatable entity types.
  2409. /** @var \Drupal\Core\Entity\EntityTypeInterface[] $last_installed_definitions */
  2410. $last_installed_definitions = array_filter($entity_definition_update_manager->getEntityTypes(), function (EntityTypeInterface $entity_type) {
  2411. return $entity_type->isRevisionable() && $entity_type->isTranslatable();
  2412. });
  2413. // Ensure that we don't use the cached in-code definitions to support sites
  2414. // that might be updating from 8.3.x straight to 8.7.x.
  2415. \Drupal::entityTypeManager()->useCaches(FALSE);
  2416. $live_definitions = \Drupal::entityTypeManager()->getDefinitions();
  2417. // Update the 'revision_translation_affected' entity key of the last installed
  2418. // definitions to use the value of the live (in-code) entity type definitions
  2419. // in cases when the key has not been populated yet.
  2420. foreach ($last_installed_definitions as $entity_type_id => $entity_type) {
  2421. // The live (in-code) entity type definition might not exist anymore, while
  2422. // an update function that would remove its last installed definition didn't
  2423. // run yet. We don't need to update it in that case.
  2424. if (!isset($live_definitions[$entity_type_id])) {
  2425. continue;
  2426. }
  2427. $revision_translation_affected_key = $live_definitions[$entity_type_id]->getKey('revision_translation_affected');
  2428. if (!$entity_type->hasKey('revision_translation_affected') && !empty($revision_translation_affected_key) && $entity_definition_update_manager->getFieldStorageDefinition($revision_translation_affected_key, $entity_type_id)) {
  2429. $entity_keys = $entity_type->getKeys();
  2430. $entity_keys['revision_translation_affected'] = $revision_translation_affected_key;
  2431. $entity_type->set('entity_keys', $entity_keys);
  2432. $entity_definition_update_manager->updateEntityType($entity_type);
  2433. }
  2434. }
  2435. \Drupal::entityTypeManager()->useCaches(TRUE);
  2436. }
  2437. /**
  2438. * Remove 'path.temporary' config if redundant.
  2439. */
  2440. function system_update_8801() {
  2441. // If settings is already being used, or the config is set to the OS default,
  2442. // clear the config value.
  2443. $config = Drupal::configFactory()->getEditable('system.file');
  2444. if (Settings::get('file_temp_path') || $config->get('path.temporary') === FileSystemComponent::getOsTemporaryDirectory()) {
  2445. $config->clear('path.temporary')
  2446. ->save(TRUE);
  2447. }
  2448. }
  2449. /**
  2450. * Fix system.theme:admin when the default theme is used as the admin theme.
  2451. */
  2452. function system_update_8802() {
  2453. $config = Drupal::configFactory()->getEditable('system.theme');
  2454. // Replace '0' with an empty string as '0' is not a valid value.
  2455. if ($config->get('admin') == '0') {
  2456. $config
  2457. ->set('admin', '')
  2458. ->save(TRUE);
  2459. }
  2460. }
  2461. /**
  2462. * Install the 'path_alias' entity type.
  2463. */
  2464. function system_update_8803() {
  2465. // Enable the Path Alias module if needed.
  2466. if (!\Drupal::moduleHandler()->moduleExists('path_alias')) {
  2467. \Drupal::service('module_installer')->install(['path_alias'], FALSE);
  2468. return t('The "path_alias" entity type has been installed.');
  2469. }
  2470. }
  2471. /**
  2472. * Convert path aliases to entities.
  2473. */
  2474. function system_update_8804(&$sandbox = NULL) {
  2475. // Bail out early if the entity type is not using the default storage class.
  2476. $storage = \Drupal::entityTypeManager()->getStorage('path_alias');
  2477. if (!$storage instanceof PathAliasStorage) {
  2478. return;
  2479. }
  2480. if (!isset($sandbox['current_id'])) {
  2481. // This must be the first run. Initialize the sandbox.
  2482. $sandbox['progress'] = 0;
  2483. $sandbox['current_id'] = 0;
  2484. }
  2485. $database = \Drupal::database();
  2486. $step_size = 200;
  2487. $url_aliases = $database->select('url_alias', 't')
  2488. ->condition('t.pid', $sandbox['current_id'], '>')
  2489. ->fields('t')
  2490. ->orderBy('pid', 'ASC')
  2491. ->range(0, $step_size)
  2492. ->execute()
  2493. ->fetchAll();
  2494. if ($url_aliases) {
  2495. /** @var \Drupal\Component\Uuid\UuidInterface $uuid */
  2496. $uuid = \Drupal::service('uuid');
  2497. $base_table_insert = $database->insert('path_alias');
  2498. $base_table_insert->fields(['id', 'revision_id', 'uuid', 'path', 'alias', 'langcode', 'status']);
  2499. $revision_table_insert = $database->insert('path_alias_revision');
  2500. $revision_table_insert->fields(['id', 'revision_id', 'path', 'alias', 'langcode', 'status', 'revision_default']);
  2501. foreach ($url_aliases as $url_alias) {
  2502. $values = [
  2503. 'id' => $url_alias->pid,
  2504. 'revision_id' => $url_alias->pid,
  2505. 'uuid' => $uuid->generate(),
  2506. 'path' => $url_alias->source,
  2507. 'alias' => $url_alias->alias,
  2508. 'langcode' => $url_alias->langcode,
  2509. 'status' => 1,
  2510. ];
  2511. $base_table_insert->values($values);
  2512. unset($values['uuid']);
  2513. $values['revision_default'] = 1;
  2514. $revision_table_insert->values($values);
  2515. }
  2516. $base_table_insert->execute();
  2517. $revision_table_insert->execute();
  2518. $sandbox['progress'] += count($url_aliases);
  2519. $last_url_alias = end($url_aliases);
  2520. $sandbox['current_id'] = $last_url_alias->pid;
  2521. // If we're not in maintenance mode, the number of path aliases could change
  2522. // at any time so make sure that we always use the latest record count.
  2523. $missing = $database->select('url_alias', 't')
  2524. ->condition('t.pid', $sandbox['current_id'], '>')
  2525. ->orderBy('pid', 'ASC')
  2526. ->countQuery()
  2527. ->execute()
  2528. ->fetchField();
  2529. $sandbox['#finished'] = $missing ? $sandbox['progress'] / ($sandbox['progress'] + (int) $missing) : 1;
  2530. }
  2531. else {
  2532. $sandbox['#finished'] = 1;
  2533. }
  2534. if ($sandbox['#finished'] >= 1) {
  2535. // Keep a backup of the old 'url_alias' table if requested.
  2536. if (Settings::get('entity_update_backup', TRUE)) {
  2537. $old_table_name = 'old_' . substr(uniqid(), 0, 6) . '_url_alias';
  2538. if (!$database->schema()->tableExists($old_table_name)) {
  2539. $database->schema()->renameTable('url_alias', $old_table_name);
  2540. }
  2541. }
  2542. else {
  2543. $database->schema()->dropTable('url_alias');
  2544. }
  2545. return t('Path aliases have been converted to entities.');
  2546. }
  2547. }
  2548. /**
  2549. * Change the provider of the 'path_alias' entity type and its base fields.
  2550. */
  2551. function system_update_8805() {
  2552. // If the path alias module is not installed, it means that
  2553. // system_update_8803() ran as part of Drupal 8.8.0-alpha1, in which case we
  2554. // need to enable the module and change the provider of the 'path_alias'
  2555. // entity type.
  2556. if (!\Drupal::moduleHandler()->moduleExists('path_alias')) {
  2557. \Drupal::service('module_installer')->install(['path_alias'], FALSE);
  2558. /** @var \Drupal\Core\Entity\EntityLastInstalledSchemaRepositoryInterface $last_installed_schema_repository */
  2559. $last_installed_schema_repository = \Drupal::service('entity.last_installed_schema.repository');
  2560. $entity_type = $last_installed_schema_repository->getLastInstalledDefinition('path_alias');
  2561. // Set the new class for the entity type.
  2562. $entity_type->setClass(PathAlias::class);
  2563. // Set the new provider for the entity type.
  2564. $reflection = new ReflectionClass($entity_type);
  2565. $property = $reflection->getProperty('provider');
  2566. $property->setAccessible(TRUE);
  2567. $property->setValue($entity_type, 'path_alias');
  2568. $last_installed_schema_repository->setLastInstalledDefinition($entity_type);
  2569. $field_storage_definitions = $last_installed_schema_repository->getLastInstalledFieldStorageDefinitions('path_alias');
  2570. foreach ($field_storage_definitions as $field_storage_definition) {
  2571. if ($field_storage_definition->isBaseField()) {
  2572. $field_storage_definition->setProvider('path_alias');
  2573. $last_installed_schema_repository->setLastInstalledFieldStorageDefinition($field_storage_definition);
  2574. }
  2575. }
  2576. }
  2577. }
  2578. /**
  2579. * Update the stored schema data for entity identifier fields.
  2580. */
  2581. function system_update_8901() {
  2582. $definition_update_manager = \Drupal::entityDefinitionUpdateManager();
  2583. $entity_type_manager = \Drupal::entityTypeManager();
  2584. $installed_storage_schema = \Drupal::keyValue('entity.storage_schema.sql');
  2585. foreach ($definition_update_manager->getEntityTypes() as $entity_type_id => $entity_type) {
  2586. // Ensure that we are dealing with a non-deleted entity type that uses the
  2587. // default SQL storage.
  2588. if (!$entity_type_manager->hasDefinition($entity_type_id)) {
  2589. continue;
  2590. }
  2591. $storage = $entity_type_manager->getStorage($entity_type_id);
  2592. if (!$storage instanceof SqlContentEntityStorage) {
  2593. continue;
  2594. }
  2595. foreach (['id', 'revision'] as $key) {
  2596. if (!$entity_type->hasKey($key)) {
  2597. continue;
  2598. }
  2599. $field_name = $entity_type->getKey($key);
  2600. $field_storage_definition = $definition_update_manager->getFieldStorageDefinition($field_name, $entity_type_id);
  2601. if (!$field_storage_definition) {
  2602. continue;
  2603. }
  2604. if ($field_storage_definition->getType() !== 'integer') {
  2605. continue;
  2606. }
  2607. // Retrieve the storage schema in order to use its own method for updating
  2608. // the identifier schema - ::processIdentifierSchema(). This is needed
  2609. // because some storage schemas might not use serial identifiers.
  2610. // @see \Drupal\user\UserStorageSchema::processIdentifierSchema()
  2611. $ref_get_storage_schema = new \ReflectionMethod($storage, 'getStorageSchema');
  2612. $ref_get_storage_schema->setAccessible(TRUE);
  2613. $storage_schema = $ref_get_storage_schema->invoke($storage);
  2614. if ($storage_schema instanceof SqlContentEntityStorageSchema) {
  2615. $field_schema_data = $installed_storage_schema->get($entity_type_id . '.field_schema_data.' . $field_storage_definition->getName(), []);
  2616. $table = $key === 'id' ? $entity_type->getBaseTable() : $entity_type->getRevisionTable();
  2617. $ref_process_identifier_schema = new \ReflectionMethod($storage_schema, 'processIdentifierSchema');
  2618. $ref_process_identifier_schema->setAccessible(TRUE);
  2619. $ref_process_identifier_schema->invokeArgs($storage_schema, [&$field_schema_data[$table], $field_name]);
  2620. $installed_storage_schema->set($entity_type_id . '.field_schema_data.' . $field_storage_definition->getName(), $field_schema_data);
  2621. }
  2622. }
  2623. }
  2624. }