This repository has been archived by the owner on Dec 22, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
file.php
729 lines (584 loc) · 15.2 KB
/
file.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
<?php
/** File handling
* @package system
* @subpackage files
*/
namespace System
{
/** File handling class
* @package system
* @subpackage files
* @property $attrs
*/
class File extends Model\Attr
{
const DIR = '/var/files';
const DIR_TMP = '/var/tmp';
const FETCHED_SIGN = '-FETCHED';
const MOD_DEFAULT = 0664;
const RESOURCE_TYPE = 'pixmap';
const RESOURCE_CNAME = '\\System\\Resource\\File';
protected $content;
/** File attrmodel attributes */
static protected $attrs = array(
"hash" => array("type" => 'varchar'), // DB
"path" => array("type" => 'varchar', 'is_null' => true),
"name" => array("type" => 'varchar'), // DB
"mime" => array("type" => 'varchar'),
"suff" => array("type" => 'varchar'), // DB
"size" => array("type" => 'int', "is_null" => true),
"time" => array("type" => 'int', "is_null" => true),
"cached" => array("type" => 'bool'),
"temp" => array("type" => 'bool'),
"keep" => array("type" => 'bool'),
);
/** Create instance from JSON
* @param string $json
*/
public static function from_json($json)
{
$model = get_called_class();
return new $model(\System\Json::decode($json));
}
/** Create instance from JSON
* @param string $json
*/
public static function from_path($path)
{
$model = get_called_class();
$file = null;
// If file_exists throws error, path is inaccessible
if (!@file_exists($path)) {
$path = \System\Composer::resolve($path);
}
if ($path) {
$file = new $model(array(
"path" => dirname($path),
"name" => basename($path),
"keep" => true
));
}
return $file;
}
public static function from_tmp($path, $real_name)
{
$model = get_called_class();
$suff = self::get_suffix_from_name($real_name);
if ($suff) {
$real_name = substr($real_name, 0, mb_strlen($real_name) - mb_strlen($suff));
}
$file = $model::from_path($path)->rename(\System\Url::gen_seoname($real_name).($suff ? '.'.$suff:''));
$file->keep = false;
return $file;
}
/** Destruction callback
* @return void
*/
public function __destruct()
{
if ($this->temp) {
if (!$this->keep && self::check($this->get_path_temp())) {
self::remove($this->get_path_temp());
}
}
}
/** Attr setter overload
* @param string $attr
* @param mixed $value
*/
public function __set($attr, $value)
{
parent::__set($attr, $value);
if ($attr == 'name') {
if (strpos($value, '.')) {
$split = explode('.', $value, 2);
parent::__set('name', $split[0]);
parent::__set('suff', $split[1]);
}
} else if ($attr == 'suff') {
return parent::__set('suff', strtolower($value));
}
}
/** Get file size
* @return int
*/
public function size()
{
if (is_null($this->size)) {
if ($this->is_cached()) {
$this->size = null;
return strlen($this->get_content());
}
if ($this->exists()) {
$this->size = filesize($this->get_path());
} else {
$this->size = null;
return 0;
}
}
return $this->size;
}
/** Return suffix, try to extract it
* @return string
*/
public function suffix()
{
if (!$this->suff) {
$this->suff = self::get_suffix_from_name($this->name());
}
return $this->suff;
}
public static function get_suffix_from_name($name)
{
$suff = null;
if (strpos($name, '.') > 0) {
$suff = explode('.', $name);
$suff = $suff[count($suff)-1];
}
return $suff;
}
public function get_url()
{
return str_replace(BASE_DIR, '', $this->get_path());
}
/** Get path leading to file
* @return null|string Returns null if file can't be reached on filesystem
*/
public function get_path()
{
if ($this->path) {
return $this->path.'/'.$this->get_full_name();
} else {
try {
$hash = $this->hash();
} catch(\System\Error\File $e) {
$hash = null;
}
if ($hash) {
return $this->get_path_hashed();
}
}
return null;
}
public function get_path_relative()
{
return str_replace(BASE_DIR, '', $this->get_path());
}
/** Get path with hash
* @return string
*/
public function get_path_hashed()
{
return $this->get_path_hashed_dir().'/'.$this->get_path_hashed_name();
}
public function get_path_hashed_relative()
{
return $this->get_path_hashed_dir_relative().'/'.$this->get_path_hashed_name();
}
public function get_path_hashed_name()
{
return $this->get_generated_name().($this->suffix() ? '.'.$this->suffix():'');
}
public function get_path_hashed_dir()
{
return BASE_DIR.self::DIR.'/'.$this->get_path_hashed_dir_relative();
}
public function get_path_hashed_dir_relative()
{
return substr($this->hash(), 0, 4).'/'.substr($this->hash(), 4, 4).'/'.substr($this->hash(), 8, 4).'/'.substr($this->hash(), 12);
}
public function get_generated_name()
{
if ($this->name) {
return $this->name;
}
$this->name = $this->get_time().'-'.md5(rand(1,PHP_INT_MAX));
return $this->name;
}
/** Get temp path
* @return string
*/
public function get_path_temp()
{
return BASE_DIR.self::DIR_TMP.'/'.$this->hash().($this->suffix() ? '.'.$this->suffix():'');
}
/** Get hash describing the file
* @return string
*/
public function hash()
{
if (!$this->hash) {
$this->hash = md5($this->name.'-'.$this->size);
}
return $this->hash;
}
public function get_time()
{
if (is_null($this->time)) {
$this->time = time();
}
return $this->time;
}
/** Get file name
* @return string
*/
public function name()
{
if ($this->name) {
return $this->name;
} else {
return $this->hash;
}
}
/** Get file name with suffix
* @return string
*/
public function get_full_name()
{
return $this->name().($this->suffix() ? '.'.$this->suffix():'');
}
/** Remove file from filesystem
* @return $this
*/
public function drop()
{
if ($this->exists()) {
self::remove($this->get_path());
return $this;
} else throw new \System\Error\File('Cannot remove file. It does not exist on the filesystem.');
}
/** Clear tmp directory
* @return void
*/
public static function clear_tmp()
{
\System\Directory::remove(BASE_DIR.self::TMP_DIR);
mkdir(BASE_DIR.self::TMP_DIR, 0777, true);
}
/** Fetch file from remote URL
* @param string $url URL of file
* @param string $dir Directory to save file
* @return self
* @throws System\Error\File
* @throws System\Error\Connection
*/
static function fetch($url)
{
$u = explode('/', $url);
$name = end($u);
$data = \Helper\Offcom\Request::get($url);
if ($data->ok()) {
$f = new self(array("name" => $name));
$f->set_content($data->content);
$f->size = $data->size;
$f->mime = $data->mime;
return $f;
} else throw new \System\Error\Connection('Couldn\'t fetch file', sprintf('HTTP error %s ', $data->status));
}
/** Move file to another location
* @param string $where Destination
* @return $this
*/
public function move($where)
{
$this->copy($where)->drop();
$this->name = basename($where);
$this->path = dirname($where);
return $this;
}
public function rename($name)
{
return $this->move(dirname($this->get_path()).'/'.$name);
}
/** Copy file to another location
* @param string $where Location to move file to
* @return $this
*/
public function copy($where)
{
if ($this->exists()) {
\System\Directory::check(dirname($where));
if (!copy($this->get_path(), $where)) {
throw new \System\Error\File('File copy from failed!',
sprintf("From: %s", $this->get_path()),
sprintf("To: %s", $where));
}
return $this;
} else throw new \System\Error\File('Cannot copy file. It does not exist on the filesystem.');
}
/** Catalogize the file
* @return $this
*/
public function save()
{
if ($this->saved) {
return $this;
}
if ($this->is_cached()) {
self::put($this->get_path_hashed(), $this->get_content());
} else {
if ($this->exists()) {
if (!$this->is_saved()) {
$this->keep ?
$this->copy($this->get_path_hashed()):
$this->move($this->get_path_hashed());
}
} else throw new \System\Error\File(sprintf('Cannot save file "%s". It does not exist on the filesystem and not in memory.', $this->get_path()));
}
$this->path = null;
return $this;
}
/** Save file into temporary storage
* return $this
*/
public function temp()
{
if ($this->is_cached()) {
self::put($this->get_path_temp(), $this->get_content());
} else {
if ($this->exists()) {
$this->copy($this->get_path_temp());
}
}
$this->update_attrs(array(
"name" => basename($this->get_path_temp()),
"path" => dirname($this->get_path_temp()),
"temp" => true,
));
return $this;
}
/** Dear sir, does this file exists?
* @return bool
*/
public function exists()
{
$path = $this->get_path();
return $path && file_exists($path);
}
/** Dear sir, does this file exists?
* @return bool
*/
public function get_all_versions()
{
$versions = array();
$dir_path = $this->get_path_hashed_dir();
if (\System\Directory::check($dir_path, false)) {
$version_files = \System\Directory::find($dir_path);
$model = get_class($this);
foreach ($version_files as $fp) {
$file = $model::from_path($fp);
$file->time = $file->name;
$versions[] = $file;
}
}
return $versions;
}
/** Dear sir, is this file cached in memory?
* @return bool
*/
public function is_cached()
{
return $this->cached;
}
/** Dear sir, is this file catalogized?
* @return bool
*/
public function is_saved()
{
return $this->hash && file_exists($this->get_path_hashed()) || $this->saved;
}
/** Dear sir, is this file empty? If cached, return true if null content size. If not, reads the size on fs.
* @return bool
*/
public function is_empty()
{
if ($this->is_cached()) {
return !is_null($this->content);
}
if ($this->exists() || $this->saved) {
return $this->size() <= 0;
}
return true;
}
/** Read file into memory
* @return $this
*/
public function load()
{
if ($this->exists()) {
$this->content = self::read($this->get_path());
$this->is_cached = true;
return $this;
} else throw new \System\Error\File('Cannot read file. It does not exists on the filesystem.');
}
/** Unload the file from memory
* @return $this
*/
public function unload()
{
$this->content = null;
$this->is_cached = false;
return $this;
}
/** Get file content, read if necessary
* @return blob
*/
public function get_content()
{
if (!$this->is_cached()) {
$this->load();
}
return $this->content;
}
/** Set file's content
* @param string $data
*/
public function set_content($data)
{
$this->content = $data;
$this->cached = true;
return $this;
}
/** Put string data into file
* @param string $path
* @param string $content
* @param int $mode
* @throws System\Error\Permissions
* @return bool
*/
public static function put($path, $content, $mode = null)
{
if (\System\Directory::check($d = dirname($path)) && (($ex = file_exists($path)) || is_writable($d))) {
if (!$ex || is_writable($path)) {
$write = file_put_contents($path, $content);
$mod = true;
if (!$ex && is_null($mode)) {
chmod($path, self::MOD_DEFAULT);
}
if (!is_null($mode)) {
if (!$mod = @chmod($path, $mode)) {
throw new \System\Error\Permissions(sprintf('Failed to set %s permissions on file "%s".', $mode, $path));
}
}
return $write && $mod;
} else throw new \System\Error\Permissions(sprintf('Failed to write data into file "%s". Check your permissions.', $path));
} else throw new \System\Error\Permissions(sprintf('Failed to write data into file "%s". Parent directory is not writeable.', $path));
return $action;
}
/** Read file data
* @param string $path
* @param bool $silent
* @throws System\Error\File
* @throws System\Error\Permissions
* @return string
*/
public static function read($path, $silent = false)
{
if (\System\Directory::check(dirname($path), false) && file_exists($path)) {
if (is_readable($path)) {
return file_get_contents($path);
} else if (!$silent) throw new \System\Error\Permissions(sprintf('Failed to read file "%s". It is not readable.', $path));
} else if (!$silent) throw new \System\Error\File(sprintf('Failed to read file "%s". It does not exist.', $path));
return false;
}
/** Export image object to JSON
* @param bool $encode Return encoded string
* @return string
*/
public function to_json($encode = true)
{
if ($this->is_saved()) {
$data = array(
"hash" => $this->hash(),
"suff" => $this->suff,
"name" => $this->name,
"time" => $this->get_time(),
);
} else {
$data = $this->data;
}
return $encode ? json_encode($data):$data;
}
public function to_object()
{
if (!$this->mime) {
$this->read_meta();
}
$path = str_replace(\System\File::DIR, '', $this->get_path_relative());
$src = 'media';
$cname = $this::RESOURCE_CNAME;
$stat = $cname::DIR_STATIC;
try {
$cache = \System\Settings::get('cache', 'resources');
} catch (\System\Error $e) {
$cache = false;
}
if ($cache) {
$dirs = array($stat);
} else {
$dirs = \System\Composer::list_dirs($stat);
array_unshift($dirs, $stat);
}
foreach ($dirs as $dir) {
if (strpos($path, $dir) === 0 || strpos($path, $dir = substr($dir, 1)) === 0) {
$path = substr($path, strlen($dir));
$src = 'static';
break;
}
}
$url = \System\Resource::get_url($src, self::RESOURCE_TYPE, preg_replace("/^\//", '', $path));
return array(
"url" => $url,
"path" => $path,
"name" => $this->name,
"mime" => $this->mime,
"size" => $this->size,
"method" => $this->method ? $this->method:'save',
);
}
public function read_meta()
{
if ($this->exists()) {
$this->size = filesize($this->get_path());
$this->mime = self::get_mime($this->get_path());
}
return $this;
}
/** Remove file from filesystem
* @param string $path
* @return bool
*/
public static function remove($path)
{
if (is_writable($path)) {
return unlink($path);
} else throw new \System\Error\Permissions(sprintf('Failed to remove file "%s". It is not accessible.', $path));
}
/** Check if file exists
* @param string $path
* @return bool
*/
public static function check($path)
{
return file_exists($path);
}
public static function get_mime($file)
{
if (function_exists("finfo_file")) {
$finfo = finfo_open(FILEINFO_MIME_TYPE); // return mime type ala mimetype extension
$mime = finfo_file($finfo, $file);
finfo_close($finfo);
return $mime;
} else if (function_exists("mime_content_type")) {
return mime_content_type($file);
} else if (!stristr(ini_get("disable_functions"), "shell_exec")) {
// http://stackoverflow.com/a/134930/1593459
$file = escapeshellarg($file);
$mime = shell_exec("file -bi " . $file);
return $mime;
} else {
return false;
}
}
}
}