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