Projet

Général

Profil

Paste
Télécharger (38,5 ko) Statistiques
| Branche: | Révision:

root / drupal7 / sites / all / modules / media / media.install @ ca0757b9

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_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
}
69

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

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

    
111
  if ($phase == 'update') {
112
    $info = system_get_info('module', 'file_entity');
113
    if (strpos($info['version'], '7.x-2') === FALSE) {
114
      $requirements['file_entity'] = array(
115
        'title' => $t('File entity 2.x'),
116
        'value' => $t('Wrong version'),
117
        'severity' => REQUIREMENT_ERROR,
118
        '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')),
119
      );
120
    }
121
  }
122

    
123
  return $requirements;
124
}
125

    
126
/**
127
 * Deprecated update function.
128
 */
129
function media_update_7000() {
130
}
131

    
132
/**
133
 * Deprecated update function.
134
 */
135
function media_update_7001() {
136
}
137

    
138
/**
139
 * Create the media_type table from the media_types variable.
140
 */
141
function media_update_7002() {
142
  $schema['media_type'] = array(
143
    'description' => 'Stores the settings for media types.',
144
    'fields' => array(
145
      'name' => array(
146
        'description' => 'The machine name of the media type.',
147
        'type' => 'varchar',
148
        'length' => 255,
149
        'not null' => TRUE,
150
        'default' => '',
151
      ),
152
      'label' => array(
153
        'description' => 'The label of the media type.',
154
        'type' => 'varchar',
155
        'length' => 255,
156
        'not null' => TRUE,
157
        'default' => '',
158
      ),
159
      'base' => array(
160
        'description' => 'If this is a base type (i.e. cannot be deleted)',
161
        'type' => 'int',
162
        'not null' => TRUE,
163
        'default' => 0,
164
        'size' => 'tiny',
165
      ),
166
      'weight' => array(
167
        'description' => 'Weight of media type. Determines which one wins when claiming a piece of media (first wins)',
168
        'type' => 'int',
169
        'not null' => TRUE,
170
        'default' => 0,
171
        'size' => 'normal',
172
      ),
173
      'type_callback' => array(
174
        'description' => 'Callback to determine if provided media is of this type.',
175
        'type' => 'varchar',
176
        'length' => 255,
177
        'not null' => FALSE,
178
        'default' => '',
179
      ),
180
      'type_callback_args' => array(
181
        'type' => 'text',
182
        'not null' => FALSE,
183
        'size' => 'big',
184
        'serialize' => TRUE,
185
        'description' => 'A serialized array of name value pairs that will be passed to the callback function',
186
      ),
187
    ),
188
    'primary key' => array('name'),
189
  );
190
  db_create_table('media_type', $schema['media_type']);
191

    
192
  drupal_load('module', 'media');
193
  $old_types = variable_get('media_types');
194
  foreach ($old_types as $type) {
195
    // Was an error in the original creation.
196
    if (isset($type->callbacks)) {
197
      unset($type->callbacks);
198
    }
199
    $type->name = $type->machine_name;
200
    unset($type->machine_name);
201
    db_merge('media_type')
202
      ->key(array('name' => $type->name))
203
      ->fields((array) $type)
204
      ->execute();
205
  }
206
  variable_del('media_types');
207
}
208

    
209
/**
210
 * We now prefix media namespaced variables with media__, so fix old variables.
211
 */
212
function media_update_7003() {
213
  drupal_load('module', 'media');
214
  foreach (media_variable_default() as $variable => $value) {
215
    if (($test = variable_get('media_' . $variable, TRUE)) == variable_get('media_' . $variable, FALSE)) {
216
      media_variable_set($variable, $test);
217
      variable_del('media_' . $variable);
218
    }
219
  }
220
}
221

    
222
/**
223
 * Empty update function to trigger a menu rebuild.
224
 */
225
function media_update_7004() {
226
}
227

    
228
/**
229
 * Deprecated update function.
230
 */
231
function media_update_7005() {
232
}
233

    
234
/**
235
 * Rename the file table to file_managed in case head2head was used.
236
 */
237
function media_update_7006() {
238
  if (db_table_exists('file') && !db_table_exists('file_managed')) {
239
    db_rename_table('file', 'file_managed');
240
  }
241
}
242

    
243
/**
244
 * Deprecated update function.
245
 */
246
function media_update_7007() {
247
}
248

    
249
/**
250
 * Empty function.
251
 */
252
function media_update_7008() {
253
}
254

    
255
/**
256
 * Deprecated update function.
257
 */
