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