Projet

Général

Profil

Paste
Télécharger (36,2 ko) Statistiques
| Branche: | Révision:

root / drupal7 / sites / all / modules / media / media.install @ 503b3f7b

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
  // Create initial display settings.
13
  module_load_include('inc', 'file_entity', 'file_entity.file_api');
14
  $default_image_styles = array(
15
    'preview' => 'media_thumbnail',
16
    'teaser' => 'medium',
17
    'full' => 'large',
18
  );
19
  // Only needed by sites that updated from Media 1.x.
20
  // @see media_entity_info_alter()
21
  if (variable_get('media__show_deprecated_view_modes')) {
22
    $default_image_styles['media_original'] = '';
23
  }
24

    
25
  foreach ($default_image_styles as $view_mode => $image_style) {
26
    $existing_display = file_displays_load('image', $view_mode);
27

    
28
    if (empty($existing_display)) {
29
      $display_name = 'image__' . $view_mode . '__file_image';
30
      $display = array(
31
        'api_version' => 1,
32
        'name' => $display_name,
33
        'status' => 1,
34
        'weight' => 5,
35
        'settings' => array('image_style' => $image_style),
36
        'export_type' => NULL,
37
      );
38
      file_display_save((object) $display);
39
    }
40
  }
41

    
42
  // Make sure that we set the icon base directory variable if it is not
43
  // already set.
44
  $base = variable_get('media__icon_base_directory', NULL);
45
  if (!isset($base)) {
46
    $default_base = 'public://media-icons';
47
    variable_set('media__icon_base_directory', $default_base);
48
  }
49
  try {
50
    _media_install_copy_icons();
51
  }
52
  catch (Exception $e) {
53
    watchdog_exception('media', $e);
54
  }
55
}
56

    
57
/**
58
 * Copy the media file icons to files directory for use with image styles.
59
 */
60
function _media_install_copy_icons() {
61
  $destination = variable_get('media__icon_base_directory', 'public://media-icons') . '/' . variable_get('media__icon_set', 'default');
62
  if (!file_prepare_directory($destination, FILE_CREATE_DIRECTORY)) {
63
    throw new Exception("Unable to create directory $destination.");
64
  }
65
  // @todo If we ever add another default icon set, this should copy all images from one directory up.
66
  $source = drupal_get_path('module', 'media') . '/images/icons/' . variable_get('media__icon_set', 'default');
67
  $files = file_scan_directory($source, '/.*\.(png|jpg)$/');
68
  foreach ($files as $file) {
69
    $result = file_unmanaged_copy($file->uri, $destination, FILE_EXISTS_REPLACE);
70
    if (!$result) {
71
      throw new Exception("Unable to copy {$file->uri} to $destination.");
72
    }
73
  }
74
}
75

    
76
/**
77
 * Implements hook_uninstall().
78
 */
79
function media_uninstall() {
80
  // Remove variables.
81
  variable_del('media__wysiwyg_title');
82
  variable_del('media__wysiwyg_icon_title');
83
  variable_del('media__wysiwyg_default_view_mode');
84
  variable_del('media__wysiwyg_upload_directory');
85
  variable_del('media__wysiwyg_allowed_types');
86
  variable_del('media__wysiwyg_allowed_attributes');
87
  variable_del('media__wysiwyg_browser_plugins');
88
  variable_del('media__dialog_theme');
89
  variable_del('media__max_filesize');
90
  variable_del('media__debug');
91
  variable_del('media__file_list_size');
92
  variable_del('media__xml_cache_expire');
93
  variable_del('media__import_batch_size');
94
  variable_del('media__fromurl_supported_schemes');
95
  variable_del('media__icon_base_directory');
96
  variable_del('media__icon_set');
97
  variable_del('media__show_deprecated_view_modes');
98
  variable_del('media__show_file_type_rebuild_nag');
99
  variable_del('media__field_select_media_text');
100
  variable_del('media__field_remove_media_text');
101
  variable_del('media__browser_library_empty_message');
102
  variable_del('media__browser_pager_limit');
103
  variable_del('media__browser_viewtype_default');
104
  variable_del('media__display_types_migration_mess');
105
}
106

    
107
/**
108
 * Implements hook_update_dependencies().
109
 */
