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