Completed
Branch master (616741)
by Michael
03:30 queued 01:05
created

JlmPicturesHandler::resizeImage()   C

Complexity

Conditions 7
Paths 9

Size

Total Lines 38
Code Lines 32

Duplication

Lines 22
Ratio 57.89 %

Importance

Changes 0
Metric Value
cc 7
eloc 32
nc 9
nop 6
dl 22
loc 38
rs 6.7272
c 0
b 0
f 0
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 44 and the first side effect is on line 33.

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
-------------------------------------------------------------------------
4
                     ADSLIGHT 2 : Module for Xoops
5
6
        Redesigned and ameliorate By Luc Bizet user at www.frxoops.org
7
        Started with the Classifieds module and made MANY changes
8
        Website : http://www.luc-bizet.fr
9
        Contact : [email protected]
10
-------------------------------------------------------------------------
11
             Original credits below Version History
12
##########################################################################
13
#                    Classified Module for Xoops                         #
14
#  By John Mordo user jlm69 at www.xoops.org and www.jlmzone.com         #
15
#      Started with the MyAds module and made MANY changes               #
16
##########################################################################
17
 Original Author: Pascal Le Boustouller
18
 Author Website : [email protected]
19
 Licence Type   : GPL
20
-------------------------------------------------------------------------
21
*/
22
23
use Xmf\Request;
24
25
/**
26
 * Protection against inclusion outside the site
27
 */
28
// defined('XOOPS_ROOT_PATH') || exit('XOOPS root path not defined');
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...
29
30
/**
31
 * Includes of form objects and uploader
32
 */
33
include_once XOOPS_ROOT_PATH . '/class/uploader.php';
34
include_once XOOPS_ROOT_PATH . '/kernel/object.php';
35
include_once XOOPS_ROOT_PATH . '/class/xoopsformloader.php';
36
include_once XOOPS_ROOT_PATH . '/kernel/object.php';
37
include_once XOOPS_ROOT_PATH . '/modules/adslight/class/utilities.php';
38
39
/**
40
 * light_pictures class.
41
 * $this class is responsible for providing data access mechanisms to the data source
42
 * of XOOPS user class objects.
43
 */