258
function media_update_7009() {
259
}
260

    
261
/**
262
 * Deprecated update function.
263
 */
264
function media_update_7010() {
265
}
266

    
267
/**
268
 * Empty update function.
269
 */
270
function media_update_7011() {
271
}
272

    
273
/**
274
 * Empty update function.
275
 */
276
function media_update_7012() {
277
}
278

    
279
/**
280
 * Work around a core bug where text format cacheability is not updated.
281
 *
282
 * @see http://drupal.org/node/993230
283
 */
284
function media_update_7013() {
285
  $formats = filter_formats();
286
  foreach ($formats as $format) {
287
    $format->filters = filter_list_format($format->format);
288
    // filter_format_save() expects filters to be an array, however
289
    // filter_list_format() gives us objects.
290
    foreach ($format->filters as $key => $value) {
291
      $format->filters[$key] = (array) $value;
292
    }
293
    filter_format_save($format);
294
  }
295
}
296

    
297
/**
298
 * Rename the media__dialog_get_theme_name variable to media__dialog_theme.
299
 */
300
function media_update_7014() {
301
  if ($old_value = variable_get('media__dialog_get_theme_name')) {
302
    variable_del('media__dialog_get_theme_name');
303
    variable_set('media__dialog_theme', $old_value);
304
  }
305
}
306

    
307
/**
308
 * Empty update function to trigger a registry rebuild.
309
 */
310
function media_update_7015() {
311
}
312

    
313
/**
314
 * Convert Media entities to File entities.
315
 *
316
 * This update function requires field_update_7002() to run before it since
317
 * the field_bundle_settings variable has been split into separate variables
318
 * per entity type and bundle.
319
 *
320
 * @see http://drupal.org/node/1418708
321
 * @see http://drupal.org/node/1211008
322
 */
323
function media_update_7016() {
324
  // Allow File Entity module to take over the {file_managed}.type field. It
325
  // will create new indexes as it needs to, but it doesn't know about old ones,
326
  // so delete them.
327
  if (db_index_exists('file_managed', 'file_type')) {
328
    db_drop_index('file_managed', 'file_type');
329
  }
330
  module_enable(array('file_entity'));
331

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

    
341
    // @todo Convert this to use _update_7000_field_read_fields()
342
    $fields = field_read_fields(array('id' => $instance['field_id']), array('include_inactive' => TRUE, 'include_deleted' => TRUE));
343
    $field = $fields[$instance['field_id']];
344

    
345
    // There is no API for updating the entity_type foreign key within field
346
    // data storage. We can do a direct db_update() for when the default SQL
347
    // storage back-end is being used, but must skip updating fields that use a
348
    // different storage type.
349
    if ($field['storage']['type'] !== 'field_sql_storage' || !module_exists('field_sql_storage') || !$field['storage']['active']) {
350
      $messages[] = t('Cannot update field %id (%field_name) because it does not use the field_sql_storage storage type.', array(
351
        '%id' => $field['id'],
352
        '%field_name' => $field['field_name'],
353
      ));
354
      continue;
355
    }
356

    
357
    // Update the data tables.
358
    $table_name = _field_sql_storage_tablename($field);
359
    $revision_name = _field_sql_storage_revision_tablename($field);
360
    db_update($table_name)
361
      ->fields(array('entity_type' => 'file'))
362
      ->condition('entity_type', 'media')
363
      ->condition('bundle', $instance['bundle'])
364
      ->execute();
365
    db_update($revision_name)
366
      ->fields(array('entity_type' => 'file'))
367
      ->condition('entity_type', 'media')
368
      ->condition('bundle', $instance['bundle'])
369
      ->execute();
370

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

    
379
  // Update the field_bundle_settings configuration variable: move media bundle
380
  // settings to file bundles, and move settings of the old self-referencing
381
  // file field to the new file pseudo-field.
382
  foreach ($instances as $instance) {
383
    if ($instance['field_name'] === 'file' && !$instance['deleted']) {
384
      $file_settings = field_bundle_settings('file', $instance['bundle']);
385
      $media_settings = field_bundle_settings('media', $instance['bundle']);
386
      $file_settings = array_merge($file_settings, $media_settings);
387
      if (isset($instance['widget']['weight'])) {
388
        $file_settings['extra_fields']['form']['file']['weight'] = $instance['widget']['weight'];
389
      }
390
      if (isset($instance['display'])) {
391
        foreach ($instance['display'] as $view_mode => $display) {
392
          if (isset($display['weight'])) {
393
            $file_settings['extra_fields']['display']['file'][$view_mode]['weight'] = $display['weight'];
394
          }
395
          if (isset($display['type'])) {
396
            $file_settings['extra_fields']['display']['file'][$view_mode]['visible'] = ($display['type'] != 'hidden');
397
          }
398
        }
399
      }
400
      field_bundle_settings('file', $instance['bundle'], $file_settings);
401
    }
402
  }
403
  // Delete old media bundle settings.
404
  db_delete('variable')
405
    ->condition('name', db_like('field_bundle_settings_media__') . '%', 'LIKE')
406
    ->execute();
407

    
408
  // Copy field formatter settings of old self-referencing file field to file
409
  // pseudo-field formatter settings.
410
  $file_displays = variable_get('file_displays', array());
411
  foreach ($instances as $instance) {
412
    if ($instance['field_name'] === 'file' && !$instance['deleted']) {
413
      if (isset($instance['display'])) {
414
        foreach ($instance['display'] as $view_mode => $display) {
415
          if (isset($display['type']) && $display['type'] != 'hidden') {
416
            $file_formatter = 'file_field_' . $display['type'];
417
            $file_displays[$instance['bundle']][$view_mode][$file_formatter]['status'] = TRUE;
418
            if (isset($display['settings'])) {
419
              $file_displays[$instance['bundle']][$view_mode][$file_formatter]['settings'] = $display['settings'];
420
            }
421
          }
422
        }
423
      }
424
    }
425
  }
426
  variable_set('file_displays', $file_displays);
427

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

    
436
  field_cache_clear();
437
}
438

    
439
/**
440
 * Move file display configuration.
441
 *
442
 * Move file display configurations from the 'file_displays' variable to the
443
 * {file_display} table.
444
 */
