Completed
Push — master ( 72613d...069c91 )
by Michael
02:16
created

ExtgalleryPhotoHandler   F

Complexity

Total Complexity 120

Size/Duplication

Total Lines 1095
Duplicated Lines 18.9 %

Coupling/Cohesion

Components 4
Dependencies 3

Importance

Changes 0
Metric Value
dl 207
loc 1095
rs 0.6631
c 0
b 0
f 0
wmc 120
lcom 4
cbo 3

48 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A createPhoto() 0 7 1
A modifyPhoto() 0 7 1
A deletePhoto() 0 7 2
A deletePhotoByCat() 0 8 2
A deleteFile() 0 4 1
A getPhoto() 13 13 2
A nbPhoto() 0 6 1
A getAlbumPhotoPage() 0 14 2
A getAlbumPhotoAdminPage() 0 12 1
A getSlideshowAlbumPhoto() 0 10 1
A getPhotoAlbumId() 16 16 2
A getAlbumPrevPhoto() 15 15 1
A getAlbumNextPhoto() 15 15 1
A getAlbumCurrentPhotoPlace() 14 14 1
A getAlbumPhoto() 0 8 1
B getCatPhoto() 11 26 3
A getAlbumCount() 0 6 1
A updateHits() 0 6 1
A updateNbRating() 0 6 1
A updateDownload() 0 6 1
A updateEcard() 0 6 1
A getAllSize() 0 4 1
C _makeWatermark() 28 58 12
A _makeBorder() 0 15 1
A _getUploadPhotoPath() 0 4 1
C _largePhotoTreatment() 3 37 8
D _mediumPhotoTreatment() 3 46 10
A _makeThumb() 3 19 3
A _haveLargePhoto() 0 4 1
B _getImageDimension() 3 25 4
B _getAutoDescription() 0 26 1
A _makeFileName() 0 11 2
A _getPhotoSize() 0 8 2
A _getFileSize() 0 4 1
A rebuildThumbnail() 0 7 2
D postPhotoTraitement() 12 114 15
C addLocalPhoto() 0 70 8
C getSearchedPhoto() 0 44 7
A getPendingPhoto() 0 6 1
A _addInCriteria() 0 13 3
A getRandomPhoto() 14 14 2
A getLastPhoto() 14 14 1
A getTopViewPhoto() 14 14 1
A getTopRatedPhoto() 14 14 1
A getTopEcardPhoto() 14 14 1
A getTopSubmitter() 0 9 1
A getInsertId() 0 4 1

How to fix   Duplicated Code    Complexity   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

Complex Class

 Tip:   Before tackling complexity, make sure that you eliminate any duplication first. This often can reduce the size of classes significantly.

Complex classes like ExtgalleryPhotoHandler often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use ExtgalleryPhotoHandler, and based on these observations, apply Extract Interface, too.

1
<?php
0 ignored issues
show
Coding Style Compatibility introduced by
For compatibility and reusability of your code, PSR1 recommends that a file should introduce either new symbols (like classes, functions, etc.) or have side-effects (like outputting something, or including other files), but not both at the same time. The first symbol is defined on line 26 and the first side effect is on line 20.

The PSR-1: Basic Coding Standard recommends that a file should either introduce new symbols, that is classes, functions, constants or similar, or have side effects. Side effects are anything that executes logic, like for example printing output, changing ini settings or writing to a file.

The idea behind this recommendation is that merely auto-loading a class should not change the state of an application. It also promotes a cleaner style of programming and makes your code less prone to errors, because the logic is not spread out all over the place.

To learn more about the PSR-1, please see the PHP-FIG site on the PSR-1.

Loading history...
2
/**
3
 * ExtGallery Class Manager
4
 *
5
 * You may not change or alter any portion of this comment or credits
6
 * of supporting developers from this source code or any supporting source code
7
 * which is considered copyrighted (c) material of the original comment or credit authors.
8
 * This program is distributed in the hope that it will be useful,
9
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
11
 *
12
 * @copyright   {@link https://xoops.org/ XOOPS Project}
13
 * @license     GNU GPL 2 (http://www.gnu.org/licenses/old-licenses/gpl-2.0.html)
14
 * @author      Zoullou (http://www.zoullou.net)
15
 * @package     ExtGallery
16
 */
17
18
// defined('XOOPS_ROOT_PATH') || exit('Restricted access.');
0 ignored issues
show
Unused Code Comprehensibility introduced by
70% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
19
20
require_once __DIR__ . '/publicPerm.php';
21
require_once __DIR__ . '/ExtgalleryPersistableObjectHandler.php';
22
23
/**
24
 * Class ExtgalleryPhoto
25
 */
26
class ExtgalleryPhoto extends XoopsObject
0 ignored issues
show
Coding Style Compatibility introduced by
PSR1 recommends that each class must be in a namespace of at least one level to avoid collisions.

You can fix this by adding a namespace to your class:

namespace YourVendor;

class YourClass { }

When choosing a vendor namespace, try to pick something that is not too generic to avoid conflicts with other libraries.

Loading history...
27
{
28
    public $externalKey = [];
29
30
    /**
31
     * ExtgalleryPhoto constructor.
32
     */
33
    public function __construct()
34
    {
35
        parent::__construct();
36
        $this->initVar('photo_id', XOBJ_DTYPE_INT, null, false);
37
        $this->initVar('cat_id', XOBJ_DTYPE_INT, 0, false);
38
        $this->initVar('photo_title', XOBJ_DTYPE_TXTBOX, '', false, 255);
39
        $this->initVar('photo_desc', XOBJ_DTYPE_TXTAREA, '', false);
40
        $this->initVar('photo_serveur', XOBJ_DTYPE_TXTBOX, '', false, 255);
41
        $this->initVar('photo_name', XOBJ_DTYPE_TXTBOX, '', false, 255);
42
        $this->initVar('photo_orig_name', XOBJ_DTYPE_TXTBOX, '', false, 255);
43
        $this->initVar('uid', XOBJ_DTYPE_INT, 0, false);
44
        $this->initVar('photo_size', XOBJ_DTYPE_INT, 0, false);
45
        $this->initVar('photo_res_x', XOBJ_DTYPE_INT, 0, false);
46
        $this->initVar('photo_res_y', XOBJ_DTYPE_INT, 0, false);
47
        $this->initVar('photo_hits', XOBJ_DTYPE_INT, 0, false);
48
        $this->initVar('photo_comment', XOBJ_DTYPE_INT, 0, false);
49
        $this->initVar('photo_rating', XOBJ_DTYPE_INT, 0, false);
50
        $this->initVar('photo_nbrating', XOBJ_DTYPE_INT, 0, false);
51
        $this->initVar('photo_download', XOBJ_DTYPE_INT, 0, false);
52
        $this->initVar('photo_ecard', XOBJ_DTYPE_INT, 0, false);
53
        $this->initVar('photo_date', XOBJ_DTYPE_INT, 0, false);
54
        $this->initVar('photo_havelarge', XOBJ_DTYPE_INT, 0, false);
55
        $this->initVar('photo_approved', XOBJ_DTYPE_INT, 0, false);
56
        $this->initVar('photo_extra', XOBJ_DTYPE_TXTAREA, '', false);
57
        $this->initVar('photo_weight', XOBJ_DTYPE_INT, 0, false);
58
        $this->initVar('dohtml', XOBJ_DTYPE_INT, 0, false);
59
60
        $this->externalKey['cat_id'] = [
61
            'className'      => 'publiccat',
62
            'getMethodeName' => 'getCat',
63
            'keyName'        => 'cat',
64
            'core'           => false
65
        ];
66
        $this->externalKey['uid']    = [
67
            'className'      => 'user',
68
            'getMethodeName' => 'get',
69
            'keyName'        => 'user',
70
            'core'           => true
71
        ];
72
    }
73
74
    /**
75
     * @param $key
76
     *
77
     * @return mixed
78
     */
79
    public function getExternalKey($key)
80
    {
81
        return $this->externalKey[$key];
82
    }
83
}
84
85
/**
86
 * Class ExtgalleryPhotoHandler
87
 */
