Completed
Push — master ( 2a7c05...7c1d68 )
by Michael
02:50
created

AdslightPicturesHandler::resizeImage()   C

Complexity

Conditions 7
Paths 9

Size

Total Lines 38
Code Lines 32

Duplication

Lines 24
Ratio 63.16 %

Importance

Changes 0
Metric Value
cc 7
eloc 32
nc 9
nop 6
dl 24
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
require_once XOOPS_ROOT_PATH . '/class/uploader.php';
34
require_once XOOPS_ROOT_PATH . '/kernel/object.php';
35
require_once XOOPS_ROOT_PATH . '/class/xoopsformloader.php';
36
require_once XOOPS_ROOT_PATH . '/kernel/object.php';
37
require_once XOOPS_ROOT_PATH . '/modules/adslight/class/utility.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 AdslightPictures 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
    /**
50
     * @param null       $id
51
     * @param null|array $lid
52
     */
53
    public function __construct($id = null, $lid = null)
54
    {
55
        $this->db = XoopsDatabaseFactory::getDatabaseConnection();
56
        $this->initVar('cod_img', XOBJ_DTYPE_INT, null, false, 10);
57
        $this->initVar('title', XOBJ_DTYPE_TXTBOX, null, false);
58
        $this->initVar('date_added', XOBJ_DTYPE_TXTBOX, null, false);
59
        $this->initVar('date_modified', XOBJ_DTYPE_TXTBOX, null, false);
60
        $this->initVar('lid', XOBJ_DTYPE_INT, null, false, 10);
61
        $this->initVar('uid_owner', XOBJ_DTYPE_TXTBOX, null, false);
62
        $this->initVar('url', XOBJ_DTYPE_TXTBOX, null, false);
63
        if (!empty($lid)) {
64
            if (is_array($lid)) {
65
                $this->assignVars($lid);
66
            } else {
67
                $this->load((int)$lid);
68
            }
69
        } else {
70
            $this->setNew();
71
        }
72
    }
73
74
    /**
75
     * @param $id
76
     */
77
    public function load($id)
78
    {
79
        global $moduleDirName;
80
        $sql   = 'SELECT * FROM ' . $this->db->prefix('adslight_pictures') . ' WHERE cod_img=' . $id . '';
81
        $myrow = $this->db->fetchArray($this->db->query($sql));
82
        $this->assignVars($myrow);
83
        if (!$myrow) {
84
            $this->setNew();
85
        }
86
    }
87
88
    /**
89
     * @param array  $criteria
90
     * @param bool   $asobject
91
     * @param string $sort
92
     * @param string $order
0 ignored issues
show
Bug introduced by
There is no parameter named $order. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
93
     * @param int    $limit
94
     * @param int    $start
95
     *
96
     * @deprecated this should be handled through {@see AdslightPicturesHandler}
97
     * @return array
98
     */
99
    public function getAllPictures($criteria = array(), $asobject = false, $sort = 'cod_img', $cat_order = 'ASC', $limit = 0, $start = 0)
100
    {
101
        global $moduleDirName;
102
        $db          = XoopsDatabaseFactory::getDatabaseConnection();
103
        $ret         = array();
104
        $where_query = '';
105
        if (is_array($criteria) && count($criteria) > 0) {
106
            $where_query = ' WHERE';
107
            foreach ($criteria as $c) {
108
                $where_query .= " {$c} AND";
109
            }
110
            $where_query = substr($where_query, 0, -4);
111
        } elseif (!is_array($criteria) && $criteria) {
112
            $where_query = " WHERE {$criteria}";
113
        }
114
        if (!$asobject) {
115
            $sql    = 'SELECT cod_img FROM ' . $db->prefix('adslight_pictures') . "$where_query ORDER BY $sort $cat_order";
116
            $result = $db->query($sql, $limit, $start);
117
            while ($myrow = $db->fetchArray($result)) {
118
                $ret[] = $myrow['cog_img'];
119
            }
120
        } else {
121
            $sql    = 'SELECT * FROM ' . $db->prefix('adslight_pictures') . "$where_query ORDER BY $sort $cat_order";
122
            $result = $db->query($sql, $limit, $start);
123
            while ($myrow = $db->fetchArray($result)) {
124
                $ret[] = new AdslightPictures($myrow);
125
            }
126
        }
127
128
        return $ret;
129
    }
