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);exit;
95         
96         $this->discover($this->args['table'], $this->args['where'], true);
97         print_r($this->dumps);
98         exit;
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 (!$this->dumps[$table]) {
234             $this->dumps[$table] = array();
235         }
236         $keys = $do->keys();
237           
238         if (is_array( $where)) {
239             $do->whereAddIn($col ? $col : $keys[0] , $where, 'int');
240         } else {
241         
242             $do->whereAdd($where);
243         }
244         
245         static $children = array();
246         
247         if (!isset($children[$table])) { 
248             
249             // force load of linsk
250             $do->links();
251             foreach($_DB_DATAOBJECT['LINKS'][$do->database()] as $tbl => $links) {
252                 // hack.. - we should get rid of this hack..
253                 if ($tbl == 'database__render') {
254                     continue;
255                 }
256                 //if ($tbl == $tn) { // skip same table 
257                 //    continue;
258                 //}
259                 foreach ($links as $tk => $kv) {
260                     
261                    // var_dump($tbl);
262                     list($k,$v) = explode(':', $kv);
263                     if ($k != $table) {
264                         continue;
265                     }
266                     $add = implode(':', array($tbl, $tk));
267                     //echo "ADD $tbl $tk=>$kv : $add\n";
268                     $children[$table][$add] = true;
269                     
270                 }
271                 
272             }
273         }
274         if (empty($children[$table])) {
275             // BLANK deletes???
276             return;
277         }
278         
279         $do->selectAdd();
280         $key = $keys[0];
281         $do->selectAdd($key);
282         $do->find();
283         while ($do->fetch()) {
284             $this->dumps[$table][$do->id] = 0;
285             if (!isset($this->deletes[$table][$do->key])) {
286                 $this->deletes[$table][$do->key] = 0;
287             }
288            
289             foreach($children[$table] as $kv=>$t) {
290                 if (!isset($this->dscan[$kv])) {
291                     $this->dscan[$kv] = array();
292                 }
293                 if (!isset($this->dscan[$kv][$do->$key])) {
294                     $this->dscan[$kv][$do->$key]= 0; // unscanned.
295                 }
296             }
297         }
298         
299         
300         // now iterate throught dependants. and scan them.
301         
302         
303         foreach($this->dscan as $kv => $ids) {
304             $ar = array();
305             foreach($ids as $id => $checked) {
306                 if (!$checked) {
307                     $this->dscan[$kv][$id] = 1; // flag it as checked.
308                     $ar[] = $id;
309                 }
310             }
311             
312             if (empty($ar)) {
313                 continue;
314                 
315             }
316             list($k, $v) = explode(':', $kv);
317             $this->discoverChildren($k, $ar, $v);
318             
319         }
320         
321         
322         
323         
324     }
325     
326     function oldStuff() {
327         
328        
329         
330         $target = $args['dump-dir'] .'/'. date('Y-m-d').'.sql';
331         $out[] = $target;
332         $this->fh = fopen($target,'w');
333         //print_r($args);
334         //DB_DataObject::debugLevel(1);
335         // since we are runnign in cli mode... we will be a bit wild and free with verification
336         $x = DB_DataObject::factory($args['table']);
337         $x->{$args['col']} = $args['val'];
338         
339         $x->find();
340          
341         while ($x->fetch()) {
342         
343             fwrite($this->fh, $this->toInsert($x));
344             $this->dumpChildren($x);
345             
346         }
347         
348          
349         foreach($this->deps as $s=>$status) {
350             if (isset($this->dumped[$s])) {
351                 continue;
352             }
353             list($tbl, $key, $val) = explode(':', $s);
354             $dd = DB_DataObject::factory($tbl);
355             if ($dd->get($key,$val)) {
356                 fwrite($this->fh, $this->toInsert($dd));
357             }
358         }
359         
360         fclose($this->fh);
361     }
362     
363     function generateDelete() {  
364         $target = $this->args['dump-dir'] .'/'. date('Y-m-d').'.delete.sql';
365         $this->out[] = $target;
366         $fh = fopen($target, 'w');
367         foreach($this->childscanned as $s=>$v) {
368             list($tbl, $key, $val) = explode(':', $s);
369             fwrite($fh, "DELETE FROM $tbl WHERE $key = $val;\n"); // we assume id's and nice column names...
370              
371         }
372         fclose($fh);
373     }
374     function generateShell() {
375         
376         
377         $target = $this->args['dump-dir'] .'/'. date('Y-m-d').'.copy.sh';
378         $this->out[] = $target;
379         $fh = fopen($target, 'w');
380         
381         $target = $this->args['dump-dir'] .'/'. date('Y-m-d').'.delete.sh';
382         $this->out[] = $target;
383         $fh2 = fopen($target, 'w');
384         
385         $target = $this->args['dump-dir'] .'/'. date('Y-m-d').'.restore.sh';
386         $this->out[] = $target;
387         $fh3 = fopen($target, 'w');
388         
389         
390         foreach($this->childfiles as $s=>$v) {
391             fwrite($fh,"mkdir -p " . escapeshellarg(dirname($args['dump-dir'] .'/'.$v[1])) ."\n" );
392             fwrite($fh,"cp " . escapeshellarg($v[0].'/'.$v[1]) . ' ' . escapeshellarg($args['dump-dir'] .'/'.$v[1]) ."\n" );
393             
394             fwrite($fh3,"mkdir -p " . escapeshellarg(dirname($v[0].'/'.$v[1])) ."\n" );
395             fwrite($fh3,"cp " .  escapeshellarg($args['dump-dir'] .'/'.$v[1]) . ' ' . escapeshellarg($v[0].'/'.$v[1]) . "\n" );
396             
397             fwrite($fh2,"rm " . escapeshellarg($v[0].'/'.$v[1]) ."\n" );
398         }
399         fclose($fh);
400         fclose($fh3); // restore does not need to bother with thumbnails.
401         
402         
403         
404         foreach($this->childthumbs as $s=>$v) {
405             foreach($v as $vv) { 
406                 fwrite($fh2,"rm " . escapeshellarg($vv). "\n");
407             }
408         }
409         fclose($fh2);
410     }
411      
412     
413     
414     var $children = array(); // map of search->checked
415     var $childscanned = array();
416     var $childfiles = array();
417     var $childthumbs = array();
418     function dumpChildren($do)
419     {
420         $kcol = array_shift($do->keys());
421         $kid = $do->tableName() . ':' . $kcol . ':' . $do->{$kcol};
422         if (isset($this->childscanned[$kid])) {
423             return;
424         }
425         $this->childscanned[$kid] = true;
426         
427         if (method_exists($do,'archivePaths')) {
428             $ct = $do->archivePaths();
429             if ($ct) {
430                 $this->childfiles[$kid] = $ct;
431             }
432         }
433         if (method_exists($do,'listThumbs')) {
434             $ct = $do->listThumbs();
435             if($ct) {
436                 $this->childthumbs[$kid] = $ct;
437             }
438         }
439         
440         global $_DB_DATAOBJECT;
441         $do->links();; //force load
442         $tn = $do->tableName();
443         
444         
445         foreach($_DB_DATAOBJECT['LINKS'][$do->database()] as $tbl => $links) {
446             // hack.. - we should get rid of this hack..
447             if ($tbl == 'database__render') {
448                 continue;
449             }
450             //if ($tbl == $tn) { // skip same table 
451             //    continue;
452             //}
453             foreach ($links as $tk => $kv) {
454                 
455                // var_dump($tbl);
456                 list($k,$v) = explode(':', $kv);
457                 if ($k != $tn) {
458                     continue;
459                 }
460                 $add = implode(':', array($tbl, $tk, $do->$v));
461                 //echo "ADD $tbl $tk=>$kv : $add\n";
462                 $this->children[$add] = 0;
463                 
464             }
465             
466         }
467        // print_r($this->children);exit;
468         $ch = $this->children ;
469         
470         $todo = array();
471         foreach($ch as $s=>$status) {
472             if ($this->children[$s]) {
473                 continue;
474             }
475             // flag it as being done, so we do not recurse..
476             $this->children[$s] = 1;
477             
478             list($tbl, $key, $val) = explode(':', $s);
479             $dd = DB_DataObject::factory($tbl);
480             $dd->$key = $val;
481             $dd->find();
482             
483             while ($dd->fetch()) {
484                 $todo [] = clone($dd);
485                 // if we have dumped this already.. ignore it..
486                 
487             }
488             
489             
490         }
491         foreach($todo as $dd) {
492             fwrite($this->fh, $this->toInsert($dd));
493             $this->dumpChildren($dd);
494         }
495         
496         
497         
498     }
499     
500  
501     var $dumped  = array();
502     /**
503      * toInsert - does not handle NULLS... 
504      */
505     function toInsert($do)
506     {
507          $kcol = array_shift($do->keys());
508         $kid = $do->tableName() . ':' . $kcol . ':' . $do->{$kcol};
509         if (isset($this->dumped[$kid])) {
510             return;
511         }
512         //echo "DUMP: $kid\n";
513         $this->dumped[$kid] = true;
514         
515         // for auto_inc column we need to use a 'set argument'...
516         $items = $do->table();
517         //print_R($items);
518         $quoteIdentifiers  = !empty($_DB_DATAOBJECT['CONFIG']['quote_identifiers']);
519         // for
520         $leftq     = '';
521         $rightq    = '';
522         
523         
524         $deplinks = $do->links();
525         
526         foreach(  $items  as $k=>$v)
527         {
528             if ($leftq) {
529                 $leftq  .= ', ';
530                 $rightq .= ', ';
531             }
532             
533             $leftq .= ($quoteIdentifiers ? ($DB->quoteIdentifier($k) . ' ')  : "$k ");
534             
535             // only handles numeric links..
536             if (is_numeric($do->$k) && $do->$k && $deplinks && !empty($deplinks[$k])) {
537                // die("got deplink" . $deplinks[$k]);
538                 $l = explode(':', $deplinks[$k]);
539                 $add = $deplinks[$k].':' . $do->$k;
540                 
541                 $this->deps[$add] = 0;
542             }
543             
544             
545             
546             if ($v & DB_DATAOBJECT_STR) {
547                 $rightq .= $do->_quote((string) (
548                         ($v & DB_DATAOBJECT_BOOL) ? 
549                             // this is thanks to the braindead idea of postgres to 
550                             // use t/f for boolean.
551                             (($do->$k === 'f') ? 0 : (int)(bool) $do->$k) :  
552                             $do->$k
553                     )) . " ";
554                 continue;
555             }
556             if (is_numeric($do->$k)) {
557                 $rightq .=" {$do->$k} ";
558                 continue;
559             }
560             $rightq .= ' ' . intval($do->$k) . ' ';
561         }
562         $table = ($quoteIdentifiers ? $DB->quoteIdentifier($do->__table)    : $do->__table);
563         return "INSERT INTO {$table} ($leftq) VALUES ($rightq);\n";
564         
565     }
566     
567     
568 }