lib.php 45.9 KB
Newer Older
Evan Goldenberg's avatar
Evan Goldenberg committed
1
2
3
4
<?php
/**
 *
 * @package    mahara
5
 * @subpackage blocktype-gallery
Evan Goldenberg's avatar
Evan Goldenberg committed
6
 * @author     Catalyst IT Ltd
7
 * @author     Gregor Anzelj (External Galleries, e.g. Flickr, Picasa)
8
9
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL version 3 or later
 * @copyright  For copyright information on Mahara, please see the README file distributed with this software.
10
 * @copyright  (C) 2011 Gregor Anzelj <gregor.anzelj@gmail.com>
Evan Goldenberg's avatar
Evan Goldenberg committed
11
12
13
14
15
 *
 */

defined('INTERNAL') || die();

16
class PluginBlocktypeGallery extends MaharaCoreBlocktype {
Evan Goldenberg's avatar
Evan Goldenberg committed
17
18
19
20
21

    public static function get_title() {
        return get_string('title', 'blocktype.file/gallery');
    }

Lisa Seeto's avatar
Lisa Seeto committed
22
23
24
25
26
27
28
29
    /** When the Image Gallery is displayed from a folder it will have a single
    ** artefact and warrant a details block header. No header will display if
    ** individual images (with multiple artefacts) were selected instead.
    **/
    public static function single_artefact_per_block() {
        return true;
    }

Evan Goldenberg's avatar
Evan Goldenberg committed
30
    public static function get_description() {
31
        return get_string('description1', 'blocktype.file/gallery');
Evan Goldenberg's avatar
Evan Goldenberg committed
32
33
34
    }

    public static function get_categories() {
35
        return array('fileimagevideo' => 5000);
Evan Goldenberg's avatar
Evan Goldenberg committed
36
37
    }

38
39
40
41
    public static function get_viewtypes() {
        return array('dashboard', 'portfolio', 'profile', 'grouphomepage');
    }

Evan Goldenberg's avatar
Evan Goldenberg committed
42
    public static function get_instance_javascript(BlockInstance $instance) {
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
        $blockid = $instance->get('id');
        // The initjs for the fancybox will be applied to all galleries on the page
        return array(
            array(
                'file'   => get_config('wwwroot') . 'js/fancybox/jquery.fancybox.min.js',
                'initjs' => " $('[data-fancybox]').fancybox({
                      buttons : [
                               'zoom',
                               'slideShow',
                               'download',
                               'close'
                               ],
                      loop : true,
                      lang : '" . current_language() . "',
                      i18n : {
                          '" . current_language() . "' : {
                              CLOSE: \"" . get_string('CLOSE', 'blocktype.file/gallery') . "\",
                              NEXT: \"" . get_string('NEXT', 'blocktype.file/gallery') . "\",
                              PREV: \"" . get_string('PREV', 'blocktype.file/gallery') . "\",
                              ERROR: \"" . get_string('ERROR', 'blocktype.file/gallery') . "\",
                              PLAY_START: \"" . get_string('PLAY_START', 'blocktype.file/gallery') . "\",
                              PLAY_STOP: \"" . get_string('PLAY_STOP', 'blocktype.file/gallery') . "\",
                              FULL_SCREEN: \"" . get_string('FULL_SCREEN', 'blocktype.file/gallery') . "\",
                              THUMBS: \"" . get_string('THUMBS', 'blocktype.file/gallery') . "\",
                              DOWNLOAD: \"" . get_string('DOWNLOAD', 'blocktype.file/gallery') . "\",
                              SHARE: \"" . get_string('SHARE', 'blocktype.file/gallery') . "\",
                              ZOOM: \"" . get_string('ZOOM', 'blocktype.file/gallery') . "\"
                          }
                      }
                });"
            ),
            array(
                'file'   => get_config('wwwroot') . 'js/masonry/masonry.min.js',
                'initjs' => " $('.js-masonry.thumbnails').masonry({ itemSelector: '.thumb' });"
77
78
            ),
            array(
79
80
81
82
83
                'file' => '',
                'initjs' => "$(function() {
                    $('#slideshow{$blockid}').on('slid.bs.carousel', function () {
                        $(window).trigger('colresize');
                    });
84
                });"
85
86
87
88
89
90
91
92
            )
        );
    }

    public static function get_instance_css(BlockInstance $instance) {
        return array(
            get_config('wwwroot') . 'js/fancybox/jquery.fancybox.min.css'
        );
Evan Goldenberg's avatar
Evan Goldenberg committed
93
94
    }

