taxonomy.post_update.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366
  1. <?php
  2. /**
  3. * @file
  4. * Post update functions for Taxonomy.
  5. */
  6. use Drupal\Core\Config\Entity\ConfigEntityUpdater;
  7. use Drupal\Core\Entity\Display\EntityDisplayInterface;
  8. use Drupal\Core\Field\BaseFieldDefinition;
  9. use Drupal\Core\Logger\RfcLogLevel;
  10. use Drupal\Core\Site\Settings;
  11. use Drupal\Core\StringTranslation\PluralTranslatableMarkup;
  12. use Drupal\Core\StringTranslation\TranslatableMarkup;
  13. use Drupal\Core\Url;
  14. use Drupal\taxonomy\TermStorage;
  15. use Drupal\views\ViewExecutable;
  16. /**
  17. * Clear caches due to updated taxonomy entity views data.
  18. */
  19. function taxonomy_post_update_clear_views_data_cache() {
  20. // An empty update will flush caches.
  21. }
  22. /**
  23. * Clear entity_bundle_field_definitions cache for new parent field settings.
  24. */
  25. function taxonomy_post_update_clear_entity_bundle_field_definitions_cache() {
  26. // An empty update will flush caches.
  27. }
  28. /**
  29. * Add a 'published' = TRUE filter for all Taxonomy term views and converts
  30. * existing ones that were using the 'content_translation_status' field.
  31. */
  32. function taxonomy_post_update_handle_publishing_status_addition_in_views(&$sandbox = NULL) {
  33. // If Views is not installed, there is nothing to do.
  34. if (!\Drupal::moduleHandler()->moduleExists('views')) {
  35. return;
  36. }
  37. $definition_update_manager = \Drupal::entityDefinitionUpdateManager();
  38. $entity_type = $definition_update_manager->getEntityType('taxonomy_term');
  39. $published_key = $entity_type->getKey('published');
  40. $status_filter = [
  41. 'id' => 'status',
  42. 'table' => 'taxonomy_term_field_data',
  43. 'field' => $published_key,
  44. 'relationship' => 'none',
  45. 'group_type' => 'group',
  46. 'admin_label' => '',
  47. 'operator' => '=',
  48. 'value' => '1',
  49. 'group' => 1,
  50. 'exposed' => FALSE,
  51. 'expose' => [
  52. 'operator_id' => '',
  53. 'label' => '',
  54. 'description' => '',
  55. 'use_operator' => FALSE,
  56. 'operator' => '',
  57. 'identifier' => '',
  58. 'required' => FALSE,
  59. 'remember' => FALSE,
  60. 'multiple' => FALSE,
  61. 'remember_roles' => [
  62. 'authenticated' => 'authenticated',
  63. 'anonymous' => '0',
  64. 'administrator' => '0',
  65. ],
  66. ],
  67. 'is_grouped' => FALSE,
  68. 'group_info' => [
  69. 'label' => '',
  70. 'description' => '',
  71. 'identifier' => '',
  72. 'optional' => TRUE,
  73. 'widget' => 'select',
  74. 'multiple' => FALSE,
  75. 'remember' => FALSE,
  76. 'default_group' => 'All',
  77. 'default_group_multiple' => [],
  78. 'group_items' => [],
  79. ],
  80. 'entity_type' => 'taxonomy_term',
  81. 'entity_field' => $published_key,
  82. 'plugin_id' => 'boolean',
  83. ];
  84. \Drupal::classResolver(ConfigEntityUpdater::class)->update($sandbox, 'view', function ($view) use ($published_key, $status_filter) {
  85. /** @var \Drupal\views\ViewEntityInterface $view */
  86. // Only alter taxonomy term views.
  87. if ($view->get('base_table') !== 'taxonomy_term_field_data') {
  88. return FALSE;
  89. }
  90. $displays = $view->get('display');
  91. foreach ($displays as $display_name => &$display) {
  92. // Update any existing 'content_translation_status fields.
  93. $fields = isset($display['display_options']['fields']) ? $display['display_options']['fields'] : [];
  94. foreach ($fields as $id => $field) {
  95. if (isset($field['field']) && $field['field'] == 'content_translation_status') {
  96. $fields[$id]['field'] = $published_key;
  97. }
  98. }
  99. $display['display_options']['fields'] = $fields;
  100. // Update any existing 'content_translation_status sorts.
  101. $sorts = isset($display['display_options']['sorts']) ? $display['display_options']['sorts'] : [];
  102. foreach ($sorts as $id => $sort) {
  103. if (isset($sort['field']) && $sort['field'] == 'content_translation_status') {
  104. $sorts[$id]['field'] = $published_key;
  105. }
  106. }
  107. $display['display_options']['sorts'] = $sorts;
  108. // Update any existing 'content_translation_status' filters or add a new
  109. // one if necessary.
  110. $filters = isset($display['display_options']['filters']) ? $display['display_options']['filters'] : [];
  111. $has_status_filter = FALSE;
  112. foreach ($filters as $id => $filter) {
  113. if (isset($filter['field']) && $filter['field'] == 'content_translation_status') {
  114. $filters[$id]['field'] = $published_key;
  115. $has_status_filter = TRUE;
  116. }
  117. }
  118. if (!$has_status_filter) {
  119. $status_filter['id'] = ViewExecutable::generateHandlerId($published_key, $filters);
  120. $filters[$status_filter['id']] = $status_filter;
  121. }
  122. $display['display_options']['filters'] = $filters;
  123. }
  124. $view->set('display', $displays);
  125. return TRUE;
  126. });
  127. }
  128. /**
  129. * Remove the 'hierarchy' property from vocabularies.
  130. */
  131. function taxonomy_post_update_remove_hierarchy_from_vocabularies(&$sandbox = NULL) {
  132. \Drupal::classResolver(ConfigEntityUpdater::class)->update($sandbox, 'taxonomy_vocabulary', function () {
  133. return TRUE;
  134. });
  135. }
  136. /**
  137. * Update taxonomy terms to be revisionable.
  138. */
  139. function taxonomy_post_update_make_taxonomy_term_revisionable(&$sandbox) {
  140. $finished = _taxonomy_post_update_make_taxonomy_term_revisionable__fix_default_langcode($sandbox);
  141. if (!$finished) {
  142. $sandbox['#finished'] = 0;
  143. return NULL;
  144. }
  145. $definition_update_manager = \Drupal::entityDefinitionUpdateManager();
  146. /** @var \Drupal\Core\Entity\EntityLastInstalledSchemaRepositoryInterface $last_installed_schema_repository */
  147. $last_installed_schema_repository = \Drupal::service('entity.last_installed_schema.repository');
  148. $entity_type = $definition_update_manager->getEntityType('taxonomy_term');
  149. $field_storage_definitions = $last_installed_schema_repository->getLastInstalledFieldStorageDefinitions('taxonomy_term');
  150. // Update the entity type definition.
  151. $entity_keys = $entity_type->getKeys();
  152. $entity_keys['revision'] = 'revision_id';
  153. $entity_keys['revision_translation_affected'] = 'revision_translation_affected';
  154. $entity_type->set('entity_keys', $entity_keys);
  155. $entity_type->set('revision_table', 'taxonomy_term_revision');
  156. $entity_type->set('revision_data_table', 'taxonomy_term_field_revision');
  157. $revision_metadata_keys = [
  158. 'revision_default' => 'revision_default',
  159. 'revision_user' => 'revision_user',
  160. 'revision_created' => 'revision_created',
  161. 'revision_log_message' => 'revision_log_message',
  162. ];
  163. $entity_type->set('revision_metadata_keys', $revision_metadata_keys);
  164. // Update the field storage definitions and add the new ones required by a
  165. // revisionable entity type.
  166. $field_storage_definitions['langcode']->setRevisionable(TRUE);
  167. $field_storage_definitions['name']->setRevisionable(TRUE);
  168. $field_storage_definitions['description']->setRevisionable(TRUE);
  169. $field_storage_definitions['changed']->setRevisionable(TRUE);
  170. $field_storage_definitions['revision_id'] = BaseFieldDefinition::create('integer')
  171. ->setName('revision_id')
  172. ->setTargetEntityTypeId('taxonomy_term')
  173. ->setTargetBundle(NULL)
  174. ->setLabel(new TranslatableMarkup('Revision ID'))
  175. ->setReadOnly(TRUE)
  176. ->setSetting('unsigned', TRUE);
  177. $field_storage_definitions['revision_default'] = BaseFieldDefinition::create('boolean')
  178. ->setName('revision_default')
  179. ->setTargetEntityTypeId('taxonomy_term')
  180. ->setTargetBundle(NULL)
  181. ->setLabel(new TranslatableMarkup('Default revision'))
  182. ->setDescription(new TranslatableMarkup('A flag indicating whether this was a default revision when it was saved.'))
  183. ->setStorageRequired(TRUE)
  184. ->setInternal(TRUE)
  185. ->setTranslatable(FALSE)
  186. ->setRevisionable(TRUE);
  187. $field_storage_definitions['revision_translation_affected'] = BaseFieldDefinition::create('boolean')
  188. ->setName('revision_translation_affected')
  189. ->setTargetEntityTypeId('taxonomy_term')
  190. ->setTargetBundle(NULL)
  191. ->setLabel(new TranslatableMarkup('Revision translation affected'))
  192. ->setDescription(new TranslatableMarkup('Indicates if the last edit of a translation belongs to current revision.'))
  193. ->setReadOnly(TRUE)
  194. ->setRevisionable(TRUE)
  195. ->setTranslatable(TRUE);
  196. $field_storage_definitions['revision_created'] = BaseFieldDefinition::create('created')
  197. ->setName('revision_created')
  198. ->setTargetEntityTypeId('taxonomy_term')
  199. ->setTargetBundle(NULL)
  200. ->setLabel(new TranslatableMarkup('Revision create time'))
  201. ->setDescription(new TranslatableMarkup('The time that the current revision was created.'))
  202. ->setRevisionable(TRUE);
  203. $field_storage_definitions['revision_user'] = BaseFieldDefinition::create('entity_reference')
  204. ->setName('revision_user')
  205. ->setTargetEntityTypeId('taxonomy_term')
  206. ->setTargetBundle(NULL)
  207. ->setLabel(new TranslatableMarkup('Revision user'))
  208. ->setDescription(new TranslatableMarkup('The user ID of the author of the current revision.'))
  209. ->setSetting('target_type', 'user')
  210. ->setRevisionable(TRUE);
  211. $field_storage_definitions['revision_log_message'] = BaseFieldDefinition::create('string_long')
  212. ->setName('revision_log_message')
  213. ->setTargetEntityTypeId('taxonomy_term')
  214. ->setTargetBundle(NULL)
  215. ->setLabel(new TranslatableMarkup('Revision log message'))
  216. ->setDescription(new TranslatableMarkup('Briefly describe the changes you have made.'))
  217. ->setRevisionable(TRUE)
  218. ->setDefaultValue('');
  219. $definition_update_manager->updateFieldableEntityType($entity_type, $field_storage_definitions, $sandbox);
  220. if (!empty($sandbox['data_fix']['default_langcode']['processed'])) {
  221. $count = $sandbox['data_fix']['default_langcode']['processed'];
  222. if (\Drupal::moduleHandler()->moduleExists('dblog')) {
  223. // @todo Simplify with https://www.drupal.org/node/2548095
  224. $base_url = str_replace('/update.php', '', \Drupal::request()->getBaseUrl());
  225. $args = [
  226. ':url' => Url::fromRoute('dblog.overview', [], ['query' => ['type' => ['update'], 'severity' => [RfcLogLevel::WARNING]]])
  227. ->setOption('base_url', $base_url)
  228. ->toString(TRUE)
  229. ->getGeneratedUrl(),
  230. ];
  231. return new PluralTranslatableMarkup($count, 'Taxonomy terms have been converted to be revisionable. One term with data integrity issues was restored. More details have been <a href=":url">logged</a>.', 'Taxonomy terms have been converted to be revisionable. @count terms with data integrity issues were restored. More details have been <a href=":url">logged</a>.', $args);
  232. }
  233. else {
  234. return new PluralTranslatableMarkup($count, 'Taxonomy terms have been converted to be revisionable. One term with data integrity issues was restored. More details have been logged.', 'Taxonomy terms have been converted to be revisionable. @count terms with data integrity issues were restored. More details have been logged.');
  235. }
  236. }
  237. else {
  238. return t('Taxonomy terms have been converted to be revisionable.');
  239. }
  240. }
  241. /**
  242. * Fixes recoverable data integrity issues in the "default_langcode" field.
  243. *
  244. * @param array $sandbox
  245. * The update sandbox array.
  246. *
  247. * @return bool
  248. * TRUE if the operation was finished, FALSE otherwise.
  249. *
  250. * @internal
  251. */
  252. function _taxonomy_post_update_make_taxonomy_term_revisionable__fix_default_langcode(array &$sandbox) {
  253. if (!empty($sandbox['data_fix']['default_langcode']['finished'])) {
  254. return TRUE;
  255. }
  256. $storage = \Drupal::entityTypeManager()->getStorage('taxonomy_term');
  257. if (!$storage instanceof TermStorage) {
  258. $sandbox['data_fix']['default_langcode']['finished'] = TRUE;
  259. return TRUE;
  260. }
  261. elseif (!isset($sandbox['data_fix']['default_langcode'])) {
  262. $sandbox['data_fix']['default_langcode'] = [
  263. 'last_id' => 0,
  264. 'processed' => 0,
  265. ];
  266. }
  267. $database = \Drupal::database();
  268. $data_table_name = 'taxonomy_term_field_data';
  269. $last_id = $sandbox['data_fix']['default_langcode']['last_id'];
  270. $limit = Settings::get('update_sql_batch_size', 200);
  271. // Detect records in the data table matching the base table language, but
  272. // having the "default_langcode" flag set to with 0, which is not supported.
  273. $query = $database->select($data_table_name, 'd');
  274. $query->leftJoin('taxonomy_term_data', 'b', 'd.tid = b.tid AND d.langcode = b.langcode AND d.default_langcode = 0');
  275. $result = $query->fields('d', ['tid', 'langcode'])
  276. ->condition('d.tid', $last_id, '>')
  277. ->isNotNull('b.tid')
  278. ->orderBy('d.tid')
  279. ->range(0, $limit)
  280. ->execute();
  281. foreach ($result as $record) {
  282. $sandbox['data_fix']['default_langcode']['last_id'] = $record->tid;
  283. // We need to exclude any term already having also a data table record with
  284. // the "default_langcode" flag set to 1, because this is a data integrity
  285. // issue that cannot be fixed automatically. However the latter will not
  286. // make the update fail.
  287. $has_default_langcode = (bool) $database->select($data_table_name, 'd')
  288. ->fields('d', ['tid'])
  289. ->condition('d.tid', $record->tid)
  290. ->condition('d.default_langcode', 1)
  291. ->range(0, 1)
  292. ->execute()
  293. ->fetchField();
  294. if ($has_default_langcode) {
  295. continue;
  296. }
  297. $database->update($data_table_name)
  298. ->fields(['default_langcode' => 1])
  299. ->condition('tid', $record->tid)
  300. ->condition('langcode', $record->langcode)
  301. ->execute();
  302. $sandbox['data_fix']['default_langcode']['processed']++;
  303. \Drupal::logger('update')
  304. ->warning('The term with ID @id had data integrity issues and was restored.', ['@id' => $record->tid]);
  305. }
  306. $finished = $sandbox['data_fix']['default_langcode']['last_id'] === $last_id;
  307. $sandbox['data_fix']['default_langcode']['finished'] = $finished;
  308. return $finished;
  309. }
  310. /**
  311. * Add status with settings to all form displays for taxonomy entities.
  312. */
  313. function taxonomy_post_update_configure_status_field_widget(&$sandbox = NULL) {
  314. \Drupal::classResolver(ConfigEntityUpdater::class)->update($sandbox, 'entity_form_display', function (EntityDisplayInterface $entity_form_display) {
  315. // Only update taxonomy term entity form displays with no existing options
  316. // for the status field.
  317. if ($entity_form_display->getTargetEntityTypeId() == 'taxonomy_term' && empty($entity_form_display->getComponent('status'))) {
  318. $entity_form_display->setComponent('status', [
  319. 'type' => 'boolean_checkbox',
  320. 'settings' => [
  321. 'display_label' => TRUE,
  322. ],
  323. ]);
  324. return TRUE;
  325. }
  326. return FALSE;
  327. });
  328. }