summaryrefslogtreecommitdiffstats
path: root/resp_img.module
blob: f978a0296150165ca84f8c696c4933f0cdbea37f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
<?php

define('RESP_IMG_CLASS', 'resp-img-picture');
define('RESP_IMG_SEPARATOR', '__');
define('RESP_IMG_STYLE_PREFIX', 'resp_img__');

/**
 * Implements hook_permission().
 */
function resp_img_permission() {
  return array(
    'administer responsive images and styles' => array(
      'title' => t('Administer Responsive Images and Styles'),
      'description' => t('Administer responsive images and styles'),
    ),
  );
}

/**
 * Implements hook_menu().
 */
function resp_img_menu() {
  $items = array();

  // @todo: link to all breakpoints and a list of all groups
  // cf theme settings page
  $items['admin/config/media/resp_img'] = array(
    'title' => 'Responsive images and styles',
    'description' => 'Manage Responsive Images and Styles',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('resp_img_admin_breakpoints'),
    'access arguments' => array('administer responsive images and styles'),
    'file' => 'resp_img.admin.inc',
  );

  $items['admin/config/media/resp_img/create_style'] = array(
    'title' => 'Add responsive style',
    'description' => 'Add a responsive image style',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('resp_img_add_style_form'),
    'access arguments' => array('administer responsive images and styles'),
    'file' => 'resp_img.admin.inc',
    'type' => MENU_LOCAL_TASK,
    'weight' => 30,
  );

  $items['admin/config/media/resp_img/groups'] = array(
    'title' => 'Groups',
    'type' => MENU_DEFAULT_LOCAL_TASK,
    'weight' => 10,
  );

  $items['admin/config/media/resp_img/groups/global'] = array(
    'title' => 'Map breakpoints and image styles',
    'type' => MENU_DEFAULT_LOCAL_TASK,
    'weight' => -1,
  );
  $items['admin/config/media/resp_img/groups/import'] = array(
    'title' => 'Import mappings',
    'page arguments' => array('resp_img_admin_import_form'),
    'type' => MENU_LOCAL_TASK,
    'access arguments' => array('administer responsive images and styles'),
    'file' => 'resp_img.admin.inc',
    'weight' => 999,
  );

  $breakpoint_groups = breakpoints_breakpoint_group_load_all();
  foreach ($breakpoint_groups as $breakpoint_group_name => $breakpoint_group) {
    if (!empty($breakpoint_group->machine_name)) {
      $items['admin/config/media/resp_img/groups/' . $breakpoint_group->machine_name] = array(
        'title' => $breakpoint_group->name,
        'page arguments' => array('resp_img_admin_breakpoints', $breakpoint_group->machine_name),
        'type' => MENU_LOCAL_TASK,
        'access arguments' => array('administer responsive images and styles'),
        'file' => 'resp_img.admin.inc',
        'weight' => 15,
      );
      $items['admin/config/media/resp_img/groups/' . $breakpoint_group->machine_name . '/export'] = array(
        'title' => 'Export ' . check_plain($breakpoint_group->name) . ' mappings',
        'page callback' => 'drupal_get_form',
        'page arguments' => array('resp_img_admin_export_form', 'mappings.' . $breakpoint_group->machine_name),
        'type' => MENU_LOCAL_ACTION,
        'access arguments' => array('administer responsive images and styles', 'mappings.' . $breakpoint_group->machine_name),
        'access callback' => 'resp_img_mappings_export_access',
        'file' => 'resp_img.admin.inc',
        'weight' => 15,
      );
    }
  }

  return $items;
}

/**
 * Access callback.
 */
function resp_img_mappings_export_access($perm, $mapping_name) {
  return resp_img_mapping_load($mapping_name) && user_access($perm);
}

/**
 * Load mappings.
 */
function resp_img_mapping_load($name = NULL) {
  ctools_include('export');
  if ($name) {
    $mappings = ctools_export_load_object('resp_img_mapping', 'names', array($name));
    $mapping = isset($mappings[$name]) ? $mappings[$name] : FALSE;
    return $mapping;
  }
  return ctools_export_load_object('resp_img_mapping');
}


