Projet

Général

Profil

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

root / drupal7 / sites / all / modules / media / media.install @ 0939d55c

1
<?php
2

    
3
/**
4
 * @file
5
 * Install, update and uninstall functions for the Media module.
6
 */
7

    
8
/**
9
 * Implements hook_install().
10
 */
11
function media_install() {
12
  // Make sure that we set the icon base directory variable if it is not
13
  // already set.
14
  $base = variable_get('media_icon_base_directory', NULL);
15
  if (!isset($base)) {
16
    $default_base = 'public://media-icons';
17
    variable_set('media_icon_base_directory', $default_base);
18
  }
19
  try {
20
    _media_install_copy_icons();
21
  }
22
  catch (Exception $e) {
23
    watchdog_exception('media', $e);
24
  }
25
}
26

    
27
/**
28
 * Copy the media file icons to files directory for use with image styles.
29
 */
30
function _media_install_copy_icons() {
31
  $destination = variable_get('media_icon_base_directory', 'public://media-icons') . '/' . variable_get('media_icon_set', 'default');
32
  if (!file_prepare_directory($destination, FILE_MODIFY_PERMISSIONS || FILE_CREATE_DIRECTORY)) {
33
    throw new Exception("Unable to create directory $destination.");
34
  }
35
  // @todo If we ever add another default icon set, this should copy all images from one directory up.
36
  $source = drupal_get_path('module', 'media') . '/images/icons/' . variable_get('media_icon_set', 'default');
37
  $files = file_scan_directory($source, '/.*\.(png|jpg)$/');
38
  foreach ($files as $file) {
39
    $result = file_unmanaged_copy($file->uri, $destination, FILE_EXISTS_REPLACE);
40
    if (!$result) {
41
      throw new Exception("Unable to copy {$file->uri} to $destination.");
42
    }
43
  }
44
}
45

    
46
/**
47
 * Implements hook_uninstall().
48
 */
49
function media_uninstall() {
50
  // Remove variables.
51
  variable_del('media_dialog_theme');
52
  variable_del('media_icon_base_directory');
53
  variable_del('media_icon_set');
54
  variable_del('media_show_deprecated_view_modes');
55

    
56
  // Dialog options.
57
  variable_del('media_dialogclass');
58
  variable_del('media_modal');
59
  variable_del('media_draggable');
60
  variable_del('media_resizable');
61
  variable_del('media_minwidth');
62
  variable_del('media_width');
63
  variable_del('media_height');
64
  variable_del('media_position');
65
  variable_del('media_zindex');
66
  variable_del('media_backgroundcolor');
67
  variable_del('media_opacity');
68
  // bulk edit option
69
  variable_del('media_bulk_upload_edit');
70
}
71

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

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

    
113
  if ($phase == 'update') {
114
    $info = system_get_info('module', 'file_entity');
115
    if (strpos($info['version'], '7.x-2') === FALSE) {
116
      $requirements['file_entity'] = array(
117
        'title' => $t('File entity 2.x'),
118
        'value' => $t('Wrong version'),
119
        'severity' => REQUIREMENT_ERROR,
120
        'description' => $t('Media 2.x requires <a href="@url">File entity 2.x</a>. Please download the correct version and make sure you have deleted the file_entity folder inside the media module directory.', array('@url' => 'http://drupal.org/project/file_entity')),
121
      );
122
    }
123
  }
124

    
125
  return $requirements;
126
}
127

    
128
/**
129
 * Deprecated update function.
130
 */
131
function media_update_7000() {
132
}
133

    
134
/**
135
 * Deprecated update function.
136
 */
137
function media_update_7001() {
138
}
139

    
140
/**
141
 * Create the media_type table from the media_types variable.
142
 */
143
function media_update_7002() {
144
  if (db_table_exists('media_type')) {
145
    return;
146
  }
147

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

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

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

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

    
234
/**
235
 * Deprecated update function.
236
 */
237
function media_update_7005() {
238
}
239

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

    
249
/**
250
 * Deprecated update function.
251
 */
252
function media_update_7007() {
253
}
254

    
255
/**
256
 * Empty function.
257
 */
258
function media_update_7008() {
259
}
260

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

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

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

    
279
/**
280
 * Empty update function.
281
 */
282
function media_update_7012() {
283
}
284

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

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

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

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

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

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

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

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

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

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

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

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

    
442
  field_cache_clear();
443
}
444

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
902
/**
903
 * Enable the hidden media_migrate_file_types module to provide a UI to update
904
 * {file_managed}.type with the new file types provided by file_entity.
905
 */
906
function media_update_7209() {
907
  drupal_load('module', 'media_migrate_file_types');
908

    
909
  if (_media_migrate_file_types_get_migratable_file_types()) {
910
    module_enable(array('media_migrate_file_types'));
911
  }
912
}
913

    
914
/**
915
 * Delete deceprated media__type_icon_directory variable.
916
 */
917
function media_update_7210() {
918
  variable_del('media__type_icon_directory');
919
}
920

    
921
/**
922
 * Save a square_thumbnail image style in the database for legacy support if one
923
 * does not already exist.
924
 */
