media.install 41.3 KB
Newer Older
1
<?php
2

3
/**
4 5 6 7
 * @file
 * Install, update and uninstall functions for the Media module.
 */

8 9 10 11
/**
 * Implements hook_install().
 */
function media_install() {
12 13
  // Make sure that we set the icon base directory variable if it is not
  // already set.
14
  $base = variable_get('media_icon_base_directory', NULL);
15
  if (!isset($base)) {
16
    $default_base = 'public://media-icons';
17
    variable_set('media_icon_base_directory', $default_base);
18
  }
19 20 21 22 23 24
  try {
    _media_install_copy_icons();
  }
  catch (Exception $e) {
    watchdog_exception('media', $e);
  }
25 26 27 28 29 30
}

/**
 * Copy the media file icons to files directory for use with image styles.
 */
function _media_install_copy_icons() {
31
  $destination = variable_get('media_icon_base_directory', 'public://media-icons') . '/' . variable_get('media_icon_set', 'default');
32
  if (!file_prepare_directory($destination, FILE_MODIFY_PERMISSIONS || FILE_CREATE_DIRECTORY)) {
33
    throw new Exception("Unable to create directory $destination.");
34
  }
35
  // @todo If we ever add another default icon set, this should copy all images from one directory up.
36
  $source = drupal_get_path('module', 'media') . '/images/icons/' . variable_get('media_icon_set', 'default');
37 38
  $files = file_scan_directory($source, '/.*\.(png|jpg)$/');
  foreach ($files as $file) {
39 40 41 42
    $result = file_unmanaged_copy($file->uri, $destination, FILE_EXISTS_REPLACE);
    if (!$result) {
      throw new Exception("Unable to copy {$file->uri} to $destination.");
    }
43
  }
44 45
}

46
/**
Dave Reid's avatar
Dave Reid committed
47
 * Implements hook_uninstall().
48 49
 */
function media_uninstall() {
50
  // Remove variables.
51
  variable_del('media_dialog_theme');
52 53 54
  variable_del('media_icon_base_directory');
  variable_del('media_icon_set');
  variable_del('media_show_deprecated_view_modes');
55 56 57 58 59 60 61 62 63 64 65 66 67

  // Dialog options.
  variable_del('media_dialogclass');
  variable_del('media_modal');
  variable_del('media_draggable');
  variable_del('media_resizable');
  variable_del('media_minwidth');
  variable_del('media_width');
  variable_del('media_height');
  variable_del('media_position');
  variable_del('media_zindex');
  variable_del('media_backgroundcolor');
  variable_del('media_opacity');
68 69
  // bulk edit option
  variable_del('media_bulk_upload_edit');
70 71
}

72 73 74 75
/**
 * Implements hook_update_dependencies().
 */
function media_update_dependencies() {
76 77 78 79 80 81
  // media_update_7200() needs to convert old 'media' permissions to new 'file'
  // permissions, so it must run before file_entity_7208 which updates existing
  // 'file' permissions to be split per file type.
  $dependencies['file_entity'][7208] = array(
    'media' => 7200,
  );
82 83 84
  // This update function requires field_update_7002() to run before it since
  // the field_bundle_settings variable has been split into separate variables
  // per entity type and bundle.
85
  $dependencies['media'][7016] = array(
86
    'field' => 7002,
87
    'rules' => 7205,
88
  );
89
  // Those updates require {file_type} table created.
90 91
  $dependencies['media'][7200] = array(
    'file_entity' => 7207,
92
  );
93 94 95 96
  // Require {file_type}.mimetypes column before updating them.
  $dependencies['media'][7208] = array(
    'file_entity' => 7210,
  );
97 98 99
  $dependencies['media'][7212] = array(
    'file_entity' => 7210,
  );
100 101 102
  return $dependencies;
}

103 104 105 106 107 108
/**
 * Implements hook_requirements().
 */
function media_requirements($phase) {
  $t = get_t();
  // Make sure that file_entity module is 2.x version.
109
  // We can't add this check in .info file because drupal.org testbot can't
110 111 112
  // handle it. See #1734648.
  $requirements = array();

113
  if ($phase == 'update') {
114
    $info = system_get_info('module', 'file_entity');
115 116 117 118 119 120 121 122 123 124 125 126 127 128
    $file_entity_installed_date = $info['datestamp'];
    $file_entity_version = $info['version'];
    $file_entity_minimum_date = 1495439635;
    // Time of 2017-05-22 07:53:55 is most recent commit in 7.x-2.0.
    if ($file_entity_installed_date < $file_entity_minimum_date) {
      $description = $t('Media 2.10 or newer requires <a href="@url">File entity 2.0 or newer (2.4 or higher recommended)</a>. Please download the correct version and make sure you have deleted the file_entity folder inside the media module directory.', array('@url' => 'http://drupal.org/project/file_entity'));
      $requirements['file_entity']['description'] = $description;
      $requirements['file_entity']['severity'] = REQUIREMENT_ERROR;
      $requirements['file_entity']['value'] = $file_entity_version;
      $requirements['file_entity']['title'] = $t('Fieldable Files (file_entity) module 7.x-2.0 or newer is required by Media');
      drupal_set_message($description, 'error', TRUE);
    }
    if (strpos($info['version'], '7.x-2') === FALSE &&
      strpos($info['version'], '7.x-3') === FALSE) {
129
      $requirements['file_entity'] = array(
130
        'title' => $t('File entity 2.x or 3.x required.'),
131 132
        'value' => $t('Wrong version'),
        'severity' => REQUIREMENT_ERROR,
133
        'description' => $t('Media requires <a href="@url">File entity 2.x or 3.x</a>. Please download the correct version and make sure you have deleted the file_entity folder inside the media module directory.', array('@url' => 'http://drupal.org/project/file_entity')),
134 135 136 137
      );
    }
  }

138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153
  if (module_exists('entity_translation')) {
    if ($phase == 'update' || $phase == 'install' || $phase == 'runtime' ) {
      $entity_translation_info = system_get_info('module', 'entity_translation');
      $et_installed_version = $entity_translation_info['version'];
      $et_installed_datestamp = $entity_translation_info['datestamp'];
      $march3rd_entity_translation_timestamp = 1488530885;
      if (!isset($entity_translation_info['version']) || !isset($entity_translation_info['datestamp'])) {
        $et_installed_datestamp = 1488530884;
      }

      if ($et_installed_datestamp < $march3rd_entity_translation_timestamp) {
        $description = $t('Your entity_translation installation version: %version is too old. media requires entity_translation at least beta6 from march 3 2017 or newer.  Your choice is to either upgrade entity_translation or to disable it.', array('%version' => $et_installed_version));
        $requirements['entity_translation']['description'] = $description;
        $requirements['entity_translation']['severity'] = REQUIREMENT_ERROR;
        $requirements['entity_translation']['value'] = $et_installed_version;
        $requirements['entity_translation']['title'] = $t('Entity translation (when installed) with Media');
154
        drupal_set_message($description, 'error', TRUE);
155 156 157
      }
    }
  }
158 159 160
  return $requirements;
}