/**
 * Save mappings.
 */
function resp_img_mapping_save(&$mapping) {
  ctools_include('export');
  $update = isset($mapping->id) ? array('id') : array();
  $style = image_style_load(RESP_IMG_STYLE_PREFIX . $mapping->breakpoint_group);
  if ($style) {
    image_style_flush($style);
  }
  return drupal_write_record('resp_img_mapping', $mapping, $update);
}

/**
 * Validate mappings.
 */
function resp_img_mapping_validate($mapping) {
  if (!is_object($mapping)) {
    return FALSE;
  }
  foreach (array('machine_name', 'breakpoint_group', 'mapping') as $property) {
    if (!property_exists($mapping, $property)) {
      return FALSE;
    }
  }
  return TRUE;
}

/**
 * Add javascript for older browser support
 */
function resp_img_add_js() {
  static $added = FALSE;
  if (!$added) {
    $added = TRUE;
    drupal_add_js(drupal_get_path('module', 'resp_img') . '/picturefill/matchmedia.js', array('type' => 'file', 'weight' => -10, 'group' => JS_DEFAULT));
    drupal_add_js(drupal_get_path('module', 'resp_img') . '/picturefill/picturefill.js', array('type' => 'file', 'weight' => -10, 'group' => JS_DEFAULT));
    drupal_add_js(drupal_get_path('module', 'resp_img') . '/resp_img.js', array('type' => 'file', 'weight' => -10, 'group' => JS_DEFAULT));
  }
}

/**
 * Implements hook_theme().
 */
function resp_img_theme() {
  return array(
    'picture' => array(
      'variables' => array(
        'style_name' => NULL,
        'path' => NULL,
        'width' => NULL,
        'height' => NULL,
        'alt' => '',
        'title' => NULL,
        'attributes' => array(),
        'breakpoints' => array(),
      ),
    ),
    'picture_formatter' => array(
      'variables' => array(
        'item' => NULL,
        'path' => NULL,
        'image_style' => NULL,
        'breakpoints' => array(),
      ),
    ),
    'colorbox_picture_formatter' => array(
      'variables' => array(
        'item' => NULL,
        'node' => NULL,
        'field' => array(),
        'display_settings' => array(),
        'breakpoints' => array(),
      ),
    ),
    'colorbox_picturefield' => array(
      'variables' => array(
        'image' => array(),
        'path' => NULL,
        'title' => NULL,
        'gid' => NULL,
        'breakpoints' => array(),
      ),
    ),
  );
}

/**
 * Implements hook_entity_info_alter().
 */
function resp_img_entity_info_alter(&$info) {
  if (isset($info['file'])) {
    foreach (breakpoints_breakpoint_group_load_all() as $group) {
      $info['file']['view modes']['media_responsive_' . $group->machine_name] = array(
        'label' => t('@group (Responsive)', array('@group' => $group->name)),
        'custom settings' => TRUE,
      );
    }
  }
}

/**
 * Implements hook_ctools_plugin_api().
 *
 * Lets CTools know which plugin APIs are implemented by resp_img module.
 */
function resp_img_ctools_plugin_api($owner, $api) {
  static $api_versions = array(
    'file_entity' => array(
      'file_default_displays' => 1,
    ),
  );
  if (isset($api_versions[$owner][$api])) {
    return array('version' => $api_versions[$owner][$api]);
  }
}

/**
 * Implements hook_file_default_displays().
 */
function resp_img_file_default_displays() {
  $default_image_styles = array();
  foreach (breakpoints_breakpoint_group_load_all() as $group) {
    $default_image_styles['media_responsive_' . $group->machine_name] = RESP_IMG_STYLE_PREFIX . $group->machine_name;
  }
  $default_displays = array();

  foreach ($default_image_styles as $view_mode => $image_style) {
    $display_name = 'image__' . $view_mode . '__file_image';
    $default_displays[$display_name] = (object) array(
      'api_version' => 1,
      'name' => $display_name,
      'status' => 1,
      'weight' => 5,
      'settings' => array('image_style' => $image_style),
    );
  }

  return $default_displays;
}

