Projet

Général

Profil

Paste
Télécharger (40,8 ko) Statistiques
| Branche: | Révision:

root / drupal7 / sites / all / modules / media / media.install @ 5d940405

1
<?php
2

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

    
8
/**
9
 * Implements hook_install().
10
 */
11
function media_install() {
12
  // Make sure that we set the icon base directory variable if it is not
13
  // 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
  try {
20
    _media_install_copy_icons();
21
  }
22
  catch (Exception $e) {
23
    watchdog_exception('media', $e);
24
  }
25
}
26

    
27
/**
28
 * Copy the media file icons to files directory for use with image styles.
29
 */
30
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
  $files = file_scan_directory($source, '/.*\.(png|jpg)$/');
38
  foreach ($files as $file) {
39
    $result = file_unmanaged_copy($file->uri, $destination, FILE_EXISTS_REPLACE);
40
    if (!$result) {
41
      throw new Exception("Unable to copy {$file->uri} to $destination.");
42
    }
43
  }
44
}
45

    
46
/**
47
 * Implements hook_uninstall().
48
 */
49
function media_uninstall() {
50
  // Remove variables.
51
  variable_del('media_dialog_theme');
52
  variable_del('media_icon_base_directory');
53
  variable_del('media_icon_set');
54
  variable_del('media_show_deprecated_view_modes');
55

    
56
  // Dialog options.
57
  variable_del('media_dialogclass');
58
  variable_del('media_modal');
59
  variable_del('media_draggable');
60
  variable_del('media_resizable');
61
  variable_del('media_minwidth');
62
  variable_del('media_width');
63
  variable_del('media_height');
64
  variable_del('media_position');
65
  variable_del('media_zindex');
66
  variable_del('media_backgroundcolor');
67
  variable_del('media_opacity');
68
  // bulk edit option
69
  variable_del('media_bulk_upload_edit');
70
}
71

    
72
/**
73
 * Implements hook_update_dependencies().
74
 */
75
function media_update_dependencies() {
76
  // media_update_7200() needs to convert old 'media' permissions to new 'file'
77
  // permissions, so it must run before file_entity_7208 which updates existing
78
  // 'file' permissions to be split per file type.
79
  $dependencies['file_entity'][7208] = array(
80
    'media' => 7200,
81
  );
82
  // This update function requires field_update_7002() to run before it since
83
  // the field_bundle_settings variable has been split into separate variables
84
  // 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
  $dependencies['media'][7200] = array(
91
    'file_entity' => 7207,
92
  );
93
  // Require {file_type}.mimetypes column before updating them.
94
  $dependencies['media'][7208] = array(
95
    'file_entity' => 7210,
96
  );
97
  $dependencies['media'][7212] = array(
98
    'file_entity' => 7210,
99
  );
100
  return $dependencies;
101
}
102

    
103
/**
104
 * Implements hook_requirements().
105
 */
