Passed
Pull Request — master (#81)
by Michael
02:58
created

class/AudioHandler.php (3 issues)

1
<?php
2
3
declare(strict_types=1);
4
5
namespace XoopsModules\Yogurt;
6
7
/*
8
 You may not change or alter any portion of this comment or credits
9
 of supporting developers from this source code or any supporting source code
10
 which is considered copyrighted (c) material of the original comment or credit authors.
11
12
 This program is distributed in the hope that it will be useful,
13
 but WITHOUT ANY WARRANTY; without even the implied warranty of
14
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
15
*/
16
17
/**
18
 * @category        Module
19
 * @package         yogurt
20
 * @copyright       {@link https://xoops.org/ XOOPS Project}
21
 * @license         GNU GPL 2 or later (https://www.gnu.org/licenses/gpl-2.0.html)
22
 * @author          Bruno Barthez, Marcello Brandão aka  Suico, Mamba, LioMJ  <https://xoops.org>
23
 */
24
25
use CriteriaCompo;
26
use CriteriaElement;
27
use Xmf\Request;
28
use XoopsDatabase;
29
use XoopsMediaUploader;
30
use XoopsObject;
31
use XoopsPersistableObjectHandler;
32
33
require_once XOOPS_ROOT_PATH . '/kernel/object.php';
34
require_once XOOPS_ROOT_PATH . '/class/uploader.php';
35
36
/**
37
 * AudioHandler class.
38
 * This class provides simple mecanisme for yogurt_audio object
39
 */
40
class AudioHandler extends XoopsPersistableObjectHandler
41
{
42
    public $isAdmin;
43
44
    public $helper;
45
46
    /**
47
     * Constructor
48
     * @param \XoopsDatabase|null $xoopsDatabase
49
     * @param Helper|null         $helper
50
     */
51
52
    public function __construct(
53
        ?XoopsDatabase $xoopsDatabase = null,
54
        $helper = null
55
    ) {
56
        /** @var Helper $this ->helper */
57
58
        if (null === $helper) {
59
            $this->helper = Helper::getInstance();
60
        } else {
61
            $this->helper = $helper;
62
        }
63
64
        $isAdmin = $this->helper->isUserAdmin();
65
66
        parent::__construct($xoopsDatabase, 'yogurt_audios', Audio::class, 'audio_id', 'title');
67
    }
68
69
    /**
70
     * @param bool $isNew
71
     *
72
     * @return XoopsObject
73
     */
74
75
    public function create($isNew = true)
76
    {
77
        $obj = parent::create($isNew);
78
79
        if ($isNew) {
80
            $obj->setNew();
81
        } else {
82
            $obj->unsetNew();
83
        }
84
85
        $obj->helper = $this->helper;
86
87
        return $obj;
88
    }
89
90
    /**
91
     * retrieve a yogurt_audio
92
     *
93
     * @param int $id of the yogurt_audio
94
     * @return mixed reference to the {@link yogurt_audio} object, FALSE if failed
95
     */
96
97
    public function get2(
98
        $id = null
99
        //        $fields = null
100
    )
101
    {
102
        $sql = 'SELECT * FROM ' . $this->db->prefix('yogurt_audios') . ' WHERE audio_id=' . $id;
103
104
        if (!$result = $this->db->query($sql)) {
105
            return false;
106
        }
107
108
        $numrows = $this->db->getRowsNum($result);
109
110
        if (1 === $numrows) {
111
            $yogurtAudio = new Audio();
112
113
            $yogurtAudio->assignVars($this->db->fetchArray($result));
114
115
            return $yogurtAudio;
116
        }
117
118
        return false;
119
    }
120
121
    /**
122
     * insert a new Audio in the database
123
     *
124
     * @param XoopsObject $xoopsObject reference to the {@link yogurt_audio}
125
     *                                 object
126
     * @param bool        $force
127
     * @return bool FALSE if failed, TRUE if already present and unchanged or successful
128
     */
129
130
    public function insert2(
131
        XoopsObject $xoopsObject,
132
        $force = false
133
    ) {
134
        global $xoopsConfig;
135
136
        if (Audio::class !== \get_class($xoopsObject)) {
137
            return false;
138
        }
139
140
        if (!$xoopsObject->isDirty()) {
141
            return true;
142
        }
143
144
        if (!$xoopsObject->cleanVars()) {
145
            return false;
146
        }
147
148
        foreach ($xoopsObject->cleanVars as $k => $v) {
149
            ${$k} = $v;
150
        }
151
152
        //        $now = 'date_add(now(), interval ' . $xoopsConfig['server_TZ'] . ' hour)';
153
154
        if ($xoopsObject->isNew()) {
155
            // adding / modifying a yogurt_audio
156
157
            $xoopsObject = new Audio();
158
159
            $format = 'INSERT INTO %s (audio_id, title, author, description, filename, uid_owner, date_created, date_updated)';
160
161
            $format .= ' VALUES (%u, %s, %s, %s, %s, %u, %s, %s)';
162
163
            $sql = \sprintf(
164
                $format,
165
                $this->db->prefix('yogurt_audios'),
166
                $audio_id,
167
                $this->db->quoteString($author),
168
                $this->db->quoteString($title),
169
                $this->db->quoteString($description),
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $description seems to be never defined.
Loading history...
170
                $this->db->quoteString($filename),
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $filename seems to be never defined.
Loading history...
171
                $uid_owner,
172
                \time(),
173
                \time()
174
            );
175
176
            $force = true;
177
        } else {
178
            $format = 'UPDATE %s SET ';
179
180
            $format .= 'audio_id=%u, title=%s, author=%s, filename=%s, description=%s,uid_owner=%u, date_created=%s, date_updated=%s';
181
182
            $format .= ' WHERE audio_id = %u';
183
184
            $sql = \sprintf(
185
                $format,
186
                $this->db->prefix('yogurt_audios'),
187
                $audio_id,
188
                $this->db->quoteString($title),
189
                $this->db->quoteString($author),
190
                $this->db->quoteString($url),
191
                $uid_owner,
192
                $now,
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $now seems to be never defined.
Loading history...
193
                $now,
194
                $audio_id
195
            );
196
        }
197
198
        if ($force) {
199
            $result = $this->db->queryF($sql);
200
        } else {
201
            $result = $this->db->query($sql);
202
        }
203
204
        if (!$result) {
205
            return false;
206
        }
207
208
        if (empty($audio_id)) {
209
            $audio_id = $this->db->getInsertId();
210
        }
211
212
        $xoopsObject->assignVar('audio_id', $audio_id);
213
214
        return true;
215
    }
216
217
    /**
218
     * delete a yogurt_audio from the database
219
     *
220
     * @param XoopsObject $xoopsObject reference to the yogurt_audio to delete
221
     * @param bool        $force
222
     * @return bool FALSE if failed.
223
     */
224
225
    public function delete(
226
        XoopsObject $xoopsObject,
227
        $force = false
228
    ) {
229
        if ('yogurt_audio' !== \get_class($xoopsObject)) {
230
            return false;
231
        }
232
233
        $sql = \sprintf(
234
            'DELETE FROM %s WHERE audio_id = %u',
235
            $this->db->prefix('yogurt_audios'),
236
            $xoopsObject->getVar('audio_id')
237
        );
238
239
        if ($force) {
240
            $result = $this->db->queryF($sql);
241
        } else {
242
            $result = $this->db->query($sql);
243
        }
244
245
        if (!$result) {
246
            return false;
247
        }
248
249
        return true;
250
    }
251
252
    /**
253
     * retrieve yogurt_audios from the database
254
     *
255
     * @param CriteriaElement|CriteriaCompo|null $criteriaElement {@link \CriteriaElement} conditions to be met
256
     * @param bool                               $id_as_key       use the UID as key for the array?
257
     * @param bool                               $as_object
258
     * @return array array of {@link yogurt_audio} objects
259
     */
260
261
    public function &getObjects(
262
        ?CriteriaElement $criteriaElement = null,
263
        $id_as_key = false,
264
        $as_object = true
265
    ) {
266
        $ret = [];
267
268
        $limit = $start = 0;
269
270
        $sql = 'SELECT * FROM ' . $this->db->prefix('yogurt_audios');
271
272
        if (isset($criteriaElement) && $criteriaElement instanceof CriteriaElement) {
273
            $sql .= ' ' . $criteriaElement->renderWhere();
274
275
            if ('' !== $criteriaElement->getSort()) {
276
                $sql .= ' ORDER BY ' . $criteriaElement->getSort() . ' ' . $criteriaElement->getOrder();
277
            }
278
279
            $limit = $criteriaElement->getLimit();
280
281
            $start = $criteriaElement->getStart();
282
        }
283
284
        $result = $this->db->query($sql, $limit, $start);
285
286
        if (!$result) {
287
            return $ret;
288
        }
289
290
        while (false !== ($myrow = $this->db->fetchArray($result))) {
291
            $yogurtAudio = new Audio();
292
293
            $yogurtAudio->assignVars($myrow);
294
295
            if (!$id_as_key) {
296
                $ret[] = &$yogurtAudio;
297
            } else {
298
                $ret[$myrow['audio_id']] = &$yogurtAudio;
299
            }
300
301
            unset($yogurtAudio);
302
        }
303
304
        return $ret;
305
    }
306
307
    /**
308
     * count yogurt_audios matching a condition
309
     *
310
     * @param CriteriaElement|CriteriaCompo|null $criteriaElement {@link \CriteriaElement} to match
311
     * @return int count of yogurt_audios
312
     */
313
314
    public function getCount(
315
        ?CriteriaElement $criteriaElement = null
316
    ) {
317
        $sql = 'SELECT COUNT(*) FROM ' . $this->db->prefix('yogurt_audios');
318
319
        if (isset($criteriaElement) && $criteriaElement instanceof CriteriaElement) {
320
            $sql .= ' ' . $criteriaElement->renderWhere();
321
        }
322
323
        $result = $this->db->query($sql);
324
325
        if (!$result) {
326
            return 0;
327
        }
328
329
        [$count] = $this->db->fetchRow($result);
330
331
        return (int)$count;
332
    }
333
334
    /**
335
     * delete yogurt_audios matching a set of conditions
336
     *
337
     * @param CriteriaElement|CriteriaCompo|null $criteriaElement {@link \CriteriaElement}
338
     * @param bool                               $force
339
     * @param bool                               $asObject
340
     * @return bool FALSE if deletion failed
341
     */
342
343
    public function deleteAll(
344
        ?CriteriaElement $criteriaElement = null,
345
        $force = true,
346
        $asObject = false
347
    ) {
348
        $sql = 'DELETE FROM ' . $this->db->prefix('yogurt_audios');
349
350
        if (isset($criteriaElement) && $criteriaElement instanceof CriteriaElement) {
351
            $sql .= ' ' . $criteriaElement->renderWhere();
352
        }
353
354
        if (!$result = $this->db->query($sql)) {
355
            return false;
356
        }
357
358
        return true;
359
    }
360
361
    /**
362
     * Upload the file and Save into database
363
     *
364
     * @param string $title       A litle description of the file
365
     * @param string $path_upload The path to where the file should be uploaded
366
     * @param string $author      the author of the music or audio file
367
     * @param        $maxfilebytes
368
     * @return bool FALSE if upload fails or database fails
369
     */
370
371
    public function receiveAudio(
372
        $title,
373
        $path_upload,
374
        $author,
375
        $maxfilebytes
376
    ) {
377
        global $xoopsUser, $xoopsDB, $_POST, $_FILES;
378
379
        //busca id do user logado
380
381
        $uid = $xoopsUser->getVar('uid');
382
383
        //create a hash so it does not erase another file
384
385
        //$hash1 = date();
386
387
        //$hash = substr($hash1,0,4);
388
389
        // mimetypes and settings put this in admin part later
390
391
        $allowed_mimetypes = [
392
            'audio/mp3',
393
            'audio/x-mp3',
394
            'audio/mpeg',
395
        ];
396
397
        $maxfilesize = $maxfilebytes;
398
399
        $uploadDir = $path_upload;
400
401
        // create the object to upload
402
403
        $uploader = new XoopsMediaUploader(
404
            $uploadDir, $allowed_mimetypes, $maxfilesize
405
        );
406
407
        // fetch the media
408
409
        if ($uploader->fetchMedia((Request::getArray('xoops_upload_file', '', 'POST')[0]))) {
410
            //lets create a name for it
411
412
            $uploader->setPrefix('aud_' . $uid . '_');
413
414
            //now let s upload the file
415
416
            if (!$uploader->upload()) {
417
                // if there are errors lets return them
418
419
                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>';
420
421
                return false;
422
            }
423
424
            // now let s create a new object audio and set its variables
425
426
            //echo "passei aqui";
427
428
            $audio = $this->create();
429
430
            $url = $uploader->getSavedFileName();
431
432
            $audio->setVar('filename', $url);
433
434
            $audio->setVar('title', $title);
435
436
            $audio->setVar('author', $author);
437
438
            $uid = $xoopsUser->getVar('uid');
439
440
            $audio->setVar('uid_owner', $uid);
441
442
            $audio->setVar('date_created', \time());
443
444
            $audio->setVar('date_updated', \time());
445
446
            $this->insert2($audio);
447
448
            $saved_destination = $uploader->getSavedDestination();
449
            //print_r($_FILES);
450
        } else {
451
            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>';
452
453
            return false;
454
        }
455
456
        return true;
457
    }
458
}
459