Completed
Push — master ( deac0a...054aa6 )
by Michael
01:55
created

AdslightPicturesHandler::renderFormEdit()   B

Complexity

Conditions 1
Paths 1

Size

Total Lines 28
Code Lines 18

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 18
nc 1
nop 3
dl 0
loc 28
rs 8.8571
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 $cat_order
93
     * @param int    $limit
94
     * @param int    $start
95
     * @return array
96
     * @internal   param string $order
97
     * @deprecated this should be handled through {@see AdslightPicturesHandler}
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 'most' method overloads
143
 */
144
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...
145
{
146
    /**
147
     * Class constructor
148
     * @param XoopsDatabase $db
149
     */
150
151
    public function __construct($db)
152
    {
153
        parent::__construct($db, 'adslight_pictures', 'AdslightPictures', 'cod_img', 'title');
154
    }
155
156
    /**
157
     * create a new light_pictures
158
     *
159
     * @param  bool $isNew flag the new objects as "new"?
160
     * @return XoopsObject light_pictures
161
     */
162
    public function create($isNew = true)
163
    {
164
        $adslightPictures = new AdslightPictures();
165
        if ($isNew) {
166
            $adslightPictures->setNew();
167
        } else {
168
            $adslightPictures->unsetNew();
169
        }
170
171
        return $adslightPictures;
172
    }
173
174
    /**
175
     * retrieve a light_pictures
176
     *
177
     * @param int $id of the light_pictures
178
     * @param     $lid
179
     *
180
     * @return mixed reference to the {@link light_pictures} object, FALSE if failed
181
     */
182
    public function get($id, $lid = null)
183
    {
184
        global $moduleDirName;
185
186
        $sql = 'SELECT * FROM ' . $this->db->prefix('adslight_pictures') . ' WHERE cod_img=' . $id . ' AND lid=' . $lid . '';
187
        if (!$result = $this->db->query($sql)) {
188
            return false;
189
        }
190
        $numrows = $this->db->getRowsNum($result);
191
        if ($numrows == 1) {
192
            $adslightPictures = new AdslightPictures();
193
            $adslightPictures->assignVars($this->db->fetchArray($result));
194
195
            return $adslightPictures;
196
        }
197
198
        return false;
199
    }
200
201
    /**
202
     * insert a new AdslightPicture object into the database
203
     *
204
     * @param XoopsObject $adslightPictures
205
     * @param bool        $force
206
     * @return bool FALSE if failed, TRUE if already present and unchanged or successful
207
     */
208
    public function insert(XoopsObject $adslightPictures, $force = false)
209
    {
210
        global $xoopsConfig, $lid, $moduleDirName;
211
        if (!$adslightPictures instanceof AdslightPictures) {
212
            return false;
213
        }
214
        if (!$adslightPictures->isDirty()) {
215
            return true;
216
        }
217
        if (!$adslightPictures->cleanVars()) {
218
            return false;
219
        }
220
        foreach ($adslightPictures->cleanVars as $k => $v) {
221
            ${$k} = $v;
222
        }
223
        $now = time();
224
        if ($adslightPictures->isNew()) {
225
            // add/modify of AdslightPictures
226
            $adslightPictures = new AdslightPictures();
227
228
            $format = 'INSERT INTO %s (cod_img, title, date_added, date_modified, lid, uid_owner, url)';
229
            $format .= 'VALUES (%u, %s, %s, %s, %s, %s, %s)';
230
            $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...
231
                              $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...
232
            $force  = true;
233
        } else {
234
            $format = 'UPDATE %s SET ';
235
            $format .= 'cod_img=%u, title=%s, date_added=%s, date_modified=%s, lid=%s, uid_owner=%s, url=%s';
236
            $format .= ' WHERE cod_img = %u';
237
            $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...
238
                              $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...
239
        }
240 View Code Duplication
        if (false !== $force) {
241
            $result = $this->db->queryF($sql);
242
        } else {
243
            $result = $this->db->query($sql);
244
        }
245
        if (!$result) {
246
            return false;
247
        }
248
        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...
249
            $cod_img = $this->db->getInsertId();
250
        }
251
        $adslightPictures->assignVars(array(
252
                                          'cod_img' => $cod_img,
253
                                          'lid'     => $lid,
254
                                          'url'     => $url
255
                                      ));
256
257
        return true;
258
    }