110
function media_update_dependencies() {
111
  // media_update_7200() needs to convert old 'media' permissions to new 'file'
112
  // permissions, so it must run before file_entity_7208 which updates existing
113
  // 'file' permissions to be split per file type.
114
  $dependencies['file_entity'][7208] = array(
115
    'media' => 7200,
116
  );
117
  // This update function requires field_update_7002() to run before it since
118
  // the field_bundle_settings variable has been split into separate variables
119
  // per entity type and bundle.
120
  $dependencies['media'][7016] = array(
121
    'field' => 7002,
122
    'rules' => 7205,
123
  );
124
  // Those updates require {file_type} table created.
125
  $dependencies['media'][7204] = array(
126
    'file_entity' => 7201,
127
  );
128
  // Require {file_type}.mimetypes column before updating them.
129
  $dependencies['media'][7208] = array(
130
    'file_entity' => 7210,
131
  );
132
  return $dependencies;
133
}
134

    
135
/**
136
 * Implements hook_requirements().
137
 */
138
function media_requirements($phase) {
139
  $t = get_t();
140
  // Make sure that file_entity module is 2.x version.
141
  // We can't add this check in .info file because drupal.org testbot cant
142
  // handle it. See #1734648.
143
  $requirements = array();
144

    
145
  if ($phase == 'update') {
146
    $info = system_get_info('module', 'file_entity');
147
    if (strpos($info['version'], '7.x-2') === FALSE) {
148
      $requirements['file_entity'] = array(
149
        'title' => $t('File entity 2.x'),
150
        'value' => $t('Wrong version'),
151
        'severity' => REQUIREMENT_ERROR,
152
        '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')),
153
      );
154
    }
155
  }
156

    
157
  return $requirements;
158
}
159

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

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

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

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

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

    
256
/**
257
 * Empty update function to trigger a menu rebuild.
258
 */
259
function media_update_7004() {
260
}
261

    
262
/**
263
 * Deprecated update function.
264
 */
265
function media_update_7005() {
266
}
267

    
268
/**
269
 * Rename the file table to file_managed in case head2head was used.
270
 */
271
function media_update_7006() {
272
  if (db_table_exists('file') && !db_table_exists('file_managed')) {
273
    db_rename_table('file', 'file_managed');
274
  }
275
}
276

    
277
/**
278
 * Deprecated update function.
279
 */
280
function media_update_7007() {
281
}
282

    
283
/**
284
 * Empty function.
285
 */
286
function media_update_7008() {
287
}
288

    
289
/**
290
 * Deprecated update function.
291
 */
292
function media_update_7009() {
293
}
294

    
295
/**
296
 * Deprecated update function.
297
 */
298
function media_update_7010() {
299
}
300

    
301
/**
302
 * Empty update function.
303
 */
304
function media_update_7011() {
305
}
306

    
307
/**
308
 * Empty update function.
309
 */
310
function media_update_7012() {
311
}
312

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

    
331
/**
332
 * Rename the media__dialog_get_theme_name variable to media__dialog_theme.
333
 */
334
function media_update_7014() {
335
  if ($old_value = variable_get('media__dialog_get_theme_name')) {
336
    variable_del('media__dialog_get_theme_name');
337
    variable_set('media__dialog_theme', $old_value);
338
  }
339
}
340

    
341
/**
342
 * Empty update function to trigger a registry rebuild.
343
 */
344
function media_update_7015() {
345
}
346

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

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

    
375
    // @todo Convert this to use _update_7000_field_read_fields()
376
    $fields = field_read_fields(array('id' => $instance['field_id']), array('include_inactive' => TRUE, 'include_deleted' => TRUE));
377
    $field = $fields[$instance['field_id']];
378

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

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

    
405
    // Once all the data has been updated, update the {field_config_instance}
406
    // record.
407
    db_update('field_config_instance')
408
      ->fields(array('entity_type' => 'file'))
409
      ->condition('id', $instance['id'])
410
      ->execute();
411
  }
412

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

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

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

    
470
  field_cache_clear();
471
}
472

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

    
491
/**
492
 * Empty update function to trigger a menu rebuild.
493
 */
494
function media_update_7018() {
495
}
496

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

    
524
/**
525
 * Delete the wysiwyg_allowed_types variable if it is the same as default.
526
 */
527
function media_update_7020() {
528
  if (variable_get('media__wysiwyg_allowed_types') == array('image', 'video')) {
529
    variable_del('media__wysiwyg_allowed_types');
530
  }
531
}
532

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
918
/**
919
 * DEPRECATED: Update {file_managed}.type with the new file types provided by
920
 * file_entity. (Types migration has been moved to admin/structure/file-types/upgrade',
921
 * where can be executed manually.)
922
 */
923
function media_update_7209() {
924

    
925
}
926

    
927
/**
928
 * Delete deceprated media__type_icon_directory variable.
929
 */
930
function media_update_7210() {
931
  variable_del('media__type_icon_directory');
932
}
933

    
934
/**
935
 * Flush old version of the image style to make the thumbnails appear correctly.
936
 */
