Passed
Push — master ( 0405fd...a3f27c )
by Michael
02:30
created

class/PicturesHandler.php (1 issue)

1
<?php
2
3
namespace XoopsModules\Adslight;
4
5
/*
6
-------------------------------------------------------------------------
7
                     ADSLIGHT 2 : Module for Xoops
8
9
        Redesigned and ameliorate By Luc Bizet user at www.frxoops.org
10
        Started with the Classifieds module and made MANY changes
11
        Website : http://www.luc-bizet.fr
12
        Contact : [email protected]
13
-------------------------------------------------------------------------
14
             Original credits below Version History
15
##########################################################################
16
#                    Classified Module for Xoops                         #
17
#  By John Mordo user jlm69 at www.xoops.org and www.jlmzone.com         #
18
#      Started with the MyAds module and made MANY changes               #
19
##########################################################################
20
 Original Author: Pascal Le Boustouller
21
 Author Website : [email protected]
22
 Licence Type   : GPL
23
-------------------------------------------------------------------------
24
*/
25
26
use Xmf\Request;
27
use XoopsModules\Adslight;
28
29
/**
30
 * Protection against inclusion outside the site
31
 */
32
// defined('XOOPS_ROOT_PATH') || die('Restricted access');
33
34
/**
35
 * Includes of form objects and uploader
36
 */
37
require_once XOOPS_ROOT_PATH . '/class/uploader.php';
38
require_once XOOPS_ROOT_PATH . '/kernel/object.php';
39
require_once XOOPS_ROOT_PATH . '/class/xoopsformloader.php';
40
require_once XOOPS_ROOT_PATH . '/kernel/object.php';
41
42
// -------------------------------------------------------------------------
43
// ------------------light_pictures user handler class -------------------
44
// -------------------------------------------------------------------------
45
46
/**
47
 * PicturesHandler class definition
48
 *
49
 * This class provides simple mechanism to manage {@see Pictures} objects
50
 * and generate forms for inclusion
51
 *
52
 * @todo change this to a XoopsPersistableObjectHandler and remove 'most' method overloads
53
 */
54
class PicturesHandler extends \XoopsObjectHandler
55
{
56
    /**
57
     * Class constructor
58
     * @param \XoopsDatabase|null $db
59
     */
60
    public function __construct($db)
61
    {
62
        parent::__construct($db, 'adslight_pictures', Pictures::class, 'cod_img', 'title');
63
    }
64
65
    /**
66
     * create a new light_pictures
67
     *
68
     * @param bool $isNew flag the new objects as "new"?
69
     * @return \XoopsObject light_pictures
70
     */
71
    public function create($isNew = true)
72
    {
73
        $adslightPictures = new Adslight\Pictures();
74
        if ($isNew) {
75
            $adslightPictures->setNew();
76
        } else {
77
            $adslightPictures->unsetNew();
78
        }
79
80
        return $adslightPictures;
81
    }
82
83
    /**
84
     * retrieve a light_pictures
85
     *
86
     * @param int $id of the light_pictures
87
     * @param     $lid
88
     *
89
     * @return mixed reference to the {@link light_pictures} object, FALSE if failed
90
     */
91
    public function get($id, $lid = null)
92
    {
93
        $sql = 'SELECT * FROM ' . $this->db->prefix('adslight_pictures') . ' WHERE cod_img=' . $id . ' AND lid=' . $lid . ' ';
94
        if (!$result = $this->db->query($sql)) {
95
            return false;
96
        }
97
        $numrows = $this->db->getRowsNum($result);
98
        if (1 == $numrows) {
99
            $adslightPictures = new Adslight\Pictures();
100
            $adslightPictures->assignVars($this->db->fetchArray($result));
101
102
            return $adslightPictures;
103
        }
104
105
        return false;
106
    }
107
108
    /**
109
     * insert a new AdslightPicture object into the database
110
     *
111
     * @param \XoopsObject $adslightPictures
112
     * @param bool         $force
113
     * @return bool FALSE if failed, TRUE if already present and unchanged or successful
114
     */
115
    public function insert(\XoopsObject $adslightPictures, $force = false)
116
    {
117
        global $lid;
118
        if (!$adslightPictures instanceof Pictures) {
119
            return false;
120
        }
121
        if (!$adslightPictures->isDirty()) {
122
            return true;
123
        }
124
        if (!$adslightPictures->cleanVars()) {
125
            return false;
126
        }
127
        foreach ($adslightPictures->cleanVars as $k => $v) {
128
            ${$k} = $v;
129
        }
130
        $now = time();
131
        if ($adslightPictures->isNew()) {
132
            // add/modify of Pictures
133
            $adslightPictures = new Adslight\Pictures();
134
135
            $format = 'INSERT INTO `%s` (cod_img, title, date_added, date_modified, lid, uid_owner, url)';
136
            $format .= 'VALUES (%u, %s, %s, %s, %s, %s, %s)';
137
            $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), $this->db->quoteString($url));
138
            $force  = true;
139
        } else {
140
            $format = 'UPDATE `%s` SET ';
141
            $format .= 'cod_img=%u, title=%s, date_added=%s, date_modified=%s, lid=%s, uid_owner=%s, url=%s';
142
            $format .= ' WHERE cod_img = %u';
143
            $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), $this->db->quoteString($url), $cod_img);