445
function media_update_7017() {
446
  // If the {file_display} table doesn't exist, then the File Entity module's
447
  // update functions will automatically take care of migrating the
448
  // configurations. However, if file_entity_update_7001() has already run
449
  // prior to media_update_7016(), run it again in order to capture those
450
  // configurations too.
451
  if (db_table_exists('file_display') && function_exists('file_entity_update_7001')) {
452
    module_load_include('install', 'file_entity', 'file_entity');
453
    file_entity_update_7001();
454
  }
455
}
456

    
457
/**
458
 * Empty update function to trigger a menu rebuild.
459
 */
460
function media_update_7018() {
461
}
462

    
463
/**
464
 * Update old view mode formaters.
465
 *
466
 * Update old per-view-mode media field formatters to the generic media
467
 * formatter with a setting.
468
 */
469
function media_update_7019() {
470
  $instances = array();
471
  $fields = field_read_fields(array('type' => 'media'), array('include_inactive' => TRUE));
472
  foreach ($fields as $field) {
473
    $instances = array_merge($instances, field_read_instances(array('field_id' => $field['id']), array('include_inactive' => TRUE)));
474
  }
475
  foreach ($instances as $instance) {
476
    $update_instance = FALSE;
477
    foreach ($instance['display'] as $view_mode => $display) {
478
      if (in_array($display['type'], array('media_link', 'media_preview', 'media_small', 'media_large', 'media_original'))) {
479
        $update_instance = TRUE;
480
        $instance['display'][$view_mode]['type'] = 'media';
481
        $instance['display'][$view_mode]['settings'] = array('file_view_mode' => $display['type']);
482
      }
483
    }
484
    if ($update_instance) {
485
      field_update_instance($instance);
486
    }
487
  }
488
}
489

    
490
/**
491
 * Delete the wysiwyg_allowed_types variable if it is the same as default.
492
 */
493
function media_update_7020() {
494
  if (variable_get('media__wysiwyg_allowed_types') == array('image', 'video')) {
495
    variable_del('media__wysiwyg_allowed_types');
496
  }
497
}
498

    
499
/**
500
 * Replace 'view media' perm from all users having the role with 'view file'.
501
 */
