Projet

Général

Profil

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

root / drupal7 / sites / all / modules / media / media.install @ 2b3c8cc1

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 can't
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
  if (db_table_exists('media_type')) {
143
    return;
144
  }
145

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

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

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

    
226
/**
227
 * Empty update function to trigger a menu rebuild.
228
 */
229
function media_update_7004() {
230
}
231

    
232
/**
233
 * Deprecated update function.
234
 */
235
function media_update_7005() {
236
}
237

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

    
247
/**
248
 * Deprecated update function.
249
 */
250
function media_update_7007() {
251
}
252

    
253
/**
254
 * Empty function.
255
 */
256
function media_update_7008() {
257
}
258

    
259
/**
260
 * Deprecated update function.
261
 */
262
function media_update_7009() {
263
}
264

    
265
/**
266
 * Deprecated update function.
267
 */
268
function media_update_7010() {
269
}
270

    
271
/**
272
 * Empty update function.
273
 */
274
function media_update_7011() {
275
}
276

    
277
/**
278
 * Empty update function.
279
 */
280
function media_update_7012() {
281
}
282

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

    
301
/**
302
 * Rename the media__dialog_get_theme_name variable to media__dialog_theme.
303
 */
304
function media_update_7014() {
305
  if ($old_value = variable_get('media__dialog_get_theme_name')) {
306
    variable_del('media__dialog_get_theme_name');
307
    variable_set('media__dialog_theme', $old_value);
308
  }
309
}
310

    
311
/**
312
 * Empty update function to trigger a registry rebuild.
313
 */
314
function media_update_7015() {
315
}
316

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

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

    
345
    // @todo Convert this to use _update_7000_field_read_fields()
346
    $fields = field_read_fields(array('id' => $instance['field_id']), array('include_inactive' => TRUE, 'include_deleted' => TRUE));
347
    $field = $fields[$instance['field_id']];
348

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

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

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

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

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

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

    
440
  field_cache_clear();
441
}
442

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

    
461
/**
462
 * Empty update function to trigger a menu rebuild.
463
 */
464
function media_update_7018() {
465
}
466

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

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

    
503
/**
504
 * Rerun media_update_7002() due to a typo that would prevent table creation.
505
 */
506
function media_update_7021() {
507
  media_update_7002();
508
}
509

    
510
/**
511
 * Replace 'view media' perm from all users having the role with 'view file'.
512
 */
513
function media_update_7200() {
514
  $perms = user_permission_get_modules();
515
  if (!isset($perms['view files'])) {
516
    throw new DrupalUpdateException('The File Entity module needs to be upgraded before continuing.');
517
  }
518
  else {
519
    $roles = user_roles(FALSE, 'view media');
520
    $permissions = array(
521
      'view media' => FALSE,
522
      'view files' => TRUE,
523
    );
524
    foreach ($roles as $rid => $role) {
525
      user_role_change_permissions($rid, $permissions);
526
    }
527
    $roles = user_roles(FALSE, 'edit media');
528
    $permissions = array(
529
      'edit media' => FALSE,
530
      'edit any files' => TRUE,
531
    );
532
    if (function_exists('file_entity_list_permissions')) {
533
      unset($permissions['edit any files']);
534

    
535
      foreach (file_entity_permissions_get_configured_types() as $type) {
536
        $permissions += file_entity_list_permissions($type);
537
      }
538
    }
539
    foreach ($roles as $rid => $role) {
540
      user_role_change_permissions($rid, $permissions);
541
    }
542
    $roles = user_roles(FALSE, 'administer media');
543
    $permissions = array(
544
      'administer media' => FALSE,
545
      'administer files' => TRUE,
546
    );
547
    foreach ($roles as $rid => $role) {
548
      user_role_change_permissions($rid, $permissions);
549
    }
550
  }
551
}
552

    
553
/**
554
 * Handle existing media fields.
555
 *
556
 * Enable the new Media Field module if this site uses "media" fields. File
557
 * fields are now preferred for storing media.
558
 */
559
function media_update_7201() {
560
  $fields = field_info_fields();
561
  foreach ($fields as $field) {
562
    if ($field['type'] == 'media') {
563
      // This update function may run even if Media is not enabled. Don't enable
564
      // Media Field if its dependencies aren't already enabled.
565
      module_enable(array('mediafield'), FALSE);
566

    
567
      // Update entries in file_usage so that they are associated with Media
568
      // Field rather than Media.
569
      // @TODO This update function may conflict with
570
      // http://drupal.org/node/1268116
571
      db_update('file_usage')
572
        ->condition('module', 'media')
573
        ->fields(array('module' => 'mediafield'))
574
        ->execute();
575

    
576
      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.');
577
    }
578
  }
579
  return t('The "Media" field type has been moved to the new "Media Field" module. File fields can be used to store media.');
580
}
581

    
582
/**
583
 * Enable the Views module if it is not already enabled.
584
 */