144
        }
145
        if (false !== $force) {
146
            $result = $this->db->queryF($sql);
147
        } else {
148
            $result = $this->db->query($sql);
149
        }
150
        if (!$result) {
151
            return false;
152
        }
153
        if (empty($cod_img)) {
154
            $cod_img = $this->db->getInsertId();
155
        }
156
        $adslightPictures->assignVars([
157
                                          'cod_img' => $cod_img,
158
                                          'lid'     => $lid,
159
                                          'url'     => $url,
160
                                      ]);
161
162
        return true;
163
    }
164
165
    /**
166
     * delete Pictures object from the database
167
     *
168
     * @param \XoopsObject $adslightPictures reference to the Pictures to delete
169
     * @param bool         $force
170
     * @return bool        FALSE if failed.
171
     */
172
    public function delete(\XoopsObject $adslightPictures, $force = false)
173
    {
174
        if (!$adslightPictures instanceof Pictures) {
175
            return false;
176
        }
177
        $sql = sprintf('DELETE FROM `%s` WHERE cod_img = %u', $this->db->prefix('adslight_pictures'), $adslightPictures->getVar('cod_img'));
178
        if (false !== $force) {
179
            $result = $this->db->queryF($sql);
180
        } else {
181
            $result = $this->db->query($sql);
182
        }
183
        if (!$result) {
184
            return false;
185
        }
186
187
        return true;
188
    }
189
190
    /**
191
     * retrieve Pictures object(s) from the database
192
     *
193
     * @param \CriteriaElement|\CriteriaCompo $criteria  {@link \CriteriaElement} conditions to be met
194
     * @param bool                            $id_as_key use the UID as key for the array?
195
     * @return array  array of {@link Pictures} objects
196
     */
197
    public function &getObjects(\CriteriaElement $criteria = null, $id_as_key = false)
198
    {
199
        $ret   = [];
200
        $limit = $start = 0;
201
        $sql   = 'SELECT * FROM ' . $this->db->prefix('adslight_pictures');
202
        if (isset($criteria) && $criteria instanceof \CriteriaElement) {
203
            $sql .= ' ' . $criteria->renderWhere();
204
            if ('' != $criteria->getSort()) {
205
                $sql .= ' ORDER BY ' . $criteria->getSort() . ' ' . $criteria->getOrder();
206
            }
207
            $limit = $criteria->getLimit();
208
            $start = $criteria->getStart();
209
        }
210
        $result = $this->db->query($sql, $limit, $start);
211
        if (!$result) {
212
            return $ret;
213
        }
214
        while (false !== ($myrow = $this->db->fetchArray($result))) {
215
            $adslightPictures = new Adslight\Pictures();
216
            $adslightPictures->assignVars($myrow);
217
            if (!$id_as_key) {
218
                $ret[] = $adslightPictures;
219
            } else {
220
                $ret[$myrow['cod_img']] = $adslightPictures;
221
            }
222
            unset($adslightPictures);
223
        }
224
225
        return $ret;
226
    }
227
228
    /**
229
     * count Pictures matching a condition
230
     *
231
     * @param \CriteriaElement|\CriteriaCompo $criteria {@link \CriteriaElement} to match
232
     * @return int    count of Pictures
233
     */
234
    public function getCount(\CriteriaElement $criteria = null)
235
    {
236
        $sql = 'SELECT COUNT(*) FROM ' . $this->db->prefix('adslight_pictures');
237
        if (isset($criteria) && $criteria instanceof \CriteriaElement) {
238
            $sql .= ' ' . $criteria->renderWhere();
239
        }
240
        $result = $this->db->query($sql);
241
        if (!$result) {
242
            return 0;
243
        }
244
        list($count) = $this->db->fetchRow($result);
245
246
        return $count;
247
    }
248
249
    /**
250
     * delete Pictures matching a set of conditions
251
     *
252
     * @param \CriteriaElement|\CriteriaCompo $criteria {@link \CriteriaElement}
253
     * @return bool   FALSE if deletion failed
254
     */
255
    public function deleteAll(\CriteriaElement $criteria = null)
