Projet

Général

Profil

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

root / drupal7 / sites / all / modules / media / media.install @ 05237dd8

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
    if (strpos($info['version'], '7.x-2') === FALSE) {
116
      $requirements['file_entity'] = array(
117
        'title' => $t('File entity 2.x'),
118
        'value' => $t('Wrong version'),
119
        'severity' => REQUIREMENT_ERROR,
120
        'description' => $t('Media 2.x requires <a href="@url">File entity 2.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')),
121
      );
122
    }
123
  }
124

    
125
  if (module_exists('entity_translation')) {
126
    if ($phase == 'update' || $phase == 'install' || $phase == 'runtime' ) {
127
      $entity_translation_info = system_get_info('module', 'entity_translation');
128
      $et_installed_version = $entity_translation_info['version'];
129
      $et_installed_datestamp = $entity_translation_info['datestamp'];
130
      $march3rd_entity_translation_timestamp = 1488530885;
131
      if (!isset($entity_translation_info['version']) || !isset($entity_translation_info['datestamp'])) {
132
        $et_installed_datestamp = 1488530884;
133
      }
134

    
135
      if ($et_installed_datestamp < $march3rd_entity_translation_timestamp) {
136
        $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));
137
        $requirements['entity_translation']['description'] = $description;
138
        $requirements['entity_translation']['severity'] = REQUIREMENT_ERROR;
139
        $requirements['entity_translation']['value'] = $et_installed_version;
140
        $requirements['entity_translation']['title'] = $t('Entity translation (when installed) with Media');
141
	drupal_set_message($description, 'error', TRUE);
142
      }
143
    }
144
  }
145
  return $requirements;
146
}
147

    
148
/**
149
 * Deprecated update function.
150
 */
151
function media_update_7000() {
152
}
153

    
154
/**
155
 * Deprecated update function.
156
 */
157
function media_update_7001() {
158
}
159

    
160
/**
161
 * Create the media_type table from the media_types variable.
162
 */
163
function media_update_7002() {
164
  if (db_table_exists('media_type')) {
165
    return;
166
  }
167

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

    
218
  drupal_load('module', 'media');
219
  $old_types = variable_get('media_types', array());
220
  foreach ($old_types as $type) {
221
    // Was an error in the original creation.
222
    if (isset($type->callbacks)) {
223
      unset($type->callbacks);
224
    }
225
    $type->name = $type->machine_name;
226
    unset($type->machine_name);
227
    db_merge('media_type')
228
      ->key(array('name' => $type->name))
229
      ->fields((array) $type)
230
      ->execute();
231
  }
232
  variable_del('media_types');
233
}
234

    
235
/**
236
 * We now prefix media namespaced variables with media__, so fix old variables.
237
 */
238
function media_update_7003() {
239
  drupal_load('module', 'media');
240
  foreach (media_variable_default() as $variable => $value) {
241
    if (($test = variable_get('media_' . $variable, TRUE)) == variable_get('media_' . $variable, FALSE)) {
242
      media_variable_set($variable, $test);
243
      variable_del('media_' . $variable);
244
    }
245
  }
246
}
247

    
248
/**
249
 * Empty update function to trigger a menu rebuild.
250
 */
251
function media_update_7004() {
252
}
253

    
254
/**
255
 * Deprecated update function.
256
 */
257
function media_update_7005() {
258
}
259

    
260
/**
261
 * Rename the file table to file_managed in case head2head was used.
262
 */
263
function media_update_7006() {
264
  if (db_table_exists('file') && !db_table_exists('file_managed')) {
265
    db_rename_table('file', 'file_managed');
266
  }
267
}
268

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

    
275
/**
276
 * Empty function.
277
 */
278
function media_update_7008() {
279
}
280

    
281
/**
282
 * Deprecated update function.
283
 */
284
function media_update_7009() {
285
}
286

    
287
/**
288
 * Deprecated update function.
289
 */
290
function media_update_7010() {
291
}
292

    
293
/**
294
 * Empty update function.
295
 */
296
function media_update_7011() {
297
}
298

    
299
/**
300
 * Empty update function.
301
 */
302
function media_update_7012() {
303
}
304

    
305
/**
306
 * Work around a core bug where text format cacheability is not updated.
307
 *
308
 * @see http://drupal.org/node/993230
309
 */
