forked from FreePBX/filestore
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathFilestore.class.php
558 lines (521 loc) · 15.9 KB
/
Filestore.class.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
<?php
namespace FreePBX\modules;
/*
* Class stub for BMO Module class
* In _Construct you may remove the database line if you don't use it
* In getActionbar change extdisplay to align with whatever variable you use to decide if the page is in edit mode.
*
*/
include __DIR__.'/vendor/autoload.php';
class Filestore extends \FreePBX_Helpers implements \BMO {
public function __construct($freepbx = null) {
if ($freepbx == null) {
throw new Exception("Not given a FreePBX Object");
}
$this->classlist = [];
$this->FreePBX = $freepbx;
$this->db = $freepbx->Database;
$this->hookdrivers = null;
$this->drivers = $this->listDrivers();
$this->driverCache = [];
}
public function listDrivers(){
$drivers = array();
foreach (new \DirectoryIterator(__DIR__.'/drivers/') as $dir) {
if($dir->isDot() || !$dir->isDir()){
continue;
}
$driver = $dir->getFilename();
$drivers[] = $driver;
}
return $drivers;
}
public function install() {
$keys = ['ftpservers' => 'FTP', 'sshservers' => 'SSH', 's3servers' => 'S3', 'localservers' => 'Local', 'emailservers' => 'Email', 'dropboxservers' => 'Dropbox'];
$servers = $this->getConfig('servers');
if(!empty($servers)){
$servers = is_array($servers) ? $servers : [];
foreach($keys as $oldkey => $newkey) {
foreach($this->getAll($oldkey) as $id => $data) {
$data['driver'] = $newkey;
$this->setConfig('driver', $data['driver'], $id);
$servers[$id] = $data;
}
$this->delById($oldkey);
}
$this->setConfig('servers',$servers);
}
else{
$data= [
"id" => Null,
"driver" => "Local",
"name" => "Local backup storage",
"desc" => "Default local directory for backup storage",
"path" => "__ASTSPOOLDIR__/backup/",
];
$this->addItem("Local",$data);
}
foreach ($this->drivers as $key) {
$class = "\FreePBX\\modules\\Filestore\\drivers\\".$key.'\\'.$key;
if (!class_exists($class)) {
continue;
}
$class::install($this->FreePBX);
}
}
public function uninstall() {
foreach ($this->drivers as $key) {
$class = "\FreePBX\\modules\\Filestore\\drivers\\".$key.'\\'.$key;
if (!class_exists($class)) {
continue;
}
$class::uninstall($this->FreePBX);
}
}
public function getDisplay($driver){
$class = "\FreePBX\\modules\\Filestore\\drivers\\".$driver.'\\'.$driver;
if (!class_exists($class)) {
return sprintf(_("Driver (%s) not found!"), $driver);
}
$config = isset($_REQUEST['id']) ? $this->getItemById($_REQUEST['id']) : [];
return $class::getDisplay($this->FreePBX, $config);
}
public function doConfigPageInit($page){
$req = freepbxGetSanitizedRequest();
$driver = $req['driver'];
$action = isset($req['action'])?$req['action']:'';
$id = isset($req['id'])?$req['id']:false;
switch ($action) {
case 'add':
if(empty($req['name'])){
return array('status' => false, 'message' => _("Invalid name"));
}
return $this->addItem($driver, $req);
break;
case 'edit':
if($id){
return $this->editItem($id, $req);
}
return array('status' => false, 'message' => _("No id supplied"));
break;
case 'delete':
if($id){
return $this->deleteItem($id);
}
return array('status' => false, 'message' => _("No id supplied"));
break;
default:
return array('status' => false, 'message' => _("Unknown action provided"));
break;
}
}
public function getActionBar($request) {
if(!isset($_REQUEST['driver'])){
return array();
}else{
$driver = $_REQUEST['driver'];
$class = "\FreePBX\\modules\\Filestore\\drivers\\".$driver.'\\'.$driver;
if (!class_exists($class)) {
return array();
}
return $class::getActionBar();
}
}
public function showPage(){
// WARNING: Do not change _GET for _REQUEST since giving submit in the creation/edition/deletion of a
// storage entails that doConfigPageInit is executed and the main page is subsequently loaded. This
// causes the "device" variable to exist since it is sent to doConfigPageInit via POST and when the
// "driver" variable exists, the page does not load the tabs of all the supported "drivers" and only
// shows the list of the driver that was specified via POST variable.
if(!isset($_GET['driver'])|| empty($_GET['driver'])){
$vars['drivers'] = $this->validateDrivers($this->drivers);
$vars['fs'] = $this;
return load_view(__DIR__.'/views/main.php',$vars);
}
return $this->getDisplay($_GET['driver']);
}
public function ajaxRequest($req, &$setting) {
// ** Allow remote consultation with Postman **
// ********************************************
// $setting['authenticate'] = false;
// $setting['allowremote'] = true;
// return true;
// ********************************************
switch($req) {
case 'grid':
return true;
break;
}
return false;
}
public function ajaxHandler(){
switch($_REQUEST['command']) {
case 'grid':
return $this->listItems($_REQUEST['driver'], true);
break;
}
}
public function getRightNav($request) {
// WARNING: Do not change _GET for _REQUEST since giving submit in the creation/edition/deletion of a
// storage entails that doConfigPageInit is executed and the main page is subsequently loaded. This makes
// the "device" variable exist since it is sent to doConfigPageInit via POST and when the "device" variable
// exists, the page loads the side navigation panel that does not have to be loaded when the "drivers" tabs
// are being shown .
if(empty($_GET['driver'])){
return '';
}
$vars = array(
'drivers' => $this->validateDrivers($this->drivers),
'current' => $_REQUEST['driver'],
);
return load_view(__DIR__.'/views/rnav.php', $vars);
}
public function listLocations($permissions = 'all'){
$locations = array(
'filestoreTypes' => array(),
'locations' => array(),
);
foreach ($this->drivers as $driver) {
$class = "\FreePBX\\modules\\Filestore\\drivers\\".$driver.'\\'.$driver;
if (!class_exists($class)) {
continue;
}
$class = new $class($this->FreePBX);
$locations['filestoreTypes'][] = $driver;
$location['locations'][$driver] = isset($location['locations'][$driver])?$location['locations'][$driver]:array();
foreach($this->listItems($driver) as $item){
$name = isset($item['name'])?$item['name']:$driver.'-'.substr($item['id'], -5);
$description = isset($item['description'])?$item['description']:'';
$locations['locations'][$driver][] = array('id' => $item['id'], 'name' => $name, 'description' => $description);
}
}
return $locations;
}
/**
* Git list of items for driver
* @return array Array of items.
*/
public function listItems($driver, $includeDisabled = false) {
$items = $this->getConfig('servers');
if(empty($items)) {
return [];
}
$check_driver = array_values(array_filter($items, function($item) use($driver){
return ($item['driver'] === $driver);
}));
if (! empty($check_driver)) {
$item_value = $check_driver[array_key_first($check_driver)];
if ($includeDisabled == false && (! empty($item_value['enabled']) && $item_value['enabled'] == 'no' )) {
return [];
}
}
return $check_driver;
}
/**
* Validates driver list
*
* @param array $drivers
* @return array validated drivers.
*/
public function validateDrivers($drivers = []){
$final = [];
foreach($drivers as $k => $v){
if(!$this->getConfig('d'.$v)){
$final[$k] = $v;
}
}
return $final;
}
//CRUD actions
/**
* Add a item for driver
* @param $data array of data for required
*/
public function addItem($driver,$data){
$id = \Ramsey\Uuid\Uuid::uuid4()->toString();
$data['driver'] = $driver;
$fsdata = array_map(function($val){
if(!is_array($val)) {
return trim($val);
}
return $val;
},$data);
return $this->saveConfig($id,$fsdata);
}
/**
* Edit Item
* @param string $id Id of item
* @param array $data array of data required
* @return bool success, failure
*/
public function editItem($id,$data){
$fsdata = array_map(function($val){
if(!is_array($val)) {
return trim($val);
}
return $val;
},$data);
return $this->saveConfig($id,$fsdata);
}
/**
* Save the configuration for the server into the database
*
* @param string $id
* @param array $data
* @return void
*/
private function saveConfig($id,$data) {
$driver = $data['driver'];
$data['path'] = rtrim($data['path'], '/') . '/';
$class = "\FreePBX\\modules\\Filestore\\drivers\\".$driver.'\\'.$driver;
if (!class_exists($class)) {
return false;
}
$data = $class::filterConfig($this->FreePBX, $data);
$data['driver'] = $driver;
$servers = $this->getConfig('servers');
if(!is_array($servers)) {
$servers = [];
}
$servers[$id] = [
'id' => $id,
'name' => $data['name'],
'desc' => $data['desc'],
'driver' => $data['driver'],
'enabled' => $data['enabled'],
];
$this->setConfig('servers', $servers);
$this->delById($id);
$this->setMultiConfig($data, $id);
return $id;
}
/**
* Delete Item by id
* @param string $id Id of item
* @return bool success, failure
*/
public function deleteItem($id){
$servers = $this->getConfig('servers');
if(!is_array($servers) || !isset($servers[$id])) {
return;
}
unset($servers[$id]);
$this->setConfig('servers', $servers);
$this->delById($id);
}
public function getItemById($id) {
$config = $this->getAll($id);
$config['id'] = $id;
return $config;
}
/**
* Get object file by ID
* @param string $id filestore item id
* @param bool $forceGet If we set it to true, it will force fetch the object even though it is marked disabled, but it won't add it to the cache.
* @return file object
*/
public function getDriverObjectById($id, $forceGet = false) {
if(isset($this->driverCache[$id])) {
return $this->driverCache[$id];
}
$config = $this->getItemById($id);
if(empty($config['driver'])) {
throw new \Exception(_("The requested driver seems invalid"));
}
$class = "FreePBX\modules\Filestore\drivers\\".$config['driver'].'\\'.$config['driver'];
if(!class_exists($class)){
throw new \Exception(sprintf(_("The requested driver %s seems invalid"),$config['driver']),404);
}
$newClass = new $class($this->FreePBX, $config);
if (! $forceGet && ! $newClass->isEnabled()) {
throw new \Exception(sprintf(_("The requested driver %s is disabled"),$config['driver']),405);
}
if ($forceGet) {
return $newClass;
}
$this->driverCache[$id] = $newClass;
return $this->driverCache[$id];
}
//Filestore Actions
/**
* Get file
* @param int $id filestore item id
* @param string $path path of item to get
* @return File object
*/
public function download($id,$remote,$local){
return $this->getDriverObjectById($id)->download($remote, $local);
}
/**
* Put file
* @param int $id filestore item id
* @param string $path path of item to put
* @param file $file to upload
* @return bool object created
*/
public function upload($id,$local,$remote){
return $this->getDriverObjectById($id)->upload($local, $remote);
}
/**
* set email options
* @param array $mailOptions
*/
public function setEmailOptions($id,$mailOptions=false){
return $this->getDriverObjectById($id)->setEmailOptions($mailOptions);
}
/**
* List files/directories in path
* @param int $id filestore item id
* @param string $path path to list
* @param type file/dir Default both.
* @return File object
*/
public function ls($id,$path='',$recursive=false){
return $this->getDriverObjectById($id)->listContents($path, $recursive);
}
/**
* Delete object by path
* @param int $id filestore item id
* @param [type] $path path to delete
* @return boolean Did it delete?
*/
public function delete($id,$path){
return $this->getDriverObjectById($id)->delete($path);
}
/**
* Rename file or directory
* @param int $id filestore item id
* @param string $oldpath file to rename
* @param string $newpath What to rename it to
* @return bool was the operation successful
*/
public function move($id,$oldpath,$newpath){
return $this->getDriverObjectById($id)->rename($oldpath,$newpath);
}
/**
* check if file exists
* @param int $id filestore item $id
* @param string $path name of file to find
* @return mixed $path path of found item or false
*/
public function fileExists($id,$path){
return $this->getDriverObjectById($id)->fileExists($path);
}
public function getSize($id,$path){
return $this->getDriverObjectById($id)->getSize($path);
}
/**
* create directory
* @param int $id filestore item $id
* @param string $filename name of file to find
* @return mixed $path path of found item or false
*/
public function makeDirectory($id,$path){
return $this->getDriverObjectById($id)->createDir($path);
}
public function runHook($hookname,$params = false){
if (!file_exists("/etc/incron.d/sysadmin")) {
throw new \Exception("Sysadmin RPM not up to date, or not a known OS.");
}
$spooldir = $this->FreePBX->Config->get('ASTSPOOLDIR');
$basedir = $spooldir."/incron";
if (!is_dir($basedir)) {
throw new \Exception("$basedir is not a directory");
}
// Does our hook actually exist?
if (!file_exists(__DIR__."/hooks/$hookname")) {
throw new \Exception("Hook $hookname doesn't exist");
}
$filename = $basedir.'/filestore'.$hookname;
// Do I have any params?
if ($params) {
// Oh. I do. If it's an array, json encode and base64
if (is_array($params)) {
$b = base64_encode(gzcompress(json_encode($params)));
// Note we derp the base64, changing / to _, because filepath.
$filename .= ".".str_replace('/', '_', $b);
} elseif (is_object($params)) {
throw new \Exception("Can't pass objects to hooks");
} else {
// Cast it to a string if it's anything else, and then make sure
// it doesn't have any spaces.
$filename .= ".".preg_replace("/[[:blank:]]+/", (string) $params);
}
}
$fh = fopen($filename, "w+");
if ($fh === false) {
// WTF, unable to create file?
throw new \Exception("Unable to create hook trigger '$filename'");
}
// As soon as we close it, incron does its thing.
fclose($fh);
// Wait for up to 5 seconds and make sure it's been deleted.
$maxloops = 10;
$deleted = false;
while ($maxloops--) {
if (!file_exists($filename)) {
$deleted = true;
break;
}
usleep(500000);
}
if (!$deleted) {
throw new \Exception("Hook file '$filename' was not picked up by Incron after 5 seconds. Is it not running?");
}
return true;
}
public function listAllFiles($subdir = false){
$final = [];
$locations = $this->listLocations('all');
foreach($locations['locations'] as $driver => $instances){
foreach($instances as $instance){
$final[$driver][$instance['id']] = $instance;
// Get files and dirs from driver
try {
$presult = $this->ls($instance['id']);
}
catch(\Exception $e) {
continue;
}
// If subdir is false, return list files and dirs
if ($subdir == false)
{
$final[$driver][$instance['id']]['results'] = $presult;
}
else
{
$dir_files = $files = [];
foreach($presult as $result)
{
switch($result["type"])
{
case "dir": // If type is dir, get a list of files and directories inside the folder
try {
$dir_files_new = $this->ls($instance['id'], $result["path"]);
}
catch(\Exception $e) {
continue 2;
}
$dir_files = array_merge($dir_files, $dir_files_new);
break;
case "file": // If type is file, set info directly
$files[] = $result;
break;
}
$final[$driver][$instance['id']]['results'] = array_merge($dir_files, $files);
}
}
}
}
return $final;
}
public function checkTableExists($tableName)
{
$sql = 'SELECT * from INFORMATION_SCHEMA.tables WHERE TABLE_NAME = :tableName ';
$stmt = $this->db->prepare($sql);
$stmt->bindParam(':tableName', $tableName);
$stmt->execute();
$res = $stmt->fetch(\PDO::FETCH_ASSOC);
return $res;
}
}