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