88
class ExtgalleryPhotoHandler extends ExtgalleryPersistableObjectHandler
0 ignored issues
show
Coding Style Compatibility introduced by
PSR1 recommends that each class should be in its own file to aid autoloaders.

Having each class in a dedicated file usually plays nice with PSR autoloaders and is therefore a well established practice. If you use other autoloaders, you might not want to follow this rule.

Loading history...
Coding Style Compatibility introduced by
PSR1 recommends that each class must be in a namespace of at least one level to avoid collisions.

You can fix this by adding a namespace to your class:

namespace YourVendor;

class YourClass { }

When choosing a vendor namespace, try to pick something that is not too generic to avoid conflicts with other libraries.

Loading history...
89
{
90
    public $photoUploader = null;
91
92
    /**
93
     * @param $db
94
     * @param $type
95
     */
96
    public function __construct(XoopsDatabase $db, $type)
97
    {
98
        parent::__construct($db, 'extgallery_' . $type . 'photo', 'Extgallery' . ucfirst($type) . 'Photo', 'photo_id');
99
    }
100
101
    /**
102
     * @param $data
103
     *
104
     * @return bool
105
     */
106
    public function createPhoto($data)
107
    {
108
        $photo = $this->create();
109
        $photo->setVars($data);
110
111
        return $this->insert($photo, true);
112
    }
113
114
    /**
115
     * @param $photoId
116
     * @param $data
117
     *
118
     * @return bool
119
     */
120
    public function modifyPhoto($photoId, $data)
121
    {
122
        $photo = $this->get($photoId);
123
        $photo->setVars($data);
124
125
        return $this->insert($photo, true);
126
    }
127
128
    /**
129
     * @param $photo
130
     */
131
    public function deletePhoto(&$photo)
132
    {
133
        if ('' == $photo->getVar('photo_serveur')) {
134
            $this->deleteFile($photo);
135
        }
136
        $this->deleteById($photo->getVar('photo_id'), true);
137
    }
138
139
    /**
140
     * @param $catId
141
     */
142
    public function deletePhotoByCat($catId)
143
    {
144
        $criteria = new Criteria('cat_id', $catId);
145
        $photos   = $this->getObjects($criteria);
146
        foreach ($photos as $photo) {
147
            $this->deletePhoto($photo);
148
        }
149
    }
150
151
    public function deleteFile()
152
    {
153
        exit('deleteFile() method must be defined on sub classes');
0 ignored issues
show
Coding Style Compatibility introduced by
The method deleteFile() contains an exit expression.

An exit expression should only be used in rare cases. For example, if you write a short command line script.

In most cases however, using an exit expression makes the code untestable and often causes incompatibilities with other libraries. Thus, unless you are absolutely sure it is required here, we recommend to refactor your code to avoid its usage.

Loading history...
154
    }
155
156
    /**
157
     * @param $photoId
158
     *
159
     * @return bool
160
     */
161 View Code Duplication
    public function getPhoto($photoId)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
162
    {
163
        $criteria = new CriteriaCompo();
164
        $criteria->add(new Criteria('photo_id', $photoId));
165
        $criteria->add(new Criteria('photo_approved', 1));
166
167
        $photo = $this->getObjects($criteria);
168
        if (1 != count($photo)) {
169
            return false;
170
        }
171
172
        return $photo[0];
173
    }
174
175
    /**
176
     * @param $cat
177
     *
178
     * @return int
179
     */
180
    public function nbPhoto(&$cat)
181
    {
182
        $criteria = new Criteria('cat_id', $cat->getVar('cat_id'));
183
184
        return $this->getCount($criteria);
185
    }
186
187
    /**
188
     * @param $catId
189
     * @param $start
190
     * @param $sortby
191
     * @param $orderby
192
     *
193
     * @return array
194
     */
195
    public function getAlbumPhotoPage($catId, $start, $sortby, $orderby)
0 ignored issues
show
Coding Style introduced by
getAlbumPhotoPage uses the super-global variable $GLOBALS which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
196
    {
197
        $criteria = new CriteriaCompo();
198
        $criteria->add(new Criteria('cat_id', $catId));
199
        $criteria->add(new Criteria('photo_approved', 1));
200
        $criteria->setStart($start);
201
        $criteria->setLimit($GLOBALS['xoopsModuleConfig']['nb_column'] * $GLOBALS['xoopsModuleConfig']['nb_line']);
202
        if ('' == $criteria->getSort()) {
203
            $criteria->setSort($sortby);
204
            $criteria->setOrder($orderby);
205
        }
206
207
        return $this->getObjects($criteria);
208
    }
209
210
    /**
211
     * @param $catId
212
     * @param $start
213
     *
214
     * @return array
215
     */
216
    public function getAlbumPhotoAdminPage($catId, $start)
0 ignored issues
show
Coding Style introduced by
getAlbumPhotoAdminPage uses the super-global variable $GLOBALS which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
217
    {
218
        $criteria = new CriteriaCompo();
219
        $criteria->add(new Criteria('cat_id', $catId));
220
        $criteria->add(new Criteria('photo_approved', 1));
221
        $criteria->setStart($start);
222
        $criteria->setLimit($GLOBALS['xoopsModuleConfig']['admin_nb_photo']);
223
        $criteria->setSort('photo_weight, photo_id');
224
        $criteria->setOrder($GLOBALS['xoopsModuleConfig']['display_set_order']);
225
226
        return $this->getObjects($criteria);
227
    }
228
229
    /**
230
     * @param $catId
231
     *
232
     * @return array
233
     */
234
    public function getSlideshowAlbumPhoto($catId)
0 ignored issues
show
Coding Style introduced by
getSlideshowAlbumPhoto uses the super-global variable $GLOBALS which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
235
    {
236
        $criteria = new CriteriaCompo();
237
        $criteria->add(new Criteria('cat_id', $catId));
238
        $criteria->add(new Criteria('photo_approved', 1));
239
        $criteria->setSort('photo_weight, photo_id');
240
        $criteria->setOrder($GLOBALS['xoopsModuleConfig']['display_set_order']);
241
242
        return $this->getObjects($criteria, false, false);
243
    }
244
245
    /**
246
     * @param $catId
247
     *
248
     * @return array
249
     */
250 View Code Duplication
    public function getPhotoAlbumId($catId)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
251
    {
252
        $criteria = new CriteriaCompo();
253
        $criteria->add(new Criteria('cat_id', $catId));
254
        $criteria->add(new Criteria('photo_approved', 1));
255
256
        $sql = 'SELECT photo_id FROM ' . $this->db->prefix('extgallery_publicphoto') . ' ' . $criteria->renderWhere() . ' ORDER BY photo_weight, photo_id ASC;';
257
258
        $result = $this->db->query($sql);
259
        $ret    = [];
260
        while (false !== ($myrow = $this->db->fetchArray($result))) {
261
            $ret[] = $myrow['photo_id'];
262
        }
263
264
        return $ret;
265
    }
266
267
    /**
268
     * @param $catId
269
     * @param $photoId
270
     *
271
     * @return array
272
     */
273 View Code Duplication
    public function getAlbumPrevPhoto($catId, $photoId)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
274
    {
275
        $catHandler = xoops_getModuleHandler('publiccat', 'extgallery');
276
277
        $criteria = new CriteriaCompo();
278
        $criteria->add($catHandler->getCatRestrictCriteria());
279
        $criteria->add(new Criteria('photo_approved', 1));
280
        $criteria->add(new Criteria('cat_id', $catId));
281
        $criteria->add(new Criteria('photo_id', $photoId, '<'));
282
        $criteria->setSort('photo_weight, photo_id');
283
        $criteria->setOrder('DESC');
284
        $criteria->setLimit(1);
285
286
        return $this->getObjects($criteria);
287
    }
288
289
    /**
290
     * @param $catId
291
     * @param $photoId
292
     *
293
     * @return array
294
     */
295 View Code Duplication
    public function getAlbumNextPhoto($catId, $photoId)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
296
    {
297
        $catHandler = xoops_getModuleHandler('publiccat', 'extgallery');
298
299
        $criteria = new CriteriaCompo();
300
        $criteria->add($catHandler->getCatRestrictCriteria());
301
        $criteria->add(new Criteria('photo_approved', 1));
302
        $criteria->add(new Criteria('cat_id', $catId));
303
        $criteria->add(new Criteria('photo_id', $photoId, '>'));
304
        $criteria->setSort('photo_weight, photo_id');
305
        $criteria->setOrder('ASC');
306
        $criteria->setLimit(1);
307
308
        return $this->getObjects($criteria);
309
    }
310
311
    /**
312
     * @param $catId
313
     * @param $photoId
314
     *
315
     * @return int
316
     */
317 View Code Duplication
    public function getAlbumCurrentPhotoPlace($catId, $photoId)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
318
    {
319
        $catHandler = xoops_getModuleHandler('publiccat', 'extgallery');
320
321
        $criteria = new CriteriaCompo();
322
        $criteria->add($catHandler->getCatRestrictCriteria());
323
        $criteria->add(new Criteria('photo_approved', 1));
324
        $criteria->add(new Criteria('cat_id', $catId));
325
        $criteria->add(new Criteria('photo_id', $photoId, '<='));
326
        $criteria->setSort('photo_weight, photo_id');
327
        $criteria->setOrder('DESC');
328
329
        return $this->getCount($criteria);
330
    }
331
332
    /**
333
     * @param $catId
334
     *
335
     * @return array
336
     */
337
    public function getAlbumPhoto($catId)
338
    {
339
        $criteria = new Criteria('cat_id', $catId);
340
        $criteria->setSort('photo_weight, photo_id');
341
        $criteria->setOrder('ASC');
342
343
        return $this->getObjects($criteria);
344
    }
345
346
    /**
347
     * @param $category
348
     *
349
     * @return array
350
     */
351
    public function getCatPhoto(&$category)
352
    {
353
        $catHandler = xoops_getModuleHandler('publiccat', 'extgallery');
354
355
        $criteria = new CriteriaCompo();
356
        $criteria->add(new Criteria('nleft', $category->getVar('nleft'), '>='));
357
        $criteria->add(new Criteria('nright', $category->getVar('nright'), '<='));
358
359
        $cats = $catHandler->getObjects($criteria);
360
361
        $count = count($cats);
362 View Code Duplication
        if ($count > 0) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
363
            $in = '(' . $cats[0]->getVar('cat_id');
364
            array_shift($cats);
365
            /** @var ExtgalleryCat $cat */
366
            foreach ($cats as $cat) {
367
                $in .= ',' . $cat->getVar('cat_id');
368
            }
369
            $in       .= ')';
370
            $criteria = new Criteria('cat_id', $in, 'IN');
371
        } else {
372
            $criteria = new Criteria('cat_id', '(0)', 'IN');
373
        }
374
375
        return $this->getObjects($criteria);
376
    }