106
function media_requirements($phase) {
107
  $t = get_t();
108
  // 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
  // handle it. See #1734648.
111
  $requirements = array();
112

    
113
  if ($phase == 'update') {
114
    $info = system_get_info('module', 'file_entity');
115
    $file_entity_version = $info['version'];
116
    $file_entity_minimum_date = 1495439635;
117
    if (isset($info['datestamp'])) {
118
      $file_entity_installed_date = $info['datestamp'];
119
    }
120
    else {
121
      if (strpos($file_entity_version, '7.x-3') !== FALSE) {
122
        // Good version, any number that passes the condition is good.
123
        $file_entity_installed_date = $file_entity_minimum_date + 1;
124
      }
125
      else {
126
        // Check version 2 release and parse into a number.
127
        // No need to check version 1 as that's checked below.
128
        $version_number = str_replace('7.x-2.', '', $file_entity_version);
129
        if (is_numeric($version_number)) {
130
          // Plain number, so good version.
131
          $file_entity_installed_date = $file_entity_minimum_date + 1;
132
        }
133
        else {
134
          // Bad version or release (beta, alpha, unstable...).
135
          $file_entity_installed_date = $file_entity_minimum_date - 1;
136
        }
137
      }
138
    }
139

    
140
    // Time of 2017-05-22 07:53:55 is most recent commit in 7.x-2.0.
141
    if ($file_entity_installed_date < $file_entity_minimum_date) {
142
      $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'));
143
      $requirements['file_entity']['description'] = $description;
144
      $requirements['file_entity']['severity'] = REQUIREMENT_ERROR;
145
      $requirements['file_entity']['value'] = $file_entity_version;
146
      $requirements['file_entity']['title'] = $t('Fieldable Files (file_entity) module 7.x-2.0 or newer is required by Media');
147
      drupal_set_message($description, 'error', TRUE);
148
    }
149
    if (strpos($info['version'], '7.x-2') === FALSE &&
150
      strpos($info['version'], '7.x-3') === FALSE) {
151
      $requirements['file_entity'] = array(
152
        'title' => $t('File entity 2.x or 3.x required.'),
153
        'value' => $t('Wrong version'),
154
        'severity' => REQUIREMENT_ERROR,
155
        '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')),
156
      );
157
    }
158
  }
159

    
160
  return $requirements;
161
}
162

    
163
/**
164
 * Deprecated update function.
165
 */
166
function media_update_7000() {
167
}
168

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

    
175
/**
176
 * Create the media_type table from the media_types variable.
177
 */
178
function media_update_7002() {
179
  if (db_table_exists('media_type')) {
180
    return;
181
  }
182

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

    
233
  drupal_load('module', 'media');
234
  $old_types = variable_get('media_types', array());
235
  foreach ($old_types as $type) {
236
    // Was an error in the original creation.
237
    if (isset($type->callbacks)) {
238
      unset($type->callbacks);
239
    }
240
    $type->name = $type->machine_name;
241
    unset($type->machine_name);
242
    db_merge('media_type')
243
      ->key(array('name' => $type->name))
244
      ->fields((array) $type)
245
      ->execute();
246
  }
247
  variable_del('media_types');
248
}
249

    
250
/**
251
 * We now prefix media namespaced variables with media__, so fix old variables.
252
 */
253
function media_update_7003() {
254
  drupal_load('module', 'media');
255
  foreach (media_variable_default() as $variable => $value) {
256
    if (($test = variable_get('media_' . $variable, TRUE)) == variable_get('media_' . $variable, FALSE)) {
257
      media_variable_set($variable, $test);
258
      variable_del('media_' . $variable);
259
    }
260
  }
261
}
262

    
263
/**
264
 * Empty update function to trigger a menu rebuild.
265
 */
266
function media_update_7004() {
267
}
268

    
269
/**
270
 * Deprecated update function.
271
 */
272
function media_update_7005() {
273
}
274

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

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

    
290
/**
291
 * Empty function.
292
 */
293
function media_update_7008() {
294
}
295

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

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

    
308
/**
309
 * Empty update function.
310
 */
311
function media_update_7011() {
312
}
313

    
314
/**
315
 * Empty update function.
316
 */
317
function media_update_7012() {
318
}
319

    
320
/**
321
 * Work around a core bug where text format cacheability is not updated.
322
 *
323
 * @see http://drupal.org/node/993230
324
 */
325
function media_update_7013() {
326
  $formats = filter_formats();
327
  foreach ($formats as $format) {
328
    $format->filters = filter_list_format($format->format);
329
    // filter_format_save() expects filters to be an array, however
330
    // filter_list_format() gives us objects.
331
    foreach ($format->filters as $key => $value) {
332
      $format->filters[$key] = (array) $value;
333
    }
334
    filter_format_save($format);
335
  }
336
}
337

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

    
348
/**
349
 * Empty update function to trigger a registry rebuild.
350
 */