130
}
131
132
// -------------------------------------------------------------------------
133
// ------------------light_pictures user handler class -------------------
134
// -------------------------------------------------------------------------
135
136
/**
137
 * AdslightPicturesHandler class definition
138
 *
139
 * This class provides simple mechanism to manage {@see AdslightPictures} objects
140
 * and generate forms for inclusion
141
 *
142
 * @todo change this to a XoopsPersistableObjectHandler and remove
143
 *       'most' method overloads
144
 */
145
class AdslightPicturesHandler 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...
146
{
147
    /**
148
     * Class constructor
149
     * @param XoopsDatabase $db
150
     */
151
152
    public function __construct($db)
153
    {
154
        parent::__construct($db, 'adslight_pictures', 'AdslightPictures', 'cod_img', 'title');
155
    }
156
157
    /**
158
     * create a new light_pictures
159
     *
160
     * @param  bool $isNew flag the new objects as "new"?
161
     * @return XoopsObject light_pictures
162
     */
163
    public function create($isNew = true)
164
    {
165
        $adslightPictures = new AdslightPictures();
166
        if ($isNew) {
167
            $adslightPictures->setNew();
168
        } else {
169
            $adslightPictures->unsetNew();
170
        }
171
172
        return $adslightPictures;
173
    }
174
175
    /**
176
     * retrieve a light_pictures
177
     *
178
     * @param int $id of the light_pictures
179
     * @param     $lid
180
     *
181
     * @return mixed reference to the {@link light_pictures} object, FALSE if failed
182
     */
183
    public function get($id, $lid = null)
184
    {
185
        global $moduleDirName;
186
187
        $sql = 'SELECT * FROM ' . $this->db->prefix('adslight_pictures') . ' WHERE cod_img=' . $id . ' AND lid=' . $lid . '';
188
        if (!$result = $this->db->query($sql)) {
189
            return false;
190
        }
191
        $numrows = $this->db->getRowsNum($result);
192
        if ($numrows == 1) {
193
            $adslightPictures = new AdslightPictures();
194
            $adslightPictures->assignVars($this->db->fetchArray($result));
195
196
            return $adslightPictures;
197
        }
198
199
        return false;
200
    }
201
202
    /**
203
     * insert a new AdslightPicture object into the database
204
     *
205
     * @param XoopsObject $adslightPictures
206
     * @param bool        $force
207
     * @return bool FALSE if failed, TRUE if already present and unchanged or successful
208
     */
209
    public function insert(XoopsObject $adslightPictures, $force = false)
210
    {
211
        global $xoopsConfig, $lid, $moduleDirName;
212
        if (!$adslightPictures instanceof AdslightPictures) {
213
            return false;
214
        }
215
        if (!$adslightPictures->isDirty()) {
216
            return true;
217
        }
218
        if (!$adslightPictures->cleanVars()) {
219
            return false;
220
        }
221
        foreach ($adslightPictures->cleanVars as $k => $v) {
222
            ${$k} = $v;
223
        }
224
        $now = time();
225
        if ($adslightPictures->isNew()) {
226
            // add/modify of AdslightPictures
227
            $adslightPictures = new AdslightPictures();
228
229
            $format = 'INSERT INTO %s (cod_img, title, date_added, date_modified, lid, uid_owner, url)';
230
            $format .= 'VALUES (%u, %s, %s, %s, %s, %s, %s)';
231
            $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 $cod_img seems only to be defined at a later point. Did you maybe move this code here without moving the variable definition?

This error can happen if you refactor code and forget to move the variable initialization.

Let’s take a look at a simple example:

function someFunction() {
    $x = 5;
    echo $x;
}

The above code is perfectly fine. Now imagine that we re-order the statements:

function someFunction() {
    echo $x;
    $x = 5;
}

In that case, $x would be read before it is initialized. This was a very basic example, however the principle is the same for the found issue.

Loading history...
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...
232
                              $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...
233
            $force  = true;
234
        } else {
235
            $format = 'UPDATE %s SET ';
236
            $format .= 'cod_img=%u, title=%s, date_added=%s, date_modified=%s, lid=%s, uid_owner=%s, url=%s';
237
            $format .= ' WHERE cod_img = %u';
238
            $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 $cod_img seems only to be defined at a later point. Did you maybe move this code here without moving the variable definition?

This error can happen if you refactor code and forget to move the variable initialization.

Let’s take a look at a simple example:

function someFunction() {
    $x = 5;
    echo $x;
}

The above code is perfectly fine. Now imagine that we re-order the statements:

function someFunction() {
    echo $x;
    $x = 5;
}

In that case, $x would be read before it is initialized. This was a very basic example, however the principle is the same for the found issue.

Loading history...
239
                              $this->db->quoteString($url), $cod_img);
0 ignored issues
show
Bug introduced by
The variable $cod_img seems only to be defined at a later point. Did you maybe move this code here without moving the variable definition?

This error can happen if you refactor code and forget to move the variable initialization.

Let’s take a look at a simple example:

function someFunction() {
    $x = 5;
    echo $x;
}

The above code is perfectly fine. Now imagine that we re-order the statements:

function someFunction() {
    echo $x;
    $x = 5;
}

In that case, $x would be read before it is initialized. This was a very basic example, however the principle is the same for the found issue.

Loading history...
240
        }
241 View Code Duplication
        if (false !== $force) {
242
            $result = $this->db->queryF($sql);
243
        } else {
244
            $result = $this->db->query($sql);
245
        }
246
        if (!$result) {
247
            return false;
248
        }
249
        if (empty($cod_img)) {
0 ignored issues
show
Bug introduced by
The variable $cod_img seems only to be defined at a later point. As such the call to empty() seems to always evaluate to true.

This check marks calls to isset(...) or empty(...) that are found before the variable itself is defined. These will always have the same result.

This is likely the result of code being shifted around. Consider removing these calls.

Loading history...
250
            $cod_img = $this->db->getInsertId();
251
        }
252
        $adslightPictures->assignVars(array(
253
                                          'cod_img' => $cod_img,
254
                                          'lid'     => $lid,
255
                                          'url'     => $url
256
                                      ));
257
258
        return true;
259
    }