377
378
    /**
379
     * @param $catId
380
     *
381
     * @return int
382
     */
383
    public function getAlbumCount($catId)
384
    {
385
        $criteria = new Criteria('cat_id', $catId);
386
387
        return $this->getCount($criteria);
388
    }
389
390
    /**
391
     * @param $photoId
392
     *
393
     * @return bool
394
     */
395
    public function updateHits($photoId)
396
    {
397
        $criteria = new Criteria('photo_id', $photoId);
398
399
        return $this->updateCounter('photo_hits', $criteria);
400
    }
401
402
    /**
403
     * @param $photoId
404
     *
405
     * @return bool
406
     */
407
    public function updateNbRating($photoId)
408
    {
409
        $criteria = new Criteria('photo_id', $photoId);
410
411
        return $this->updateCounter('photo_nbrating', $criteria);
412
    }
413
414
    /**
415
     * @param $photoId
416
     *
417
     * @return bool
418
     */
419
    public function updateDownload($photoId)
420
    {
421
        $criteria = new Criteria('photo_id', $photoId);
422
423
        return $this->updateCounter('photo_download', $criteria);
424
    }
425
426
    /**
427
     * @param $photoId
428
     *
429
     * @return bool
430
     */
431
    public function updateEcard($photoId)
432
    {
433
        $criteria = new Criteria('photo_id', $photoId);
434
435
        return $this->updateCounter('photo_ecard', $criteria);
436
    }
437
438
    public function getAllSize()
439
    {
440
        exit('getAllSize() method must be defined on sub classes');
0 ignored issues
show
Coding Style Compatibility introduced by
The method getAllSize() contains an exit expression.

An exit expression should only be used in rare cases. For example, if you write a short command line script.

In most cases however, using an exit expression makes the code untestable and often causes incompatibilities with other libraries. Thus, unless you are absolutely sure it is required here, we recommend to refactor your code to avoid its usage.

Loading history...
441
    }
442
443
    /**
444
     * @param $imageTransform
445
     */
446
    public function _makeWatermark(&$imageTransform)
