Passed
Push — master ( f0fd80...9c2eb6 )
by Michael
33s queued 12s
created

AudioHandler::create()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 10
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 7
dl 0
loc 10
rs 10
c 0
b 0
f 0
cc 2
nc 2
nop 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace XoopsModules\Suico;
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         suico
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
use XoopsModules\Suico\{
33
    Helper
0 ignored issues
show
Bug introduced by
This use statement conflicts with another class in this namespace, XoopsModules\Suico\Helper. Consider defining an alias.

Let?s assume that you have a directory layout like this:

.
|-- OtherDir
|   |-- Bar.php
|   `-- Foo.php
`-- SomeDir
    `-- Foo.php

and let?s assume the following content of Bar.php:

// Bar.php
namespace OtherDir;

use SomeDir\Foo; // This now conflicts the class OtherDir\Foo

If both files OtherDir/Foo.php and SomeDir/Foo.php are loaded in the same runtime, you will see a PHP error such as the following:

PHP Fatal error:  Cannot use SomeDir\Foo as Foo because the name is already in use in OtherDir/Foo.php

However, as OtherDir/Foo.php does not necessarily have to be loaded and the error is only triggered if it is loaded before OtherDir/Bar.php, this problem might go unnoticed for a while. In order to prevent this error from surfacing, you must import the namespace with a different alias:

// Bar.php
namespace OtherDir;

use SomeDir\Foo as SomeDirFoo; // There is no conflict anymore.
Loading history...
34
};
35
/** @var Helper $helper */
36
37
require_once XOOPS_ROOT_PATH . '/kernel/object.php';
38
require_once XOOPS_ROOT_PATH . '/class/uploader.php';
39
40
/**
41
 * AudioHandler class.
42
 * This class provides simple mechanism for suico_audio object
43
 */
44
class AudioHandler extends XoopsPersistableObjectHandler
45
{
46
    public $isAdmin;
47
    public $helper;
48
49
    /**
50
     * Constructor
51
     * @param \XoopsDatabase|null $xoopsDatabase
52
     * @param Helper|null         $helper
53
     */
54
    public function __construct(
55
        ?XoopsDatabase $xoopsDatabase = null,
56
        $helper = null
57
    ) {
58
        /** @var Helper $this->helper */
59
        if (null === $helper) {
60
            $this->helper = Helper::getInstance();
61
        } else {
62
            $this->helper = $helper;
63
        }
64
        $isAdmin = $this->helper->isUserAdmin();
0 ignored issues
show
Unused Code introduced by
The assignment to $isAdmin is dead and can be removed.
Loading history...
65
        parent::__construct($xoopsDatabase, 'suico_audios', Audio::class, 'audio_id', 'title');
66
    }
67
68
    /**
69
     * @param bool $isNew
70
     *
71
     * @return XoopsObject
72
     */
73
    public function create($isNew = true)
74
    {
75
        $obj = parent::create($isNew);
76
        if ($isNew) {
77
            $obj->setNew();
78
        } else {
79
            $obj->unsetNew();
80
        }
81
        $obj->helper = $this->helper;
82
        return $obj;
83
    }
84
85
    /**
86
     * retrieve a suico_audio
87
     *
88
     * @param int|null $id of the suico_audio
89
     * @return mixed reference to the {@link suico_audio} object, FALSE if failed
90
     */
91
    public function get2(
92
        $id = null
93
        //        $fields = null
94
    )
95
    {
96
        $sql = 'SELECT * FROM ' . $this->db->prefix('suico_audios') . ' WHERE audio_id=' . $id;
97
        if (!$result = $this->db->query($sql)) {
98
            return false;
99
        }
100
        $numrows = $this->db->getRowsNum($result);
101
        if (1 === $numrows) {
102
            $suicoAudio = new Audio();
103
            $suicoAudio->assignVars($this->db->fetchArray($result));
104
            return $suicoAudio;
105
        }
106
        return false;
107
    }
108
109
    /**
110
     * insert a new Audio in the database
111
     *
112
     * @param XoopsObject $xoopsObject reference to the {@link suico_audio}
113
     *                                 object
114
     * @param bool        $force
115
     * @return bool FALSE if failed, TRUE if already present and unchanged or successful
116
     */
117
    public function insert2(
118
        XoopsObject $xoopsObject,
119
        $force = false
120
    ) {
121
        global $xoopsConfig;
122
        if (Audio::class !== \get_class($xoopsObject)) {
123
            return false;
124
        }
125
        if (!$xoopsObject->isDirty()) {
126
            return true;
127
        }
128
        if (!$xoopsObject->cleanVars()) {
129
            return false;
130
        }
131
        foreach ($xoopsObject->cleanVars as $k => $v) {
132
            ${$k} = $v;
133
        }
134
        $audio_id     = Request::getString('audio_id', '', 'POST');
135
        $uid_owner    = Request::getInt('audio_id', 0, 'POST');
136
        $title        = Request::getString('title', '', 'POST');
137
        $author       = Request::getString('author', '', 'POST');
138
        $description  = Request::getText('description', '', 'POST');
139
        $filename     = Request::getString('filename', '', 'POST');
140
        $date_created = Request::getString('date_created', \time(), 'POST');
141
        $date_updated = Request::getString('date_updated', \time(), 'POST');
142
        //        $now = 'date_add(now(), interval ' . $xoopsConfig['server_TZ'] . ' hour)';
143
        if ($xoopsObject->isNew()) {
144
            // adding / modifying a suico_audio
145
            $xoopsObject = new Audio();
146
            $format      = 'INSERT INTO %s (audio_id, title, author, description, filename, uid_owner, date_created, date_updated)';
147
            $format      .= ' VALUES (%u, %s, %s, %s, %s, %u, %s, %s)';
148
            $sql         = \sprintf(
149
                $format,
150
                $this->db->prefix('suico_audios'),
151
                $audio_id,
152
                $this->db->quoteString($author),
153
                $this->db->quoteString($title),
154
                $this->db->quoteString($description),
155
                $this->db->quoteString($filename),
156
                $uid_owner,
157
                $date_created,
158
                $date_updated
159
            );
160
            $force       = true;
161
        } else {
162
            $format = 'UPDATE %s SET ';
163
            $format .= 'audio_id=%u, title=%s, author=%s, filename=%s, description=%s,uid_owner=%u, date_created=%s, date_updated=%s';
164
            $format .= ' WHERE audio_id = %u';
165
            $sql    = \sprintf(
166
                $format,
167
                $this->db->prefix('suico_audios'),
168
                $audio_id,
169
                $this->db->quoteString($title),
170
                $this->db->quoteString($author),
171
                $this->db->quoteString($filename),
172
                $uid_owner,
173
                $date_created,
174
                $date_updated,
175
                $audio_id
176
            );
177
        }
178
        if ($force) {
179
            $result = $this->db->queryF($sql);
180
        } else {
181
            $result = $this->db->query($sql);
182
        }
183
        if (!$result) {
184
            return false;
185
        }
186
        if (empty($audio_id)) {
187
            $audio_id = $this->db->getInsertId();
188
        }
189
        $xoopsObject->assignVar('audio_id', $audio_id);
190
        return true;
191
    }
192
193
    /**
194
     * delete a suico_audio from the database
195
     *
196
     * @param XoopsObject $xoopsObject reference to the suico_audio to delete
197
     * @param bool        $force
198
     * @return bool FALSE if failed.
199
     */
200
    public function delete(
201
        XoopsObject $xoopsObject,
202
        $force = false
203
    ) {
204
        if ('suico_audio' !== \get_class($xoopsObject)) {
205
            return false;
206
        }
207
        $sql = \sprintf(
208
            'DELETE FROM %s WHERE audio_id = %u',
209
            $this->db->prefix('suico_audios'),
210
            $xoopsObject->getVar('audio_id')
0 ignored issues
show
Bug introduced by
It seems like $xoopsObject->getVar('audio_id') can also be of type array and array; however, parameter $args of sprintf() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

210
            /** @scrutinizer ignore-type */ $xoopsObject->getVar('audio_id')
Loading history...
211
        );
212
        if ($force) {
213
            $result = $this->db->queryF($sql);
214
        } else {
215
            $result = $this->db->query($sql);
216
        }
217
        if (!$result) {
218
            return false;
219
        }
220
        return true;
221
    }
222
223
    /**
224
     * retrieve suico_audios from the database
225
     *
226
     * @param \CriteriaElement|\CriteriaCompo|null $criteriaElement {@link \CriteriaElement} conditions to be met
227
     * @param bool                                 $id_as_key       use the UID as key for the array?
228
     * @param bool                                 $as_object
229
     * @return array array of {@link suico_audio} objects
230
     */
231
    public function &getObjects(
232
        ?CriteriaElement $criteriaElement = null,
233
        $id_as_key = false,
234
        $as_object = true
235
    ) {
236
        $ret   = [];
237
        $limit = $start = 0;
238
        $sql   = 'SELECT * FROM ' . $this->db->prefix('suico_audios');
239
        if (isset($criteriaElement) && $criteriaElement instanceof CriteriaElement) {
240
            $sql .= ' ' . $criteriaElement->renderWhere();
0 ignored issues
show
Bug introduced by
The method renderWhere() does not exist on CriteriaElement. Did you maybe mean render()? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

240
            $sql .= ' ' . $criteriaElement->/** @scrutinizer ignore-call */ renderWhere();

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
241
            if ('' !== $criteriaElement->getSort()) {
242
                $sql .= ' ORDER BY ' . $criteriaElement->getSort() . ' ' . $criteriaElement->getOrder();
243
            }
244
            $limit = $criteriaElement->getLimit();
245
            $start = $criteriaElement->getStart();
246
        }
247
        $result = $this->db->query($sql, $limit, $start);
248
        if (!$result) {
249
            return $ret;
250
        }
251
        while (false !== ($myrow = $this->db->fetchArray($result))) {
252
            $suicoAudio = new Audio();
253
            $suicoAudio->assignVars($myrow);
254
            if ($id_as_key) {
255
                $ret[$myrow['audio_id']] = &$suicoAudio;
256
            } else {
257
                $ret[] = &$suicoAudio;
258
            }
259
            unset($suicoAudio);
260
        }
261
        return $ret;
262
    }
263
264
    /**
265
     * count suico_audios matching a condition
266
     *
267
     * @param CriteriaElement|CriteriaCompo|null $criteriaElement {@link \CriteriaElement} to match
268
     * @return int count of suico_audios
269
     */
270
    public function getCount(
271
        ?CriteriaElement $criteriaElement = null
272
    ) {
273
        $sql = 'SELECT COUNT(*) FROM ' . $this->db->prefix('suico_audios');
274
        if (isset($criteriaElement) && $criteriaElement instanceof CriteriaElement) {
275
            $sql .= ' ' . $criteriaElement->renderWhere();
276
        }
277
        $result = $this->db->query($sql);
278
        if (!$result) {
279
            return 0;
280
        }
281
        [$count] = $this->db->fetchRow($result);
282
        return (int)$count;
283
    }
284
285
    /**
286
     * delete suico_audios matching a set of conditions
287
     *
288
     * @param CriteriaElement|CriteriaCompo|null $criteriaElement {@link \CriteriaElement}
289
     * @param bool                               $force
290
     * @param bool                               $asObject
291
     * @return bool FALSE if deletion failed
292
     */
293
    public function deleteAll(
294
        ?CriteriaElement $criteriaElement = null,
295
        $force = true,
296
        $asObject = false
297
    ) {
298
        $sql = 'DELETE FROM ' . $this->db->prefix('suico_audios');
299
        if (isset($criteriaElement) && $criteriaElement instanceof CriteriaElement) {
300
            $sql .= ' ' . $criteriaElement->renderWhere();
301
        }
302
        if (!$result = $this->db->query($sql)) {
0 ignored issues
show
Unused Code introduced by
The assignment to $result is dead and can be removed.
Loading history...
303
            return false;
304
        }
305
        return true;
306
    }
307
308
    /**
309
     * Upload the file and Save into database
310
     *
311
     * @param string $title       A litle description of the file
312
     * @param string $path_upload The path to where the file should be uploaded
313
     * @param string $author      the author of the music or audio file
314
     * @param        $maxfilebytes
315
     * @param        $description
316
     * @return bool FALSE if upload fails or database fails
317
     */
318
    public function receiveAudio(
319
        $title,
320
        $path_upload,
321
        $author,
322
        $maxfilebytes,
323
        $description
324
    ) {
325
        global $xoopsUser, $xoopsDB, $_POST, $_FILES;
326
        //busca id do user logado
327
        $uid = $xoopsUser->getVar('uid');
328
        //create a hash so it does not erase another file
329
        //$hash1 = date();
330
        //$hash = substr($hash1,0,4);
331
        // mimetypes and settings put this in admin part later
332
        $allowed_mimetypes = [
333
            'audio/mp3',
334
            'audio/x-mp3',
335
            'audio/mpeg',
336
        ];
337
        $maxfilesize       = $maxfilebytes;
338
        $uploadDir         = $path_upload;
339
        // create the object to upload
340
        $uploader = new \XoopsMediaUploader(
341
            $uploadDir, $allowed_mimetypes, $maxfilesize
342
        );
343
        // fetch the media
344
        if ($uploader->fetchMedia((Request::getArray('xoops_upload_file', '', 'POST')[0]))) {
345
            //lets create a name for it
346
            $uploader->setPrefix('aud_' . $uid . '_');
347
            //now let s upload the file
348
            if (!$uploader->upload()) {
349
                // if there are errors lets return them
350
                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>';
351
                return false;
352
            }
353
            // now let s create a new object audio and set its variables
354
            //echo "passei aqui";
355
            $audio = $this->create();
356
            $audio->setVar('uid_owner', $xoopsUser->getVar('uid'));
357
            $audio->setVar('title', $title);
358
            $audio->setVar('author', $author);
359
            $audio->setVar('description', $description);
360
            $audio->setVar(
361
                'filename',
362
                $uploader->getSavedFileName()
363
            );
364
            $audio->setVar('date_created', \time());
365
            $audio->setVar('date_updated', \time());
366
            $this->insert($audio);
367
            $saved_destination = $uploader->getSavedDestination();
0 ignored issues
show
Unused Code introduced by
The assignment to $saved_destination is dead and can be removed.
Loading history...
368
            //print_r($_FILES);
369
        } else {
370
            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>';
371
            return false;
372
        }
373
        return true;
374
    }
375
}
376