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($this, $persons, $opt['prefix']);
84             die("DONE! \n");
85         }
86         
87         if($args == 'Company'){
88             if(empty($opt['name']) || empty($opt['comptype'])){
89                 die("Missing company name or type! Try --name=[the name of company] -- comptype=[the type of company] \n");
90             }
91             
92             DB_DataObject::factory('companies')->initCompanies($this, $opt['name'], $opt['comptype']);
93             
94             die("DONE! \n");
95         }
96         
97         $this->importSQL();
98         $this->runUpdateModulesData();
99          
100     }
101     function output() {
102         return '';
103     }
104      /**
105      * imports SQL files from all DataObjects directories....
106      * 
107      * except any matching /migrate/
108      */
109     function importSQL()
110     {
111         
112         $ff = HTML_Flexyframework::get();
113         
114         $url = parse_url($ff->DB_DataObject['database']);
115         
116         $this->{'import' . $url['scheme']}($url);
117         
118     }
119     
120     /**
121      * mysql - does not support conversions.
122      * 
123      *
124      */
125     
126     
127     function importmysqldir($dburl, $dir)
128     {
129         echo "Import MYSQL :: $dir\n";
130         
131         
132         require_once 'System.php';
133         $cat = System::which('cat');
134         $mysql = System::which('mysql');
135         
136        
137            
138         $mysql_cmd = $mysql .
139             ' -h ' . $dburl['host'] .
140             ' -u' . escapeshellarg($dburl['user']) .
141             (!empty($dburl['pass']) ? ' -p' . escapeshellarg($dburl['pass'])  :  '') .
142             ' ' . basename($dburl['path']);
143         //echo $mysql_cmd . "\n" ;
144        
145        
146         foreach(glob($dir.'/*.sql') as $fn) {
147                 
148                  
149                 if (preg_match('/migrate/i', basename($fn))) { // skip migration scripts at present..
150                     continue;
151                 }
152                 // .my.sql but not .pg.sql
153                 if (preg_match('#\.[a-z]{2}\.sql#i', basename($fn))
154                     && !preg_match('#\.my\.sql#i', basename($fn))
155                 ) { // skip migration scripts at present..
156                     continue;
157                 }
158                 if (!strlen(trim($fn))) {
159                     continue;
160                 }
161                 
162                 $cmd = "$mysql_cmd -f < " . escapeshellarg($fn) ;
163                 
164                 echo basename($dir).'/'. basename($fn) .    '::' .  $cmd. ($this->cli ? "\n" : "<BR>\n");
165                 
166                 passthru($cmd);
167             
168                 
169         }
170        
171         
172         
173     }
174     
175     
176     
177     function importmysql($dburl)
178     {
179         
180         // hide stuff for web..
181         $ar = $this->modulesList();
182         
183          
184         
185         // old -- DAtaObjects/*.sql
186         
187         foreach($ar as $m) {
188             
189             $fd = $this->rootDir. "/Pman/$m/DataObjects";
190             
191             $this->importmysqldir($dburl, $fd);
192             
193             // new -- sql directory..
194             // new style will not support migrate ... they have to go into mysql-migrate.... directories..
195             // new style will not support pg.sql etc.. naming - that's what the direcotries are for..
196             
197             $this->importmysqldir($dburl, $this->rootDir. "/Pman/$m/sql");
198             $this->importmysqldir($dburl, $this->rootDir. "/Pman/$m/mysql");
199               
200             
201         }
202         
203         
204         
205     }
206     /**
207      * postgresql import..
208      */
209     function importpgsql($url)
210     {
211         
212         // hide stuff for web..
213         
214         
215        
216         
217         $ar = $this->modulesList();
218        
219          foreach($ar as $m) {
220             
221             $fd = $this->rootDir. "/Pman/$m/DataObjects";
222             
223             $this->importpgsqldir($dburl, $fd);
224             
225             // new -- sql directory..
226             // new style will not support migrate ... they have to go into mysql-migrate.... directories..
227             // new style will not support pg.sql etc.. naming - that's what the direcotries are for..
228             
229             $this->importpgsqldir($dburl, $this->rootDir. "/Pman/$m/sql");
230             $this->importpgsqldir($dburl, $this->rootDir. "/Pman/$m/pgsql");
231               
232             
233         }
234        
235           
236     }
237     function importpgsqldir($url, $dir)
238     {
239         require_once 'System.php';
240         $cat = System::which('cat');
241         $psql = System::which('psql');
242         
243          
244         if (!empty($url['pass'])) { 
245             putenv("PGPASSWORD=". $url['pass']);
246         }
247            
248         $psql_cmd = $psql .
249             ' -h ' . $url['host'] .
250             ' -U' . escapeshellarg($url['user']) .
251              ' ' . basename($url['path']);
252         echo $psql_cmd . "\n" ;
253         foreach(glob($dir.'/*.sql') as $bfn) {
254
255
256             if (preg_match('/migrate/i', basename($bfn))) { // skip migration scripts at present..
257                 continue;
258             }
259             if (preg_match('#\.[a-z]{2}\.sql#i', basename($bfn))
260                 && !preg_match('#\.pg\.sql#i', basename($bfn))
261             ) { // skip migration scripts at present..
262                 continue;
263             }
264             $fn = false;
265
266             if (basename($dir) != 'pgsql') {
267                  if ( !preg_match('#\.pg\.sql$#', basename($bfn))) {
268                     $fn = $this->convertToPG($bfn);
269                 }
270             }
271
272             // files ending in .pg.sql are native postgres files.. ## depricated
273
274
275             $cmd = "$psql_cmd  < " . escapeshellarg($fn ? $fn : $bfn) . ' 2>&1' ;
276
277             echo "$bfn:   $cmd ". ($this->cli ? "\n" : "<BR>\n");
278
279
280             passthru($cmd);
281
282             if ($fn) {
283                 unlink($fn);
284             }
285         }
286
287               
288              
289         
290     }
291     /**
292      * simple regex based convert mysql to pgsql...
293      */
294     function convertToPG($src)
295     {
296         //echo "Convert $src\n";
297                
298         $fn = $this->tempName('sql');
299         
300         $ret = array( ); // pad it a bit.
301         $extra = array("", "" );
302         
303         $tbl = false;
304         foreach(file($src) as $l) {
305             $l = trim($l);
306             
307             if (!strlen($l) || $l[0] == '#') {
308                 continue;
309             }
310             $m = array();
311             if (preg_match('#create\s+table\s+([a-z0-9_]+)#i',  $l, $m)) {
312                 $tbl = $m[1];
313              }
314             if (preg_match('#create\s+table\s+\`([a-z0-9_]+)\`#i',  $l, $m)) {
315                 $tbl = 'shop_' . strtolower($m[1]);
316                 $l = preg_replace('#\`{0,1}([a-z0-9_]+)\`{0,1}#i', "{$tbl}", $l);
317              }else{
318                  if (preg_match('#\`([a-z0-9_]+)\`#i',  $l, $m)) {
319                      $l = preg_replace('#\`([a-z0-9_]+)\`#i', "{$m[1]}_name", $l);
320                  }
321              }
322              
323             // autoinc
324             if ($tbl && preg_match('#auto_increment#i',  $l, $m)) {
325                 $l = preg_replace('#auto_increment#i', "default nextval('{$tbl}_seq')", $l);
326                 $extra[]  =   "create sequence {$tbl}_seq;";
327               
328             }
329             
330             // enum value
331             if ($tbl && preg_match('#alter\s+table\s+#i',  $l, $m)) {
332                 
333                 if ($tbl && preg_match('#column\s+[\w]+#i',  $l, $m)) {
334                     $name = explode(" ", $m[0]);
335                     $name = $name[0];
336                 }
337                 if ($tbl && preg_match('#enum\([\w|\W]+\)#i',  $l, $m)) {
338                     $extra[] = "CREATE TYPE {$tbl}_enum AS {$m[0]};";
339                 }
340                 continue;
341                 
342             }else{
343                 
344                 if ($tbl && preg_match('#([\w]+)\s+(enum\([\w|\W]+\))#i',  $l, $m)) {
345                     
346                     $l = preg_replace('#enum\([\w|\W]+\)#i', "{$tbl}_{$m[1]}_enum", $l);
347                 }
348             }
349             
350             // UNIQUE KEY .. ignore
351             if ($tbl && preg_match('#UNIQUE KEY#i',  $l, $m)) {
352 //                preg_match('#UNIQUE\s+KEY\s+([\w]+)\s+([\w|\W]+)#i',  $l, $m);
353 //                            
354 //                $unique[] = 'CREATE UNIQUE INDEX ' . $m[1] . '_idx ON "' . $tbl . '" USING btree ' . $m[2] . ';';
355                 $last = array_pop($ret);
356                 $ret[] = trim($last, ",");
357                 continue;
358             }
359             
360             // INDEX lookup ..ignore
361             if ($tbl && preg_match('#INDEX lookup+([\w|\W]+)#i',  $l, $m)) {
362 //               $unique[] = 'CREATE INDEX lookup_idx ON "' . $tbl . '" USING btree ' . $m[1] . ';';
363                $last = array_pop($ret);
364                $ret[] = trim($last, ",");
365                continue;
366                
367             }
368             
369             $m = array();
370             if (preg_match('#alter\s+table\s+([a-z0-9_]+)\s+add\s+index\s+([^(]+)(.*)$#i',  $l, $m)) {
371                $l = "CREATE INDEX  {$m[1]}_{$m[2]} ON {$m[1]} {$m[3]}";
372              }
373             // ALTER TABLE core_event_audit ADD     INDEX looku
374             // CREATE INDEX 
375             
376             // basic types..
377             $l = preg_replace('#int\([0-9]+\)#i', 'INT', $l);
378             
379             $l = preg_replace('# datetime#i', ' TIMESTAMP WITHOUT TIME ZONE', $l);
380             $l = preg_replace('# blob#i', ' TEXT', $l);
381             $l = preg_replace('# longtext#i', ' TEXT', $l);
382             $l = preg_replace('# tinyint#i', ' BOOLEAN', $l);
383             
384             // keyword handle...
385             if(preg_match('#([\w]+)\s+([\w|\W]+)#i',  $l, $m) && !preg_match('#CREATE|PRIMARY|ALERT#i', $l)){
386                 if($m[1] == 'group'){
387                     $m[1] = 'group_name';
388                 }
389                 
390                 $l = "{$m[1]} {$m[2]}";
391             }
392             
393             
394             $ret[] = $l;
395             
396         }
397         $ret = array_merge($extra,$ret);
398 //        echo implode("\n", $ret); exit;
399         
400         file_put_contents($fn, implode("\n", $ret));
401         
402         return $fn;
403     }
404     
405     function runUpdateModulesData()
406     {
407         // runs core...
408         $this->updateData(); 
409         $modules = array_reverse($this->modulesList());
410         
411         // move 'project' one to the end...
412         
413         foreach ($modules as $module){
414             $file = $this->rootDir. "/Pman/$module/UpdateDatabase.php";
415             if($module == 'Core' || !file_exists($file)){
416                 continue;
417             }
418             require_once $file;
419             $class = "Pman_{$module}_UpdateDatabase";
420             $x = new $class;
421             if(!method_exists($x, 'updateData')){
422                 continue;
423             };
424             $x->updateData();
425         }
426                 
427     }
428     
429     
430     function updateDataEnums()
431     {
432         $enum = DB_DataObject::Factory('core_enum');
433         $enum->initEnums(
434             array(
435                 array(
436                     'etype' => '',
437                     'name' => 'COMPTYPE',
438                     'display_name' =>  'Company Types',
439                     'is_system_enum' => 1,
440                     'cn' => array(
441                         array(
442                             'name' => 'OWNER',
443                             'display_name' => 'Owner',
444                             'seqid' => 999, // last...
445                             'is_system_enum' => 1,
446                         )
447                         
448                     )
449                 ),
450                 array(
451                     'etype' => '',
452                     'name' => 'HtmlEditor.font-family',
453                     'display_name' =>  'HTML Editor font families',
454                     'is_system_enum' => 1,
455                     'cn' => array(
456                         array(
457                             'name' => 'Helvetica,Arial,sans-serif',
458                             'display_name' => 'Helvetica',
459                             
460                         ),
461                         
462                         array(
463                             'name' => 'Courier New',
464                             'display_name' => 'Courier',
465                              
466                         ),
467                         array(
468                             'name' => 'Tahoma',
469                             'display_name' => 'Tahoma',
470                             
471                         ),
472                         array(
473                             'name' => 'Times New Roman,serif',
474                             'display_name' => 'Times',
475                            
476                         ),
477                         array(
478                             'name' => 'Verdana',
479                             'display_name' => 'Verdana',
480                             
481                         ),
482                         
483                             
484                         
485                     )
486                 ),
487             )
488         ); 
489         
490     }
491     function updateDataGroups()
492     {
493          
494         $groups = DB_DataObject::factory('groups');
495         $groups->initGroups();
496         
497         $groups->initDatabase($this,array(
498             array(
499                 'name' => 'bcc-email', // group who are bcc'ed on all requests.
500                 'type' => 0, // system
501             ),
502             
503         ));
504         
505     }
506     
507     function updateDataCompanies()
508     {
509          
510         // fix comptypes enums..
511         $c = DB_DataObject::Factory('Companies');
512         $c->selectAdd();
513         $c->selectAdd('distinct(comptype) as comptype');
514         $c->whereAdd("comptype != ''");
515         
516         $ctb = array();
517         foreach($c->fetchAll('comptype') as $cts) {
518             
519             
520             
521            $ctb[]= array( 'etype'=>'COMPTYPE', 'name' => $cts, 'display_name' => ucfirst(strtolower($cts)));
522         
523         }
524          $c = DB_DataObject::Factory('core_enum');
525          
526         $c->initEnums($ctb);
527         //DB_DataObject::debugLevel(1);
528         // fix comptypeid
529         $c = DB_DataObject::Factory('Companies');
530         $c->query("
531             UPDATE Companies 
532                 SET
533                     comptype_id = (SELECT id FROM core_enum where etype='comptype' and name=Companies.comptype)
534                 WHERE
535                     comptype_id = 0
536                     AND
537                     LENGTH(comptype) > 0
538                   
539                   
540                   ");
541          
542         
543         
544     }
545     
546     function updateData()
547     {
548         // fill i18n data..
549         
550         $this->updateDataEnums();
551         $this->updateDataGroups();
552         $this->updateDataCompanies();
553         
554        
555          
556        
557         
558         
559     }
560     
561     
562 }