Completed
Push — development ( c8f467...de45b7 )
by Andrij
10:53
created

application/modules/gallery/admin.php (1 issue)

Drupal.WhiteSpace.Comma.NoSpace

Unknown

Upgrade to new PHP Analysis Engine

These results are based on our legacy PHP analysis, consider migrating to our new PHP analysis engine instead. Learn more

1
<?php
2
3
if (!defined('BASEPATH')) {
4
    exit('No direct script access allowed');
5
}
6
7
/**
8
 * ImageCMS
9
 *
10
 * Gallery Module _Admin_
11
 */
12
//class Admin extends MY_Controller {
13
class Admin extends BaseAdminController
14
{
15
16
    // Gallery config
17
    public $conf = [
18
        'engine' => 'gd2', // Image library. Possible values: GD, GD2, ImageMagick, NetPBM
19
        'max_file_size' => 5, // Max file size for upload in Mb.
20
        'max_archive_size' => 50,
21
        'max_width' => 0, // Max image width.
22
        'max_height' => 0, // Max image height.
23
        'allowed_types' => 'gif|jpg|jpeg|png|zip', // Allowed image types.
24
        'allowed_archive_types' => 'zip',
25
        'upload_path' => './uploads/gallery/', // Image upload dir. With ending slash.
26
        'upload_url' => 'uploads/gallery/', // Image upload url. With ending slash.
27
        'cache_path' => './system/cache/',
28
        'quality' => '90%', // Image quality
29
        'thumb_width' => '100', // Thumb width. min. 20px; max 1000px;
30
        'thumb_height' => '100', // Thumb height min. 20px; max 1000px;
31
        'thumb_marker' => '', // Thumb suffix
32
        'thumbs_folder' => '_thumbs', // Thumbs folder name. ! Without ending slash.
33
        'prev_img_marker' => '_prev', // Preview image suffix
34
        'maintain_ratio' => TRUE, // Specifies whether to maintain the original aspect ratio when resizing.
35
        'maintain_ratio_prev' => TRUE, // Specifies whether to maintain the original aspect ratio when resizing prev image.
36
        'maintain_ratio_icon' => TRUE, // Specifies whether to maintain the original aspect ratio when resizing icon.
37
        'crop' => TRUE, // Specifies whether to crop image for save the original aspect ratio when resizing.
38
        'crop_prev' => TRUE, // Specifies whether to crop image for save the original aspect ratio when resizing prev image.
39
        'crop_icon' => TRUE, // Specifies whether to crop image for save the original aspect ratio when resizing icon.
40
        'prev_img_width' => '500', // Preview image width
41
        'prev_img_height' => '375', // Preview image height
42
        // Watermark params
43
        'watermark_text' => '', // Watermark text.
44
        'watermark_image' => '', // Path to watermark image.
45
        'watermark_image_opacity' => '', // Watermark image opacity.
46
        'watermark_type' => 'overlay', // Watermark type. Possible values: text/overlay.
47
        'wm_vrt_alignment' => 'bottom', // Watermark vertical position. Possible values: top, middle, bottom.
48
        'wm_hor_alignment' => 'right', // Watermark horizontal position. Possible values: left, center, right.
49
        'watermark_font_path' => './system/fonts/1.ttf', // Path to watermark font.
50
        'watermark_font_size' => 16, // Watermark font size.
51
        'watermark_padding' => '-5', // Watermark padding.
52
        'watermark_color' => 'ffffff', // Watermark font color.
53
        'watermark_min_width' => '10', // Min. image width to draw watermark.
54
        'watermark_min_height' => '10', // Min. image height to draw watermark.
55
        // Albums
56
        'order_by' => 'date', // Albums order. Posiible values: date/name/position.
57
        'sort_order' => 'desc'          // Sort order. Possible values: desc/asc.
58
    ];
59
60
    protected $lastnewid;
61
62
    public function __construct() {
63
        parent::__construct();
64
        $lang = new MY_Lang();
65
        $lang->load('gallery');
66
67
        if ($this->dx_auth->is_admin() == FALSE) {
68
            exit;
69
        }
70
71
        $this->lang->load('gallery');
72
73
        $this->load->model('gallery_m');
74
        $this->init_settings();
75
76
        $this->test_uploads_folder($this->conf['upload_path']);
77
        $this->load->helper('file');
78
        $this->load->helper('gallery');
79
    }
80
81
    /**
82
     * Test if gallery upload folder exists.
83
     */
84
    private function test_uploads_folder($path) {
85
        if (!file_exists($path)) {
86
            @mkdir($path);
87
            @chmod($path, 0777);
88
        }
89
90
        if (!is_really_writable($this->conf['upload_path']) OR !file_exists($this->conf['upload_path'])) {
91
92
            \CMSFactory\assetManager::create()
93
                ->setData(
94
                    [
95
                        'error' => lang('Create a directory to continue your work with the gallery', 'gallery') . $this->conf['upload_path'] . lang('Set the write access', 'gallery')
96
                    ]
97
                )
98
                ->renderAdmin('error');
99
            exit;
100
        }
101
    }
102
103
    /**
104
     * Load gallery settings
105
     */
106
    private function init_settings() {
107
        $settings = $this->gallery_m->load_settings();
108
109
        foreach ($settings as $k => $v) {
110
            $this->conf[$k] = $v;
111
        }
112
113
        return TRUE;
114
    }
115
116
    /**
117
     * Display categories list
118
     */
119
    public function index() {
120
121
        $categories = $this->gallery_m->get_categories('position', 'asc');
122
123
        \CMSFactory\assetManager::create()
124
            ->setData(
125
                [
126
                    'categories' => $categories,
127
                ]
128
            )
129
            ->renderAdmin('categories');
130
    }
131
132
    /**
133
     * Display category albums
134
     */
135
    public function category($id) {
136
        $albums = $this->gallery_m->get_albums('position', 'asc', $id);
137
138
        if ($albums != FALSE) {
139
            $cnt = count($albums);
140
141
            for ($i = 0; $i < $cnt; $i++) {
142
                // Create url to album cover
143
                $albums[$i]['cover_url'] = media_url($upload_url . $albums[$i]['id'] . '/' . $albums[$i]['cover_name'] . $albums[$i]['cover_ext']);
144
145
                $upload_url = $this->conf['upload_url'];
146
147
                if ($albums[$i]['cover_name'] == NULL) {
148
                    $image = $this->gallery_m->get_last_image($albums[$i]['id']);
149
150
                    if ($image != FALSE) {
151
                        $albums[$i]['cover_url'] = media_url($upload_url . $albums[$i]['id'] . '/' . $image['file_name'] . $image['file_ext']);
152
                    } else {
153
                        $albums[$i]['cover_url'] = 'empty';
154
                    }
155
                } else {
156
                    $albums[$i]['cover_url'] = media_url($upload_url . $albums[$i]['id'] . '/' . $albums[$i]['cover_name'] . $albums[$i]['cover_ext']);
157
                }
158
            }
159
160
            $this->template->add_array([]);
161
        }
162
163
        \CMSFactory\assetManager::create()
164
            ->setData(
165
                [
166
                    'albums' => $albums,
167
                    'category' => $this->gallery_m->get_category($id)
168
                ]
169
            )
170
            ->renderAdmin('album_list');
171
    }
172
173
    /**
174
     * Display settings.tpl and update seetings.
175
     */
176
    public function settings($action = 'show') {
177
178
        switch ($action) {
179
            case 'show':
180
                \CMSFactory\assetManager::create()
181
                    ->setData(
182
                        [
183
                            'settings' => $this->gallery_m->load_settings()
184
                        ]
185
                    )
186
                    ->renderAdmin('settings');
187
                break;
188
189
            case 'update':
190
191
                $this->load->library('Form_validation');
192
                $val = $this->form_validation;
193
194
                $val->set_rules('max_image_size', lang('File size', 'gallery'), 'required|is_natural');
195
                $val->set_rules('max_width', lang('Maximum width', 'gallery'), 'required|is_natural');
196
                $val->set_rules('max_height', lang('Maximum height', 'gallery'), 'required|is_natural');
197
                $val->set_rules('quality', lang('Quality', 'gallery'), 'required|is_natural');
198
                $val->set_rules('prev_img_width', lang('Pre-image width', 'gallery'), 'required|is_natural');
199
                $val->set_rules('prev_img_height', lang('pre-image height', 'gallery'), 'required|is_natural');
200
                $val->set_rules('thumb_width', lang('Icon width', 'gallery'), 'required|is_natural');
201
                $val->set_rules('thumb_height', lang('Icon height', 'gallery'), 'required|is_natural');
202
                $val->set_rules('watermark_text', lang('Watermark text', 'gallery'), 'max_length[100]');
203
                $val->set_rules('watermark_font_size', lang('Font size', 'gallery'), 'required|is_natural');
204
                $val->set_rules('watermark_image_opacity', lang('Transparency', 'gallery'), 'required|is_natural|min_length[1]|max_length[3]');
205
206
                if ($this->form_validation->run($this) == FALSE) {
207
                    showMessage(validation_errors(), false, 'r');
208
                    break;
209
                }
210
211
                // Check if watermark image exists.
212
                if ($this->input->post('watermark_type') == 'overlay' && !file_exists('./uploads/' . $this->input->post('watermark_image')) && !file_exists($this->input->post('watermark_image'))) {
213
                    showMessage(lang('Specify the correct path to watermark image', 'gallery'), false, 'r');
214
                    break;
215
                }
216
217
                if (file_exists('./uploads/' . $this->input->post('watermark_image'))) {
218
                    $imagePath = './uploads/' . trim($this->input->post('watermark_image'));
219
                } elseif (file_exists($this->input->post('watermark_image'))) {
220
                    $imagePath = trim($this->input->post('watermark_image'));
221
                }
222
223
                // Check if watermark font exists.
224
                $params = [
225
                    'max_image_size' => $this->input->post('max_image_size'),
226
                    'max_width' => $this->input->post('max_width'),
227
                    'max_height' => $this->input->post('max_height'),
228
                    'quality' => $this->input->post('quality'),
229
                    'maintain_ratio' => (bool) $this->input->post('maintain_ratio'),
230
                    'maintain_ratio_prev' => (bool) $this->input->post('maintain_ratio_prev'),
231
                    'maintain_ratio_icon' => (bool) $this->input->post('maintain_ratio_icon'),
232
                    'crop' => (bool) $this->input->post('crop'),
233
                    'crop_prev' => (bool) $this->input->post('crop_prev'),
234
                    'crop_icon' => (bool) $this->input->post('crop_icon'),
235
                    'prev_img_width' => $this->input->post('prev_img_width'),
236
                    'prev_img_height' => $this->input->post('prev_img_height'),
237
                    'thumb_width' => $this->input->post('thumb_width'),
238
                    'thumb_height' => $this->input->post('thumb_height'),
239
                    // watermark settings
240
                    'watermark_text' => trim($this->input->post('watermark_text')),
241
                    'wm_vrt_alignment' => $this->input->post('wm_vrt_alignment'),
242
                    'wm_hor_alignment' => $this->input->post('wm_hor_alignment'),
243
                    'watermark_font_size' => trim($this->input->post('watermark_font_size')),
244
                    'watermark_color' => trim($this->input->post('watermark_color')),
245
                    'watermark_padding' => trim($this->input->post('watermark_padding')),
246
                    'watermark_image' => $imagePath,
247
                    'watermark_image_opacity' => trim($this->input->post('watermark_image_opacity')),
248
                    'watermark_type' => trim($this->input->post('watermark_type')),
249
                    'order_by' => $this->input->post('order_by'),
250
                    'sort_order' => $this->input->post('sort_order'),
251
                ];
252
                $uploadPath = './uploads/';
253
                $this->load->library(
254
                    'upload',
255
                    [
256
                        'upload_path' => $uploadPath,
257
                        'max_size' => 1024 * 1024 * 2, //2 Mb
258
                        //'allowed_types' => 'ttf|fnt|fon|otf'
259
                        'allowed_types' => '*'
260
                    ]
261
                );
262
                // saving font file, if specified
263
                if (isset($_FILES['watermark_font_path'])) {
264
                    $uploadPath = './uploads/';
265
                    // TODO: there are no mime-types for fonts in application/config/mimes.php
266
                    $allowedTypes = ['ttf', 'fnt', 'fon', 'otf'];
267
                    $ext = pathinfo($_FILES['watermark_font_path']['name'], PATHINFO_EXTENSION);
268
                    if (in_array($ext, $allowedTypes)) {
269 View Code Duplication
                        if (!$this->upload->do_upload('watermark_font_path')) {
270
                            $this->upload->display_errors('', '');
271
                        } else {
272
                            $udata = $this->upload->data();
273
                            // changing value in the DB
274
                            $params['watermark_font_path'] = $uploadPath . $udata['file_name'];
275
                        }
276
                    }
277
                } else {
278
                    $params['watermark_font_path'] = trim($this->input->post('watermark_font_path_tmp'));
279
                }
280
281
                $postData = $this->input->post();
282
                if ($postData['watermark']['delete_watermark_font_path'] == 1) {
283
                    $path = trim($this->input->post('watermark_font_path_tmp'));
284
                    if (file_exists($path) && !is_dir($path)) {
285
                        chmod($path, 0777);
286
                        unlink($path);
287
                    }
288
289
                    $params['watermark_font_path'] = '';
290
                }
291
292
                $this->db->where('name', 'gallery');
293
                $this->db->update('components', ['settings' => serialize($params)]);
294
295
                $this->lib_admin->log(lang('Gallery settings was edited', 'gallery'));
296
                showMessage(lang('Settings have been saved', 'gallery'));
297
298
                break;
299
        }
300
    }
301
302
    // --------------------------------------------------------------------
303
304
    /**
305
     * Create album
306
     */
307
    public function create_album() {
308
        $this->load->library('Form_validation');
309
310
        $this->form_validation->set_rules('name', lang('Name', 'gallery'), 'required|min_length[3]|max_length[250]');
311
        $this->form_validation->set_rules('email', lang('Description', 'gallery'), 'max_length[500]');
312
        $this->form_validation->set_rules('category_id', lang('Categories', 'gallery'), 'required');
313
314
        if ($this->form_validation->run($this) == FALSE) {
315
            showMessage(validation_errors(), false, 'r');
316
        } else {
317
            $album_id = $this->gallery_m->create_album();
318
319
            // Create album folder
320
            @mkdir($this->conf['upload_path'] . $album_id);
321
322
            chmod($this->conf['upload_path'] . $album_id, 0777);
323
324
            // Create thumbs folder
325
            @mkdir($this->conf['upload_path'] . $album_id . '/' . $this->conf['thumbs_folder']);
326
327
            // Create folder for admin thumbs
328
            @mkdir($this->conf['upload_path'] . $album_id . '/_admin_thumbs');
329
330
            $this->lib_admin->log(lang('Gallery album was created', 'gallery'));
331
            showMessage(lang('Album created', 'gallery'));
332
333
            $this->input->post('action') ? $action = $this->input->post('action') : $action = 'edit';
334
335
            if ($action == 'edit') {
336
                pjax(site_url('admin/components/cp/gallery/edit_album_params/' . $album_id));
337
            }
338
339
            if ($action == 'exit') {
340
                pjax('/admin/components/cp/gallery/category/' . $this->input->post('category_id'));
341
            }
342
        }
343
    }
344
345
    /**
346
     * Update album info
347
     */
348
    public function update_album($id, $locale) {
349
        $this->form_validation->set_rules('name', lang('Name', 'gallery'), 'required');
350
        $tpl_file = $this->input->post('tpl_file');
351
        if (!preg_match('/[a-z]/', $tpl_file) && !empty($tpl_file)) {
352
            showMessage('wrong tpl name', '', 'r');
353
            exit();
354
        }
355
        if ($this->form_validation->run() == false) {
356
            showMessage(validation_errors(), '', 'r');
357
            exit();
358
        } else {
359
            $this->lib_admin->log(lang('Gallery album was updated', 'gallery') . '. Id: ' . $id);
360
            showMessage(lang('Changes have been saved', 'gallery'));
361
        }
362
363
        $data = [
364
            'category_id' => (int) $this->input->post('cat_id'),
365
            // 'name' => $this->input->post('name'),
366
            // 'description' => trim($this->input->post('description')),
367
            'position' => (int) $this->input->post('position'),
368
            'tpl_file' => $this->input->post('tpl_file')
369
        ];
370
371
        $this->gallery_m->update_album($id, $data);
372
373
        $data_locale = [
374
            'id' => $id,
375
            'locale' => $locale,
376
            'name' => $this->input->post('name'),
377
            'description' => trim($this->input->post('description')),
378
        ];
379
380 View Code Duplication
        if ($this->db->where('id', $id)->where('locale', $locale)->get('gallery_albums_i18n')->num_rows()) {
381
            $this->db->where('id', $id)->where('locale', $locale);
382
            $this->db->update('gallery_albums_i18n', $data_locale);
383
        } else {
384
            $this->db->insert('gallery_albums_i18n', $data_locale);
385
        }
386
387
        $album = $this->gallery_m->get_album($id);
388
389
        $this->input->post('action') ? $action = $this->input->post('action') : $action = 'edit';
390
391
        if ($action == 'edit') {
392
            pjax('/admin/components/cp/gallery/edit_album_params/' . $id . '/'. $locale);
393
        }
394
395
        if ($action == 'close') {
396
            pjax('/admin/components/cp/gallery/category/' . $album['category_id']);
397
        }
398
    }
399
400
    public function edit_album_params($id, $locale = null) {
401
        if (null === $locale) {
402
            $locale = $this->gallery_m->chose_locale();
403
        }
404
405
        $album = $this->gallery_m->get_album($id, true, false, false, $locale);
406
407
        if ($album != FALSE) {
408
            \CMSFactory\assetManager::create()
409
                ->setData(
410
                    [
411
                        'locale' => $locale,
412
                        'languages' => $this->db->get('languages')->result_array(),
413
                        'album' => $album,
414
                        'categories' => $this->gallery_m->get_categories($album['category_id']),
415
                    ]
416
                )
417
                ->renderAdmin('album_params');
418
        } else {
419
            show_error(lang("Can't load album information", 'gallery'));
420
        }
421
    }
422
423
    /**
424
     * Delete album
425
     */
426
    public function delete_album($id = FALSE, $category = NULL) {
427
        if ($id == FALSE) {
428
            $id = (int) $this->input->post('album_id');
429
        }
430
431
        $album = $this->gallery_m->get_album($id);
432
433
        if ($album != FALSE) {
434
            //            if ($folder != FALSE) {
435
            $this->load->helper('file');
436
437
            // delete images.
438
            delete_files($this->conf['upload_path'] . $album['id'], TRUE);
439
440
            // delete album dir.
441
            exec('rmdir ' . $this->conf['upload_path'] . $album['id']);
442
            //            rmdir($this->conf['upload_path'] . $album['id'], TRUE);
443
            //            }
444
            $this->gallery_m->delete_album($album['id']);
445
            $this->lib_admin->log(lang('Gallery album was removed', 'gallery') . '. Id: ' . $id);
446
            pjax('/admin/components/cp/gallery/category/' . $category);
447
            //            echo 'deleted';
448
            //            exit;
449
        } else {
450
            showMessage(lang("Can't load album information", 'gallery'));
451
        }
452
    }
453
454
    /**
455
     * Display create_album template
456
     */
457
    public function show_crate_album() {
458
        // Select only category id and name for selectbox
459
        // $this->db->select('id, name');
460
        $cats = $this->gallery_m->get_categories('position', 'asc');
461
        $selectCategory = $this->input->get('category_id');
462
463
        \CMSFactory\assetManager::create()
464
            ->setData(
465
                [
466
                    'categories' => $cats,
467
                    'selectCategory' => $selectCategory,
468
                ]
469
            )
470
            ->renderAdmin('create_album');
471
    }
472
473
    /**
474
     * Show edit album template
475
     */
476
    public function edit_album($id = 0) {
477
        $album = $this->gallery_m->get_album($id);
478
479
        \CMSFactory\assetManager::create()
480
            ->setData(
481
                [
482
                    'album' => $album,
483
                    'category' => $this->gallery_m->get_category($album['category_id']),
484
                    'album_url' => $this->conf['upload_url'] . $id
485
                ]
486
            )
487
            ->renderAdmin('edit_album');
488
    }
489
490
    // --------------------------------------------------------------------
491
492
    public function edit_image($id, $locale = null) {
493
        if ($locale === null) {
494
            $locale = $this->gallery_m->chose_locale();
495
        }
496
        $image = $this->gallery_m->get_image_info($id, $locale);
497
498
        if ($image != FALSE) {
499
            $album = $this->gallery_m->get_album($image['album_id'], FALSE);
500
501
            \CMSFactory\assetManager::create()
502
                ->setData(
503
                    [
504
                        'locale' => $locale,
505
                        'languages' => $this->db->get('languages')->result_array(),
506
                        'image' => $image,
507
                        'album' => $album,
508
                        'category' => $this->gallery_m->get_category($album['category_id']),
509
                        'album_url' => $this->conf['upload_url'] . $album['id']
510
                    ]
511
                )
512
                ->renderAdmin('edit_image');
513
        } else {
514
            show_error(lang("Can't load image information", 'gallery'));
515
        }
516
    }
517
518
    /**
519
     * Rename image
520
     */
521
    public function rename_image($id) {
522
        $image = $this->gallery_m->get_image_info($id);
523
524
        if ($image != FALSE) {
525
            $this->load->library('Form_validation');
526
527
            $this->form_validation->set_rules('new_name', lang('New name', 'gallery'), 'trim|required');
528
529
            if ($this->form_validation->run($this) == FALSE) {
530
                showMessage(validation_errors(), false, 'r');
531
            } else {
532
                $album = $this->gallery_m->get_album($image['album_id'], FALSE);
533
                $new_name = $this->input->post('new_name');
534
535
                $file_path = $this->conf['upload_path'] . $album['id'] . '/';
536
537
                // Rename original file
538
                rename($file_path . $image['file_name'] . $image['file_ext'], $file_path . $new_name . $image['file_ext']);
539
540
                // Rename preview file
541
                rename($file_path . $image['file_name'] . $this->conf['prev_img_marker'] . $image['file_ext'], $file_path . $new_name . $this->conf['prev_img_marker'] . $image['file_ext']);
542
543
                // Rename thumb
544
                rename($file_path . $this->conf['thumbs_folder'] . '/' . $image['file_name'] . $image['file_ext'], $file_path . $this->conf['thumbs_folder'] . '/' . $new_name . $image['file_ext']);
545
546
                // Rename admin thumb
547
                rename($file_path . '_admin_thumbs/' . $image['file_name'] . $image['file_ext'], $file_path . '_admin_thumbs/' . $new_name . $image['file_ext']);
548
549
                // Update file name in db
550
                $this->gallery_m->rename_image($id, $new_name);
551
552
                pjax('/admin/components/cp/gallery/edit_image/' . $image['id']);
553
                showMessage(lang('Changes have been saved', 'gallery'));
554
            }
555
        } else {
556
            showMessage(lang("Can't load image information", 'gallery'), false, 'r');
557
        }
558
    }
559
560
    /**
561
     * Delete image files
562
     */
563
    public function delete_image($ids = 0) {
564
        if ($this->input->post('id')) {
565
            $ids = $this->input->post('id');
566
        }
567
568
        foreach ($ids as $key => $id) {
569
            $image = $this->gallery_m->get_image_info($id);
570
            if ($image != FALSE) {
571
                $album = $this->gallery_m->get_album($image['album_id'], FALSE);
572
                $path = $this->conf['upload_path'] . $album['id'] . '/';
573
574
                // Delete image.
575
                //./uploads/gallery/13/53e96a8b7146a2976f6dd3e064de61db.jpeg
576
                unlink($path . $image['file_name'] . $image['file_ext']);
577
578
                // Delete thumb.
579
                //./uploads/gallery/13/_thumbs/53e96a8b7146a2976f6dd3e064de61db.jpeg
580
                unlink($path . $this->conf['thumbs_folder'] . '/' . $image['file_name'] . $image['file_ext']);
581
582
                // Delete preview file.
583
                unlink($path . $image['file_name'] . $this->conf['prev_img_marker'] . $image['file_ext']);
584
585
                // Delete admin thumb.
586
                unlink($path . '_admin_thumbs/' . $image['file_name'] . $image['file_ext']);
587
588
                // Delete image info.
589
                $this->gallery_m->delete_image($image['id']);
590
                $this->lib_admin->log(lang('Album image deleted.', 'gallery') . '. Id: ' . $image['id']);
591
                showMessage(lang('Photos removed', 'gallery'));
592
            }
593
        }
594
    }
595
596
    /**
597
     * Update image description/position
598
     */
599
    public function update_info($id, $locale = null) {
600
601
        if (null === $locale) {
602
            $locale = $this->gallery_m->chose_locale();
603
        }
604
        $image = $this->gallery_m->get_image_info($id);
605
606
        if ($image != FALSE) {
607
            $album = $this->gallery_m->get_album($image['album_id'], FALSE);
608
609
            $data = [
610
                'description' => trim($this->input->post('description')),
611
                'title' => trim($this->input->post('title')),
612
            ];
613
614
            $this->gallery_m->update_description($id, $data, $locale);
615
616
            $this->gallery_m->update_position($id, trim((int) $this->input->post('position')));
617
618
            if ($this->input->post('cover') == 1) {
619
                $this->gallery_m->set_album_cover($image['album_id'], $image['id']);
620
            } elseif ($this->input->post('cover') != 1 AND $album['cover_id'] == $image['id']) {
621
                $this->gallery_m->set_album_cover($image['album_id'], NULL);
622
            }
623
624
            //showMessage(lang('Changes are saved', 'gallery'));
625
626
            pjax('/admin/components/cp/gallery/edit_album/' . $image['album_id']);
627
        } else {
628
            showMessage(lang("Can't load image information", 'gallery'), false, 'r');
629
        }
630
    }
631
632 View Code Duplication
    public function update_positions() {
633
        $positions = $this->input->post('positions');
634
        foreach ($positions as $key => $value) {
635
            $this->db->where('id', (int) $value)->set('position', $key)->update('gallery_category');
636
        }
637
        showMessage(lang('Positions updated', 'gallery'));
638
    }
639
640 View Code Duplication
    public function update_album_positions() {
641
        $positions = $this->input->post('positions');
642
        foreach ($positions as $key => $value) {
643
            $this->db->where('id', (int) $value)->set('position', $key)->update('gallery_albums');
644
        }
645
        showMessage(lang('Positions updated', 'gallery'));
646
    }
647
648 View Code Duplication
    public function update_img_positions() {
649
        $positions = $this->input->post('positions');
650
        foreach ($positions as $key => $value) {
651
            $this->db->where('id', (int) $value)->set('position', $key)->update('gallery_images');
652
        }
653
        showMessage(lang('Positions updated', 'gallery'));
654
    }
655
656
    /**
657
     * Add uploaded image to album
658
     */
659
    private function add_image($album_id = 0, $file_data = []) {
660
        $this->load->helper('number');
661
662
        $size = $this->get_image_size($file_data['full_path']);
663
664
        $size = byte_format(filesize($file_data['full_path']));
665
666
        $size = str_replace(
667
            ['bytes', 'kilobyte_abbr', 'megabyte_abbr' , 'gigabyte_abbr' , 'terabyte_abbr'],
668
            ['B', 'kB','MB', 'GB', 'TB'],
0 ignored issues
show
Expected one space after the comma, 0 found
Loading history...
669
            $size
670
        );
671
672
        $image_info = [
673
            'album_id' => $album_id,
674
            'file_name' => $file_data['raw_name'],
675
            'file_ext' => $file_data['file_ext'],
676
            'file_size' => $size,
677
            'width' => $size['width'],
678
            'height' => $size['height'],
679
            'uploaded' => time(),
680
            'views' => 0
681
        ];
682
683
        $this->gallery_m->add_image($image_info);
684
    }
685
686
    /**
687
     * Get image width and height
688
     */
689
    private function get_image_size($file_path) {
690
        if (function_exists('getimagesize')) {
691
            $image = @getimagesize($file_path);
692
693
            $size = [
694
                'width' => $image[0],
695
                'height' => $image[1]
696
            ];
697
698
            return $size;
699
        }
700
701
        return FALSE;
702
    }
703
704
    // --------------------------------------------------------------------
705
    // Categories
706
    // --------------------------------------------------------------------
707
708
    public function show_create_category() {
709
        \CMSFactory\assetManager::create()->renderAdmin('create_category');
710
    }
711
712
    public function create_category() {
713
714
        $locale = $this->gallery_m->chose_locale();
715
716
        $this->load->library('Form_validation');
717
        $val = $this->form_validation;
718
719
        $val->set_rules('name', lang('Name', 'gallery'), 'trim|required|max_length[250]|min_length[1]');
720
        $val->set_rules('position', lang('Position', 'gallery'), 'numeric');
721
722
        if ($val->run() == FALSE) {
723
            showMessage(validation_errors(), false, 'r');
724
        } else {
725
            $data = [
726
                //'name' => $this->input->post('name'),
727
                //'description' => trim($this->input->post('description')),
728
                'position' => $this->input->post('position'),
729
                'created' => time(),
730
            ];
731
732
            $last_id = $this->gallery_m->create_category($data);
733
734
            $data_locale = [
735
                'id' => $last_id,
736
                'locale' => $locale,
737
                'name' => $this->input->post('name'),
738
                'description' => trim($this->input->post('description')),
739
            ];
740
741
            $this->db->insert('gallery_category_i18n', $data_locale);
742
743
            $this->lib_admin->log(lang('Gallery category was created', 'gallery'));
744
            //updateDiv('page', site_url('admin/components/cp/gallery'));
745
            //$this->input->post('action') ? $action = $this->input->post('action') : $action = 'edit';
746
747
            if ($this->input->post('action') == 'close') {
748
                pjax('/admin/components/cp/gallery/index');
749
            } else {
750
                pjax('/admin/components/cp/gallery/edit_category/' . $last_id);
751
            }
752
        }
753
    }
754
755
    public function edit_category($id, $locale = null) {
756
757
        if (null === $locale) {
758
            $locale = $this->gallery_m->chose_locale();
759
        }
760
        $category = $this->gallery_m->get_category($id, $locale);
761
762
        \CMSFactory\assetManager::create()
763
            ->setData(
764
                [
765
                    'category' => $category,
766
                    'locale' => $locale,
767
                    'languages' => $this->db->get('languages')->result_array()
768
                ]
769
            )
770
            ->renderAdmin('edit_category');
771
    }
772
773
    public function update_category($id, $locale) {
774
        $this->load->library('Form_validation');
775
        $val = $this->form_validation;
776
777
        $val->set_rules('name', lang('Name', 'gallery'), 'trim|required|max_length[250]|min_length[1]');
778
        $val->set_rules('position', lang('Position', 'gallery'), 'numeric');
779
780
        if ($val->run() == FALSE) {
781
            showMessage(validation_errors(), false, 'r');
782
        } else {
783
            $data = [
784
                'position' => $this->input->post('position')
785
            ];
786
787
            $this->gallery_m->update_category($data, $id);
788
789
            $data_locale = [
790
                'id' => $id,
791
                'locale' => $locale,
792
                'name' => $this->input->post('name'),
793
                'description' => trim($this->input->post('description')),
794
            ];
795
796 View Code Duplication
            if ($this->db->where('id', $id)->where('locale', $locale)->get('gallery_category_i18n')->num_rows()) {
797
                $this->db->where('id', $id)->where('locale', $locale);
798
                $this->db->update('gallery_category_i18n', $data_locale);
799
            } else {
800
                $this->db->insert('gallery_category_i18n', $data_locale);
801
            }
802
803
            $this->lib_admin->log(lang('Gallery category was edited', 'gallery') . '. Id: ' . $id);
804
            showMessage(lang('Changes have been saved', 'gallery'));
805
806
            //updateDiv('page', site_url('admin/components/cp/gallery'));
807
            $this->input->post('action') ? $action = $this->input->post('action') : $action = 'edit';
808
809
            if ($action == 'close') {
810
                pjax('/admin/components/cp/gallery/index');
811
            }
812
            if ($action == 'edit') {
813
                pjax('/admin/components/cp/gallery/edit_category/' . $id .'/' . $locale);
814
            }
815
        }
816
    }
817
818
    public function delete_category() {
819
        foreach ($this->input->post('id') as $id) {
820
821
            // Delete category albums
822
            $albums = $this->gallery_m->get_albums('date', 'desc', $id);
823
824
            if (count($albums) > 0) {
825
                foreach ($albums as $album) {
826
                    $this->delete_album($album['id']);
827
                }
828
            }
829
            $this->gallery_m->delete_category($id);
830
        }
831
        $this->lib_admin->log(lang('Gallery category was removed', 'gallery') . '. Ids: ' . implode(', ', $this->input->post('id')));
832
    }
833
834
    /**
835
     * In CI's class Upload not provided the input's files array (name='somefile[]')
836
     * So the structure of $_FILES must be
837
     * Array (
838
     *      [somefile] => Array (
839
     *            [name] => qwe.jpg
840
     *               ...
841
     *  ))
842
     * But in case of many file it is like this:
843
     * Array (
844
     *      [somefile] => Array (
845
     *            [name] => Array (
846
     *                  [0] => 'qwe.jpg',
847
     *                  [1] => 'asd.jpg',
848
     *                  ...
849
     *            )
850
     *               ...
851
     *  ))
852
     * There is a need to transform $_FILES like each file come from his own input
853
     *
854
     * @param string $field name of the input[name]
855
     */
856
    private function transform_FILES($field = 'userfile') {
857
        if (!array_key_exists($field, $_FILES)) {
858
            return FALSE;
859
        }
860
861
        $newFiles = [];
862
        $count = count($_FILES[$field]['name']);
863
        for ($i = 0; $i < $count; $i++) {
864
            $oneFileData = [];
865
            foreach ($_FILES[$field] as $assocKey => $fileDataArray) {
866
                $oneFileData[$assocKey] = $fileDataArray[$i];
867
            }
868
            $newFiles[$field . '_' . $i] = $oneFileData;
869
        }
870
        $_FILES = $newFiles;
871
        return TRUE;
872
    }
873
874
    /**
875
     * Upload image
876
     *
877
     * Upload image to album folder.
878
     *
879
     */
880
    public function upload_image($album_id = 0) {
881
        $temp_conf = $this->conf;
882
        if (is_array($_FILES['newPic'])) {
883
884
            if (count($_FILES['newPic']['name']) > ini_get('max_file_uploads')) {
885
                showMessage(langf('You can upload only |max_file_uploads| images at once', 'admin', ['max_file_uploads' => ini_get('max_file_uploads')]), lang('Error', 'admin'), 'r');
886
                exit;
887
            }
888
889
            // making transformation of $_FILES array for CodeIgniter's Upload class
890
            $this->transform_FILES('newPic');
891
892
            // configs for Upload
893
            $this->conf['upload_path'] = $this->conf['upload_path'] . $album_id;
894
            if (!is_dir($this->conf['upload_path'])) {
895
                mkdir($this->conf['upload_path']);
896
            }
897
            $config['upload_path'] = $this->conf['upload_path'];
898
899
            $config['allowed_types'] = $this->conf['allowed_types'];
900
            $config['max_size'] = 1024 * 1024 * $this->max_image_size;
901
            $config['encrypt_name'] = TRUE;
902
903
            // init Upload
904
            $this->load->library('upload', $config);
905
906
            // saving each file
907
            $data = [];
908
            $i = 0;
909
            foreach ($_FILES as $fieldName => $filesData) {
910
                if (!$this->upload->do_upload($fieldName)) {
911
                    $error = $filesData['name'] . ' - ' . $this->upload->display_errors('', '') . '<br /> ';
912
                    $data['error'] .= $error;
913
                } else {
914
                    $data[$i] = ['upload_data' => $this->upload->data()];
915
916
                    // Resize Image and create thumb
917
                    $this->resize_and_thumb($data[$i]['upload_data']);
918
                    $this->add_image($album_id, $data[$i]['upload_data']);
919
                }
920
                $buf = $this->conf['upload_path'];
921
                $this->conf = $temp_conf;
922
                $this->conf['upload_path'] = $buf;
923
                $i++;
924
            }
925
926
            if (isset($data['error'])) {
927
                showMessage($data['error'], '', 'r');
928
            } else {
929
                showMessage(lang('Upload success', 'gallery'));
930
                pjax('');
931
            }
932
        }
933
        $this->lib_admin->log(lang('Photos in gallery the album are saved', 'gallery'));
934
    }
935
936
    /**
937
     * Resize image and create thumb
938
     */
939
    private function resize_and_thumb($file = []) {
940
        $this->load->library('image_lib');
941
942
        // Resize image
943
        if ($this->conf['max_width'] > 0 AND $this->conf['max_height'] > 0) {
944
            if ($file['image_width'] > $this->conf['max_width'] OR $file['image_height'] > $this->conf['max_height']) {
945
                $config = [];
946
                $config['image_library'] = $this->conf['engine'];
947
                $config['source_image'] = $file['full_path'];
948
                $config['create_thumb'] = FALSE;
949
                $config['maintain_ratio'] = $this->conf['maintain_ratio'];
950
                $config['width'] = $this->conf['max_width'];
951
                $config['height'] = $this->conf['max_height'];
952
                $config['quality'] = $this->conf['quality'];
953
954 View Code Duplication
                if (($this->conf['maintain_ratio']) AND ($this->conf['crop'])) { // Уменьшаем изображение и обрезаем края
955
                    $size = $this->get_image_size($file['full_path']); // Получаем размеры сторон изображения
956
957
                    $size['width'] >= $size['height'] ? $config['master_dim'] = 'height' : $config['master_dim'] = 'width'; // Задаем master_dim
958
959
                    $this->image_lib->clear();
960
                    $this->image_lib->initialize($config);
961
                    $this->image_lib->resize();
962
963
                    $config['image_library'] = $this->conf['engine'];
964
                    $config['source_image'] = $file['full_path'];
965
                    $config['maintain_ratio'] = FALSE;
966
                    $config['width'] = $this->conf['max_width'];
967
                    $config['height'] = $this->conf['max_height'];
968
969
                    $this->image_lib->clear();
970
                    $this->image_lib->initialize($config);
971
                    $this->image_lib->crop();
972
                } else { // Только уменьшаем
973
                    $this->image_lib->clear();
974
                    $this->image_lib->initialize($config);
975
                    $this->image_lib->resize();
976
                }
977
            }
978
        }
979
        // Create image preview
980
        $config = [];
981
        $prev_img_name = $file['raw_name'] . '_prev' . $file['file_ext'];
982
983
        if ($file['image_width'] > $this->conf['prev_img_width'] OR $file['image_height'] > $this->conf['prev_img_height']) {
984
            $config['image_library'] = $this->conf['engine'];
985
            $config['source_image'] = $file['full_path'];
986
            $config['new_image'] = $prev_img_name;
987
            $config['create_thumb'] = FALSE;
988
            $config['maintain_ratio_prev'] = $this->conf['maintain_ratio_prev'];
989
            $config['width'] = $this->conf['prev_img_width'];
990
            $config['height'] = $this->conf['prev_img_height'];
991
            $config['quality'] = $this->conf['quality'];
992
993 View Code Duplication
            if (($this->conf['maintain_ratio_prev']) AND ($this->conf['crop_prev'])) { // Уменьшаем изображение и обрезаем края
994
                $size = $this->get_image_size($file['full_path']); // Получаем размеры сторон изображения
995
996
                $size['width'] >= $size['height'] ? $config['master_dim'] = 'height' : $config['master_dim'] = 'width'; // Задаем master_dim
997
998
                $this->image_lib->clear();
999
                $this->image_lib->initialize($config);
1000
                $this->image_lib->resize();
1001
1002
                $config['image_library'] = $this->conf['engine'];
1003
                $config['source_image'] = $prev_img_name;
1004
                $config['maintain_ratio'] = FALSE;
1005
                $config['width'] = $this->conf['prev_img_width'];
1006
                $config['height'] = $this->conf['prev_img_height'];
1007
1008
                $this->image_lib->clear();
1009
                $this->image_lib->initialize($config);
1010
                $this->image_lib->crop();
1011
            } else { // Только уменьшаем
1012
                $this->image_lib->clear();
1013
                $this->image_lib->initialize($config);
1014
                $this->image_lib->resize();
1015
            }
1016
        } else {
1017
            $this->load->helper('File');
1018
            $file_data = read_file($file['full_path']);
1019
            write_file($file['file_path'] . $prev_img_name, $file_data);
1020
        }
1021
1022
        // Create thumb file
1023
        $config = [];
1024
        $thumb_name = $this->conf['upload_path'] . '/' . $this->conf['thumbs_folder'] . '/' . $file['raw_name'] . $this->conf['thumb_marker'] . $file['file_ext'];
1025
1026
        if ($file['image_width'] > $this->conf['thumb_width'] OR $file['image_height'] > $this->conf['thumb_height']) {
1027
            $config['image_library'] = $this->conf['engine'];
1028
            $config['source_image'] = $file['full_path'];
1029
            $config['new_image'] = $thumb_name;
1030
            $config['create_thumb'] = FALSE;
1031
            $config['maintain_ratio'] = $this->conf['maintain_ratio_icon'];
1032
            $config['width'] = $this->conf['thumb_width'];
1033
            $config['height'] = $this->conf['thumb_height'];
1034
            $config['quality'] = $this->conf['quality'];
1035
1036
            if (($this->conf['maintain_ratio_icon']) AND ($this->conf['crop_icon'])) { // Уменьшаем изображение и обрезаем края
1037
                $size = $this->get_image_size($file['full_path']); // Получаем размеры сторон изображения
1038
1039
                $size['width'] >= $size['height'] ? $config['master_dim'] = 'width' : $config['master_dim'] = 'height'; // Задаем master_dim
1040
1041
                $this->image_lib->clear();
1042
                $this->image_lib->initialize($config);
1043
                if (!$this->image_lib->resize()) {
1044
                    echo 'fck';
1045
                }
1046
1047
                $config['image_library'] = $this->conf['engine'];
1048
                $config['source_image'] = $thumb_name;
1049
                $config['maintain_ratio'] = FALSE;
1050
                $config['width'] = $this->conf['thumb_width'];
1051
                $config['height'] = $this->conf['thumb_height'];
1052
1053
                $this->image_lib->clear();
1054
                $this->image_lib->initialize($config);
1055
                $this->image_lib->crop();
1056
            } else { // Только уменьшаем
1057
                $this->image_lib->clear();
1058
                $this->image_lib->initialize($config);
1059
                if (!$this->image_lib->resize()) {
1060
                    echo $this->image_lib->display_errors();
1061
                }
1062
            }
1063 View Code Duplication
        } else {
1064
            // copy file to thumbs folder
1065
            $this->load->helper('File');
1066
            $file_data = read_file($file['full_path']);
1067
            write_file($thumb_name, $file_data);
1068
        }
1069
1070
        // Create admin thumb file
1071
        $config = [];
1072
        $thumb_name = $this->conf['upload_path'] . '/_admin_thumbs/' . $file['raw_name'] . $this->conf['thumb_marker'] . $file['file_ext'];
1073
1074
        if ($file['image_width'] > 100 OR $file['image_height'] > 100) {
1075
            $config['image_library'] = $this->conf['engine'];
1076
            $config['source_image'] = $file['full_path'];
1077
            $config['new_image'] = $thumb_name;
1078
            $config['create_thumb'] = FALSE;
1079
            $config['maintain_ratio'] = TRUE;
1080
            $config['width'] = 100;
1081
            $config['height'] = 100;
1082
            $config['quality'] = '80%';
1083
1084
            $this->image_lib->clear();
1085
            $this->image_lib->initialize($config);
1086
            $this->image_lib->resize();
1087 View Code Duplication
        } else {
1088
            $this->load->helper('File');
1089
            $file_data = read_file($file['full_path']);
1090
            write_file($thumb_name, $file_data);
1091
        }
1092
1093
        // Draw watermark.
1094
        if ($file['image_width'] > $this->conf['watermark_min_width'] AND $file['image_height'] > $this->conf['watermark_min_height']) {
1095
            $this->make_watermark($file['full_path']);
1096
            $this->make_watermark($file['file_path'] . $prev_img_name);
1097
        }
1098
1099
        return TRUE;
1100
    }
1101
1102
    /**
1103
     * Watermarking an Image if watermark_text is not empty
1104
     */
1105
    private function make_watermark($file_path) {
1106
        if (!$this->conf['watermark_font_path']) {
1107
            $this->conf['watermark_font_path'] = './uploads/defaultFont.ttf';
1108
        }
1109
1110
        $config = [];
1111
        $config['source_image'] = $file_path;
1112
        $config['wm_vrt_alignment'] = $this->conf['wm_vrt_alignment'];
1113
        $config['wm_hor_alignment'] = $this->conf['wm_hor_alignment'];
1114
        $config['wm_padding'] = $this->conf['watermark_padding'];
1115
1116
        if ($this->conf['watermark_type'] == 'overlay') {
1117
            $config['wm_type'] = 'overlay';
1118
            $config['wm_opacity'] = $this->conf['watermark_image_opacity'];
1119
            $config['wm_overlay_path'] = $this->conf['watermark_image'];
1120
        } else {
1121
            if ($this->conf['watermark_text'] == '') {
1122
                return FALSE;
1123
            }
1124
1125
            $config['wm_text'] = $this->conf['watermark_text'];
1126
            $config['wm_type'] = 'text';
1127
            $config['wm_font_path'] = $this->conf['watermark_font_path'];
1128
            $config['wm_font_size'] = $this->conf['watermark_font_size'];
1129
            $config['wm_font_color'] = $this->conf['watermark_color'];
1130
        }
1131
1132
        $this->image_lib->clear();
1133
        $this->image_lib->initialize($config);
1134
        $this->image_lib->watermark();
1135
    }
1136
1137
}
1138
1139
/* End of file admin.php */