-
Notifications
You must be signed in to change notification settings - Fork 19
/
BackupBase.php
270 lines (246 loc) · 8.01 KB
/
BackupBase.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
<?php
namespace FreePBX\modules\Backup;
use Symfony\Component\Process\Process;
use Symfony\Component\Process\Exception\ProcessFailedException;
use Symfony\Component\Filesystem\Filesystem;
use FreePBX\modules\Backup\Models as Model;
/**
* This is a base class used when creating your modules "Backup.php" class
*/
class BackupBase extends Model\Backup{
/**
* Run Backup method. This is implemented by other modules
*
* If it's not implemented then it will export defaults by guessing
*
* @param [type] $id
* @param [type] $transaction
* @return void
*/
public function runBackup($id,$transaction) {
if($this->defaultFallback) {
$this->log(sprintf(_("RunBackup method is not implemented in %s, using default fallback"), $module),'WARNING');
$this->addConfigs(array_merge($this->dumpAll(),["defaultFallback" => true]));
} else {
$this->log(sprintf(_("RunBackup method is not implemented in %s"), $module),'WARNING');
}
}
/**
* Dump all relevant settings into an array
*
* Advanced Settings
* Feature Codes
* Module Tables
* Key Value Store
*
* @return array
*/
public function dumpAll($under_score=false) {
return [
"settings" => $this->dumpAdvancedSettings(),
"features" => $this->dumpFeatureCodes(),
"tables" => $this->dumpTables($under_score),
"kvstore" => $this->dumpKVStore()
];
}
/**
* Dump all known advanced settings
*
* @return array
*/
public function dumpAdvancedSettings() {
$module = strtolower($this->data['module']);
$this->log(sprintf(_("Exporting Advanced settings from %s"), $module));
$sql = "SELECT `keyword`, `value` FROM freepbx_settings WHERE module= :name";
$sth = $this->FreePBX->Database->prepare($sql);
$sth->execute([":name" => $module]);
return $sth->fetchAll(\PDO::FETCH_KEY_PAIR);
}
/**
* Dump all known feature codes
*
* @return array
*/
public function dumpFeatureCodes() {
$module = strtolower($this->data['module']);
$this->log(sprintf(_("Exporting Feature Codes from %s"), $module));
$sql = "SELECT `featurename` , `description` , `helptext` , `defaultcode` , `customcode` , `enabled` , `providedest` FROM featurecodes WHERE modulename = :name";
$sth = $this->FreePBX->Database->prepare($sql);
$sth->execute([":name" => $module]);
return $sth->fetchAll(\PDO::FETCH_GROUP|\PDO::FETCH_ASSOC|\PDO::FETCH_UNIQUE);
}
/**
* $modulename
* $under_score = true or false search with like modulename_
*/
public function dumpDBTables($modename,$under_score=true,$ignoretables=[]) {
if(!$under_score) {
$query = "SELECT table_name FROM information_schema.tables WHERE table_name LIKE '".$modename."%'";
} else {
$query = "SELECT table_name FROM information_schema.tables WHERE table_name LIKE '".$modename."\_%'";
}
$tables = $this->FreePBX->Database->query($query)->fetchAll(\PDO::FETCH_ASSOC);
$ret = [];
foreach($tables as $table) {
$tname = (string)$table['table_name'];
if(in_array($tname,$ignoretables)){
continue;
}
$ret[$tname] = $this->FreePBX->Database->query(sprintf("SELECT * FROM `%s`", $tname))->fetchAll(\PDO::FETCH_ASSOC);
}
return $ret;
}
/**
* dumpAstDB
*
* @param string $family
*
* @return array()
*/
public function dumpAstDB($family = ""){
if(!is_string($family)){
return array();
}
$astdb = $this->FreePBX->astman->command("database show $family");
$astdb = explode("\n",$astdb["data"]);
$result = array();
foreach($astdb as $line){
$line = explode(":", $line);
if (count($line) > 1) {
list($root, $value) = $line;
} else {
$root = $line[0];
}
if(strpos($root, $family) !== False){
$children = substr(trim($root),1);
$children = trim(substr(str_replace($family, "", $children),1));
$result[] = array($family => array($children => trim($value)));
}
}
return $result;
}
/**
* Dump all known databases from said module
*
* @return array
*/
public function dumpTables($under_score=false,$ignoretables = []) {
$module = strtolower($this->data['module']);
$this->log(sprintf(_("Exporting Databases from %s"), $module));
$dir = $this->FreePBX->Config->get('AMPWEBROOT').'/admin/modules/'.$module;
if(!file_exists($dir.'/module.xml')) {
return [];
}
$xml = simplexml_load_file($dir.'/module.xml');
$tables = [];
$tables = $this->dumpDBTables($module, $under_score,$ignoretables);
if(is_object($xml->database->table)) {
foreach($xml->database->table as $table) {
$tname = (string)$table->attributes()->name;
//ignore tables
if(in_array($tname,$ignoretables)) {
continue;
}
if(array_key_exists($tname,$tables)) {
continue;
} else {
$tables[$tname] = $this->FreePBX->Database->query(sprintf("SELECT * FROM `%s`", $tname))->fetchAll(\PDO::FETCH_ASSOC);
}
}
}
return $tables;
}
/**
* Dump KVStore to a multidimensional array
*
* @return array
*/
public function dumpKVStore($ids=false) {
$module = ucfirst(strtolower($this->data['module']));
$this->log(sprintf(_("Exporting KVStore from %s"), $module));
if (is_array($ids)) {
$this->log(sprintf(_("Exporting KVStore based on ids %s"), implode(',',$ids)));
}
if(!is_subclass_of($this->FreePBX->$module,'FreePBX\DB_Helper')) {
return [];
}
if(!is_array($ids)) {
$ids = $this->FreePBX->$module->getAllids();
$ids[] = 'noid';
}
$final = [];
foreach($ids as $id) {
$final[$id] = $this->FreePBX->$module->getAll($id);
}
return $final;
}
/**
* Dump specific tables
*
* @param String $moduleName
* @param String $tableName
* @param Boolean $dumpOtherOptions
* @param Boolean $zipDump
* @return Object
*/
function dumpTableIntoFile($moduleName, $tableName, $dumpOtherOptions = false, $zipDump = false)
{
global $amp_conf;
$dbhost = $amp_conf['AMPDBHOST'];
$dbuser = $amp_conf['AMPDBUSER'];
$dbport = $amp_conf['AMPDBPORT'] ?? '3306';
$dbpass = $amp_conf['AMPDBPASS'];
$dbname = $amp_conf['AMPDBNAME'];
$dbsock = $amp_conf['AMPDBSOCK'] ?? '';
$cdrDbTables = ['cdr', 'cel', 'queuelog'];
if (in_array($tableName, $cdrDbTables)) {
$dbhost = $this->FreePBX->Config->get('CDRDBHOST') ? $this->FreePBX->Config->get('CDRDBHOST') : $amp_conf['AMPDBHOST'];
$dbuser = $this->FreePBX->Config->get('CDRDBUSER') ? $this->FreePBX->Config->get('CDRDBUSER') : $amp_conf['AMPDBUSER'];
$dbport = $this->FreePBX->Config->get('CDRDBPORT') ? $this->FreePBX->Config->get('CDRDBPORT') : ($amp_conf['AMPDBPORT'] ?? '3306');
$dbpass = $this->FreePBX->Config->get('CDRDBPASS') ? $this->FreePBX->Config->get('CDRDBPASS') : $amp_conf['AMPDBPASS'];
$dbname = $this->FreePBX->Config->get('CDRDBNAME') ? $this->FreePBX->Config->get('CDRDBNAME') : 'asteriskcdrdb';
}
$fs = new Filesystem();
$tmpdir = sys_get_temp_dir() . "/{$moduleName}_dump";
if (is_dir($tmpdir)) {
$fs->remove($tmpdir);
}
$fs->mkdir($tmpdir);
$mysqldump = fpbx_which('mysqldump');
$fileExt = $zipDump ? 'sql.gz' : 'sql';
$tmpfile = "{$tmpdir}/{$moduleName}.{$fileExt}";
if (empty($dbsock)) {
$dbhost = ($dbhost === 'localhost' || $dbhost === '127.0.0.1') ? '' : '-h ' . $dbhost;
$dbport = empty(trim($dbport)) ? '' : '-P ' . $dbport;
} else {
$dbhost = '-S ' . $dbsock;
$dbport = '';
}
$command = "{$mysqldump} {$dbport} {$dbhost} -u{$dbuser} -p{$dbpass} {$dbname} ";
if ($dumpOtherOptions) {
$command .= "{$dumpOtherOptions} ";
}
$command .= "{$tableName} ";
if ($zipDump) {
$command .= "| gzip -9 > {$tmpfile}";
} else {
$command .= "--result-file={$tmpfile}";
}
$this->log(sprintf(_("Starting mysql dumps of : %s"), $tableName));
try {
$process = \freepbx_get_process_obj($command);
$process->setTimeout(3600);
$process->disableOutput();
$process->mustRun();
} catch (ProcessFailedException $e) {
$this->log(sprintf(_("%s table Backup Error %s "), $tableName, $e->getMessage()), 'ERROR');
return false;
}
$fileObj = new \SplFileInfo($tmpfile);
$this->addSplFile($fileObj);
// deletes files, directories and symlinks
$this->addGarbage($tmpdir);
$this->log(sprintf(_("Completed mysql dumps of : %s"), $tableName));
return $fileObj;
}
}