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