44
class JlmPictures 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...
45
{
46
    public $db;
47
    // constructor
48
    /**
49
     * @param null       $id
50
     * @param null|array $lid
51
     */
52
    public function __construct($id = null, $lid = null)
53
    {
54
        $this->db = XoopsDatabaseFactory::getDatabaseConnection();
55
        $this->initVar('cod_img', XOBJ_DTYPE_INT, null, false, 10);
56
        $this->initVar('title', XOBJ_DTYPE_TXTBOX, null, false);
57
        $this->initVar('date_added', XOBJ_DTYPE_TXTBOX, null, false);
58
        $this->initVar('date_modified', XOBJ_DTYPE_TXTBOX, null, false);
59
        $this->initVar('lid', XOBJ_DTYPE_INT, null, false, 10);
60
        $this->initVar('uid_owner', XOBJ_DTYPE_TXTBOX, null, false);
61
        $this->initVar('url', XOBJ_DTYPE_TXTBOX, null, false);
62
        if (!empty($lid)) {
63
            if (is_array($lid)) {
64
                $this->assignVars($lid);
65
            } else {
66
                $this->load((int)$lid);
67
            }
68
        } else {
69
            $this->setNew();
70
        }
71
    }
72
73
    /**
74
     * @param $id
75
     */
76
    public function load($id)
77
    {
78
        global $moduleDirName;
79
        $sql   = 'SELECT * FROM ' . $this->db->prefix('adslight_pictures') . ' WHERE cod_img=' . $id . '';
80
        $myrow = $this->db->fetchArray($this->db->query($sql));
81
        $this->assignVars($myrow);
82
        if (!$myrow) {
83
            $this->setNew();
84
        }
85
    }
86
87
    /**
88
     * @param array  $criteria
89
     * @param bool   $asobject
90
     * @param string $sort
91
     * @param string $order
92
     * @param int    $limit
93
     * @param int    $start
94
     *
95
     * @return array
96
     */
97
    public function getAllPictures(
98
        $criteria = array(),
99
        $asobject = false,
100
        $sort = 'cod_img',
101
        $order = 'ASC',
102
        $limit = 0,
103
        $start = 0
104
    ) {
105
        global $moduleDirName;
106
        $db          = XoopsDatabaseFactory::getDatabaseConnection();
107
        $ret         = array();
108
        $where_query = '';
109
        if (is_array($criteria) && count($criteria) > 0) {
110
            $where_query = ' WHERE';
111
            foreach ($criteria as $c) {
112
                $where_query .= " $c AND";
113
            }
114
            $where_query = substr($where_query, 0, -4);
115
        } elseif (!is_array($criteria) && $criteria) {
116
            $where_query = " WHERE {$criteria}";
117
        }
118
        if (!$asobject) {
119
            $sql    = 'SELECT cod_img FROM ' . $db->prefix('adslight_pictures') . "$where_query ORDER BY $sort $order";
120
            $result = $db->query($sql, $limit, $start);
121
            while ($myrow = $db->fetchArray($result)) {
122
                $ret[] = $myrow['jlm_pictures_id'];
123
            }
124
        } else {
125
            $sql    = 'SELECT * FROM ' . $db->prefix('adslight_pictures') . "$where_query ORDER BY $sort $order";
126
            $result = $db->query($sql, $limit, $start);
127
            while ($myrow = $db->fetchArray($result)) {
128
                $ret[] = new JlmPictures($myrow);
129
            }
130
        }
131
132
        return $ret;
133
    }
134
}
135
136
// -------------------------------------------------------------------------
137
// ------------------light_pictures user handler class -------------------
138
// -------------------------------------------------------------------------
139
/**
140
 * light_pictureshandler class.
141
 * This class provides simple mechanism for light_pictures object and generate forms for inclusion etc
142
 */