256
    {
257
        $sql = 'DELETE FROM ' . $this->db->prefix('adslight_pictures');
258
        if (isset($criteria) && $criteria instanceof \CriteriaElement) {
259
            $sql .= ' ' . $criteria->renderWhere();
260
        }
261
        if (!$result = $this->db->query($sql)) {
262
            return false;
263
        }
264
265
        return true;
266
    }
267
268
    /**
269
     * Render a form to send pictures
270
     *
271
     * @param int       $uid
272
     * @param int       $lid
273
     * @param int       $maxbytes the maximum size of a picture
274
     * @param \XoopsTpl $xoopsTpl the one in which the form will be rendered
275
     * @return bool   TRUE
276
     *
277
     * obs: Some functions wont work on php 4 so edit lines down under acording to your version
278
     */
279
    public function renderFormSubmit($uid, $lid, $maxbytes, $xoopsTpl)
280
    {
281
        $uid        = (int)$uid;
282
        $lid        = (int)$lid;
283
        $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
Comprehensibility Best Practice introduced by
The variable $xoopsUser seems to be never defined.
Loading history...
284
        $field_url  = new \XoopsFormFile(_ADSLIGHT_SELECT_PHOTO, 'sel_photo', 2000000);
285
        $field_desc = new \XoopsFormText(_ADSLIGHT_CAPTION, 'caption', 35, 55);
286
287
        $form->setExtra('enctype="multipart/form-data"');
288
        $button_send   = new \XoopsFormButton('', 'submit_button', _ADSLIGHT_UPLOADPICTURE, 'submit');
289
        $field_warning = new \XoopsFormLabel(sprintf(_ADSLIGHT_YOUCANUPLOAD, $maxbytes / 1024));
290
        $field_lid     = new \XoopsFormHidden('lid', $lid);
291
        $field_uid     = new \XoopsFormHidden('uid', $uid);
292
293
        $field_token = $GLOBALS['xoopsSecurity']->getTokenHTML();
294
295
        $form->addElement($field_warning);
296
        $form->addElement($field_url, true);
297
        $form->addElement($field_desc, true);
298
        $form->addElement($field_lid, true);
299
        $form->addElement($field_uid, true);
300
301
        $form->addElement($field_token, true);
302
303
        $form->addElement($button_send);
304
        if (str_replace('.', '', PHP_VERSION) > 499) {
305
            $form->assign($xoopsTpl);
306
        } else {
307
            $form->display();
308
        }
309
310
        return true;
311
    }
312
313
    /**
314
     * Render a form to edit the description of the pictures
315
     *
316
     * @param string $caption  The description of the picture
317
     * @param int    $cod_img  the id of the image in database
318
     * @param string $filename the url to the thumb of the image so it can be displayed
319
     * @return bool   TRUE
320
     */
321
    public function renderFormEdit($caption, $cod_img, $filename)
322
    {
323
        $form       = new \XoopsThemeForm(_ADSLIGHT_EDIT_CAPTION, 'form_picture', 'editdesc.php', 'post', true);
324
        $field_desc = new \XoopsFormText($caption, 'caption', 35, 55);
325
        $form->setExtra('enctype="multipart/form-data"');
326
        $button_send = new \XoopsFormButton(_ADSLIGHT_EDIT, 'submit_button', _SUBMIT, 'submit');
327
        //@todo - replace alt with language string
328
        $field_warning = new \XoopsFormLabel("<img src='{$filename}' alt='sssss'>");
329
        $field_cod_img = new \XoopsFormHidden('cod_img', $cod_img);
330
        //    $field_lid = new \XoopsFormHidden('lid', $lid);
331
        $field_marker = new \XoopsFormHidden('marker', 1);
332
333
        $field_token = $GLOBALS['xoopsSecurity']->getTokenHTML();
334
335
        $form->addElement($field_warning);
336
        $form->addElement($field_desc);
337
        $form->addElement($field_cod_img);
338
        $form->addElement($field_marker);
339
        $form->addElement($field_token);
340
        $form->addElement($button_send);
341
        $form->display();
342
343
        return true;
344
    }
345
346
    /**
347
     * Upload the file and Save into database
348
     *
349
     * @param string $title         A litle description of the file
350
     * @param string $path_upload   The path to where the file should be uploaded
351
     * @param int    $thumbwidth    the width in pixels that the thumbnail will have
352
     * @param int    $thumbheight   the height in pixels that the thumbnail will have
353
     * @param int    $pictwidth     the width in pixels that the pic will have
354
     * @param int    $pictheight    the height in pixels that the pic will have
355
     * @param int    $maxfilebytes  the maximum size a file can have to be uploaded in bytes
356
     * @param int    $maxfilewidth  the maximum width in pixels that a pic can have
357
     * @param int    $maxfileheight the maximum height in pixels that a pic can have
358
     * @return bool FALSE if upload fails or database fails
359
     */
360
    public function receivePicture($title, $path_upload, $thumbwidth, $thumbheight, $pictwidth, $pictheight, $maxfilebytes, $maxfilewidth, $maxfileheight)