310
function media_update_7013() {
311
  $formats = filter_formats();
312
  foreach ($formats as $format) {
313
    $format->filters = filter_list_format($format->format);
314
    // filter_format_save() expects filters to be an array, however
315
    // filter_list_format() gives us objects.
316
    foreach ($format->filters as $key => $value) {
317
      $format->filters[$key] = (array) $value;
318
    }
319
    filter_format_save($format);
320
  }
321
}
322

    
323
/**
324
 * Rename the media__dialog_get_theme_name variable to media__dialog_theme.
325
 */
326
function media_update_7014() {
327
  if ($old_value = variable_get('media__dialog_get_theme_name')) {
328
    variable_del('media__dialog_get_theme_name');
329
    variable_set('media__dialog_theme', $old_value);
330
  }
331
}
332

    
333
/**
334
 * Empty update function to trigger a registry rebuild.
335
 */
336
function media_update_7015() {
337
}
338

    
339
/**
340
 * Convert Media entities to File entities.
341
 *
342
 * This update function requires field_update_7002() to run before it since
343
 * the field_bundle_settings variable has been split into separate variables
344
 * per entity type and bundle.
345
 *
346
 * @see http://drupal.org/node/1418708
347
 * @see http://drupal.org/node/1211008
348
 */
349
function media_update_7016() {
350
  // Allow File Entity module to take over the {file_managed}.type field. It
351
  // will create new indexes as it needs to, but it doesn't know about old ones,
352
  // so delete them.
353
  if (db_index_exists('file_managed', 'file_type')) {
354
    db_drop_index('file_managed', 'file_type');
355
  }
356
  module_enable(array('file_entity'));
357

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

    
367
    // @todo Convert this to use _update_7000_field_read_fields()
368
    $fields = field_read_fields(array('id' => $instance['field_id']), array('include_inactive' => TRUE, 'include_deleted' => TRUE));
369
    $field = $fields[$instance['field_id']];
370

    
371
    // There is no API for updating the entity_type foreign key within field
372
    // data storage. We can do a direct db_update() for when the default SQL
373
    // storage back-end is being used, but must skip updating fields that use a
374
    // different storage type.
375
    if ($field['storage']['type'] !== 'field_sql_storage' || !module_exists('field_sql_storage') || !$field['storage']['active']) {
376
      $messages[] = t('Cannot update field %id (%field_name) because it does not use the field_sql_storage storage type.', array(
377
        '%id' => $field['id'],
378
        '%field_name' => $field['field_name'],
379
      ));
380
      continue;
381
    }
382

    
383
    // Update the data tables.
384
    $table_name = _field_sql_storage_tablename($field);
385
    $revision_name = _field_sql_storage_revision_tablename($field);
386
    db_update($table_name)
387
      ->fields(array('entity_type' => 'file'))
388
      ->condition('entity_type', 'media')
389
      ->condition('bundle', $instance['bundle'])
390
      ->execute();
391
    db_update($revision_name)
392
      ->fields(array('entity_type' => 'file'))
393
      ->condition('entity_type', 'media')
394
      ->condition('bundle', $instance['bundle'])
395
      ->execute();
396

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

    
405
  // Update the field_bundle_settings configuration variable: move media bundle
406
  // settings to file bundles, and move settings of the old self-referencing
407
  // file field to the new file pseudo-field.
408
  foreach ($instances as $instance) {
409
    if ($instance['field_name'] === 'file' && !$instance['deleted']) {
410
      $file_settings = field_bundle_settings('file', $instance['bundle']);
411
      $media_settings = field_bundle_settings('media', $instance['bundle']);
412
      $file_settings = array_merge($file_settings, $media_settings);
413
      if (isset($instance['widget']['weight'])) {
414
        $file_settings['extra_fields']['form']['file']['weight'] = $instance['widget']['weight'];
415
      }
416
      if (isset($instance['display'])) {
417
        foreach ($instance['display'] as $view_mode => $display) {
418
          if (isset($display['weight'])) {
419
            $file_settings['extra_fields']['display']['file'][$view_mode]['weight'] = $display['weight'];
420
          }
421
          if (isset($display['type'])) {
422
            $file_settings['extra_fields']['display']['file'][$view_mode]['visible'] = ($display['type'] != 'hidden');
423
          }
424
        }
425
      }
426
      field_bundle_settings('file', $instance['bundle'], $file_settings);
427
    }
428
  }
429
  // Delete old media bundle settings.
430
  db_delete('variable')
431
    ->condition('name', db_like('field_bundle_settings_media__') . '%', 'LIKE')
432
    ->execute();
433

    
434
  // Copy field formatter settings of old self-referencing file field to file
435
  // pseudo-field formatter settings.
436
  $file_displays = variable_get('file_displays', array());
437
  foreach ($instances as $instance) {
438
    if ($instance['field_name'] === 'file' && !$instance['deleted']) {
439
      if (isset($instance['display'])) {
440
        foreach ($instance['display'] as $view_mode => $display) {
441
          if (isset($display['type']) && $display['type'] != 'hidden') {
442
            $file_formatter = 'file_field_' . $display['type'];
443
            $file_displays[$instance['bundle']][$view_mode][$file_formatter]['status'] = TRUE;
444
            if (isset($display['settings'])) {
445
              $file_displays[$instance['bundle']][$view_mode][$file_formatter]['settings'] = $display['settings'];
446
            }
447
          }
448
        }
449
      }
450
    }
451
  }
452
  variable_set('file_displays', $file_displays);
453

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

    
462
  field_cache_clear();
463
}
464

    
465
/**
466
 * Move file display configuration.
467
 *
468
 * Move file display configurations from the 'file_displays' variable to the
469
 * {file_display} table.
470
 */
