/
file.php
659 lines (567 loc) · 19.5 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
<?php
/* CodKep - Lightweight web framework core file
* Written by Peter Deak (C) hyper80@gmail.com , License GPLv2
*
* File module
* Required modules: core,sql,user
*/
define('FILE_ACCESS_IGNORE',0);
define('FILE_ACCESS_ALLOW',1);
define('FILE_ACCESS_DENY',2);
/** @ignore
* File module default settings. You can change this values in your site/_settings.php */
function hook_file_boot()
{
global $sys_data;
global $site_config;
$site_config->public_file_path = 'data';
$site_config->public_file_url = '/data';
$site_config->secure_file_path = 'data/secure';
$site_config->secure_file_url = '/data/secure';
$sys_data->image_file_sizeclass_list = [];
$site_config->file_ufi_lastInsertId_name = '';
}
/**
* Returns true if a directory exists and writeable
* @param string $dir The directory path to examine
* @return bool
* @package file */
function directory_exists_and_writeable($dir)
{
return file_exists($dir) && is_dir($dir) && is_writeable($dir);
}
/** @ignore
* The check_module_requirements hook of file module.
* This checks the prerequisites of file module */
function hook_file_check_module_requirements()
{
global $site_config;
ob_start();
$pub_has = directory_exists_and_writeable($site_config->public_file_path);
$sec_has = directory_exists_and_writeable($site_config->secure_file_path);
if(!$pub_has)
{
mkdir($site_config->public_file_path,0777,true);
$pub_has = directory_exists_and_writeable($site_config->public_file_path);
}
if(!$sec_has)
{
mkdir($site_config->secure_file_path,0777,true);
$sec_has = directory_exists_and_writeable($site_config->secure_file_path);
}
if($pub_has && !file_exists($site_config->public_file_path.'/.htaccess'))
{
$str = "Options None\nOptions +FollowSymLinks\n<IfModule mod_php5.c>\n php_flag engine off\n</IfModule>";
if(file_put_contents($site_config->public_file_path.'/.htaccess',$str) === FALSE)
$sec_has = false;
}
if($sec_has && !file_exists($site_config->secure_file_path.'/.htaccess'))
{
$str = "Deny from all\nOptions None\nOptions +FollowSymLinks";
if(file_put_contents($site_config->secure_file_path.'/.htaccess',$str) === FALSE)
$sec_has = false;
}
print '<tr>';
print '<td class="normal">Public directory (CODKEP/'.$site_config->public_file_path.')</td>';
print '<td class="'.($pub_has ? 'green':'red').'">'.($pub_has ? 'Exists & Writeable' : 'Not exists or Not writeable').'</td>';
print '</tr>';
print '<tr>';
print '<td class="normal">Secure directory (CODKEP/'.$site_config->secure_file_path.')</td>';
print '<td class="'.($sec_has ? 'green':'red').'">'.($sec_has ? 'Exists & Writeable' : 'Not exists or Not writeable').'</td>';
print '</tr>';
return ob_get_clean();
}
function hook_file_defineroute()
{
$i = [];
$i[] = [
'path' => 'file/secure/{ufi}/{filename}',
'callback' => 'file_get_secure',
'type' => 'raw',
];
$i[] = [
'path' => 'file/disabled_content',
'callback' => 'file_disabled_content',
"theme" => "base_page",
];
return $i;
}
/**
* File class
*
* @property-read string $url The url of the file
* @property-read string $path The filesystem path of the file
*/
class File
{
public $ufi;
public $type;
public $subdir;
public $name;
public $fsname;
public $mime;
public $uploaded;
public $uploader;
public $grantaccess;
public function __construct($type)
{
if(!in_array($type,['public','secure','']))
load_loc('error',t('Unknown file container: _unk_',['_unk_' => $type]),t('File upload error'));
$this->type = $type;
$this->ufi = NULL;
$this->name = '';
$this->subdir = '';
$this->fsname = '';
$this->mime = '';
$this->uploader = '';
$this->uploaded = '';
$this->grantaccess = false;
}
public function basePath($t_url_f_path = false,$create = false)
{
global $site_config;
$dir = '';
if($this->type == '')
load_loc('error',t('Path request created with empty type!'),t('File error'));
if($this->type == 'public')
$dir = $t_url_f_path ? $site_config->public_file_url : $site_config->public_file_path;
if($this->type == 'secure')
$dir = $t_url_f_path ? $site_config->secure_file_url : $site_config->secure_file_path;
if($this->subdir != '')
{
$dir .= '/' . $this->subdir;
if($create && !file_exists($dir))
mkdir($dir,0777,true);
}
return $dir;
}
protected function scCacheFilePath($sc,$create = false)
{
$dir = $this->basePath(false) . '/' . $sc;
if($create && !file_exists($dir))
mkdir($dir, 0777, true);
return $dir . '/' . $this->fsname;
}
protected function scCacheFileUrl($sc)
{
return $this->basePath(true) . '/' . $sc . '/' . $this->fsname;
}
public function addFromTemp($name,$from,$subdir='',array $context = [])
{
global $db;
global $user;
global $site_config;
$this->ufi = NULL;
$this->subdir = $subdir;
$this->name = $name;
if(file_access($this,'create',$user) != FILE_ACCESS_ALLOW)
{
load_loc('error',t('You don\'t have the required permission to create the file'),t('Permission denied'));
return 'Permission denied';
}
$dir = $this->basePath(false,true);
$uidx = 1;
$path_parts = pathinfo($name);
$p0 = new stdClass();
$p0->pp_ref = &$path_parts;
$p0->file_ref = &$this;
run_hook('upload_filename_alter',$p0);
//Due to usability reasons the spaces are replaced to underscores
$path_parts['filename'] = preg_replace('/\s/','_',$path_parts['filename']);
$this->name = preg_replace('/\s/','_',$this->name);
$fsname = $path_parts['filename'] . '.' . $path_parts['extension'];
while(file_exists($dir.'/'.$fsname))
{
$fsname = $path_parts['filename'] . "_$uidx" . '.' . $path_parts['extension'];
++$uidx;
}
$mime = '';
try
{
if(isset($context['noupload']) && $context['noupload'])
{
if(!rename($from,$dir.'/'.$fsname))
load_loc('error','Sorry to inform you, something wrong with the file moving','File access error');
}
else
{
if(!move_uploaded_file($from,$dir.'/'.$fsname))
load_loc('error','Sorry to inform you, something wrong with the file upload','File upload error');
}
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$mime = finfo_file($finfo,$dir.'/'.$fsname);
finfo_close($finfo);
}
catch(Exception $e)
{
load_loc('error','Error on file upload:'.$e->getMessage(),'File upload error');
}
$this->mime = $mime;
$this->fsname = $fsname;
$this->uploader = $user->auth ? $user->login : '<unauthenticated>';
$p1 = new stdClass();
$p1->file_ref = &$this;
$p1->context = $context;
run_hook('file_upload_in',$p1);
sql_exec("INSERT INTO file(type,sub,name,fsname,mime,uploader,uploaded)
VALUES(:ttype,:subdir,:tname,:fsname,:mime,:tuploader,".sql_t('current_timestamp').")",
[':ttype' => $this->type,
':subdir' => $subdir,
':tname' => $this->name,
':fsname' => $fsname,
':mime' => $mime,
':tuploader' => $this->uploader]);
$this->ufi = sql_getLastInsertId('file','ufi',$site_config->file_ufi_lastInsertId_name);
$p2 = new stdClass();
$p2->file_ref = &$this;
$p2->context = $context;
run_hook('file_uploaded',$p2);
return $this->ufi;
}
public function load($ufi,$disable_show_error = false)
{
$this->ufi = NULL;
$f = sql_exec_fetchN("SELECT ufi,type,sub,mime,name,fsname,uploader,uploaded FROM file WHERE ufi=:ufi",
[':ufi' => $ufi]);
if($f == NULL || empty($f))
{
if(!$disable_show_error)
load_loc('error','File UFI not found','Not found file error');
return NULL;
}
$this->ufi = $f['ufi'];
$this->type = $f['type'];
$this->name = $f['name'];
$this->subdir = $f['sub'];
$this->mime = $f['mime'];
$this->fsname = $f['fsname'];
$this->uploader = $f['uploader'];
$this->uploaded = $f['uploaded'];
$p1 = new stdClass();
$p1->file_ref = &$this;
run_hook('file_loaded',$p1);
return $this->ufi;
}
public function load_from_array($file_data_array)
{
$this->ufi = $file_data_array['file_ufi'];
$this->type = $file_data_array['file_type'];
$this->name = $file_data_array['file_name'];
$this->subdir = $file_data_array['file_sub'];
$this->mime = $file_data_array['file_mime'];
$this->fsname = $file_data_array['file_fsname'];
$this->uploader = $file_data_array['file_uploader'];
$this->uploaded = $file_data_array['file_uploaded'];
$p1 = new stdClass();
$p1->file_ref = &$this;
run_hook('file_loaded',$p1);
return $this->ufi;
}
public function remove()
{
global $user;
if($this->ufi == NULL)
return;
if(file_access($this,'delete',$user) != FILE_ACCESS_ALLOW)
{
load_loc('error',t('You don\'t have the required permission to remove this file'),t('Permission denied'));
return 'Permission denied';
}
$p1 = new stdClass();
$p1->file_ref = &$this;
run_hook('file_will_delete',$p1);
if($this->sizeClassesAllowed())
{
global $sys_data;
foreach($sys_data->image_file_sizeclass_list as $sc => $sc_sizes)
if(file_image_sizeclass($this,$sc) == FILE_ACCESS_ALLOW)
{
$sc_file = $this->scCacheFilePath($sc);
if(file_exists($sc_file))
unlink($sc_file);
}
}
if(file_exists($this->basePath(false) . '/' . $this->fsname))
unlink($this->basePath(false) . '/' . $this->fsname);
sql_exec("DELETE FROM file WHERE ufi=:ufi",
[':ufi' => $this->ufi]);
}
public function __get($n)
{
if($n == 'url' && $this->ufi != NULL)
{
if($this->type == 'secure')
{
return url("file/secure/".$this->ufi."/".$this->name);
}
return $this->basePath(true) . '/' . $this->fsname;
}
if($n == 'path' && $this->ufi != NULL)
{
return $this->basePath(false) . '/' . $this->fsname;
}
return NULL;
}
public function __isset($n)
{
if($n == 'url' && $this->ufi != NULL)
return true;
if($n == 'path' && $this->ufi != NULL)
return true;
return false;
}
public function sizeClassesAllowed()
{
if($this->mime == 'image/jpeg' ||
$this->mime == 'image/png' ||
$this->mime == 'image/gif' )
return true;
return false;
}
public function getContent()
{
ob_start();
readfile($this->basePath(false) . '/' . $this->fsname);
return ob_get_clean();
}
public function getContentBase64()
{
return base64_encode($this->getContent());
}
public function serveFile($name_in_url)
{
global $user;
global $sys_data;
par_def('sc','text1ns');
if($name_in_url == $this->name)
{
if(file_access($this,'view',$user) != FILE_ACCESS_ALLOW)
{
run_hook('file_denied',$this,$user);
goto_loc('file/disabled_content');
}
if(par_ex('sc'))
{
$sc = par('sc');
if(array_key_exists($sc,$sys_data->image_file_sizeclass_list) &&
$this->sizeClassesAllowed() &&
file_image_sizeclass($this,$sc) == FILE_ACCESS_ALLOW )
{
header('Content-Type:'.$this->mime);
return $this->getContentInSizeClass($sc);
}
}
header('Content-Type:'.$this->mime);
return $this->getContent();
}
goto_loc('file/disabled_content');
return '';
}
public function getContentInSizeClass($sc)
{
global $sys_data;
$resized_img_path = $this->scCacheFilePath($sc);
if(!file_exists($resized_img_path))
{
$resized_img_path = $this->scCacheFilePath($sc,true);
image_resample($this->path, $resized_img_path,
$sys_data->image_file_sizeclass_list[$sc][0], $sys_data->image_file_sizeclass_list[$sc][1]);
}
return file_get_contents($resized_img_path);
}
public function urlResized($sizeclass)
{
$url = $this->url;
if($this->type == 'public')
{
global $sys_data;
if(array_key_exists($sizeclass,$sys_data->image_file_sizeclass_list) &&
$this->sizeClassesAllowed() &&
file_image_sizeclass($this,$sizeclass) == FILE_ACCESS_ALLOW )
{
$resized_img_path = $this->scCacheFilePath($sizeclass,false);
if(file_exists($resized_img_path))
return $this->scCacheFileUrl($sizeclass);
$resized_img_path = $this->scCacheFilePath($sizeclass,true);
image_resample($this->path,$resized_img_path,
$sys_data->image_file_sizeclass_list[$sizeclass][0],$sys_data->image_file_sizeclass_list[$sizeclass][1]);
return $this->scCacheFileUrl($sizeclass);
}
return $url;
}
if($this->type == 'secure')
return url($url,['sc' => $sizeclass]);
}
};
function file_access(File $file,$op,$account)
{
if(!in_array($op,['create','delete','view']))
return FILE_ACCESS_DENY;
$far = run_hook('file_access',$file,$op,$account);
if(in_array(FILE_ACCESS_DENY,$far))
return FILE_ACCESS_DENY;
if(in_array(FILE_ACCESS_ALLOW,$far))
return FILE_ACCESS_ALLOW;
if($file->grantaccess)
return FILE_ACCESS_ALLOW;
//Default file permissions:
// Allows everything for admins
if($account->role == ROLE_ADMIN)
return FILE_ACCESS_ALLOW;
// Allows creation for authenticated users
if($op == 'create' && $account->auth)
return FILE_ACCESS_ALLOW;
// Allows to view public files (pointless to disable it)
if($op == 'view' && $file->type == 'public')
return FILE_ACCESS_ALLOW;
// Allows delete/view to the owner/uploader
if($account->auth && $account->login == $file->uploader)
return FILE_ACCESS_ALLOW;
return FILE_ACCESS_DENY;
}
function register_image_sizeclass($name,$w,$h)
{
global $sys_data;
$sys_data->image_file_sizeclass_list[$name] = [$w,$h];
}
function file_image_sizeclass(File $file,$sizeclass)
{
$far = run_hook('file_image_sizeclass',$file,$sizeclass);
if(in_array(FILE_ACCESS_DENY,$far))
return FILE_ACCESS_DENY;
if(in_array(FILE_ACCESS_ALLOW,$far))
return FILE_ACCESS_ALLOW;
//Default:
return FILE_ACCESS_DENY;
}
function file_load($ufi,$disable_show_error = false)
{
$file = new File('');
$file->load($ufi,$disable_show_error);
return $file;
}
function file_load_from_array($file_data_array)
{
$file = new File('');
$file->load_from_array($file_data_array);
return $file;
}
function file_remove($ufi,$disable_show_error = false)
{
$file = new File('');
$file->load($ufi,$disable_show_error);
$file->remove();
}
function file_get_secure()
{
par_def('ufi','number0');
par_def('filename','text4ns');
$ufi = par('ufi');
$f = new File('');
$f->load($ufi);
return $f->serveFile(par('filename'));
}
/** Manages after the form submitted part of a file upload procedure */
function file_create_upload($name,array $opts = [])
{
if($_FILES[$name]['error'] == UPLOAD_ERR_OK)
{
if(isset($opts['filetypes']))
{
$req_filetypes = explode(';', $opts['filetypes']);
if(!in_array($_FILES[$name]['type'],$req_filetypes))
{
load_loc('error',
t('The uploaded file type is "_upltype_" not in "_reqtype_". Please upload the allowed kind of file',
['_upltype_' => $_FILES[$name]['type'],
'_reqtype_' => $opts['filetypes']]),
t('Form validation error'));
}
}
if(in_array($_FILES[$name]['type'],
['image/jpeg', 'image/png', 'image/tiff', 'image/gif']
))
{
$check = getimagesize($_FILES[$name]["tmp_name"]);
if($check === false)
load_loc('error', t('The uploaded file type is not image file. Please upload image file'),
t('Form validation error'));
}
$f = new File(isset($opts['container']) ? $opts['container'] : 'public');
$f->addFromTemp($_FILES[$name]['name'],
$_FILES[$name]["tmp_name"],
(isset($opts['subdir']) ? $opts['subdir'] : ''));
return $f->ufi;
}
return NULL;
}
function file_disabled_content()
{
ob_start();
print '<h2>Access denied</h2>';
print 'You are not authorized to access this file';
return ob_get_clean();
}
function hook_file_required_sql_schema()
{
$t = [];
$t['file_module_file_table'] =
[
"tablename" => 'file',
"columns" => [
'ufi' => 'SERIAL',
'type' => 'VARCHAR(8)',
'name' => 'VARCHAR(128)',
'sub' => 'VARCHAR(32)',
'fsname' => 'VARCHAR(128)',
'mime' => 'VARCHAR(128)',
'uploader' => 'VARCHAR(32)',
'uploaded' => sql_t('timestamp_noupd'),
],
];
return $t;
}
function hook_file_documentation($section)
{
$docs = [];
if($section == "codkep")
{
$docs[] = ['file' => ['path' => 'sys/doc/files.mdoc','index' => false, 'imagepath' => '/sys/doc/images']];
}
return $docs;
}
/**
* Controls the access to a secured file
* @package file */
function _HOOK_file_access() {}
/**
* Controls the size classes of a file
* @package file */
function HOOK_file_image_sizeclass() {}
/**
* Runs before the user will redirect to access denied page.
* Change to display some "not found" message instead
* @package file */
function _HOOK_file_denied() {}
/**
* Runs when a file is uploaded and the local fs name is determined
* This hook can change the local stored filename
*/
function _HOOK_upload_filename_alter() {}
/**
* Runs when a file is uploaded, stored in sql
* @package file */
function _HOOK_file_uploaded() {}
/**
* Runs when a file is uploaded but not yet stored in sql
* @package file */
function _HOOK_file_upload_in() {}
/**
* Runs when a file is loaded
* @package file */
function _HOOK_file_loaded() {}
/**
* Runs before a file is removed
* @package file */
function _HOOK_file_will_delete() {}
//end.