0 ignored issues
show
Coding Style introduced by
_makeWatermark uses the super-global variable $GLOBALS which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
447
    {
448
        if (!function_exists('imagettfbbox')) {
449
            return;
450
        }
451
452
        global $xoopsModuleConfig;
0 ignored issues
show
Compatibility Best Practice introduced by
Use of global functionality is not recommended; it makes your code harder to test, and less reusable.

Instead of relying on global state, we recommend one of these alternatives:

1. Pass all data via parameters

function myFunction($a, $b) {
    // Do something
}

2. Create a class that maintains your state

class MyClass {
    private $a;
    private $b;

    public function __construct($a, $b) {
        $this->a = $a;
        $this->b = $b;
    }

    public function myFunction() {
        // Do something
    }
}
Loading history...
453
454
        /*  Text position param
455
        /
456
        /   0 : orig
457
        /   -1 : opposit
458
        /   1 : center
459
        /
460
        */
461 View Code Duplication
        if ('tl' === $xoopsModuleConfig['watermark_position']) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
462
            $x = 0;
463
            $y = 0;
464
        } elseif ('tr' === $xoopsModuleConfig['watermark_position']) {
465
            $x = -1;
466
            $y = 0;
467
        } elseif ('bl' === $xoopsModuleConfig['watermark_position']) {
468
            $x = 0;
469
            $y = -1;
470
        } elseif ('br' === $xoopsModuleConfig['watermark_position']) {
471
            $x = -1;
472
            $y = -1;
473
        } elseif ('tc' === $xoopsModuleConfig['watermark_position']) {
474
            $x = 1;
475
            $y = 0;
476
        } elseif ('bc' === $xoopsModuleConfig['watermark_position']) {
477
            $x = 1;
478
            $y = -1;
479
        } elseif ('lc' === $xoopsModuleConfig['watermark_position']) {
480
            $x = 0;
481
            $y = 1;
482
        } elseif ('rc' === $xoopsModuleConfig['watermark_position']) {
483
            $x = -1;
484
            $y = 1;
485
        } elseif ('cc' === $xoopsModuleConfig['watermark_position']) {
486
            $x = 1;
487
            $y = 1;
488
        }
489
490
        $text = (0 == $xoopsModuleConfig['watermark_type']) ? $GLOBALS['xoopsUser']->getVar('uname') : $xoopsModuleConfig['watermark_text'];
491
492
        $watermarkParams = [
493
            'text'         => $text,
494
            'x'            => $x,
0 ignored issues
show
Bug introduced by
The variable $x does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
495
            'y'            => $y,
0 ignored issues
show
Bug introduced by
The variable $y does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
496
            'color'        => $xoopsModuleConfig['watermark_color'],
497
            'font'         => XOOPS_ROOT_PATH . '/modules/extgallery/fonts/' . $xoopsModuleConfig['watermark_font'],
498
            'size'         => $xoopsModuleConfig['watermark_fontsize'],
499
            'resize_first' => false,
500
            'padding'      => $xoopsModuleConfig['watermark_padding']
501
        ];
502
        $imageTransform->addText($watermarkParams);
503
    }
504
505
    /**
506
     * @param $imageTransform
507
     */
508
    public function _makeBorder(&$imageTransform)
509
    {
510
        global $xoopsModuleConfig;
0 ignored issues
show
Compatibility Best Practice introduced by
Use of global functionality is not recommended; it makes your code harder to test, and less reusable.

Instead of relying on global state, we recommend one of these alternatives:

1. Pass all data via parameters

function myFunction($a, $b) {
    // Do something
}

2. Create a class that maintains your state

class MyClass {
    private $a;
    private $b;

    public function __construct($a, $b) {
        $this->a = $a;
        $this->b = $b;
    }

    public function myFunction() {
        // Do something
    }
}
Loading history...
511
512
        $borders   = [];
513
        $borders[] = [
514
            'borderWidth' => $xoopsModuleConfig['inner_border_size'],
515
            'borderColor' => $xoopsModuleConfig['inner_border_color']
516
        ];
517
        $borders[] = [
518
            'borderWidth' => $xoopsModuleConfig['outer_border_size'],
519
            'borderColor' => $xoopsModuleConfig['outer_border_color']
520
        ];
521
        $imageTransform->addBorders($borders);
522
    }
523
524
    public function _getUploadPhotoPath()
525
    {
526
        exit('_getUploadPhotoPath() method must be defined on sub classes');
0 ignored issues
show
Coding Style Compatibility introduced by
The method _getUploadPhotoPath() contains an exit expression.

An exit expression should only be used in rare cases. For example, if you write a short command line script.

In most cases however, using an exit expression makes the code untestable and often causes incompatibilities with other libraries. Thus, unless you are absolutely sure it is required here, we recommend to refactor your code to avoid its usage.

Loading history...
527
    }
528
529
    /**
530
     * @param $photoName
531
     */
532
    public function _largePhotoTreatment($photoName)
533
    {
534
        global $xoopsModuleConfig;
0 ignored issues
show
Compatibility Best Practice introduced by
Use of global functionality is not recommended; it makes your code harder to test, and less reusable.

Instead of relying on global state, we recommend one of these alternatives:

1. Pass all data via parameters

function myFunction($a, $b) {
    // Do something
}

2. Create a class that maintains your state

class MyClass {
    private $a;
    private $b;

    public function __construct($a, $b) {
        $this->a = $a;
        $this->b = $b;
    }

    public function myFunction() {
        // Do something
    }
}
Loading history...
535
536
        // Check if must save large photo
537
        if ($xoopsModuleConfig['save_large']) {
538
539
            // Define Graphical library path
540 View Code Duplication
            if (!defined('IMAGE_TRANSFORM_IM_PATH') && 'imagick' === $xoopsModuleConfig['graphic_lib']) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
541
                define('IMAGE_TRANSFORM_IM_PATH', $xoopsModuleConfig['graphic_lib_path']);
542
            }
543
            $imageFactory   = new Image_Transform;
544
            $imageTransform = $imageFactory->factory($xoopsModuleConfig['graphic_lib']);
545
546
            $filePath = $this->_getUploadPhotoPath();
0 ignored issues
show
Bug introduced by
Are you sure the assignment to $filePath is correct as $this->_getUploadPhotoPath() (which targets ExtgalleryPhotoHandler::_getUploadPhotoPath()) seems to always return null.

This check looks for function or method calls that always return null and whose return value is assigned to a variable.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
$object = $a->getObject();

The method getObject() can return nothing but null, so it makes no sense to assign that value to a variable.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
547
            $imageTransform->load($filePath . $photoName);
548
549
            // Save large photo only if it's bigger than medium size
550
            if ($imageTransform->getImageWidth() > $xoopsModuleConfig['medium_width']
551
                || $imageTransform->getImageHeight() > $xoopsModuleConfig['medium_heigth']) {
552
553
                // Make watermark
554
                if ($xoopsModuleConfig['enable_large_watermark']) {
555
                    $this->_makeWatermark($imageTransform);
556
                }
557
558
                // Make border
559
                if ($xoopsModuleConfig['enable_large_border']) {
560
                    $this->_makeBorder($imageTransform);
561
                }
562
563
                $largeFilePath = $filePath . 'large/large_' . $photoName;
564
                $imageTransform->save($largeFilePath, '', 100);
565
                $imageTransform->free();
566
            }
567
        }
568
    }
569
570
    /**
571
     * @param             $photoName
572
     * @param null|string $filePath
573
     * @param null        $mediumFilePath
574
     */
575
    public function _mediumPhotoTreatment($photoName, $filePath = null, $mediumFilePath = null)