161
/**
162
 * Deprecated update function.
163
 */
Dave Reid's avatar
Dave Reid committed
164
function media_update_7000() {
165 166 167
}

/**
168
 * Deprecated update function.
169 170 171 172 173
 */
function media_update_7001() {
}

/**
Dave Reid's avatar
Dave Reid committed
174
 * Create the media_type table from the media_types variable.
175 176
 */
function media_update_7002() {
177 178 179 180
  if (db_table_exists('media_type')) {
    return;
  }

Dave Reid's avatar
Dave Reid committed
181
  $schema['media_type'] = array(
182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228
    'description' => 'Stores the settings for media types.',
    'fields' => array(
      'name' => array(
        'description' => 'The machine name of the media type.',
        'type' => 'varchar',
        'length' => 255,
        'not null' => TRUE,
        'default' => '',
      ),
      'label' => array(
        'description' => 'The label of the media type.',
        'type' => 'varchar',
        'length' => 255,
        'not null' => TRUE,
        'default' => '',
      ),
      'base' => array(
        'description' => 'If this is a base type (i.e. cannot be deleted)',
        'type' => 'int',
        'not null' => TRUE,
        'default' => 0,
        'size' => 'tiny',
      ),
      'weight' => array(
        'description' => 'Weight of media type. Determines which one wins when claiming a piece of media (first wins)',
        'type' => 'int',
        'not null' => TRUE,
        'default' => 0,
        'size' => 'normal',
      ),
      'type_callback' => array(
        'description' => 'Callback to determine if provided media is of this type.',
        'type' => 'varchar',
        'length' => 255,
        'not null' => FALSE,
        'default' => '',
      ),
      'type_callback_args' => array(
        'type' => 'text',
        'not null' => FALSE,
        'size' => 'big',
        'serialize' => TRUE,
        'description' => 'A serialized array of name value pairs that will be passed to the callback function',
      ),
    ),
    'primary key' => array('name'),
  );
Dave Reid's avatar
Dave Reid committed
229 230 231
  db_create_table('media_type', $schema['media_type']);

  drupal_load('module', 'media');
232
  $old_types = variable_get('media_types', array());
Dave Reid's avatar
Dave Reid committed
233
  foreach ($old_types as $type) {
234
    // Was an error in the original creation.
Dave Reid's avatar
Dave Reid committed
235 236 237 238 239
    if (isset($type->callbacks)) {
      unset($type->callbacks);
    }
    $type->name = $type->machine_name;
    unset($type->machine_name);
240 241 242 243
    db_merge('media_type')
      ->key(array('name' => $type->name))
      ->fields((array) $type)
      ->execute();
Dave Reid's avatar
Dave Reid committed
244 245
  }
  variable_del('media_types');
246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261
}

/**
 * We now prefix media namespaced variables with media__, so fix old variables.
 */
function media_update_7003() {
  drupal_load('module', 'media');
  foreach (media_variable_default() as $variable => $value) {
    if (($test = variable_get('media_' . $variable, TRUE)) == variable_get('media_' . $variable, FALSE)) {
      media_variable_set($variable, $test);
      variable_del('media_' . $variable);
    }
  }
}

/**
Dave Reid's avatar
Dave Reid committed
262
 * Empty update function to trigger a menu rebuild.
263 264 265 266 267
 */
function media_update_7004() {
}

/**
Dave Reid's avatar
Dave Reid committed
268
 * Deprecated update function.
269 270 271
 */
function media_update_7005() {
}
272 273

/**
Dave Reid's avatar
Dave Reid committed
274
 * Rename the file table to file_managed in case head2head was used.
275 276
 */
function media_update_7006() {
Dave Reid's avatar
Dave Reid committed
277
  if (db_table_exists('file') && !db_table_exists('file_managed')) {
278 279
    db_rename_table('file', 'file_managed');
  }
280
}
281 282

/**
283
 * Deprecated update function.
284 285 286
 */
function media_update_7007() {
}
287 288

/**
Dave Reid's avatar
Dave Reid committed
289
 * Empty function.
290 291 292
 */
function media_update_7008() {
}
293 294

/**
295
 * Deprecated update function.
296 297 298 299 300
 */