937
function media_update_7211() {
938
  $style = image_style_load('square_thumbnail');
939

    
940
  if ($style) {
941
    $style['name'] = 'media_thumbnail';
942
    image_style_save($style);
943
  }
944

    
945
  // Replace any instances in display settings
946
  module_load_include('inc', 'file_entity', 'file_entity.file_api');
947
  $entity_info = entity_get_info('file');
948
  $view_modes = array('default' => array('label' => t('Default'))) + $entity_info['view modes'];
949
  foreach ($view_modes as $view_mode => $view_mode_info) {
950
    $displays = file_displays_load('image', $view_mode);
951
    foreach ($displays as $display) {
952
      if ($display->settings['image_style'] == 'square_thumbnail') {
953
        $display->settings['image_style'] = 'media_thumbnail';
954
        file_display_save($display);
955
      }
956
    }
957
  }
958

    
959
  return t('Flushed image style and updated display styles.');
960
}
961

    
962
/**
963
 * Utility function for update 7204. Updates display options within Views.
964
 */
965
function _media_update_7204_update_views_display_options(&$display_options, $view_mode_updates) {
966
  $updated = FALSE;
967

    
968
  // Update fields that use a formatter with a file_view_mode formatter setting.
969
  if (!empty($display_options['fields'])) {
970
    foreach ($display_options['fields'] as $field_name => $field_display) {
971
      if (isset($field_display['settings']['file_view_mode']) && isset($view_mode_updates[$field_display['settings']['file_view_mode']])) {
972
        $display_options['fields'][$field_name]['settings']['file_view_mode'] = $view_mode_updates[$field_display['settings']['file_view_mode']];
973
        $updated = TRUE;
974
      }
975
    }
976
  }
977

    
978
  // Update Views that display files directly using a row plugin with a view
979
  // mode setting.
980
  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']])) {
981
    $display_options['row_options']['view_mode'] = $view_mode_updates[$display_options['row_options']['view_mode']];
982
    $updated = TRUE;
983
  }
984
  return $updated;
985
}
986

    
987
/**
988
 * Re-create application file type for legacy reasons.
989
 */
990
function media_update_7212() {
991
  module_load_include('inc', 'file_entity', 'file_entity.file_api');
992
  if (!file_type_load('application')) {
993
    $application = (object) array(
994
      'api_version' => 1,
995
      'type' => 'application',
996
      'label' => t('Application'),
997
      'description' => t('Multipurpose type - kept to support older sites.'),
998
      'mimetypes' => array(),
999
      'streams' => array(
1000
        'public',
1001
      ),
1002
    );
1003

    
1004
    file_type_save($application);
1005
    $application = file_type_load('application');
1006
    file_type_disable($application);
1007
  }
1008
}
1009

    
1010
/**
1011
 * Remove the obsolete file_extensions variable.
1012
 */
1013
function media_update_7213() {
1014
  $media_file_extensions = explode(' ', variable_get('media__file_extensions'));
1015
  $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'));
1016

    
1017
  // Preserve any custom file extensions.
1018
  if (array_diff($media_file_extensions, $file_entity_file_extensions)) {
1019
    $combined_file_extensions = array_unique(array_merge($file_entity_file_extensions, $media_file_extensions));
1020
    variable_set('file_entity_default_allowed_extensions', implode(' ' , $combined_file_extensions));
1021
  }
1022

    
1023
  variable_del('media__file_extensions');
1024
}
1025

    
1026
/**
1027
 * Drop the legacy {media_filter_usage} table.
1028
 */
1029
function media_update_7214() {
1030
  if (db_table_exists('media_filter_usage')) {
1031
    db_drop_table('media_filter_usage');
1032
  }
1033
}
1034

    
1035
/**
1036
 * Skipped to run media_update_7217().
1037
 */
1038
function media_update_7216() {
1039
  // Do nothing.
1040
}
1041

    
1042
/**
1043
 * Copy file type icons to public files directory.
1044
 */
1045
function media_update_7217() {
1046
  // Remove any trailing slashes from the icon base directory variable.
1047
  $dir = variable_get('media__icon_base_directory');
1048
  if (!empty($dir)) {
1049
    $dir = rtrim($dir, '/');
1050
    variable_set('media__icon_base_directory', $dir);
1051
  }
1052

    
1053
  try {
1054
    _media_install_copy_icons();
1055
  }
1056
  catch (Exception $e) {
1057
    throw new DrupalUpdateException($e->getMessage());
1058
  }
1059
}
1060

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

    
1069
  variable_del('media__xml_cache_expire');
1070
}