585
function media_update_7202() {
586
  module_enable(array('views'));
587
  if (!module_exists('views')) {
588
    throw new DrupalUpdateException('The <a href="https://drupal.org/project/views">Views module</a> must be downloaded and available for Media updates to proceed.');
589
  }
590
}
591

    
592
/**
593
 * Empty update function to trigger cache clear.
594
 */
595
function media_update_7203() {
596
  // Do nothing.
597
}
598

    
599
/**
600
 * Update old Media view modes to the new File Entity ones.
601
 */
602
function media_update_7204() {
603
  $view_mode_updates = array(
604
    'media_preview' => 'preview',
605
    'media_small' => 'teaser',
606
    'media_large' => 'full',
607
  );
608

    
609
  // Update the media__wysiwyg_default_view_mode variable.
610
  $wysiwyg_default_view_mode = variable_get('media__wysiwyg_default_view_mode');
611
  if (isset($wysiwyg_default_view_mode) && isset($view_mode_updates[$wysiwyg_default_view_mode])) {
612
    $wysiwyg_default_view_mode = $view_mode_updates[$wysiwyg_default_view_mode];
613
    variable_set('media__wysiwyg_default_view_mode', $wysiwyg_default_view_mode);
614
  }
615

    
616
  // Update view mode references in the 'field_bundle_settings' variable.
617
  $field_bundle_settings = variable_get('field_bundle_settings');
618
  if (!empty($field_bundle_settings['file'])) {
619
    foreach ($field_bundle_settings['file'] as $file_type => $info) {
620
      // Per-bundle information about the view modes.
621
      foreach ($view_mode_updates as $old_view_mode => $new_view_mode) {
622
        if (isset($info['view_modes'][$old_view_mode])) {
623
          $field_bundle_settings['file'][$file_type]['view_modes'][$new_view_mode] = $info['view_modes'][$old_view_mode];
624
          unset($field_bundle_settings['file'][$file_type]['view_modes'][$old_view_mode]);
625
        }
626
        // The File Entity module defaults to not use custom settings for the
627
        // new view modes, but the Media module used to default to using custom
628
        // settings, so if this variable is not defined, use the prior default.
629
        if (!isset($field_bundle_settings['file'][$file_type]['view_modes'][$new_view_mode]['custom_settings'])) {
630
          $field_bundle_settings['file'][$file_type]['view_modes'][$new_view_mode]['custom_settings'] = TRUE;
631
        }
632
      }
633

    
634
      // Settings for the "extra fields" configured on the Manage Display page.
635
      if (!empty($info['extra_fields']['display'])) {
636
        foreach ($info['extra_fields']['display'] as $extra_field_name => $extra_field_info) {
637
          foreach ($view_mode_updates as $old_view_mode => $new_view_mode) {
638
            if (isset($extra_field_info[$old_view_mode])) {
639
              $field_bundle_settings['file'][$file_type]['extra_fields']['display'][$extra_field_name][$new_view_mode] = $extra_field_info[$old_view_mode];
640
              unset($field_bundle_settings['file'][$file_type]['extra_fields']['display'][$extra_field_name][$old_view_mode]);
641
            }
642
          }
643
        }
644
      }
645
    }
646
  }
647
  variable_set('field_bundle_settings', $field_bundle_settings);
648

    
649
  // Move settings for fields attached to files from the old view modes to the
650
  // new ones.
651
  $instances = field_read_instances(array('entity_type' => 'file'));
652
  foreach ($instances as $instance) {
653
    $updated = FALSE;
654
    foreach ($view_mode_updates as $old_view_mode => $new_view_mode) {
655
      if (isset($instance['display'][$old_view_mode])) {
656
        $instance['display'][$new_view_mode] = $instance['display'][$old_view_mode];
657
        unset($instance['display'][$old_view_mode]);
658
        $updated = TRUE;
659
      }
660
    }
661
    if ($updated) {
662
      field_update_instance($instance);
663
    }
664
  }
665

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

    
678
  // Update file/image/media fields that use a formatter that reference an old
679
  // file view modes to reference the new ones.
680
  foreach (field_read_instances() as $instance) {
681
    if (!empty($instance['display'])) {
682
      $updated = FALSE;
683
      foreach ($instance['display'] as $instance_view_mode => $display) {
684
        if (isset($display['settings']['file_view_mode']) && isset($view_mode_updates[$display['settings']['file_view_mode']])) {
685
          $instance['display'][$instance_view_mode]['settings']['file_view_mode'] = $view_mode_updates[$display['settings']['file_view_mode']];
686
          $updated = TRUE;
687
        }
688
      }
689
      if ($updated) {
690
        field_update_instance($instance);
691
      }
692
    }
693
  }
694

    
695
  // Update formatter settings that reference the old view modes within saved
696
  // Views.
697
  if (db_table_exists('views_display')) {
698
    $result = db_select('views_display', 'v')->fields('v', array('vid', 'id', 'display_options'))->execute();
699
    foreach ($result as $record) {
700
      if (!empty($record->display_options)) {
701
        $display_options = unserialize($record->display_options);
702
        if (_media_update_7204_update_views_display_options($display_options, $view_mode_updates)) {
703
          db_update('views_display')
704
            ->fields(array('display_options' => serialize($display_options)))
705
            ->condition('vid', $record->vid)
706
            ->condition('id', $record->id)
707
            ->execute();
708
        }
709
      }
710
    }
711
  }
712

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

    
740
  // Clear caches that might contain stale Views displays.
741
  if (module_exists('views')) {
742
    cache_clear_all('*', 'cache_views', TRUE);
743
    cache_clear_all('*', 'cache_views_data', TRUE);
744
  }
745
  if (module_exists('block')) {
746
    cache_clear_all('*', 'cache_block', TRUE);
747
  }
748
  cache_clear_all('*', 'cache_page', TRUE);
749

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

    
757
/**
758
 * Drop the unused {media_list_type} table.
759
 */
760
function media_update_7205() {
761
  if (db_table_exists('media_list_type')) {
762
    db_drop_table('media_list_type');
763
    return t('Dropped the unused {media_list_type} table.');
764
  }
765
}
766

    
767
/**
768
 * Move default file display configurations to the database.
769
 */
770
function media_update_7206() {
771
  module_load_include('inc', 'file_entity', 'file_entity.file_api');
772
  module_load_include('inc', 'ctools', 'includes/export');
773
  $default_image_styles = array(
774
    'preview' => 'square_thumbnail',
775
    'teaser' => 'medium',
776
    'full' => 'large',
777
  );
778

    
779
  // Only needed by sites that updated from Media 1.x.
780
  // @see media_entity_info_alter()
781
  if (variable_get('media__show_deprecated_view_modes')) {
782
    $default_image_styles['media_original'] = '';
783
  }
784

    
785
  // Clear out the ctools cache so that the old default implementations
786
  // are removed.
787
  ctools_export_load_object_reset('file_display');
788
  foreach ($default_image_styles as $view_mode => $image_style) {
789
    $existing_displays = file_displays_load('image', $view_mode, TRUE);
790
    // Only insert default config into the database if no existing
791
    // configuration is found.
792
    if (!isset($existing_displays['file_image'])) {
793
      $display_name = 'image__' . $view_mode . '__file_image';
794
      $display = array(
795
        'api_version' => 1,
796
        'name' => $display_name,
797
        'status' => 1,
798
        'weight' => 5,
799
        'settings' => array('image_style' => $image_style),
800
        'export_type' => NULL,
801
      );
802
      file_display_save((object) $display);
803
    }
804
  }
805
}
806

    
807
/**
808
 * Trigger cache clear.
809
 *
810
 * Empty update function to trigger cache clear after changing access callbacks
811
 * to file_entity_access.
812
 */
813
function media_update_7207() {
814
  // Do nothing.
815
}
816

    
817
/**
818
 * Drop the media_types table and migrate files to file_entity types.
819
 */
820
function media_update_7208() {
821
  // Reset static cache to ensure our new file types are recognized
822
  drupal_static_reset('ctools_export_load_object_table_exists');
823

    
824
  if (!db_table_exists('media_type')) {
825
    // No types to migrate.
826
    return;
827
  }
828
  // @see http://drupal.org/node/1292382
829
  if (!function_exists('file_type_get_enabled_types')) {
830
    throw new DrupalUpdateException('The File Entity module needs to be upgraded before continuing.');
831
  }
832
  else {
833
    $existing_types = db_select('media_type', 'mt')
834
      ->orderBy('weight')
835
      ->fields('mt')
836
      ->execute()
837
      // Will key by the name field.
838
      ->fetchAllAssoc('name');
839
    foreach ($existing_types as &$type) {
840
      $type->type_callback_args = unserialize($type->type_callback_args);
841
    }
842

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

    
879
    // Special treatment for old media application type to new file_entity
880
    // document one. Add some more mimetypes to document.
881
    $document_type = file_type_load('document');
882
    if (!$document_type) {
883
      return;
884
    }
885
    foreach ($mapping['mimetypes'] as $mimetype) {
886
      $is_document = strpos($mimetype, 'document') !== FALSE || strpos($mimetype, 'application/vnd.ms-') !== FALSE;
887
      if ($is_document && !in_array($mimetype, $document_type->mimetypes)) {
888
        $document_type->mimetypes[] = $mimetype;
889
      }
890
    }
891
    file_type_save($document_type);
892
  }
893
}
894

    
895
/**
896
 * Enable the hidden media_migrate_file_types module to provide a UI to update
897
 * {file_managed}.type with the new file types provided by file_entity.
898
 */
899
function media_update_7209() {
900
  drupal_load('module', 'media_migrate_file_types');
901

    
902
  if (_media_migrate_file_types_get_migratable_file_types()) {
903
    module_enable(array('media_migrate_file_types'));
904
  }
905
}
906

    
907
/**
908
 * Delete deceprated media__type_icon_directory variable.
909
 */
910
function media_update_7210() {
911
  variable_del('media__type_icon_directory');
912
}
913

    
914
/**
915
 * Save a square_thumbnail image style in the database for legacy support if one
916
 * does not already exist.
917
 */
918
function media_update_7211() {
919
  $default_style = array(
920
    'name' => 'square_thumbnail'
921
  );
922

    
923
  // Clear the image cache to remove any old image styles that only exist in
924
  // code.
925
  cache_clear_all('*', 'cache_image', TRUE);
926

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

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

    
938
    $effect = array(
939
      'name' => 'image_scale_and_crop',
940
      'data' => array(
941
        'width' => 180,
942
        'height' => 180,
943
        'weight' => 0,
944
      ),
945
      'isid' => $style['isid'],
946
    );
947

    
948
    image_effect_save($effect);
949
  }
950

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

    
954
/**
955
 * Utility function for update 7204. Updates display options within Views.
956
 */
957
function _media_update_7204_update_views_display_options(&$display_options, $view_mode_updates) {
958
  $updated = FALSE;
959

    
960
  // Update fields that use a formatter with a file_view_mode formatter setting.
961
  if (!empty($display_options['fields'])) {
962
    foreach ($display_options['fields'] as $field_name => $field_display) {
963
      if (isset($field_display['settings']['file_view_mode']) && isset($view_mode_updates[$field_display['settings']['file_view_mode']])) {
964
        $display_options['fields'][$field_name]['settings']['file_view_mode'] = $view_mode_updates[$field_display['settings']['file_view_mode']];
965
        $updated = TRUE;
966
      }
967
    }
968
  }
969

    
970
  // Update Views that display files directly using a row plugin with a view
971
  // mode setting.
972
  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']])) {
973
    $display_options['row_options']['view_mode'] = $view_mode_updates[$display_options['row_options']['view_mode']];
974
    $updated = TRUE;
975
  }
976
  return $updated;
977
}
978

    
979
/**
980
 * Re-create application file type for legacy reasons.
981
 */