/**
 * Implements hook_preprocess_field().
 */
function resp_img_field_attach_view_alter(&$output, $context) {
  $view = module_exists('views') ? views_get_current_view() : FALSE;
  foreach (element_children($output) as $field_name) {
    $element = &$output[$field_name];
    $vars = array();
    if (isset($element['#formatter'])) {
      if ($element['#formatter'] == 'image') {
        $vars['image_style'] = 'image_style';
        $vars['#formatter'] = 'picture';
        $vars['#theme'] = 'picture_formatter';
      }
      elseif ($element['#formatter'] == 'colorbox') {
        $vars['image_style'] = 'colorbox_node_style';
        $vars['#formatter'] = 'picture';
        $vars['#theme'] = 'colorbox_picture_formatter';
      }
      elseif ($element['#formatter'] == 'slideshow') {
        $vars['image_style'] = 'slideshow_image_style';
        $vars['#formatter'] = 'slideshow';
        $vars['#theme'] = 'field_slideshow';
      }

      if (!empty($vars)) {
        $instance = field_info_instance($element['#entity_type'], $element['#field_name'], $element['#bundle']);
        if ($view && isset($view->query->pager->display->handler->handlers['field'][$element['#field_name']])) {
          $settings = $view->query->pager->display->handler->handlers['field'][$element['#field_name']]->options['settings'];
        }
        elseif (isset($instance['display'][$context['view_mode']]['settings'][$vars['image_style']]) && !empty($instance['display'][$context['view_mode']]['settings'][$vars['image_style']])) {
          $settings = $instance['display'][$context['view_mode']]['settings'];
        }
        else {
          $settings = $instance['display']['default']['settings'];
        }
        if (isset($settings[$vars['image_style']]) && strpos($settings[$vars['image_style']], RESP_IMG_STYLE_PREFIX) !== FALSE) {
          $group_name = drupal_substr($settings[$vars['image_style']], drupal_strlen(RESP_IMG_STYLE_PREFIX));
          $breakpoint_styles = _resp_img_get_breakpoint_styles($group_name);
          if (!empty($breakpoint_styles)) {
            // Change the formatter so it uses ours.
            $element['#formatter'] = $vars['#formatter'];

             // Change the formatter on all items as well.
            $num_fields = ($element['#formatter'] != 'slideshow') ? count($element['#items']) : 1;
            for ($delta = 0; $delta < $num_fields; $delta++) {
              $element[$delta]['#theme'] = $vars['#theme'];
              // Change the image style to the first in use.
              $reset = reset($breakpoint_styles['mapping']);
              $element[$delta]['#image_style'] = reset($reset);
              $element[$delta]['#breakpoints'] = $breakpoint_styles;
            }
          }
          else {
            watchdog('Responsive images', 'You have to map at least 1 style for ' . check_plain($group_name) . '.');
          }
        }
      }
    }
  }
}

function theme_picture_formatter($variables) {
  if (!isset($variables['breakpoints']) || empty($variables['breakpoints'])) {
    return theme('image_formatter', $variables);
  }

  $item = $variables['item'];

  // Do not output an empty 'title' attribute.
  if (isset($item['title']) && drupal_strlen($item['title']) == 0) {
    unset($item['title']);
  }

  $item['style_name'] = $variables['image_style'];
  $item['breakpoints'] = $variables['breakpoints'];

  if (!isset($item['path']) && isset($variables['uri'])) {
    $item['path'] = $variables['uri'];
  }
  $output = theme('picture', $item);

  if (isset($variables['path']['path'])) {
    $path = $variables['path']['path'];
    $options = isset($variables['path']['options']) ? $variables['path']['options'] : array();
    $options['html'] = TRUE;
    $output = l($output, $path, $options);
  }
  return $output;
}