260
261
    /**
262
     * delete AdslightPictures object from the database
263
     *
264
     * @param  XoopsObject $adslightPictures reference to the AdslightPictures to delete
265
     * @param  bool        $force
266
     * @return bool        FALSE if failed.
267
     */
268
    public function delete(XoopsObject $adslightPictures, $force = false)
269
    {
270
        global $moduleDirName;
271
272
        if (!$adslightPictures instanceof AdslightPictures) {
273
            return false;
274
        }
275
        $sql = sprintf('DELETE FROM %s WHERE cod_img = %u', $this->db->prefix('adslight_pictures'), $adslightPictures->getVar('cod_img'));
276 View Code Duplication
        if (false !== $force) {
277
            $result = $this->db->queryF($sql);
278
        } else {
279
            $result = $this->db->query($sql);
280
        }
281
        if (!$result) {
282
            return false;
283
        }
284
285
        return true;
286
    }
287
288
    /**
289
     * retrieve AdslightPictures object(s) from the database
290
     *
291
     * @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...
292
     * @param  bool            $id_as_key use the UID as key for the array?
293
     * @return array  array of {@link AdslightPictures} objects
294
     */
295
    public function &getObjects(CriteriaElement $criteria = null, $id_as_key = false)
296
    {
297
        global $moduleDirName;
298
299
        $ret   = array();
300
        $limit = $start = 0;
301
        $sql   = 'SELECT * FROM ' . $this->db->prefix('adslight_pictures');
302
        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...
303
            $sql .= ' ' . $criteria->renderWhere();
304
            if ($criteria->getSort() != '') {
305
                $sql .= ' ORDER BY ' . $criteria->getSort() . ' ' . $criteria->getOrder();
306
            }
307
            $limit = $criteria->getLimit();
308
            $start = $criteria->getStart();
309
        }
310
        $result = $this->db->query($sql, $limit, $start);
311
        if (!$result) {
312
            return $ret;
313
        }
314
        while ($myrow = $this->db->fetchArray($result)) {
315
            $adslightPictures = new AdslightPictures();
316
            $adslightPictures->assignVars($myrow);
317
            if (!$id_as_key) {
318
                $ret[] = $adslightPictures;
319
            } else {
320
                $ret[$myrow['cod_img']] = $adslightPictures;
321
            }
322
            unset($adslightPictures);
323
        }