471
function media_update_7017() {
472
  // If the {file_display} table doesn't exist, then the File Entity module's
473
  // update functions will automatically take care of migrating the
474
  // configurations. However, if file_entity_update_7001() has already run
475
  // prior to media_update_7016(), run it again in order to capture those
476
  // configurations too.
477
  if (db_table_exists('file_display') && function_exists('file_entity_update_7001')) {
478
    module_load_include('install', 'file_entity', 'file_entity');
479
    file_entity_update_7001();
480
  }
481
}
482

    
483
/**
484
 * Empty update function to trigger a menu rebuild.
485
 */
486
function media_update_7018() {
487
}
488

    
489
/**
490
 * Update old view mode formaters.
491
 *
492
 * Update old per-view-mode media field formatters to the generic media
493
 * formatter with a setting.
494
 */
495
function media_update_7019() {
496
  $instances = array();
497
  $fields = field_read_fields(array('type' => 'media'), array('include_inactive' => TRUE));
498
  foreach ($fields as $field) {
499
    $instances = array_merge($instances, field_read_instances(array('field_id' => $field['id']), array('include_inactive' => TRUE)));
500
  }
501
  foreach ($instances as $instance) {
502
    $update_instance = FALSE;
503
    foreach ($instance['display'] as $view_mode => $display) {
504
      if (in_array($display['type'], array('media_link', 'media_preview', 'media_small', 'media_large', 'media_original'))) {
505
        $update_instance = TRUE;
506
        $instance['display'][$view_mode]['type'] = 'media';
507
        $instance['display'][$view_mode]['settings'] = array('file_view_mode' => $display['type']);
508
      }
509
    }
510
    if ($update_instance) {
511
      field_update_instance($instance);
512
    }
513
  }
514
}
515

    
516
/**
517
 * Delete the wysiwyg_allowed_types variable if it is the same as default.
518
 */
519
function media_update_7020() {
520
  if (variable_get('media__wysiwyg_allowed_types') == array('image', 'video')) {
521
    variable_del('media__wysiwyg_allowed_types');
522
  }
523
}
524

    
525
/**
526
 * Rerun media_update_7002() due to a typo that would prevent table creation.
527
 */
528
function media_update_7021() {
529
  media_update_7002();
530
}
531

    
532
/**
533
 * Replace 'view media' perm from all users having the role with 'view file'.
534
 */