351
function media_update_7015() {
352
}
353

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

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

    
382
    // @todo Convert this to use _update_7000_field_read_fields()
383
    $fields = field_read_fields(array('id' => $instance['field_id']), array('include_inactive' => TRUE, 'include_deleted' => TRUE));
384
    $field = $fields[$instance['field_id']];
385

    
386
    // There is no API for updating the entity_type foreign key within field
387
    // data storage. We can do a direct db_update() for when the default SQL
388
    // storage back-end is being used, but must skip updating fields that use a
389
    // different storage type.
390
    if ($field['storage']['type'] !== 'field_sql_storage' || !module_exists('field_sql_storage') || !$field['storage']['active']) {
391
      $messages[] = t('Cannot update field %id (%field_name) because it does not use the field_sql_storage storage type.', array(
392
        '%id' => $field['id'],
393
        '%field_name' => $field['field_name'],
394
      ));
395
      continue;
396
    }
397

    
398
    // Update the data tables.
399
    $table_name = _field_sql_storage_tablename($field);
400
    $revision_name = _field_sql_storage_revision_tablename($field);
401
    db_update($table_name)
402
      ->fields(array('entity_type' => 'file'))
403
      ->condition('entity_type', 'media')
404
      ->condition('bundle', $instance['bundle'])
405
      ->execute();
406
    db_update($revision_name)
407
      ->fields(array('entity_type' => 'file'))
408
      ->condition('entity_type', 'media')
409
      ->condition('bundle', $instance['bundle'])
410
      ->execute();
411

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

    
420
  // Update the field_bundle_settings configuration variable: move media bundle
421
  // settings to file bundles, and move settings of the old self-referencing
422
  // file field to the new file pseudo-field.
423
  foreach ($instances as $instance) {
424
    if ($instance['field_name'] === 'file' && !$instance['deleted']) {
425
      $file_settings = field_bundle_settings('file', $instance['bundle']);
426
      $media_settings = field_bundle_settings('media', $instance['bundle']);
427
      $file_settings = array_merge($file_settings, $media_settings);
428
      if (isset($instance['widget']['weight'])) {
429
        $file_settings['extra_fields']['form']['file']['weight'] = $instance['widget']['weight'];
430
      }
431
      if (isset($instance['display'])) {
432
        foreach ($instance['display'] as $view_mode => $display) {
433
          if (isset($display['weight'])) {
434
            $file_settings['extra_fields']['display']['file'][$view_mode]['weight'] = $display['weight'];
435
          }
436
          if (isset($display['type'])) {
437
            $file_settings['extra_fields']['display']['file'][$view_mode]['visible'] = ($display['type'] != 'hidden');
438
          }
439
        }
440
      }
441
      field_bundle_settings('file', $instance['bundle'], $file_settings);
442
    }
443
  }
444
  // Delete old media bundle settings.
445
  db_delete('variable')
446
    ->condition('name', db_like('field_bundle_settings_media__') . '%', 'LIKE')
447
    ->execute();
448

    
449
  // Copy field formatter settings of old self-referencing file field to file
450
  // pseudo-field formatter settings.
451
  $file_displays = variable_get('file_displays', array());
452
  foreach ($instances as $instance) {
453
    if ($instance['field_name'] === 'file' && !$instance['deleted']) {
454
      if (isset($instance['display'])) {
455
        foreach ($instance['display'] as $view_mode => $display) {
456
          if (isset($display['type']) && $display['type'] != 'hidden') {
457
            $file_formatter = 'file_field_' . $display['type'];
458
            $file_displays[$instance['bundle']][$view_mode][$file_formatter]['status'] = TRUE;
459
            if (isset($display['settings'])) {
460
              $file_displays[$instance['bundle']][$view_mode][$file_formatter]['settings'] = $display['settings'];
461
            }
462
          }
463
        }
464
      }
465
    }
466
  }
467
  variable_set('file_displays', $file_displays);