576
    {
577
        global $xoopsModuleConfig;
0 ignored issues
show
Compatibility Best Practice introduced by
Use of global functionality is not recommended; it makes your code harder to test, and less reusable.

Instead of relying on global state, we recommend one of these alternatives:

1. Pass all data via parameters

function myFunction($a, $b) {
    // Do something
}

2. Create a class that maintains your state

class MyClass {
    private $a;
    private $b;

    public function __construct($a, $b) {
        $this->a = $a;
        $this->b = $b;
    }

    public function myFunction() {
        // Do something
    }
}
Loading history...
578
579
        // Define Graphical library path
580 View Code Duplication
        if (!defined('IMAGE_TRANSFORM_IM_PATH') && 'imagick' === $xoopsModuleConfig['graphic_lib']) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
581
            define('IMAGE_TRANSFORM_IM_PATH', $xoopsModuleConfig['graphic_lib_path']);
582
        }
583
        $imageFactory   = new Image_Transform;
584
        $imageTransform = $imageFactory->factory($xoopsModuleConfig['graphic_lib']);
585
586
        if (null === $filePath) {
587
            $filePath = $this->_getUploadPhotoPath();
0 ignored issues
show
Bug introduced by
Are you sure the assignment to $filePath is correct as $this->_getUploadPhotoPath() (which targets ExtgalleryPhotoHandler::_getUploadPhotoPath()) seems to always return null.

This check looks for function or method calls that always return null and whose return value is assigned to a variable.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
$object = $a->getObject();

The method getObject() can return nothing but null, so it makes no sense to assign that value to a variable.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
588
        }
589
        if (null === $mediumFilePath) {
590
            $mediumFilePath = $filePath . 'medium/' . $photoName;
591
        }
592
        $imageTransform->load($filePath . $photoName);
593
594
        // Fitting image to desired size
595
        if ($xoopsModuleConfig['enable_medium_border']) {
596
            $borderSize = ($xoopsModuleConfig['inner_border_size'] * 2) + ($xoopsModuleConfig['outer_border_size'] * 2);
597
        } else {
598
            $borderSize = 0;
599
        }
600
        $imageTransform->fit($xoopsModuleConfig['medium_width'] - $borderSize, $xoopsModuleConfig['medium_heigth'] - $borderSize);
601
        $imageTransform->save($mediumFilePath, '', $xoopsModuleConfig['medium_quality']);
602
        $imageTransform->free();
603
604
        if ($xoopsModuleConfig['enable_medium_watermark'] || $xoopsModuleConfig['enable_medium_border']) {
605
            $imageTransform->load($mediumFilePath);
606
607
            // Make watermark
608
            if ($xoopsModuleConfig['enable_medium_watermark']) {
609
                $this->_makeWatermark($imageTransform);
610
            }
611
612
            // Make border
613
            if ($xoopsModuleConfig['enable_medium_border']) {
614
                $this->_makeBorder($imageTransform);
615
            }
616
617
            $imageTransform->save($mediumFilePath, '', $xoopsModuleConfig['medium_quality']);
618
            $imageTransform->free();
619
        }
620
    }
621
622
    /**
623
     * @param $photoName
624
     */
625
    public function _makeThumb($photoName)
626
    {
627
        global $xoopsModuleConfig;
0 ignored issues
show
Compatibility Best Practice introduced by
Use of global functionality is not recommended; it makes your code harder to test, and less reusable.

Instead of relying on global state, we recommend one of these alternatives:

1. Pass all data via parameters

function myFunction($a, $b) {
    // Do something
}

2. Create a class that maintains your state

class MyClass {
    private $a;
    private $b;

    public function __construct($a, $b) {
        $this->a = $a;
        $this->b = $b;
    }

    public function myFunction() {
        // Do something
    }
}
Loading history...
628
629
        // Define Graphical library path
630 View Code Duplication
        if (!defined('IMAGE_TRANSFORM_IM_PATH') && 'imagick' === $xoopsModuleConfig['graphic_lib']) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
631
            define('IMAGE_TRANSFORM_IM_PATH', $xoopsModuleConfig['graphic_lib_path']);
632
        }
633
        $imageFactory   = new Image_Transform;
634
        $imageTransform = $imageFactory->factory($xoopsModuleConfig['graphic_lib']);
635
636
        $filePath  = $this->_getUploadPhotoPath() . 'medium/' . $photoName;
637
        $thumbPath = $this->_getUploadPhotoPath() . 'thumb/thumb_' . $photoName;
638
639
        $imageTransform->load($filePath);
640
        $imageTransform->fit($xoopsModuleConfig['thumb_width'], $xoopsModuleConfig['thumb_heigth']);
641
        $imageTransform->save($thumbPath, '', $xoopsModuleConfig['thumb_quality']);
642
        $imageTransform->free();
643
    }
644
645
    /**
646
     * @param $photoName
647
     *
648
     * @return bool
649
     */
650
    public function _haveLargePhoto($photoName)
651
    {
652
        return file_exists($this->_getUploadPhotoPath() . 'large/large_' . $photoName);
653
    }
654
655
    /**
656
     * @param $photoName
657
     *
658
     * @return array
659
     */
660
    public function _getImageDimension($photoName)
661
    {
662
        global $xoopsModuleConfig;
0 ignored issues
show
Compatibility Best Practice introduced by
Use of global functionality is not recommended; it makes your code harder to test, and less reusable.

Instead of relying on global state, we recommend one of these alternatives:

1. Pass all data via parameters

function myFunction($a, $b) {
    // Do something
}

2. Create a class that maintains your state

class MyClass {
    private $a;
    private $b;

    public function __construct($a, $b) {
        $this->a = $a;
        $this->b = $b;
    }

    public function myFunction() {
        // Do something
    }
}
Loading history...
663
664
        // Define Graphical library path
665 View Code Duplication
        if (!defined('IMAGE_TRANSFORM_IM_PATH') && 'imagick' === $xoopsModuleConfig['graphic_lib']) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
666
            define('IMAGE_TRANSFORM_IM_PATH', $xoopsModuleConfig['graphic_lib_path']);
667
        }
668
        $imageFactory   = new Image_Transform;
669
        $imageTransform = $imageFactory->factory($xoopsModuleConfig['graphic_lib']);
670
671
        $ret = [];
672
        if ($this->_haveLargePhoto($photoName)) {
673
            $imageTransform->load($this->_getUploadPhotoPath() . 'large/large_' . $photoName);
674
            $ret['width']  = $imageTransform->getImageWidth();
675
            $ret['height'] = $imageTransform->getImageHeight();
676
        } else {
677
            $imageTransform->load($this->_getUploadPhotoPath() . 'medium/' . $photoName);
678
            $ret['width']  = $imageTransform->getImageWidth();
679
            $ret['height'] = $imageTransform->getImageHeight();
680
        }
681
        $imageTransform->free();
682
683
        return $ret;
684
    }
685
686
    /**
687
     * @param $photoName
688
     *
689
     * @return string
690
     */
691
    public function _getAutoDescription($photoName)
