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         'init' => array(
50             'desc' => 'Initialize the database (pg only supported)',
51             'short' => 'i',
52             'default' => '',
53             'min' => 1,
54             'max' => 1,
55         ),
56         
57         'json-company' => array(
58             'desc' => 'Company JSON file',
59             'default' => '',
60             'min' => 1,
61             'max' => 1,
62             
63         ),
64         'json-person' => array(
65             'desc' => 'Person JSON file',
66             'default' => '',
67             'min' => 1,
68             'max' => 1,
69             
70         ),
71     );
72     
73     static function cli_opts()
74     {
75         
76         $ret = self::$cli_opts;
77         $ff = HTML_FlexyFramework::get();
78         $a = new Pman();
79         $mods = $a->modulesList();
80         foreach($mods as $m) {
81             
82             $fd = $ff->rootDir. "/Pman/$m/UpdateDatabase.php";
83             if (!file_exists($fd)) {
84                 continue;
85             }
86             
87             require_once $fd;
88             
89             $cls = new ReflectionClass('Pman_'. $m . '_UpdateDatabase');
90             
91             $ret = array_merge($ret, $cls->getStaticPropertyValue('cli_opts'));
92             
93             
94         }
95         
96         return $ret;
97     }
98     
99     var $opts = false;
100     
101     
102     var $cli = false;
103     function getAuth() {
104         
105         
106         $ff = HTML_FlexyFramework::get();
107         if (!empty($ff->cli)) {
108             $this->cli = true;
109             return true;
110         }
111         
112         parent::getAuth(); // load company!
113         $au = $this->getAuthUser();
114         if (!$au || $au->company()->comptype != 'OWNER') {
115             $this->jerr("Not authenticated", array('authFailure' => true));
116         }
117         $this->authUser = $au;
118         return true;
119     }
120      
121     function get($args, $opt)
122     {
123         
124         $this->opts = $opt;
125         
126         // ask all the modules to verify the opts
127         
128         $this->checkOpts($opt);
129         
130         
131         
132         if($args == 'Person'){
133             if(empty($opt['source']) || empty($opt['prefix'])){
134                 die("Missing Source directory for person json files or prefix for the passwrod! Try -f [JSON file path] -p [prefix] \n");
135             }
136             if (!file_exists($opt['source'])) {
137                 die("can not found person json file : {$opt['source']} \n");
138             }
139             
140             $persons = json_decode(file_get_contents($opt['source']),true);
141             
142             DB_DataObject::factory('person')->importFromArray($this, $persons, $opt['prefix']);
143             die("DONE! \n");
144         }
145         
146         
147         
148         if($args == 'Company'){
149             if(empty($opt['name']) || empty($opt['comptype'])){
150                 die("Missing company name or type! Try --name=[the name of company] -- comptype=[the type of company] \n");
151             }
152             
153             DB_DataObject::factory('companies')->initCompanies($this, $opt['name'], $opt['comptype']);
154             
155             die("DONE! \n");
156         }
157         
158         $this->importSQL();
159         $this->runUpdateModulesData();
160          
161     }
162     function output() {
163         return '';
164     }
165      /**
166      * imports SQL files from all DataObjects directories....
167      * 
168      * except any matching /migrate/
169      */
170     function importSQL()
171     {
172         
173         $ff = HTML_Flexyframework::get();
174         
175         $url = parse_url($ff->DB_DataObject['database']);
176         
177         $this->{'import' . $url['scheme']}($url);
178         
179     }
180     
181     /**
182      * mysql - does not support conversions.
183      * 
184      *
185      */
186     
187     
188     function importmysqldir($dburl, $dir)
189     {
190         echo "Import MYSQL :: $dir\n";
191         
192         
193         require_once 'System.php';
194         $cat = System::which('cat');
195         $mysql = System::which('mysql');
196         
197        
198            
199         $mysql_cmd = $mysql .
200             ' -h ' . $dburl['host'] .
201             ' -u' . escapeshellarg($dburl['user']) .
202             (!empty($dburl['pass']) ? ' -p' . escapeshellarg($dburl['pass'])  :  '') .
203             ' ' . basename($dburl['path']);
204         //echo $mysql_cmd . "\n" ;
205        
206        
207         foreach(glob($dir.'/*.sql') as $fn) {
208                 
209                  
210                 if (preg_match('/migrate/i', basename($fn))) { // skip migration scripts at present..
211                     continue;
212                 }
213                 // .my.sql but not .pg.sql
214                 if (preg_match('#\.[a-z]{2}\.sql#i', basename($fn))
215                     && !preg_match('#\.my\.sql#i', basename($fn))
216                 ) { // skip migration scripts at present..
217                     continue;
218                 }
219                 if (!strlen(trim($fn))) {
220                     continue;
221                 }
222                 
223                 $cmd = "$mysql_cmd -f < " . escapeshellarg($fn) ;
224                 
225                 echo basename($dir).'/'. basename($fn) .    '::' .  $cmd. ($this->cli ? "\n" : "<BR>\n");
226                 
227                 passthru($cmd);
228             
229                 
230         }
231        
232         
233         
234     }
235     
236     
237     
238     function importmysql($dburl)
239     {
240         
241         // hide stuff for web..
242         $ar = $this->modulesList();
243         
244          
245         
246         // old -- DAtaObjects/*.sql
247         
248         foreach($ar as $m) {
249             
250             $fd = $this->rootDir. "/Pman/$m/DataObjects";
251             
252             $this->importmysqldir($dburl, $fd);
253             
254             // new -- sql directory..
255             // new style will not support migrate ... they have to go into mysql-migrate.... directories..
256             // new style will not support pg.sql etc.. naming - that's what the direcotries are for..
257             
258             $this->importmysqldir($dburl, $this->rootDir. "/Pman/$m/sql");
259             $this->importmysqldir($dburl, $this->rootDir. "/Pman/$m/mysql");
260               
261             
262         }
263         
264         
265         
266     }
267     /**
268      * postgresql import..
269      */
270     function importpgsql($dburl)
271     {
272         
273         // hide stuff for web..
274         
275         
276        
277         
278         $ar = $this->modulesList();
279        
280         foreach($ar as $m) {
281             
282             // if init has been called
283             // look in pgsql.ini
284             if (!empty($this->opts['init'])) {
285                 $this->importpgsqldir($dburl, $this->rootDir. "/Pman/$m/pgsql.init");
286                 
287             }
288             
289             
290             
291             $fd = $this->rootDir. "/Pman/$m/DataObjects";
292             
293             $this->importpgsqldir($dburl, $fd);
294             
295             // new -- sql directory..
296             // new style will not support migrate ... they have to go into mysql-migrate.... directories..
297             // new style will not support pg.sql etc.. naming - that's what the direcotries are for..
298             
299             $this->importpgsqldir($dburl, $this->rootDir. "/Pman/$m/sql");
300             $this->importpgsqldir($dburl, $this->rootDir. "/Pman/$m/pgsql");
301             
302             
303             
304             if (!empty($this->opts['init']) && file_exists($this->rootDir. "/Pman/$m/pgsql.initdata")) {
305                 HTML_FlexyFramework::get()->generateDataobjectsCache(true);
306                 
307                 $this->importpgsqldir($dburl, $this->rootDir. "/Pman/$m/pgsql.initdata");
308                 $this->fixSequencesPgsql();
309                 
310             }
311               
312             
313         }
314        
315           
316     }
317     function importpgsqldir($url, $dir, $disable_triggers = false)
318     {
319         require_once 'System.php';
320         $cat = System::which('cat');
321         $psql = System::which('psql');
322         
323          
324         if (!empty($url['pass'])) { 
325             putenv("PGPASSWORD=". $url['pass']);
326         }
327            
328         $psql_cmd = $psql .
329             ' -h ' . $url['host'] .
330             ' -U' . escapeshellarg($url['user']) .
331              ' ' . basename($url['path']);
332         
333         
334         echo $psql_cmd . "\n" ;
335         echo "scan : $dir\n";
336         foreach(glob($dir.'/*.sql') as $bfn) {
337
338
339             if (preg_match('/migrate/i', basename($bfn))) { // skip migration scripts at present..
340                 continue;
341             }
342             if (preg_match('#\.[a-z]{2}\.sql#i', basename($bfn))
343                 && !preg_match('#\.pg\.sql#i', basename($bfn))
344             ) { // skip migration scripts at present..
345                 continue;
346             }
347             $fn = false;
348
349             if (!preg_match('/pgsql/', basename($dir) )) {
350                  if ( !preg_match('#\.pg\.sql$#', basename($bfn))) {
351                     $fn = $this->convertToPG($bfn);
352                 }
353             }
354
355             // files ending in .pg.sql are native postgres files.. ## depricated
356
357
358             $cmd = "$psql_cmd  < " . escapeshellarg($fn ? $fn : $bfn) . ' 2>&1' ;
359
360             echo "$bfn:   $cmd ". ($this->cli ? "\n" : "<BR>\n");
361
362
363             passthru($cmd);
364
365             if ($fn) {
366                 unlink($fn);
367             }
368         }
369
370               
371              
372         
373     }
374     /**
375      * simple regex based convert mysql to pgsql...
376      */
377     function convertToPG($src)
378     {
379         //echo "Convert $src\n";
380                
381         $fn = $this->tempName('sql');
382         
383         $ret = array( ); // pad it a bit.
384         $extra = array("", "" );
385         
386         $tbl = false;
387         foreach(file($src) as $l) {
388             $l = trim($l);
389             
390             if (!strlen($l) || $l[0] == '#') {
391                 continue;
392             }
393             $m = array();
394             if (preg_match('#create\s+table\s+([a-z0-9_]+)#i',  $l, $m)) {
395                 $tbl = $m[1];
396              }
397             if (preg_match('#create\s+table\s+\`([a-z0-9_]+)\`#i',  $l, $m)) {
398                 $tbl = 'shop_' . strtolower($m[1]);
399                 $l = preg_replace('#create\s+table\s+\`([a-z0-9_]+)\`#i', "CREATE TABLE {$tbl}", $l);
400             }
401             if (preg_match('#\`([a-z0-9_]+)\`#i',  $l, $m) && !preg_match('#alter\s+table\s+#i',  $l)) {
402                 $l = preg_replace('#\`([a-z0-9_]+)\`#i', "{$m[1]}_name", $l);
403             }
404             // autoinc
405             if ($tbl && preg_match('#auto_increment#i',  $l, $m)) {
406                 $l = preg_replace('#auto_increment#i', "default nextval('{$tbl}_seq')", $l);
407                 $extra[]  =   "create sequence {$tbl}_seq;";
408               
409             }
410             
411             if (preg_match('#alter\s+table\s+(\`[a-z0-9_]+\`)#i',  $l, $m)){
412                 $l = preg_replace('#alter\s+table\s+(\`[a-z0-9_]+\`)#i', "ALTER TABLE {$tbl}", $l);
413             }
414             
415             // enum value -- use the text instead..
416             
417             if ($tbl && preg_match('#([\w]+)\s+(enum\([\w|\W]+\))#i',  $l, $m)) {
418                 $l = preg_replace('#enum\([\w|\W]+\)#i', "TEXT", $l);
419             }
420             // ignore the alter enum
421             if ($tbl && preg_match('#alter\s+table\s+([\w|\W]+)\s+enum\([\w|\W]+\)#i',  $l, $m)) {
422                 continue;
423             }
424             
425             // UNIQUE KEY .. ignore
426             if ($tbl && preg_match('#UNIQUE KEY#i',  $l, $m)) {
427                 $last = array_pop($ret);
428                 $ret[] = trim($last, ",");
429                 continue;
430             }
431             
432             if ($tbl && preg_match('#RENAME\s+TO#i',  $l, $m)) {
433                 continue;
434             }
435             
436             if ($tbl && preg_match('#change\s+column#i',  $l, $m)) {
437                 continue;
438             }
439             
440             // INDEX lookup ..ignore
441             if ($tbl && preg_match('#INDEX lookup+([\w|\W]+)#i',  $l, $m)) {
442                $last = array_pop($ret);
443                $ret[] = trim($last, ",");
444                continue;
445                
446             }
447             
448             // CREATE INDEX ..ignore
449             if (preg_match('#alter\s+table\s+([a-z0-9_]+)\s+add\s+index\s+#i',  $l, $m)) {
450 //               $l = "CREATE INDEX  {$m[1]}_{$m[2]} ON {$m[1]} {$m[3]}";
451                 continue;
452              }
453              
454             // basic types..
455             $l = preg_replace('#int\([0-9]+\)#i', 'INT', $l);
456             
457             $l = preg_replace('# datetime#i', ' TIMESTAMP WITHOUT TIME ZONE', $l);
458             $l = preg_replace('# blob#i', ' TEXT', $l);
459             $l = preg_replace('# longtext#i', ' TEXT', $l);
460             $l = preg_replace('# tinyint#i', ' INT', $l);
461             
462             $ret[] = $l;
463             
464         }
465         
466         $ret = array_merge($extra,$ret);
467 //        echo implode("\n", $ret); exit;
468         
469         file_put_contents($fn, implode("\n", $ret));
470         
471         return $fn;
472     }
473     
474     
475     function checkOpts($opts)
476     {
477         
478         
479         foreach($opts as $o=>$v) {
480             if (!preg_match('/^json-/', $o) || empty($v)) {
481                 continue;
482             }
483             if (!file_exists($v)) {
484                 die("File does not exist : OPTION --{$o} = {$v} \n");
485             }
486         }
487         
488         $modules = array_reverse($this->modulesList());
489         
490         // move 'project' one to the end...
491         
492         foreach ($modules as $module){
493             $file = $this->rootDir. "/Pman/$module/UpdateDatabase.php";
494             if($module == 'Core' || !file_exists($file)){
495                 continue;
496             }
497             require_once $file;
498             $class = "Pman_{$module}_UpdateDatabase";
499             $x = new $class;
500             if(!method_exists($x, 'checkOpts')){
501                 continue;
502             };
503             $x->checkOpts($opts);
504         }
505                 
506     }
507     static function jsonImportFromArray($opts)
508     {
509         foreach($opts as $o=>$v) {
510             if (!preg_match('/^json-/', $o) || empty($v)) {
511                 continue;
512             }
513             $type = str_replace('_', '-', substr($o,6));
514             $data= json_decode(file_get_contents($file),true);
515             DB_DataObject::factory($type)->importFromArray($data);
516             
517         }
518         
519         
520         
521     }
522     
523     function runUpdateModulesData()
524     {
525         HTML_FlexyFramework::get()->generateDataobjectsCache(true);
526
527         Pman_Core_UpdateDatabase::jsonImportFromArray($this->opts);
528         
529         
530         
531         // runs core...
532         $this->updateData(); 
533         $modules = array_reverse($this->modulesList());
534         
535         // move 'project' one to the end...
536         
537         foreach ($modules as $module){
538             $file = $this->rootDir. "/Pman/$module/UpdateDatabase.php";
539             if($module == 'Core' || !file_exists($file)){
540                 continue;
541             }
542             require_once $file;
543             $class = "Pman_{$module}_UpdateDatabase";
544             $x = new $class;
545             if(!method_exists($x, 'updateData')){
546                 continue;
547             };
548             $x->updateData();
549         }
550                 
551     }
552     
553     
554     function updateDataEnums()
555     {
556         $enum = DB_DataObject::Factory('core_enum');
557         $enum->initEnums(
558             array(
559                 array(
560                     'etype' => '',
561                     'name' => 'COMPTYPE',
562                     'display_name' =>  'Company Types',
563                     'is_system_enum' => 1,
564                     'cn' => array(
565                         array(
566                             'name' => 'OWNER',
567                             'display_name' => 'Owner',
568                             'seqid' => 999, // last...
569                             'is_system_enum' => 1,
570                         )
571                         
572                     )
573                 ),
574                 array(
575                     'etype' => '',
576                     'name' => 'HtmlEditor.font-family',
577                     'display_name' =>  'HTML Editor font families',
578                     'is_system_enum' => 1,
579                     'cn' => array(
580                         array(
581                             'name' => 'Helvetica,Arial,sans-serif',
582                             'display_name' => 'Helvetica',
583                             
584                         ),
585                         
586                         array(
587                             'name' => 'Courier New',
588                             'display_name' => 'Courier',
589                              
590                         ),
591                         array(
592                             'name' => 'Tahoma',
593                             'display_name' => 'Tahoma',
594                             
595                         ),
596                         array(
597                             'name' => 'Times New Roman,serif',
598                             'display_name' => 'Times',
599                            
600                         ),
601                         array(
602                             'name' => 'Verdana',
603                             'display_name' => 'Verdana',
604                             
605                         ),
606                         
607                             
608                         
609                     )
610                 ),
611             )
612         ); 
613         
614     }
615     function updateDataGroups()
616     {
617          
618         $groups = DB_DataObject::factory('groups');
619         $groups->initGroups();
620         
621         $groups->initDatabase($this,array(
622             array(
623                 'name' => 'bcc-email', // group who are bcc'ed on all requests.
624                 'type' => 0, // system
625             ),
626             
627         ));
628         
629     }
630     
631     function updateDataCompanies()
632     {
633          
634         // fix comptypes enums..
635         $c = DB_DataObject::Factory('Companies');
636         $c->selectAdd();
637         $c->selectAdd('distinct(comptype) as comptype');
638         $c->whereAdd("comptype != ''");
639         
640         $ctb = array();
641         foreach($c->fetchAll('comptype') as $cts) {
642             
643             
644             
645            $ctb[]= array( 'etype'=>'COMPTYPE', 'name' => $cts, 'display_name' => ucfirst(strtolower($cts)));
646         
647         }
648          $c = DB_DataObject::Factory('core_enum');
649          
650         $c->initEnums($ctb);
651         //DB_DataObject::debugLevel(1);
652         // fix comptypeid
653         $c = DB_DataObject::Factory('Companies');
654         $c->query("
655             UPDATE Companies 
656                 SET
657                     comptype_id = (SELECT id FROM core_enum where etype='comptype' and name=Companies.comptype)
658                 WHERE
659                     comptype_id = 0
660                     AND
661                     LENGTH(comptype) > 0
662                   
663                   
664                   ");
665          
666         
667         
668     }
669     
670     function updateData()
671     {
672         // fill i18n data..
673         
674         $this->updateDataEnums();
675         $this->updateDataGroups();
676         $this->updateDataCompanies();
677         
678         $c = DB_DataObject::Factory('I18n');
679         $c->buildDB();
680          
681        
682         
683         
684     }
685     function fixSequencesPgsql()
686     {
687         DB_DataObject::debugLevel(1);
688         $cs = DB_DataObject::factory('core_enum');
689          $cs->query("
690                SELECT  'SELECT SETVAL(' ||
691                          quote_literal(quote_ident(nspname) || '.' || quote_ident(S.relname)) ||
692                         ', MAX(' || quote_ident(C.attname)|| ') )  FROM ' || nspname || '.' || quote_ident(T.relname)|| ';' as cmd 
693                 FROM pg_class AS S,
694                     pg_depend AS D,
695                     pg_class AS T,
696                     pg_attribute AS C,
697                     pg_namespace AS NS
698                 WHERE S.relkind = 'S'
699                     AND S.oid = D.objid
700                     AND D.refobjid = T.oid
701                     AND D.refobjid = C.attrelid
702                     AND D.refobjsubid = C.attnum
703                     AND NS.oid = T.relnamespace
704                 ORDER BY S.relname;     
705         ");
706         while ($cs->fetch()) {
707             $cmds[] = $cs->cmd;
708         }
709         foreach($cmds as $cmd) {
710             $cs = DB_DataObject::factory('core_enum');
711             $cs->query($cmd);
712         }
713         
714          
715         
716         
717     }
718     
719 }