259
260
    /**
261
     * delete AdslightPictures object from the database
262
     *
263
     * @param  XoopsObject $adslightPictures reference to the AdslightPictures to delete
264
     * @param  bool        $force
265
     * @return bool        FALSE if failed.
266
     */
267
    public function delete(XoopsObject $adslightPictures, $force = false)
268
    {
269
        global $moduleDirName;
270
271
        if (!$adslightPictures instanceof AdslightPictures) {
272
            return false;
273
        }
274
        $sql = sprintf('DELETE FROM %s WHERE cod_img = %u', $this->db->prefix('adslight_pictures'), $adslightPictures->getVar('cod_img'));
275 View Code Duplication
        if (false !== $force) {
276
            $result = $this->db->queryF($sql);
277
        } else {
278
            $result = $this->db->query($sql);
279
        }
280
        if (!$result) {
281
            return false;
282
        }
283
284
        return true;
285
    }
286
287
    /**
288
     * retrieve AdslightPictures object(s) from the database
289
     *
290
     * @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...
291
     * @param  bool            $id_as_key use the UID as key for the array?
292
     * @return array  array of {@link AdslightPictures} objects
293
     */
294
    public function &getObjects(CriteriaElement $criteria = null, $id_as_key = false)
295
    {
296
        global $moduleDirName;
297
298
        $ret   = array();
299
        $limit = $start = 0;
300
        $sql   = 'SELECT * FROM ' . $this->db->prefix('adslight_pictures');
301
        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...
302
            $sql .= ' ' . $criteria->renderWhere();
303
            if ($criteria->getSort() != '') {
304
                $sql .= ' ORDER BY ' . $criteria->getSort() . ' ' . $criteria->getOrder();
305
            }
306
            $limit = $criteria->getLimit();
307
            $start = $criteria->getStart();
308
        }
309
        $result = $this->db->query($sql, $limit, $start);
310
        if (!$result) {
311
            return $ret;
312
        }
313
        while ($myrow = $this->db->fetchArray($result)) {
314
            $adslightPictures = new AdslightPictures();
315
            $adslightPictures->assignVars($myrow);
316
            if (!$id_as_key) {
317
                $ret[] = $adslightPictures;
318
            } else {
319
                $ret[$myrow['cod_img']] = $adslightPictures;
320
            }
321
            unset($adslightPictures);
322
        }
323
324
        return $ret;
325
    }
326
327
    /**
328
     * count AdslightPictures matching a condition
329
     *
330
     * @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...
331
     * @return int    count of AdslightPictures
332
     */
333
    public function getCount(CriteriaElement $criteria = null)
334
    {
335
        global $moduleDirName;
336
337
        $sql = 'SELECT COUNT(*) FROM ' . $this->db->prefix('adslight_pictures');
338
        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...
339
            $sql .= ' ' . $criteria->renderWhere();
340
        }
341
        $result = $this->db->query($sql);
342
        if (!$result) {
343
            return 0;
344
        }
345
        list($count) = $this->db->fetchRow($result);
346
347
        return $count;
348
    }
349
350
    /**
351
     * delete AdslightPictures matching a set of conditions
352
     *
353
     * @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...
354
     * @return bool   FALSE if deletion failed
355
     */
356
    public function deleteAll(CriteriaElement $criteria = null)
357
    {
358
        global $moduleDirName;
359
        $sql = 'DELETE FROM ' . $this->db->prefix('adslight_pictures');
360
        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...
361
            $sql .= ' ' . $criteria->renderWhere();
362
        }
363
        if (!$result = $this->db->query($sql)) {
364
            return false;
365
        }
366
367
        return true;
368
    }
369
370
    /**
371
     * Render a form to send pictures
372
     *
373
     * @param int      $uid
374
     * @param int      $lid
375
     * @param int      $maxbytes the maximum size of a picture
376
     * @param XoopsTpl $xoopsTpl the one in which the form will be rendered
377
     * @return bool   TRUE
378
     *
379
     * obs: Some functions wont work on php 4 so edit lines down under acording to your version
380
     */
381
    public function renderFormSubmit($uid, $lid, $maxbytes, $xoopsTpl)