535
function media_update_7200() {
536
  $perms = user_permission_get_modules();
537
  if (!isset($perms['view files'])) {
538
    throw new DrupalUpdateException('The File Entity module needs to be upgraded before continuing.');
539
  }
540
  else {
541
    $roles = user_roles(FALSE, 'view media');
542
    $permissions = array(
543
      'view media' => FALSE,
544
      'view files' => TRUE,
545
    );
546
    foreach ($roles as $rid => $role) {
547
      user_role_change_permissions($rid, $permissions);
548
    }
549
    $roles = user_roles(FALSE, 'edit media');
550
    $permissions = array(
551
      'edit media' => FALSE,
552
      'edit any files' => TRUE,
553
    );
554
    if (function_exists('file_entity_list_permissions')) {
555
      unset($permissions['edit any files']);
556

    
557
      foreach (file_entity_permissions_get_configured_types() as $type) {
558
        $permissions += file_entity_list_permissions($type);
559
      }
560
    }
561
    foreach ($roles as $rid => $role) {
562
      user_role_change_permissions($rid, $permissions);
563
    }
564
    $roles = user_roles(FALSE, 'administer media');
565
    $permissions = array(
566
      'administer media' => FALSE,
567
      'administer files' => TRUE,
568
    );
569
    foreach ($roles as $rid => $role) {
570
      user_role_change_permissions($rid, $permissions);
571
    }
572
  }
573
}
574

    
575
/**
576
 * Handle existing media fields.
577
 *
578
 * Enable the new Media Field module if this site uses "media" fields. File
579
 * fields are now preferred for storing media.
580
 */
581
function media_update_7201() {
582
  $fields = field_info_fields();
583
  foreach ($fields as $field) {
584
    if ($field['type'] == 'media') {
585
      // This update function may run even if Media is not enabled. Don't enable
586
      // Media Field if its dependencies aren't already enabled.
587
      module_enable(array('mediafield'), FALSE);
588

    
589
      // Update entries in file_usage so that they are associated with Media
590
      // Field rather than Media.
591
      // @TODO This update function may conflict with
592
      // http://drupal.org/node/1268116
593
      db_update('file_usage')
594
        ->condition('module', 'media')
595
        ->fields(array('module' => 'mediafield'))
596
        ->execute();
597

    
598
      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.');
599
    }
600
  }
601
  return t('The "Media" field type has been moved to the new "Media Field" module. File fields can be used to store media.');
602
}
603

    
604
/**
605
 * Enable the Views module if it is not already enabled.
606
 */
607
function media_update_7202() {
608
  module_enable(array('views'));
609
  if (!module_exists('views')) {
610
    throw new DrupalUpdateException('The <a href="https://drupal.org/project/views">Views module</a> must be downloaded and available for Media updates to proceed.');
611
  }
612
}
613

    
614
/**
615
 * Empty update function to trigger cache clear.
616
 */
617
function media_update_7203() {
618
  // Do nothing.
619
}
620

    
621
/**
622
 * Update old Media view modes to the new File Entity ones.
623
 */
