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         ini_set('memory_limit', '256M'); // we need alot of memory
68         set_time_limit(0);
69         
70         $argv = $_SERVER['argv'];
71         array_shift($argv);
72         array_shift($argv);
73         
74         $opts = explode(',', 'table==,where==,dump-dir==,dump-dir==,debug=');
75         require_once 'Console/Getopt.php';
76         $go = Console_Getopt::getopt2($argv, '', $opts );
77         if (is_object($go)) {
78             die($go->toString());
79         }
80          
81         foreach($go[0] as $ar) {
82             $args[substr($ar[0],2)] = $ar[1];
83         }
84         $errs = array();
85         foreach($opts as $req) {
86             if (substr($req,-2, 2) != '==') { // skip optional arguments
87                 continue;
88             }
89             if (empty($args[substr($req,0, -2)])) {
90                 $errs[] = "--".substr($req,0, -2) . ' is required';
91             }
92         }
93         if (!empty($errs)) {
94             die(print_R($errs,true));
95         }
96         if (!empty($args['debug'])) {
97             DB_DataObject::debugLevel($args['debug']);
98         }
99         $this->args = $args;
100         $this->out = array();
101         $this->discoverChildren($this->args['table'], $this->args['where'], true);
102         //print_R($this->deletes);
103         //print_r($this->dumps);
104         //exit;
105         
106         $this->discover($this->args['table'], $this->args['where'], true);
107          
108         
109         if (!file_exists($args['dump-dir'])) {
110             mkdir($args['dump-dir'], 0777, true);
111         }
112          
113         $this->generateInsert();
114         $this->generateDelete();
115         $this->generateShell();
116
117         echo "DELETING:\n";
118         foreach($this->deletes as $tbl => $ar) {
119             if (empty($ar)) { continue; }
120             echo "   " .$tbl . ' -> ' . count(array_keys($ar)) . " Records\n";
121         }
122         echo "DUMPING:\n";
123         foreach($this->dumps as $tbl => $ar) {
124             if (empty($ar)) { continue; }
125             echo "   " .$tbl . ' -> ' . count(array_keys($ar)) . " Records\n";
126         }
127         echo "FILES:"
128         echo "   Total : ". count($this->childfiles) . " using " . floor($this->filesize/1000000) . "Mb\n";
129         
130         echo "GENERATED FILES:\n";
131         // summary
132         echo "    ". implode("\n    ", $this->out). "\n";
133         
134         
135         exit;
136         
137       
138          
139     }
140      
141     var $deletes = array(); // TABLE => [key] => TRUE|FALSE
142     var $dumps = array(); // TABLE => [key] => TRUE|FALSE - if it's been scanned..
143     var $dscan = array(); // TABLE:COL => [value => TRUE|FALSE] - if its been scanned..
144     var $childfiles = array(); // array of [ 'sourcedirectory' , 'subdirectory(s) and filename' ]
145     var $childthumbs = array(); // array of [ 'filename', 'filename' ,......]
146     var $filesize = 0; // size of files to be saved. (not total deletd..)
147     /**
148      * scan table for
149      * a) what depends on it (eg. child elements) - which will be deleted.
150      * b) what it depends on it (eg. parent elements) - which will be dumped..
151      */
152         
153     function discover($table, $where, $is_delete = false )
154     {
155         
156         if (!isset($this->dumps[$table])) {
157             $this->dumps[$table] = array();
158         }
159         if ($is_delete && !isset($this->deletes[$table])) {
160             $this->deletes[$table] = array();
161         }
162         //DB_DataObject::debugLevel(1);
163         $x = DB_DataObject::factory($table);
164         if (PEAR::isError($x)) {
165             if (isset($this->dumps[$table])) {
166                 unset($this->dumps[$table]); // links to non-existant tables..
167             }
168             return;
169         }
170         
171         $keys = $x->keys();
172           
173         if (is_array( $where)) {
174             $x->whereAddIn($keys[0] , $where, 'int');
175         } else {
176         
177             $x->whereAdd($where);
178         }
179         // what we need
180         // a) id's of elements in this table
181         // b) columns which point to other tables..
182         $links = $x->links();
183         $cols = array_keys($links);
184       
185          array_push($cols, $keys[0]);
186          
187         
188         $x->selectAdd();
189         $x->selectAdd('`'.  implode('`,`', $cols) . '`');
190         $x->find();
191         //DB_DataObject::debugLevel(0);
192         while ($x->fetch()) {
193             foreach($cols as $k) {
194                 if (empty($x->$k)) { // skip blanks.
195                     continue;
196                 }
197                 if (isset($links[$k])) {
198                     // it's a sublink..
199                     $kv = explode(':', $links[$k]);
200                     if (!isset($this->dumps[$kv[0]])) {
201                         $this->dumps[$kv[0]] = array();
202                     }
203                     if (!isset($this->dumps[$kv[0]][$x->$k])) {
204                         $this->dumps[$kv[0]][$x->$k] = 0; // not checked yet..
205                     }
206                     continue;
207                 }
208                 // assume it's the key..
209                 if (empty($this->dumps[$table][$x->$k])) {
210                     $this->dumps[$table][$x->$k] = 1; // we have checked this one...
211                 }
212                 //if ($is_delete && !isset($this->deletes[$table][$x->$k])) {
213                 //    
214                 //    $this->deletes[$table][$x->$k] = 0 ; // not checked yet..
215                 //}
216                 
217                 
218             }
219             
220         }
221         $x->free();
222         // flag as checked if we where given an array.. - as some links might have been broken.
223         if (is_array($where)) {
224             foreach($where as $k) {
225                 $this->dumps[$table][$k] = 1;
226             }
227         }
228         
229         
230         // itterate through dumps to find what needs discovering
231         foreach($this->dumps as $k=>$v) {
232             $ar = array();
233             foreach($v as $id => $fetched) {
234                 if (!$fetched) {
235                     $ar[] = $id;
236                 }
237             }
238             if (count($ar)) { 
239                 $this->discover($k, $ar,false);
240             }
241              
242         }
243         
244         
245          
246         
247         
248     }
249     
250      
251     function discoverChildren($table, $where, $col=false  )
252     {
253         echo "discoverChildren:$table:$col:". (is_array($where) ? (count($where) . " children" ): $where ). "\n";
254         global $_DB_DATAOBJECT;
255         $do = DB_DataObject::factory($table);
256         if (PEAR::isError($do)) {
257             if (isset($this->dumps[$table])) {
258                 unset($this->dumps[$table]); // links to non-existant tables..
259             }
260             echo "SKIPPING invalid table $table\n";
261             return;
262         }
263         if (!isset($this->dumps[$table])) {
264             $this->dumps[$table] = array();
265         }
266         if (!isset($this->deletes[$table])) {
267             $this->deletes[$table] = array();
268         }
269         
270         
271         $keys = $do->keys();
272           
273         if (is_array( $where)) {
274             $do->whereAddIn($col ? $col : $keys[0] , $where, 'int');
275         } else {
276         
277             $do->whereAdd($where);
278         }
279         
280         static $children = array();
281         
282         if (!isset($children[$table])) { 
283             $children[$table] = array();
284             // force load of linsk
285             $do->links();
286             foreach($_DB_DATAOBJECT['LINKS'][$do->database()] as $tbl => $links) {
287                 // hack.. - we should get rid of this hack..
288                 if ($tbl == 'database__render') {
289                     continue;
290                 }
291                 //if ($tbl == $tn) { // skip same table 
292                 //    continue;
293                 //}
294                 foreach ($links as $tk => $kv) {
295                     
296                    // var_dump($tbl);
297                     list($k,$v) = explode(':', $kv);
298                     if ($k != $table) {
299                         continue;
300                     }
301                     $add = implode(':', array($tbl, $tk));
302                     //echo "ADD $tbl $tk=>$kv : $add\n";
303                     $children[$table][$add] = true;
304                     
305                 }
306                 
307             }
308             print_R($children);
309         }
310          
311         $do->selectAdd();
312         $key = $keys[0];
313         $do->selectAdd($key);
314         echo "GOT ". $do->find() ." results\n";
315         //DB_DataObject::debugLevel(0);
316         while ($do->fetch()) {
317             $this->dumps[$table][$do->$key] = 0;
318             if (!isset($this->deletes[$table][$do->$key])) {
319                 $this->deletes[$table][$do->$key] = 0;
320             }
321             
322             foreach($children[$table] as $kv=>$t) {
323                 if (!isset($this->dscan[$kv])) {
324                     $this->dscan[$kv] = array();
325                 }
326                 if (!isset($this->dscan[$kv][$do->$key])) {
327                     $this->dscan[$kv][$do->$key]= 0; // unscanned.
328                 }
329             }
330         }
331         $do->free();
332          
333         // now iterate throught dependants. and scan them.
334         
335         
336         foreach($this->dscan as $kv => $ids) {
337             $ar = array();
338             foreach($ids as $id => $checked) {
339                 if (!$checked) {
340                     $this->dscan[$kv][$id] = 1; // flag it as checked.
341                     $ar[] = $id;
342                 }
343             }
344             
345             if (empty($ar)) {
346                 continue;
347                 
348             }
349             list($k, $v) = explode(':', $kv);
350             $this->discoverChildren($k, $ar, $v);
351             
352         }
353         
354         
355         
356         
357     }
358      
359     function generateDelete() {  
360         $target = $this->args['dump-dir'] .'/'. date('Y-m-d').'.delete.sql';
361         $this->out[] = $target;
362         $fh = fopen($target, 'w');
363         
364         
365         
366         foreach($this->deletes as $tbl=>$ar) {
367             
368             $do = DB_DataObject::factory($tbl);
369             $tbl = $do->tableName();
370             $keys = $do->keys();
371             $key = $keys[0];
372             $do->whereAddIn($keys[0] , array_keys($ar), 'int');
373             $do->find();
374             $archivePaths = method_exists($do,'archivePaths');
375             $listThumbs = method_exists($do,'listThumbs');
376             while ($do->fetch()) {
377                 
378                 if ($archivePaths) {
379                     $ct = $do->archivePaths();
380                     if ($ct) {
381                         $this->childfiles[] = $ct;
382                     }
383                 }
384                 if ($listThumbs) {
385                     $ct = $do->listThumbs();
386                     if($ct) {
387                         $this->childthumbs[] = $ct;
388                     }
389                 }
390                 $id = $do->$key;
391                 
392                 fwrite($fh, "DELETE FROM `$tbl` WHERE `$key` = $id;\n"); // we assume id's and nice column names...
393             }
394             $do->free();
395         }
396         fclose($fh);
397     }
398     function generateShell() {
399         
400         if (empty($this->childfiles) && empty($this->childthumbs)) {
401             return;
402         }
403         $target = $this->args['dump-dir'] .'/'. date('Y-m-d').'.copy.sh';
404         $this->out[] = $target;
405         $fh = fopen($target, 'w');
406         
407         $target = $this->args['dump-dir'] .'/'. date('Y-m-d').'.delete.sh';
408         $this->out[] = $target;
409         $fh2 = fopen($target, 'w');
410         
411         $target = $this->args['dump-dir'] .'/'. date('Y-m-d').'.restore.sh';
412         $this->out[] = $target;
413         $fh3 = fopen($target, 'w');
414         
415         $fs = 0;
416         foreach($this->childfiles as  $v) {
417             $fs += filesize($v[0].'/'.$v[1]);
418             fwrite($fh,"mkdir -p " . escapeshellarg(dirname($this->args['dump-dir'] .'/'.$v[1])) ."\n" );
419             fwrite($fh,"cp " . escapeshellarg($v[0].'/'.$v[1]) . ' ' . escapeshellarg($this->args['dump-dir'] .'/'.$v[1]) ."\n" );
420             
421             fwrite($fh3,"mkdir -p " . escapeshellarg(dirname($v[0].'/'.$v[1])) ."\n" );
422             fwrite($fh3,"cp " .  escapeshellarg($this->args['dump-dir'] .'/'.$v[1]) . ' ' . escapeshellarg($v[0].'/'.$v[1]) . "\n" );
423             
424             fwrite($fh2,"rm " . escapeshellarg($v[0].'/'.$v[1]) ."\n" );
425         }
426         fclose($fh);
427         fclose($fh3); // restore does not need to bother with thumbnails.
428         
429         $this->filesize = $fs;
430         
431         
432         foreach($this->childthumbs as  $v) {
433             foreach($v as $vv) { 
434                 fwrite($fh2,"rm " . escapeshellarg($vv). "\n");
435             }
436         }
437         fclose($fh2);
438     }
439      
440     function generateInsert()
441     {
442         $target = $this->args['dump-dir'] .'/'. date('Y-m-d').'.sql';
443         $this->out[] = $target;
444         $fh = fopen($target,'w');
445          
446          
447         
448         foreach($this->dumps as $tbl => $ar) {
449             if (empty($ar)) {
450                 continue;
451             }
452             $do = DB_DataObject::factory($tbl);
453              
454             $keys = $do->keys();
455          
456             $do->whereAddIn($keys[0] , array_keys($ar), 'int');
457             $do->find();
458             while ($do->fetch()) {
459                 fwrite($fh,$this->toInsert($do));
460             }
461              $do->free();
462             
463         }
464         fclose($fh);
465         
466         
467     }
468
469     
470       
471     /**
472      * toInsert - does not handle NULLS... 
473      */
474     function toInsert($do)
475     {
476         $kcol = array_shift($do->keys());
477          
478         // for auto_inc column we need to use a 'set argument'...
479         $items = $do->table();
480         //print_R($items);
481         
482         // for
483         $leftq     = '';
484         $rightq    = '';
485         
486         $table = $do->tableName();
487         
488          
489         foreach(  $items  as $k=>$v)
490         {
491             if ($leftq) {
492                 $leftq  .= ', ';
493                 $rightq .= ', ';
494             }
495             
496             $leftq .= '`' . $k . '`';
497             
498              
499             
500             
501             if ($v & DB_DATAOBJECT_STR) {
502                 $rightq .= $do->_quote((string) (
503                         ($v & DB_DATAOBJECT_BOOL) ? 
504                             // this is thanks to the braindead idea of postgres to 
505                             // use t/f for boolean.
506                             (($do->$k === 'f') ? 0 : (int)(bool) $do->$k) :  
507                             $do->$k
508                     )) . " ";
509                 continue;
510             }
511             if (is_numeric($do->$k)) {
512                 $rightq .=" {$do->$k} ";
513                 continue;
514             }
515             $rightq .= ' ' . intval($do->$k) . ' ';
516         }
517         
518         return "INSERT INTO `{$table}` ($leftq) VALUES ($rightq);\n";
519         
520     }
521     
522     
523 }