Passed
Push — master ( 3b9afc...64a367 )
by Goffy
03:06
created

DirectoryHandler::getFullPathRecursive()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 10
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 3
eloc 7
c 1
b 0
f 0
nc 3
nop 1
dl 0
loc 10
rs 10
1
<?php
2
3
declare(strict_types=1);
4
5
6
namespace XoopsModules\Wgfilemanager;
7
8
/*
9
 You may not change or alter any portion of this comment or credits
10
 of supporting developers from this source code or any supporting source code
11
 which is considered copyrighted (c) material of the original comment or credit authors.
12
13
 This program is distributed in the hope that it will be useful,
14
 but WITHOUT ANY WARRANTY; without even the implied warranty of
15
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
16
*/
17
18
/**
19
 * wgFileManager module for xoops
20
 *
21
 * @copyright    2021 XOOPS Project (https://xoops.org)
22
 * @license      GPL 2.0 or later
23
 * @package      wgfilemanager
24
 * @author       Goffy - Wedega - Email:[email protected] - Website:https://xoops.wedega.com
25
 */
26
27
use Xmf\Request;
28
use XoopsModules\Wgfilemanager;
29
use XoopsModules\Wgfilemanager\Common\FilesManagement;
30
31
32
/**
33
 * Class Object Handler Directory
34
 */