502
function media_update_7200() {
503
  $perms = user_permission_get_modules();
504
  if (!isset($perms['view files'])) {
505
    throw new DrupalUpdateException('The File Entity module needs to be upgraded before continuing.');
506
  }
507
  else {
508
    $roles = user_roles(FALSE, 'view media');
509
    $permissions = array(
510
      'view media' => FALSE,
511
      'view files' => TRUE,
512
    );
513
    foreach ($roles as $rid => $role) {
514
      user_role_change_permissions($rid, $permissions);
515
    }
516
    $roles = user_roles(FALSE, 'edit media');
517
    $permissions = array(
518
      'edit media' => FALSE,
519
      'edit any files' => TRUE,
520
    );
521
    if (function_exists('file_entity_list_permissions')) {
522
      unset($permissions['edit any files']);
523

    
524
      foreach (file_entity_permissions_get_configured_types() as $type) {
525
        $permissions += file_entity_list_permissions($type);
526
      }
527
    }
528
    foreach ($roles as $rid => $role) {
529
      user_role_change_permissions($rid, $permissions);
530
    }
531
    $roles = user_roles(FALSE, 'administer media');
532
    $permissions = array(
533
      'administer media' => FALSE,
534
      'administer files' => TRUE,
535
    );
536
    foreach ($roles as $rid => $role) {
537
      user_role_change_permissions($rid, $permissions);
538
    }
539
  }
540
}
541

    
542
/**
543
 * Handle existing media fields.
544
 *
545
 * Enable the new Media Field module if this site uses "media" fields. File
546
 * fields are now preferred for storing media.
547
 */
548
function media_update_7201() {
549
  $fields = field_info_fields();
550
  foreach ($fields as $field) {
551
    if ($field['type'] == 'media') {
552
      // This update function may run even if Media is not enabled. Don't enable
553
      // Media Field if its dependencies aren't already enabled.
554
      module_enable(array('mediafield'), FALSE);
555

    
556
      // Update entries in file_usage so that they are associated with Media
557
      // Field rather than Media.
558
      // @TODO This update function may conflict with
559
      // http://drupal.org/node/1268116
560
      db_update('file_usage')
561
        ->condition('module', 'media')
562
        ->fields(array('module' => 'mediafield'))
563
        ->execute();
564

    
565
      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.');
566
    }
567
  }
568
  return t('The "Media" field type has been moved to the new "Media Field" module. File fields can be used to store media.');
569
}
570

    
571
/**
572
 * Enable the Views module if it is not already enabled.
573
 */
574
function media_update_7202() {
575
  module_enable(array('views'));
576
  if (!module_exists('views')) {
577
    throw new DrupalUpdateException('The <a href="https://drupal.org/project/views">Views module</a> must be downloaded and available for Media updates to proceed.');
578
  }
579
}
580

    
581
/**
582
 * Empty update function to trigger cache clear.
583
 */
584
function media_update_7203() {
585
  // Do nothing.
586
}
587

    
588
/**
589
 * Update old Media view modes to the new File Entity ones.
590
 */
