DataObjects/core.sql
[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                 $this->importpgsqldir($dburl, $this->rootDir. "/Pman/$m/pgsql.initdata");
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        
259           
260     }
261     function importpgsqldir($url, $dir, $disable_triggers = false)
262     {
263         require_once 'System.php';
264         $cat = System::which('cat');
265         $psql = System::which('psql');
266         
267          
268         if (!empty($url['pass'])) { 
269             putenv("PGPASSWORD=". $url['pass']);
270         }
271            
272         $psql_cmd = $psql .
273             ' -h ' . $url['host'] .
274             ' -U' . escapeshellarg($url['user']) .
275              ' ' . basename($url['path']);
276         
277         
278         echo $psql_cmd . "\n" ;
279         echo "scan : $dir\n";
280         foreach(glob($dir.'/*.sql') as $bfn) {
281
282
283             if (preg_match('/migrate/i', basename($bfn))) { // skip migration scripts at present..
284                 continue;
285             }
286             if (preg_match('#\.[a-z]{2}\.sql#i', basename($bfn))
287                 && !preg_match('#\.pg\.sql#i', basename($bfn))
288             ) { // skip migration scripts at present..
289                 continue;
290             }
291             $fn = false;
292
293             if (!preg_match('/pgsql/', basename($dir) )) {
294                  if ( !preg_match('#\.pg\.sql$#', basename($bfn))) {
295                     $fn = $this->convertToPG($bfn);
296                 }
297             }
298
299             // files ending in .pg.sql are native postgres files.. ## depricated
300
301
302             $cmd = "$psql_cmd  < " . escapeshellarg($fn ? $fn : $bfn) . ' 2>&1' ;
303
304             echo "$bfn:   $cmd ". ($this->cli ? "\n" : "<BR>\n");
305
306
307             passthru($cmd);
308
309             if ($fn) {
310                 unlink($fn);
311             }
312         }
313
314               
315              
316         
317     }
318     /**
319      * simple regex based convert mysql to pgsql...
320      */
321     function convertToPG($src)
322     {
323         //echo "Convert $src\n";
324                
325         $fn = $this->tempName('sql');
326         
327         $ret = array( ); // pad it a bit.
328         $extra = array("", "" );
329         
330         $tbl = false;
331         foreach(file($src) as $l) {
332             $l = trim($l);
333             
334             if (!strlen($l) || $l[0] == '#') {
335                 continue;
336             }
337             $m = array();
338             if (preg_match('#create\s+table\s+([a-z0-9_]+)#i',  $l, $m)) {
339                 $tbl = $m[1];
340              }
341             if (preg_match('#create\s+table\s+\`([a-z0-9_]+)\`#i',  $l, $m)) {
342                 $tbl = 'shop_' . strtolower($m[1]);
343                 $l = preg_replace('#create\s+table\s+\`([a-z0-9_]+)\`#i', "CREATE TABLE {$tbl}", $l);
344             }
345             if (preg_match('#\`([a-z0-9_]+)\`#i',  $l, $m) && !preg_match('#alter\s+table\s+#i',  $l)) {
346                 $l = preg_replace('#\`([a-z0-9_]+)\`#i', "{$m[1]}_name", $l);
347             }
348             // autoinc
349             if ($tbl && preg_match('#auto_increment#i',  $l, $m)) {
350                 $l = preg_replace('#auto_increment#i', "default nextval('{$tbl}_seq')", $l);
351                 $extra[]  =   "create sequence {$tbl}_seq;";
352               
353             }
354             
355             if (preg_match('#alter\s+table\s+(\`[a-z0-9_]+\`)#i',  $l, $m)){
356                 $l = preg_replace('#alter\s+table\s+(\`[a-z0-9_]+\`)#i', "ALTER TABLE {$tbl}", $l);
357             }
358             
359             // enum value -- use the text instead..
360             
361             if ($tbl && preg_match('#([\w]+)\s+(enum\([\w|\W]+\))#i',  $l, $m)) {
362                 $l = preg_replace('#enum\([\w|\W]+\)#i', "TEXT", $l);
363             }
364             // ignore the alter enum
365             if ($tbl && preg_match('#alter\s+table\s+([\w|\W]+)\s+enum\([\w|\W]+\)#i',  $l, $m)) {
366                 continue;
367             }
368             
369             // UNIQUE KEY .. ignore
370             if ($tbl && preg_match('#UNIQUE KEY#i',  $l, $m)) {
371                 $last = array_pop($ret);
372                 $ret[] = trim($last, ",");
373                 continue;
374             }
375             
376             if ($tbl && preg_match('#RENAME\s+TO#i',  $l, $m)) {
377                 continue;
378             }
379             
380             if ($tbl && preg_match('#change\s+column#i',  $l, $m)) {
381                 continue;
382             }
383             
384             // INDEX lookup ..ignore
385             if ($tbl && preg_match('#INDEX lookup+([\w|\W]+)#i',  $l, $m)) {
386                $last = array_pop($ret);
387                $ret[] = trim($last, ",");
388                continue;
389                
390             }
391             
392             // CREATE INDEX ..ignore
393             if (preg_match('#alter\s+table\s+([a-z0-9_]+)\s+add\s+index\s+#i',  $l, $m)) {
394 //               $l = "CREATE INDEX  {$m[1]}_{$m[2]} ON {$m[1]} {$m[3]}";
395                 continue;
396              }
397              
398             // basic types..
399             $l = preg_replace('#int\([0-9]+\)#i', 'INT', $l);
400             
401             $l = preg_replace('# datetime#i', ' TIMESTAMP WITHOUT TIME ZONE', $l);
402             $l = preg_replace('# blob#i', ' TEXT', $l);
403             $l = preg_replace('# longtext#i', ' TEXT', $l);
404             $l = preg_replace('# tinyint#i', ' INT', $l);
405             
406             $ret[] = $l;
407             
408         }
409         
410         $ret = array_merge($extra,$ret);
411 //        echo implode("\n", $ret); exit;
412         
413         file_put_contents($fn, implode("\n", $ret));
414         
415         return $fn;
416     }
417     
418     function runUpdateModulesData()
419     {
420         // runs core...
421         $this->updateData(); 
422         $modules = array_reverse($this->modulesList());
423         
424         // move 'project' one to the end...
425         
426         foreach ($modules as $module){
427             $file = $this->rootDir. "/Pman/$module/UpdateDatabase.php";
428             if($module == 'Core' || !file_exists($file)){
429                 continue;
430             }
431             require_once $file;
432             $class = "Pman_{$module}_UpdateDatabase";
433             $x = new $class;
434             if(!method_exists($x, 'updateData')){
435                 continue;
436             };
437             $x->updateData();
438         }
439                 
440     }
441     
442     
443     function updateDataEnums()
444     {
445         $enum = DB_DataObject::Factory('core_enum');
446         $enum->initEnums(
447             array(
448                 array(
449                     'etype' => '',
450                     'name' => 'COMPTYPE',
451                     'display_name' =>  'Company Types',
452                     'is_system_enum' => 1,
453                     'cn' => array(
454                         array(
455                             'name' => 'OWNER',
456                             'display_name' => 'Owner',
457                             'seqid' => 999, // last...
458                             'is_system_enum' => 1,
459                         )
460                         
461                     )
462                 ),
463                 array(
464                     'etype' => '',
465                     'name' => 'HtmlEditor.font-family',
466                     'display_name' =>  'HTML Editor font families',
467                     'is_system_enum' => 1,
468                     'cn' => array(
469                         array(
470                             'name' => 'Helvetica,Arial,sans-serif',
471                             'display_name' => 'Helvetica',
472                             
473                         ),
474                         
475                         array(
476                             'name' => 'Courier New',
477                             'display_name' => 'Courier',
478                              
479                         ),
480                         array(
481                             'name' => 'Tahoma',
482                             'display_name' => 'Tahoma',
483                             
484                         ),
485                         array(
486                             'name' => 'Times New Roman,serif',
487                             'display_name' => 'Times',
488                            
489                         ),
490                         array(
491                             'name' => 'Verdana',
492                             'display_name' => 'Verdana',
493                             
494                         ),
495                         
496                             
497                         
498                     )
499                 ),
500             )
501         ); 
502         
503     }
504     function updateDataGroups()
505     {
506          
507         $groups = DB_DataObject::factory('groups');
508         $groups->initGroups();
509         
510         $groups->initDatabase($this,array(
511             array(
512                 'name' => 'bcc-email', // group who are bcc'ed on all requests.
513                 'type' => 0, // system
514             ),
515             
516         ));
517         
518     }
519     
520     function updateDataCompanies()
521     {
522          
523         // fix comptypes enums..
524         $c = DB_DataObject::Factory('Companies');
525         $c->selectAdd();
526         $c->selectAdd('distinct(comptype) as comptype');
527         $c->whereAdd("comptype != ''");
528         
529         $ctb = array();
530         foreach($c->fetchAll('comptype') as $cts) {
531             
532             
533             
534            $ctb[]= array( 'etype'=>'COMPTYPE', 'name' => $cts, 'display_name' => ucfirst(strtolower($cts)));
535         
536         }
537          $c = DB_DataObject::Factory('core_enum');
538          
539         $c->initEnums($ctb);
540         //DB_DataObject::debugLevel(1);
541         // fix comptypeid
542         $c = DB_DataObject::Factory('Companies');
543         $c->query("
544             UPDATE Companies 
545                 SET
546                     comptype_id = (SELECT id FROM core_enum where etype='comptype' and name=Companies.comptype)
547                 WHERE
548                     comptype_id = 0
549                     AND
550                     LENGTH(comptype) > 0
551                   
552                   
553                   ");
554          
555         
556         
557     }
558     
559     function updateData()
560     {
561         // fill i18n data..
562         
563         $this->updateDataEnums();
564         $this->updateDataGroups();
565         $this->updateDataCompanies();
566         
567         $c = DB_DataObject::Factory('I18n');
568         $c->buildDB();
569          
570        
571         
572         
573     }
574     
575     
576 }