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