143
class JlmPicturesHandler extends XoopsObjectHandler
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...
144
{
145
    /**
146
     * create a new light_pictures
147
     *
148
     * @param  bool $isNew flag the new objects as "new"?
149
     * @return XoopsObject light_pictures
150
     */
151
    public function create($isNew = true)
152
    {
153
        $jlm_pictures = new JlmPictures();
154
        if ($isNew) {
155
            $jlm_pictures->setNew();
156
        } else {
157
            $jlm_pictures->unsetNew();
158
        }
159
160
        return $jlm_pictures;
161
    }
162
163
    /**
164
     * retrieve a light_pictures
165
     *
166
     * @param int $id of the light_pictures
167
     * @param     $lid
168
     *
169
     * @return mixed reference to the {@link light_pictures} object, FALSE if failed
170
     */
171
    public function get($id, $lid = null)
172
    {
173
        global $moduleDirName;
174
175
        $sql = 'SELECT * FROM ' . $this->db->prefix('adslight_pictures') . ' WHERE cod_img=' . $id . ' AND lid=' . $lid . '';
176
        if (!$result = $this->db->query($sql)) {
177
            return false;
178
        }
179
        $numrows = $this->db->getRowsNum($result);
180
        if ($numrows == 1) {
181
            $jlm_pictures = new JlmPictures();
182
            $jlm_pictures->assignVars($this->db->fetchArray($result));
183
184
            return $jlm_pictures;
185
        }
186
187
        return false;
188
    }
189
190
    /**
191
     * insert a new light_pictures in the database
192
     *
193
     * @param XoopsObject $jlm_pictures
194
     * @param bool        $force
195
     * @internal param object $light_pictures reference to the {@link light_pictures} object object
196
     * @return bool FALSE if failed, TRUE if already present and unchanged or successful
197
     */
198
    public function insert(XoopsObject $jlm_pictures, $force = false)
199
    {
200
        global $xoopsConfig, $lid, $moduleDirName;
201
        $cod_img = '';
202
        if (get_class($jlm_pictures) !== 'JlmPictures') {
203
            return false;
204
        }
205
        if (!$jlm_pictures->isDirty()) {
206
            return true;
207
        }
208
        if (!$jlm_pictures->cleanVars()) {
209
            return false;
210
        }
211
        foreach ($jlm_pictures->cleanVars as $k => $v) {
212
            ${$k} = $v;
213
        }
214
        $now = time();
215
        if ($jlm_pictures->isNew()) {
216
            // ajout/modification d'un JlmPictures
217
            $jlm_pictures = new JlmPictures();
218
219
            $format = 'INSERT INTO %s (cod_img, title, date_added, date_modified, lid, uid_owner, url)';
220
            $format .= 'VALUES (%u, %s, %s, %s, %s, %s, %s)';
221
            $sql   = sprintf($format, $this->db->prefix('adslight_pictures'), $cod_img, $this->db->quoteString($title), $now, $now, $this->db->quoteString($lid), $this->db->quoteString($uid_owner),
0 ignored issues
show
Bug introduced by
The variable $title does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
Bug introduced by
The variable $uid_owner does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
222
                             $this->db->quoteString($url));
0 ignored issues
show
Bug introduced by
The variable $url does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
223
            $force = true;
224
        } else {
225
            $format = 'UPDATE %s SET ';
226
            $format .= 'cod_img=%u, title=%s, date_added=%s, date_modified=%s, lid=%s, uid_owner=%s, url=%s';
227
            $format .= ' WHERE cod_img = %u';
228
            $sql = sprintf($format, $this->db->prefix('adslight_pictures'), $cod_img, $this->db->quoteString($title), $now, $now, $this->db->quoteString($lid), $this->db->quoteString($uid_owner),
229
                           $this->db->quoteString($url), $cod_img);
230
        }
231 View Code Duplication
        if (false !== $force) {
232
            $result = $this->db->queryF($sql);
233
        } else {
234
            $result = $this->db->query($sql);
235
        }
236
        if (!$result) {
237
            return false;
238
        }
239
        if (empty($cod_img)) {
240
            $cod_img = $this->db->getInsertId();
241
        }
242
        $jlm_pictures->assignVar('cod_img', $cod_img);
243
        $jlm_pictures->assignVar('lid', $lid);
244
        $jlm_pictures->assignVar('url', $url);
245
246
        return true;
247
    }
248
249
    /**
250
     * delete a JlmPictures from the database
251
     *
252
     * @param  XoopsObject $jlm_pictures reference to the JlmPictures to delete
253
     * @param  bool        $force
254
     * @return bool        FALSE if failed.
255
     */
256
    public function delete(XoopsObject $jlm_pictures, $force = false)
257
    {
258
        global $moduleDirName;
259
260
        if (get_class($jlm_pictures) !== 'JlmPictures') {
261
            return false;
262
        }
263
        $sql = sprintf('DELETE FROM %s WHERE cod_img = %u', $this->db->prefix('adslight_pictures'), $jlm_pictures->getVar('cod_img'));
264 View Code Duplication
        if (false !== $force) {
265
            $result = $this->db->queryF($sql);
266
        } else {
267
            $result = $this->db->query($sql);
268
        }
269
        if (!$result) {
270
            return false;
271
        }
272
273
        return true;
274
    }
275
276
    /**
277
     * retrieve JlmPictures from the database
278
     *
279
     * @param  CriteriaElement $criteria  {@link CriteriaElement} conditions to be met
0 ignored issues
show
Documentation introduced by
Should the type for parameter $criteria not be null|CriteriaElement?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
280
     * @param  bool            $id_as_key use the UID as key for the array?
281
     * @return array  array of {@link JlmPictures} objects
282
     */
283
    public function &getObjects(CriteriaElement $criteria = null, $id_as_key = false)
284
    {
285
        global $moduleDirName;
286
287
        $ret   = array();
288
        $limit = $start = 0;
289
        $sql   = 'SELECT * FROM ' . $this->db->prefix('adslight_pictures');
290
        if (isset($criteria) && is_subclass_of($criteria, 'criteriaelement')) {
0 ignored issues
show
Bug introduced by
Due to PHP Bug #53727, is_subclass_of returns inconsistent results on some PHP versions for interfaces; you could instead use ReflectionClass::implementsInterface.
Loading history...
291
            $sql .= ' ' . $criteria->renderWhere();
292
            if ($criteria->getSort() != '') {
293
                $sql .= ' ORDER BY ' . $criteria->getSort() . ' ' . $criteria->getOrder();
294
            }
295
            $limit = $criteria->getLimit();
296
            $start = $criteria->getStart();
297
        }
298
        $result = $this->db->query($sql, $limit, $start);
299
        if (!$result) {
300
            return $ret;
301
        }
302
        while ($myrow = $this->db->fetchArray($result)) {
303
            $jlm_pictures = new JlmPictures();
304
            $jlm_pictures->assignVars($myrow);
305
            if (!$id_as_key) {
306
                $ret[] =& $jlm_pictures;
307
            } else {
308
                $ret[$myrow['cod_img']] =& $jlm_pictures;
309
            }
310
            unset($jlm_pictures);
311
        }
312
313
        return $ret;
314
    }
315
316
    /**
317
     * count JlmPictures matching a condition
318
     *
319
     * @param  CriteriaElement $criteria {@link CriteriaElement} to match
0 ignored issues
show
Documentation introduced by
Should the type for parameter $criteria not be null|CriteriaElement?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
320
     * @return int    count of JlmPictures
321
     */
322
    public function getCount(CriteriaElement $criteria = null)
323
    {
324
        global $moduleDirName;
325
326
        $sql = 'SELECT COUNT(*) FROM ' . $this->db->prefix('adslight_pictures');
327
        if (isset($criteria) && is_subclass_of($criteria, 'criteriaelement')) {
0 ignored issues
show
Bug introduced by
Due to PHP Bug #53727, is_subclass_of returns inconsistent results on some PHP versions for interfaces; you could instead use ReflectionClass::implementsInterface.
Loading history...
328
            $sql .= ' ' . $criteria->renderWhere();
329
        }
330
        $result = $this->db->query($sql);
331
        if (!$result) {
332
            return 0;
333
        }
334
        list($count) = $this->db->fetchRow($result);
335
336
        return $count;
337
    }
338
339
    /**
340
     * delete JlmPictures matching a set of conditions
341
     *
342
     * @param  CriteriaElement $criteria {@link CriteriaElement}
0 ignored issues
show
Documentation introduced by
Should the type for parameter $criteria not be null|CriteriaElement?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
343
     * @return bool   FALSE if deletion failed
344
     */
345
    public function deleteAll(CriteriaElement $criteria = null)
346
    {
347
        global $moduleDirName;
348
        $sql = 'DELETE FROM ' . $this->db->prefix('adslight_pictures');
349
        if (isset($criteria) && is_subclass_of($criteria, 'criteriaelement')) {
0 ignored issues
show
Bug introduced by
Due to PHP Bug #53727, is_subclass_of returns inconsistent results on some PHP versions for interfaces; you could instead use ReflectionClass::implementsInterface.
Loading history...
350
            $sql .= ' ' . $criteria->renderWhere();
351
        }
352
        if (!$result = $this->db->query($sql)) {
353
            return false;
354
        }
355
356
        return true;
357
    }
358
359
    /**
360
     * Render a form to send pictures
361
     *
362
     * @param int      $uid
363
     * @param int      $lid
364
     * @param int      $maxbytes the maximum size of a picture
365
     * @param XoopsTpl $xoopsTpl the one in which the form will be rendered
366
     * @return bool   TRUE
367
     *
368
     * obs: Some functions wont work on php 4 so edit lines down under acording to your version
369
     */
370
    public function renderFormSubmit($uid, $lid, $maxbytes, $xoopsTpl)
371
    {
372
        global $moduleDirName, $main_lang;
373
        $field_token = '';
374
        $form       = new XoopsThemeForm(constant('_ADSLIGHT_SUBMIT_PIC_TITLE'), 'form_picture',
375
                                         '' . XOOPS_URL . "/modules/adslight/add_photo.php?lid=$lid&uid=" . $GLOBALS['xoopsUser']->getVar('uid') . '', 'post', true);
376
        $field_url  = new XoopsFormFile(constant('_ADSLIGHT_SELECT_PHOTO'), 'sel_photo', 2000000);
377
        $field_desc = new XoopsFormText(constant('_ADSLIGHT_CAPTION'), 'caption', 35, 55);
378
        $form->setExtra('enctype="multipart/form-data"');
379
        $button_send   = new XoopsFormButton('', 'submit_button', constant('_ADSLIGHT_UPLOADPICTURE'), 'submit');
380
        $field_warning = new XoopsFormLabel(sprintf(constant('_ADSLIGHT_YOUCANUPLOAD'), $maxbytes / 1024));
381
        $field_lid     = new XoopsFormHidden('lid', $lid);
382
        $field_uid     = new XoopsFormHidden('uid', $uid);
383
        /**
384
         * Check if using Xoops or XoopsCube (by jlm69)
385
         */
386
387
        $xCube = false;
388
        if (preg_match('/^XOOPS Cube/', XOOPS_VERSION)) { // XOOPS Cube 2.1x
389
            $xCube = true;
390
        }
391
392
        /**
393
         * Verify Ticket (by jlm69)
394
         * If your site is XoopsCube it uses $xoopsGTicket for the token.
395
         * If your site is Xoops it uses xoopsSecurity for the token.
396
         */
397
398 View Code Duplication
        if ($xCube) {
399
            $GLOBALS['xoopsGTicket']->addTicketXoopsFormElement($form, __LINE__, 1800, 'token');
400
        } else {
401
            $field_token = $GLOBALS['xoopsSecurity']->getTokenHTML();
402
        }
403
        $form->addElement($field_warning);
404
        $form->addElement($field_url, true);
405
        $form->addElement($field_desc, true);
406
        $form->addElement($field_lid, true);
407
        $form->addElement($field_uid, true);
408
409
        $form->addElement($field_token, true);
410
411
        $form->addElement($button_send);
412
        if (str_replace('.', '', PHP_VERSION) > 499) {
413
            $form->assign($xoopsTpl);
414
        } else {
415
            $form->display();
416
        }
417
418
        return true;
419
    }
420
421
    /**
422
     * Render a form to edit the description of the pictures
423
     *
424
     * @param  string $caption  The description of the picture
425
     * @param  int    $cod_img  the id of the image in database
426
     * @param  text   $filename the url to the thumb of the image so it can be displayed
427
     * @return bool   TRUE
428
     */
429
    public function renderFormEdit($caption, $cod_img, $filename)
430
    {
431
        global $moduleDirName, $main_lang;
432
433
        $form       = new XoopsThemeForm(_ADSLIGHT_EDIT_CAPTION, 'form_picture', 'editdesc.php', 'post', true);
434
        $field_desc = new XoopsFormText($caption, 'caption', 35, 55);
435
        $form->setExtra('enctype="multipart/form-data"');
436
        $button_send   = new XoopsFormButton('' . _ADSLIGHT_EDIT . '', 'submit_button', 'Submit', 'submit');
437
        $field_warning = new XoopsFormLabel("<img src='" . $filename . "' alt='sssss'>");
438
        $field_cod_img = new XoopsFormHidden('cod_img', $cod_img);
439
        //  $field_lid = new XoopsFormHidden("lid",$lid);
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...
440
        $field_marker = new XoopsFormHidden('marker', 1);
441
442
        /**
443
         * Check if using Xoops or XoopsCube (by jlm69)
444
         * Right now Xoops does not have a directory called preload, Xoops Cube does.
445
         * If this finds a diectory called preload in the Xoops Root folder $xCube=true.
446
         * This could change if Xoops adds a Directory called preload
447
         */
448
449
        $xCube   = false;
0 ignored issues
show
Unused Code introduced by
$xCube 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...
450
        $preload = XOOPS_ROOT_PATH . '/preload';
451
        if (is_dir($preload)) {
452
            $xCube = true;
0 ignored issues
show
Unused Code introduced by
$xCube 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...
453
        }
454
455
        /**
456
         * Verify Ticket (by jlm69)
457
         * If your site is XoopsCube it uses $xoopsGTicket for the token.
458
         * If your site is Xoops it uses xoopsSecurity for the token.
459
         */
460
461 View Code Duplication
        if ($xCube = true) {
0 ignored issues
show
Unused Code introduced by
$xCube 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...
462
            $GLOBALS['xoopsGTicket']->addTicketXoopsFormElement($form, __LINE__, 1800, 'token');
463
        } else {
464
            $field_token = $GLOBALS['xoopsSecurity']->getTokenHTML();
465
        }
466
467
        $form->addElement($field_warning);
468
        $form->addElement($field_desc);
469
        $form->addElement($field_cod_img);
470
        $form->addElement($field_marker);
471
        $form->addElement($field_token);
0 ignored issues
show
Bug introduced by
The variable $field_token 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...
472
        $form->addElement($button_send);
473
        $form->display();
474
475
        return true;
476
    }
477
478
    /**
479
     * Upload the file and Save into database
480
     *
481
     * @param  text $title         A litle description of the file
482
     * @param  text $path_upload   The path to where the file should be uploaded
483
     * @param  int  $thumbwidth    the width in pixels that the thumbnail will have
484
     * @param  int  $thumbheight   the height in pixels that the thumbnail will have
485
     * @param  int  $pictwidth     the width in pixels that the pic will have
486
     * @param  int  $pictheight    the height in pixels that the pic will have
487
     * @param  int  $maxfilebytes  the maximum size a file can have to be uploaded in bytes
488
     * @param  int  $maxfilewidth  the maximum width in pixels that a pic can have
489
     * @param  int  $maxfileheight the maximum height in pixels that a pic can have
490
     * @return bool FALSE if upload fails or database fails
491
     */
492
    public function receivePicture(
0 ignored issues
show
Coding Style introduced by
receivePicture 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...
Coding Style introduced by
receivePicture uses the super-global variable $_FILES 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...
493
        $title,
494
        $path_upload,
495
        $thumbwidth,
496
        $thumbheight,
497
        $pictwidth,
498
        $pictheight,
499
        $maxfilebytes,
500
        $maxfilewidth,
501
        $maxfileheight
502
    ) {
503
        global $xoopsDB, $_POST, $_FILES, $lid;
504
        //busca id do user logado
505
        $uid = $GLOBALS['xoopsUser']->getVar('uid');
0 ignored issues
show
Unused Code introduced by
$uid 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...
506
        $lid = Request::getInt('lid', 0, 'POST');
507
        //create a hash so it does not erase another file
508
        $hash1 = time();
509
        $hash  = substr($hash1, 0, 4);
0 ignored issues
show
Unused Code introduced by
$hash 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...
510
        // mimetypes and settings put this in admin part later
511
        $allowed_mimetypes = array('image/jpeg', 'image/gif');
512
        $maxfilesize       = $maxfilebytes;
513
        // create the object to upload
514
        $uploader = new XoopsMediaUploader($path_upload, $allowed_mimetypes, $maxfilesize, $maxfilewidth, $maxfileheight);
515
        // fetch the media
516
        if ($uploader->fetchMedia($_POST['xoops_upload_file'][0])) {
517
            //lets create a name for it
518
            $uploader->setPrefix('pic_' . $lid . '_');
519
            //now let s upload the file
520
            if (!$uploader->upload()) {
521
                // if there are errors lets return them
522
                echo "<div style=\"color:#FF0000; background-color:#FFEAF4; border-color:#FF0000; border-width:thick; border-style:solid; text-align:center;\"><p>"
523
                     . $uploader->getErrors()
524
                     . '</p></div>';
525
526
                return false;
527
            } else {
528
                // now let s create a new object picture and set its variables
529
                $picture = $this->create();
530
                $url     = $uploader->getSavedFileName();
531
                $picture->setVar('url', $url);
532
                $picture->setVar('title', $title);
533
                $uid = $GLOBALS['xoopsUser']->getVar('uid');
534
                $lid = (int)$lid;
535
                $picture->setVar('lid', $lid);
536
                $picture->setVar('uid_owner', $uid);
537
                $this->insert($picture);
538
                $saved_destination = $uploader->getSavedDestination();
539
                $this->resizeImage($saved_destination, $thumbwidth, $thumbheight, $pictwidth, $pictheight, $path_upload);
540
            }
541
        } else {
542
            echo "<div style=\"color:#FF0000; background-color:#FFEAF4; border-color:#FF0000; border-width:thick; border-style:solid; text-align:center;\"><p>" . $uploader->getErrors() . '</p></div>';
543
544
            return false;
545
        }
546
547
        return true;
548
    }
549
550
    /**
551
     * Resize a picture and save it to $path_upload
552
     *
553
     * @param  string $img         the path to the file
554
     * @param  string $path_upload The path to where the files should be saved after resizing
555
     * @param  int    $thumbwidth  the width in pixels that the thumbnail will have
556
     * @param  int    $thumbheight the height in pixels that the thumbnail will have
557
     * @param  int    $pictwidth   the width in pixels that the pic will have
558
     * @param  int    $pictheight  the height in pixels that the pic will have
559
     * @return nothing
0 ignored issues
show
Documentation introduced by
Should the return type not be nothing|null?

This check compares the return type specified in the @return annotation of a function or method doc comment with the types returned by the function and raises an issue if they mismatch.

Loading history...
560
     */
561
    public function resizeImage($img, $thumbwidth, $thumbheight, $pictwidth, $pictheight, $path_upload)
562
    {
563
        $img2   = $img;
564
        $path   = pathinfo($img);
565
        $img    = imagecreatefromjpeg($img);
566
        $xratio = $thumbwidth / imagesx($img);
567
        $yratio = $thumbheight / imagesy($img);
568 View Code Duplication
        if ($xratio < 1 || $yratio < 1) {
569
            if ($xratio < $yratio) {
570
                $resized = imagecreatetruecolor($thumbwidth, floor(imagesy($img) * $xratio));
571
            } else {
572
                $resized = imagecreatetruecolor(floor(imagesx($img) * $yratio), $thumbheight);
573
            }
574
            imagecopyresampled($resized, $img, 0, 0, 0, 0, imagesx($resized) + 1, imagesy($resized) + 1, imagesx($img), imagesy($img));
575
            imagejpeg($resized, $path_upload . '/thumbs/thumb_' . $path['basename']);
576
            imagedestroy($resized);
577
        } else {
578
            imagejpeg($img, $path_upload . '/thumbs/thumb_' . $path['basename']);
579
        }
580
        imagedestroy($img);
581
        $path2   = pathinfo($img2);
582
        $img2    = imagecreatefromjpeg($img2);
583
        $xratio2 = $pictwidth / imagesx($img2);
584
        $yratio2 = $pictheight / imagesy($img2);
585 View Code Duplication
        if ($xratio2 < 1 || $yratio2 < 1) {
586
            if ($xratio2 < $yratio2) {
587
                $resized2 = imagecreatetruecolor($pictwidth, floor(imagesy($img2) * $xratio2));
588
            } else {
589
                $resized2 = imagecreatetruecolor(floor(imagesx($img2) * $yratio2), $pictheight);
590
            }
591
            imagecopyresampled($resized2, $img2, 0, 0, 0, 0, imagesx($resized2) + 1, imagesy($resized2) + 1, imagesx($img2), imagesy($img2));
592
            imagejpeg($resized2, $path_upload . '/midsize/resized_' . $path2['basename']);
593
            imagedestroy($resized2);
594
        } else {
595
            imagejpeg($img2, $path_upload . '/midsize/resized_' . $path2['basename']);
596
        }
597
        imagedestroy($img2);
598
    }
599
}
600