468

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

    
477
  field_cache_clear();
478
}
479

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

    
498
/**
499
 * Empty update function to trigger a menu rebuild.
500
 */
501
function media_update_7018() {
502
}
503

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

    
531
/**
532
 * Delete the wysiwyg_allowed_types variable if it is the same as default.
533
 */
534
function media_update_7020() {
535
  if (variable_get('media__wysiwyg_allowed_types') == array('image', 'video')) {
536
    variable_del('media__wysiwyg_allowed_types');
537
  }
538
}
539

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

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

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

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

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

    
613
      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.');
614
    }
615
  }
616
  return t('The "Media" field type has been moved to the new "Media Field" module. File fields can be used to store media.');
617
}
618

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

    
629
/**
630
 * Empty update function to trigger cache clear.
631
 */
632
function media_update_7203() {
633
  // Do nothing.
634
}
635

    
636
/**
637
 * Update old Media view modes to the new File Entity ones.
638
 */
639
function media_update_7204() {
640
  $view_mode_updates = array(
641
    'media_preview' => 'preview',
642
    'media_small' => 'teaser',
643
    'media_large' => 'full',
644
  );
645

    
646
  // Update the media__wysiwyg_default_view_mode variable.
647
  $wysiwyg_default_view_mode = variable_get('media__wysiwyg_default_view_mode');
648
  if (isset($wysiwyg_default_view_mode) && isset($view_mode_updates[$wysiwyg_default_view_mode])) {
649
    $wysiwyg_default_view_mode = $view_mode_updates[$wysiwyg_default_view_mode];
650
    variable_set('media__wysiwyg_default_view_mode', $wysiwyg_default_view_mode);
651
  }
652

    
653
  // Update view mode references in the 'field_bundle_settings' variable.
654
  $field_bundle_settings = variable_get('field_bundle_settings');
655
  if (!empty($field_bundle_settings['file'])) {
656
    foreach ($field_bundle_settings['file'] as $file_type => $info) {
657
      // Per-bundle information about the view modes.
658
      foreach ($view_mode_updates as $old_view_mode => $new_view_mode) {
659
        if (isset($info['view_modes'][$old_view_mode])) {
660
          $field_bundle_settings['file'][$file_type]['view_modes'][$new_view_mode] = $info['view_modes'][$old_view_mode];
661
          unset($field_bundle_settings['file'][$file_type]['view_modes'][$old_view_mode]);
662
        }
663
        // The File Entity module defaults to not use custom settings for the
664
        // new view modes, but the Media module used to default to using custom
665
        // settings, so if this variable is not defined, use the prior default.
666
        if (!isset($field_bundle_settings['file'][$file_type]['view_modes'][$new_view_mode]['custom_settings'])) {
667
          $field_bundle_settings['file'][$file_type]['view_modes'][$new_view_mode]['custom_settings'] = TRUE;
668
        }
669
      }
670

    
671
      // Settings for the "extra fields" configured on the Manage Display page.
672
      if (!empty($info['extra_fields']['display'])) {
673
        foreach ($info['extra_fields']['display'] as $extra_field_name => $extra_field_info) {
674
          foreach ($view_mode_updates as $old_view_mode => $new_view_mode) {
675
            if (isset($extra_field_info[$old_view_mode])) {
676
              $field_bundle_settings['file'][$file_type]['extra_fields']['display'][$extra_field_name][$new_view_mode] = $extra_field_info[$old_view_mode];
677
              unset($field_bundle_settings['file'][$file_type]['extra_fields']['display'][$extra_field_name][$old_view_mode]);
678
            }
679
          }
680
        }
681
      }
682
    }
683
  }
684
  variable_set('field_bundle_settings', $field_bundle_settings);
685

    
686
  // Move settings for fields attached to files from the old view modes to the
687
  // new ones.
688
  $instances = field_read_instances(array('entity_type' => 'file'));
689
  foreach ($instances as $instance) {
690
    $updated = FALSE;
691
    foreach ($view_mode_updates as $old_view_mode => $new_view_mode) {
692
      if (isset($instance['display'][$old_view_mode])) {
693
        $instance['display'][$new_view_mode] = $instance['display'][$old_view_mode];
694
        unset($instance['display'][$old_view_mode]);
695
        $updated = TRUE;
696
      }
697
    }
698
    if ($updated) {
699
      field_update_instance($instance);
700
    }
701
  }
702

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

    
715
  // Update file/image/media fields that use a formatter that reference an old
716
  // file view modes to reference the new ones.
717
  foreach (field_read_instances() as $instance) {
718
    if (!empty($instance['display'])) {
719
      $updated = FALSE;
720
      foreach ($instance['display'] as $instance_view_mode => $display) {
721
        if (isset($display['settings']['file_view_mode']) && isset($view_mode_updates[$display['settings']['file_view_mode']])) {
722
          $instance['display'][$instance_view_mode]['settings']['file_view_mode'] = $view_mode_updates[$display['settings']['file_view_mode']];
723
          $updated = TRUE;
724
        }
725
      }
726
      if ($updated) {
727
        field_update_instance($instance);
728
      }
729
    }
730
  }
731

    
732
  // Update formatter settings that reference the old view modes within saved
733
  // Views.
734
  if (db_table_exists('views_display')) {
735
    $result = db_select('views_display', 'v')->fields('v', array('vid', 'id', 'display_options'))->execute();
736
    foreach ($result as $record) {
737
      if (!empty($record->display_options)) {
738
        $display_options = unserialize($record->display_options);
739
        if (_media_update_7204_update_views_display_options($display_options, $view_mode_updates)) {
740
          db_update('views_display')
741
            ->fields(array('display_options' => serialize($display_options)))
742
            ->condition('vid', $record->vid)
743
            ->condition('id', $record->id)
744
            ->execute();
745
        }
746
      }
747
    }
748
  }
749

    
750
  // Update formatter settings that reference the old view modes within unsaved
751
  // Views in the CTools object cache. Objects in the CTools cache are instances
752
  // of classes, so the Views module must be enabled to unserialize it
753
  // correctly.
754
  if (db_table_exists('ctools_object_cache') && module_exists('views')) {
755
    $result = db_select('ctools_object_cache', 'c')->fields('c', array('sid', 'name', 'obj', 'data'))->condition('obj', 'view')->execute();
756
    foreach ($result as $record) {
757
      $view = unserialize($record->data);
758
      if (!empty($view->display)) {
759
        $updated = FALSE;
760
        foreach ($view->display as $display_name => $display) {
761
          if (!empty($display->display_options) && _media_update_7204_update_views_display_options($display->display_options, $view_mode_updates)) {
762
            $updated = TRUE;
763
          }
764
        }
765
        if ($updated) {
766
          db_update('ctools_object_cache')
767
            ->fields(array('data' => serialize($view)))
768
            ->condition('sid', $record->sid)
769
            ->condition('name', $record->name)
770
            ->condition('obj', $record->obj)
771
            ->execute();
772
        }
773
      }
774
    }
775
  }
776

    
777
  // Clear caches that might contain stale Views displays.
778
  if (module_exists('views')) {
779
    cache_clear_all('*', 'cache_views', TRUE);
780
    cache_clear_all('*', 'cache_views_data', TRUE);
781
  }
782
  if (module_exists('block')) {
783
    cache_clear_all('*', 'cache_block', TRUE);
784
  }
785
  cache_clear_all('*', 'cache_page', TRUE);
786

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

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

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

    
816
  // Only needed by sites that updated from Media 1.x.
817
  // @see media_entity_info_alter()
818
  if (variable_get('media__show_deprecated_view_modes')) {
819
    $default_image_styles['media_original'] = '';
820
  }
821

    
822
  // Clear out the ctools cache so that the old default implementations
823
  // are removed.
824
  ctools_export_load_object_reset('file_display');
825
  foreach ($default_image_styles as $view_mode => $image_style) {
826
    $existing_displays = file_displays_load('image', $view_mode, TRUE);
827
    // Only insert default config into the database if no existing
828
    // configuration is found.
829
    if (!isset($existing_displays['file_image'])) {
830
      $display_name = 'image__' . $view_mode . '__file_image';
831
      $display = array(
832
        'api_version' => 1,
833
        'name' => $display_name,
834
        'status' => 1,
835
        'weight' => 5,
836
        'settings' => array('image_style' => $image_style),
837
        'export_type' => NULL,
838
      );
839
      file_display_save((object) $display);
840
    }
841
  }
842
}
843

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

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

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

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

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

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

    
944
  if (_media_migrate_file_types_get_migratable_file_types()) {
945
    module_enable(array('media_migrate_file_types'));
946
  }
