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