Passed
Push — master ( 8a5673...b078ef )
by Goffy
03:36
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('/', $path);
143
        \krsort($pathArray);
144
145
        return \implode('/', \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 .= '/' . $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
        FilesManagement::createFolder(\WGFILEMANAGER_REPO_PATH . $path);
187
188
    }
189
190
    /**
191
     * Rename directory
192
     *
193
     * @param string $oldDirname
194
     * @param string $newDirname
195
     * @return boolean
196
     */
197
    public function renameDirectory($oldDirname, $newDirname)
198
    {
199
        $oldFilePath = \WGFILEMANAGER_REPO_PATH . $oldDirname;
200
        $newFilePath = \WGFILEMANAGER_REPO_PATH . $newDirname;
201
202
        if (\file_exists($oldFilePath)) {
203
            if (!\file_exists($newFilePath)) {
204
                return \rename($oldFilePath, $newFilePath);
205
            } else {
206
                throw new \Exception('New filename already exists.');
207
            }
208
        } else {
209
            throw new \Exception('Old file does not exist.');
210
        }
211
    }
212
213
    /**
214
     * Delete directory from given path
215
     *
216
     * @param string $path
217
     * @return boolean
218
     */
219
    public function deleteDirectory($path)
220
    {
221
        $fullPath = \WGFILEMANAGER_REPO_PATH . $path;
222
223
        if (!FilesManagement::deleteDirectory($fullPath)) {
224
            return false;
225
        }
226
227
        return !$this->existDirectory($fullPath);
228
229
    }
230
231
    /**
232
     * Check whether given directory is used as parent
233
     *
234
     * @param int $dirId
235
     * @return boolean
236
     */
237
    public function dirIsParent ($dirId) {
238
        $crCountDirectory = new \CriteriaCompo();
239
        $crCountDirectory->add(new \Criteria('parent_id', $dirId));
240
241
        return $this->getCount($crCountDirectory) > 0;
242
243
    }
244
245
    /**
246
     * Count subdirectories from given directory
247
     *
248
     * @param int $dirId
249
     * @return integer
250
     */
251
    public function countSubDirs($dirId) {
252
253
        $crSubDir = new \CriteriaCompo();
254
        $crSubDir->add(new \Criteria('parent_id', $dirId));
255
256
        return $this->getCount($crSubDir) ;
257
258
    }
259
260
    /**
261
     * Count files in given directory
262
     *
263
     * @param string $fullpath
264
     * @return integer
265
     */
266
    public function countFiles($fullpath) {
267
        $file_new = [];
268
        $path = \WGFILEMANAGER_REPO_PATH . $fullpath;
269
        if (!\file_exists($path)) {
270
            return -1;
271
        }
272
        $files = scandir($path);
273
        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...
274
            if(\is_file($path .  '/' . $files[$i]) && $files[$i] !='.' && $files[$i] !='..'  && $files[$i] !='index.php'  && $files[$i] !='index.html') {
275
                $file_new[] = $files[$i];
276
            }
277
        }
278
279
        return count($file_new);
280
    }
281
282
    /**
283
     * Delete data from all subdirectories from given directory
284
     *
285
     * @param int $dirId
286
     * @return boolean
287
     */
288
    public function deleteSubDirData($dirId) {
289
290
        $crSubDir = new \CriteriaCompo();
291
        $crSubDir->add(new \Criteria('parent_id', $dirId));
292
        if ($this->getCount($crSubDir) > 0) {
293
            $directoryAll = $this->getAll($crSubDir);
294
            foreach (\array_keys($directoryAll) as $i) {
295
                if (!$this->deleteSubDirData($i)) {
296
                    return false;
297
                }
298
            }
299
        }
300
        $directoryObj = $this->get($dirId);
301
        if (\is_object($directoryObj) && !$this->delete($directoryObj)) {
302
            return false;
303
        }
304
305
        return true;
306
307
    }
308
309
    /**
310
     * Move directory
311
     *
312
     * @param string $pathSource
313
     * @param string $pathDest
314
     * @return boolean
315
     */
316
    public function moveDirectory($pathSource, $pathDest) {
317
318
        if(!FilesManagement::rcopy(\WGFILEMANAGER_REPO_PATH . $pathSource, \WGFILEMANAGER_REPO_PATH . $pathDest)){
319
            return false;
320
        }
321
        if (!FilesManagement::deleteDirectory(\WGFILEMANAGER_REPO_PATH . $pathSource)) {
322
            return false;
323
        }
324
325
        return true;
326
    }
327
328
    /**
329
     * Returns an array directories
330
     *
331
     * @param int $dirId
332
     * @param int $dirCurrent
333
     * @param int $levelCurrent
334
     * @return array
335
     */
