-
Notifications
You must be signed in to change notification settings - Fork 22
/
CFile.php
1396 lines (1227 loc) · 48.6 KB
/
CFile.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
/**
* CFile provides common methods to manipulate filesystem objects (files and
* directories) from Yii Framework (http://www.yiiframework.com).
*
* Please use CFileHelper class to access CFile functionality if not using Yii.
*
* @version 1.0
*
* @author idle sign <[email protected]>
* @link http://www.yiiframework.com/extension/cfile/
* @copyright Copyright © 2009-2013 Igor 'idle sign' Starikov
* @license LICENSE
*/
/* Exception type raised by CFile. */
class CFileException extends Exception {}
/**
* Base CFile class built to work with Yii.
*/
class CFile extends CApplicationComponent {
/**
* @var array object instances array with key set to $_filepath
*/
private static $_instances = array();
/**
* @var string filesystem object path submitted by user
*/
private $_filepath;
/**
* @var string real filesystem object path figured by script on the basis of $_filepath
*/
private $_realpath;
/**
* @var boolean 'True' if filesystem object described by $_realpath exists
*/
private $_exists;
/**
* @var boolean 'True' if filesystem object described by $_realpath is a regular file
*/
private $_is_file = False;
/**
* @var boolean 'True' if filesystem object described by $_realpath is a directory
*/
private $_is_dir = False;
/**
* @var boolean 'True' if file described by $_realpath is uploaded
*/
private $_is_uploaded = False;
/**
* @var boolean 'True' if filesystem object described by $_realpath is readable
*/
private $_readable;
/**
* @var boolean 'True' if filesystem object described by $_realpath writeable
*/
private $_writeable;
/**
* @var string basename of the file (e.g.: 'myfile.htm' for '/var/www/htdocs/files/myfile.htm')
*/
private $_basename;
/**
* @var string name of the file (e.g.: 'myfile' for '/var/www/htdocs/files/myfile.htm')
*/
private $_filename;
/**
* @var string directory name of the filesystem object
* (e.g.: '/var/www/htdocs/files' for '/var/www/htdocs/files/myfile.htm')
*/
private $_dirname;
/**
* @var string file extension(e.g.: 'htm' for '/var/www/htdocs/files/myfile.htm')
*/
private $_extension;
/**
* @var string file extension(e.g.: 'text/html' for '/var/www/htdocs/files/myfile.htm')
*/
private $_mime_type;
/**
* Works on Windows System only
* @var integer the time the filesystem object was created (Unix timestamp e.g.: '1213760802')
*/
private $_time_created;
/**
* @var integer the time the filesystem object was last modified (Unix timestamp e.g.: '1213760802')
*/
private $_time_modified;
/**
* @var string filesystem object size formatted (e.g.: '70.4 KB') or in bytes (e.g.: '72081')
* see {@link getSize} parameters
*/
private $_size;
/**
* @var boolean filesystem object has contents flag
*/
private $_is_empty;
/**
* @var int|string filesystem object owner name (e.g.: 'idle') or in ID (e.g.: '1000')
* see {@link getOwner} parameters
*/
private $_owner;
/**
* @var int|string filesystem object group name (e.g.: 'apache') or in ID (e.g.: '127')
* see {@link getGroup} parameters
*/
private $_group;
/**
* @var string filesystem object permissions (considered octal e.g.: '0755')
*/
private $_permissions;
/**
* @var resource file pointer resource (for {@link open} & {@link close})
*/
private $_handle=null;
/**
* @var CUploadedFile object instance
*/
private $_uploaded_inst=null;
/**
* Returns the instance of CFile for the specified file.
*
* @param string $filepath Path to file specified by user.
* @param string $class_name Class name to spawn object for.
* @return object CFile instance
* @throws CFileException
*/
public static function getInstance($filepath, $class_name=__CLASS__) {
if ($class_name!=__CLASS__ && !is_subclass_of($class_name, __CLASS__)) {
throw new CFileException('Unable to spawn CFile object from `' . $class_name . '` class');
}
if (!array_key_exists($filepath, self::$_instances)) {
self::$_instances[$filepath] = new $class_name($filepath);
}
return self::$_instances[$filepath];
}
/**
* Logs a message.
*
* @param string $message Message to be logged
* @param string $level Level of the message (e.g. 'trace', 'warning', 'error', 'info',
* see CLogger constants definitions)
*/
protected function addLog($message, $level='info') {
Yii::log($message.' (obj: ' . $this->getRealPath() . ')', $level, 'ext.file');
}
/**
* Returns filepath for a given alias.
*
* @param string $alias
* @return bool|string
*/
protected function getPathOfAlias($alias) {
return Yii::getPathOfAlias($alias);
}
/**
* Formats a given number into a given format and returns it.
*
* See {@link CNumberFormatter}.
*
* @param number $number
* @param string $format
* @return string
*/
protected function formatNumber ($number, $format) {
return Yii::app()->numberFormatter->format($format, $number);
}
/**
* Basic CFile method. Sets CFile object to work with specified filesystem object.
* Essentially path supplied by user is resolved into real path (see {@link getRealPath}), all the other property
* getting methods should use that real path.
* Uploaded files are supported through {@link CUploadedFile} Yii class.
* Path aliases are supported through {@link getPathOfAlias} Yii method.
*
* @param string $filepath Path to the file specified by user, if not set exception is raised
* @param bool $greedy If True file properties (such as 'Size', 'Owner', 'Permission', etc.) would be autoloaded
* @return object CFile instance for the specified filesystem object
* @throws CFileException
*/
public function set($filepath, $greedy=False) {
if (trim($filepath)!='') {
$uploaded = null;
if (strpos($filepath, '\\')===False && strpos($filepath, '/')===False) {
$uploaded = CUploadedFile::getInstanceByName($filepath);
if ($uploaded) {
$filepath = $uploaded->getTempName();
$this->addLog('File "' . $filepath . '" is identified as uploaded', 'trace');
} elseif ($aliased_path=$this->getPathOfAlias($filepath)) {
$this->addLog('The string supplied to set() - "' . $filepath . '" is identified as the alias to "' . $aliased_path . '"', 'trace');
$filepath = $aliased_path;
}
}
clearstatcache();
$cl = get_class($this);
$realPath = $cl::realPath($filepath);
$inst = $cl::getInstance($realPath);
$inst->_filepath = $filepath;
$inst->_realpath = $realPath;
if ($inst->exists()) {
$inst->_uploaded_inst = $uploaded;
$inst->pathInfo();
$inst->readable;
$inst->writeable;
if ($greedy) {
$inst->isempty;
$inst->size;
$inst->owner;
$inst->group;
$inst->permissions;
$inst->timeModified;
if ($inst->isFile) {
$inst->mimeType;
}
}
}
return $inst;
}
throw new CFileException('Path to filesystem object is not specified within set() method');
}
/**
* Populates basic CFile properties (i.e. 'Dirname', 'Basename', etc.) using values resolved by pathinfo()
* php function.
* Detects filesystem object type (file, directory).
*/
private function pathInfo() {
if (is_file($this->_realpath)) {
$this->_is_file = True;
} elseif (is_dir($this->_realpath)) {
$this->_is_dir = True;
}
if ($this->_uploaded_inst) {
$this->_is_uploaded = True;
}
$pathinfo = pathinfo($this->_is_uploaded ? $this->_uploaded_inst->getName() : $this->_realpath);
$this->_dirname = $pathinfo['dirname'];
$this->_basename = $pathinfo['basename'];
// PHP version < 5.2 workaround
if (!isset($pathinfo['filename'])) {
$this->_filename = substr($pathinfo['basename'], 0, strrpos($pathinfo['basename'], '.'));
} else {
$this->_filename = $pathinfo['filename'];
}
if (array_key_exists('extension', $pathinfo)) {
$this->_extension = $pathinfo['extension'];
} else {
$this->_extension = null;
}
}
/**
* Returns real filesystem object path figured by script (see {@link realPath}) on the basis of user
* supplied $_filepath.
* If $_realpath property is set, returned value is read from that property.
*
* @param string $dir_separator Directory separator char (depends upon OS)
* @return string Real file path
*/
public function getRealPath($dir_separator=DIRECTORY_SEPARATOR) {
if (!isset($this->_realpath)) {
$this->_realpath = $this->realPath($this->_filepath, $dir_separator);
}
return $this->_realpath;
}
/**
* Returns relative filesystem object path figured by script on the basis of $_realpath
*
* @return string Relative file path
*/
public function getRelativePath() {
$current_path = getcwd();
if ($current_path === "/")
{
return $this->_realpath;
}
else if (substr($this->_realpath,0,strlen($current_path)) === $current_path ) {
return substr($this->_realpath,strlen($current_path));
}
else
{
throw new CFileException('Unable to resolve relative path for filesystem object.');
}
}
/**
* Base real filesystem object path resolving method.
* Returns real path resolved from the supplied path.
*
* @param string $supplied_path Path from which real filesystem object path should be resolved
* @param string $dir_separator Directory separator char (depends upon OS)
* @return string Real file path
*/
private function realPath($supplied_path, $dir_separator=DIRECTORY_SEPARATOR) {
$current_path = $supplied_path;
if (!strlen($current_path)) {
return $dir_separator;
}
$win_drive = '';
// Windows OS path type detection
if (!strncasecmp(PHP_OS, 'win', 3)) {
$current_path = preg_replace('/[\\\\\/]/', $dir_separator, $current_path);
if (preg_match('/([a-zA-Z]\:)(.*)/', $current_path, $matches)) {
$win_drive = $matches[1];
$current_path = $matches[2];
} else {
$workingDir = getcwd();
$win_drive = substr($workingDir, 0, 2);
if ($current_path{0}!==$dir_separator{0}) {
$current_path = substr($workingDir, 3) . $dir_separator . $current_path;
}
}
} elseif ($current_path{0}!==$dir_separator) {
$current_path = getcwd() . $dir_separator . $current_path;
}
$paths = array();
foreach (explode($dir_separator, $current_path) as $path) {
if (strlen($path) && $path !== '.') {
if ($path=='..') {
array_pop($paths);
} else {
$paths[] = $path;
}
}
}
$realpath = $win_drive . $dir_separator . implode($dir_separator, $paths);
if ($current_path!=$supplied_path) {
$this->addLog('Path "' . $supplied_path . '" resolved into "' . $realpath . '"', 'trace');
}
return $realpath;
}
/**
* Tests current filesystem object existence and returns boolean (see {@link exists}).
* If $_exists property is set, returned value is read from that property.
*
* @return boolean 'True' if file exists, otherwise 'False'
*/
public function getExists() {
if (!isset($this->_exists)) {
$this->exists();
}
return $this->_exists;
}
/**
* Returns filesystem object type for the current file (see {@link pathInfo}).
* Tells whether filesystem object is a regular file.
*
* @return boolean 'True' if filesystem object is a regular file, otherwise 'False'
*/
public function getIsFile() {
return $this->_is_file;
}
/**
* Returns filesystem object type for the current file (see {@link pathInfo}).
* Tells whether filesystem object is a directory.
*
* @return boolean 'True' if filesystem object is a directory, otherwise 'False'
*/
public function getIsDir() {
return $this->_is_dir;
}
/**
* Tells whether file is uploaded through a web form.
*
* @return boolean 'True' if file is uploaded, otherwise 'False'
*/
public function getIsUploaded() {
return $this->_is_uploaded;
}
/**
* Returns filesystem object has-contents flag.
* Directory considered empty if it doesn't contain descendants.
* File considered empty if its size is 0 bytes.
*
* @return boolean 'True' if file is a directory, otherwise 'False'
*/
public function getIsEmpty() {
if (!isset($this->_is_empty)) {
if (($this->getIsFile() && $this->getSize(False)==0) || (!$this->getIsFile() && count($this->dirContents($this->_realpath))==0 )) {
$this->_is_empty = True;
} else {
$this->_is_empty = False;
}
}
return $this->_is_empty;
}
/**
* Tests whether the current filesystem object is readable and returns boolean.
* If $_readable property is set, returned value is read from that property.
*
* @return boolean 'True' if filesystem object is readable, otherwise 'False'
*/
public function getReadable() {
if (!isset($this->_readable)) {
$this->_readable = is_readable($this->_realpath);
}
return $this->_readable;
}
/**
* Tests whether the current filesystem object is readable and returns boolean.
* If $_writeable property is set, returned value is read from that property.
*
* @return boolean 'True' if filesystem object is writeable, otherwise 'False'
*/
public function getWriteable() {
if (!isset($this->_writeable)) {
$this->_writeable = is_writable($this->_realpath);
}
return $this->_writeable;
}
/**
* Base filesystem object existence resolving method.
* Tests current filesystem object existence and returns boolean.
*
* @return boolean 'True' if filesystem object exists, otherwise 'False'
*/
private function exists() {
$this->addLog('Filesystem object availability test: ' . $this->_realpath, 'trace');
if (file_exists($this->_realpath)) {
$this->_exists = True;
} else {
$this->_exists = False;
}
if ($this->_exists) {
return True;
}
$this->addLog('Filesystem object not found');
return False;
}
/**
* Creates empty file if the current file doesn't exist.
*
* @return CFile|bool Updated the current CFile object on success, 'False' on fail.
*/
public function create() {
if (!$this->getExists()) {
if ($this->open('w')) {
$this->close();
return $this->set($this->_realpath);
}
$this->addLog('Unable to create empty file');
return False;
}
$this->addLog('File creation failed. File already exists');
return False;
}
/**
* Creates empty directory defined either through {@link set} or through the $directory parameter.
*
* @param int|string $permissions Access permissions for the directory
* @param null|string $directory Parameter used to create directory other than supplied by {@link set} method
* of the CFile
* @return bool|CFile Updated the current CFile object on success, 'False' on fail.
*/
public function createDir($permissions=0754, $directory=null) {
if ($directory===null) {
$dir = $this->_realpath;
} else {
$dir = $directory;
}
if (@mkdir($dir, $permissions, True)) {
if (!$directory) {
return $this->set($dir);
} else {
return True;
}
}
$this->addLog('Unable to create empty directory "' . $dir . '"');
return False;
}
/**
* Opens (if not already opened) the current file using certain mode.
* See fopen() php function for more info.
*
* For now used only internally.
*
* @param string $mode Type of access required to the stream
* @return bool|CFile Current CFile object on success, 'False' on fail.
*/
private function open($mode) {
if ($this->_handle===null) {
if ($this->_handle = fopen($this->_realpath, $mode)) {
return $this;
}
$this->addLog('Unable to open file using mode "' . $mode . '"');
return False;
}
return $this;
}
/**
* Closes (if opened) the current file pointer.
* See fclose() php function for more info.
*
* For now used only internally.
*/
private function close() {
if ($this->_handle!==null) {
fclose($this->_handle);
$this->_handle = null;
}
}
/**
* Returns owner of current filesystem object (UNIX systems).
* Returned value depends upon $getName parameter value.
* If $_owner property is set, returned value is read from that property.
*
* @param boolean $get_name Defaults to 'True', meaning that owner name instead of ID should be returned.
* @return int|string|bool Owner name, or ID if $getName set to 'False'
*/
public function getOwner($get_name=True) {
if (!isset($this->_owner)) {
$this->_owner = $this->getExists() ? fileowner($this->_realpath) : null;
}
if (is_int($this->_owner) && function_exists('posix_getpwuid') && $get_name==True) {
$this->_owner = posix_getpwuid($this->_owner);
$this->_owner = $this->_owner['name'];
}
return $this->_owner;
}
/**
* Returns group of current filesystem object (UNIX systems).
* Returned value depends upon $getName parameter value.
* If $_group property is set, returned value is read from that property.
*
* @param boolean $get_name Defaults to 'True', meaning that group name instead of ID should be returned.
* @return int|string|bool Group name, or ID if $getName set to 'False'
*/
public function getGroup($get_name=True) {
if (!isset($this->_group)) {
$this->_group = $this->getExists() ? filegroup($this->_realpath) : null;
}
if (is_int($this->_group) && function_exists('posix_getgrgid') && $get_name==True) {
$this->_group = posix_getgrgid($this->_group);
$this->_group = $this->_group['name'];
}
return $this->_group;
}
/**
* Returns permissions of current filesystem object (UNIX systems).
* If $_permissions property is set, returned value is read from that property.
*
* @return string Filesystem object permissions in octal format (i.e. '0755')
*/
public function getPermissions() {
if (!isset($this->_permissions)) {
$this->_permissions = $this->getExists() ? substr(sprintf('%o', fileperms($this->_realpath)), -4) : null;
}
return $this->_permissions;
}
/**
* Returns size of current filesystem object.
* Returned value depends upon $format parameter value.
* If $_size property is set, returned value is read from that property.
* Uses {@link dirSize} method for directory size calculation.
*
* @param string|bool $format Number format or 'False'
* @return string|int Filesystem object size formatted (e.g.: '70.4 KB') or in bytes (e.g.: '72081') if $format
* set to 'False'
*/
public function getSize($format='0.00'){
if (!isset($this->_size)){
if ($this->getIsFile()) {
$this->_size = $this->getExists() ? sprintf('%u', filesize($this->_realpath)) : null;
} else {
$this->_size = $this->getExists() ? sprintf('%u', $this->dirSize()) : null;
}
}
$size = $this->_size;
if ($format!==False) {
$size = $this->formatFileSize($this->_size, $format);
}
return $size;
}
/**
* Calculates the current directory size recursively fetching sizes of all descendant files.
*
* This method is used internally and only for folders.
* See {@link getSize} method params for detailed information.
*
* @return int
*/
private function dirSize() {
$size = 0;
foreach ($this->dirContents($this->_realpath, True) as $item) {
if (is_file($item)) {
$size += (int)sprintf('%u', filesize($item));
}
}
return $size;
}
/**
* Base filesystem object size format method.
* Converts file size in bytes into human readable format (i.e. '70.4 KB')
*
* @param integer $bytes Filesystem object size in bytes
* @param string $format Number format (see {@link CNumberFormatter})
* @return string Filesystem object size in human readable format
*/
private function formatFileSize($bytes, $format='0.00') {
$units = array('B', 'kB', 'MB', 'GB', 'TB', 'PB');
$bytes = max($bytes, 0);
$expo = floor(($bytes ? log($bytes) : 0) / log(1024));
$expo = min($expo, count($units)-1);
$bytes /= pow(1024, $expo);
return $this->formatNumber($bytes, $format) . ' ' . $units[$expo];
}
/**
* Returns the current file created time. Works on Windows System only!
* Returned Unix timestamp could be passed to php date() function.
*
* @return integer created at time Unix timestamp (e.g.: '1213760802')
*/
public function getTimeCreated() {
if (empty($this->_time_created)) {
$this->_time_created = $this->getExists() ? filectime($this->_realpath) : null;
}
return $this->_time_created;
}
/**
* Returns the current file last modified time.
* Returned Unix timestamp could be passed to php date() function.
*
* @return integer Last modified time Unix timestamp (e.g.: '1213760802')
*/
public function getTimeModified() {
if (empty($this->_time_modified)) {
$this->_time_modified = $this->getExists() ? filemtime($this->_realpath) : null;
}
return $this->_time_modified;
}
/**
* Returns the current file extension from $_extension property set by {@link pathInfo}
* (e.g.: 'htm' for '/var/www/htdocs/files/myfile.htm').
*
* @return string Current file extension without the leading dot
*/
public function getExtension() {
return $this->_extension;
}
/**
* Returns the current file basename (file name plus extension) from $_basename property set by {@link pathInfo}
* (e.g.: 'myfile.htm' for '/var/www/htdocs/files/myfile.htm').
*
* @return string Current file basename
*/
public function getBasename() {
return $this->_basename;
}
/**
* Returns the current file name (without extension) from $_filename property set by {@link pathInfo}
* (e.g.: 'myfile' for '/var/www/htdocs/files/myfile.htm')
*
* @return string Current file name
*/
public function getFilename() {
return $this->_filename;
}
/**
* Returns the current file directory name (without final slash) from $_dirname property set by {@link pathInfo}
* (e.g.: '/var/www/htdocs/files' for '/var/www/htdocs/files/myfile.htm')
*
* @return string Current file directory name
*/
public function getDirname() {
return $this->_dirname;
}
/**
* Returns the current filesystem object contents.
* Reads data from filesystem object if it is a regular file.
* List files and directories inside the specified path if filesystem object is a directory.
*
* @param boolean $recursive If True method would return all directory descendants.
* @param string $filter Filter to be applied to all directory descendants. Could be a string, or an array
* of strings (perl regexp are supported, if started with '~').
* @return string|array|bool Data read for files, or directory contents names array. False on fail.
*/
public function getContents($recursive=False, $filter=null) {
if ($this->getReadable()) {
if ($this->getIsFile()) {
if ($contents = file_get_contents($this->_realpath)) {
return $contents;
}
} else {
return $this->dirContents($this->_realpath, $recursive, $filter);
}
}
$this->addLog('Unable to get filesystem object contents' . ($filter!==null ? ' *using supplied filter*' : ''));
return False;
}
/**
* Gets directory contents (descendant files and folders).
*
* @param null|string $directory Initial directory to get descendants for
* @param bool $recursive If 'True' method would return all descendants recursively, otherwise just immediate
* descendants
* @param null|string $filter Filter to be applied to all directory descendants. Could be a string, or an array
* of strings (perl regexp are supported, if started with '~').
* See {@link filterPassed} method for further information on filters.
* @return array Array of descendants filepaths
* @throws CFileException
*/
private function dirContents($directory=null, $recursive=False, $filter=null) {
$descendants = array();
if (!$directory) {
$directory = $this->_realpath;
}
if ($filter!==null) {
if (is_string($filter)) {
$filter = array($filter);
}
}
if ($contents = @scandir($directory . DIRECTORY_SEPARATOR)) {
foreach ($contents as $key=>$item) {
$contents[$key] = $directory . DIRECTORY_SEPARATOR . $item;
if (!in_array($item, array('.', '..'))) {
if ($this->filterPassed($contents[$key], $filter)) {
$descendants[] = $contents[$key];
}
if (is_dir($contents[$key]) && $recursive) {
$descendants = array_merge($descendants, $this->dirContents($contents[$key], $recursive, $filter));
}
}
}
} else {
throw new CFileException('Unable to get directory contents for "' . $directory . DIRECTORY_SEPARATOR . '"');
}
return $descendants;
}
/**
* Applies an array of filter rules to the string representing filepath.
* Used internally by {@link dirContents} method.
*
* @param string $str String representing filepath to be filtered
* @param array $filter An array of filter rules, where each rule is a string, supposing that the string
* starting with '~' is a regular expression. Any other string treated as an extension part of the given
* filepath (e.g.: file extension)
* @return boolean Returns 'True' if the supplied string matched one of the filter rules.
*/
private function filterPassed($str, $filter) {
if ($filter!==null) {
foreach ($filter as $rule) {
if ($rule[0]!='~') {
$passed = (bool)substr_count($str, $rule);
} else {
$passed = (bool)preg_match($rule, $str);
}
if (!$passed) {
return False;
}
}
}
return True;
}
/**
* Writes contents (data) into the current file.
* This method works only for files.
*
* @param string $contents Contents to be written
* @param boolean $autocreate If 'True' file will be created automatically
* @param integer $flags Flags for file_put_contents(). E.g.: FILE_APPEND to append data to file instead
* of overwriting.
* @return CFile|bool Current CFile object on success, 'False' on fail.
*/
public function setContents($contents=null, $autocreate=True, $flags=0) {
if ($this->getIsFile()) {
if ($autocreate && !$this->getExists()) {
$this->create();
}
if ($this->getWriteable() && file_put_contents($this->_realpath, $contents, $flags)!==False) {
return $this;
}
$this->addLog('Unable to put file contents');
return False;
} else {
$this->addLog('setContents() method is available only for files', 'warning');
return False;
}
}
/**
* Returns filesystem object filepath.
*
* @return string
*/
public function __toString() {
return $this->_realpath;
}
/**
* Sets basename for the current file.
* Lazy wrapper for {@link rename}.
* This method works only for files.
*
* @param null|string $basename New file basename (e.g.: 'mynewfile.txt')
* @return bool|CFile Current CFile object on success, 'False' on fail.
*/
public function setBasename($basename=null) {
if ($this->getIsFile()) {
if ($this->getIsUploaded()) {
$this->addLog('setBasename() is unavailable for uploaded files. Please copy/move uploaded file from temporary directory', 'warning');
return False;
}
if ($this->getWriteable() && $basename && $this->rename($basename)) {
return $this;
}
$this->addLog('Unable to set file basename "' . $basename . '"');
return False;
}
$this->addLog('setBasename() is available only for files', 'warning');
return False;
}
/**
* Sets the current file name.
* Lazy wrapper for {@link rename}.
* This method works only for files.
*
* @param null|string $filename New file name (e.g.: 'mynewfile')
* @return bool|CFile Current CFile object on success, 'False' on fail.
*/
public function setFilename($filename=null) {
if ($this->getIsFile()) {
if ($this->getIsUploaded()) {
$this->addLog('setFilename() is unavailable for uploaded files. Please copy/move uploaded file from temporary directory', 'warning');
return False;
}
if ($this->getWriteable() && $filename && $this->rename(str_replace($this->getFilename(), $filename, $this->getBasename()))) {
return $this;
}
$this->addLog('Unable to set file name "' . $filename . '"');
return False;
}
$this->addLog('setFilename() method is available only for files', 'warning');
return False;
}
/**
* Sets the current file extension.
* If new extension is 'null' or 'False' current file extension is dropped.
* Lazy wrapper for {@link rename}.
* This method works only for files.
*
* @param null|bool|string $extension New file extension (e.g.: 'txt'). Pass null to drop current extension.
* @return bool|CFile Current CFile object on success, 'False' on fail.
*/
public function setExtension($extension=False) {
if ($this->getIsFile()) {
if ($this->getIsUploaded()) {
$this->addLog('setExtension() is unavailable for uploaded files. Please copy/move uploaded file from temporary directory', 'warning');
return False;
}
if ($this->getWriteable() && $extension!==False) {
$extension = trim($extension);
// Drop current extension.
if ($extension===null || $extension=='') {
$new_base_name = $this->getFilename();
} else {
// Apply new extension.
$extension = ltrim($extension, '.');
if ($this->getExtension()===null) {
$new_base_name = $this->getFilename() . '.' . $extension;
} else {
$new_base_name = str_replace($this->getExtension(), $extension, $this->getBasename());
}
}
if ($this->rename($new_base_name)) {
return $this;
}
}
$this->addLog('Unable to set file extension "' . $extension . '"');
return False;
}
$this->addLog('setExtension() is available only for files', 'warning');
return False;
}
/**
* Sets the current filesystem object owner, updates $_owner property on success.
*
* For POSIX systems.
*
* Asserts that user exists before process if posix_ functions are available.
*
* @param string|int $owner New owner name or ID
* @param bool $recursive Apply owner to directory contents flag.
* @return CFile|bool Current CFile object on success, 'False' on fail.
* @throws CFileException When the given user is not found, if posix_ functions are available.
*/
public function setOwner($owner, $recursive=False) {
if (function_exists('posix_getpwnam') && function_exists('posix_getpwuid')) {
if (posix_getpwnam($owner)==False xor (is_numeric($owner) && posix_getpwuid($owner)==False)) {
throw new CFileException('Unable to set owner for filesystem object. User "' . $owner . '" is not found.');
}
}