692
    {
693
        global $xoopsModuleConfig;
0 ignored issues
show
Compatibility Best Practice introduced by
Use of global functionality is not recommended; it makes your code harder to test, and less reusable.

Instead of relying on global state, we recommend one of these alternatives:

1. Pass all data via parameters

function myFunction($a, $b) {
    // Do something
}

2. Create a class that maintains your state

class MyClass {
    private $a;
    private $b;

    public function __construct($a, $b) {
        $this->a = $a;
        $this->b = $b;
    }

    public function myFunction() {
        // Do something
    }
}
Loading history...
694
695
        //DNPROSSI
696
        /*if ($xoopsModuleConfig['enable_longdesc']) {
0 ignored issues
show
Unused Code Comprehensibility introduced by
58% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
697
            $newphotoname = '';
698
            $newnewphotoname = '';
699
            $patterns = array();
700
            $patterns[0] = "/-/";
701
            $patterns[1] = "/_/";
702
            $replacements = array();
703
            $replacements[0] = " ";
704
            $replacements[1] = "'";
705
            $newphotoName = substr($photoName, strpos($photoName, "-") + 1);
706
            $newphotoName = substr($newphotoName, strpos($newphotoName, "-") + 1);
707
708
            return preg_replace($patterns, $replacements, substr($newphotoName,0,-12));
709
        } else { */
710
        $matches = [];
711
        preg_match_all($xoopsModuleConfig['photoname_pattern'], substr($photoName, 0, -12), $matches);
712
        preg_match_all($xoopsModuleConfig['photoname_pattern'], $photoName, $matches);
713
714
        return implode(' ', $matches[1]);
715
        //}
716
    }
717
718
    /**
719
     * @param $fileName
720
     *
721
     * @return string
722
     */
723
    public function _makeFileName($fileName)
0 ignored issues
show
Coding Style introduced by
_makeFileName uses the super-global variable $GLOBALS which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
724
    {
725
        //DNPROSSI
726
        //$fileName = preg_replace("/[^a-zA-Z0-9()_\.-]/", "-", $fileName);
0 ignored issues
show
Unused Code Comprehensibility introduced by
60% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
727
        $fileName = preg_replace("/[^a-zA-Z0-9_\.-]/", '-', $fileName);
728
729
        $fileName = explode('.', $fileName);
730
        $userId   = is_object($GLOBALS['xoopsUser']) ? $GLOBALS['xoopsUser']->getVar('uid') : 0;
731
732
        return $fileName[0] . '_' . $userId . '_' . substr(md5(uniqid(mt_rand(), true)), 27) . '.' . $fileName[1];
733
    }
734
735
    /**
736
     * @param $photoName
737
     *
738
     * @return float
739
     */
740
    public function _getPhotoSize($photoName)
741
    {
742
        if ($this->_haveLargePhoto($photoName)) {
743
            return $this->_getFileSize('large/large_' . $photoName);
744
        } else {
745
            return $this->_getFileSize($photoName);
746
        }
747
    }
748
749
    /**
750
     * @param $fileName
751
     *
752
     * @return float
753
     */
754
    public function _getFileSize($fileName)
755
    {
756
        return round(filesize($this->_getUploadPhotoPath() . $fileName) / 1024, 2);
757
    }
758
759
    /**
760
     * @param $catId
761
     */
762
    public function rebuildThumbnail($catId)
763
    {
764
        $photos = $this->getAlbumPhoto($catId);
765
        foreach ($photos as $photo) {
766
            $this->_makeThumb($photo->getVar('photo_name'));
767
        }
768
    }
769
770
    /* Return Code :
771
        0 : Photo added
772
        1 : Photo pending
773
        2 : This is not an album
774
        3 : HTTP Upload error
775
        4 : File rejected
776
        5 : File chunk receive
777
        */
778
    /**
779
     * @param      $file
780
     * @param bool $checkMd5
781
     *
782
     * @return int
783
     */
784
    public function postPhotoTraitement($file, $checkMd5 = false)
0 ignored issues
show
Coding Style introduced by
postPhotoTraitement uses the super-global variable $_POST which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
785
    {
786
        //        require_once XOOPS_ROOT_PATH.'/modules/extgallery/class/photoUploader.php';
0 ignored issues
show
Unused Code Comprehensibility introduced by
43% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
787
788
        $catHandler = xoops_getModuleHandler('publiccat', 'extgallery');
789
790
        $catId = (int)$_POST['cat_id'];
791
792
        // If isn't an album when stop the traitment
793
        $cat = $catHandler->getCat($catId);
794
        if (null !== $cat && (1 != $cat->getVar('nright') - $cat->getVar('nleft'))) {
795
            return 2;
796
        }
797
798
        $allowedMimeTypes = ['image/jpeg', 'image/jpg', 'image/pjpeg', 'image/gif', 'image/png', 'image/x-png'];
799
        //        $allowedMimeTypes = array('jpg/jpeg', 'image/bmp', 'image/gif', 'image/jpeg', 'image/jpg', 'image/x-png', 'image/png');
0 ignored issues
show
Unused Code Comprehensibility introduced by
65% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
800
801
        $uploadDir = XOOPS_ROOT_PATH . '/uploads/extgallery/public-photo/';
802
803
        //        $this->photoUploader = new ExtgalleryPhotoUploader($uploadDir,  50000000, 5000, 5000);
0 ignored issues
show
Unused Code Comprehensibility introduced by
57% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
804
        //        $this->photoUploader->checkMd5 = $checkMd5;
0 ignored issues
show
Unused Code Comprehensibility introduced by
46% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
805
        //        $this->photoUploader->fetchPhoto($_FILES[$file]);
0 ignored issues
show
Unused Code Comprehensibility introduced by
77% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
806
807
        //------------------------
808
        require_once XOOPS_ROOT_PATH . '/class/uploader.php';
809
        $this->photoUploader = new XoopsMediaUploader($uploadDir, $allowedMimeTypes, 50000000, 5000, 5000);
810
811
        $jupart  = isset($_POST['jupart']) ? (int)$_POST['jupart'] : 0;
812
        $jufinal = isset($_POST['jufinal']) ? (int)$_POST['jufinal'] : 1;
813
814
        if ($this->photoUploader->fetchMedia($file) && $this->photoUploader->upload()) {
0 ignored issues
show
Unused Code introduced by
This if statement is empty and can be removed.

This check looks for the bodies of if statements that have no statements or where all statements have been commented out. This may be the result of changes for debugging or the code may simply be obsolete.

These if bodies can be removed. If you have an empty if but statements in the else branch, consider inverting the condition.

if (rand(1, 6) > 3) {
//print "Check failed";
} else {
    print "Check succeeded";
}

could be turned into

if (rand(1, 6) <= 3) {
    print "Check succeeded";
}

This is much more concise to read.

Loading history...
815
        } else {
816
            // We got a chunk, so we don't add photo to database
817
            if ($jupart && !$jufinal) {
818
                return 5;
819
            } else {
820
                return 4;
821
            }
822
        }
823
824
        //---------------------------
825
826
        /*
827
828
                $jupart = (isset($_POST['jupart'])) ? (int) $_POST['jupart'] : 0;
829
                $jufinal = (isset($_POST['jufinal'])) ? (int) $_POST['jufinal'] : 1;
830
831
                if ($this->photoUploader->isError()) {
832
                    return 4;
833
                // We got a chunk, so we don't add photo to database
834
                } elseif ($jupart && !$jufinal) {
835
                    return 5;
836
                }
837
        */
838
839
        //DNPROSSI - add missing title and description on upload
840
        $photoTitle = '';
841
        $photoDesc  = '';
842
        $photoExtra = '';
843
        $photoTag   = '';
844
845
        if (isset($_POST['photo_title'])) {
846
            $photoTitle = $_POST['photo_title'];
847
        }
848
        if (isset($_POST['photo_desc'])) {
849
            $photoDesc = $_POST['photo_desc'];
850
        }
851
        if (isset($_POST['photo_extra'])) {
852
            $photoExtra = $_POST['photo_extra'];
853
        }
854
        if (isset($_POST['tag'])) {
855
            $photoTag = $_POST['tag'];
856
        }
857
858
        $photoStatus = $this->addLocalPhoto($catId, $this->photoUploader->getSavedFileName(), $photoTitle, $photoDesc, $photoExtra, $photoTag);
859
        /** @var ExtgalleryCat $cat */
860
        $cat = $catHandler->getCat($catId);
861
        $cat->setVar('cat_isalbum', 1);
862
        $catHandler->insert($cat);
863
864
        /** @var XoopsNotificationHandler $notificationHandler */
865
        $notificationHandler = xoops_getHandler('notification');
866
        $extraTags           = [
867
            'X_ITEM_CAT'     => $cat->getVar('cat_name'),
868
            'X_ITEM_NBPHOTO' => 1
869
        ];
870
871
        if (1 == $photoStatus) {
872
            $extraTags['X_ITEM_URL'] = XOOPS_URL . '/modules/extgallery/public-album.php?id=' . $cat->getVar('cat_id');
873
            $notificationHandler->triggerEvent('global', 0, 'new_photo', $extraTags);
874
            $notificationHandler->triggerEvent('album', $cat->getVar('cat_id'), 'new_photo_album', $extraTags);
875
876
            // Update album count
877 View Code Duplication
            if (0 == $cat->getVar('cat_nb_photo')) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
878
                $criteria = new CriteriaCompo();
879
                $criteria->add(new Criteria('nleft', $cat->getVar('nleft'), '<'));
880
                $criteria->add(new Criteria('nright', $cat->getVar('nright'), '>'));
881
                $catHandler->updateFieldValue('cat_nb_album', 'cat_nb_album + 1', $criteria);
882
            }
883
884
            // Update photo count
885
            $criteria = new CriteriaCompo();
886
            $criteria->add(new Criteria('nleft', $cat->getVar('nleft'), '<='));
887
            $criteria->add(new Criteria('nright', $cat->getVar('nright'), '>='));
888
            $catHandler->updateFieldValue('cat_nb_photo', 'cat_nb_photo + 1', $criteria);
889
890
            return 0;
891 View Code Duplication
        } else {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
892
            $extraTags['X_ITEM_URL'] = XOOPS_URL . '/modules/extgallery/admin/photo.php';
893
            $notificationHandler->triggerEvent('global', 0, 'new_photo_pending', $extraTags);
894
895
            return 1;
896
        }