982
function media_update_7212() {
983
  module_load_include('inc', 'file_entity', 'file_entity.file_api');
984
  if (!file_type_load('application')) {
985
    $application = (object) array(
986
      'api_version' => 1,
987
      'type' => 'application',
988
      'label' => t('Application'),
989
      'description' => t('Multipurpose type - kept to support older sites.'),
990
      'mimetypes' => array(),
991
      'streams' => array(
992
        'public',
993
      ),
994
    );
995

    
996
    file_type_save($application);
997
    $application = file_type_load('application');
998
    file_type_disable($application);
999
  }
1000
}
1001

    
1002
/**
1003
 * Remove the obsolete file_extensions variable.
1004
 */
1005
function media_update_7213() {
1006
  $media_file_extensions = explode(' ', variable_get('media__file_extensions'));
1007
  $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'));
1008

    
1009
  // Preserve any custom file extensions.
1010
  if (array_diff($media_file_extensions, $file_entity_file_extensions)) {
1011
    $combined_file_extensions = array_unique(array_merge($file_entity_file_extensions, $media_file_extensions));
1012
    variable_set('file_entity_default_allowed_extensions', implode(' ' , $combined_file_extensions));
1013
  }
1014

    
1015
  variable_del('media__file_extensions');
1016
}
1017

    
1018
/**
1019
 * Drop the legacy {media_filter_usage} table.
1020
 */