/**
 * Theme a picture element.
 */
function theme_picture($variables) {
  resp_img_add_js();
  // Add classes to ease styling
  if (!isset($variables['attributes'])) {
    $variables['attributes'] = array();
  }
  if (!isset($variables['attributes']['class'])) {
    $variables['attributes']['class'] = array();
  }
  $variables['attributes']['class'][] = RESP_IMG_CLASS;

  // Make sure that width and height are proper values
  // If they exists we'll output them
  // @see http://www.w3.org/community/respimg/2012/06/18/florians-compromise/
  if (isset($variables['width']) && empty($variables['width'])) {
    unset($variables['width']);
    unset($variables['height']);
  }
  elseif (isset($variables['height']) && empty($variables['height'])) {
    unset($variables['width']);
    unset($variables['height']);
  }

  // Use path or uri untill D7 uses one in all places.
  if (!isset($variables['path']) || empty($variables['path'])) {
    $variables['path'] = ($variables['uri']);
  }
  if (!isset($variables['uri']) || empty($variables['uri'])) {
    $variables['uri'] = ($variables['path']);
  }

  $images = array();
  $output = array();

  // Fallback image.
  if (isset($variables['image_style']) && !empty($variables['image_style'])) {
    $img = theme('image_style', $variables);
    $img = str_replace('<img', '', $img);
    $img = str_replace('/>', '', $img);
    $images[] = array(
      'image' => $img,
    );
  }

  // All breakpoints and multipliers.
  if (isset($variables['breakpoints']['mapping'])) {
    foreach ($variables['breakpoints']['mapping'] as $breakpoint_name => $multipliers) {
      $breakpoint = breakpoints_breakpoint_load_by_fullkey($breakpoint_name);
      if ($breakpoint) {
        $new_images = array();
        foreach ($multipliers as $multiplier => $image_style) {
          $new_image = $variables;
          // Add classes to ease styling
          $new_image['attributes']['class'][] = RESP_IMG_CLASS . '-' . drupal_clean_css_identifier($breakpoint->name);
          $new_image['style_name'] = $image_style;
          $new_image['#multiplier'] = $multiplier;
          $new_images[] = $new_image;
        }
        $img = theme('image_style', $new_images[0]);
        $img = str_replace('<img', '', $img);
        $img = str_replace('/>', '', $img);

        // Only one image, output as src.
        if (count($new_images) == 1) {
          $images[] = array(
            'image' => $img,
            'media' => $breakpoint->breakpoint,
          );
        }
        else {
          // Mutliple images, output as srcset.
          $srcset = array();
          foreach ($new_images as $new_image) {
            $srcset[] = image_style_url($new_image['style_name'], $new_image['uri']) . ' ' . $new_image['#multiplier'];
          }
          $img = preg_replace('/src="[^"]*"/', '', $img);
          $images[] = array(
            'srcset' => implode(', ', $srcset),
            'media' => $breakpoint->breakpoint,
            'image' => $img,
          );
        }
      }
    }
  }

  if (!empty($images)) {
    $output[] = '<picture class="' . RESP_IMG_CLASS . '" alt="' . check_plain($variables['alt']) . '" title="' . check_plain($variables['title']) . '">';

    // add variants to the output
    foreach ($images as $image) {
      if (isset($image['media']) && !empty($image['media'])) {
        if (!isset($image['srcset'])) {
          $output[] = '<!-- <source media="' . $image['media'] . '" ' . $image['image'] . ' /> -->';
          $output[] = '<source media="' . $image['media'] . '" ' . $image['image'] . ' />';
        }
        else {
          $output[] = '<!-- <source media="' . $image['media'] . '" srcset="' . $image['srcset'] . '" ' . $image['image'] . ' /> -->';
          $output[] = '<source media="' . $image['media'] . '" srcset="' . $image['srcset'] . '" ' . $image['image'] . ' />';
        }
      }
      else {
        $output[] = '<!-- <source ' . $image['image'] . ' /> -->';
        $output[] = '<source ' . $image['image'] . ' />';
      }
    }

    // output the default image as fallback
    // $output .= '<img src="' . image_style_url($variables['style_name'], $variables['uri']) . '" alt="' . check_plain($variables['alt']) . '" />';
    $output[] = '<noscript><img ' . $images[0]['image'] . '/></noscript>';
    $output[] = '</picture>';
    return implode("\n", $output);
  }
}