897
    }
898
899
    /**
900
     * @param        $catId
901
     * @param        $dirtyPhotoName
902
     * @param string $photoTitle
903
     * @param string $photoDesc
904
     * @param string $photoExtra
905
     * @param string $photoTag
906
     *
907
     * @return mixed
908
     */
909
    public function addLocalPhoto(
0 ignored issues
show
Coding Style introduced by
addLocalPhoto uses the super-global variable $GLOBALS which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
910
        $catId,
911
        $dirtyPhotoName,
912
        $photoTitle = '',
913
        $photoDesc = '',
914
        $photoExtra = '',
915
        $photoTag = ''
916
    ) {
917
        require_once XOOPS_ROOT_PATH . '/modules/extgallery/class/pear/Image/Transform.php';
918
919
        global $xoopsModuleConfig;
0 ignored issues
show
Compatibility Best Practice introduced by
Use of global functionality is not recommended; it makes your code harder to test, and less reusable.

Instead of relying on global state, we recommend one of these alternatives:

1. Pass all data via parameters

function myFunction($a, $b) {
    // Do something
}

2. Create a class that maintains your state

class MyClass {
    private $a;
    private $b;

    public function __construct($a, $b) {
        $this->a = $a;
        $this->b = $b;
    }

    public function myFunction() {
        // Do something
    }
}
Loading history...
920
        $permHandler = ExtgalleryPublicPermHandler::getInstance();
921
922
        // Replace all bad file name character
923
        $photoName = $this->_makeFileName($dirtyPhotoName);
924
        rename($this->_getUploadPhotoPath() . $dirtyPhotoName, $this->_getUploadPhotoPath() . $photoName);
925
926
        //DNPROSSI - changed photo_desc to photo_title
927
        // Making auto description
928
        if ('' === $photoTitle) {
929
            $photoTitle = $this->_getAutoDescription($photoName);
930
        }
931
932
        $originalName = '';
933
        // Save original photo
934
        if ($xoopsModuleConfig['save_large'] && $xoopsModuleConfig['save_original']) {
935
            $fileName     = explode('.', $photoName);
936
            $originalName = md5(uniqid(mt_rand(), true)) . '.' . $fileName[1];
937
            copy($this->_getUploadPhotoPath() . $photoName, $this->_getUploadPhotoPath() . 'original/' . $originalName);
938
        }
939
940
        $this->_largePhotoTreatment($photoName);
941
942
        $this->_mediumPhotoTreatment($photoName);
943
944
        $this->_makeThumb($photoName);
945
946
        $imageDimension = $this->_getImageDimension($photoName);
947
948
        $userId = is_object($GLOBALS['xoopsUser']) ? $GLOBALS['xoopsUser']->getVar('uid') : 0;
949
        $data   = [
950
            'cat_id'          => $catId,
951
            'photo_title'     => $photoTitle,
952
            'photo_desc'      => $photoDesc,
953
            'photo_name'      => $photoName,
954
            'photo_orig_name' => $originalName,
955
            'uid'             => $userId,
956
            'photo_size'      => $this->_getPhotoSize($photoName),
957
            'photo_res_x'     => $imageDimension['width'],
958
            'photo_res_y'     => $imageDimension['height'],
959
            'photo_date'      => time(),
960
            'photo_havelarge' => $this->_haveLargePhoto($photoName),
961
            'photo_approved'  => $permHandler->isAllowed($GLOBALS['xoopsUser'], 'public_autoapprove', $catId),
962
            'photo_extra'     => $photoExtra,
963
            'dohtml'          => $xoopsModuleConfig['allow_html']
964
        ];
965
966
        // Deleting working photo
967
        unlink($this->_getUploadPhotoPath() . $photoName);
968
969
        $this->createPhoto($data);
970
971
        if (1 == $xoopsModuleConfig['usetag'] || (is_dir('../tag') || is_dir('../../tag'))) {
972
            $newid      = $this->db->getInsertId();
973
            $tagHandler = xoops_getModuleHandler('tag', 'tag');
974
            $tagHandler->updateByItem($photoTag, $newid, 'extgallery', 0);
975
        }
976
977
        return $data['photo_approved'];
978
    }
979
980
    /**
981
     * @param $queryArray
982
     * @param $condition
983
     * @param $limit
984
     * @param $start
985
     * @param $userId
986
     *
987
     * @return array
988
     */
989
    public function getSearchedPhoto($queryArray, $condition, $limit, $start, $userId)