591
function media_update_7204() {
592
  $view_mode_updates = array(
593
    'media_preview' => 'preview',
594
    'media_small' => 'teaser',
595
    'media_large' => 'full',
596
  );
597

    
598
  // Update the media__wysiwyg_default_view_mode variable.
599
  $wysiwyg_default_view_mode = variable_get('media__wysiwyg_default_view_mode');
600
  if (isset($wysiwyg_default_view_mode) && isset($view_mode_updates[$wysiwyg_default_view_mode])) {
601
    $wysiwyg_default_view_mode = $view_mode_updates[$wysiwyg_default_view_mode];
602
    variable_set('media__wysiwyg_default_view_mode', $wysiwyg_default_view_mode);
603
  }
604

    
605
  // Update view mode references in the 'field_bundle_settings' variable.
606
  $field_bundle_settings = variable_get('field_bundle_settings');
607
  if (!empty($field_bundle_settings['file'])) {
608
    foreach ($field_bundle_settings['file'] as $file_type => $info) {
609
      // Per-bundle information about the view modes.
610
      foreach ($view_mode_updates as $old_view_mode => $new_view_mode) {
611
        if (isset($info['view_modes'][$old_view_mode])) {
612
          $field_bundle_settings['file'][$file_type]['view_modes'][$new_view_mode] = $info['view_modes'][$old_view_mode];
613
          unset($field_bundle_settings['file'][$file_type]['view_modes'][$old_view_mode]);
614
        }
615
        // The File Entity module defaults to not use custom settings for the
616
        // new view modes, but the Media module used to default to using custom
617
        // settings, so if this variable is not defined, use the prior default.
618
        if (!isset($field_bundle_settings['file'][$file_type]['view_modes'][$new_view_mode]['custom_settings'])) {
619
          $field_bundle_settings['file'][$file_type]['view_modes'][$new_view_mode]['custom_settings'] = TRUE;
620
        }
621
      }
622

    
623
      // Settings for the "extra fields" configured on the Manage Display page.
624
      if (!empty($info['extra_fields']['display'])) {
625
        foreach ($info['extra_fields']['display'] as $extra_field_name => $extra_field_info) {
626
          foreach ($view_mode_updates as $old_view_mode => $new_view_mode) {
627
            if (isset($extra_field_info[$old_view_mode])) {
628
              $field_bundle_settings['file'][$file_type]['extra_fields']['display'][$extra_field_name][$new_view_mode] = $extra_field_info[$old_view_mode];
629
              unset($field_bundle_settings['file'][$file_type]['extra_fields']['display'][$extra_field_name][$old_view_mode]);
630
            }
631
          }
632
        }
633
      }
634
    }
635
  }
636
  variable_set('field_bundle_settings', $field_bundle_settings);
637

    
638
  // Move settings for fields attached to files from the old view modes to the
639
  // new ones.
640
  $instances = field_read_instances(array('entity_type' => 'file'));
641
  foreach ($instances as $instance) {
642
    $updated = FALSE;
643
    foreach ($view_mode_updates as $old_view_mode => $new_view_mode) {
644
      if (isset($instance['display'][$old_view_mode])) {
645
        $instance['display'][$new_view_mode] = $instance['display'][$old_view_mode];
646
        unset($instance['display'][$old_view_mode]);
647
        $updated = TRUE;
648
      }
649
    }
650
    if ($updated) {
651
      field_update_instance($instance);
652
    }
653
  }
654

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

    
667
  // Update file/image/media fields that use a formatter that reference an old
668
  // file view modes to reference the new ones.
669
  foreach (field_read_instances() as $instance) {
670
    if (!empty($instance['display'])) {
671
      $updated = FALSE;
672
      foreach ($instance['display'] as $instance_view_mode => $display) {
673
        if (isset($display['settings']['file_view_mode']) && isset($view_mode_updates[$display['settings']['file_view_mode']])) {
674
          $instance['display'][$instance_view_mode]['settings']['file_view_mode'] = $view_mode_updates[$display['settings']['file_view_mode']];
675
          $updated = TRUE;
676
        }
677
      }
678
      if ($updated) {
679
        field_update_instance($instance);
680
      }
681
    }
682
  }
683

    
684
  // Update formatter settings that reference the old view modes within saved
685
  // Views.
686
  if (db_table_exists('views_display')) {
687
    $result = db_select('views_display', 'v')->fields('v', array('vid', 'id', 'display_options'))->execute();
688
    foreach ($result as $record) {
689
      if (!empty($record->display_options)) {
690
        $display_options = unserialize($record->display_options);
691
        if (_media_update_7204_update_views_display_options($display_options, $view_mode_updates)) {
692
          db_update('views_display')
693
            ->fields(array('display_options' => serialize($display_options)))
694
            ->condition('vid', $record->vid)
695
            ->condition('id', $record->id)
696
            ->execute();
697
        }
698
      }
699
    }
700
  }
701

    
702
  // Update formatter settings that reference the old view modes within unsaved
703
  // Views in the CTools object cache. Objects in the CTools cache are instances
704
  // of classes, so the Views module must be enabled to unserialize it
705
  // correctly.
706
  if (db_table_exists('ctools_object_cache') && module_exists('views')) {
707
    $result = db_select('ctools_object_cache', 'c')->fields('c', array('sid', 'name', 'obj', 'data'))->condition('obj', 'view')->execute();
708
    foreach ($result as $record) {
709
      $view = unserialize($record->data);
710
      if (!empty($view->display)) {
711
        $updated = FALSE;
712
        foreach ($view->display as $display_name => $display) {
713
          if (!empty($display->display_options) && _media_update_7204_update_views_display_options($display->display_options, $view_mode_updates)) {
714
            $updated = TRUE;
715
          }
716
        }
717
        if ($updated) {
718
          db_update('ctools_object_cache')
719
            ->fields(array('data' => serialize($view)))
720
            ->condition('sid', $record->sid)
721
            ->condition('name', $record->name)
722
            ->condition('obj', $record->obj)
723
            ->execute();
724
        }
725
      }
726
    }
727
  }
728

    
729
  // Clear caches that might contain stale Views displays.
730
  if (module_exists('views')) {
731
    cache_clear_all('*', 'cache_views', TRUE);
732
    cache_clear_all('*', 'cache_views_data', TRUE);
733
  }
734
  if (module_exists('block')) {
735
    cache_clear_all('*', 'cache_block', TRUE);
736
  }
737
  cache_clear_all('*', 'cache_page', TRUE);
738

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

    
746
/**
747
 * Drop the unused {media_list_type} table.
748
 */
749
function media_update_7205() {
750
  if (db_table_exists('media_list_type')) {
751
    db_drop_table('media_list_type');
752
    return t('Dropped the unused {media_list_type} table.');
753
  }
754
}
755

    
756
/**
757
 * Move default file display configurations to the database.
758
 */
759
function media_update_7206() {
760
  module_load_include('inc', 'file_entity', 'file_entity.file_api');
761
  module_load_include('inc', 'ctools', 'includes/export');
762
  $default_image_styles = array(
763
    'preview' => 'square_thumbnail',
764
    'teaser' => 'medium',
765
    'full' => 'large',
766
  );
767

    
768
  // Only needed by sites that updated from Media 1.x.
769
  // @see media_entity_info_alter()
770
  if (variable_get('media__show_deprecated_view_modes')) {
771
    $default_image_styles['media_original'] = '';
772
  }
773

    
774
  // Clear out the ctools cache so that the old default implementations
775
  // are removed.
776
  ctools_export_load_object_reset('file_display');
777
  foreach ($default_image_styles as $view_mode => $image_style) {
778
    $existing_displays = file_displays_load('image', $view_mode, TRUE);
779
    // Only insert default config into the database if no existing
780
    // configuration is found.
781
    if (!isset($existing_displays['file_image'])) {
782
      $display_name = 'image__' . $view_mode . '__file_image';
783
      $display = array(
784
        'api_version' => 1,
785
        'name' => $display_name,
786
        'status' => 1,
787
        'weight' => 5,
788
        'settings' => array('image_style' => $image_style),
789
        'export_type' => NULL,
790
      );
791
      file_display_save((object) $display);
792
    }
793
  }
794
}
795

    
796
/**
797
 * Trigger cache clear.
798
 *
799
 * Empty update function to trigger cache clear after changing access callbacks
800
 * to file_entity_access.
801
 */
802
function media_update_7207() {
803
  // Do nothing.
804
}
805

    
806
/**
807
 * Drop the media_types table and migrate files to file_entity types.
808
 */
809
function media_update_7208() {
810
  // Reset static cache to ensure our new file types are recognized
811
  drupal_static_reset('ctools_export_load_object_table_exists');
812

    
813
  if (!db_table_exists('media_type')) {
814
    // No types to migrate.
815
    return;
816
  }
817
  // @see http://drupal.org/node/1292382
818
  if (!function_exists('file_type_get_enabled_types')) {
819
    throw new DrupalUpdateException('The File Entity module needs to be upgraded before continuing.');
820
  }
821
  else {
822
    $existing_types = db_select('media_type', 'mt')
823
      ->orderBy('weight')
824
      ->fields('mt')
825
      ->execute()
826
      // Will key by the name field.
827
      ->fetchAllAssoc('name');
828
    foreach ($existing_types as &$type) {
829
      $type->type_callback_args = unserialize($type->type_callback_args);
830
    }
831

    
832
    include_once DRUPAL_ROOT . '/includes/file.mimetypes.inc';
833
    $mapping = file_mimetype_mapping();
834
    // We do not migrate this type, since there is no way to handle its weight.
835
    unset($existing_types['default']);
836
    foreach ($existing_types as $type) {
837
      $extensions = isset($type->type_callback_args['extensions']) ? $type->type_callback_args['extensions'] : array();
838
      $mimetypes = isset($type->type_callback_args['mimetypes']) ? $type->type_callback_args['mimetypes'] : array();
839
      // Add mimetypes by extensions.
840
      foreach ($extensions as $extension) {
841
        if (isset($mapping['extensions'][$extension])) {
842
          $type->mimetypes[] = $mapping['mimetypes'][$mapping['extensions'][$extension]];
843
        }
844
      }
845
      // Add rest mimetypes.
846
      foreach ($mimetypes as $mimetype) {
847
        // Mimetype is a regex pattern.
848
        foreach ($mapping['mimetypes'] as $mapping_mimetype) {
849
          if (preg_match($mimetype, $mapping_mimetype) && !in_array($mapping_mimetype, $type->mimetypes)) {
850
            $type->mimetypes[] = $mapping_mimetype;
851
          }
852
        }
853
      }
854
      $type->streams = isset($type->type_callback_args['streams']) ? $type->type_callback_args['streams'] : array();
855
      $type->type = $type->name;
856
      // Merge existing type with new ones.
857
      if ($new_type = file_type_load($type->name)) {
858
        $new_type->mimetypes = array_merge($type->mimetypes, $new_type->mimetypes);
859
        $new_type->streams = array_merge($type->streams, $new_type->streams);
860
      }
861
      else {
862
        $new_type = $type;
863
      }
864
      file_type_save($new_type);
865
    }
866
    db_drop_table('media_type');
867

    
868
    // Special treatment for old media application type to new file_entity
869
    // document one. Add some more mimetypes to document.
870
    $document_type = file_type_load('document');
871
    if (!$document_type) {
872
      return;
873
    }
874
    foreach ($mapping['mimetypes'] as $mimetype) {
875
      $is_document = strpos($mimetype, 'document') !== FALSE || strpos($mimetype, 'application/vnd.ms-') !== FALSE;
876
      if ($is_document && !in_array($mimetype, $document_type->mimetypes)) {
877
        $document_type->mimetypes[] = $mimetype;
878
      }
879
    }
880
    file_type_save($document_type);
881
  }
882
}
883

    
884
/**
885
 * Enable the hidden media_migrate_file_types module to provide a UI to update
886
 * {file_managed}.type with the new file types provided by file_entity.
887
 */
888
function media_update_7209() {
889
  drupal_load('module', 'media_migrate_file_types');
890

    
891
  if (_media_migrate_file_types_get_migratable_file_types()) {
892
    module_enable(array('media_migrate_file_types'));
893
  }
894
}
895

    
896
/**
897
 * Delete deceprated media__type_icon_directory variable.
898
 */
899
function media_update_7210() {
900
  variable_del('media__type_icon_directory');
901
}
902

    
903
/**
904
 * Save a square_thumbnail image style in the database for legacy support if one
905
 * does not already exist.
906
 */
907
function media_update_7211() {
908
  $default_style = array(
909
    'name' => 'square_thumbnail'
910
  );
911

    
912
  // Clear the image cache to remove any old image styles that only exist in
913
  // code.
914
  cache_clear_all('*', 'cache_image', TRUE);
915

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

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

    
927
    $effect = array(
928
      'name' => 'image_scale_and_crop',
929
      'data' => array(
930
        'width' => 180,
931
        'height' => 180,
932
        'weight' => 0,
933
      ),
934
      'isid' => $style['isid'],
935
    );
936

    
937
    image_effect_save($effect);
938
  }
939

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

    
943
/**
944
 * Utility function for update 7204. Updates display options within Views.
945
 */
946
function _media_update_7204_update_views_display_options(&$display_options, $view_mode_updates) {
947
  $updated = FALSE;
948

    
949
  // Update fields that use a formatter with a file_view_mode formatter setting.
950
  if (!empty($display_options['fields'])) {
951
    foreach ($display_options['fields'] as $field_name => $field_display) {
952
      if (isset($field_display['settings']['file_view_mode']) && isset($view_mode_updates[$field_display['settings']['file_view_mode']])) {
953
        $display_options['fields'][$field_name]['settings']['file_view_mode'] = $view_mode_updates[$field_display['settings']['file_view_mode']];
954
        $updated = TRUE;
955
      }
956
    }
957
  }
958

    
959
  // Update Views that display files directly using a row plugin with a view
960
  // mode setting.
961
  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']])) {
962
    $display_options['row_options']['view_mode'] = $view_mode_updates[$display_options['row_options']['view_mode']];
963
    $updated = TRUE;
964
  }
965
  return $updated;
966
}
967

    
968
/**
969
 * Re-create application file type for legacy reasons.
970
 */