/**
 * colorbox_picture_formatter similar to colorbox_image_formatter.
 *
 * only differences are:
 *   'breakpoints' => $variables['breakpoints'],
 *   is the last line.
 */
function theme_colorbox_picture_formatter($variables) {
  $item = $variables['item'];
  $node = $variables['node'];
  $field = $variables['field'];
  $settings = $variables['display_settings'];

  $image = array(
    'path' => $item['uri'],
    'alt' => $item['alt'],
    'title' => $item['title'],
    'style_name' => $settings['colorbox_node_style'],
    'breakpoints' => $variables['breakpoints'],
  );

  if (isset($item['width']) && isset($item['height'])) {
    $image['width'] = $item['width'];
    $image['height'] = $item['height'];
  }

  switch ($settings['colorbox_caption']) {
    case 'auto':
      // If the title is empty use alt or the node title in that order.
      if (!empty($image['title'])) {
        $caption = $image['title'];
      }
      elseif (!empty($image['alt'])) {
        $caption = $image['alt'];
      }
      elseif (!empty($node->title)) {
        $caption = $node->title;
      }
      else {
        $caption = '';
      }
      break;
    case 'title':
      $caption = $image['title'];
      break;
    case 'alt':
      $caption = $image['alt'];
      break;
    case 'node_title':
      $caption = $node->title;
      break;
    case 'custom':
      $caption = token_replace($settings['colorbox_caption_custom'], array('node' => $node));
      break;
    default:
      $caption = '';
  }

  // Shorten the caption for the example styles or when caption shortening is active.
  $colorbox_style = variable_get('colorbox_style', 'default');
  $trim_length = variable_get('colorbox_caption_trim_length', 75);
  if (((strpos($colorbox_style, 'colorbox/example') !== FALSE) || variable_get('colorbox_caption_trim', 0)) && (drupal_strlen($caption) > $trim_length)) {
    $caption = drupal_substr($caption, 0, $trim_length - 5) . '...';
  }

  // Build the gallery id.
  $nid = !empty($node->nid) ? $node->nid : 'nid';
  switch ($settings['colorbox_gallery']) {
    case 'post':
      $gallery_id = 'gallery-' . $nid;
      break;
    case 'page':
      $gallery_id = 'gallery-all';
      break;
    case 'field_post':
      $gallery_id = 'gallery-' . $nid . '-' . $field['field_name'];
      break;
    case 'field_page':
      $gallery_id = 'gallery-' . $field['field_name'];
      break;
    case 'custom':
      $gallery_id = $settings['colorbox_gallery_custom'];
      break;
    default:
      $gallery_id = '';
  }

  if ($style_name = $settings['colorbox_image_style']) {
    $path = image_style_url($style_name, $image['path']);
  }
  else {
    $path = file_create_url($image['path']);
  }

  return theme('colorbox_picturefield', array('image' => $image, 'path' => $path, 'title' => $caption, 'gid' => $gallery_id));
}

/**
 * theme_colorbox_picturefield similar to theme_colorbox_imagefield.
 *
 * only difference is: $image = theme('picture', $variables['image']);.
 */
function theme_colorbox_picturefield($variables) {
  $class = array('colorbox');

  if ($variables['image']['style_name'] == 'hide') {
    $image = '';
    $class[] = 'js-hide';
  }
  elseif (!empty($variables['image']['style_name'])) {
    $image = theme('picture', $variables['image']);
  }
  else {
    $image = theme('image', $variables['image']);
  }

  $options = array(
    'html' => TRUE,
    'attributes' => array(
      'title' => $variables['title'],
      'class' => implode(' ', $class),
      'rel' => $variables['gid'],
    )
  );

  return l($image, $variables['path'], $options);
}