function media_update_7009() {
}

/**
301
 * Deprecated update function.
302 303 304
 */
function media_update_7010() {
}
305 306

/**
Dave Reid's avatar
Dave Reid committed
307
 * Empty update function.
308 309
 */
function media_update_7011() {
310 311 312
}

/**
313
 * Empty update function.
314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334
 */
function media_update_7012() {
}

/**
 * Work around a core bug where text format cacheability is not updated.
 *
 * @see http://drupal.org/node/993230
 */
function media_update_7013() {
  $formats = filter_formats();
  foreach ($formats as $format) {
    $format->filters = filter_list_format($format->format);
    // filter_format_save() expects filters to be an array, however
    // filter_list_format() gives us objects.
    foreach ($format->filters as $key => $value) {
      $format->filters[$key] = (array) $value;
    }
    filter_format_save($format);
  }
}
335 336

/**
Dave Reid's avatar
Dave Reid committed
337
 * Rename the media__dialog_get_theme_name variable to media__dialog_theme.
338 339 340 341 342 343
 */
function media_update_7014() {
  if ($old_value = variable_get('media__dialog_get_theme_name')) {
    variable_del('media__dialog_get_theme_name');
    variable_set('media__dialog_theme', $old_value);
  }
344 345 346
}

/**
Dave Reid's avatar
Dave Reid committed
347
 * Empty update function to trigger a registry rebuild.
348 349
 */
function media_update_7015() {
350 351 352
}

/**
Dave Reid's avatar
Dave Reid committed
353
 * Convert Media entities to File entities.
354 355 356 357 358 359 360
 *
 * This update function requires field_update_7002() to run before it since
 * the field_bundle_settings variable has been split into separate variables
 * per entity type and bundle.
 *
 * @see http://drupal.org/node/1418708
 * @see http://drupal.org/node/1211008
361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379
 */
function media_update_7016() {
  // Allow File Entity module to take over the {file_managed}.type field. It
  // will create new indexes as it needs to, but it doesn't know about old ones,
  // so delete them.
  if (db_index_exists('file_managed', 'file_type')) {
    db_drop_index('file_managed', 'file_type');
  }
  module_enable(array('file_entity'));

  // Move all field instances from Media entity to File entity.
  $instances = field_read_instances(array('entity_type' => 'media'), array('include_inactive' => TRUE, 'include_deleted' => TRUE));
  foreach ($instances as $instance) {
    // Skip the old self-referencing file field. It will be deleted later in
    // this function.
    if ($instance['field_name'] === 'file') {
      continue;
    }

Dave Reid's avatar
Dave Reid committed
380
    // @todo Convert this to use _update_7000_field_read_fields()
381 382 383 384 385 386 387 388
    $fields = field_read_fields(array('id' => $instance['field_id']), array('include_inactive' => TRUE, 'include_deleted' => TRUE));
    $field = $fields[$instance['field_id']];

    // There is no API for updating the entity_type foreign key within field
    // data storage. We can do a direct db_update() for when the default SQL
    // storage back-end is being used, but must skip updating fields that use a
    // different storage type.
    if ($field['storage']['type'] !== 'field_sql_storage' || !module_exists('field_sql_storage') || !$field['storage']['active']) {
Dave Reid's avatar
Dave Reid committed
389 390 391 392
      $messages[] = t('Cannot update field %id (%field_name) because it does not use the field_sql_storage storage type.', array(
        '%id' => $field['id'],
        '%field_name' => $field['field_name'],
      ));
393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422
      continue;
    }

    // Update the data tables.
    $table_name = _field_sql_storage_tablename($field);
    $revision_name = _field_sql_storage_revision_tablename($field);
    db_update($table_name)
      ->fields(array('entity_type' => 'file'))
      ->condition('entity_type', 'media')
      ->condition('bundle', $instance['bundle'])
      ->execute();
    db_update($revision_name)
      ->fields(array('entity_type' => 'file'))
      ->condition('entity_type', 'media')
      ->condition('bundle', $instance['bundle'])
      ->execute();

    // Once all the data has been updated, update the {field_config_instance}
    // record.
    db_update('field_config_instance')
      ->fields(array('entity_type' => 'file'))
      ->condition('id', $instance['id'])
      ->execute();
  }

  // Update the field_bundle_settings configuration variable: move media bundle
  // settings to file bundles, and move settings of the old self-referencing
  // file field to the new file pseudo-field.
  foreach ($instances as $instance) {
    if ($instance['field_name'] === 'file' && !$instance['deleted']) {
423 424 425
      $file_settings = field_bundle_settings('file', $instance['bundle']);
      $media_settings = field_bundle_settings('media', $instance['bundle']);
      $file_settings = array_merge($file_settings, $media_settings);
426
      if (isset($instance['widget']['weight'])) {
427
        $file_settings['extra_fields']['form']['file']['weight'] = $instance['widget']['weight'];
428 429 430 431
      }
      if (isset($instance['display'])) {
        foreach ($instance['display'] as $view_mode => $display) {
          if (isset($display['weight'])) {
432
            $file_settings['extra_fields']['display']['file'][$view_mode]['weight'] = $display['weight'];
433 434
          }
          if (isset($display['type'])) {
435
            $file_settings['extra_fields']['display']['file'][$view_mode]['visible'] = ($display['type'] != 'hidden');
436 437 438
          }
        }
      }
439
      field_bundle_settings('file', $instance['bundle'], $file_settings);
440 441
    }
  }
442 443 444 445
  // Delete old media bundle settings.
  db_delete('variable')
    ->condition('name', db_like('field_bundle_settings_media__') . '%', 'LIKE')
    ->execute();
446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476

  // Copy field formatter settings of old self-referencing file field to file
  // pseudo-field formatter settings.
  $file_displays = variable_get('file_displays', array());
  foreach ($instances as $instance) {
    if ($instance['field_name'] === 'file' && !$instance['deleted']) {
      if (isset($instance['display'])) {
        foreach ($instance['display'] as $view_mode => $display) {
          if (isset($display['type']) && $display['type'] != 'hidden') {
            $file_formatter = 'file_field_' . $display['type'];
            $file_displays[$instance['bundle']][$view_mode][$file_formatter]['status'] = TRUE;
            if (isset($display['settings'])) {
              $file_displays[$instance['bundle']][$view_mode][$file_formatter]['settings'] = $display['settings'];
            }
          }
        }
      }
    }
  }
  variable_set('file_displays', $file_displays);

  // Delete the old self-referencing file field instances. If all instances are
  // deleted, field_delete_instance() will delete the field too.
  foreach ($instances as $instance) {
    if ($instance['field_name'] === 'file' && !$instance['deleted']) {
      field_delete_instance($instance);
    }
  }

  field_cache_clear();
}
477 478