947
}
948

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

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

    
965
  // Clear the image cache to remove any old image styles that only exist in
966
  // code.
967
  cache_clear_all('image_styles', 'cache_image', TRUE);
968

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

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

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

    
990
    image_effect_save($effect);
991
  }
992

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

    
996
/**
997
 * Utility function for update 7204. Updates display options within Views.
998
 */
999
function _media_update_7204_update_views_display_options(&$display_options, $view_mode_updates) {
1000
  $updated = FALSE;
1001

    
1002
  // Update fields that use a formatter with a file_view_mode formatter setting.
1003
  if (!empty($display_options['fields'])) {
1004
    foreach ($display_options['fields'] as $field_name => $field_display) {
1005
      if (isset($field_display['settings']['file_view_mode']) && isset($view_mode_updates[$field_display['settings']['file_view_mode']])) {
1006
        $display_options['fields'][$field_name]['settings']['file_view_mode'] = $view_mode_updates[$field_display['settings']['file_view_mode']];
1007
        $updated = TRUE;
1008
      }
1009
    }
1010
  }
1011

    
1012
  // Update Views that display files directly using a row plugin with a view
1013
  // mode setting.
1014
  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']])) {
1015
    $display_options['row_options']['view_mode'] = $view_mode_updates[$display_options['row_options']['view_mode']];
1016
    $updated = TRUE;
1017
  }
