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