root/modules/branches/2.9/backup/bin/ampbackup.php

Revision 11824, 12.7 kB (checked in by mbrevda, 2 years ago)

closes #4980

  • Property svn:executable set to *
Line 
1 #!/usr/bin/env php
2 <?php
3 /*
4  ampbackup.php Copyright (C) 2009 Moshe Brevda
5  original perl version (C) 2004 Coalescent Systems Inc. (info@coalescentsystems.ca)
6
7  this program is in charge of looking into the database to pick up the backup sets name and options
8  Then it creates the tar files and places them in the /var/lib/asterisk/backups folder
9
10  The program if run from asterisk users crontab it is run as ampbackup.php <Backup Job Record Number in Mysql>
11  OR
12  The program is called from the backup.php script and implemented immediately as such:
13  ampbackup.php <Backup_Name> <Backup_Voicemail_(yes/no)> <Backup_Recordings_(yes/no)> <Backup_Configuration_files(yes/no)>
14  <Backup_CDR_(yes/no)> <Backup_FOP_(yes/no)
15
16  example ampbackup.php "My_Nightly_Backup" yes yes no no yes
17
18
19  This program is free software; you can redistribute it and/or
20  modify it under the terms of the GNU General Public License
21  as published by the Free Software Foundation; either version 2
22  of the License, or (at your option) any later version.
23
24  This program is distributed in the hope that it will be useful,
25  but WITHOUT ANY WARRANTY; without even the implied warranty of
26  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
27  GNU General Public License for more details.
28 */
29
30 $restrict_mods = true;
31 $bootstrap_settings['freepbx_auth'] = false;
32 if (!@include_once(getenv('FREEPBX_CONF') ? getenv('FREEPBX_CONF') : '/etc/freepbx.conf')) {
33     include_once('/etc/asterisk/freepbx.conf');
34 }
35
36 switch (true){
37     case $argc == 1://no args recieved - show help text
38             showopts();
39     break;
40     case $argv[1] == 'cli'://args passed on cli
41         for($i=2;$i<$argc;$i++){
42             if(substr($argv[$i],0,2)=='--'){
43                 $arg=explode('=',substr($argv[$i],2));
44                 $opts[$arg[0]]=trim($arg[1]);
45             }
46         }
47     break;
48     case $argc == 2: //got backup id, do a db lookup
49         $sql = "SELECT * FROM backup WHERE id= ?";
50         $opts=$db->getRow($sql,array($argv[1]), DB_FETCHMODE_ASSOC);
51         
52         if(!$opts){echo "No Backup Schedules defined in backup table or you may need to run this program with more arguments.\n";exit;}
53     break;
54     default: //legacy method of calling script
55         $opts['name']=isset($argv[1])?$argv[1]:false;
56         $opts['voicemail']=(isset($argv[2])&& $argv[2]=='yes')?true:false;
57         $opts['recordings']=(isset($argv[3])&& $argv[3]=='yes')?true:false;
58         $opts['configurations']=(isset($argv[4])&& $argv[4]=='yes')?true:false;
59         $opts['cdr']=(isset($argv[5])&& $argv[5]=='yes')?true:false;
60         $opts['fop']=(isset($argv[6])&& $argv[6]=='yes')?true:false;
61     break;
62 }
63
64 $opts['ftpfile']='/tmp/freepbx-backup.ftp';
65 $opts['budir']=$amp_conf['ASTVARLIBDIR'].'/backups';
66 if(!isset($opts['now']) || $opts['now']==''){$opts['now']=date('Ymd.H.i.s');}//only set if not already set
67
68 //get arguments
69
70 if($opts['sudo']==true){$sudo='/usr/bin/sudo';}else{$sudo='';}
71 //if all options are set to no/false, return an error
72 if(!$opts['voicemail']&&!$opts['recordings']&&!$opts['configurations']&&!$opts['cdr']&&!$opts['fop']&&!$opts['include']){echo "Backup Error: You need to set at least one option\n";showopts();}
73
74 //run backup remotly if requested
75 if($opts['remotesshhost'] && $opts['remotesshkey']){
76     $opts['now']=$opts['remotesshhost'].'.'.$opts['now'];
77     chmod($opts['remotesshkey'],0400);
78     $user=(isset($opts['remotesshuser']) && $opts['remotesshuser']!='')?$opts['remotesshuser'].'\@':'';
79     $exec='/usr/bin/ssh -o StrictHostKeyChecking=no -i '.$opts['remotesshkey'].' '.$user.$opts['remotesshhost'];
80     $exec.=' \'. /usr/sbin/amportal;';
81     $exec.='$ASTVARLIBDIR/bin/ampbackup.php cli ';
82     foreach($opts as $key => $val){
83         switch($key){
84             case 'remotesshhost':
85             case 'remotesshkey':
86             case 'remoteuser':
87             case 'remotesshkey':
88             case 'budir':
89             case 'id':
90             case 'overwritebackup':
91                 $exec.=' --'.$key.'=';
92                 break;
93             case 'exclude':
94             case 'include':
95                 $exec.=' --'.$key.'='.str_replace(array("\n","\r","\r\n"),' ',$val);
96                 break;
97             default:
98                 $exec.=' --'.$key.'='.$val;
99                 break;
100         }
101     }
102     $exec.='; echo $ASTVARLIBDIR';
103     $exec.='\'';
104     exec($exec,$rbudir,$execok);
105     //if the ssh completed with exit code 0, copy backup over to this server
106     if($execok==0){
107         mkdir($opts['budir'].'/'.$opts['name']);//ensure dir structure
108         $exec='/usr/bin/scp -i '.$opts['remotesshkey'].' -c blowfish '.$user.$opts['remotesshhost'].':'.$rbudir[0].'/backups/'.$opts['name'].'/'.$opts['now'].'.tar.gz '.$opts['budir'].'/'.$opts['name'];
109         exec($exec,$ret);
110     }
111     //if we have the backup file localy, delete it from the remote server
112     if(is_file($opts['budir'].'/'.$opts['name'].'/'.$opts['now'].'.tar.gz')){
113         $exec='/usr/bin/ssh -o StrictHostKeyChecking=no -i '.$opts['remotesshkey'].' '.$user.$opts['remotesshhost'];
114         $exec.=' \'dir='.$rbudir[0].'/backups/'.$opts['name'].'; rm -f $dir/'.$opts['now'].'.tar.gz; if [ ! "$(ls -A $dir)" ]; then rmdir $dir; fi\'';
115         exec($exec,$ret);
116     }
117     if($opts['remoterestore']=='yes'){//restore to local machine if requested
118         include_once($amp_conf['AMPWEBROOT'].'/admin/modules/backup/functions.inc.php');
119         @backup_restore_tar($opts['budir'].'/'.$opts['name'].'/'.$opts['now'].'.tar.gz', $opts['now'].'.tar.gz','ALL');
120     }
121 }else{//otherwise, run it localy
122     system('/bin/rm -rf /tmp/ampbackups.'.$opts['now'].' > /dev/null  2>&1');//remove stale backup
123     system('/bin/mkdir /tmp/ampbackups.'.$opts['now'].' > /dev/null  2>&1');//create directory for current backup
124     //backup voicmail if requested
125     if($opts['voicemail']){system('/bin/tar -Pcz -f /tmp/ampbackups.'.$opts['now'].'/voicemail.tar.gz '.$amp_conf['ASTSPOOLDIR'].'/voicemail');}
126     //backup recordings in requested
127     if($opts['recordings']){system('/bin/tar -Pcz -f /tmp/ampbackups.'.$opts['now'].'/recordings.tar.gz '.$amp_conf['ASTVARLIBDIR'].'/sounds/custom');}
128     //backup configurations if requested
129     if($opts['configurations']){
130         system($amp_conf['ASTVARLIBDIR'].'/bin/dumpastdb.php '.$opts['now'].' > /dev/null');
131     
132         $cmd='/bin/tar -Pcz -f /tmp/ampbackups.'.$opts['now'].'/configurations.tar.gz '.$amp_conf['ASTVARLIBDIR'].'/agi-bin/ ';
133         $cmd.=$amp_conf['ASTVARLIBDIR'].'/bin/ '.$amp_conf['ASTETCDIR'].' /etc/amportal.conf ';
134         if($opts['admin']=='yes'){$cmd.=$amp_conf['AMPWEBROOT'].'/admin ';}//include admin/ unless otherwise requested
135         if(isset($amp_conf['ZAP2DAHDICOMPAT']) && $amp_conf['ZAP2DAHDICOMPAT']==true){$cmd.='/etc/dahdi ';}else{$cmd.='/etc/zaptel.conf ';}//include zap OR dahdi
136         $cmd.='/tmp/ampbackups.'.$opts['now'].'/astdb.dump';
137         system($cmd);
138         if($opts['include']){
139             $exclude='';
140             if(isset($opts['exclude']) && $opts['exclude']!=''){
141                 $excludes=str_replace(array("\n","\r","\r\n"),' ',$opts['exclude']);
142                 $ex=explode('  ',$excludes);
143                 foreach($ex as $x){ //exclude each option in the space delimited list
144                     $exclude.='--exclude='.$x.' ';
145                 }
146             }
147             $inculde=str_replace(array("\n","\r","\r\n"),' ',$opts['include']);
148             $exec=$sudo.' /bin/tar -Pcz -f /tmp/ampbackups.'.$opts['now'].'/phoneconfig.tar.gz '.$inculde.'  '.$exclude;
149             exec($exec,$ret);
150         }
151         $ignorbackup=(($opts['overwritebackup']!='yes')?' --ignore-table='.$amp_conf['AMPDBNAME'].'.backup ':' ');
152         system('mysqldump --add-drop-table -h'.$amp_conf['AMPDBHOST'].' -u'.$amp_conf['AMPDBUSER'].' -p'.$amp_conf['AMPDBPASS'].' --database '.$amp_conf['AMPDBNAME'].$ignorbackup.' > /tmp/ampbackups.'.$opts['now'].'/asterisk.sql');
153     }
154     //backup cdr if requested
155     if($opts['cdr']){
156         system('/bin/tar -Pcz -f /tmp/ampbackups.'.$opts['now'].'/cdr.tar.gz '.$amp_conf['AMPWEBROOT'].'/admin/cdr');
157         system('mysqldump --add-drop-table -h '.$amp_conf['AMPDBHOST'].' -u '.$amp_conf['AMPDBUSER'].' -p'.$amp_conf['AMPDBPASS'].' --database asteriskcdrdb > /tmp/ampbackups.'.$opts['now'].'/asteriskcdr.sql');
158     }
159     //backup FOP if requested
160     if($opts['fop']){system('/bin/tar -Pcz -f /tmp/ampbackups.'.$opts['now'].'/fop.tar.gz '.$amp_conf['AMPWEBROOT'].'/panel');}
161     system('/bin/mkdir -p '.$opts['budir'].'/'.$opts['name'].' > /dev/null  2>&1');
162     system('/bin/tar -Pcz -f '.$opts['budir'].'/'.$opts['name'].'/'.$opts['now'].'.tar.gz /tmp/ampbackups.'.$opts['now']);
163     system('/bin/rm -rf /tmp/ampbackups.'.$opts['now'].' > /dev/null  2>&1');
164 }
165
166 /*
167  FTP Sucessfull Backup's to FTPSERVER
168  leaves $ftpbackup which gets overwritten next time but can be checked to see if there were errors.
169  IMPORTANT - if testing as root, delete files since backup runs as asterisk and will fail here since
170              root leave the file around and asterisk can't overwrite it.
171  Note - the hardcoded full backup that cron does will overwrite each day at destination.
172 */
173 if( $opts['ftpuser'] && $opts['ftppass'] && $opts['ftphost']){
174     $fh=fopen($opts['ftpfile'], 'w');
175     $data='user '.$opts['ftpuser'].' '.$opts['ftppass']." \n";
176     $data.="binary\n";
177     if($opts['ftpdir']!=''){$data.="cd ${opts['ftpdir']} \n";}
178     $data.='lcd '.$opts['budir'].'/'.$opts['name']."/\n";
179     $data.='put '.$opts['now'].".tar.gz\n";
180     $data.='bye\n';
181     fwrite($fh, $data);
182     fclose($fh);
183     exec('ftp -n '.$opts['ftphost'].' < '.$opts['ftpfile'].' ',$ftpres);
184     unlink($opts['ftpfile']);
185 }
186
187 //ssh backup
188 if($opts['sshkey'] && $opts['sshhost']){
189     if(!$opts['sshuser']){exec('whoami',$opts['sshuser']);}//use username of whoever scrip is running as if username isnt set
190     if($opts['sshdir']!=''){  //ensure that remote directory exists
191         system('/usr/bin/ssh -o StrictHostKeyChecking=no -i '.$opts['sshkey'].' '.$opts['sshuser'].'\@'.$opts['sshhost'].' mkdir -p '.$opts['sshdir']);
192     }
193     system('/usr/bin/scp -o StrictHostKeyChecking=no -i '.$opts['sshkey'].' '.$opts['budir'].'/'.$opts['name'].'/'.$opts['now'].'.tar.gz '.$opts['sshuser'].'\@'.$opts['sshhost'].':'.$opts['sshdir']);
194 }
195
196 //email backup
197 if($opts['emailaddr']){
198     if(filesize($opts['budir'].'/'.$opts['name']) <= size2bytes($opts['emailmaxsize'].$opts['emailmaxtype'])){
199         //credit to: http://articles.sitepoint.com/print/advanced-email-php
200         $hostname=exec('/bin/hostname',$name);
201         $subject = 'FreePBX backup of '.$hostname;
202         $emessage = sprintf("Hello. Attached, please find your FreePBX backup file from backup set: %s, run on %s, at %s",$opts['name'],$hostname,date('Y-m-d h:i:sa'));
203         
204         // Obtain file info
205         $filename=$opts['budir'].'/'.$opts['name'].'/'.$opts['now'].'.tar.gz';
206         exec('file -bi '.$filename,$type);
207         $file_type=$type[0];
208         
209         $headers = 'From: '.$amp_conf['AMPBACKUPEMAILFROM'];
210         // Read the file to be attached ('rb' = read binary)
211         $file = fopen($filename,'rb');
212         $data = fread($file,filesize($filename));
213         fclose($file);
214         
215         // Generate a random boundary string
216         $mime_boundary='==Multipart_Boundary_x'.md5(time()).'x';
217         // Add the headers for a file attachment
218         $headers.="\nMIME-Version: 1.0\n";
219         $headers.="Content-Type: multipart/mixed;\n";
220         $headers.=" boundary=\"{$mime_boundary}\"";
221         // Add a multipart boundary above the plain message
222         $message="This is a multi-part message in MIME format.\n\n";
223         $message.="--{$mime_boundary}\n";
224         $message.="Content-Type: text/plain; charset=\"iso-8859-1\"\n";
225         $message.="Content-Transfer-Encoding: 7bit\n\n";
226         $message.=$emessage . "\n\n";
227         // Base64 encode the file data
228         $data = chunk_split(base64_encode($data));
229         // Add file attachment to the message
230         $message.="--{$mime_boundary}\n";
231         $message.="Content-Type: {$file_type};\n";
232         $message.=' name="'.$opts['now'].'.tar.gz'."\"\n";
233         //$message.="Content-Disposition: attachment;\n";
234         //$message.=" filename=\"{$file}\"\n";
235         $message.="Content-Transfer-Encoding: base64\n\n";
236         $message.=$data . "\n\n";
237         $message.="--{$mime_boundary}--\n";
238         
239         //debug output
240         //echo "To:\n";echo $opts['emailaddr'];echo "\n\nSubject:\n";echo $subject;echo "\n\nMessage:\n";echo $message;echo "\n\nHeaders:\n";echo $headers."\n";
241         // Send the message
242         mail($opts['emailaddr'], $subject, $message, $headers);
243     }
244 }
245
246 function size2bytes($str){
247   $bytes=0;
248   $bytes_array=array('B'=>1, 'KB'=>1024, 'MB'=>1024*1024, 'GB'=>1024*1024*1024,
249                                 'TB'=>1024*1024*1024*1024, 'PB'=>1024*1024*1024*1024*1024);
250   $bytes=floatval($str);
251   if(preg_match('#([KMGTP]?B)$#si',$str,$matches) && !empty($bytes_array[$matches[1]])){
252       $bytes*=$bytes_array[$matches[1]];
253   }
254   $bytes=intval(round($bytes, 2));
255   return $bytes;
256 }
257
258 function showopts(){
259     echo "\n";
260     echo "# ampbackup.php Backup-set-ID \n";
261     echo "This script Reads the backup options from the BackupTable then runs the backup picking up the items that were turned.\n";
262     echo "\n";echo "                         --OR--                         \n";echo "\n";
263     echo "The program is called from the backup.php script and implemented immediately as such:\n";
264     echo "# ampbackup.php Name Voicemail(yes/no) Recordings(yes/no) Config_files(yes/no) CDR(yes/no) FOP(yes/no)\n";
265     echo " \n";
266     echo "example: ampbackup.php \"My_Nightly_Backup\" yes yes no no yes\n";
267     exit(1);
268 }
269
270 function getOpts(){
271     array_shift($_SERVER['argv']);
272     foreach($_SERVER['argv'] as $arg){
273         $arg=explode('=',$arg);
274         //remove leading '--'
275         if(substr($arg['0'],0,2) == '--'){$arg['0']=substr($arg['0'],2);}
276         $opts[$arg['0']]=isset($arg['1'])?$arg['1']:null;
277     }
278     return isset($opts)?$opts:false;
279 }
280
281 ?>
282
Note: See TracBrowser for help on using the browser.