624
function media_update_7204() {
625
  $view_mode_updates = array(
626
    'media_preview' => 'preview',
627
    'media_small' => 'teaser',
628
    'media_large' => 'full',
629
  );
630

    
631
  // Update the media__wysiwyg_default_view_mode variable.
632
  $wysiwyg_default_view_mode = variable_get('media__wysiwyg_default_view_mode');
633
  if (isset($wysiwyg_default_view_mode) && isset($view_mode_updates[$wysiwyg_default_view_mode])) {
634
    $wysiwyg_default_view_mode = $view_mode_updates[$wysiwyg_default_view_mode];
635
    variable_set('media__wysiwyg_default_view_mode', $wysiwyg_default_view_mode);
636
  }
637

    
638
  // Update view mode references in the 'field_bundle_settings' variable.
639
  $field_bundle_settings = variable_get('field_bundle_settings');
640
  if (!empty($field_bundle_settings['file'])) {
641
    foreach ($field_bundle_settings['file'] as $file_type => $info) {
642
      // Per-bundle information about the view modes.
643
      foreach ($view_mode_updates as $old_view_mode => $new_view_mode) {
644
        if (isset($info['view_modes'][$old_view_mode])) {
645
          $field_bundle_settings['file'][$file_type]['view_modes'][$new_view_mode] = $info['view_modes'][$old_view_mode];
646
          unset($field_bundle_settings['file'][$file_type]['view_modes'][$old_view_mode]);
647
        }
648
        // The File Entity module defaults to not use custom settings for the
649
        // new view modes, but the Media module used to default to using custom
650
        // settings, so if this variable is not defined, use the prior default.
651
        if (!isset($field_bundle_settings['file'][$file_type]['view_modes'][$new_view_mode]['custom_settings'])) {
652
          $field_bundle_settings['file'][$file_type]['view_modes'][$new_view_mode]['custom_settings'] = TRUE;
653
        }
654
      }
655

    
656
      // Settings for the "extra fields" configured on the Manage Display page.
657
      if (!empty($info['extra_fields']['display'])) {
658
        foreach ($info['extra_fields']['display'] as $extra_field_name => $extra_field_info) {
659
          foreach ($view_mode_updates as $old_view_mode => $new_view_mode) {
660
            if (isset($extra_field_info[$old_view_mode])) {
661
              $field_bundle_settings['file'][$file_type]['extra_fields']['display'][$extra_field_name][$new_view_mode] = $extra_field_info[$old_view_mode];
662
              unset($field_bundle_settings['file'][$file_type]['extra_fields']['display'][$extra_field_name][$old_view_mode]);
663
            }
664
          }
665
        }
666
      }
667
    }
668
  }
669
  variable_set('field_bundle_settings', $field_bundle_settings);
670

    
671
  // Move settings for fields attached to files from the old view modes to the
672
  // new ones.
673
  $instances = field_read_instances(array('entity_type' => 'file'));
674
  foreach ($instances as $instance) {
675
    $updated = FALSE;
676
    foreach ($view_mode_updates as $old_view_mode => $new_view_mode) {
677
      if (isset($instance['display'][$old_view_mode])) {
678
        $instance['display'][$new_view_mode] = $instance['display'][$old_view_mode];
679
        unset($instance['display'][$old_view_mode]);
680
        $updated = TRUE;
681
      }
682
    }
683
    if ($updated) {
684
      field_update_instance($instance);
685
    }
686
  }
687

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

    
700
  // Update file/image/media fields that use a formatter that reference an old
701
  // file view modes to reference the new ones.
702
  foreach (field_read_instances() as $instance) {
703
    if (!empty($instance['display'])) {
704
      $updated = FALSE;
705
      foreach ($instance['display'] as $instance_view_mode => $display) {
706
        if (isset($display['settings']['file_view_mode']) && isset($view_mode_updates[$display['settings']['file_view_mode']])) {
707
          $instance['display'][$instance_view_mode]['settings']['file_view_mode'] = $view_mode_updates[$display['settings']['file_view_mode']];
708
          $updated = TRUE;
709
        }
710
      }
711
      if ($updated) {
712
        field_update_instance($instance);
713
      }
714
    }
715
  }
716

    
717
  // Update formatter settings that reference the old view modes within saved
718
  // Views.
719
  if (db_table_exists('views_display')) {
720
    $result = db_select('views_display', 'v')->fields('v', array('vid', 'id', 'display_options'))->execute();
721
    foreach ($result as $record) {
722
      if (!empty($record->display_options)) {
723
        $display_options = unserialize($record->display_options);
724
        if (_media_update_7204_update_views_display_options($display_options, $view_mode_updates)) {
725
          db_update('views_display')
726
            ->fields(array('display_options' => serialize($display_options)))
727
            ->condition('vid', $record->vid)
728
            ->condition('id', $record->id)
729
            ->execute();
730
        }
731
      }
732
    }
733
  }
734

    
735
  // Update formatter settings that reference the old view modes within unsaved
736
  // Views in the CTools object cache. Objects in the CTools cache are instances
737
  // of classes, so the Views module must be enabled to unserialize it
738
  // correctly.
739
  if (db_table_exists('ctools_object_cache') && module_exists('views')) {
740
    $result = db_select('ctools_object_cache', 'c')->fields('c', array('sid', 'name', 'obj', 'data'))->condition('obj', 'view')->execute();
741
    foreach ($result as $record) {
742
      $view = unserialize($record->data);
743
      if (!empty($view->display)) {
744
        $updated = FALSE;
745
        foreach ($view->display as $display_name => $display) {
746
          if (!empty($display->display_options) && _media_update_7204_update_views_display_options($display->display_options, $view_mode_updates)) {
747
            $updated = TRUE;
748
          }
749
        }
750
        if ($updated) {
751
          db_update('ctools_object_cache')
752
            ->fields(array('data' => serialize($view)))
753
            ->condition('sid', $record->sid)
754
            ->condition('name', $record->name)
755
            ->condition('obj', $record->obj)
756
            ->execute();
757
        }
758
      }
759
    }
760
  }
761

    
762
  // Clear caches that might contain stale Views displays.
763
  if (module_exists('views')) {
764
    cache_clear_all('*', 'cache_views', TRUE);
765
    cache_clear_all('*', 'cache_views_data', TRUE);
766
  }
767
  if (module_exists('block')) {
768
    cache_clear_all('*', 'cache_block', TRUE);
769
  }
770
  cache_clear_all('*', 'cache_page', TRUE);
771

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

    
779
/**
780
 * Drop the unused {media_list_type} table.
781
 */
782
function media_update_7205() {
783
  if (db_table_exists('media_list_type')) {
784
    db_drop_table('media_list_type');
785
    return t('Dropped the unused {media_list_type} table.');
786
  }
787
}
788

    
789
/**
790
 * Move default file display configurations to the database.
791
 */
792
function media_update_7206() {
793
  module_load_include('inc', 'file_entity', 'file_entity.file_api');
794
  module_load_include('inc', 'ctools', 'includes/export');
795
  $default_image_styles = array(
796
    'preview' => 'square_thumbnail',
797
    'teaser' => 'medium',
798
    'full' => 'large',
799
  );
800

    
801
  // Only needed by sites that updated from Media 1.x.
802
  // @see media_entity_info_alter()
803
  if (variable_get('media__show_deprecated_view_modes')) {
804
    $default_image_styles['media_original'] = '';
805
  }
806

    
807
  // Clear out the ctools cache so that the old default implementations
808
  // are removed.
809
  ctools_export_load_object_reset('file_display');
810
  foreach ($default_image_styles as $view_mode => $image_style) {
811
    $existing_displays = file_displays_load('image', $view_mode, TRUE);
812
    // Only insert default config into the database if no existing
813
    // configuration is found.
814
    if (!isset($existing_displays['file_image'])) {
815
      $display_name = 'image__' . $view_mode . '__file_image';
816
      $display = array(
817
        'api_version' => 1,
818
        'name' => $display_name,
819
        'status' => 1,
820
        'weight' => 5,
821
        'settings' => array('image_style' => $image_style),
822
        'export_type' => NULL,
823
      );
824
      file_display_save((object) $display);
825
    }
826
  }
827
}
828

    
829
/**
830
 * Trigger cache clear.
831
 *
832
 * Empty update function to trigger cache clear after changing access callbacks
833
 * to file_entity_access.
834
 */
835
function media_update_7207() {
836
  // Do nothing.
837
}
838

    
839
/**
840
 * Drop the media_types table and migrate files to file_entity types.
841
 */
842
function media_update_7208() {
843
  // Reset static cache to ensure our new file types are recognized
844
  drupal_static_reset('ctools_export_load_object_table_exists');
845

    
846
  if (!db_table_exists('media_type')) {
847
    // No types to migrate.
848
    return;
849
  }
850
  // @see http://drupal.org/node/1292382
851
  if (!function_exists('file_type_get_enabled_types')) {
852
    throw new DrupalUpdateException('The File Entity module needs to be upgraded before continuing.');
853
  }
854
  else {
855
    $existing_types = db_select('media_type', 'mt')
856
      ->orderBy('weight')
857
      ->fields('mt')
858
      ->execute()
859
      // Will key by the name field.
860
      ->fetchAllAssoc('name');
861
    foreach ($existing_types as &$type) {
862
      $type->type_callback_args = unserialize($type->type_callback_args);
863
    }
864

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

    
906
    // Special treatment for old media application type to new file_entity
907
    // document one. Add some more mimetypes to document.
908
    $document_type = file_type_load('document');
909
    if (!$document_type) {
910
      return;
911
    }
912
    foreach ($mapping['mimetypes'] as $mimetype) {
913
      $is_document = strpos($mimetype, 'document') !== FALSE || strpos($mimetype, 'application/vnd.ms-') !== FALSE;
914
      if ($is_document && !in_array($mimetype, $document_type->mimetypes)) {
915
        $document_type->mimetypes[] = $mimetype;
916
      }
917
    }
918
    file_type_save($document_type);
919
  }
920
}
921

    
922
/**
923
 * Enable the hidden media_migrate_file_types module to provide a UI to update
924
 * {file_managed}.type with the new file types provided by file_entity.
925
 */
926
function media_update_7209() {
927
  drupal_load('module', 'media_migrate_file_types');
928

    
929
  if (_media_migrate_file_types_get_migratable_file_types()) {
930
    module_enable(array('media_migrate_file_types'));
931
  }
932
}
933

    
934
/**
935
 * Delete deceprated media__type_icon_directory variable.
936
 */
937
function media_update_7210() {
938
  variable_del('media__type_icon_directory');
939
}
940

    
941
/**
942
 * Save a square_thumbnail image style in the database for legacy support if one
943
 * does not already exist.
944
 */
945
function media_update_7211() {
946
  $default_style = array(
947
    'name' => 'square_thumbnail'
948
  );
949

    
950
  // Clear the image cache to remove any old image styles that only exist in
951
  // code.
952
  cache_clear_all('image_styles', 'cache_image', TRUE);
953

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

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

    
965
    $effect = array(
966
      'name' => 'image_scale_and_crop',
967
      'data' => array(
968
        'width' => 100,
969
        'height' => 100,
970
        'weight' => 0,
971
      ),
972
      'isid' => $style['isid'],
973
    );
974

    
975
    image_effect_save($effect);
976
  }
977

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

    
981
/**
982
 * Utility function for update 7204. Updates display options within Views.
983
 */
984
function _media_update_7204_update_views_display_options(&$display_options, $view_mode_updates) {
985
  $updated = FALSE;
986

    
987
  // Update fields that use a formatter with a file_view_mode formatter setting.
988
  if (!empty($display_options['fields'])) {
989
    foreach ($display_options['fields'] as $field_name => $field_display) {
990
      if (isset($field_display['settings']['file_view_mode']) && isset($view_mode_updates[$field_display['settings']['file_view_mode']])) {
991
        $display_options['fields'][$field_name]['settings']['file_view_mode'] = $view_mode_updates[$field_display['settings']['file_view_mode']];
992
        $updated = TRUE;
993
      }
994
    }
995
  }
996

    
997
  // Update Views that display files directly using a row plugin with a view
998
  // mode setting.
999
  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']])) {
1000
    $display_options['row_options']['view_mode'] = $view_mode_updates[$display_options['row_options']['view_mode']];
1001
    $updated = TRUE;
1002
  }
1003
  return $updated;
1004
}
1005

    
1006
/**
1007
 * Re-create application file type for legacy reasons.
1008
 */