/**
479 480
 * Move file display configuration.
 *
481 482 483 484 485 486 487 488 489
 * Move file display configurations from the 'file_displays' variable to the
 * {file_display} table.
 */
function media_update_7017() {
  // If the {file_display} table doesn't exist, then the File Entity module's
  // update functions will automatically take care of migrating the
  // configurations. However, if file_entity_update_7001() has already run
  // prior to media_update_7016(), run it again in order to capture those
  // configurations too.
490
  if (db_table_exists('file_display') && function_exists('file_entity_update_7001')) {
491
    module_load_include('install', 'file_entity', 'file_entity');
492 493 494
    file_entity_update_7001();
  }
}
495 496

/**
Dave Reid's avatar
Dave Reid committed
497
 * Empty update function to trigger a menu rebuild.
498 499 500
 */
function media_update_7018() {
}
501 502

/**
503 504 505 506
 * Update old view mode formaters.
 *
 * Update old per-view-mode media field formatters to the generic media
 * formatter with a setting.
507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527
 */
function media_update_7019() {
  $instances = array();
  $fields = field_read_fields(array('type' => 'media'), array('include_inactive' => TRUE));
  foreach ($fields as $field) {
    $instances = array_merge($instances, field_read_instances(array('field_id' => $field['id']), array('include_inactive' => TRUE)));
  }
  foreach ($instances as $instance) {
    $update_instance = FALSE;
    foreach ($instance['display'] as $view_mode => $display) {
      if (in_array($display['type'], array('media_link', 'media_preview', 'media_small', 'media_large', 'media_original'))) {
        $update_instance = TRUE;
        $instance['display'][$view_mode]['type'] = 'media';
        $instance['display'][$view_mode]['settings'] = array('file_view_mode' => $display['type']);
      }
    }
    if ($update_instance) {
      field_update_instance($instance);
    }
  }
}
528 529 530 531 532 533 534 535 536

/**
 * Delete the wysiwyg_allowed_types variable if it is the same as default.
 */
function media_update_7020() {
  if (variable_get('media__wysiwyg_allowed_types') == array('image', 'video')) {
    variable_del('media__wysiwyg_allowed_types');
  }
}
537

538 539 540 541 542 543 544
/**
 * Rerun media_update_7002() due to a typo that would prevent table creation.
 */
function media_update_7021() {
  media_update_7002();
}

545 546 547 548 549
/**
 * Replace 'view media' perm from all users having the role with 'view file'.
 */
function media_update_7200() {
  $perms = user_permission_get_modules();
550
  if (!isset($perms['view files'])) {
551 552 553 554 555 556
    throw new DrupalUpdateException('The File Entity module needs to be upgraded before continuing.');
  }
  else {
    $roles = user_roles(FALSE, 'view media');
    $permissions = array(
      'view media' => FALSE,
557
      'view files' => TRUE,
558 559 560 561 562 563 564
    );
    foreach ($roles as $rid => $role) {
      user_role_change_permissions($rid, $permissions);
    }
    $roles = user_roles(FALSE, 'edit media');
    $permissions = array(
      'edit media' => FALSE,
565
      'edit any files' => TRUE,
566
    );
567 568 569 570 571 572 573
    if (function_exists('file_entity_list_permissions')) {
      unset($permissions['edit any files']);

      foreach (file_entity_permissions_get_configured_types() as $type) {
        $permissions += file_entity_list_permissions($type);
      }
    }
574 575 576 577 578 579 580 581 582 583 584 585 586
    foreach ($roles as $rid => $role) {
      user_role_change_permissions($rid, $permissions);
    }
    $roles = user_roles(FALSE, 'administer media');
    $permissions = array(
      'administer media' => FALSE,
      'administer files' => TRUE,
    );
    foreach ($roles as $rid => $role) {
      user_role_change_permissions($rid, $permissions);
    }
  }
}
587 588

/**
589 590 591 592
 * Handle existing media fields.
 *
 * Enable the new Media Field module if this site uses "media" fields. File
 * fields are now preferred for storing media.
593 594 595 596 597 598 599 600 601 602 603
 */
