/
Filesystem.php
1399 lines (1210 loc) · 40.5 KB
/
Filesystem.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/*
* Ionitium - Full-stack PHP framework
*
* @package Ionitium
* @copyright Copyright (C) 2015-2016 with MIT license
* @version 1.0.0
* @author Marin Sagovac <marin@sagovac.com>
*/
namespace Ionitium\Filesystem;
use Ionitium\Filesystem\FileNotFoundException;
use Ionitium\Filesystem\Filesysteminfo;
use RecursiveDirectoryIterator;
use RecursiveIteratorIterator;
use IteratorIterator;
use DirectoryIterator;
use Exception;
/**
* The filesystem functions allows to access and use filesystem
*
* @author Marin Sagovac <marin@sagovac.com>
* @todo ini set file upload
* @version 1.0.0
*/
class Filesystem
{
const UPLOAD_ERR_OK = 0;
const UPLOAD_ERR_INI_SIZE = 1;
const UPLOAD_ERR_FORM_SIZE = 2;
const UPLOAD_ERR_NO_TMP_DIR = 6;
const UPLOAD_ERR_CANT_WRITE = 7;
const UPLOAD_ERR_EXTENSION = 8;
const UPLOAD_ERR_PARTIAL = 3;
// Most common chmod filters
const CHMOD_OWNER_RW_OTHER_NONE = 0600;
const CHMOD_600 = 0600;
const CHMOD_755 = 0755;
/**
* Constructor
*/
public function __construct() {}
/**
* Makes directory
*
* Create a directory using chmod attribute and context
*
* @param string $directory The directory path
* @param int $mode Chmod mode
* @param string $context Context stream
* @return boolean
* @throws \Exception Throws error on creating a directory
* @throws \RuntimeException
*/
public function mkdir($directory, $mode = 0755, $context = null)
{
if (!$directory) {
throw new \Exception('Directory should be set');
}
if ($this->isExists($directory)) {
return true;
}
if (!is_null($context)) {
$context_res = $context;
}
if (stristr($directory, "/") || stristr($directory, "\\")) {
if (stristr($directory, "\\")) {
$mode = null;
}
$recursive = true;
}
else {
$recursive = false;
}
if (!is_null($context)) {
$result = @mkdir($directory, $mode, $recursive, $context);
}
else {
$result = @mkdir($directory, $mode, $recursive);
}
@chmod($directory, $mode);
if (!$result) {
if (!is_dir($directory)) {
throw new \RuntimeException(sprintf('Error on create directory: %s', $directory));
}
}
return true;
}
/**
* Create a file or set access time
*
* Set access time or create a file
*
* @param string $file Filepath
* @param int $time Time in seconds (like time() + 3600) Default is current time
* @param int $atime Set access time (fileatime)
* @throws \RuntimeException Throws not modified a file
*/
public function touch($file, $time = null, $atime = null)
{
if ($time || $atime) {
if (is_null($time)) {
$time = time();
}
if (!is_null($atime)) {
$touch = touch($file, $time, $atime);
} else {
$touch = touch($file, $time);
}
} else {
$touch = touch($file);
}
clearstatcache();
if (!$touch) {
throw new \RuntimeException('Could not change a modification touch a file %s', $file);
} else {
return true;
}
}
/**
* Touch a file without change an owner
*
* Change a file state that is changed by owner
*
* @param string $file Filepath
*/
public function touchWithoutOwnerSet($file)
{
@exec('touch '.escapeshellarg($file));
clearstatcache();
}
/**
* Touch a file using fopen
*
* In some case if you can't use touch
*
* @param string $file File destination
* @throws \RuntimeException Throws if no files found
*/
public function touchAlternate($file)
{
if (!file_exists($file)) {
throw new \RuntimeException(sprintf('No file to handle touch %s', $file));
}
$fp = fopen($file, 'w+');
fclose($fp);
}
/**
* Remove a file or folder from path
*
* Remove a file or directory, remove safe delete to overwrite a file
*
* @param string $path Remove a file or folder
* @param bool $safedelete Overwrite to a file then delete
* @throws \RuntimeException
*/
public function remove($path, $safedelete = false)
{
if (!is_dir($path)) {
if (!static::removeFile($path, $safedelete)) {
throw new \RuntimeException(sprintf('Could not remove a file %s', $path));
}
} else {
if (!@rmdir($path)) {
throw new \RuntimeException(sprintf('Could not remove a folder %s', $path));
}
}
}
/**
* Copy recursive file and folder
*
* Options streamCopy or native copy
* Use copy() by default
*
* @param string $source Source filepath
* @param string $destination Destination filepath
* @param bool $streamCopy Use stream_copy_to_stream() instead copy()
*/
public function copy($source, $destination, $streamCopy = false)
{
if (!is_dir($source)) {
throw new \RuntimeException(sprintf("No folder to copy from source %s", $source));
}
$dir = opendir($source);
@mkdir($destination);
while(false !== ( $file = readdir($dir)) ) {
if (($file != '.') && ($file != '..')) {
if ( is_dir($source . '/' . $file) ) {
$this->copy($source . '/' . $file,$destination . '/' . $file);
}
else {
if (!$streamCopy) {
copy($source . '/' . $file,$destination . '/' . $file);
} else {
$streamSource = @fopen($source. '/' . $file, 'r');
$streamDestination = @fopen($destination. '/' . $file, 'w+');
stream_copy_to_stream($streamSource, $streamDestination);
fclose($streamSource);
fclose($streamDestination);
}
}
}
}
closedir($dir);
}
/**
* Check if file or directory exists
*
* Returns true if file_exists()
*
* @param string $path A filepath
* @return boolean Returns boolean if exists file or directory
*/
public function isExists($path)
{
if (!file_exists($path)) {
return false;
}
return true;
}
/**
* Check if any file exists in folder recursive or get lists of files
*
* Returns bool if exists any files or get an arrays lists files
*
* @param string $directory A root of directory to find a files recursive
* @param bool $returnFiles Show lists of files as array
* @return bool|array
*/
public function isExistsAnyFile($directory, $returnFiles = false)
{
$lists = array();
if (is_dir($directory)) {
$opendir = opendir($directory);
if ($opendir) {
foreach (new RecursiveIteratorIterator(new RecursiveDirectoryIterator($directory)) as $key=>$val)
{
if ($val->isFile()) {
if ($returnFiles) {
$lists[] = $val->getPathName();
} else {
closedir($opendir);
return true;
}
}
}
closedir($opendir);
if ($returnFiles) {
return $lists;
}
}
}
return false;
}
/**
* Get files inside directory non-recursive or recursive
*
* Default is recursive find files
* Returns only files available recursive or by root only
*
* @param string $directory Set a path of scan directory
* @param bool $recursive By default is true to search files recursive, false for root scan files only
* @return string|array
*/
public function getFiles($directory, $recursive = true) {
if (is_dir($directory)) {
$ds = DIRECTORY_SEPARATOR;
$files_root = array();
$root = scandir($directory);
foreach ($root as $value)
{
if ($value === '.' || $value === '..') {
continue;
}
if (is_file("$directory".$ds."$value")) {
$result[] = "$directory/$value";
$files_root[] = "$directory/$value";
continue;
}
if ($recursive) {
foreach($this->getFiles("$directory".$ds."$value") as $value) {
$result[] = $value;
}
}
}
if (!$recursive) {
return $files_root;
}
return $result;
} else {
return $directory;
}
}
/**
*
* Check is directory exists with file permission to check is directory
*
* checkbypermission is false by default, if is 'true' it will check fileperms
* (0x4000) to check if is really directory by file pemission on unix
*
* @param string $directory A directory to check if exists
* @param bool $checkbypermission Use fileperms() to check is directory
* @return bool
*/
public function isDirectory($directory, $checkbypermission = false)
{
if (is_dir($directory)) {
return true;
}
if ($checkbypermission) {
if (@(fileperms("$directory") & 0x4000) == 0x4000) {
return true;
} else {
return false;
}
}
return false;
}
/**
* Changes file mode
*
* Set chmod for a pathname
*
* @param string $path A pathname
* @param int $mode Chmod decimal 0644 or octal 511 (0755) or "rwxsSxtT" type
* @param bool $force If error chmod supress error
* @param bool $skipOnFalse If error on chmod don't show error
* @return boolean
* @throws \RuntimeException
*/
public function setChmod($path, $mode, $force = true, $skipOnFalse = false)
{
if (preg_match('/^[drwxsStT\-]*$/i', $mode))
{
$permissions = $mode;
$modeRes = 0;
if ($permissions[1] == 'r') $modeRes += 0400;
if ($permissions[2] == 'w') $modeRes += 0200;
if ($permissions[3] == 'x') $modeRes += 0100;
else if ($permissions[3] == 's') $modeRes += 04100;
else if ($permissions[3] == 'S') $modeRes += 04000;
if ($permissions[4] == 'r') $modeRes += 040;
if ($permissions[5] == 'w') $modeRes += 020;
if ($permissions[6] == 'x') $modeRes += 010;
else if ($permissions[6] == 's') $modeRes += 02010;
else if ($permissions[6] == 'S') $modeRes += 02000;
if ($permissions[7] == 'r') $modeRes += 04;
if ($permissions[8] == 'w') $modeRes += 02;
if ($permissions[9] == 'x') $modeRes += 01;
else if ($permissions[9] == 't') $modeRes += 01001;
else if ($permissions[9] == 'T') $modeRes += 01000;
$modeOutput = sprintf('%d', $modeRes);
}
else
{
if (!is_numeric($mode)) {
throw new \Exception("Mode must be CHMOD defined as 644 or 666 integer value");
}
$modeOutput = $mode;
}
if (is_dir($path) || is_file($path))
{
if ($force) {
if (@chmod($path, $modeOutput)) {
return true;
} else {
if (!$skipOnFalse) {
throw new \RuntimeException(sprintf("Not chmod a path %s in mode %s", $path, $mode));
}
}
}
else {
if (chmod($path, $modeOutput)) {
return true;
} else {
if (!$skipOnFalse) {
throw new \RuntimeException(sprintf("Not chmod a path %s in mode %s", $path, $mode));
}
}
}
}
else
{
throw new \RuntimeException(sprintf("No file or folder in %s on mode", $path, $mode));
}
}
/**
* Changes file mode separated by file chmod and directory chmod
*
* Set a chmod for file, link and directory recursive
*
* @param string $path A pathname
* @param int $modeFile Chmod a file decimal 0666 or octal 511 (0755) or "rwxsSxtT" type
* @param int $modeDirectory Chmod a directory decimal 0666 or octal 511 (0755) or "rwxsSxtT" type
* @param bool $force If error chmod supress error
* @param bool $skipOnFalse If error on chmod don't show error
* @return boolean
* @throws \RuntimeException
*/
public function setChmodRecursive($path, $modeFile, $modeDirectory = null, $force = true, $skipOnFalse = false)
{
if (is_dir($path)) {
$iter = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($path, RecursiveDirectoryIterator::SKIP_DOTS),
RecursiveIteratorIterator::SELF_FIRST,
RecursiveIteratorIterator::CATCH_GET_CHILD // Ignore "Permission denied"
);
foreach ($iter as $val)
{
if ($val->isFile()) {
$this->setChmod($val->getPathName(), $modeFile, $force, $skipOnFalse);
}
if ($val->isDir()) {
$this->setChmod($val->getPathName(), $modeFile, $force, $skipOnFalse);
}
}
}
else if (is_file($path))
{
$this->setChmod($path, $modeFile, $force, $skipOnFalse);
}
else
{
throw new \RuntimeException(sprintf("No file or folder in %s on mode file %s and directory %s", $path, $modeFile, $modeDirectory));
}
}
/**
* Changes file group
*
* Change group of file and directory or a link
* Set a group like name or GUID (ex: 1000)
*
* @param string $path Path to the file
* @param string $user A group name or number
* @param bool $recursive Recursive set a group
* @return bool State of changes
* @throws \RuntimeException
*/
public function setChgrp($path, $user, $recursive = false)
{
$state = false;
if ($recursive)
{
$iter = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($path, RecursiveDirectoryIterator::SKIP_DOTS),
RecursiveIteratorIterator::SELF_FIRST,
RecursiveIteratorIterator::CATCH_GET_CHILD // Ignore "Permission denied"
);
foreach ($iter as $val)
{
if (is_link($val->getPathName())) {
if (!lchgrp($path, $user)) {
throw new Exception(sprintf("Can not change file owner for link %s with user %s", $path, $user));
}
$state = true;
} else if ($val->isFile()) {
if (!chgrp($path, $user)) {
throw new Exception(sprintf("Can not change file owner for file %s with user %s", $path, $user));
}
$state = true;
}
}
}
else
{
if (is_link($path)) {
if (!lchgrp($path, $user)) {
throw new Exception(sprintf("Can not change file owner for link %s with user %s", $path, $user));
}
$state = true;
} else if (is_file($path)) {
if (!chgrp($path, $user)) {
throw new Exception(sprintf("Can not change file owner for file %s with user %s", $path, $user));
}
$state = true;
}
}
clearstatcache();
return $state;
}
/**
* Change file owner
*
* Change a file owner to filepath
*
* @param string $path Path to the file
* @param string $user A file owner name or number UID
* @param bool $recursive Recursive set a group
* @return bool State of changes
* @throws \RuntimeException
*/
public function setChown($path, $user, $recursive = false)
{
$state = false;
if ($recursive)
{
$iter = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($path, RecursiveDirectoryIterator::SKIP_DOTS),
RecursiveIteratorIterator::SELF_FIRST,
RecursiveIteratorIterator::CATCH_GET_CHILD // Ignore "Permission denied"
);
foreach ($iter as $val)
{
if (is_link($val->getPathName())) {
if (!@lchown($path, $user)) {
throw new \Exception(sprintf("Can not change file owner for link %s with user %s", $path, $user));
}
$state = true;
} else if ($val->isFile()) {
if (!@chown($path, $user)) {
throw new \Exception(sprintf("Can not change file owner for file %s with user %s", $path, $user));
}
$state = true;
}
}
}
else
{
if (is_link($path)) {
if (!lchown($path, $user)) {
throw new Exception(sprintf("Can not change file owner for link %s with user %s", $path, $user));
}
$state = true;
} else if (is_file($path)) {
if (!chown($path, $user)) {
throw new Exception(sprintf("Can not change file owner for file %s with user %s", $path, $user));
}
$state = true;
}
}
return $state;
}
/**
* Rename a file or folder
*
* @param string $from A filepath remove
* @param string $to A new filename
* @throws \RuntimeException A throw of failed to rename()
*/
public function rename($from, $to)
{
if (!rename($from, $to)) {
throw new \RuntimeException(sprintf("Failed to rename from %s to %s", $from, $to));
}
}
/**
* Return info about a user by user id
*
* Return as owner id
*
* @param string $file A pathname
* @return string Returns name of the name
*/
public function getFileOwner($file)
{
$uid = stat($file);
return posix_getpwuid($uid['uid']);
}
/**
* Return info about a user name
*
* Return as owner user
*
* @param string $file A pathname
* @return string Returns file owner name
*/
public function getFileOwnerName($file)
{
$uid = stat($file);
$posix = posix_getpwuid($uid['uid']);
return $posix['name'];
}
/**
* Get last access time of file
*
* Returns unix timestamp of file access time
*
* @param string $file A pathname
* @return int Returns unix timestamp
* @throws RuntimeException Exception that not file exists
*/
public function getLastAccessTime($file)
{
if (!file_exists($file)) {
throw new \RuntimeException(sprintf("No file on %s", $file));
}
return fileatime($file);
}
/**
* Read a file
*
* Read a file using fopen as regular or binary mode, buffer can change
*
* @param string $file File path
* @param bool $binary By default false is not set to binary
* @param int $length A length of buffer reading a file, default false
* @return string Returns a data form a readed file
* @throws RuntimeException
*/
public function readFile($file, $binary = false, $length = false)
{
if (is_dir($file)) {
throw new \RuntimeException(sprintf("Cannot read file should not be folder", $file));
}
if (is_link($file)) {
throw new \RuntimeException(sprintf("Cannot read file should not be symbolic link", $file));
}
if (!file_exists($file)) {
throw new \RuntimeException(sprintf("A file %s does not exists", $file));
}
if (!is_readable($file)) {
throw new \RuntimeException(sprintf("A file %s can not read", $file));
}
if (!is_integer($length) && $length !== false) {
throw new \RuntimeException(sprintf('A length "%s" should be integer type', $length));
}
if ($binary) {
$fp = fopen($file, "rb");
} else {
$fp = fopen($file, "r");
}
if (!$fp) {
throw new \RuntimeException(sprintf("A file cannot open using fopen() %s", $file));
}
$curr = false;
if ($length) {
if ($length === 1) {
return '';
}
while (($current_line = fgets($fp, $length)) !== false) {
$curr .= $current_line;
}
} else {
while (($current_line = fgets($fp)) !== false) {
$curr .= $current_line;
}
}
fclose($fp);
return $curr;
}
/**
* Prepend a data to a file
*
* Append a data on top of file
*
* @param string $file File path
* @param string $content Content to prepend
* @param int $buffer Buffer in bytes, default 512 bytes
*/
public function writeFilePrepend($file, $content, $buffer = 512)
{
$fhandle = fopen($file, 'r');
$read = null;
$fhandlePrepend = fopen($file.'_prepend', 'w');
fwrite($fhandlePrepend, $content);
while (!feof($fhandle)) {
$read .= fread($fhandle, $buffer);
fwrite($fhandlePrepend, $read);
}
fclose($fhandle);
fclose($fhandlePrepend);
unlink($file);
clearstatcache();
rename($file.'_prepend', $file);
}
/**
* Append a data to a file
*
* If file not exists it will create
*
* @param string $file File path
* @param string $content Content to9 append end of file
* @param int $buffer Buffer in bytes, default is false
*/
public function writeFileAppend($file, $content, $buffer = false)
{
$fhandle = fopen($file, 'a+');
if ($buffer !== false) {
fwrite($fhandle, $content, $buffer);
} else {
fwrite($fhandle, $content);
}
fclose($fhandle);
}
/**
* Write a new file, overwrite if exists
*
* Writing only. If exists, truncate content
*
* @param string $file File path
* @param string $content Content
* @param int $buffer Buffer in bytes, default is false
*/
public function writeFile($file, $content, $buffer = false)
{
$fhandle = fopen($file, 'c');
if (!$buffer) {
fwrite($fhandle, $content);
} else {
fwrite($fhandle, $content, strlen($content));
}
fclose($fhandle);
}
/**
* Create a non-exists file then close
*
* Create a file if not exists, open read-only mode and close a file
*
* @param string $file File path
* @return boolean Returns if action executed successfully
*/
public function createFileAndClose($file)
{
if (!is_file($file)) {
fclose(fopen($file, 'x'));
return true;
} else return false;
}
/**
* Tells whether the filename is writable
*
* Check if file exists and if a file is writeable
*
* @param string $filename A filepath
* @return bool Returns is writeable
* @throws RuntimeException Throw exception if is not writeable or exists a file
*/
public function isWriteable($filename)
{
if (!file_exists($filename)) {
throw new \RuntimeException(sprintf("A file cannot find %s", $filename));
}
if (!is_writable($filename)) {
throw new \RuntimeException(sprintf("A file cannot find %s", $filename));
} else {
return true;
}
}
/**
* FileSystem class
*
* Instance FilesystemInfo
*
* @param string $source A filepath
* @return Filesysteminfo object
*/
public function getFileSystemInfo($source)
{
return new Filesysteminfo($source);
}
/**
* Generate 128 bits of random data
*
* Generate truly random 128 bit random data in a form xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
*
* @see http://tools.ietf.org/html/rfc4122#section-4.4
* @return string
*/
public function getGuid()
{
$data = openssl_random_pseudo_bytes(16);
$data[6] = chr( ord( $data[6] ) & 0x0f | 0x40 ); // set version to 0100
$data[8] = chr( ord( $data[8] ) & 0x3f | 0x80 ); // set bits 6-7 to 10
return vsprintf( '%s%s-%s-%s-%s-%s%s%s', str_split( bin2hex( $data ), 4 ) );
}
/**
* Truncate a file
*
* Truncate using ftruncate() function
*
* @param string $file A filename
*/
public function emptyFile($file)
{
if (!file_exists($file)) {
throw new \Exception(sprintf('No file exists %s', $file));
}
$handle = fopen($file, 'w');
ftruncate($handle, 0);
fclose($handle);
}
/**
* Tells whether the filename is a symbolic link
*
* Check is filepath symbolic link
*
* @param string $source A symbolic path
* @return bool Is symbolic link
* @throws Exception If no exists file or directory
*/
public function isSymbolicLink($source)
{
if (!file_exists($source) || is_dir($source)) {
throw new \Exception(sprintf('No source is path is defined or is not a file %s', $source));
}
return is_link($source);
}
/**
* Moves an uploaded file to a new location
*
* Move a filepath to destination. If overwrite is set to true by default,
* it will rewrite uploaded destination file
*
* @param string $filename The filename of the uploaded file
* @param string $destination The destination of the moved file
* @param bool $overwrite If exists skip overwrite
* @return boolean If exists returns true if exists otherwise move upload file boolean state
*/
public function uploadFile($filename, $destination, $overwrite = true)
{
if (!$overwrite) {
if (file_exists($destination)) {
return true;
}
}
return move_uploaded_file($filename, $destination);
}
/**
* Create a hard link
*
* Create identically link from source. linkinfo() returns 2049 link state
*
* @param string $source Target of the link
* @param string $target The link name
* @return boolean Returns link() state
* @throws Exception If not exists a file or is directory throws error
*/
public function createHardLink($source, $target)
{
if (!file_exists($source) || is_dir($source)) {
throw new \Exception(sprintf('No source is path is defined %s', $source));
}
return link($source, $target);
}
/**
* Creates a symbolic link
*
* Create soft link, a symbolic link from source to target
*
* @param string $source Target of the link
* @param string $link The link name
* @return boolean Retruns if symlink created
*/
public function createSymbolicLink($source, $link)
{
if (is_link($link) && is_file($link)) {
throw new Exception(sprintf("A symbolic link is already set %s", $link));
}
return symlink($source, $link);
}
/**
* Returns the target of a symbolic link
*
* Returns the target filepath of symbolic or hard link
*
* @return boolean Returns filepath
*/
public function getLinkTarget($path)
{
return readlink($path);
}
/**
* Create file with unique file name
*
* Create a temporary file automatically into temporary directory with/without content.
* Can be set a prefix into filename temporary file.
*
* @param string $directory Directory to crate temporary path, if not set use sys_get_temp_dir like "/tmp"
* @param string $prefix The prefix generated in filename
* @param string $content The content in a path
* @return string Returns a filename
*/
public function createFileAutoUnique($directory = null, $prefix = null, $content = '')
{
if (is_null($directory)) {
$directory = sys_get_temp_dir();
}
$tmpfname = tempnam($directory, $prefix);
if ($content !== null) {
$handle = fopen($tmpfname, "w");
fwrite($handle, $content);
fclose($handle);