1021
function media_update_7214() {
1022
  if (db_table_exists('media_filter_usage')) {
1023
    db_drop_table('media_filter_usage');
1024
  }
1025
}
1026

    
1027
/**
1028
 * Skipped to run media_update_7217().
1029
 */
1030
function media_update_7216() {
1031
  // Do nothing.
1032
}
1033

    
1034
/**
1035
 * Copy file type icons to public files directory.
1036
 */
1037
function media_update_7217() {
1038
  // Remove any trailing slashes from the icon base directory variable.
1039
  $dir = variable_get('media__icon_base_directory');
1040
  if (!empty($dir)) {
1041
    $dir = rtrim($dir, '/');
1042
    variable_set('media__icon_base_directory', $dir);
1043
  }
1044

    
1045
  try {
1046
    _media_install_copy_icons();
1047
  }
1048
  catch (Exception $e) {
1049
    throw new DrupalUpdateException($e->getMessage());
1050
  }
1051
}
1052

    
1053
/**
1054
 * Drop the legacy {cache_media_xml} table.
1055
 */
1056
function media_update_7218() {
1057
  if (db_table_exists('cache_media_xml')) {
1058
    db_drop_table('cache_media_xml');
1059
  }
1060

    
1061
  variable_del('media__xml_cache_expire');
1062
}
1063

    
1064
/**
1065
 * Enable the Media WYSIWYG submodule.
1066
 */