function media_update_7201() {
  $fields = field_info_fields();
  foreach ($fields as $field) {
    if ($field['type'] == 'media') {
      // This update function may run even if Media is not enabled. Don't enable
      // Media Field if its dependencies aren't already enabled.
      module_enable(array('mediafield'), FALSE);

      // Update entries in file_usage so that they are associated with Media
      // Field rather than Media.
604 605
      // @TODO This update function may conflict with
      // http://drupal.org/node/1268116
606 607 608 609 610 611 612 613 614 615
      db_update('file_usage')
        ->condition('module', 'media')
        ->fields(array('module' => 'mediafield'))
        ->execute();

      return t('The "Media" field type has been moved to the new "Media Field" module. This site uses media fields, so the Media Field module has been enabled.');
    }
  }
  return t('The "Media" field type has been moved to the new "Media Field" module. File fields can be used to store media.');
}
616 617 618 619 620 621

/**
 * Enable the Views module if it is not already enabled.
 */
function media_update_7202() {
  module_enable(array('views'));
622
  if (!module_exists('views')) {
623
    throw new DrupalUpdateException('The <a href="https://drupal.org/project/views">Views module</a> must be downloaded and available for Media updates to proceed.');
624
  }
625
}
626 627 628 629 630 631 632

/**
 * Empty update function to trigger cache clear.
 */
function media_update_7203() {
  // Do nothing.
}
633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791

/**
 * Update old Media view modes to the new File Entity ones.
 */
function media_update_7204() {
  $view_mode_updates = array(
    'media_preview' => 'preview',
    'media_small' => 'teaser',
    'media_large' => 'full',
  );

  // Update the media__wysiwyg_default_view_mode variable.
  $wysiwyg_default_view_mode = variable_get('media__wysiwyg_default_view_mode');
  if (isset($wysiwyg_default_view_mode) && isset($view_mode_updates[$wysiwyg_default_view_mode])) {
    $wysiwyg_default_view_mode = $view_mode_updates[$wysiwyg_default_view_mode];
    variable_set('media__wysiwyg_default_view_mode', $wysiwyg_default_view_mode);
  }

  // Update view mode references in the 'field_bundle_settings' variable.
  $field_bundle_settings = variable_get('field_bundle_settings');
  if (!empty($field_bundle_settings['file'])) {
    foreach ($field_bundle_settings['file'] as $file_type => $info) {
      // Per-bundle information about the view modes.
      foreach ($view_mode_updates as $old_view_mode => $new_view_mode) {
        if (isset($info['view_modes'][$old_view_mode])) {
          $field_bundle_settings['file'][$file_type]['view_modes'][$new_view_mode] = $info['view_modes'][$old_view_mode];
          unset($field_bundle_settings['file'][$file_type]['view_modes'][$old_view_mode]);
        }
        // The File Entity module defaults to not use custom settings for the
        // new view modes, but the Media module used to default to using custom
        // settings, so if this variable is not defined, use the prior default.
        if (!isset($field_bundle_settings['file'][$file_type]['view_modes'][$new_view_mode]['custom_settings'])) {
          $field_bundle_settings['file'][$file_type]['view_modes'][$new_view_mode]['custom_settings'] = TRUE;
        }
      }

      // Settings for the "extra fields" configured on the Manage Display page.
      if (!empty($info['extra_fields']['display'])) {
        foreach ($info['extra_fields']['display'] as $extra_field_name => $extra_field_info) {
          foreach ($view_mode_updates as $old_view_mode => $new_view_mode) {
            if (isset($extra_field_info[$old_view_mode])) {
              $field_bundle_settings['file'][$file_type]['extra_fields']['display'][$extra_field_name][$new_view_mode] = $extra_field_info[$old_view_mode];
              unset($field_bundle_settings['file'][$file_type]['extra_fields']['display'][$extra_field_name][$old_view_mode]);
            }
          }
        }
      }
    }
  }
  variable_set('field_bundle_settings', $field_bundle_settings);

  // Move settings for fields attached to files from the old view modes to the
  // new ones.
  $instances = field_read_instances(array('entity_type' => 'file'));
  foreach ($instances as $instance) {
    $updated = FALSE;
    foreach ($view_mode_updates as $old_view_mode => $new_view_mode) {
      if (isset($instance['display'][$old_view_mode])) {
        $instance['display'][$new_view_mode] = $instance['display'][$old_view_mode];
        unset($instance['display'][$old_view_mode]);
        $updated = TRUE;
      }
    }
    if ($updated) {
      field_update_instance($instance);
    }
  }

  // Move "Manage file display" settings from old view modes to new ones.
  $file_display_names = db_query('SELECT name FROM {file_display}')->fetchCol();
  foreach ($file_display_names as $old_file_display_name) {
    list($file_type, $view_mode, $formatter) = explode('__', $old_file_display_name, 3);
    if (isset($view_mode_updates[$view_mode])) {
      $view_mode = $view_mode_updates[$view_mode];
      $new_file_display_name = implode('__', array($file_type, $view_mode, $formatter));
      db_delete('file_display')->condition('name', $new_file_display_name)->execute();
      db_update('file_display')->fields(array('name' => $new_file_display_name))->condition('name', $old_file_display_name)->execute();
    }
  }

  // Update file/image/media fields that use a formatter that reference an old
  // file view modes to reference the new ones.
  foreach (field_read_instances() as $instance) {
    if (!empty($instance['display'])) {
      $updated = FALSE;
      foreach ($instance['display'] as $instance_view_mode => $display) {
        if (isset($display['settings']['file_view_mode']) && isset($view_mode_updates[$display['settings']['file_view_mode']])) {
          $instance['display'][$instance_view_mode]['settings']['file_view_mode'] = $view_mode_updates[$display['settings']['file_view_mode']];
          $updated = TRUE;
        }
      }
      if ($updated) {
        field_update_instance($instance);
      }
    }
  }

  // Update formatter settings that reference the old view modes within saved
  // Views.
  if (db_table_exists('views_display')) {
    $result = db_select('views_display', 'v')->fields('v', array('vid', 'id', 'display_options'))->execute();
    foreach ($result as $record) {
      if (!empty($record->display_options)) {
        $display_options = unserialize($record->display_options);
        if (_media_update_7204_update_views_display_options($display_options, $view_mode_updates)) {
          db_update('views_display')
            ->fields(array('display_options' => serialize($display_options)))
            ->condition('vid', $record->vid)
            ->condition('id', $record->id)
            ->execute();
        }
      }
    }
  }

  // Update formatter settings that reference the old view modes within unsaved
  // Views in the CTools object cache. Objects in the CTools cache are instances
  // of classes, so the Views module must be enabled to unserialize it
  // correctly.
  if (db_table_exists('ctools_object_cache') && module_exists('views')) {
    $result = db_select('ctools_object_cache', 'c')->fields('c', array('sid', 'name', 'obj', 'data'))->condition('obj', 'view')->execute();
    foreach ($result as $record) {
      $view = unserialize($record->data);
      if (!empty($view->display)) {
        $updated = FALSE;
        foreach ($view->display as $display_name => $display) {
          if (!empty($display->display_options) && _media_update_7204_update_views_display_options($display->display_options, $view_mode_updates)) {
            $updated = TRUE;
          }
        }
        if ($updated) {
          db_update('ctools_object_cache')
            ->fields(array('data' => serialize($view)))
            ->condition('sid', $record->sid)
            ->condition('name', $record->name)
            ->condition('obj', $record->obj)
            ->execute();
        }
      }
    }
  }

  // Clear caches that might contain stale Views displays.
  if (module_exists('views')) {
    cache_clear_all('*', 'cache_views', TRUE);
    cache_clear_all('*', 'cache_views_data', TRUE);
  }
  if (module_exists('block')) {
    cache_clear_all('*', 'cache_block', TRUE);
  }
  cache_clear_all('*', 'cache_page', TRUE);

  // We still have the old media_link and media_original view modes that must be
  // supported for now.
  // @TODO: Make this apply only to updates from Media 1.x.
  // @see media_entity_info_alter()
  variable_set('media__show_deprecated_view_modes', TRUE);
}