925
function media_update_7211() {
926
  $default_style = array(
927
    'name' => 'square_thumbnail'
928
  );
929

    
930
  // Clear the image cache to remove any old image styles that only exist in
931
  // code.
932
  cache_clear_all('*', 'cache_image', TRUE);
933

    
934
  // Check if the square_thumbnail image style exists.
935
  // The style will only exist if the user has customized it, otherwise it would
936
  // have been removed by clearing the image style cache.
937
  $existing_style = image_style_load('square_thumbnail');
938

    
939
  // Save a square_thumbnail image style in the database for legacy support.
940
  // This is only necessary if a square_thumbnail image style doesn't already
941
  // exist.
942
  if (empty($existing_style)) {
943
    $style = image_style_save($default_style);
944

    
945
    $effect = array(
946
      'name' => 'image_scale_and_crop',
947
      'data' => array(
948
        'width' => 180,
949
        'height' => 180,
950
        'weight' => 0,
951
      ),
952
      'isid' => $style['isid'],
953
    );
954

    
955
    image_effect_save($effect);
956
  }
957

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

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

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

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

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

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

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

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

    
1022
  variable_del('media__file_extensions');
1023
}
1024

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

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

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

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

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

    
1068
  variable_del('media__xml_cache_expire');
1069
}
1070

    
1071
/**
1072
 * Enable the Media WYSIWYG submodule.
1073
 */
1074
function media_update_7219() {
1075
  if (module_exists('wysiwyg')) {
1076
    module_enable(array('media_wysiwyg'));
1077
  }
1078
}
1079

    
1080
/**
1081
 * Delete the deprecated media__file_list_size variable.
1082
 */
1083
function media_update_7220() {
1084
  variable_del('media__file_list_size');
1085
}
1086

    
1087
/**
1088
 * Enable the Media Bulk Upload submodule.
1089
 */
1090
function media_update_7221() {
1091
  if (module_exists('multiform') && module_exists('plupload')) {
1092
    module_enable(array('media_bulk_upload'));
1093
  }
1094
}
1095

    
1096
/**
1097
 * Delete the deprecated media__display_types_migration_mess variable.
1098
 */
1099
function media_update_7222() {
1100
  variable_del('media__display_types_migration_mess');
1101
}
1102

    
1103
/**
1104
 * Delete legacy variables.
1105
 */
1106
function media_update_7223() {
1107
  variable_del('media__max_filesize');
1108
  variable_del('media__debug');
1109
  variable_del('media__xml_cache_expire');
1110
  variable_del('media__show_file_type_rebuild_nag');
1111
  variable_del('media__field_select_media_text');
1112
  variable_del('media__field_remove_media_text');
1113
  variable_del('media__browser_library_empty_message');
1114
  variable_del('media__browser_pager_limit');
1115
  variable_del('media__browser_viewtype_default');
1116
}
1117

    
1118
/**
1119
 * Rename variables, removing variable namespace.
1120
 */
1121
function media_update_7224() {
1122
  // Create an array of variables sans 'media' prefix.
1123
  $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');
1124

    
1125
  foreach ($variables as $variable) {
1126
    // Find the value of the old variable.
1127
    $value = variable_get('media__' . $variable);
1128

    
1129
    // Port the value of the variable if it was set.
1130
    if (!is_null($value)) {
1131
      variable_set('media_' . $variable, $value);
1132
    }
1133

    
1134
    // Remove the old variable.
1135
    variable_del('media__' . $variable);
1136
  }
1137
}
1138

    
1139
/**
1140
 * Migrate variables to appropriate submodules.
1141
 */
1142
function media_update_7225() {
1143
  $data = array(
1144
    'media_wysiwyg' => array(
1145
      'wysiwyg_title',
1146
      'wysiwyg_icon_title',
1147
      'wysiwyg_default_view_mode',
1148
      'wysiwyg_upload_directory',
1149
      'wysiwyg_allowed_types',
1150
      'wysiwyg_allowed_attributes',
1151
      'wysiwyg_browser_plugins',
1152
    ),
1153
    'media_internet' => array(
1154
      'fromurl_supported_schemes',
1155
    ),
1156
    'media_bulk_upload' => array(
1157
      'import_batch_size',
1158
    ),
1159
  );
1160

    
1161
  foreach ($data as $module => $variables) {
1162
    foreach ($variables as $variable) {
1163
      // Only port variables to submodules if the submodule exists.
1164
      if (module_exists($module)) {
1165
        // Find the value of the old variable.
1166
        $value = variable_get('media_' . $variable);
1167

    
1168
        // Port the value of the variable if it was set.
1169
        if (!is_null($value)) {
1170
          variable_set($module . '_' . $variable, $value);
1171
        }
1172
      }
1173

    
1174
      // Remove the old variable.
1175
      variable_del('media_' . $variable);
1176
    }
1177
  }
1178
}
1179

    
1180
/**
1181
 * Grant existing user access to new media browser permission.
1182
 */
1183
function media_update_7226() {
1184
  $roles = user_roles(FALSE, 'create files');
1185

    
1186
  foreach ($roles as $rid => $role) {
1187
    user_role_grant_permissions($rid, array('access media browser'));
1188
  }
1189
}