1067
function media_update_7219() {
1068
  if (module_exists('wysiwyg')) {
1069
    module_enable(array('media_wysiwyg'));
1070
  }
1071
}
1072

    
1073
/**
1074
 * Delete the deprecated media__file_list_size variable.
1075
 */
1076
function media_update_7220() {
1077
  variable_del('media__file_list_size');
1078
}
1079

    
1080
/**
1081
 * Enable the Media Bulk Upload submodule.
1082
 */
1083
function media_update_7221() {
1084
  if (module_exists('multiform') && module_exists('plupload')) {
1085
    module_enable(array('media_bulk_upload'));
1086
  }
1087
}
1088

    
1089
/**
1090
 * Delete the deprecated media__display_types_migration_mess variable.
1091
 */
1092
function media_update_7222() {
1093
  variable_del('media__display_types_migration_mess');
1094
}
1095

    
1096
/**
1097
 * Delete legacy variables.
1098
 */
1099
function media_update_7223() {
1100
  variable_del('media__max_filesize');
1101
  variable_del('media__debug');
1102
  variable_del('media__xml_cache_expire');
1103
  variable_del('media__show_file_type_rebuild_nag');
1104
  variable_del('media__field_select_media_text');
1105
  variable_del('media__field_remove_media_text');
1106
  variable_del('media__browser_library_empty_message');
1107
  variable_del('media__browser_pager_limit');
1108
  variable_del('media__browser_viewtype_default');
1109
}
1110

    
1111
/**
1112
 * Rename variables, removing variable namespace.
1113
 */
1114
function media_update_7224() {
1115
  // Create an array of variables sans 'media' prefix.
1116
  $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');
1117

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

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

    
1127
    // Remove the old variable.
1128
    variable_del('media__' . $variable);
1129
  }
1130
}
1131

    
1132
/**
1133
 * Migrate variables to appropriate submodules.
1134
 */
1135
function media_update_7225() {
1136
  $data = array(
1137
    'media_wysiwyg' => array(
1138
      'wysiwyg_title',
1139
      'wysiwyg_icon_title',
1140
      'wysiwyg_default_view_mode',
1141
      'wysiwyg_upload_directory',
1142
      'wysiwyg_allowed_types',
1143
      'wysiwyg_allowed_attributes',
1144
      'wysiwyg_browser_plugins',
1145
    ),
1146
    'media_internet' => array(
1147
      'fromurl_supported_schemes',
1148
    ),
1149
    'media_bulk_upload' => array(
1150
      'import_batch_size',
1151
    ),
1152
  );
1153

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

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

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

    
1173
/**
1174
 * Grant existing user access to new media browser permission.
1175
 */
1176
function media_update_7226() {
1177
  $roles = user_roles(FALSE, 'create files');
1178

    
1179
  foreach ($roles as $rid => $role) {
1180
    user_role_grant_permissions($rid, array('access media browser'));
1181
  }
1182
}