1018
  return $updated;
1019
}
1020

    
1021
/**
1022
 * Re-create application file type for legacy reasons.
1023
 */
1024
function media_update_7212() {
1025
  module_load_include('inc', 'file_entity', 'file_entity.file_api');
1026
  if (!file_type_load('application')) {
1027
    $application = (object) array(
1028
      'api_version' => 1,
1029
      'type' => 'application',
1030
      'label' => t('Application'),
1031
      'description' => t('Multipurpose type - kept to support older sites.'),
1032
      'mimetypes' => array(),
1033
      'streams' => array(
1034
        'public',
1035
      ),
1036
    );
1037

    
1038
    file_type_save($application);
1039
    $application = file_type_load('application');
1040
    file_type_disable($application);
1041
  }
1042
}
1043

    
1044
/**
1045
 * Remove the obsolete file_extensions variable.
1046
 */
1047
function media_update_7213() {
1048
  $media_file_extensions = explode(' ', variable_get('media__file_extensions'));
1049
  $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'));
1050

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

    
1057
  variable_del('media__file_extensions');
1058
}
1059

    
1060
/**
1061
 * Drop the legacy {media_filter_usage} table.
1062
 */
1063
function media_update_7214() {
1064
  if (db_table_exists('media_filter_usage')) {
1065
    db_drop_table('media_filter_usage');
1066
  }
1067
}
1068

    
1069
/**
1070
 * Skipped to run media_update_7217().
1071
 */
1072
function media_update_7216() {
1073
  // Do nothing.
1074
}
1075

    
1076
/**
1077
 * Copy file type icons to public files directory.
1078
 */