971
function media_update_7212() {
972
  module_load_include('inc', 'file_entity', 'file_entity.file_api');
973
  if (!file_type_load('application')) {
974
    $application = (object) array(
975
      'api_version' => 1,
976
      'type' => 'application',
977
      'label' => t('Application'),
978
      'description' => t('Multipurpose type - kept to support older sites.'),
979
      'mimetypes' => array(),
980
      'streams' => array(
981
        'public',
982
      ),
983
    );
984

    
985
    file_type_save($application);
986
    $application = file_type_load('application');
987
    file_type_disable($application);
988
  }
989
}
990

    
991
/**
992
 * Remove the obsolete file_extensions variable.
993
 */
994
function media_update_7213() {
995
  $media_file_extensions = explode(' ', variable_get('media__file_extensions'));
996
  $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'));
997

    
998
  // Preserve any custom file extensions.
999
  if (array_diff($media_file_extensions, $file_entity_file_extensions)) {
1000
    $combined_file_extensions = array_unique(array_merge($file_entity_file_extensions, $media_file_extensions));
1001
    variable_set('file_entity_default_allowed_extensions', implode(' ' , $combined_file_extensions));
1002
  }
1003

    
1004
  variable_del('media__file_extensions');
1005
}
1006

    
1007
/**
1008
 * Drop the legacy {media_filter_usage} table.
1009
 */
