Export.php
[Pman.Admin] / Export.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_Export extends Pman_Admin_Dump {
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     var $uid = array();
66     
67     function get($path )
68     {
69         ini_set('memory_limit', '256M'); // we need alot of memory
70         set_time_limit(0);
71         
72         $argv = $_SERVER['argv'];
73         array_shift($argv);
74         array_shift($argv);
75         
76         $opts = explode(',', 'table==,where==,dump-dir==,debug=');
77         require_once 'Console/Getopt.php';
78         $go = Console_Getopt::getopt2($argv, '', $opts );
79         if (is_object($go)) {
80             die($go->toString());
81         }
82          
83         foreach($go[0] as $ar) {
84             $args[substr($ar[0],2)] = $ar[1];
85         }
86         $errs = array();
87         foreach($opts as $req) {
88             if (substr($req,-2, 2) != '==') { // skip optional arguments
89                 continue;
90             }
91             if (empty($args[substr($req,0, -2)])) {
92                 $errs[] = "--".substr($req,0, -2) . ' is required';
93             }
94         }
95         if (!empty($errs)) {
96             die(print_R($errs,true));
97         }
98         if (!empty($args['debug'])) {
99             DB_DataObject::debugLevel($args['debug']);
100         }
101         $this->args = $args;
102         $this->out = array();
103         
104         
105         
106         
107         
108         
109         
110         
111         
112         $this->discoverChildren($this->args['table'], $this->args['where'], true);
113         //print_R($this->deletes);
114         //print_r($this->dumps);
115         //exit;
116         
117         $this->discover($this->args['table'], $this->args['where'], true);
118          
119         
120         if (!file_exists($args['dump-dir'])) {
121             mkdir($args['dump-dir'], 0777, true);
122         }
123           
124           
125           // create uid's
126         
127         // dump items..
128         
129         
130           
131         echo "GENERATED FILES:\n";
132         // summary
133         echo "    ". implode("\n    ", $this->out). "\n";
134         
135         
136         exit;
137         
138       
139          
140     }
141      
142     var $deletes = array(); // TABLE => [key] => TRUE|FALSE
143     var $dumps = array(); // TABLE => [key] => TRUE|FALSE - if it's been scanned..
144     var $dscan = array(); // TABLE:COL => [value => TRUE|FALSE] - if its been scanned..
145     var $childfiles = array(); // array of [ 'sourcedirectory' , 'subdirectory(s) and filename' ]
146     var $childthumbs = array(); // array of [ 'filename', 'filename' ,......]
147     var $filesize = 0; // size of files to be saved. (not total deletd..)
148     var $filetotal = 0; // number of distinct files to be saved (not total deleted)
149     /**
150      * scan table for
151      * a) what depends on it (eg. child elements) - which will be deleted.
152      * b) what it depends on it (eg. parent elements) - which will be dumped..
153      */
154       
155     
156     
157     function generateDelete() {  
158         $target = $this->args['dump-dir'] .'/'. date('Y-m-d').'.delete.sql';
159         $this->out[] = $target;
160         $fh = fopen($target, 'w');
161         
162         
163         
164         foreach($this->deletes as $tbl=>$ar) {
165             
166             $do = DB_DataObject::factory($tbl);
167             $tbl = $do->tableName();
168             $keys = $do->keys();
169             $key = $keys[0];
170             $do->whereAddIn($keys[0] , array_keys($ar), 'int');
171             $do->find();
172             $archivePaths = method_exists($do,'archivePaths');
173             $listThumbs = method_exists($do,'listThumbs');
174             while ($do->fetch()) {
175                 
176                 if ($archivePaths) {
177                     $ct = $do->archivePaths();
178                     if ($ct) {
179                         $this->childfiles[] = $ct;
180                     }
181                 }
182                 if ($listThumbs) {
183                     $ct = $do->listThumbs();
184                     if($ct) {
185                         $this->childthumbs[] = $ct;
186                     }
187                 }
188                 $id = $do->$key;
189                 
190                 fwrite($fh, "DELETE FROM `$tbl` WHERE `$key` = $id;\n"); // we assume id's and nice column names...
191             }
192             $do->free();
193         }
194         fclose($fh);
195     }
196     function generateShell() {
197         
198         if (empty($this->childfiles) && empty($this->childthumbs)) {
199             return;
200         }
201         $target = $this->args['dump-dir'] .'/'. date('Y-m-d').'.copy.sh';
202         $this->out[] = $target;
203         $fh = fopen($target, 'w');
204         
205         $target = $this->args['dump-dir'] .'/'. date('Y-m-d').'.delete.sh';
206         $this->out[] = $target;
207         $fh2 = fopen($target, 'w');
208         
209         $target = $this->args['dump-dir'] .'/'. date('Y-m-d').'.restore.sh';
210         $this->out[] = $target;
211         $fh3 = fopen($target, 'w');
212         
213       
214         $done = array();
215         $donedir  = array();
216         foreach($this->childfiles as  $v) {
217             
218             if (isset($done[$v[1]])) {
219                 continue;
220             }
221             
222             $done[$v[1]] = true;
223             
224             $this->filesize += filesize($v[0].'/'.$v[1]);
225             $this->filetotal++;
226             $fdir = dirname($this->args['dump-dir'] .'/'.$v[1]);
227             if (!isset($donedir[$fdir])) { 
228                 fwrite($fh,"mkdir -p " . escapeshellarg(dirname($this->args['dump-dir'] .'/'.$v[1])) ."\n" );
229             }
230             fwrite($fh,"cp " . escapeshellarg($v[0].'/'.$v[1]) . ' ' . escapeshellarg($this->args['dump-dir'] .'/'.$v[1]) ."\n" );
231             if (!isset($donedir[$fdir])) { 
232                 fwrite($fh3,"mkdir -p " . escapeshellarg(dirname($v[0].'/'.$v[1])) ."\n" );
233             }
234             $donedir[$fdir] = true;
235             
236             fwrite($fh3,"cp " .  escapeshellarg($this->args['dump-dir'] .'/'.$v[1]) . ' ' . escapeshellarg($v[0].'/'.$v[1]) . "\n" );
237             fwrite($fh2,"rm " . escapeshellarg($v[0].'/'.$v[1]) ."\n" );
238         }
239         fclose($fh);
240         fclose($fh3); // restore does not need to bother with thumbnails.
241          
242         
243         
244         foreach($this->childthumbs as  $v) {
245             foreach($v as $vv) { 
246                 fwrite($fh2,"rm " . escapeshellarg($vv). "\n");
247             }
248         }
249         fclose($fh2);
250     }
251      
252     function generateInsert()
253     {
254         $target = $this->args['dump-dir'] .'/'. date('Y-m-d').'.sql';
255         $this->out[] = $target;
256         $fh = fopen($target,'w');
257          
258          
259         
260         foreach($this->dumps as $tbl => $ar) {
261             if (empty($ar)) {
262                 continue;
263             }
264             $do = DB_DataObject::factory($tbl);
265              
266             $keys = $do->keys();
267          
268             $do->whereAddIn($keys[0] , array_keys($ar), 'int');
269             $do->find();
270             while ($do->fetch()) {
271                 fwrite($fh,$this->toInsert($do));
272             }
273              $do->free();
274             
275         }
276         fclose($fh);
277         
278         
279     }
280
281     
282       
283     /**
284      * toInsert - does not handle NULLS... 
285      */
286     function toInsert($do)
287     {
288         $kcol = array_shift($do->keys());
289          
290         // for auto_inc column we need to use a 'set argument'...
291         $items = $do->table();
292         //print_R($items);
293         
294         // for
295         $leftq     = '';
296         $rightq    = '';
297         
298         $table = $do->tableName();
299         
300          
301         foreach(  $items  as $k=>$v)
302         {
303             if ($leftq) {
304                 $leftq  .= ', ';
305                 $rightq .= ', ';
306             }
307             
308             $leftq .= '`' . $k . '`';
309             
310              
311             
312             
313             if ($v & DB_DATAOBJECT_STR) {
314                 $rightq .= $do->_quote((string) (
315                         ($v & DB_DATAOBJECT_BOOL) ? 
316                             // this is thanks to the braindead idea of postgres to 
317                             // use t/f for boolean.
318                             (($do->$k === 'f') ? 0 : (int)(bool) $do->$k) :  
319                             $do->$k
320                     )) . " ";
321                 continue;
322             }
323             if (is_numeric($do->$k)) {
324                 $rightq .=" {$do->$k} ";
325                 continue;
326             }
327             $rightq .= ' ' . intval($do->$k) . ' ';
328         }
329         
330         return "INSERT INTO `{$table}` ($leftq) VALUES ($rightq);\n";
331         
332     }
333     
334     
335 }