/**
 * Implements hook_field_formatter_info_alter().
 */
function resp_img_field_formatter_info_alter(&$info) {
  foreach ($info as $formatter_key => &$formatter) {
    if ($formatter_key == 'image') {
      if (!isset($formatter['settings']) || !is_array($formatter['settings'])) {
        $formatter['settings'] = array();
      }
    }
  }
}

/**
 * Implements hook_image_default_styles().
 */
function resp_img_image_default_styles() {
  $styles = array();
  // Provide fake responsive image styles for users to select.
  $breakpoint_groups = breakpoints_breakpoint_group_load_all();
  if ($breakpoint_groups && !empty($breakpoint_groups)) {
    foreach (array_keys($breakpoint_groups) as $machine_name) {
      $styles[RESP_IMG_STYLE_PREFIX . $machine_name] = array(
        'effects' => array(),
      );
    }
  }
  return $styles;
}

/**
 * Implements hook_image_styles_alter().
 */
function resp_img_image_styles_alter(&$styles) {
  $breakpoint_groups = breakpoints_breakpoint_group_load_all();
  if ($breakpoint_groups && !empty($breakpoint_groups)) {
    foreach ($breakpoint_groups as $machine_name => $breakpoint_group) {
      $mapping = _resp_img_get_breakpoint_styles($machine_name);
      $first_style = FALSE;
      if (!empty($mapping)) {
        $first_style = reset(reset($mapping['mapping']));
      }
      if ($first_style) {
        $first_style = isset($styles[$first_style]) ? $styles[$first_style] : FALSE;
      }
      if ($first_style) {
        $new_effects = array();
        foreach ($first_style['effects'] as $effect) {
          $new_effect = $effect;
          unset($new_effect['isid']);
          unset($new_effect['ieid']);
          $new_effects[] = $new_effect;
        }
        $styles[RESP_IMG_STYLE_PREFIX . $machine_name]['effects'] = $new_effects;
      }
    }
  }
}

/**
 * Implements MODULE_preprocess_HOOK().
 */
function resp_img_preprocess_image_style_list(&$variables) {
  $variables['styles'] = array_filter($variables['styles'], '_resp_img_filter_styles');
}

/**
 * array_filter callback.
 */
function _resp_img_filter_styles($var) {
  return strpos(is_array($var) ? $var['name'] : $var, RESP_IMG_STYLE_PREFIX) !== 0;
}

/**
 * Implements hook_field_formatter_settings_summary_alter().
 */
function resp_img_field_formatter_settings_summary_alter(&$summary, $context) {
  if (isset($context['field']['type']) && $context['field']['type'] === 'image') {
    $settings = $context['instance']['display'][$context['view_mode']]['settings'];
    if (isset($settings['image_style']) && strpos($settings['image_style'], RESP_IMG_STYLE_PREFIX) !== FALSE) {
      $group_name = drupal_substr($settings['image_style'], drupal_strlen(RESP_IMG_STYLE_PREFIX));
      $summary = 'Responsive mode activated using ' . $group_name;
    }
    if (isset($settings['colorbox_node_style']) && strpos($settings['colorbox_node_style'], RESP_IMG_STYLE_PREFIX) !== FALSE) {
      $group_name = drupal_substr($settings['colorbox_node_style'], drupal_strlen(RESP_IMG_STYLE_PREFIX));
      $summary .= '<br />Responsive mode activated using ' . $group_name;
    }
  }
}

function resp_img_entity_view_alter(&$build, $type) {
  foreach (element_children($build) as $child) {
    if (isset($build[$child]['#field_name'])) {
      $build[$child]['#post_render'][] = 'resp_img_post_render';
    }
  }
}

/**
 * #post_render callback.
 */