1079
function media_update_7217() {
1080
  // Remove any trailing slashes from the icon base directory variable.
1081
  $dir = variable_get('media__icon_base_directory');
1082
  if (!empty($dir)) {
1083
    $dir = rtrim($dir, '/');
1084
    variable_set('media__icon_base_directory', $dir);
1085
  }
1086

    
1087
  try {
1088
    _media_install_copy_icons();
1089
  }
1090
  catch (Exception $e) {
1091
    throw new DrupalUpdateException($e->getMessage());
1092
  }
1093
}
1094

    
1095
/**
1096
 * Drop the legacy {cache_media_xml} table.
1097
 */
1098
function media_update_7218() {
1099
  if (db_table_exists('cache_media_xml')) {
1100
    db_drop_table('cache_media_xml');
1101
  }
1102

    
1103
  variable_del('media__xml_cache_expire');
1104
}
1105

    
1106
/**
1107
 * Enable the Media WYSIWYG submodule.
1108
 */
1109
function media_update_7219() {
1110
  if (module_exists('wysiwyg')) {
1111
    module_enable(array('media_wysiwyg'));
1112
  }
1113
}
1114

    
1115
/**
1116
 * Delete the deprecated media__file_list_size variable.
1117
 */
1118
function media_update_7220() {
1119
  variable_del('media__file_list_size');
1120
}
1121

    
1122
/**
1123
 * Enable the Media Bulk Upload submodule.
1124
 */
1125
function media_update_7221() {
1126
  if (module_exists('multiform') && module_exists('plupload')) {
1127
    module_enable(array('media_bulk_upload'));
1128
  }
1129
}
1130

    
1131
/**
1132
 * Delete the deprecated media__display_types_migration_mess variable.
1133
 */
1134
function media_update_7222() {
1135
  variable_del('media__display_types_migration_mess');
1136
}
1137

    
1138
/**
1139
 * Delete legacy variables.
1140
 */
1141
function media_update_7223() {
1142
  variable_del('media__max_filesize');
1143
  variable_del('media__debug');
1144
  variable_del('media__xml_cache_expire');
1145
  variable_del('media__show_file_type_rebuild_nag');
1146
  variable_del('media__field_select_media_text');
1147
  variable_del('media__field_remove_media_text');
1148
  variable_del('media__browser_library_empty_message');
1149
  variable_del('media__browser_pager_limit');
1150
  variable_del('media__browser_viewtype_default');
1151
}
1152

    
1153
/**
1154
 * Rename variables, removing variable namespace.
1155
 */
1156
function media_update_7224() {
1157
  // Create an array of variables sans 'media' prefix.
1158
  $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');
1159

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

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

    
1169
    // Remove the old variable.
1170
    variable_del('media__' . $variable);
1171
  }
1172
}
1173

    
1174
/**
1175
 * Migrate variables to appropriate submodules.
1176
 */
1177
function media_update_7225() {
1178
  $data = array(
1179
    'media_wysiwyg' => array(
1180
      'wysiwyg_title',
1181
      'wysiwyg_icon_title',
1182
      'wysiwyg_default_view_mode',
1183
      'wysiwyg_upload_directory',
1184
      'wysiwyg_allowed_types',
1185
      'wysiwyg_allowed_attributes',
1186
      'wysiwyg_browser_plugins',
1187
    ),
1188
    'media_internet' => array(
1189
      'fromurl_supported_schemes',
1190
    ),
1191
    'media_bulk_upload' => array(
1192
      'import_batch_size',
1193
    ),
1194
  );
1195

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

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

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

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

    
1221
  foreach ($roles as $rid => $role) {
1222
    user_role_grant_permissions($rid, array('access media browser'));
1223
  }
1224
}
1225

    
1226
/**
1227
 * Make sure that the image style square_thumbnail is created.
1228
 */
1229
function media_update_7227() {
1230
  media_update_7211();
1231
}