1010
function media_update_7214() {
1011
  if (db_table_exists('media_filter_usage')) {
1012
    db_drop_table('media_filter_usage');
1013
  }
1014
}
1015

    
1016
/**
1017
 * Skipped to run media_update_7217().
1018
 */
1019
function media_update_7216() {
1020
  // Do nothing.
1021
}
1022

    
1023
/**
1024
 * Copy file type icons to public files directory.
1025
 */
1026
function media_update_7217() {
1027
  // Remove any trailing slashes from the icon base directory variable.
1028
  $dir = variable_get('media__icon_base_directory');
1029
  if (!empty($dir)) {
1030
    $dir = rtrim($dir, '/');
1031
    variable_set('media__icon_base_directory', $dir);
1032
  }
1033

    
1034
  try {
1035
    _media_install_copy_icons();
1036
  }
1037
  catch (Exception $e) {
1038
    throw new DrupalUpdateException($e->getMessage());
1039
  }
1040
}
1041

    
1042
/**
1043
 * Drop the legacy {cache_media_xml} table.
1044
 */
1045
function media_update_7218() {
1046
  if (db_table_exists('cache_media_xml')) {
1047
    db_drop_table('cache_media_xml');
1048
  }
1049

    
1050
  variable_del('media__xml_cache_expire');
1051
}
1052

    
1053
/**
1054
 * Enable the Media WYSIWYG submodule.
1055
 */
