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