Dump.php
[Pman.Admin] / Dump.php
1 <?php
2
3
4 /**
5  * This should allow you to dump a series of data, so it could be restored later...
6  * The format will be an SQL file...
7  *
8  * usage:
9  *    php index.php  Admin/Dump --table=Project --where="id=123"
10  *              --dump-dir=/directory_to_put_sql+shell files
11  *
12  *    outputs list of generated files.
13  *    
14  *     RESTORE FILES:
15  *      {DATE}.sql - the recreate sql including all dependancies, run with mysql DB -f  < ....
16  *      {DATE}.restore.sh - shell script to recreate files that where removed (excluding thumgs)
17  *      
18  *     BACKUP
19  *      {DATE}.copy.sh - shell script that backs up all the related files.
20  *      
21  *     DESTROY
22  *      {DATE}.delete.sql - the delete data sql.
23  *      {DATE}.delete.sh - shell script to delete the files related to these records
24  
25  *    
26  *  Basically it has to output all the records and their dependants. (parent and children)
27  *
28  *  Then when deleting it deletes record + children..
29  *
30  *
31  *  Each ouput is simple insert statement..
32  *
33  *
34  *  TODO - handle Images table (or similar) where we use tablename=XXXX, tid=.... etc..
35  *
36  *
37  *  INTERFACES :
38  *
39  *      DataObjects->archivePaths() - returns array ( sourcedirectory, remainder of path to dependant file )
40  *      DataObjects->listThumbs() - returns array ( list of full path to thumbnail urls. )
41  *
42  *
43  *  DISCOVERY
44  *    
45  *
46  * 
47  */
48
49 require_once 'Pman.php';
50
51 class Pman_Admin_Dump extends Pman {
52     
53     function getAuth()
54     {
55         
56         if (!HTML_FlexyFramework::get()->cli) {
57             die("Access only permitted from cli");
58         }
59         
60     }
61     var $args = array();
62     var $deps = array(); // list of dependants
63     var $out = array(); // list of created sql/shell scripts.
64     
65     function get($path )
66     {
67         $argv = $_SERVER['argv'];
68         array_shift($argv);
69         array_shift($argv);
70         
71         $opts = explode(',', 'table==,where==,dump-dir==');
72         require_once 'Console/Getopt.php';
73         $go = Console_Getopt::getopt2($argv, '', $opts );
74         if (is_object($go)) {
75             die($go->toString());
76         }
77          
78         foreach($go[0] as $ar) {
79             $args[substr($ar[0],2)] = $ar[1];
80         }
81         $errs = array();
82         foreach($opts as $req) {
83             if (empty($args[substr($req,0, -2)])) {
84                 $errs[] = "--".substr($req,0, -2) . ' is required';
85             }
86         }
87         if (!empty($errs)) {
88             die(print_R($errs,true));
89         }
90         
91         $this->args = $args;
92         $this->out = array();
93         $this->discoverChildren($this->args['table'], $this->args['where'], true);
94         //print_R($this->deletes);
95         //print_r($this->dumps);
96         //exit;
97         
98         $this->discover($this->args['table'], $this->args['where'], true);
99          
100         
101         if (!file_exists($args['dump-dir'])) {
102             mkdir($args['dump-dir'], 0777, true);
103         }
104          
105         $this->generateInsert();
106         $this->generateDelete();
107         $this->generateShell();
108            
109         echo "GENERATED FILES:";
110         print_r($out);
111         exit;
112         
113       
114          
115     }
116      
117     var $deletes = array(); // TABLE => [key] => TRUE|FALSE
118     var $dumps = array(); // TABLE => [key] => TRUE|FALSE - if it's been scanned..
119     var $dscan = array(); // TABLE:COL => [value => TRUE|FALSE] - if its been scanned..
120     /**
121      * scan table for
122      * a) what depends on it (eg. child elements) - which will be deleted.
123      * b) what it depends on it (eg. parent elements) - which will be dumped..
124      */
125         
126     function discover($table, $where, $is_delete = false )
127     {
128         
129         if (!isset($this->dumps[$table])) {
130             $this->dumps[$table] = array();
131         }
132         if ($is_delete && !isset($this->deletes[$table])) {
133             $this->deletes[$table] = array();
134         }
135         //DB_DataObject::debugLevel(1);
136         $x = DB_DataObject::factory($table);
137         if (PEAR::isError($x)) {
138             if (isset($this->dumps[$table])) {
139                 unset($this->dumps[$table]); // links to non-existant tables..
140             }
141             return;
142         }
143         
144         $keys = $x->keys();
145           
146         if (is_array( $where)) {
147             $x->whereAddIn($keys[0] , $where, 'int');
148         } else {
149         
150             $x->whereAdd($where);
151         }
152         // what we need
153         // a) id's of elements in this table
154         // b) columns which point to other tables..
155         $links = $x->links();
156         $cols = array_keys($links);
157       
158          array_push($cols, $keys[0]);
159          
160         
161         $x->selectAdd();
162         $x->selectAdd('`'.  implode('`,`', $cols) . '`');
163         $x->find();
164         //DB_DataObject::debugLevel(0);
165         while ($x->fetch()) {
166             foreach($cols as $k) {
167                 if (empty($x->$k)) { // skip blanks.
168                     continue;
169                 }
170                 if (isset($links[$k])) {
171                     // it's a sublink..
172                     $kv = explode(':', $links[$k]);
173                     if (!isset($this->dumps[$kv[0]])) {
174                         $this->dumps[$kv[0]] = array();
175                     }
176                     if (!isset($this->dumps[$kv[0]][$x->$k])) {
177                         $this->dumps[$kv[0]][$x->$k] = 0; // not checked yet..
178                     }
179                     continue;
180                 }
181                 // assume it's the key..
182                 if (empty($this->dumps[$table][$x->$k])) {
183                     $this->dumps[$table][$x->$k] = 1; // we have checked this one...
184                 }
185                 //if ($is_delete && !isset($this->deletes[$table][$x->$k])) {
186                 //    
187                 //    $this->deletes[$table][$x->$k] = 0 ; // not checked yet..
188                 //}
189                 
190                 
191             }
192             
193         }
194         // flag as checked if we where given an array.. - as some links might have been broken.
195         if (is_array($where)) {
196             foreach($where as $k) {
197                 $this->dumps[$table][$k] = 1;
198             }
199         }
200         
201         
202         // itterate through dumps to find what needs discovering
203         foreach($this->dumps as $k=>$v) {
204             $ar = array();
205             foreach($v as $id => $fetched) {
206                 if (!$fetched) {
207                     $ar[] = $id;
208                 }
209             }
210             if (count($ar)) { 
211                 $this->discover($k, $ar,false);
212             }
213              
214         }
215         
216         
217          
218         
219         
220     }
221     
222      
223     function discoverChildren($table, $where, $col=false  )
224     {
225         global $_DB_DATAOBJECT;
226         $do = DB_DataObject::factory($table);
227         if (PEAR::isError($do)) {
228             if (isset($this->dumps[$table])) {
229                 unset($this->dumps[$table]); // links to non-existant tables..
230             }
231             return;
232         }
233         if (!isset($this->dumps[$table])) {
234             $this->dumps[$table] = array();
235         }
236         if (!isset($this->deletes[$table])) {
237             $this->deletes[$table] = array();
238         }
239         
240         
241         $keys = $do->keys();
242           
243         if (is_array( $where)) {
244             $do->whereAddIn($col ? $col : $keys[0] , $where, 'int');
245         } else {
246         
247             $do->whereAdd($where);
248         }
249         
250         static $children = array();
251         
252         if (!isset($children[$table])) { 
253             
254             // force load of linsk
255             $do->links();
256             foreach($_DB_DATAOBJECT['LINKS'][$do->database()] as $tbl => $links) {
257                 // hack.. - we should get rid of this hack..
258                 if ($tbl == 'database__render') {
259                     continue;
260                 }
261                 //if ($tbl == $tn) { // skip same table 
262                 //    continue;
263                 //}
264                 foreach ($links as $tk => $kv) {
265                     
266                    // var_dump($tbl);
267                     list($k,$v) = explode(':', $kv);
268                     if ($k != $table) {
269                         continue;
270                     }
271                     $add = implode(':', array($tbl, $tk));
272                     //echo "ADD $tbl $tk=>$kv : $add\n";
273                     $children[$table][$add] = true;
274                     
275                 }
276                 
277             }
278         }
279         if (empty($children[$table])) {
280             // BLANK deletes???
281             return;
282         }
283        // DB_DataObject::debugLevel(1);
284         $do->selectAdd();
285         $key = $keys[0];
286         $do->selectAdd($key);
287         $do->find();
288         while ($do->fetch()) {
289             $this->dumps[$table][$do->$key] = 0;
290             if (!isset($this->deletes[$table][$do->$key])) {
291                 $this->deletes[$table][$do->$key] = 0;
292             }
293            
294             foreach($children[$table] as $kv=>$t) {
295                 if (!isset($this->dscan[$kv])) {
296                     $this->dscan[$kv] = array();
297                 }
298                 if (!isset($this->dscan[$kv][$do->$key])) {
299                     $this->dscan[$kv][$do->$key]= 0; // unscanned.
300                 }
301             }
302         }
303         
304         
305         // now iterate throught dependants. and scan them.
306         
307         
308         foreach($this->dscan as $kv => $ids) {
309             $ar = array();
310             foreach($ids as $id => $checked) {
311                 if (!$checked) {
312                     $this->dscan[$kv][$id] = 1; // flag it as checked.
313                     $ar[] = $id;
314                 }
315             }
316             
317             if (empty($ar)) {
318                 continue;
319                 
320             }
321             list($k, $v) = explode(':', $kv);
322             $this->discoverChildren($k, $ar, $v);
323             
324         }
325         
326         
327         
328         
329     }
330      
331     function generateDelete() {  
332         $target = $this->args['dump-dir'] .'/'. date('Y-m-d').'.delete.sql';
333         $this->out[] = $target;
334         $fh = fopen($target, 'w');
335         foreach($this->deletes as $tbl=>$ar) {
336             $do = DB_DataObject::factory($tbl);
337             $keys = $do->keys();
338             $key = $keys[0];
339             foreach($ar as $id => $deleted) { 
340                 fwrite($fh, "DELETE FROM `$tbl` WHERE `$key` = $id;\n"); // we assume id's and nice column names...
341             }
342         }
343         fclose($fh);
344     }
345     function generateShell() {
346         
347         if (empty($this->childfiles)) {
348             return;
349         }
350         $target = $this->args['dump-dir'] .'/'. date('Y-m-d').'.copy.sh';
351         $this->out[] = $target;
352         $fh = fopen($target, 'w');
353         
354         $target = $this->args['dump-dir'] .'/'. date('Y-m-d').'.delete.sh';
355         $this->out[] = $target;
356         $fh2 = fopen($target, 'w');
357         
358         $target = $this->args['dump-dir'] .'/'. date('Y-m-d').'.restore.sh';
359         $this->out[] = $target;
360         $fh3 = fopen($target, 'w');
361         
362         
363         foreach($this->childfiles as $s=>$v) {
364             fwrite($fh,"mkdir -p " . escapeshellarg(dirname($args['dump-dir'] .'/'.$v[1])) ."\n" );
365             fwrite($fh,"cp " . escapeshellarg($v[0].'/'.$v[1]) . ' ' . escapeshellarg($args['dump-dir'] .'/'.$v[1]) ."\n" );
366             
367             fwrite($fh3,"mkdir -p " . escapeshellarg(dirname($v[0].'/'.$v[1])) ."\n" );
368             fwrite($fh3,"cp " .  escapeshellarg($args['dump-dir'] .'/'.$v[1]) . ' ' . escapeshellarg($v[0].'/'.$v[1]) . "\n" );
369             
370             fwrite($fh2,"rm " . escapeshellarg($v[0].'/'.$v[1]) ."\n" );
371         }
372         fclose($fh);
373         fclose($fh3); // restore does not need to bother with thumbnails.
374         
375         
376         
377         foreach($this->childthumbs as $s=>$v) {
378             foreach($v as $vv) { 
379                 fwrite($fh2,"rm " . escapeshellarg($vv). "\n");
380             }
381         }
382         fclose($fh2);
383     }
384      
385     function generateInsert()
386     {
387         $target = $this->args['dump-dir'] .'/'. date('Y-m-d').'.sql';
388         $this->out[] = $target;
389         $fh = fopen($target,'w');
390          
391           
392         
393         
394         foreach($this->dumps as $tbl => $ar) {
395             if (empty($ar)) {
396                 continue;
397             }
398             $do = DB_DataObject::factory($tbl);
399              
400             $keys = $do->keys();
401          
402             $do->whereAddIn($keys[0] , $ar, 'int');
403             $do->find();
404             while ($do->fetch()) {
405                 fwrite($fh,$this->toInsert($do));
406             }
407              
408             
409         }
410         fclose($fh);
411         
412         
413     }
414
415     
416       
417     /**
418      * toInsert - does not handle NULLS... 
419      */
420     function toInsert($do)
421     {
422         $kcol = array_shift($do->keys());
423          
424         // for auto_inc column we need to use a 'set argument'...
425         $items = $do->table();
426         //print_R($items);
427         
428         // for
429         $leftq     = '';
430         $rightq    = '';
431         
432         
433         
434          
435         foreach(  $items  as $k=>$v)
436         {
437             if ($leftq) {
438                 $leftq  .= ', ';
439                 $rightq .= ', ';
440             }
441             
442             $leftq .= '`' . $k . '`';
443             
444              
445             
446             
447             if ($v & DB_DATAOBJECT_STR) {
448                 $rightq .= $do->_quote((string) (
449                         ($v & DB_DATAOBJECT_BOOL) ? 
450                             // this is thanks to the braindead idea of postgres to 
451                             // use t/f for boolean.
452                             (($do->$k === 'f') ? 0 : (int)(bool) $do->$k) :  
453                             $do->$k
454                     )) . " ";
455                 continue;
456             }
457             if (is_numeric($do->$k)) {
458                 $rightq .=" {$do->$k} ";
459                 continue;
460             }
461             $rightq .= ' ' . intval($do->$k) . ' ';
462         }
463         
464         return "INSERT INTO `{$table}` ($leftq) VALUES ($rightq);\n";
465         
466     }
467     
468     
469 }