324
325
        return $ret;
326
    }
327
328
    /**
329
     * count AdslightPictures matching a condition
330
     *
331
     * @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...
332
     * @return int    count of AdslightPictures
333
     */
334
    public function getCount(CriteriaElement $criteria = null)
335
    {
336
        global $moduleDirName;
337
338
        $sql = 'SELECT COUNT(*) FROM ' . $this->db->prefix('adslight_pictures');
339
        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...
340
            $sql .= ' ' . $criteria->renderWhere();
341
        }
342
        $result = $this->db->query($sql);
343
        if (!$result) {
344
            return 0;
345
        }
346
        list($count) = $this->db->fetchRow($result);
347
348
        return $count;
349
    }
350
351
    /**
352
     * delete AdslightPictures matching a set of conditions
353
     *
354
     * @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...
355
     * @return bool   FALSE if deletion failed
356
     */
357
    public function deleteAll(CriteriaElement $criteria = null)
358
    {
359
        global $moduleDirName;
360
        $sql = 'DELETE FROM ' . $this->db->prefix('adslight_pictures');
361
        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...
362
            $sql .= ' ' . $criteria->renderWhere();
363
        }
364
        if (!$result = $this->db->query($sql)) {
365
            return false;
366
        }
367
368
        return true;
369
    }
370
371
    /**
372
     * Render a form to send pictures
373
     *
374
     * @param int      $uid
375
     * @param int      $lid
376
     * @param int      $maxbytes the maximum size of a picture
377
     * @param XoopsTpl $xoopsTpl the one in which the form will be rendered
378
     * @return bool   TRUE
379
     *
380
     * obs: Some functions wont work on php 4 so edit lines down under acording to your version
381
     */
382
    public function renderFormSubmit($uid, $lid, $maxbytes, $xoopsTpl)
383
    {
384
        global $moduleDirName, $main_lang;
385
        $uid        = (int)$uid;
386
        $lid        = (int)$lid;
387
        $form       = new XoopsThemeForm(_ADSLIGHT_SUBMIT_PIC_TITLE, 'form_picture', XOOPS_URL . "/modules/adslight/add_photo.php?lid={$lid}&uid=" . $xoopsUser->getVar('uid'), 'post', true);
0 ignored issues
show
Bug introduced by
The variable $xoopsUser 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...
388
        $field_url  = new XoopsFormFile(_ADSLIGHT_SELECT_PHOTO, 'sel_photo', 2000000);
389
        $field_desc = new XoopsFormText(_ADSLIGHT_CAPTION, 'caption', 35, 55);
390
391
        $form->setExtra('enctype="multipart/form-data"');
392
        $button_send   = new XoopsFormButton('', 'submit_button', _ADSLIGHT_UPLOADPICTURE, 'submit');
393
        $field_warning = new XoopsFormLabel(sprintf(_ADSLIGHT_YOUCANUPLOAD, $maxbytes / 1024));
394
        $field_lid     = new XoopsFormHidden('lid', $lid);
395
        $field_uid     = new XoopsFormHidden('uid', $uid);
396
        /**
397
         * Check if using Xoops or XoopsCube (by jlm69)
398
         */
399
        // XOOPS Cube 2.1x
400
        $xCube = preg_match('/^XOOPS Cube/', XOOPS_VERSION) ? true : false;
401
402
        /**
403
         * Verify Ticket (by jlm69)
404
         * If your site is XoopsCube it uses $xoopsGTicket for the token.
405
         * If your site is Xoops it uses xoopsSecurity for the token.
406
         */
407
408 View Code Duplication
        if ($xCube) {
409
            $GLOBALS['xoopsGTicket']->addTicketXoopsFormElement($form, __LINE__, 1800, 'token');
410
        } else {
411
            $field_token = $GLOBALS['xoopsSecurity']->getTokenHTML();
412
        }
413
        $form->addElement($field_warning);
414
        $form->addElement($field_url, true);
415
        $form->addElement($field_desc, true);
416
        $form->addElement($field_lid, true);
417
        $form->addElement($field_uid, true);
418
419
        $form->addElement($field_token, true);
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...
420
421
        $form->addElement($button_send);
422
        if (str_replace('.', '', PHP_VERSION) > 499) {
423
            $form->assign($xoopsTpl);
424
        } else {
425
            $form->display();
426
        }
427
428
        return true;
429
    }