792 793 794 795
/**
 * Drop the unused {media_list_type} table.
 */
function media_update_7205() {
796 797 798 799
  if (db_table_exists('media_list_type')) {
    db_drop_table('media_list_type');
    return t('Dropped the unused {media_list_type} table.');
  }
800 801
}

802 803 804 805 806 807 808 809 810 811 812 813 814 815
/**
 * Move default file display configurations to the database.
 */
function media_update_7206() {
  module_load_include('inc', 'file_entity', 'file_entity.file_api');
  module_load_include('inc', 'ctools', 'includes/export');
  $default_image_styles = array(
    'preview' => 'square_thumbnail',
    'teaser' => 'medium',
    'full' => 'large',
  );

  // Only needed by sites that updated from Media 1.x.
  // @see media_entity_info_alter()
816
  if (variable_get('media__show_deprecated_view_modes')) {
817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841
    $default_image_styles['media_original'] = '';
  }

  // Clear out the ctools cache so that the old default implementations
  // are removed.
  ctools_export_load_object_reset('file_display');
  foreach ($default_image_styles as $view_mode => $image_style) {
    $existing_displays = file_displays_load('image', $view_mode, TRUE);
    // Only insert default config into the database if no existing
    // configuration is found.
    if (!isset($existing_displays['file_image'])) {
      $display_name = 'image__' . $view_mode . '__file_image';
      $display = array(
        'api_version' => 1,
        'name' => $display_name,
        'status' => 1,
        'weight' => 5,
        'settings' => array('image_style' => $image_style),
        'export_type' => NULL,
      );
      file_display_save((object) $display);
    }
  }
}

842
/**
843 844 845 846
 * Trigger cache clear.
 *
 * Empty update function to trigger cache clear after changing access callbacks
 * to file_entity_access.
847 848 849 850 851
 */
function media_update_7207() {
  // Do nothing.
}

852
/**
853
 * Drop the media_types table and migrate files to file_entity types.
854 855
 */
