UpdateDatabase.php
[Pman.Core] / UpdateDatabase.php
1 <?php
2
3 /**
4  *
5  * This applies database files from
6  * a) OLD - {MODULE}/DataObjects/XXXX.{dbtype}.sql
7  *
8  * b) NEW - {MODULE}/sql/XXX.sql (SHARED or translable)
9  *  and {MODULE}/{dbtype}/XXX.sql (SHARED or translable)
10  *
11  *
12  */
13
14 require_once 'Pman.php';
15 class Pman_Core_UpdateDatabase extends Pman
16 {
17     
18     static $cli_desc = "Update SQL - Beta (it will run updateData of all modules)";
19  
20     static $cli_opts = array(
21         'source' => array(
22             'desc' => 'Source directory for json files.',
23             'short' => 'f',
24             'default' => '',
25             'min' => 1,
26             'max' => 1,
27         ),
28         'prefix' => array(
29             'desc' => 'prefix for the passwrod',
30             'short' => 'p',
31             'default' => '',
32             'min' => 1,
33             'max' => 1,
34         ),
35         'name' => array(
36             'desc' => 'name of the company',
37             'short' => 'n',
38             'default' => '',
39             'min' => 1,
40             'max' => 1,
41         ),
42         'comptype' => array(
43             'desc' => 'the type of company',
44             'short' => 't',
45             'default' => '',
46             'min' => 1,
47             'max' => 1,
48         ),
49         
50     );
51     
52     var $cli = false;
53     function getAuth() {
54         
55         
56         $ff = HTML_FlexyFramework::get();
57         if (!empty($ff->cli)) {
58             $this->cli = true;
59             return true;
60         }
61         
62         parent::getAuth(); // load company!
63         $au = $this->getAuthUser();
64         if (!$au || $au->company()->comptype != 'OWNER') {
65             $this->jerr("Not authenticated", array('authFailure' => true));
66         }
67         $this->authUser = $au;
68         return true;
69     }
70      
71     function get($args, $opt)
72     {
73         if($args == 'Person'){
74             if(empty($opt['source']) || empty($opt['prefix'])){
75                 die("Missing Source directory for person json files or prefix for the passwrod! Try -f [JSON file path] -p [prefix] \n");
76             }
77             if (!file_exists($opt['source'])) {
78                 die("can not found person json file : {$opt['source']} \n");
79             }
80             
81             $persons = json_decode(file_get_contents($opt['source']),true);
82             
83             DB_DataObject::factory('person')->importFromArray(HTML_Flexyframework::get()->page, $persons, $opt['prefix']);
84             die("DONE! \n");
85         }
86         
87         if($args == 'Account'){
88             if(empty($opt['source'])){
89                 die("Missing Source directory for account json files! Try -f [JSON file path] \n");
90             }
91             
92             if (!file_exists($opt['source'])) {
93                 die("can not found account json file : {$opt['source']} \n");
94             }
95
96             $accounts = json_decode(file_get_contents($opt['source']),true);
97             
98             DB_DataObject::factory('accnt')->importFromArray($accounts);
99             die("DONE! \n");
100         }
101         
102         if($args == 'Company'){
103             if(empty($opt['name']) || empty($opt['comptype'])){
104                 die("Missing company name or type! Try --name=[the name of company] -- comptype=[the type of company] \n");
105             }
106             
107            // DB_DataObject::factory('companies')->initCompanies(HTML_Flexyframework::get()->page, $opt['name'], $opt['comptype']);
108             $companies = DB_DataObject::factory('companies');
109             $companies->setFrom(array(
110                 'name' => $opt['name'],
111                 'comptype' => $opt['comptype']
112             ));
113
114             $companies->insert();
115             $companies->onInsert(array(), '');
116             
117             die("DONE! \n");
118         }
119         
120         $this->importSQL();
121         $this->runUpdateModulesData();
122          
123     }
124     function output() {
125         return '';
126     }
127      /**
128      * imports SQL files from all DataObjects directories....
129      * 
130      * except any matching /migrate/
131      */
132     function importSQL()
133     {
134         
135         $ff = HTML_Flexyframework::get();
136         
137         $url = parse_url($ff->DB_DataObject['database']);
138         
139         $this->{'import' . $url['scheme']}($url);
140         
141     }
142     
143     /**
144      * mysql - does not support conversions.
145      * 
146      *
147      */
148     
149     
150     
151     function importmysql($url)
152     {
153         
154         // hide stuff for web..
155         
156         require_once 'System.php';
157         $cat = System::which('cat');
158         $mysql = System::which('mysql');
159         
160         $ar = $this->modulesList();
161         
162            
163         $mysql_cmd = $mysql .
164             ' -h ' . $url['host'] .
165             ' -u' . escapeshellarg($url['user']) .
166             (!empty($url['pass']) ? ' -p' . escapeshellarg($url['pass'])  :  '') .
167             ' ' . basename($url['path']);
168         echo $mysql_cmd . "\n" ;
169         
170         
171         // old -- DAtaObjects/*.sql
172         
173         foreach($ar as $m) {
174             
175             $fd = $this->rootDir. "/Pman/$m/DataObjects";
176             
177             foreach(glob($fd.'/*.sql') as $fn) {
178                 
179                  
180                 if (preg_match('/migrate/i', basename($fn))) { // skip migration scripts at present..
181                     continue;
182                 }
183                 // .my.sql but not .pg.sql
184                 if (preg_match('#\.[a-z]{2}\.sql#i', basename($fn))
185                     && !preg_match('#\.my\.sql#i', basename($fn))
186                 ) { // skip migration scripts at present..
187                     continue;
188                 }
189                 $cmd = "$mysql_cmd -f < " . escapeshellarg($fn) ;
190                 
191                 echo $cmd. ($this->cli ? "\n" : "<BR>\n");
192                 
193                 passthru($cmd);
194             
195                 
196             }
197             // new -- sql directory..
198             // new style will not support migrate ... they have to go into mysql-migrate.... directories..
199             // new style will not support pg.sql etc.. naming - that's what the direcotries are for..
200             $fd = $this->rootDir. "/Pman/$m/sql";
201             
202             foreach(glob($fd.'/*.sql') as $fn) {
203                 $cmd = "$mysql_cmd -f < " . escapeshellarg($fn) ;
204                 echo $cmd. ($this->cli ? "\n" : "<BR>\n");
205                 passthru($cmd);
206             }
207             $fd = $this->rootDir. "/Pman/$m/mysql";
208             
209             foreach(glob($fd.'/*.sql') as $fn) {
210                 $cmd = "$mysql_cmd -f < " . escapeshellarg($fn) ;
211                 echo $cmd. ($this->cli ? "\n" : "<BR>\n");
212                 passthru($cmd);
213             }
214               
215             
216             
217             
218             
219             
220         }
221         
222         
223         
224     }
225     /**
226      * postgresql import..
227      */
228     function importpgsql($url)
229     {
230         
231         // hide stuff for web..
232         
233         require_once 'System.php';
234         $cat = System::which('cat');
235         $psql = System::which('psql');
236         
237         $ar = $this->modulesList();
238         
239         if (!empty($url['pass'])) { 
240             putenv("PGPASSWORD=". $url['pass']);
241         }
242            
243         $psql_cmd = $psql .
244             ' -h ' . $url['host'] .
245             ' -U' . escapeshellarg($url['user']) .
246              ' ' . basename($url['path']);
247         echo $psql_cmd . "\n" ;
248         
249         
250         
251         
252         foreach($ar as $m) {
253             
254             $fd = $this->rootDir. "/Pman/$m/DataObjects";
255             
256             foreach(glob($fd.'/*.sql') as $bfn) {
257                 
258                  
259                 if (preg_match('/migrate/i', basename($bfn))) { // skip migration scripts at present..
260                     continue;
261                 }
262                 if (preg_match('#\.[a-z]{2}\.sql#i', basename($bfn))
263                     && !preg_match('#\.pg\.sql#i', basename($bfn))
264                 ) { // skip migration scripts at present..
265                     continue;
266                 }
267                 // files ending in .pg.sql are native postgres files..
268                 $fn = preg_match('#\.pg\.sql$#', basename($bfn)) ? false : $this->convertToPG($bfn);
269                 
270                 $cmd = "$psql_cmd  < " . escapeshellarg($fn ? $fn : $bfn) . ' 2>&1' ;
271                 
272                 echo "$bfn:   $cmd ". ($this->cli ? "\n" : "<BR>\n");
273                 
274                 
275                 passthru($cmd);
276                 
277                 if ($fn) {
278                     unlink($fn);
279                 }
280             }
281             
282             
283             
284             $fd = $this->rootDir. "/Pman/$m/sql";
285             // sql directory  - we try to convert..
286             foreach(glob($fd.'/*.sql') as $bfn) {
287                 $fn =  $this->convertToPG($bfn);
288                 $cmd = "$psql_cmd  < " . escapeshellarg($fn) ;
289                 echo $cmd. ($this->cli ? "\n" : "<BR>\n");
290                 passthru($cmd);
291             }
292             
293             // postgres specific directory..
294             
295             $fd = $this->rootDir. "/Pman/$m/pgsql";
296             
297             foreach(glob($fd.'/*.sql') as $fn) {
298                 $cmd = "$psql_cmd   < " . escapeshellarg($fn) ;
299                 echo $cmd. ($this->cli ? "\n" : "<BR>\n");
300                 passthru($cmd);
301             }
302             
303             
304             
305         }
306         
307     }
308     /**
309      * simple regex based convert mysql to pgsql...
310      */
311     function convertToPG($src)
312     {
313         $fn = $this->tempName('sql');
314         
315         $ret = array( ); // pad it a bit.
316         $extra = array("", "" );
317         
318         $tbl = false;
319         foreach(file($src) as $l) {
320             $l = trim($l);
321             
322             if (!strlen($l) || $l[0] == '#') {
323                 continue;
324             }
325             $m = array();
326             if (preg_match('#create\s+table\s+([a-z0-9_]+)#i',  $l, $m)) {
327                 $tbl = $m[1];
328                // $extra[]  =   "drop table {$tbl};";
329              }
330             // autoinc
331             if ($tbl && preg_match('#auto_increment#i',  $l, $m)) {
332                 $l = preg_replace('#auto_increment#i', "default nextval('{$tbl}_seq')", $l);
333                 $extra[]  =   "create sequence {$tbl}_seq;";
334               
335             }
336             $m = array();
337             if (preg_match('#alter\s+table\s+([a-z0-9_]+)\s+add\s+index\s+([^(]+)(.*)$#i',  $l, $m)) {
338                $l = "CREATE INDEX  {$m[1]}_{$m[2]} ON {$m[1]} {$m[3]}";
339              }
340             // ALTER TABLE core_event_audit ADD     INDEX looku
341             // CREATE INDEX 
342             
343             // basic types..
344             $l = preg_replace('#int\([0-9]+\)#i', 'INT', $l);
345             
346             $l = preg_replace('# datetime #i', ' TIMESTAMP WITHOUT TIME ZONE ', $l);
347             $l = preg_replace('# blob #i', ' TEXT ', $l);
348              $l = preg_replace('# longtext #i', ' TEXT ', $l);
349             //$l = preg_match('#int\([0-9]+\)#i', 'INT', $l);
350                             
351             $ret[] = $l;
352             
353             
354             
355             
356             
357             
358             
359         }
360         $ret = array_merge($extra,$ret);
361         
362         //echo implode("\n", $ret); //exit;
363         file_put_contents($fn, implode("\n", $ret));
364         
365         return $fn;
366     }
367     
368     function runUpdateModulesData()
369     {
370         $this->updateData();
371         $modules = $this->modulesList();
372         foreach ($modules as $module){
373             $file = $this->rootDir. "/Pman/$module/UpdateDatabase.php";
374             if($module == 'Core' || !file_exists($file)){
375                 continue;
376             }
377             require_once $file;
378             $class = "Pman_{$module}_UpdateDatabase";
379             $x = new $class;
380             if(!method_exists($x, 'updateData')){
381                 continue;
382             };
383             $x->updateData();
384         }
385                 
386     }
387     
388     function updateData()
389     {
390         // fill i18n data..
391         
392         $enum = DB_DataObject::Factory('core_enum');
393         $enum->initEnums(
394             array(
395                 array(
396                     'etype' => '',
397                     'name' => 'COMPTYPE',
398                     'display_name' =>  'Company Types',
399                     'cn' => array(
400                         array(
401                             'name' => 'OWNER',
402                             'display_name' => 'Owner',
403                             'seqid' => 999, // last...
404                         )
405                         
406                     )
407                 )
408             )
409         ); 
410         
411         $groups = DB_DataObject::factory('groups');
412         $groups->initGroups();
413     }
414     
415     
416 }