430
431
    /**
432
     * Render a form to edit the description of the pictures
433
     *
434
     * @param  string $caption  The description of the picture
435
     * @param  int    $cod_img  the id of the image in database
436
     * @param  text   $filename the url to the thumb of the image so it can be displayed
437
     * @return bool   TRUE
438
     */
439
    public function renderFormEdit($caption, $cod_img, $filename)
440
    {
441
        global $moduleDirName, $main_lang;
442
443
        $form       = new XoopsThemeForm(_ADSLIGHT_EDIT_CAPTION, 'form_picture', 'editdesc.php', 'post', true);
444
        $field_desc = new XoopsFormText($caption, 'caption', 35, 55);
445
        $form->setExtra('enctype="multipart/form-data"');
446
        $button_send = new XoopsFormButton(_ADSLIGHT_EDIT, 'submit_button', _SUBMIT, 'submit');
447
        //@todo - replace alt with language string
448
        $field_warning = new XoopsFormLabel("<img src='{$filename}' alt='sssss'>");
449
        $field_cod_img = new XoopsFormHidden('cod_img', $cod_img);
450
        //    $field_lid = new XoopsFormHidden('lid', $lid);
0 ignored issues
show
Unused Code Comprehensibility introduced by
54% 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...
451
        $field_marker = new XoopsFormHidden('marker', 1);
452
453
        /**
454
         * Check if using Xoops or XoopsCube (by jlm69)
455
         * Right now Xoops does not have a directory called preload, Xoops Cube does.
456
         * If this finds a diectory called preload in the Xoops Root folder $xCube=true.
457
         * This could change if Xoops adds a Directory called preload
458
         */
459
460
        $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...
461
        $preload = XOOPS_ROOT_PATH . '/preload';
462
        if (is_dir($preload)) {
463
            $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...
464
        }
465
466
        /**
467
         * Verify Ticket (by jlm69)
468
         * If your site is XoopsCube it uses $xoopsGTicket for the token.
469
         * If your site is Xoops it uses xoopsSecurity for the token.
470
         */
471
472 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...
473
            $GLOBALS['xoopsGTicket']->addTicketXoopsFormElement($form, __LINE__, 1800, 'token');
474
        } else {
475
            $field_token = $GLOBALS['xoopsSecurity']->getTokenHTML();
476
        }
477
478
        $form->addElement($field_warning);
479
        $form->addElement($field_desc);
480
        $form->addElement($field_cod_img);
481
        $form->addElement($field_marker);
482
        $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...
483
        $form->addElement($button_send);
484
        $form->display();
485
486
        return true;
487
    }
488
489
    /**
490
     * Upload the file and Save into database
491
     *
492
     * @param  text $title         A litle description of the file
493
     * @param  text $path_upload   The path to where the file should be uploaded
494
     * @param  int  $thumbwidth    the width in pixels that the thumbnail will have
495
     * @param  int  $thumbheight   the height in pixels that the thumbnail will have
496
     * @param  int  $pictwidth     the width in pixels that the pic will have
497
     * @param  int  $pictheight    the height in pixels that the pic will have
498
     * @param  int  $maxfilebytes  the maximum size a file can have to be uploaded in bytes
499
     * @param  int  $maxfilewidth  the maximum width in pixels that a pic can have
500
     * @param  int  $maxfileheight the maximum height in pixels that a pic can have
501
     * @return bool FALSE if upload fails or database fails
502
     */
