Projet

Général

Profil

Paste
Télécharger (41,3 ko) Statistiques
| Branche: | Révision:

root / drupal7 / sites / all / modules / media / media.install @ 81b16cc2

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_installed_date = $info['datestamp'];
116
    $file_entity_version = $info['version'];
117
    $file_entity_minimum_date = 1495439635;
118
    // Time of 2017-05-22 07:53:55 is most recent commit in 7.x-2.0.
119
    if ($file_entity_installed_date < $file_entity_minimum_date) {
120
      $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'));
121
      $requirements['file_entity']['description'] = $description;
122
      $requirements['file_entity']['severity'] = REQUIREMENT_ERROR;
123
      $requirements['file_entity']['value'] = $file_entity_version;
124
      $requirements['file_entity']['title'] = $t('Fieldable Files (file_entity) module 7.x-2.0 or newer is required by Media');
125
      drupal_set_message($description, 'error', TRUE);
126
    }
127
    if (strpos($info['version'], '7.x-2') === FALSE &&
128
      strpos($info['version'], '7.x-3') === FALSE) {
129
      $requirements['file_entity'] = array(
130
        'title' => $t('File entity 2.x or 3.x required.'),
131
        'value' => $t('Wrong version'),
132
        '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
  if (module_exists('entity_translation')) {
139
    if ($phase == 'update' || $phase == 'install' || $phase == 'runtime' ) {
140
      $entity_translation_info = system_get_info('module', 'entity_translation');
141
      $et_installed_version = $entity_translation_info['version'];
142
      $et_installed_datestamp = $entity_translation_info['datestamp'];
143
      $march3rd_entity_translation_timestamp = 1488530885;
144
      if (!isset($entity_translation_info['version']) || !isset($entity_translation_info['datestamp'])) {
145
        $et_installed_datestamp = 1488530884;
146
      }
147

    
148
      if ($et_installed_datestamp < $march3rd_entity_translation_timestamp) {
149
        $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));
150
        $requirements['entity_translation']['description'] = $description;
151
        $requirements['entity_translation']['severity'] = REQUIREMENT_ERROR;
152
        $requirements['entity_translation']['value'] = $et_installed_version;
153
        $requirements['entity_translation']['title'] = $t('Entity translation (when installed) with Media');
154
        drupal_set_message($description, 'error', TRUE);
155
      }
156
    }
157
  }
158
  return $requirements;
159
}
160

    
161
/**
162
 * Deprecated update function.
163
 */
164
function media_update_7000() {
165
}
166

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

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

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

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

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

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

    
267
/**
268
 * Deprecated update function.
269
 */
270
function media_update_7005() {
271
}
272

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

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

    
288
/**
289
 * Empty function.
290
 */
291
function media_update_7008() {
292
}
293

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

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

    
306
/**
307
 * Empty update function.
308
 */
309
function media_update_7011() {
310
}
311

    
312
/**
313
 * Empty update function.
314
 */
315
function media_update_7012() {
316
}
317

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

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

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

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

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

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

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

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

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

    
418
  // Update the field_bundle_settings configuration variable: move media bundle
419
  // settings to file bundles, and move settings of the old self-referencing
420
  // file field to the new file pseudo-field.
421
  foreach ($instances as $instance) {
422
    if ($instance['field_name'] === 'file' && !$instance['deleted']) {
423
      $file_settings = field_bundle_settings('file', $instance['bundle']);
424
      $media_settings = field_bundle_settings('media', $instance['bundle']);
425
      $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
      if (isset($instance['display'])) {
430
        foreach ($instance['display'] as $view_mode => $display) {
431
          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
  // Delete old media bundle settings.
443
  db_delete('variable')
444
    ->condition('name', db_like('field_bundle_settings_media__') . '%', 'LIKE')
445
    ->execute();
446

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

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

    
475
  field_cache_clear();
476
}
477

    
478
/**
479
 * Move file display configuration.
480
 *
481
 * Move file display configurations from the 'file_displays' variable to the
482
 * {file_display} table.
483
 */
484
function media_update_7017() {
485
  // If the {file_display} table doesn't exist, then the File Entity module's
486
  // update functions will automatically take care of migrating the
487
  // configurations. However, if file_entity_update_7001() has already run
488
  // prior to media_update_7016(), run it again in order to capture those
489
  // 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
    file_entity_update_7001();
493
  }
494
}
495

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

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

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

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

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

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

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

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

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

    
617
/**
618
 * Enable the Views module if it is not already enabled.
619
 */
620
function media_update_7202() {
621
  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
 * Empty update function to trigger cache clear.
629
 */
630
function media_update_7203() {
631
  // Do nothing.
632
}
633

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
935
/**
936
 * Enable the hidden media_migrate_file_types module to provide a UI to update
937
 * {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
 * Delete deceprated media__type_icon_directory variable.
949
 */
950
function media_update_7210() {
951
  variable_del('media__type_icon_directory');
952
}
953

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

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

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

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

    
978
    $effect = array(
979
      'name' => 'image_scale_and_crop',
980
      'data' => array(
981
        'width' => 100,
982
        'height' => 100,
983
        'weight' => 0,
984
      ),
985
      'isid' => $style['isid'],
986
    );
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
function _media_update_7204_update_views_display_options(&$display_options, $view_mode_updates) {
998
  $updated = FALSE;
999

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

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

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

    
1036
    file_type_save($application);
1037
    $application = file_type_load('application');
1038
    file_type_disable($application);
1039
  }
1040
}
1041

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

    
1049
  // Preserve any custom file extensions.
1050
  if (array_diff($media_file_extensions, $file_entity_file_extensions)) {
1051
    $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
  variable_del('media__file_extensions');
1056
}
1057

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

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

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

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

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

    
1101
  variable_del('media__xml_cache_expire');
1102
}
1103

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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