1009
function media_update_7212() {
1010
  module_load_include('inc', 'file_entity', 'file_entity.file_api');
1011
  if (!file_type_load('application')) {
1012
    $application = (object) array(
1013
      'api_version' => 1,
1014
      'type' => 'application',
1015
      'label' => t('Application'),
1016
      'description' => t('Multipurpose type - kept to support older sites.'),
1017
      'mimetypes' => array(),
1018
      'streams' => array(
1019
        'public',
1020
      ),
1021
    );
1022

    
1023
    file_type_save($application);
1024
    $application = file_type_load('application');
1025
    file_type_disable($application);
1026
  }
1027
}
1028

    
1029
/**
1030
 * Remove the obsolete file_extensions variable.
1031
 */
1032
function media_update_7213() {
1033
  $media_file_extensions = explode(' ', variable_get('media__file_extensions'));
1034
  $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'));
1035

    
1036
  // Preserve any custom file extensions.
1037
  if (array_diff($media_file_extensions, $file_entity_file_extensions)) {
1038
    $combined_file_extensions = array_unique(array_merge($file_entity_file_extensions, $media_file_extensions));
1039
    variable_set('file_entity_default_allowed_extensions', implode(' ' , $combined_file_extensions));
1040
  }
1041

    
1042
  variable_del('media__file_extensions');
1043
}
1044

    
1045
/**
1046
 * Drop the legacy {media_filter_usage} table.
1047
 */