Son Nguyen's avatar
Son Nguyen committed
95
    public static function get_instance_config_javascript(BlockInstance $instance) {
96
97
98
        return array(
            'js/configform.js',
        );
Evan Goldenberg's avatar
Evan Goldenberg committed
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
    public static function render_instance_export(BlockInstance $instance, $editing=false, $versioning=false, $exporting=null) {
        if ($exporting != 'pdf') {
            return self::render_instance($instance, $editing, $versioning);
        }
        // The exporting for pdf
        $configdata = $instance->get('configdata'); // this will make sure to unserialize it for us
        $viewid = $instance->get('view');
        $style = isset($configdata['style']) ? intval($configdata['style']) : 2;

        if ($style !== 1) {
            // If not the slideshow then render in normal way
            return self::render_instance($instance, $editing, $versioning);
        }
        else {
            safe_require('artefact', 'file');
            // Slideshow piles all the images on top of each other in PDF so we need to avoid this
            if (isset($configdata['select']) && $configdata['select'] == 1 && is_array($configdata['artefactids'])) {
                $artefactids = $configdata['artefactids'];
            }
            else if ($versioning && !empty($configdata['existing_artefacts'])) {
                $artefactids = (array) $configdata['existing_artefacts'];
            }
            else if (!empty($configdata['artefactid'])) {
                // Get descendents of this folder.
                $artefactids = artefact_get_descendants(array(intval($configdata['artefactid'])));
            }

            $artefactids = $instance->order_artefacts_by_title($artefactids);
            $html = '';

            if ($artefactids) {
                $firstdone = false;
                foreach ($artefactids as $artefactid) {
                    $artefact = $instance->get_artefact_instance($artefactid);
135
136
137
                    if ($artefact->get('artefacttype') == 'folder') {
                        continue;
                    }
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
                    if (!file_exists($artefact->get_path())) {
                        continue;
                    }
                    $urlbase = get_config('wwwroot');
                    $url = $urlbase . 'artefact/file/download.php?file=' . $artefactid . '&view=' . $viewid;
                    $description = $artefact->get('description');
                    if (!$firstdone) {
                        $html .= '<div class="image"><img src="' . $url . '" alt="' . $artefact->get('title') . '"></div>';
                        if ($description) {
                            $html .= '<div class="card-body">' . $description . '</div>';
                        }
                        $html .= '<div class="text-midtone">' . get_string('notrendertopdf', 'artefact.file');
                        $html .= '<br>' . get_string('notrendertopdffiles', 'artefact.file', count($artefactids));
                        $firstdone = true;
                    }
                    $html .= '<br><a href="' . $url . '">' . $artefact->get('title') . '</a>';
                }
                $html .= '</div>';
            }
            return $html;
        }
    }

161
    public static function render_instance(BlockInstance $instance, $editing=false, $versioning=false) {
Evan Goldenberg's avatar
Evan Goldenberg committed
162
163
        $configdata = $instance->get('configdata'); // this will make sure to unserialize it for us
        $configdata['viewid'] = $instance->get('view');
164
165
        $style = isset($configdata['style']) ? intval($configdata['style']) : 2;
        $copyright = null; // Needed to set Panoramio copyright later...
166
        $width = !empty($configdata['width']) ? $configdata['width'] : 75;
167
        $width = floor($width);
Richard Mansfield's avatar
Richard Mansfield committed
168
        switch ($style) {
Evan Goldenberg's avatar
Evan Goldenberg committed
169
170
171
172
173
            case 0: // thumbnails
                $template = 'thumbnails';
                break;
            case 1: // slideshow
                $template = 'slideshow';
174
                $width = !empty($configdata['width']) ? $configdata['width'] : 400;
Evan Goldenberg's avatar
Evan Goldenberg committed
175
                break;
176
177
178
            case 2: // square thumbnails
                $template = 'squarethumbs';
                break;
Evan Goldenberg's avatar
Evan Goldenberg committed
179
180
        }

181
        $images = array();
182
        $fancyboxattr = get_config_plugin('blocktype', 'gallery', 'usefancybox') ? 'lightbox_' . $instance->get('id') : null;
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
        // if we're trying to embed external gallery (thumbnails or slideshow)
        if (isset($configdata['select']) && $configdata['select'] == 2) {
            $gallery = self::make_gallery_url($configdata['external']);
            if (empty($gallery)) {
                return get_string('externalnotsupported', 'blocktype.file/gallery');
            }
            $url  = isset($gallery['url']) ? hsc($gallery['url']) : null;
            $type = isset($gallery['type']) ? hsc($gallery['type']) : null;
            $var1 = isset($gallery['var1']) ? hsc($gallery['var1']) : null;
            $var2 = isset($gallery['var2']) ? hsc($gallery['var2']) : null;

            switch ($type) {
                case 'widget':
                /*****************************
                  Roy Tanck's FLICKR WIDGET
                  for Flickr RSS & Picasa RSS
          http://www.roytanck.com/get-my-flickr-widget/
                 *****************************/
                    $widget_sizes = array(100, 200, 300);
                    $width = self::find_nearest($widget_sizes, $width);
                    $images = urlencode(str_replace('&amp;', '&', $url));
                    $template = 'imagecloud';
                    break;
                case 'picasa':
                    // Slideshow
                    if ($style == 1) {
                        $picasa_show_sizes = array(144, 288, 400, 600, 800);
                        $width = self::find_nearest($picasa_show_sizes, $width);
                        $height = round($width * 0.75);
                        $images = array('user' => $var1, 'gallery' => $var2);
                        $template = 'picasashow';
                    }
                    // Thumbnails
                    else {
                        $picasa_thumbnails = array(32, 48, 64, 72, 104, 144, 150, 160);
                        $width = self::find_nearest($picasa_thumbnails, $width);
                        // If the Thumbnails should be Square...
                        if ($style == 2) {
                            $small = 's' . $width . '-c';
                            $URL = 'http://picasaweb.google.com/data/feed/api/user/' . $var1 . '/album/' . $var2 . '?kind=photo&thumbsize=' . $width . 'c';
                        }
                        else {
                            $small = 's' . $width;
                            $URL = 'http://picasaweb.google.com/data/feed/api/user/' . $var1 . '/album/' . $var2 . '?kind=photo&thumbsize=' . $width;
                        }
                        $big = 's' . get_config_plugin('blocktype', 'gallery', 'previewwidth');

231
                        libxml_before(true);
232
233
234
235
236
237
238
239
                        $xmlDoc = new DOMDocument('1.0', 'UTF-8');
                        $config = array(
                            CURLOPT_URL => $URL,
                            CURLOPT_RETURNTRANSFER => true,
                        );
                        $result = mahara_http_request($config);
                        $xmlDoc->loadXML($result->data);
                        $photos = $xmlDoc->getElementsByTagNameNS('http://search.yahoo.com/mrss/', 'group');
240
241
                        libxml_after();

242
243
244
245
246
247
248
249
250
251
252
253
                        foreach ($photos as $photo) {
                            $children = $photo->cloneNode(true);
                            $thumb = $children->getElementsByTagNameNS('http://search.yahoo.com/mrss/', 'thumbnail')->item(0)->getAttribute('url');
                            $description = null;
                            if (isset($children->getElementsByTagNameNS('http://search.yahoo.com/mrss/', 'description')->item(0)->firstChild->nodeValue)) {
                                $description = $children->getElementsByTagNameNS('http://search.yahoo.com/mrss/', 'description')->item(0)->firstChild->nodeValue;
                            }

                            $images[] = array(
                                'link' => str_replace($small, $big, $thumb),
                                'source' => $thumb,
                                'title' => $description,
254
                                'fancybox' => $fancyboxattr
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
                            );
                        }
                    }
                    break;
                case 'flickr':
                    // Slideshow
                    if ($style == 1) {
                        $flickr_show_sizes = array(400, 500, 700, 800);
                        $width = self::find_nearest($flickr_show_sizes, $width);
                        $height = round($width * 0.75);
                        $images = array('user' => $var1, 'gallery' => $var2);
                        $template = 'flickrshow';
                    }
                    // Thumbnails
                    else {
                        $width = 75; // Currently only thumbnail size, that Flickr supports

                        $api_key = get_config_plugin('blocktype', 'gallery', 'flickrapikey');
273
                        $URL = 'https://api.flickr.com/services/rest/?method=flickr.photosets.getPhotos&extras=url_sq,url_t&photoset_id=' . $var2 . '&api_key=' . $api_key;
274
                        libxml_before(true);
275
276
277
278
279
280
281
282
                        $xmlDoc = new DOMDocument('1.0', 'UTF-8');
                        $config = array(
                            CURLOPT_URL => $URL,
                            CURLOPT_RETURNTRANSFER => true,
                        );
                        $result = mahara_http_request($config);
                        $xmlDoc->loadXML($result->data);
                        $photos = $xmlDoc->getElementsByTagName('photo');
283
                        libxml_after();
284
285
286
287
288
289
290
291
292
293
294
                        foreach ($photos as $photo) {
                            // If the Thumbnails should be Square...
                            if ($style == 2) {
                                $thumb = $photo->getAttribute('url_sq');
                                $link = str_replace('_s.jpg', '_b.jpg', $thumb);
                            }
                            else {
                                $thumb = $photo->getAttribute('url_t');
                                $link = str_replace('_t.jpg', '_b.jpg', $thumb);
                            }
                            $description = $photo->getAttribute('title');
295

296
297
298
299
                            $images[] = array(
                                'link' => $link,
                                'source' => $thumb,
                                'title' => $description,
300
                                'fancybox' => $fancyboxattr
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
                            );
                        }
                    }
                    break;
                case 'photobucket':
                    // Slideshow
                    if ($style == 1) {
                        $height = round($width * 0.75);
                        $images = array('url' => $url, 'user' => $var1, 'album' => $var2);
                        $template = 'photobucketshow';
                    }
                    // Thumbnails
                    else {
                        $consumer_key = get_config_plugin('blocktype', 'gallery', 'pbapikey'); // PhotoBucket API key
                        $consumer_secret = get_config_plugin('blocktype', 'gallery', 'pbapiprivatekey'); //PhotoBucket API private key

                        $oauth_signature_method = 'HMAC-SHA1';
                        $oauth_version = '1.0';
                        $oauth_timestamp = time();
                        $mt = microtime();
                        $rand = mt_rand();
                        $oauth_nonce = md5($mt . $rand);

                        $method = 'GET';
                        $albumname = $var1 . '/' . $var2;
                        $api_url = 'http://api.photobucket.com/album/' . urlencode($albumname);

                        $params = null;
                        $paramstring = 'oauth_consumer_key=' . $consumer_key . '&oauth_nonce=' . $oauth_nonce . '&oauth_signature_method=' . $oauth_signature_method . '&oauth_timestamp=' . $oauth_timestamp . '&oauth_version=' . $oauth_version;
                        $base = urlencode($method) . '&' . urlencode($api_url) . '&' . urlencode($paramstring);
                        $oauth_signature = base64_encode(hash_hmac('sha1', $base, $consumer_secret.'&', true));

                        $URL = $api_url . '?' . $paramstring . '&oauth_signature=' . urlencode($oauth_signature);
334
                        libxml_before(true);
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
                        $xmlDoc = new DOMDocument('1.0', 'UTF-8');
                        $config = array(
                            CURLOPT_URL => $URL,
                            CURLOPT_HEADER => false,
                            CURLOPT_RETURNTRANSFER => true,
                        );
                        $result = mahara_http_request($config);
                        $xmlDoc->loadXML($result->data);

                        $xmlDoc2 = new DOMDocument('1.0', 'UTF-8');
                        $config2 = array(
                            CURLOPT_URL => $xmlDoc->getElementsByTagName('url')->item(0)->firstChild->nodeValue,
                            CURLOPT_HEADER => false,
                            CURLOPT_RETURNTRANSFER => true,
                        );
                        $result2 = mahara_http_request($config2);
                        $xmlDoc2->loadXML($result->data);

                        $photos = $xmlDoc2->getElementsByTagName('media');
354
                        libxml_after();
355
356
357
358
359
360
361
362
363
364
365
366
367
                        foreach ($photos as $photo) {
                            $children = $photo->cloneNode(true);
                            $link = $children->getElementsByTagName('url')->item(0)->firstChild->nodeValue;
                            $thumb = $children->getElementsByTagName('thumb')->item(0)->firstChild->nodeValue;
                            $description = null;
                            if (isset($children->getElementsByTagName('description')->item(0)->firstChild->nodeValue)) {
                                $description = $children->getElementsByTagName('description')->item(0)->firstChild->nodeValue;
                            }

                            $images[] = array(
                                'link' => $link,
                                'source' => $thumb,
                                'title' => $description,
368
                                'fancybox' => $fancyboxattr
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
                            );
                        }
                    }
                    break;
                case 'windowslive':
                    // Slideshow
                    if ($style == 1) {
                        $images = array('url' => $url, 'user' => $var1, 'album' => $var2);
                        $template = 'windowsliveshow';
                    }
                    // Thumbnails
                    else {
                        $config = array(
                            CURLOPT_URL => str_replace(' ', '%20', $url),
                            CURLOPT_HEADER => false,
                            CURLOPT_RETURNTRANSFER => true,
                        );
                        $result = mahara_http_request($config);
                        $data = $result->data;

                        // Extract data about images and thumbs from HTML source - hack!
                        preg_match_all("#previewImageUrl: '([a-zA-Z0-9\_\-\.\\\/]+)'#", $data, $photos);
                        preg_match_all("#thumbnailImageUrl: '([a-zA-Z0-9\_\-\.\\\/]+)'#", $data, $thumbs);

                        for ($i = 0; $i < sizeof($photos[1]); $i++) {
                            $images[] = array(
                                'link' => str_replace(array('\x3a','\x2f','\x25','\x3fpsid\x3d1'), array(':','/','%',''), $photos[1][$i]),
                                'source' => str_replace(array('\x3a','\x2f','\x25','\x3fpsid\x3d1'), array(':','/','%',''), $thumbs[1][$i]),
                                'title' => null,
398
                                'fancybox' => $fancyboxattr
399
400
401
402
                            );
                        }
                    }
                    break;
403
            }
404
405
        }
        else {
406
            safe_require('artefact', 'file');
407
408
409
            $artefactids = array();
            if (isset($configdata['select']) && $configdata['select'] == 1 && is_array($configdata['artefactids'])) {
                $artefactids = $configdata['artefactids'];
410
            }
411
412
413
            else if ($versioning && !empty($configdata['existing_artefacts'])) {
                $artefactids = (array) $configdata['existing_artefacts'];
            }
414
415
416
            else if (!empty($configdata['artefactid'])) {
                // Get descendents of this folder.
                $artefactids = artefact_get_descendants(array(intval($configdata['artefactid'])));
Evan Goldenberg's avatar
Evan Goldenberg committed
417
            }
418

419
420
            $artefactids = $instance->order_artefacts_by_title($artefactids);

421
422
423
424
            // This can be either an image or profileicon. They both implement
            // render_self
            foreach ($artefactids as $artefactid) {
                $image = $instance->get_artefact_instance($artefactid);
425

426
427
                if ($image instanceof ArtefactTypeProfileIcon) {
                    $src = get_config('wwwroot') . 'thumb.php?type=profileiconbyid&id=' . $artefactid;
428
                    $src .= '&view=' . $instance->get('view');
429
430
431
432
433
434
435
436
437
438
439
                    $description = $image->get('title');
                }
                else if ($image instanceof ArtefactTypeImage) {
                    $src = get_config('wwwroot') . 'artefact/file/download.php?file=' . $artefactid;
                    $src .= '&view=' . $instance->get('view');
                    $description = $image->get('description');
                }
                else {
                    continue;
                }

440
                if ($fancyboxattr) {
441
442
443
                    $link = $src . '&maxwidth=' . get_config_plugin('blocktype', 'gallery', 'previewwidth');
                }
                else {
444
                    $link = get_config('wwwroot') . 'view/view.php?id=' . $instance->get('view') . '&modal=1&block=' . $instance->get('id') .' &artefact=' . $artefactid;
445
446
447
448
                }

                // If the Thumbnails are Square or not...
                if ($style == 2) {
449
450
                    // Determine the scaling for the fitting the image in the square of $width size
                    // Calculate the bigger, width vs height, to work out the ratio
451
                    $configwidth = $width - (!empty($configdata['photoframe']) ? 8 : 0); // $width - photo frame padding
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
                    $imagewidth = $image->get('width');
                    $imageheight = $image->get('height');
                    if ($imagewidth > $imageheight) {
                        $ratio = $imagewidth / $configwidth;
                    }
                    else {
                        $ratio = $imageheight / $configwidth;
                    }
                    $ratiowidth = floor($imagewidth / $ratio);
                    $ratioheight = floor($imageheight / $ratio);
                    // All image dimensions need to be bigger than 15px
                    // see function imagesize_data_to_internal_form()
                    $ratiowidth = $ratiowidth < 16 ? 16 : $ratiowidth;
                    $ratioheight = $ratioheight < 16 ? 16 : $ratioheight;

467
                    $topoffset = floor(($configwidth - $ratioheight) / 2);
468
469
                    $src .= '&size=' . $ratiowidth . 'x' . $ratioheight;
                    $height = $ratioheight;
470
471
472
                }
                else {
                    $src .= '&maxwidth=' . $width;
473
474
475
                    $imgwidth = $image->get('width');
                    $imgheight = $image->get('height');
                    $height = ($imgwidth > $width) ? intval(($width / $imgwidth) * $imgheight) : $imgheight;
476
477
478
                }

                $images[] = array(
Lisa Seeto's avatar
Lisa Seeto committed
479
                    'id' => $image->get('id'),
480
481
                    'link' => $link,
                    'source' => $src,
482
                    'height' => $height,
483
                    'width' => (!empty($ratiowidth) ? $ratiowidth : null),
484
                    'title' => $image->get('description'),
485
                    'fancybox' => $fancyboxattr,
486
487
                    'squaredimensions' => $width,
                    'squaretop' => (!empty($topoffset) ? $topoffset : null),
488
489
                );
            }
Evan Goldenberg's avatar
Evan Goldenberg committed
490
491
492
493
        }

        $smarty = smarty_core();
        $smarty->assign('count', count($images));
494
        $smarty->assign('instanceid', $instance->get('id'));
Evan Goldenberg's avatar
Evan Goldenberg committed
495
        $smarty->assign('images', $images);
496
        $smarty->assign('showdescription', (!empty($configdata['showdescription'])) ? $configdata['showdescription'] : false);
497
        $smarty->assign('width', $width);
Lisa Seeto's avatar
Lisa Seeto committed
498
        $smarty->assign('editing', $editing);
499
500
501
502
503
504
        if (isset($height)) {
            $smarty->assign('height', $height);
        }
        if (isset($needsapikey)) {
            $smarty->assign('needsapikey', $needsapikey);
        }
505
        $smarty->assign('frame', !empty($configdata['photoframe']));
506
        $smarty->assign('copyright', $copyright);
507
508
        if (!empty($configdata['artefactid'])) {
            $artefact = $instance->get_artefact_instance($configdata['artefactid']);
Evan Goldenberg's avatar
Evan Goldenberg committed
509

510
511
512
            require_once(get_config('docroot') . 'artefact/comment/lib.php');
            require_once(get_config('docroot') . 'lib/view.php');
            $view = new View($configdata['viewid']);
513
            list($commentcount, $comments) = ArtefactTypeComment::get_artefact_comments_for_view($artefact, $view, $instance->get('id'), true, $editing, $versioning);
514
        }
Evan Goldenberg's avatar
Evan Goldenberg committed
515
516
517
        return $smarty->fetch('blocktype:gallery:' . $template . '.tpl');
    }

518
519
520
521
522
523
524
525
526
527
528
    public static function has_config() {
        return true;
    }

    public static function get_config_options() {
        $elements = array();
        $elements['gallerysettings'] = array(
            'type' => 'fieldset',
            'legend' => get_string('gallerysettings', 'blocktype.file/gallery'),
            'collapsible' => true,
            'elements' => array(
529
                'usefancybox' => array(
530
                    'type'         => 'switchbox',
531
532
533
                    'title'        => get_string('usefancybox', 'blocktype.file/gallery'),
                    'description'  => get_string('usefancyboxdesc', 'blocktype.file/gallery'),
                    'defaultvalue' => get_config_plugin('blocktype', 'gallery', 'usefancybox'),
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
                ),
                'previewwidth' => array(
                    'type'         => 'text',
                    'size'         => 4,
                    'title'        => get_string('previewwidth', 'blocktype.file/gallery'),
                    'description'  => get_string('previewwidthdesc', 'blocktype.file/gallery'),
                    'defaultvalue' => get_config_plugin('blocktype', 'gallery', 'previewwidth'),
                    'rules'        => array('integer' => true, 'minvalue' => 16, 'maxvalue' => 1600),
                )
            ),
        );
        $elements['flickrsettings'] = array(
            'type' => 'fieldset',
            'legend' => get_string('flickrsettings', 'blocktype.file/gallery'),
            'collapsible' => true,
            'collapsed' => true,
            'elements' => array(
                'flickrapikey' => array(
                    'type'         => 'text',
                    'title'        => get_string('flickrapikey', 'blocktype.file/gallery'),
                    'size'         => 40, // Flickr API key is actually 32 characters long
                    'description'  => get_string('flickrapikeydesc', 'blocktype.file/gallery'),
                    'defaultvalue' => get_config_plugin('blocktype', 'gallery', 'flickrapikey'),
                ),
            ),
        );
        $elements['photobucketsettings'] = array(
            'type' => 'fieldset',
            'legend' => get_string('pbsettings', 'blocktype.file/gallery'),
            'collapsible' => true,
            'collapsed' => true,
565
            'class' => 'last',
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
            'elements' => array(
                'pbapikey' => array(
                    'type'         => 'text',
                    'title'        => get_string('pbapikey', 'blocktype.file/gallery'),
                    'size'         => 20, // PhotoBucket API key is actually 9 characters long
                    'description'  => get_string('pbapikeydesc', 'blocktype.file/gallery'),
                    'defaultvalue' => get_config_plugin('blocktype', 'gallery', 'pbapikey'),
                ),
                'pbapiprivatekey' => array(
                    'type'         => 'text',
                    'title'        => get_string('pbapiprivatekey', 'blocktype.file/gallery'),
                    'size'         => 40, // PhotoBucket API private key is actually 32 characters long
                    'defaultvalue' => get_config_plugin('blocktype', 'gallery', 'pbapiprivatekey'),
                ),
            ),
        );
        return array(
            'elements' => $elements,
584
585
            // Don't apply "panel panel-body" style to this form.
            'class' => null,
586
587
588
589
        );

    }

Son Nguyen's avatar
Son Nguyen committed
590
    public static function save_config_options(Pieform $form, $values) {
591
        set_config_plugin('blocktype', 'gallery', 'usefancybox', (int)$values['usefancybox']);
592
593
594
595
596
597
598
599
        set_config_plugin('blocktype', 'gallery', 'previewwidth', (int)$values['previewwidth']);
        set_config_plugin('blocktype', 'gallery', 'flickrapikey', $values['flickrapikey']);
        set_config_plugin('blocktype', 'gallery', 'pbapikey', $values['pbapikey']);
        set_config_plugin('blocktype', 'gallery', 'pbapiprivatekey', $values['pbapiprivatekey']);
    }

    public static function postinst($prevversion) {
        if ($prevversion == 0) {
600
601
            set_config_plugin('blocktype', 'gallery', 'usefancybox', 1); // Use Fancybox 3 by default
            set_config_plugin('blocktype', 'gallery', 'previewwidth', 1024); // Maximum photo width for fancybox preview
602
603
604
        }
    }

605
    public static function has_instance_config(BlockInstance $instance) {
Evan Goldenberg's avatar
Evan Goldenberg committed
606
607
608
        return true;
    }

Son Nguyen's avatar
Son Nguyen committed
609
    public static function instance_config_form(BlockInstance $instance) {
Evan Goldenberg's avatar
Evan Goldenberg committed
610
611
612
613
614
        $configdata = $instance->get('configdata');
        safe_require('artefact', 'file');
        $instance->set('artefactplugin', 'file');
        $user = $instance->get('view_obj')->get('owner');
        $select_options = array(
615
616
            0 => get_string('selectfolder', 'blocktype.file/gallery'),
            1 => get_string('selectimages', 'blocktype.file/gallery'),
617
            2 => get_string('selectexternal', 'blocktype.file/gallery'),
Evan Goldenberg's avatar
Evan Goldenberg committed
618
619
620
        );
        $style_options = array(
            0 => get_string('stylethumbs', 'blocktype.file/gallery'),
621
            2 => get_string('stylesquares', 'blocktype.file/gallery'),
Evan Goldenberg's avatar
Evan Goldenberg committed
622
623
            1 => get_string('styleslideshow', 'blocktype.file/gallery'),
        );
624
625
626
        if (isset($configdata['select']) && $configdata['select'] == 1) {
            $imageids = isset($configdata['artefactids']) ? $configdata['artefactids'] : array();
            $imageselector = self::imageselector($instance, $imageids);
627
628
            $folderselector = self::folderselector($instance, null, 'd-none');
            $externalurl = self::externalurl($instance, null, 'd-none');
629
630
        }
        else if (isset($configdata['select']) && $configdata['select'] == 2) {
631
632
            $imageselector = self::imageselector($instance, null, 'd-none');
            $folderselector = self::folderselector($instance, null, 'd-none');
633
634
            $url = isset($configdata['external']) ? urldecode($configdata['external']) : null;
            $externalurl = self::externalurl($instance, $url);
635
636
        }
        else {
637
            $imageselector = self::imageselector($instance, null, 'd-none');
638
639
            $folderid = !empty($configdata['artefactid']) ? array(intval($configdata['artefactid'])) : null;
            $folderselector = self::folderselector($instance, $folderid);
640
            $externalurl = self::externalurl($instance, null, 'd-none');
641
        }
Evan Goldenberg's avatar
Evan Goldenberg committed
642
643
644
645
646
647
648
649
650
651
652
        return array(
            'user' => array(
                'type' => 'hidden',
                'value' => $user,
            ),
            'select' => array(
                'type' => 'radio',
                'title' => get_string('select', 'blocktype.file/gallery'),
                'options' => $select_options,
                'defaultvalue' => (isset($configdata['select'])) ? $configdata['select'] : 0,
            ),
653
654
            'images' => $imageselector,
            'folder' => $folderselector,
655
            'external' => $externalurl,
Evan Goldenberg's avatar
Evan Goldenberg committed
656
657
658
659
            'style' => array(
                'type' => 'radio',
                'title' => get_string('style', 'blocktype.file/gallery'),
                'options' => $style_options,
660
                'defaultvalue' => (isset($configdata['style'])) ? $configdata['style'] : 2, // Square thumbnails should be default...
Evan Goldenberg's avatar
Evan Goldenberg committed
661
            ),
662
            'showdescription' => array(
663
                'type'  => 'switchbox',
664
665
666
667
                'title' => get_string('showdescriptions', 'blocktype.file/gallery'),
                'description' => get_string('showdescriptionsdescription', 'blocktype.file/gallery'),
                'defaultvalue' => !empty($configdata['showdescription']) ? true : false,
            ),
668
669
670
671
672
673
            'photoframe' => array(
                'type'         => 'switchbox',
                'title'        => get_string('photoframe', 'blocktype.file/gallery'),
                'description'  => get_string('photoframedesc2', 'blocktype.file/gallery'),
                'defaultvalue' => !empty($configdata['photoframe']) ? true : false,
            ),
Evan Goldenberg's avatar
Evan Goldenberg committed
674
675
676
677
678
679
680
681
682
683
684
685
686
687
            'width' => array(
                'type' => 'text',
                'title' => get_string('width', 'blocktype.file/gallery'),
                'size' => 3,
                'description' => get_string('widthdescription', 'blocktype.file/gallery'),
                'rules' => array(
                    'minvalue' => 16,
                    'maxvalue' => get_config('imagemaxwidth'),
                ),
                'defaultvalue' => (isset($configdata['width'])) ? $configdata['width'] : '75',
            ),
        );
    }

Son Nguyen's avatar
Son Nguyen committed
688
    public static function instance_config_validate(Pieform $form, $values) {
689
690
691
692
        global $USER;

        if (!empty($values['images'])) {
            foreach ($values['images'] as $id) {
693
                $image = artefact_instance_from_id($id);
694
                if (!($image instanceof ArtefactTypeImage) || !$USER->can_view_artefact($image)) {
695
696
697
698
699
700
                    $result['message'] = get_string('unrecoverableerror', 'error');
                    $form->set_error(null, $result['message']);
                    $form->reply(PIEFORM_ERR, $result);
                }
            }
        }
701
702
703

        if (!empty($values['folder'])) {
            $folder = artefact_instance_from_id($values['folder']);
704
            if (!($folder instanceof ArtefactTypeFolder) || !$USER->can_view_artefact($folder)) {
705
706
707
708
709
                $result['message'] = get_string('unrecoverableerror', 'error');
                $form->set_error(null, $result['message']);
                $form->reply(PIEFORM_ERR, $result);
            }
        }
710
711
    }

Evan Goldenberg's avatar
Evan Goldenberg committed
712
713
    public static function instance_config_save($values) {
        if ($values['select'] == 0) {
714
715
            $values['artefactid'] = $values['folder'];
            unset($values['artefactids']);
716
            unset($values['external']);
717
718
719
720
        }
        else if ($values['select'] == 1) {
            $values['artefactids'] = $values['images'];
            unset($values['artefactid']);
721
722
723
724
725
            unset($values['external']);
        }
        else if ($values['select'] == 2) {
            unset($values['artefactid']);
            unset($values['artefactids']);
Evan Goldenberg's avatar
Evan Goldenberg committed
726
        }
727
728
        unset($values['folder']);
        unset($values['images']);
729
730
731
732
733
734
735
736
737
        switch ($values['style']) {
            case 0: // thumbnails
            case 2: // square thumbnails
                $values['width'] = !empty($values['width']) ? $values['width'] : 75;
                break;
            case 1: // slideshow
                $values['width'] = !empty($values['width']) ? $values['width'] : 400;
                break;
        }
Evan Goldenberg's avatar
Evan Goldenberg committed
738
739
740
        return $values;
    }

741
    public static function imageselector(&$instance, $default=array(), $class=null) {
Evan Goldenberg's avatar
Evan Goldenberg committed
742
        $element = ArtefactTypeFileBase::blockconfig_filebrowser_element($instance, $default);
743
744
        $element['title'] = get_string('Images', 'artefact.file');
        $element['name'] = 'images';
745
        $element['accept'] = 'image/*';
746
747
748
        if ($class) {
            $element['class'] = $class;
        }
Evan Goldenberg's avatar
Evan Goldenberg committed
749
        $element['config']['selectone'] = false;
750
        $element['config']['selectmodal'] = true;
Evan Goldenberg's avatar
Evan Goldenberg committed
751
        $element['filters'] = array(
752
            'artefacttype'    => array('image', 'profileicon'),
Evan Goldenberg's avatar
Evan Goldenberg committed
753
754
755
756
        );
        return $element;
    }

757
758
759
760
761
762
763
764
765
766
    public static function folderselector(&$instance, $default=array(), $class=null) {
        $element = ArtefactTypeFileBase::blockconfig_filebrowser_element($instance, $default);
        $element['title'] = get_string('folder', 'artefact.file');
        $element['name'] = 'folder';
        if ($class) {
            $element['class'] = $class;
        }
        $element['config']['upload'] = false;
        $element['config']['selectone'] = true;
        $element['config']['selectfolders'] = true;
767
        $element['config']['selectmodal'] = true;
768
769
770
771
772
773
        $element['filters'] = array(
            'artefacttype'    => array('folder'),
        );
        return $element;
    }

774
775
776
777
778
779
780
781
    public static function externalurl(&$instance, $default=null, $class=null) {
        $element['title'] = get_string('externalgalleryurl', 'blocktype.file/gallery');
        $element['name'] = 'external';
        $element['type'] = 'textarea';
        if ($class) {
            $element['class'] = $class;
        }
        $element['rows'] = 5;
782
        $element['cols'] = 76;
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
        $element['defaultvalue'] = $default;
        $element['description'] = '<tr id="externalgalleryhelp" class="'.($class ? $class : '').'"><td colspan="2" class="description">'.
                                  get_string('externalgalleryurldesc', 'blocktype.file/gallery') . self::get_supported_external_galleries() .
                                  '</td></tr>';
        $element['help'] = true;
        return $element;
    }

    private static function make_gallery_url($url) {
        static $embedsources = array(
            // PicasaWeb Album (RSS) - for Roy Tanck's widget
            array(
                'match' => '#.*picasaweb.google.([a-zA-Z]{3}).*user\/([a-zA-Z0-9\_\-\=\&\.\/\:\%]+)\/albumid\/(\d+).*#',
                'url'   => 'http://picasaweb.google.$1/data/feed/base/user/$2/albumid/$3?alt=rss&kind=photo',
                'type'  => 'widget',
                'var1' => '$2',
                'var2' => '$3',
            ),
            // PicasaWeb Album (embed code)
            array(
                'match' => '#.*picasaweb.google.([a-zA-Z]{3})\/s\/c.*picasaweb.google.([a-zA-Z]{3})\/([a-zA-Z0-9\_\-\.]+)\/([a-zA-Z0-9\_\-\=\&\.\/\:\%]+).*#',
                'url'   => 'http://picasaweb.google.$2',
                'type'  => 'picasa',
                'var1' => '$3',
                'var2' => '$4',
            ),
            // PicasaWeb Album (direct link)
            array(
                'match' => '#.*picasaweb.google.([a-zA-Z]{3})\/([a-zA-Z0-9\_\-\.]+)\/([a-zA-Z0-9\_\-\=\&\.\/\:\%]+).*#',
                'url'   => 'http://picasaweb.google.$1',
                'type'  => 'picasa',
                'var1' => '$2',
                'var2' => '$3',
            ),
            // Flickr Set (RSS) - for Roy Tanck's widget
            array(
                'match' => '#.*api.flickr.com.*set=(\d+).*nsid=([a-zA-Z0-9\@]+).*#',
820
                'url'   => 'https://api.flickr.com/services/feeds/photoset.gne?set=$1&nsid=$2',
821
822
823
824
825
826
827
                'type'  => 'widget',
                'var1' => '$2',
                'var2' => '$1',
            ),
            // Flickr Set (direct link)
            array(
                'match' => '#.*www.flickr.com/photos/([a-zA-Z0-9\_\-\.\@]+).*/sets/([0-9]+).*#',
828
                'url'   => 'https://www.flickr.com/photos/$1/sets/$2/',
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
                'type'  => 'flickr',
                'var1' => '$1',
                'var2' => '$2',
            ),
            // Photobucket User Photos (direct link)
            array(
                'match' => '#.*([a-zA-Z0-9]+).photobucket.com/albums/([a-zA-Z0-9]+)/([a-zA-Z0-9\.\,\:\;\@\-\_\+\ ]+).*#',
                'url'   => 'http://$1.photobucket.com/albums/$2/$3',
                'type'  => 'photobucket',
                'var1' => '$3',
                'var2' => null,
            ),
            // Photobucket User Album Photos (direct link)
            array(
                'match' => '#.*([a-zA-Z0-9]+).photobucket.com/albums/([a-zA-Z0-9]+)/([a-zA-Z0-9\.\,\:\;\@\-\_\+\ ]+)/([a-zA-Z0-9\.\,\:\;\@\-\_\+\ ]*).*#',
                'url'   => 'http://$1.photobucket.com/albums/$2/$3/$4',
                'type'  => 'photobucket',
                'var1' => '$3',
                'var2' => '$4',
            ),
            // Windows Live Photo Gallery (MUST be a direct link to one of the photos in the album!)
            // This is a hack - in order to show photos from the album, we require a direct link to one of the photos.
            array(
                'match' => '#.*cid-([a-zA-Z0-9]+).photos.live.com/self.aspx/([a-zA-Z0-9\.\,\:\;\@\-\_\+\%\ ]+)/([a-zA-Z0-9\,\:\;\@\-\_\+\%\ ]+).(gif|png|jpg|jpeg)*#',
                'url'   => 'http://cid-$1.photos.live.com/self.aspx/$2/$3.$4',
                'type'  => 'windowslive',
                'var1' => 'cid-$1',
                'var2' => '$2',
            ),
        );

        foreach ($embedsources as $source) {
            $url = htmlspecialchars_decode($url); // convert &amp; back to &, etc.
            if (preg_match($source['match'], $url)) {
                $images_url = preg_replace($source['match'], $source['url'], $url);
                $images_type = $source['type'];
                $images_var1 = preg_replace($source['match'], $source['var1'], $url);
                $images_var2 = preg_replace($source['match'], $source['var2'], $url);
                return array('url' => $images_url, 'type' => $images_type, 'var1' => $images_var1, 'var2' => $images_var2);
            }
        }
        return array();
    }

    /**
     * Returns a block of HTML that the Gallery block can use to list
     * which external galleries or photo services are supported.
     */
    private static function get_supported_external_galleries() {
        $smarty = smarty_core();
        $smarty->assign('wwwroot', get_config('wwwroot'));
880
        if (is_https() === true) {
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
            $smarty->assign('protocol', 'https');
        }
        else {
            $smarty->assign('protocol', 'http');
        }
        return $smarty->fetch('blocktype:gallery:supported.tpl');
    }

    // Function to find nearest value (in array of values) to given value
    // e.g.: user defined thumbnail width is 75, abvaliable picasa thumbnails are array(32, 48, 64, 72, 104, 144, 150, 160)
    //         so this function should return 72 (which is nearest form available values)
    // Function found at http://www.sitepoint.com/forums/showthread.php?t=537541
    public static function find_nearest($values, $item) {
        if (in_array($item,$values)) {
            $out = $item;
        }
        else {
            sort($values);
            $length = count($values);
            for ($i=0; $i<$length; $i++) {
                if ($values[$i] > $item) {
                    if ($i == 0) {
                        return $values[$i];
                    }
                    $out = ($item - $values[$i-1]) > ($values[$i]-$item) ? $values[$i] : $values[$i-1];
                    break;
                }
            }
        }
        if (!isset($out)) {
            $out = end($values);
        }
        return $out;
    }

Evan Goldenberg's avatar
Evan Goldenberg committed
916
917
918
919
920
921
    public static function artefactchooser_element($default=null) {
    }

    public static function default_copy_type() {
        return 'full';
    }
922
923
924
925
926
927
928
929
930
931

    public static function get_current_artefacts(BlockInstance $instance) {
        $configdata = $instance->get('configdata');
        $artefacts = array();
        if (isset($configdata['artefactid'])) {
            safe_require('artefact', 'file');
            $artefacts = artefact_get_descendants(array(intval($configdata['artefactid'])));
        }
        return $artefacts;
    }
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976

    public static function shows_details_in_modal(BlockInstance $instance) {
        $configdata = $instance->get('configdata');
        return isset($configdata['artefactids']);
    }

    public static function render_details_in_modal(BlockInstance $instance) {
        $artefacts = $instance->get('configdata')['artefactids'];
        $smarty = smarty_core();

        if ($artefacts) {
            safe_require('artefact', 'comment');
            $childrecords = array();
            foreach ($artefacts as $a) {
                $c = artefact_instance_from_id($a);
                $child = new StdClass();
                $child->id = $a;
                $child->description = $c->get('description');
                $child->size = $c->describe_size();
                $child->title = $child->hovertitle = $c->get('title');
                $child->artefacttype = $c->get('artefacttype');
                $child->iconsrc = call_static_method(generate_artefact_class_name($c->get('artefacttype')), 'get_icon', array('id' => $a, 'viewid' => $instance->get('view')));
                $count = ArtefactTypeComment::count_comments(null, array($child->id));
                if ($count) {
                    $child->commentcount = $count[$child->id]->comments;
                }
                else {
                    $child->commentcount = 0;
                }
                $childrecords[] = $child;
            }
            $smarty->assign('children', $childrecords);
        }
        $smarty->assign('blockid', $instance->get('id'));
        $smarty->assign('modal', true);
        $smarty->assign('viewid', $instance->get('view'));

        $template = 'artefact:file:folder_render_in_modal.tpl';

        return array(
            'html' => $smarty->fetch($template),
            'artefactids' =>  $instance->get('configdata')['artefactids'],
            'javascript'=>'',
        );
    }
Evan Goldenberg's avatar
Evan Goldenberg committed
977
}