336
    public function getDirList($dirId, $dirCurrent, $levelCurrent = 1) {
337
338
        $result = [];
339
/*        if (0 === $dirId) {
340
            $result[0]['id'] = 0;
341
            $result[0]['parent_id'] = 0;
342
            $result[0]['name'] = \_MA_WGFILEMANAGER_DIRECTORY_HOME;
343
            $result[0]['state'] = 0 === $dirCurrent ? 'open' : 'closed';
344
            $result[0]['class'] = 'home';
345
            $result[0]['level'] = 0;
346
            $crSubDir = new \CriteriaCompo();
347
            $crSubDir->add(new \Criteria('parent_id', $dirId));
348
            $result[0]['count_subdirs'] = $this->getCount($crSubDir);
349
            $result[0]['count_files'] = $this->countFiles('');
350
            $result[0]['subdirs'] = [];
351
        }*/
352
        $levelCurrent++;
353
        $crSubDir = new \CriteriaCompo();
354
        $crSubDir->add(new \Criteria('parent_id', $dirId));
355
        $crSubDir->setSort('weight ASC, id');
356
        $crSubDir->setOrder('ASC');
357
        if ($this->getCount($crSubDir) > 0) {
358
            $directoryAll = $this->getAll($crSubDir);
359
            foreach (\array_keys($directoryAll) as $i) {
360
                $directory = $directoryAll[$i]->getValuesDir();
361
                $result[$i]['id'] = $directory['id'];
362
                $result[$i]['parent_id'] = $directory['parent_id'];
363
                $result[$i]['name'] = $directory['name'];
364
                $result[$i]['state'] = $i === $dirCurrent ? 'open' : 'closed';
365
                $result[$i]['count_subdirs'] = $directory['count_subdirs'];
366
                $result[$i]['count_files'] = $directory['count_files'];
367
                $result[$i]['level'] = $levelCurrent;
368
                if ($directory['count_subdirs'] > 0) {
369
                    $result[$i]['subdirs'] = $this->getDirList($i, $dirCurrent, $levelCurrent);
370
                }
371
            }
372
        }
373
374
        return $result;
375
376
    }
377
378
    /**
379
     * Returns an array directories for form select
380
     *
381
     * @param int $dirId
382
     * @return array
383
     */
384
    public function getDirListFormSelect($dirId) {
385
386
        $result = [];
387
        $crSubDir = new \CriteriaCompo();
388
        $crSubDir->add(new \Criteria('parent_id', $dirId));
389
        $crSubDir->setSort('weight ASC, id');
390
        $crSubDir->setOrder('ASC');
391
        if ($this->getCount($crSubDir) > 0) {
392
            $directoryAll = $this->getAll($crSubDir);
393
            foreach (\array_keys($directoryAll) as $i) {
394
                $directory = $directoryAll[$i]->getValuesDir();
395
                $name = $directory['name'];
396
                if ($dirId > 0) {
397
                    $level = \mb_substr_count($directory['fullpath'], '/');
398
                    $name = \str_repeat('- ', $level) . $name;
399
                }
400
                $result[$i] = [$directory['id'] => $name];
401
                if ($directory['count_subdirs'] > 0) {
402
                    $result[$i][]= $this->getDirListFormSelect($i);
403
                }
404
            }
405
        }
406
407
        return $result;
408
    }
409
410
    /**
411
     * Returns an array directories for breadcrumbs
412
     *
413
     * @param int $dirId
414
     * @return array
415
     */
416
    public function getDirListBreadcrumb($dirId) {
417
418
        $result = [];
419
        do {
420
            $dirObj = $this->get($dirId);
421
            if ($dirId > 1) {
422
                $result[$dirId] = $dirObj->getVar('name');
423
            }
424
            $dirId = $dirObj->getVar('parent_id');
425
        } while ($dirId > 0);
426
427
        return $result;
428
    }
429
430
    /**
431
     * Returns an array directories
432
     *
433
     * @param int $dirId
434
     * @return array
435
     */
436
    public function getSubDirList($dirId) {
437
438
        $result = [];
439
        $crSubDir = new \CriteriaCompo();
440
        $crSubDir->add(new \Criteria('parent_id', $dirId));
441
        $crSubDir->setSort('weight ASC, id');
442
        $crSubDir->setOrder('ASC');
443
        if ($this->getCount($crSubDir) > 0) {
444
            $directoryAll = $this->getAll($crSubDir);
445
            foreach (\array_keys($directoryAll) as $i) {
446
                $directory = $directoryAll[$i]->getValuesDir();
447
                $result[$i]['id'] = $directory['id'];
448
                $result[$i]['parent_id'] = $directory['parent_id'];
449
                $result[$i]['name'] = $directory['name'];
450
                $result[$i]['count_subdirs'] = $directory['count_subdirs'];
451
                $result[$i]['count_files'] = $directory['count_files'];
452
                $result[$i]['ctime_text'] = \formatTimestamp($directory['date_created'], 's');
453
            }
454
        }
455
456
        return $result;
457
458
    }
459
460
}
461