503
    public function receivePicture($title, $path_upload, $thumbwidth, $thumbheight, $pictwidth, $pictheight, $maxfilebytes, $maxfilewidth, $maxfileheight)
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...
504
    {
505
        global $xoopsDB, $lid;
506
        //busca id do user logado
507
        $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...
508
        $lid = Request::getInt('lid', 0, 'POST');
509
        //create a hash so it does not erase another file
510
        $hash1 = time();
511
        $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...
512
        // mimetypes and settings put this in admin part later
513
        $allowed_mimetypes = array(
514
            'image/jpeg',
515
            'image/gif'
516
        );
517
        $maxfilesize       = $maxfilebytes;
518
        // create the object to upload
519
        $uploader = new XoopsMediaUploader($path_upload, $allowed_mimetypes, $maxfilesize, $maxfilewidth, $maxfileheight);
520
        // fetch the media
521
        if ($uploader->fetchMedia($_POST['xoops_upload_file'][0])) {
522
            //lets create a name for it
523
            $uploader->setPrefix("pic_{$lid}_");
524
            //now let s upload the file
525
            if (!$uploader->upload()) {
526
                // if there are errors lets return them
527
                echo "<div style=\"color:#FF0000; background-color:#FFEAF4; border-color:#FF0000; border-width:thick; border-style:solid; text-align:center;\"><p>"
528
                     . $uploader->getErrors()
529
                     . '</p></div>';
530
531
                return false;
532
            } else {
533
                // now let s create a new object picture and set its variables
534
                $picture = $this->create();
535
                $url     = $uploader->getSavedFileName();
536
                $picture->setVar('url', $url);
537
                $picture->setVar('title', $title);
538
                $uid = $GLOBALS['xoopsUser']->getVar('uid');
539
                $lid = (int)$lid;
540
                $picture->setVar('lid', $lid);
541
                $picture->setVar('uid_owner', $uid);
542
                $this->insert($picture);
543
                $saved_destination = $uploader->getSavedDestination();
544
                $this->resizeImage($saved_destination, $thumbwidth, $thumbheight, $pictwidth, $pictheight, $path_upload);
545
            }
546
        } else {
547
            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>';
548
549
            return false;
550
        }
551
552
        return true;
553
    }
554
555
    /**
556
     * Resize a picture and save it to $path_upload
557
     *
558
     * @param  string $img         the path to the file
559
     * @param  string $path_upload The path to where the files should be saved after resizing
560
     * @param  int    $thumbwidth  the width in pixels that the thumbnail will have
561
     * @param  int    $thumbheight the height in pixels that the thumbnail will have
562
     * @param  int    $pictwidth   the width in pixels that the pic will have
563
     * @param  int    $pictheight  the height in pixels that the pic will have
564
     * @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...
565
     */
566
    public function resizeImage($img, $thumbwidth, $thumbheight, $pictwidth, $pictheight, $path_upload)
567
    {
568
        $img2   = $img;
569
        $path   = pathinfo($img);
570
        $img    = imagecreatefromjpeg($img);
571
        $xratio = $thumbwidth / imagesx($img);
572
        $yratio = $thumbheight / imagesy($img);
573 View Code Duplication
        if ($xratio < 1 || $yratio < 1) {
574
            if ($xratio < $yratio) {
575
                $resized = imagecreatetruecolor($thumbwidth, floor(imagesy($img) * $xratio));
576
            } else {
577
                $resized = imagecreatetruecolor(floor(imagesx($img) * $yratio), $thumbheight);
578
            }
579
            imagecopyresampled($resized, $img, 0, 0, 0, 0, imagesx($resized) + 1, imagesy($resized) + 1, imagesx($img), imagesy($img));
580
            imagejpeg($resized, "{$path_upload}/thumbs/thumb_{$path['basename']}");
581
            imagedestroy($resized);
582
        } else {
583
            imagejpeg($img, "{$path_upload}/thumbs/thumb_{$path['basename']}");
584
        }
585
        imagedestroy($img);
586
        $path2   = pathinfo($img2);
587
        $img2    = imagecreatefromjpeg($img2);
588
        $xratio2 = $pictwidth / imagesx($img2);
589
        $yratio2 = $pictheight / imagesy($img2);
590 View Code Duplication
        if ($xratio2 < 1 || $yratio2 < 1) {
591
            if ($xratio2 < $yratio2) {
592
                $resized2 = imagecreatetruecolor($pictwidth, floor(imagesy($img2) * $xratio2));
593
            } else {
594
                $resized2 = imagecreatetruecolor(floor(imagesx($img2) * $yratio2), $pictheight);
595
            }
596
            imagecopyresampled($resized2, $img2, 0, 0, 0, 0, imagesx($resized2) + 1, imagesy($resized2) + 1, imagesx($img2), imagesy($img2));
597
            imagejpeg($resized2, "{$path_upload}/midsize/resized_{$path2['basename']}");
598
            imagedestroy($resized2);
599
        } else {
600
            imagejpeg($img2, "{$path_upload}/midsize/resized_{$path2['basename']}");
601
        }
602
        imagedestroy($img2);
603
    }
604
}
605