1048
function media_update_7214() {
1049
  if (db_table_exists('media_filter_usage')) {
1050
    db_drop_table('media_filter_usage');
1051
  }
1052
}
1053

    
1054
/**
1055
 * Skipped to run media_update_7217().
1056
 */
1057
function media_update_7216() {
1058
  // Do nothing.
1059
}
1060

    
1061
/**
1062
 * Copy file type icons to public files directory.
1063
 */
1064
function media_update_7217() {
1065
  // Remove any trailing slashes from the icon base directory variable.
1066
  $dir = variable_get('media__icon_base_directory');
1067
  if (!empty($dir)) {
1068
    $dir = rtrim($dir, '/');
1069
    variable_set('media__icon_base_directory', $dir);
1070
  }
1071

    
1072
  try {
1073
    _media_install_copy_icons();
1074
  }
1075
  catch (Exception $e) {
1076
    throw new DrupalUpdateException($e->getMessage());
1077
  }
1078
}
1079

    
1080
/**
1081
 * Drop the legacy {cache_media_xml} table.
1082
 */
1083
function media_update_7218() {
1084
  if (db_table_exists('cache_media_xml')) {
1085
    db_drop_table('cache_media_xml');
1086
  }
1087

    
1088
  variable_del('media__xml_cache_expire');
1089
}
1090

    
1091
/**
1092
 * Enable the Media WYSIWYG submodule.
1093
 */