382
    {
383
        global $moduleDirName, $main_lang;
384
        $uid        = (int)$uid;
385
        $lid        = (int)$lid;
386
        $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...
387
        $field_url  = new XoopsFormFile(_ADSLIGHT_SELECT_PHOTO, 'sel_photo', 2000000);
388
        $field_desc = new XoopsFormText(_ADSLIGHT_CAPTION, 'caption', 35, 55);
389
390
        $form->setExtra('enctype="multipart/form-data"');
391
        $button_send   = new XoopsFormButton('', 'submit_button', _ADSLIGHT_UPLOADPICTURE, 'submit');
392
        $field_warning = new XoopsFormLabel(sprintf(_ADSLIGHT_YOUCANUPLOAD, $maxbytes / 1024));
393
        $field_lid     = new XoopsFormHidden('lid', $lid);
394
        $field_uid     = new XoopsFormHidden('uid', $uid);
395
396
        $field_token = $GLOBALS['xoopsSecurity']->getTokenHTML();
397
398
        $form->addElement($field_warning);
399
        $form->addElement($field_url, true);
400
        $form->addElement($field_desc, true);
401
        $form->addElement($field_lid, true);
402
        $form->addElement($field_uid, true);
403
404
        $form->addElement($field_token, true);
405
406
        $form->addElement($button_send);
407
        if (str_replace('.', '', PHP_VERSION) > 499) {
408
            $form->assign($xoopsTpl);
409
        } else {
410
            $form->display();
411
        }
412
413
        return true;
414
    }
415
416
    /**
417
     * Render a form to edit the description of the pictures
418
     *
419
     * @param  string $caption  The description of the picture
420
     * @param  int    $cod_img  the id of the image in database
421
     * @param  text   $filename the url to the thumb of the image so it can be displayed
422
     * @return bool   TRUE
423
     */
424
    public function renderFormEdit($caption, $cod_img, $filename)
425
    {
426
        global $moduleDirName, $main_lang;
427
428
        $form       = new XoopsThemeForm(_ADSLIGHT_EDIT_CAPTION, 'form_picture', 'editdesc.php', 'post', true);
429
        $field_desc = new XoopsFormText($caption, 'caption', 35, 55);
430
        $form->setExtra('enctype="multipart/form-data"');
431
        $button_send = new XoopsFormButton(_ADSLIGHT_EDIT, 'submit_button', _SUBMIT, 'submit');
432
        //@todo - replace alt with language string
433
        $field_warning = new XoopsFormLabel("<img src='{$filename}' alt='sssss'>");
434
        $field_cod_img = new XoopsFormHidden('cod_img', $cod_img);
435
        //    $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...
436
        $field_marker = new XoopsFormHidden('marker', 1);
437
438
439
        $field_token = $GLOBALS['xoopsSecurity']->getTokenHTML();
440
441
442
        $form->addElement($field_warning);
443
        $form->addElement($field_desc);
444
        $form->addElement($field_cod_img);
445
        $form->addElement($field_marker);
446
        $form->addElement($field_token);
447
        $form->addElement($button_send);
448
        $form->display();
449
450
        return true;
451
    }
452
453
    /**
454
     * Upload the file and Save into database
455
     *
456
     * @param  text $title         A litle description of the file
457
     * @param  text $path_upload   The path to where the file should be uploaded
458
     * @param  int  $thumbwidth    the width in pixels that the thumbnail will have
459
     * @param  int  $thumbheight   the height in pixels that the thumbnail will have
460
     * @param  int  $pictwidth     the width in pixels that the pic will have
461
     * @param  int  $pictheight    the height in pixels that the pic will have
462
     * @param  int  $maxfilebytes  the maximum size a file can have to be uploaded in bytes
463
     * @param  int  $maxfilewidth  the maximum width in pixels that a pic can have
464
     * @param  int  $maxfileheight the maximum height in pixels that a pic can have
465
     * @return bool FALSE if upload fails or database fails
466
     */
467
    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...