35
class DirectoryHandler extends \XoopsPersistableObjectHandler
36
{
37
    /**
38
     * Constructor
39
     *
40
     * @param \XoopsDatabase $db
41
     */
42
    public function __construct(\XoopsDatabase $db)
43
    {
44
        parent::__construct($db, 'wgfilemanager_directory', Directory::class, 'id', 'name');
45
    }
46
47
    /**
48
     * @param bool $isNew
49
     *
50
     * @return object
51
     */
52
    public function create($isNew = true)
53
    {
54
        return parent::create($isNew);
55
    }
56
57
    /**
58
     * retrieve a field
59
     *
60
     * @param int $id field id
61
     * @param null $fields fields
0 ignored issues
show
Documentation Bug introduced by
Are you sure the doc-type for parameter $fields is correct as it would always require null to be passed?
Loading history...
62
     * @return \XoopsObject|null reference to the {@link Get} object
63
     */
64
    public function get($id = null, $fields = null)
65
    {
66
        return parent::get($id, $fields);
67
    }
68
69
    /**
70
     * get inserted id
71
     *
72
     * @return int reference to the {@link Get} object
73
     */
74
    public function getInsertId()
75
    {
76
        return $this->db->getInsertId();
77
    }
78
79
    /**
80
     * Get Count Directory in the database
81
     * @param int    $start
82
     * @param int    $limit
83
     * @param string $sort
84
     * @param string $order
85
     * @return int
86
     */
87
    public function getCountDirectory($start = 0, $limit = 0, $sort = 'id ASC, name', $order = 'ASC')
88
    {
89
        $crCountDirectory = new \CriteriaCompo();
90
        $crCountDirectory = $this->getDirectoryCriteria($crCountDirectory, $start, $limit, $sort, $order);
91
        return $this->getCount($crCountDirectory);
0 ignored issues
show
Bug introduced by
$crCountDirectory of type integer is incompatible with the type CriteriaElement|null expected by parameter $criteria of XoopsPersistableObjectHandler::getCount(). ( Ignorable by Annotation )

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

91
        return $this->getCount(/** @scrutinizer ignore-type */ $crCountDirectory);
Loading history...
92
    }
93
94
    /**
95
     * Get All Directory in the database
96
     * @param int    $start
97
     * @param int    $limit
98
     * @param string $sort
99
     * @param string $order
100
     * @return array
101
     */
102
    public function getAllDirectory($start = 0, $limit = 0, $sort = 'id ASC, name', $order = 'ASC')
103
    {
104
        $crAllDirectory = new \CriteriaCompo();
105
        $crAllDirectory = $this->getDirectoryCriteria($crAllDirectory, $start, $limit, $sort, $order);
106
        return $this->getAll($crAllDirectory);
0 ignored issues
show
Bug introduced by
$crAllDirectory of type integer is incompatible with the type CriteriaElement|null expected by parameter $criteria of XoopsPersistableObjectHandler::getAll(). ( Ignorable by Annotation )

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

106
        return $this->getAll(/** @scrutinizer ignore-type */ $crAllDirectory);
Loading history...
107
    }
108
109
    /**
110
     * Get Criteria Directory
111
     * @param        $crDirectory
112
     * @param int    $start
113
     * @param int    $limit
114
     * @param string $sort
115
     * @param string $order
116
     * @return int
117
     */
118
    private function getDirectoryCriteria($crDirectory, $start, $limit, $sort, $order)
119
    {
120
        $crDirectory->setStart($start);
121
        $crDirectory->setLimit($limit);
122
        $crDirectory->setSort($sort);
123
        $crDirectory->setOrder($order);
124
        return $crDirectory;
125
    }
126
127
    /**
128
     * Get full path of given parent directory
129
     *
130
     * @param int $parent_id
131
     * @return string
132
     */
133
    public function getFullPath($parent_id) {
134
135
        $path = '';
136
        if ($parent_id > 0) {
137
            $path = $this->getFullPathRecursive($parent_id);
138
        }
139
        if ('' === $path) {
140
            return '';
141
        }
142
        $pathArray = \explode(DS, $path);
143
        \krsort($pathArray);
144
145
        return \implode(DS, \array_filter($pathArray));
146
    }
147
148
    /**
149
     * Get full path of given parent directory
150
     *
151
     * @param int $parent_id
152
     * @return string
153
     */
154
    public function getFullPathRecursive($parent_id) {
155
        $path = '';
156
        if ($parent_id > 1) {
157
            $directoryObj = $this->get($parent_id);
158
            $path .= mb_strtolower($directoryObj->getVar('name'));
159
            if ($directoryObj->getVar('parent_id') > 1) {
160
                $path .= DS . $this->getFullPathRecursive($directoryObj->getVar('parent_id'));
161
            }
162
        }
163
        return $path;
164
    }
165
166
    /**
167
     * Check whether given path is a directory
168
     *
169
     * @param string $path
170
     * @return boolean
171
     */
172
    public function existDirectory ($path) {
173
174
        return \is_dir(\WGFILEMANAGER_REPO_PATH . $path);
175
176
    }
177
178
    /**
179
     * Create directory from given path
180
     *
181
     * @param string $path
182
     * @return boolean
183
     */
184
    public function createDirectory($path) {
185
186
        if (FilesManagement::createFolder(\WGFILEMANAGER_REPO_PATH . $path)) {
0 ignored issues
show
Bug introduced by
Are you sure the usage of XoopsModules\Wgfilemanag...AGER_REPO_PATH . $path) targeting XoopsModules\Wgfilemanag...agement::createFolder() seems to always return null.

This check looks for function or method calls that always return null and whose return value is used.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
if ($a->getObject()) {

The method getObject() can return nothing but null, so it makes no sense to use the return value.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
187
            return true;
188
        } else {
189
            throw new \Exception('New filename already exists.');
190
        }
191
    }
192
193
    /**
194
     * Rename directory
195
     *
196
     * @param string $oldDirname
197
     * @param string $newDirname
198
     * @return boolean
199
     */
200
    public function renameDirectory($oldDirname, $newDirname)
201
    {
202
        $oldFilePath = \WGFILEMANAGER_REPO_PATH . $oldDirname;
203
        $newFilePath = \WGFILEMANAGER_REPO_PATH . $newDirname;
204
205
        if (\file_exists($oldFilePath)) {
206
            if (!\file_exists($newFilePath)) {
207
                return \rename($oldFilePath, $newFilePath);
208
            } else {
209
                throw new \Exception('New filename already exists.');
210
            }
211
        } else {
212
            throw new \Exception('Old file does not exist.');
213
        }
214
    }
215
216
    /**
217
     * Delete directory from given path
218
     *
219
     * @param string $path
220
     * @return boolean
221
     */
222
    public function deleteDirectory($path)
223
    {
224
        $fullPath = \WGFILEMANAGER_REPO_PATH . $path;
225
226
        if (!FilesManagement::deleteDirectory($fullPath)) {
227
            return false;
228
        }
229
230
        return !$this->existDirectory($fullPath);
231
232
    }
233
234
    /**
235
     * Check whether given directory is used as parent
236
     *
237
     * @param int $dirId
238
     * @return integer
239
     */
240
    public function dirIsParent ($dirId) {
241
        $crCountDirectory = new \CriteriaCompo();
242
        $crCountDirectory->add(new \Criteria('parent_id', $dirId));
243
244
        return $this->getCount($crCountDirectory) > 0;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $this->getCount($crCountDirectory) > 0 returns the type boolean which is incompatible with the documented return type integer.
Loading history...
245
246
    }
247
248
    /**
249
     * Count subdirectories from given directory
250
     *
251
     * @param int $dirId
252
     * @return integer
253
     */
254
    public function countSubDirs($dirId) {
255
256
        $crSubDir = new \CriteriaCompo();
257
        $crSubDir->add(new \Criteria('parent_id', $dirId));
258
259
        return $this->getCount($crSubDir) ;
260
261
    }
262
263
    /**
264
     * Count files in given directory
265
     *
266
     * @param string $fullpath
267
     * @return integer
268
     */
269
    public function countFiles($fullpath) {
270
        $file_new = [];
271
        $path = \WGFILEMANAGER_REPO_PATH . $fullpath;
272
        if (!\file_exists($path)) {
273
            return -1;
274
        }
275
        $files = scandir($path);
276
        for($i = 0 ; $i < count($files) ; $i++){
0 ignored issues
show
Performance Best Practice introduced by
It seems like you are calling the size function count() as part of the test condition. You might want to compute the size beforehand, and not on each iteration.

If the size of the collection does not change during the iteration, it is generally a good practice to compute it beforehand, and not on each iteration:

for ($i=0; $i<count($array); $i++) { // calls count() on each iteration
}

// Better
for ($i=0, $c=count($array); $i<$c; $i++) { // calls count() just once
}
Loading history...
277
            if(\is_file($path .  DS . $files[$i]) && $files[$i] !='.' && $files[$i] !='..'  && $files[$i] !='index.php'  && $files[$i] !='index.html') {
278
                $file_new[] = $files[$i];
279
            }
280
        }
281
282
        return count($file_new);
283
    }
284
285
    /**
286
     * Delete data from all subdirectories from given directory
287
     *
288
     * @param int $dirId
289
     * @return boolean
290
     */
291
    public function deleteSubDirData($dirId) {
292
293
        $crSubDir = new \CriteriaCompo();
294
        $crSubDir->add(new \Criteria('parent_id', $dirId));
295
        if ($this->getCount($crSubDir) > 0) {
296
            $directoryAll = $this->getAll($crSubDir);
297
            foreach (\array_keys($directoryAll) as $i) {
298
                if (!$this->deleteSubDirData($i)) {
299
                    return false;
300
                }
301
            }
302
        }
303
        $directoryObj = $this->get($dirId);
304
        if (\is_object($directoryObj) && !$this->delete($directoryObj)) {
305
            return false;
306
        }
307
308
        return true;
309
310
    }
311
312
    /**
313
     * Move directory
314
     *
315
     * @param string $pathSource
316
     * @param string $pathDest
317
     * @return boolean
318
     */
319
    public function moveDirectory($pathSource, $pathDest) {
320
321
        if(!FilesManagement::rcopy(\WGFILEMANAGER_REPO_PATH . $pathSource, \WGFILEMANAGER_REPO_PATH . $pathDest)){
322
            return false;
323
        }
324
        if (!FilesManagement::deleteDirectory(\WGFILEMANAGER_REPO_PATH . $pathSource)) {
325
            return false;
326
        }
327
328
        return true;
329
    }
330
331
    /**
332
     * Returns an array directories
333
     *
334
     * @param int $dirId
335
     * @param int $dirCurrent
336
     * @param int $levelCurrent
337
     * @return array
338
     */
339
    public function getDirList($dirId, $dirCurrent, $levelCurrent = 0) {
340
341
        $result = [];
342
/*        if (0 === $dirId) {
343
            $result[0]['id'] = 0;
344
            $result[0]['parent_id'] = 0;
345
            $result[0]['name'] = \_MA_WGFILEMANAGER_DIRECTORY_HOME;
346
            $result[0]['state'] = 0 === $dirCurrent ? 'open' : 'closed';
347
            $result[0]['class'] = 'home';
348
            $result[0]['level'] = 0;
349
            $crSubDir = new \CriteriaCompo();
350
            $crSubDir->add(new \Criteria('parent_id', $dirId));
351
            $result[0]['count_subdirs'] = $this->getCount($crSubDir);
352
            $result[0]['count_files'] = $this->countFiles('');
353
            $result[0]['subdirs'] = [];
354
        }*/
355
        $levelCurrent++;
356
        $crSubDir = new \CriteriaCompo();
357
        $crSubDir->add(new \Criteria('parent_id', $dirId));
358
        $crSubDir->setSort('weight ASC, id');
359
        $crSubDir->setOrder('ASC');
360
        if ($this->getCount($crSubDir) > 0) {
361
            $directoryAll = $this->getAll($crSubDir);
362
            foreach (\array_keys($directoryAll) as $i) {
363
                $directory = $directoryAll[$i]->getValuesDir();
364
                $result[$i]['id'] = $directory['id'];
365
                $result[$i]['parent_id'] = $directory['parent_id'];
366
                $result[$i]['name'] = $directory['name'];
367
                $result[$i]['state'] = $i === $dirCurrent ? 'open' : 'closed';
368
                $result[$i]['count_subdirs'] = $directory['count_subdirs'];
369
                $result[$i]['count_files'] = $directory['count_files'];
370
                $result[$i]['level'] = $levelCurrent;
371
                if ($directory['count_subdirs'] > 0) {
372
                                        $result[$i]['subdirs'] = $this->getDirList($i, $dirCurrent, $levelCurrent);
373
                }
374
            }
375
        }
376
377
        return $result;
378
379
    }
380
381
    /**
382
     * Returns an array directories for form select
383
     *
384
     * @param int $dirId
385
     * @return array
386
     */
387
    public function getDirListFormSelect($dirId) {
388
389
        $result = [];
390
        $crSubDir = new \CriteriaCompo();
391
        $crSubDir->add(new \Criteria('parent_id', $dirId));
392
        $crSubDir->setSort('weight ASC, id');
393
        $crSubDir->setOrder('ASC');
394
        if ($this->getCount($crSubDir) > 0) {
395
            $directoryAll = $this->getAll($crSubDir);
396
            foreach (\array_keys($directoryAll) as $i) {
397
                $directory = $directoryAll[$i]->getValuesDir();
398
                $name = $directory['name'];
399
                if ($dirId > 0) {
400
                    $level = \mb_substr_count($directory['fullpath'], '\\');
401
                    $name = \str_repeat('- ', $level) . $name;
402
                }
403
                $result[$i] = [$directory['id'] => $name];
404
                if ($directory['count_subdirs'] > 0) {
405
                    $result[$i][]= $this->getDirListFormSelect($i);
406
                }
407
            }
408
        }
409
410
        return $result;
411
    }
412
413
    /**
414
     * Returns an array directories for breadcrumbs
415
     *
416
     * @param int $dirId
417
     * @return array
418
     */
419
    public function getDirListBreadcrumb($dirId) {
420
421
        $result = [];
422
        do {
423
            $dirObj = $this->get($dirId);
424
            $result[$dirId] = $dirObj->getVar('name');
425
            $dirId = $dirObj->getVar('parent_id');
426
        } while ($dirId > 0);
427
428
        return $result;
429
    }
430
431
}
432