function media_update_7208() {
856 857 858
  // Reset static cache to ensure our new file types are recognized
  drupal_static_reset('ctools_export_load_object_table_exists');

859
  if (!db_table_exists('media_type')) {
860 861 862
    // No types to migrate.
    return;
  }
863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879
  // @see http://drupal.org/node/1292382
  if (!function_exists('file_type_get_enabled_types')) {
    throw new DrupalUpdateException('The File Entity module needs to be upgraded before continuing.');
  }
  else {
    $existing_types = db_select('media_type', 'mt')
      ->orderBy('weight')
      ->fields('mt')
      ->execute()
      // Will key by the name field.
      ->fetchAllAssoc('name');
    foreach ($existing_types as &$type) {
      $type->type_callback_args = unserialize($type->type_callback_args);
    }

    include_once DRUPAL_ROOT . '/includes/file.mimetypes.inc';
    $mapping = file_mimetype_mapping();
880 881
    // We do not migrate this type, since there is no way to handle its weight.
    unset($existing_types['default']);
882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904
    foreach ($existing_types as $type) {
      $extensions = isset($type->type_callback_args['extensions']) ? $type->type_callback_args['extensions'] : array();
      $mimetypes = isset($type->type_callback_args['mimetypes']) ? $type->type_callback_args['mimetypes'] : array();
      // Add mimetypes by extensions.
      foreach ($extensions as $extension) {
        if (isset($mapping['extensions'][$extension])) {
          $type->mimetypes[] = $mapping['mimetypes'][$mapping['extensions'][$extension]];
        }
      }
      // Add rest mimetypes.
      foreach ($mimetypes as $mimetype) {
        // Mimetype is a regex pattern.
        foreach ($mapping['mimetypes'] as $mapping_mimetype) {
          if (preg_match($mimetype, $mapping_mimetype) && !in_array($mapping_mimetype, $type->mimetypes)) {
            $type->mimetypes[] = $mapping_mimetype;
          }
        }
      }
      $type->streams = isset($type->type_callback_args['streams']) ? $type->type_callback_args['streams'] : array();
      $type->type = $type->name;
      // Merge existing type with new ones.
      if ($new_type = file_type_load($type->name)) {
        $new_type->mimetypes = array_merge($type->mimetypes, $new_type->mimetypes);
905 906 907 908 909 910
        if (!empty($new_type->streams)) {
          $new_type->streams = array_merge($type->streams, $new_type->streams);
        }
        else{
          $new_type->streams = $type->streams;
        }
911
      }
912 913 914
      else {
        $new_type = $type;
      }
915 916 917 918 919 920 921
      file_type_save($new_type);
    }
    db_drop_table('media_type');

    // Special treatment for old media application type to new file_entity
    // document one. Add some more mimetypes to document.
    $document_type = file_type_load('document');
922 923 924
    if (!$document_type) {
      return;
    }
925
    foreach ($mapping['mimetypes'] as $mimetype) {
926 927 928 929 930 931 932 933 934 935
      $is_document = strpos($mimetype, 'document') !== FALSE || strpos($mimetype, 'application/vnd.ms-') !== FALSE;
      if ($is_document && !in_array($mimetype, $document_type->mimetypes)) {
        $document_type->mimetypes[] = $mimetype;
      }
    }
    file_type_save($document_type);
  }
}

/**
936 937
 * Enable the hidden media_migrate_file_types module to provide a UI to update
 * {file_managed}.type with the new file types provided by file_entity.
938 939
 */
function media_update_7209() {
940
  drupal_load('module', 'media_migrate_file_types');
941

942
  if (_media_migrate_file_types_get_migratable_file_types()) {
943
    module_enable(array('media_migrate_file_types'));
944
  }
945 946
}

947 948 949 950
/**
 * Delete deceprated media__type_icon_directory variable.
 */
function media_update_7210() {
951
  variable_del('media__type_icon_directory');
952 953
}

954
/**
955 956
 * Save a square_thumbnail image style in the database for legacy support if one
 * does not already exist.
957 958
 */
function media_update_7211() {
959 960 961
  $default_style = array(
    'name' => 'square_thumbnail'
  );
962

963 964
  // Clear the image cache to remove any old image styles that only exist in
  // code.
965
  cache_clear_all('image_styles', 'cache_image', TRUE);
966 967 968 969 970 971 972 973 974 975 976 977 978 979 980

  // Check if the square_thumbnail image style exists.
  // The style will only exist if the user has customized it, otherwise it would
  // have been removed by clearing the image style cache.
  $existing_style = image_style_load('square_thumbnail');

  // Save a square_thumbnail image style in the database for legacy support.
  // This is only necessary if a square_thumbnail image style doesn't already
  // exist.
  if (empty($existing_style)) {
    $style = image_style_save($default_style);

    $effect = array(
      'name' => 'image_scale_and_crop',
      'data' => array(
981 982
        'width' => 100,
        'height' => 100,
983 984 985 986
        'weight' => 0,
      ),
      'isid' => $style['isid'],
    );
987

988
    image_effect_save($effect);
989 990
  }

991
  return t('Saved a square_thumbnail image style in the database for legacy support if one did not already exist.');
992 993
}

994
/**
995
 * Utility function for update 7204. Updates display options within Views.
996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017
 */
function _media_update_7204_update_views_display_options(&$display_options, $view_mode_updates) {
  $updated = FALSE;

  // Update fields that use a formatter with a file_view_mode formatter setting.
  if (!empty($display_options['fields'])) {
    foreach ($display_options['fields'] as $field_name => $field_display) {
      if (isset($field_display['settings']['file_view_mode']) && isset($view_mode_updates[$field_display['settings']['file_view_mode']])) {
        $display_options['fields'][$field_name]['settings']['file_view_mode'] = $view_mode_updates[$field_display['settings']['file_view_mode']];
        $updated = TRUE;
      }
    }
  }

  // Update Views that display files directly using a row plugin with a view
  // mode setting.
  if (isset($display_options['row_plugin']) && $display_options['row_plugin'] === 'file' && isset($display_options['row_options']['view_mode']) && isset($view_mode_updates[$display_options['row_options']['view_mode']])) {
    $display_options['row_options']['view_mode'] = $view_mode_updates[$display_options['row_options']['view_mode']];
    $updated = TRUE;
  }
  return $updated;
}
1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040

/**
 * Re-create application file type for legacy reasons.
 */
function media_update_7212() {
  module_load_include('inc', 'file_entity', 'file_entity.file_api');
  if (!file_type_load('application')) {
    $application = (object) array(
      'api_version' => 1,
      'type' => 'application',
      'label' => t('Application'),
      'description' => t('Multipurpose type - kept to support older sites.'),
      'mimetypes' => array(),
      'streams' => array(
        'public',
      ),
    );

    file_type_save($application);
    $application = file_type_load('application');
    file_type_disable($application);
  }
}
1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051

/**
 * Remove the obsolete file_extensions variable.
 */