361
    {
362
        global $lid;
363
        //busca id do user logado
364
        $uid = $GLOBALS['xoopsUser']->getVar('uid');
365
        $lid = Request::getInt('lid', 0, 'POST');
366
        //create a hash so it does not erase another file
367
        $hash1 = time();
368
        $hash  = mb_substr($hash1, 0, 4);
369
        // mimetypes and settings put this in admin part later
370
        $allowed_mimetypes = [
371
            'image/jpeg',
372
            'image/gif',
373
        ];
374
        $maxfilesize       = $maxfilebytes;
375
        // create the object to upload
376
        $uploader = new \XoopsMediaUploader($path_upload, $allowed_mimetypes, $maxfilesize, $maxfilewidth, $maxfileheight);
377
        // fetch the media
378
        if ($uploader->fetchMedia($_POST['xoops_upload_file'][0])) {
379
            //lets create a name for it
380
            $uploader->setPrefix("pic_{$lid}_");
381
            //now let s upload the file
382
            if (!$uploader->upload()) {
383
                // if there are errors lets return them
384
                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>';
385
386
                return false;
387
            }
388
            // now let s create a new object picture and set its variables
389
            $picture = $this->create();
390
            $url     = $uploader->getSavedFileName();
391
            $picture->setVar('url', $url);
392
            $picture->setVar('title', $title);
393
            $uid = $GLOBALS['xoopsUser']->getVar('uid');
394
            $lid = $lid;
395
            $picture->setVar('lid', $lid);
396
            $picture->setVar('uid_owner', $uid);
397
            $this->insert($picture);
398
            $saved_destination = $uploader->getSavedDestination();
399
            $this->resizeImage($saved_destination, $thumbwidth, $thumbheight, $pictwidth, $pictheight, $path_upload);
400
        } else {
401
            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>';
402
403
            return false;
404
        }
405
406
        return true;
407
    }
408
409
    /**
410
     * Resize a picture and save it to $path_upload
411
     *
412
     * @param string $img         the path to the file
413
     * @param int    $thumbwidth  the width in pixels that the thumbnail will have
414
     * @param int    $thumbheight the height in pixels that the thumbnail will have
415
     * @param int    $pictwidth   the width in pixels that the pic will have
416
     * @param int    $pictheight  the height in pixels that the pic will have
417
     * @param string $path_upload The path to where the files should be saved after resizing
418
     */
419
    public function resizeImage($img, $thumbwidth, $thumbheight, $pictwidth, $pictheight, $path_upload)
420
    {
421
        $img2   = $img;
422
        $path   = pathinfo($img);
423
        $img    = imagecreatefromjpeg($img);
424
        $xratio = $thumbwidth / imagesx($img);
425
        $yratio = $thumbheight / imagesy($img);
426
        if ($xratio < 1 || $yratio < 1) {
427
            if ($xratio < $yratio) {
428
                $resized = imagecreatetruecolor($thumbwidth, floor(imagesy($img) * $xratio));
429
            } else {
430
                $resized = imagecreatetruecolor(floor(imagesx($img) * $yratio), $thumbheight);
431
            }
432
            imagecopyresampled($resized, $img, 0, 0, 0, 0, imagesx($resized) + 1, imagesy($resized) + 1, imagesx($img), imagesy($img));
433
            imagejpeg($resized, "{$path_upload}/thumbs/thumb_{$path['basename']}");
434
            imagedestroy($resized);
435
        } else {
436
            imagejpeg($img, "{$path_upload}/thumbs/thumb_{$path['basename']}");
437
        }
438
        imagedestroy($img);
439
        $path2   = pathinfo($img2);
440
        $img2    = imagecreatefromjpeg($img2);
441
        $xratio2 = $pictwidth / imagesx($img2);
442
        $yratio2 = $pictheight / imagesy($img2);
443
        if ($xratio2 < 1 || $yratio2 < 1) {
444
            if ($xratio2 < $yratio2) {
445
                $resized2 = imagecreatetruecolor($pictwidth, floor(imagesy($img2) * $xratio2));
446
            } else {
447
                $resized2 = imagecreatetruecolor(floor(imagesx($img2) * $yratio2), $pictheight);
448
            }
449
            imagecopyresampled($resized2, $img2, 0, 0, 0, 0, imagesx($resized2) + 1, imagesy($resized2) + 1, imagesx($img2), imagesy($img2));
450
            imagejpeg($resized2, "{$path_upload}/midsize/resized_{$path2['basename']}");
451
            imagedestroy($resized2);
452
        } else {
453
            imagejpeg($img2, "{$path_upload}/midsize/resized_{$path2['basename']}");
454
        }
455
        imagedestroy($img2);
456
    }
457
}
458