990
    {
991
        $criteria = new CriteriaCompo();
992
        if ($userId > 0) {
993
            $criteria->add(new Criteria('uid', $userId));
994
        }
995
        $criteria->add(new Criteria('photo_approved', 1));
996
        if (is_array($queryArray) && count($queryArray) > 0) {
997
            $subCriteria = new CriteriaCompo();
998
            foreach ($queryArray as $keyWord) {
999
                $keyWordCriteria = new CriteriaCompo();
1000
                $keyWordCriteria->add(new Criteria('photo_title', '%' . $keyWord . '%', 'LIKE'));
1001
                $keyWordCriteria->add(new Criteria('photo_desc', '%' . $keyWord . '%', 'LIKE'), 'OR');
1002
                $keyWordCriteria->add(new Criteria('photo_name', '%' . $keyWord . '%', 'LIKE'), 'OR');
1003
                $subCriteria->add($keyWordCriteria, $condition);
1004
                unset($keyWordCriteria);
1005
            }
1006
            $criteria->add($subCriteria);
1007
        }
1008
        $criteria->setStart($start);
1009
        $criteria->setLimit($limit);
1010
        $criteria->setSort('photo_date');
1011
1012
        $photos = $this->getObjects($criteria);
1013
1014
        $ret = [];
1015
        foreach ($photos as $photo) {
1016
            if ($photo->getVar('photo_title')) {
1017
                $title = $photo->getVar('photo_title');
1018
            } else {
1019
                $title = $photo->getVar('photo_desc');
1020
            }
1021
            $data  = [
1022
                'image' => 'assets/images/extgallery-posticon.gif',
1023
                'link'  => 'public-photo.php?photoId=' . $photo->getVar('photo_id'),
1024
                'title' => $title,
1025
                'time'  => $photo->getVar('photo_date'),
1026
                'uid'   => $photo->getVar('uid')
1027
            ];
1028
            $ret[] = $data;
1029
        }
1030
1031
        return $ret;
1032
    }
1033
1034
    /**
1035
     * @return array
1036
     */
1037
    public function getPendingPhoto()
1038
    {
1039
        $criteria = new Criteria('photo_approved', 0);
1040
1041
        return $this->getObjects($criteria);
1042
    }
1043
1044
    /**
1045
     * @param $criteria
1046
     * @param $data
1047
     */
1048
    public function _addInCriteria(&$criteria, $data)
1049
    {
1050
        $count = count($data);
1051
        if ($count > 0) {
1052
            $in = '(' . $data[0];
1053
            array_shift($data);
1054
            foreach ($data as $elmt) {
1055
                $in .= ',' . $elmt;
1056
            }
1057
            $in .= ')';
1058
            $criteria->add(new Criteria('cat_id', $in, 'IN'));
1059
        }
1060
    }
1061
1062
    /**
1063
     * @param $param
1064
     *
1065
     * @return array
1066
     */
1067 View Code Duplication
    public function getRandomPhoto($param)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
1068
    {
1069
        $catHandler = xoops_getModuleHandler('publiccat', 'extgallery');
1070
        $criteria   = new CriteriaCompo();
1071
        if (null !== $catHandler->getCatRestrictCriteria()) {
1072
            $criteria->add($catHandler->getCatRestrictCriteria());
1073
        }
1074
        $criteria->add(new Criteria('photo_approved', 1));
1075
        $this->_addInCriteria($criteria, $param['cat']);
1076
        $criteria->setSort('RAND()');
1077
        $criteria->setLimit($param['limit']);
1078
1079
        return $this->getObjects($criteria);
1080
    }
1081
1082
    /**
1083
     * @param $param
1084
     *
1085
     * @return array
1086
     */
1087 View Code Duplication
    public function getLastPhoto($param)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
1088
    {
1089
        $catHandler = xoops_getModuleHandler('publiccat', 'extgallery');
1090
1091
        $criteria = new CriteriaCompo();
1092
        $criteria->add($catHandler->getCatRestrictCriteria());
1093
        $criteria->add(new Criteria('photo_approved', 1));
1094
        $this->_addInCriteria($criteria, $param['cat']);
1095
        $criteria->setSort('photo_date');
1096
        $criteria->setOrder('DESC');
1097
        $criteria->setLimit($param['limit']);
1098
1099
        return $this->getObjects($criteria);
1100
    }
1101
1102
    /**
1103
     * @param $param
1104
     *
1105
     * @return array
1106
     */
1107 View Code Duplication
    public function getTopViewPhoto($param)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
1108
    {
1109
        $catHandler = xoops_getModuleHandler('publiccat', 'extgallery');
1110
1111
        $criteria = new CriteriaCompo();
1112
        $criteria->add($catHandler->getCatRestrictCriteria());
1113
        $criteria->add(new Criteria('photo_approved', 1));
1114
        $this->_addInCriteria($criteria, $param['cat']);
1115
        $criteria->setSort('photo_hits');
1116
        $criteria->setOrder('DESC');
1117
        $criteria->setLimit($param['limit']);
1118
1119
        return $this->getObjects($criteria);
1120
    }
1121
1122
    /**
1123
     * @param $param
1124
     *
1125
     * @return array
1126
     */
1127 View Code Duplication
    public function getTopRatedPhoto($param)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
1128
    {
1129
        $catHandler = xoops_getModuleHandler('publiccat', 'extgallery');
1130
1131
        $criteria = new CriteriaCompo();
1132
        $criteria->add($catHandler->getCatRestrictCriteria());
1133
        $criteria->add(new Criteria('photo_approved', 1));
1134
        $this->_addInCriteria($criteria, $param['cat']);
1135
        $criteria->setSort('photo_rating');
1136
        $criteria->setOrder('DESC');
1137
        $criteria->setLimit($param['limit']);
1138
1139
        return $this->getObjects($criteria);
1140
    }
1141
1142
    /**
1143
     * @param $param
1144
     *
1145
     * @return array
1146
     */
1147 View Code Duplication
    public function getTopEcardPhoto($param)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
1148
    {
1149
        $catHandler = xoops_getModuleHandler('publiccat', 'extgallery');
1150
1151
        $criteria = new CriteriaCompo();
1152
        $criteria->add($catHandler->getCatRestrictCriteria());
1153
        $criteria->add(new Criteria('photo_approved', 1));
1154
        $this->_addInCriteria($criteria, $param['cat']);
1155
        $criteria->setSort('photo_ecard');
1156
        $criteria->setOrder('DESC');
1157
        $criteria->setLimit($param['limit']);
1158
1159
        return $this->getObjects($criteria);
1160
    }
1161
1162
    /**
1163
     * @param $param
1164
     */
1165
    public function getTopSubmitter($param)
1166
    {
1167
        $catHandler = xoops_getModuleHandler('publiccat', 'extgallery');
0 ignored issues
show
Unused Code introduced by
$catHandler is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
1168
1169
        $criteria = new Criteria();
1170
        $this->_addInCriteria($criteria, $param['cat']);
1171
1172
        echo $criteria->renderWhere();
1173
    }
1174
1175
    /**
1176
     * @return mixed
1177
     */
1178
    public function getInsertId()
1179
    {
1180
        return $this->db->getInsertId();
1181
    }
1182
}
1183