function resp_img_post_render($content, $element) {
  return _resp_img_replace_picture($content);
}

function _resp_img_replace_picture($content) {
  $result = array();
  preg_match_all('/<img[^>]*>/i', $content, $result);
  $orig_imgs = $imgs = $result[0];
  $vars['image_style'] = 'image_style';
  $vars['#formatter'] = 'picture';
  $vars['#theme'] = 'picture_formatter';
  foreach ($imgs as &$img) {
    if (strpos($img, RESP_IMG_STYLE_PREFIX) !== FALSE) {
      $xml = simplexml_load_string('<image>' . html_entity_decode($img, ENT_QUOTES, "utf-8") . '</image>');
      if (isset($xml->img[0]) && is_object($xml->img[0])) {
        $attributes = array();
        foreach ($xml->img[0]->attributes() as $a => $b) {
          $attributes[$a] = (string)$b;
        }
      }

      if (isset($attributes['src']) && !empty($attributes['src'])) {
        $group_name = drupal_substr($attributes['src'], strpos($attributes['src'], RESP_IMG_STYLE_PREFIX));
        $group_name = str_replace(RESP_IMG_STYLE_PREFIX, '', drupal_substr($group_name, 0, strpos($group_name, '/')));
        $breakpoint_styles = _resp_img_get_breakpoint_styles($group_name);

        // @todo: Ugly! Find a better way?
        $src = drupal_substr($attributes['src'], strpos($attributes['src'], RESP_IMG_STYLE_PREFIX . $group_name) + drupal_strlen(RESP_IMG_STYLE_PREFIX . $group_name) + 1);
        $src = preg_replace('/\//', '://', $src, 1);
        unset($attributes['src']);
        $variables = array(
          'path' => $src,
          'breakpoints' => $breakpoint_styles,
        );
        if (isset($attributes['width'])) {
          $variables['width'] = $attributes['width'];
          unset($attributes['width']);
        }
        if (isset($attributes['height'])) {
          $variables['height'] = $attributes['height'];
          unset($attributes['height']);
        }
        $variables['attributes'] = $attributes;
        if (isset($variables['attributes']['class'])) {
          $variables['attributes']['class'] = explode(' ', $variables['attributes']['class']);
        }
        $variables['style_name'] = RESP_IMG_STYLE_PREFIX . $group_name;
        $img = theme('picture', $variables);
      }
    }
  }
  $content = str_replace($orig_imgs, $imgs, $content);
  return $content;
}

function _resp_img_get_breakpoint_styles($group_name) {
  $active_breakpoints = &drupal_static('resp_img_breakpoints', FALSE);
  if (!$active_breakpoints) {
    $active_breakpoints = breakpoints_breakpoint_load_all_active();
  }
  $breakpoint_styles = array();
  if ($mappings = resp_img_mapping_load('mappings.' . $group_name)) {
    $group = breakpoints_breakpoint_group_load($group_name);
    $breakpoints = array_intersect_key(drupal_map_assoc($group->breakpoints), $active_breakpoints);
    $mappings->mapping = array_intersect_key($mappings->mapping, $breakpoints);
    foreach ($mappings->mapping as $breakpoint_name => $multipliers) {
      $settings = breakpoints_settings();
      $existing_multipliers = drupal_map_assoc($settings->multipliers);
      $multipliers = array_intersect_key($multipliers, array_intersect_key($existing_multipliers, array_filter($active_breakpoints[$breakpoint_name]->multipliers)));
      if (!empty($multipliers) && is_array($multipliers)) {
        foreach ($multipliers as $multiplier => $image_style) {
          if (!empty($image_style)) {
            if (!isset($breakpoint_styles['mapping'][$breakpoint_name])) {
              $breakpoint_styles['mapping'][$breakpoint_name] = array();
            }
            $breakpoint_styles['mapping'][$breakpoint_name][$multiplier] = $image_style;
          }
        }
      }
    }
  }
  return $breakpoint_styles;
}