1094
function media_update_7219() {
1095
  if (module_exists('wysiwyg')) {
1096
    module_enable(array('media_wysiwyg'));
1097
  }
1098
}
1099

    
1100
/**
1101
 * Delete the deprecated media__file_list_size variable.
1102
 */
1103
function media_update_7220() {
1104
  variable_del('media__file_list_size');
1105
}
1106

    
1107
/**
1108
 * Enable the Media Bulk Upload submodule.
1109
 */
1110
function media_update_7221() {
1111
  if (module_exists('multiform') && module_exists('plupload')) {
1112
    module_enable(array('media_bulk_upload'));
1113
  }
1114
}
1115

    
1116
/**
1117
 * Delete the deprecated media__display_types_migration_mess variable.
1118
 */
1119
function media_update_7222() {
1120
  variable_del('media__display_types_migration_mess');
1121
}
1122

    
1123
/**
1124
 * Delete legacy variables.
1125
 */
1126
function media_update_7223() {
1127
  variable_del('media__max_filesize');
1128
  variable_del('media__debug');
1129
  variable_del('media__xml_cache_expire');
1130
  variable_del('media__show_file_type_rebuild_nag');
1131
  variable_del('media__field_select_media_text');
1132
  variable_del('media__field_remove_media_text');
1133
  variable_del('media__browser_library_empty_message');
1134
  variable_del('media__browser_pager_limit');
1135
  variable_del('media__browser_viewtype_default');
1136
}
1137

    
1138
/**
1139
 * Rename variables, removing variable namespace.
1140
 */
1141
function media_update_7224() {
1142
  // Create an array of variables sans 'media' prefix.
1143
  $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');
1144

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

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

    
1154
    // Remove the old variable.
1155
    variable_del('media__' . $variable);
1156
  }
1157
}
1158

    
1159
/**
1160
 * Migrate variables to appropriate submodules.
1161
 */
1162
function media_update_7225() {
1163
  $data = array(
1164
    'media_wysiwyg' => array(
1165
      'wysiwyg_title',
1166
      'wysiwyg_icon_title',
1167
      'wysiwyg_default_view_mode',
1168
      'wysiwyg_upload_directory',
1169
      'wysiwyg_allowed_types',
1170
      'wysiwyg_allowed_attributes',
1171
      'wysiwyg_browser_plugins',
1172
    ),
1173
    'media_internet' => array(
1174
      'fromurl_supported_schemes',
1175
    ),
1176
    'media_bulk_upload' => array(
1177
      'import_batch_size',
1178
    ),
1179
  );
1180

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

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

    
1194
      // Remove the old variable.
1195
      variable_del('media_' . $variable);
1196
    }
1197
  }
1198
}
1199

    
1200
/**
1201
 * Grant existing user access to new media browser permission.
1202
 */
1203
function media_update_7226() {
1204
  $roles = user_roles(FALSE, 'create files');
1205

    
1206
  foreach ($roles as $rid => $role) {
1207
    user_role_grant_permissions($rid, array('access media browser'));
1208
  }
1209
}
1210

    
1211
/**
1212
 * Make sure that the image style square_thumbnail is created.
1213
 */
1214
function media_update_7227() {
1215
  media_update_7211();
1216
}