1056
function media_update_7219() {
1057
  if (module_exists('wysiwyg')) {
1058
    module_enable(array('media_wysiwyg'));
1059
  }
1060
}
1061

    
1062
/**
1063
 * Delete the deprecated media__file_list_size variable.
1064
 */
1065
function media_update_7220() {
1066
  variable_del('media__file_list_size');
1067
}
1068

    
1069
/**
1070
 * Enable the Media Bulk Upload submodule.
1071
 */
1072
function media_update_7221() {
1073
  if (module_exists('multiform') && module_exists('plupload')) {
1074
    module_enable(array('media_bulk_upload'));
1075
  }
1076
}
1077

    
1078
/**
1079
 * Delete the deprecated media__display_types_migration_mess variable.
1080
 */
1081
function media_update_7222() {
1082
  variable_del('media__display_types_migration_mess');
1083
}
1084

    
1085
/**
1086
 * Delete legacy variables.
1087
 */
1088
function media_update_7223() {
1089
  variable_del('media__max_filesize');
1090
  variable_del('media__debug');
1091
  variable_del('media__xml_cache_expire');
1092
  variable_del('media__show_file_type_rebuild_nag');
1093
  variable_del('media__field_select_media_text');
1094
  variable_del('media__field_remove_media_text');
1095
  variable_del('media__browser_library_empty_message');
1096
  variable_del('media__browser_pager_limit');
1097
  variable_del('media__browser_viewtype_default');
1098
}
1099

    
1100
/**
1101
 * Rename variables, removing variable namespace.
1102
 */
1103
function media_update_7224() {
1104
  // Create an array of variables sans 'media' prefix.
1105
  $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');
1106

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

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

    
1116
    // Remove the old variable.
1117
    variable_del('media__' . $variable);
1118
  }
1119
}
1120

    
1121
/**
1122
 * Migrate variables to appropriate submodules.
1123
 */
1124
function media_update_7225() {
1125
  $data = array(
1126
    'media_wysiwyg' => array(
1127
      'wysiwyg_title',
1128
      'wysiwyg_icon_title',
1129
      'wysiwyg_default_view_mode',
1130
      'wysiwyg_upload_directory',
1131
      'wysiwyg_allowed_types',
1132
      'wysiwyg_allowed_attributes',
1133
      'wysiwyg_browser_plugins',
1134
    ),
1135
    'media_internet' => array(
1136
      'fromurl_supported_schemes',
1137
    ),
1138
    'media_bulk_upload' => array(
1139
      'import_batch_size',
1140
    ),
1141
  );
1142

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

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

    
1156
      // Remove the old variable.
1157
      variable_del('media_' . $variable);
1158
    }
1159
  }
1160
}
1161

    
1162
/**
1163
 * Accommodate the introduction of a new permission which restricts access to
1164
 * the media browser by granting it to existing users who were able to access
1165
 * it.
1166
 */
1167
function media_update_7226() {
1168
  $roles = user_roles(FALSE, 'create files');
1169

    
1170
  foreach ($roles as $rid => $role) {
1171
    user_role_grant_permissions($rid, array('access media browser'));
1172
  }
1173
}