468
    {
469
        global $xoopsDB, $lid;
470
        //busca id do user logado
471
        $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...
472
        $lid = Request::getInt('lid', 0, 'POST');
473
        //create a hash so it does not erase another file
474
        $hash1 = time();
475
        $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...
476
        // mimetypes and settings put this in admin part later
477
        $allowed_mimetypes = array(
478
            'image/jpeg',
479
            'image/gif'
480
        );
481
        $maxfilesize       = $maxfilebytes;
482
        // create the object to upload
483
        $uploader = new XoopsMediaUploader($path_upload, $allowed_mimetypes, $maxfilesize, $maxfilewidth, $maxfileheight);
484
        // fetch the media
485
        if ($uploader->fetchMedia($_POST['xoops_upload_file'][0])) {
486
            //lets create a name for it
487
            $uploader->setPrefix("pic_{$lid}_");
488
            //now let s upload the file
489
            if (!$uploader->upload()) {
490
                // if there are errors lets return them
491
                echo '<div style="color:#FF0000; background-color:#FFEAF4; border-color:#FF0000; border-width:thick; border-style:solid; text-align:center;"><p>'
492
                     . $uploader->getErrors()
493
                     . '</p></div>';
494
495
                return false;
496
            } else {
497
                // now let s create a new object picture and set its variables
498
                $picture = $this->create();
499
                $url     = $uploader->getSavedFileName();
500
                $picture->setVar('url', $url);
501
                $picture->setVar('title', $title);
502
                $uid = $GLOBALS['xoopsUser']->getVar('uid');
503
                $lid = (int)$lid;
504
                $picture->setVar('lid', $lid);
505
                $picture->setVar('uid_owner', $uid);
506
                $this->insert($picture);
507
                $saved_destination = $uploader->getSavedDestination();
508
                $this->resizeImage($saved_destination, $thumbwidth, $thumbheight, $pictwidth, $pictheight, $path_upload);
509
            }
510
        } else {
511
            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>';
512
513
            return false;
514
        }
515
516
        return true;
517
    }
518
519
    /**
520
     * Resize a picture and save it to $path_upload
521
     *
522
     * @param  string $img         the path to the file
523
     * @param  string $path_upload The path to where the files should be saved after resizing
524
     * @param  int    $thumbwidth  the width in pixels that the thumbnail will have
525
     * @param  int    $thumbheight the height in pixels that the thumbnail will have
526
     * @param  int    $pictwidth   the width in pixels that the pic will have
527
     * @param  int    $pictheight  the height in pixels that the pic will have
528
     * @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...
529
     */
530
    public function resizeImage($img, $thumbwidth, $thumbheight, $pictwidth, $pictheight, $path_upload)
531
    {
532
        $img2   = $img;
533
        $path   = pathinfo($img);
534
        $img    = imagecreatefromjpeg($img);
535
        $xratio = $thumbwidth / imagesx($img);
536
        $yratio = $thumbheight / imagesy($img);
537 View Code Duplication
        if ($xratio < 1 || $yratio < 1) {
538
            if ($xratio < $yratio) {
539
                $resized = imagecreatetruecolor($thumbwidth, floor(imagesy($img) * $xratio));
540
            } else {
541
                $resized = imagecreatetruecolor(floor(imagesx($img) * $yratio), $thumbheight);
542
            }
543
            imagecopyresampled($resized, $img, 0, 0, 0, 0, imagesx($resized) + 1, imagesy($resized) + 1, imagesx($img), imagesy($img));
544
            imagejpeg($resized, "{$path_upload}/thumbs/thumb_{$path['basename']}");
545
            imagedestroy($resized);
546
        } else {
547
            imagejpeg($img, "{$path_upload}/thumbs/thumb_{$path['basename']}");
548
        }
549
        imagedestroy($img);
550
        $path2   = pathinfo($img2);
551
        $img2    = imagecreatefromjpeg($img2);
552
        $xratio2 = $pictwidth / imagesx($img2);
553
        $yratio2 = $pictheight / imagesy($img2);
554 View Code Duplication
        if ($xratio2 < 1 || $yratio2 < 1) {
555
            if ($xratio2 < $yratio2) {
556
                $resized2 = imagecreatetruecolor($pictwidth, floor(imagesy($img2) * $xratio2));
557
            } else {
558
                $resized2 = imagecreatetruecolor(floor(imagesx($img2) * $yratio2), $pictheight);
559
            }
560
            imagecopyresampled($resized2, $img2, 0, 0, 0, 0, imagesx($resized2) + 1, imagesy($resized2) + 1, imagesx($img2), imagesy($img2));
561
            imagejpeg($resized2, "{$path_upload}/midsize/resized_{$path2['basename']}");
562
            imagedestroy($resized2);
563
        } else {
564
            imagejpeg($img2, "{$path_upload}/midsize/resized_{$path2['basename']}");
565
        }
566
        imagedestroy($img2);
567
    }
568
}
569