function media_update_7213() {
  $media_file_extensions = explode(' ', variable_get('media__file_extensions'));
  $file_entity_file_extensions = explode(' ', variable_get('file_entity_default_allowed_extensions', 'jpg jpeg gif png txt doc docx xls xlsx pdf ppt pptx pps ppsx odt ods odp mp3 mov mp4 m4a m4v mpeg avi ogg oga ogv weba webp webm'));

  // Preserve any custom file extensions.
  if (array_diff($media_file_extensions, $file_entity_file_extensions)) {
    $combined_file_extensions = array_unique(array_merge($file_entity_file_extensions, $media_file_extensions));
1052
    variable_set('file_entity_default_allowed_extensions', implode(' ' , $combined_file_extensions));
1053 1054 1055 1056
  }

  variable_del('media__file_extensions');
}
1057 1058 1059 1060 1061 1062 1063 1064 1065

/**
 * Drop the legacy {media_filter_usage} table.
 */
function media_update_7214() {
  if (db_table_exists('media_filter_usage')) {
    db_drop_table('media_filter_usage');
  }
}
1066 1067

/**
1068
 * Skipped to run media_update_7217().
1069 1070
 */
function media_update_7216() {
1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089
  // Do nothing.
}

/**
 * Copy file type icons to public files directory.
 */
function media_update_7217() {
  // Remove any trailing slashes from the icon base directory variable.
  $dir = variable_get('media__icon_base_directory');
  if (!empty($dir)) {
    $dir = rtrim($dir, '/');
    variable_set('media__icon_base_directory', $dir);
  }

  try {
    _media_install_copy_icons();
  }
  catch (Exception $e) {
    throw new DrupalUpdateException($e->getMessage());
1090 1091
  }
}
1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102

/**
 * Drop the legacy {cache_media_xml} table.
 */
function media_update_7218() {
  if (db_table_exists('cache_media_xml')) {
    db_drop_table('cache_media_xml');
  }

  variable_del('media__xml_cache_expire');
}
1103 1104 1105 1106 1107 1108 1109 1110 1111

/**
 * Enable the Media WYSIWYG submodule.
 */
function media_update_7219() {
  if (module_exists('wysiwyg')) {
    module_enable(array('media_wysiwyg'));
  }
}
1112 1113 1114 1115 1116 1117 1118

/**
 * Delete the deprecated media__file_list_size variable.
 */
function media_update_7220() {
  variable_del('media__file_list_size');
}
1119 1120 1121 1122 1123 1124 1125 1126 1127

/**
 * Enable the Media Bulk Upload submodule.
 */
function media_update_7221() {
  if (module_exists('multiform') && module_exists('plupload')) {
    module_enable(array('media_bulk_upload'));
  }
}
1128 1129 1130 1131 1132 1133 1134

/**
 * Delete the deprecated media__display_types_migration_mess variable.
 */
function media_update_7222() {
  variable_del('media__display_types_migration_mess');
}
1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149

/**
 * Delete legacy variables.
 */
function media_update_7223() {
  variable_del('media__max_filesize');
  variable_del('media__debug');
  variable_del('media__xml_cache_expire');
  variable_del('media__show_file_type_rebuild_nag');
  variable_del('media__field_select_media_text');
  variable_del('media__field_remove_media_text');
  variable_del('media__browser_library_empty_message');
  variable_del('media__browser_pager_limit');
  variable_del('media__browser_viewtype_default');
}
1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170

/**
 * Rename variables, removing variable namespace.
 */
function media_update_7224() {
  // Create an array of variables sans 'media' prefix.
  $variables = array('wysiwyg_title', 'wysiwyg_icon_title', 'wysiwyg_default_view_mode', 'wysiwyg_upload_directory', 'wysiwyg_allowed_types', 'wysiwyg_allowed_attributes', 'wysiwyg_browser_plugins', 'dialog_theme', 'import_batch_size', 'fromurl_supported_schemes', 'icon_base_directory', 'icon_set', 'show_deprecated_view_modes');

  foreach ($variables as $variable) {
    // Find the value of the old variable.
    $value = variable_get('media__' . $variable);

    // Port the value of the variable if it was set.
    if (!is_null($value)) {
      variable_set('media_' . $variable, $value);
    }

    // Remove the old variable.
    variable_del('media__' . $variable);
  }
}
1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211

/**
 * Migrate variables to appropriate submodules.
 */
function media_update_7225() {
  $data = array(
    'media_wysiwyg' => array(
      'wysiwyg_title',
      'wysiwyg_icon_title',
      'wysiwyg_default_view_mode',
      'wysiwyg_upload_directory',
      'wysiwyg_allowed_types',
      'wysiwyg_allowed_attributes',
      'wysiwyg_browser_plugins',
    ),
    'media_internet' => array(
      'fromurl_supported_schemes',
    ),
    'media_bulk_upload' => array(
      'import_batch_size',
    ),
  );

  foreach ($data as $module => $variables) {
    foreach ($variables as $variable) {
      // Only port variables to submodules if the submodule exists.
      if (module_exists($module)) {
        // Find the value of the old variable.
        $value = variable_get('media_' . $variable);

        // Port the value of the variable if it was set.
        if (!is_null($value)) {
          variable_set($module . '_' . $variable, $value);
        }
      }

      // Remove the old variable.
      variable_del('media_' . $variable);
    }
  }
}
1212 1213

/**
1214
 * Grant existing user access to new media browser permission.
1215 1216 1217 1218 1219 1220 1221 1222
 */
function media_update_7226() {
  $roles = user_roles(FALSE, 'create files');

  foreach ($roles as $rid => $role) {
    user_role_grant_permissions($rid, array('access media browser'));
  }
}
1223 1224 1225 1226 1227 1228 1229

/**
 * Make sure that the image style square_thumbnail is created.
 */
function media_update_7227() {
  media_update_7211();
}