Merge branch 'master' of http://git.roojs.com:8081/Pman.Core
[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       
22         'prefix' => array(
23             'desc' => 'prefix for the password (eg. fred > xxx4fred - prefix is xxx4)',
24             'short' => 'p',
25             'default' => '',
26             'min' => 1,
27             'max' => 1,
28         ),
29         'data-only' => array(
30             'desc' => 'only run the updateData - do not run import the tables and procedures.',
31             'short' => 'p',
32             'default' => '',
33             'min' => 1,
34             'max' => 1,
35             
36         ),
37         'add-company' => array(
38             'desc' => 'add a company name of the company',
39             'short' => 'n',
40             'default' => '',
41             'min' => 1,
42             'max' => 1,
43         ),
44         'add-company-with-type' => array(
45             'desc' => 'the type of company (default OWNER)',
46             'short' => 't',
47             'default' => 'OWNER',
48             'min' => 1,
49             'max' => 1,
50         ),
51         'init' => array(
52             'desc' => 'Initialize the database (pg only supported)',
53             'short' => 'i',
54             'default' => '',
55             'min' => 1,
56             'max' => 1,
57         ),
58         'only-module-sql' => array(
59             'desc' => 'Only run sql import on this modules - eg. Core',
60             'default' => '',
61             'min' => 1,
62             'max' => 1,
63         ),
64         'procedures-only' => array(
65             'desc' => 'Only import procedures (not supported by most modules yet) - ignores sql directory',
66             'default' => '',
67             'min' => 1,
68             'max' => 1,
69         ),
70         
71         
72         'json-person' => array(
73             'desc' => 'Person JSON file',
74             'default' => '',
75             'min' => 1,
76             'max' => 1,
77             
78         ),
79     );
80     
81     static function cli_opts()
82     {
83         
84         $ret = self::$cli_opts;
85         $ff = HTML_FlexyFramework::get();
86         $a = new Pman();
87         $mods = $a->modulesList();
88         foreach($mods as $m) {
89             
90             $fd = $ff->rootDir. "/Pman/$m/UpdateDatabase.php";
91             if (!file_exists($fd)) {
92                 continue;
93             }
94             
95             require_once $fd;
96             
97             $cls = new ReflectionClass('Pman_'. $m . '_UpdateDatabase');
98             
99             $ret = array_merge($ret, $cls->getStaticPropertyValue('cli_opts'));
100             
101             
102         }
103         
104         return $ret;
105     }
106     
107     var $opts = false;
108     var $disabled = array();
109     
110     
111     var $cli = false;
112     function getAuth() {
113         
114         
115         $ff = HTML_FlexyFramework::get();
116         if (!empty($ff->cli)) {
117             $this->cli = true;
118             return true;
119         }
120         
121         parent::getAuth(); // load company!
122         $au = $this->getAuthUser();
123         if (!$au || $au->company()->comptype != 'OWNER') {
124             $this->jerr("Not authenticated", array('authFailure' => true));
125         }
126         $this->authUser = $au;
127         return true;
128     }
129      
130     function get($args, $opts)
131     {
132         PEAR::setErrorHandling(PEAR_ERROR_CALLBACK, array($this, 'onPearError'));
133    
134         $this->checkSystem();
135    
136         $ff = HTML_FlexyFramework::get();
137         
138         $this->disabled = explode(',', $ff->disable);
139         
140         //$this->fixSequencesPgsql();exit;
141         $this->opts = $opts;
142         
143         // ask all the modules to verify the opts
144         
145         $this->checkOpts($opts);
146         
147         if (empty($opts['data-only'])) {
148             $this->importSQL();
149         }
150         if (!empty($opts['only-module-sql'])) {
151             return;
152         }
153         
154         $this->runUpdateModulesData();
155         
156         
157         if (!empty($opts['add-company']) && !in_array('Core', $this->disabled)) {
158             // make sure we have a good cache...?
159            
160             DB_DataObject::factory('companies')->initCompanies($this, $opts);
161         }
162         
163         $this->runExtensions();
164          
165          
166     }
167     function output() {
168         return '';
169     }
170      /**
171      * imports SQL files from all DataObjects directories....
172      * 
173      * except any matching /migrate/
174      */
175     function importSQL()
176     {
177         
178         // loop through all the modules, and see if they have a importSQL method?
179         
180         
181         $ff = HTML_Flexyframework::get();
182         
183         $dburl = parse_url($ff->DB_DataObject['database']);
184         
185         //$this->{'import' . $url['scheme']}($url);
186         
187         $dbtype = $dburl['scheme'];
188         $dirmethod = 'import' . $dburl['scheme'] . 'dir';
189         
190         
191        
192         
193         $ar = $this->modulesList();
194         
195         
196         foreach($ar as $m) {
197             
198             if(in_array($m, $this->disabled)){
199                 echo "module $m is disabled \n";
200                 continue;
201             }
202             
203             echo "Importing SQL from module $m\n";
204             if (!empty($this->opts['only-module-sql']) && $m != $this->opts['only-module-sql']) {
205                 continue;
206             }
207             
208             
209             // check to see if the class has
210             
211             
212             
213             $file = $this->rootDir. "/Pman/$m/UpdateDatabase.php";
214             if($m != 'Core' && file_exists($file)){
215                 
216                 require_once $file;
217                 $class = "Pman_{$m}_UpdateDatabase";
218                 $x = new $class;
219                 if(method_exists($x, 'importModuleSQL')){
220                     echo "Importing SQL from module $m using Module::importModuleSQL\n";
221                     $x->opts = $this->opts;
222                     $x->rootDir = $this->rootDir;
223                     $x->importModuleSQL($dburl);
224                     continue;
225                 }
226             };
227
228             echo "Importing SQL from module $m\n";
229             
230             
231             // if init has been called
232             // look in pgsql.ini
233             if (!empty($this->opts['init'])) {
234                 $this->{$dirmethod}($dburl, $this->rootDir. "/Pman/$m/{$dbtype}.init");
235                 
236             }
237             
238             
239             
240             $fd = $this->rootDir. "/Pman/$m/DataObjects";
241             
242             $this->{$dirmethod}($dburl, $fd);
243             
244             
245             // new -- sql directory..
246             // new style will not support migrate ... they have to go into mysql-migrate.... directories..
247             // new style will not support pg.sql etc.. naming - that's what the direcotries are for..
248             
249             $this->{$dirmethod}($dburl, $this->rootDir. "/Pman/$m/sql");
250             $this->{$dirmethod}($dburl, $this->rootDir. "/Pman/$m/{$dbtype}");
251             
252             
253             
254             if (!empty($this->opts['init']) && file_exists($this->rootDir. "/Pman/$m/{$dbtype}.initdata")) {
255                 HTML_FlexyFramework::get()->generateDataobjectsCache(true);
256                 
257                 $this->{$dirmethod}($dburl, $this->rootDir. "/Pman/$m/{$dbtype}.initdata");
258                 $this->{'fixSequences'. $dbtype}();
259                 
260             }
261               
262             
263         }
264         
265     }
266     
267     
268     
269      
270     /** -------------- code to handle importing a whole directory of files into the database  -------  **/
271     
272     
273     function importpgsqldir($url, $dir, $disable_triggers = false)
274     {
275         $ff = HTML_FlexyFramework::get();
276         
277         require_once 'System.php';
278         $cat = System::which('cat');
279         $psql = System::which('psql');
280         
281          
282         if (!empty($url['pass'])) { 
283             putenv("PGPASSWORD=". $url['pass']);
284         }
285            
286         $psql_cmd = $psql .
287             ' -h ' . $url['host'] .
288             ' -U' . escapeshellarg($url['user']) .
289              ' ' . basename($url['path']);
290         
291         
292         echo $psql_cmd . "\n" ;
293         echo "scan : $dir\n";
294         
295         if (is_file($dir)) {
296             $files = array($dir);
297
298         } else {
299         
300         
301             $files = glob($dir.'/*.sql');
302             uksort($files, 'strcasecmp');
303         }
304         //$lsort = create_function('$a,$b','return strlen($a) > strlen($b) ? 1 : -1;');
305         //usort($files, $lsort);
306         
307         
308         foreach($files as $bfn) {
309
310
311             if (preg_match('/migrate/i', basename($bfn))) { // skip migration scripts at present..
312                 continue;
313             }
314             if (preg_match('#\.[a-z]{2}\.sql#i', basename($bfn))
315                 && !preg_match('#\.pg\.sql#i', basename($bfn))
316             ) { // skip migration scripts at present..
317                 continue;
318             }
319             $fn = false;
320
321             if (!preg_match('/pgsql/', basename($dir) )) {
322                  if ( !preg_match('#\.pg\.sql$#', basename($bfn))) {
323                     $fn = $this->convertToPG($bfn);
324                 }
325             }
326
327             // files ending in .pg.sql are native postgres files.. ## depricated
328
329
330             $cmd = "$psql_cmd  < " . escapeshellarg($fn ? $fn : $bfn) . ' 2>&1' ;
331
332             echo "$bfn:   $cmd ". ($ff->cli ? "\n" : "<BR>\n");
333
334             passthru($cmd);
335
336             if ($fn) {
337                 unlink($fn);
338             }
339         }
340
341               
342              
343         
344     }
345     
346     
347     /**
348      * mysql - does not support conversions.
349      * 
350      *
351      */
352     
353     
354     function importmysqldir($dburl, $dir)
355     {
356         
357         $this->fixMysqlInnodb(); /// run once 
358         
359         echo "Import MYSQL :: $dir\n";
360         
361         
362         require_once 'System.php';
363         $cat = System::which('cat');
364         $mysql = System::which('mysql');
365         
366        
367            
368         $mysql_cmd = $mysql .
369             ' -h ' . $dburl['host'] .
370             ' -u' . escapeshellarg($dburl['user']) .
371             (!empty($dburl['pass']) ? ' -p' . escapeshellarg($dburl['pass'])  :  '') .
372             ' ' . basename($dburl['path']);
373         //echo $mysql_cmd . "\n" ;
374         
375         $files = glob($dir.'/*.sql');
376         uksort($files, 'strcasecmp');
377         
378        
379         foreach($files as $fn) {
380                 
381                  
382                 if (preg_match('/migrate/i', basename($fn))) { // skip migration scripts at present..
383                     continue;
384                 }
385                 // .my.sql but not .pg.sql
386                 if (preg_match('#\.[a-z]{2}\.sql#i', basename($fn))
387                     && !preg_match('#\.my\.sql#i', basename($fn))
388                 ) { // skip migration scripts at present..
389                     continue;
390                 }
391                 if (!strlen(trim($fn))) {
392                     continue;
393                 }
394                 
395                 $cmd = "$mysql_cmd -f < " . escapeshellarg($fn) ." 2>&1" ;
396                 
397                 echo basename($dir).'/'. basename($fn) .    '::' .  $cmd. ($this->cli ? "\n" : "<BR>\n");
398                 
399                 
400                 $fp = popen($cmd, "r"); 
401                 while(!feof($fp)) 
402                 { 
403                     // send the current file part to the browser 
404                     $line = trim(fgets($fp, 1024));
405                     $matches = array();
406                     if (!preg_match('/^ERROR\s+([0-9]+)/', $line, $matches)) {
407                         echo "OK - {$line}\n"; flush();
408                         continue;
409                     }
410                     $continue =0;
411                     switch($matches[1]) {
412                         case 1050: // create tables triggers this..
413                         case 1060: //    Duplicate column name
414                             
415                         case 1054: // Unknown column -- triggered by CHANGE COLUMN - but may hide other errrors..
416
417                             $continue = 1;
418                             break;
419                         
420                     }
421                     if ($continue) {
422                         echo "IGNORE - {$line}\n"; flush();
423                         continue;
424                     }
425                     // real errors...
426                     // 1051: // Unknown table -- normally drop = add iff exists..
427                     
428                     print_r(array($line,$matches));exit;
429                     
430                     
431                 } 
432                 
433             
434                 
435         }
436        
437         
438         
439     }
440     
441     
442     /**
443      * simple regex based convert mysql to pgsql...
444      */
445     function convertToPG($src)
446     {
447         //echo "Convert $src\n";
448                
449         $fn = $this->tempName('sql');
450         
451         $ret = array( ); // pad it a bit.
452         $extra = array("", "" );
453         
454         $tbl = false;
455         foreach(file($src) as $l) {
456             $l = trim($l);
457             
458             if (!strlen($l) || $l[0] == '#') {
459                 continue;
460             }
461             $m = array();
462             if (preg_match('#create\s+table\s+([a-z0-9_]+)#i',  $l, $m)) {
463                 $tbl = $m[1];
464              }
465             if (preg_match('#create\s+table\s+\`([a-z0-9_]+)\`#i',  $l, $m)) {
466                 $tbl = 'shop_' . strtolower($m[1]);
467                 $l = preg_replace('#create\s+table\s+\`([a-z0-9_]+)\`#i', "CREATE TABLE {$tbl}", $l);
468             }
469             if (preg_match('#\`([a-z0-9_]+)\`#i',  $l, $m) && !preg_match('#alter\s+table\s+#i',  $l)) {
470                 $l = preg_replace('#\`([a-z0-9_]+)\`#i', "{$m[1]}_name", $l);
471             }
472             // autoinc
473             if ($tbl && preg_match('#auto_increment#i',  $l, $m)) {
474                 $l = preg_replace('#auto_increment#i', "default nextval('{$tbl}_seq')", $l);
475                 $extra[]  =   "create sequence {$tbl}_seq;";
476               
477             }
478             
479             if (preg_match('#alter\s+table\s+(\`[a-z0-9_]+\`)#i',  $l, $m)){
480                 $l = preg_replace('#alter\s+table\s+(\`[a-z0-9_]+\`)#i', "ALTER TABLE {$tbl}", $l);
481             }
482             
483             // enum value -- use the text instead..
484             
485             if ($tbl && preg_match('#([\w]+)\s+(enum\([\w|\W]+\))#i',  $l, $m)) {
486                 $l = preg_replace('#enum\([\w|\W]+\)#i', "TEXT", $l);
487             }
488             // ignore the alter enum
489             if ($tbl && preg_match('#alter\s+table\s+([\w|\W]+)\s+enum\([\w|\W]+\)#i',  $l, $m)) {
490                 continue;
491             }
492             
493             // UNIQUE KEY .. ignore
494             if ($tbl && preg_match('#UNIQUE KEY#i',  $l, $m)) {
495                 $last = array_pop($ret);
496                 $ret[] = trim($last, ",");
497                 continue;
498             }
499             
500             if ($tbl && preg_match('#RENAME\s+TO#i',  $l, $m)) {
501                 continue;
502             }
503             
504             if ($tbl && preg_match('#change\s+column#i',  $l, $m)) {
505                 continue;
506             }
507             
508             // INDEX lookup ..ignore
509             if ($tbl && preg_match('#INDEX lookup+([\w|\W]+)#i',  $l, $m)) {
510                $last = array_pop($ret);
511                $ret[] = trim($last, ",");
512                continue;
513                
514             }
515             
516             // CREATE INDEX ..ignore
517             if (preg_match('#alter\s+table\s+([a-z0-9_]+)\s+add\s+index\s+#i',  $l, $m)) {
518 //               $l = "CREATE INDEX  {$m[1]}_{$m[2]} ON {$m[1]} {$m[3]}";
519                 continue;
520              }
521              
522             // basic types..
523             $l = preg_replace('#int\([0-9]+\)#i', 'INT', $l);
524             
525             $l = preg_replace('# datetime#i', ' TIMESTAMP WITHOUT TIME ZONE', $l);
526             $l = preg_replace('# blob#i', ' TEXT', $l);
527             $l = preg_replace('# longtext#i', ' TEXT', $l);
528             $l = preg_replace('# tinyint#i', ' INT', $l);
529             
530             $ret[] = $l;
531             
532         }
533         
534         $ret = array_merge($extra,$ret);
535 //        echo implode("\n", $ret); exit;
536         
537         file_put_contents($fn, implode("\n", $ret));
538         
539         return $fn;
540     }
541     
542     
543     function checkOpts($opts)
544     {
545         
546         
547         foreach($opts as $o=>$v) {
548             if (!preg_match('/^json-/', $o) || empty($v)) {
549                 continue;
550             }
551             if (!file_exists($v)) {
552                 die("File does not exist : OPTION --{$o} = {$v} \n");
553             }
554         }
555         
556         $modules = array_reverse($this->modulesList());
557         
558         // move 'project' one to the end...
559         
560         foreach ($modules as $module){
561             $file = $this->rootDir. "/Pman/$module/UpdateDatabase.php";
562             if($module == 'Core' || !file_exists($file)){
563                 continue;
564             }
565             require_once $file;
566             $class = "Pman_{$module}_UpdateDatabase";
567             $x = new $class;
568             if(!method_exists($x, 'checkOpts')){
569                 continue;
570             };
571             $x->checkOpts($opts);
572         }
573                 
574     }
575     static function jsonImportFromArray($opts)
576     {
577         foreach($opts as $o=>$v) {
578             if (!preg_match('/^json-/', $o) || empty($v)) {
579                 continue;
580             }
581             $type = str_replace('_', '-', substr($o,5));
582             
583             $data= json_decode(file_get_contents($v),true);
584             $pg = HTML_FlexyFramework::get()->page;
585             DB_DataObject::factory($type)->importFromArray($pg ,$data,$opts);
586             
587         }
588         
589         
590         
591     }
592     
593     
594     
595     function runUpdateModulesData()
596     {
597         HTML_FlexyFramework::get()->generateDataobjectsCache(true);
598         
599         if(!in_array('Core', $this->disabled)){
600             echo "Running jsonImportFromArray\n";
601             Pman_Core_UpdateDatabase::jsonImportFromArray($this->opts);
602
603
604             echo "Running updateData on modules\n";
605             // runs core...
606             echo "Core\n";
607             $this->updateData(); 
608         }
609         
610         $modules = array_reverse($this->modulesList());
611         
612         // move 'project' one to the end...
613         
614         foreach ($modules as $module){
615             if(in_array($module, $this->disabled)){
616                 continue;
617             }
618             $file = $this->rootDir. "/Pman/$module/UpdateDatabase.php";
619             if($module == 'Core' || !file_exists($file)){
620                 continue;
621             }
622             
623             require_once $file;
624             $class = "Pman_{$module}_UpdateDatabase";
625             $x = new $class;
626             if(!method_exists($x, 'updateData')){
627                 continue;
628             };
629             echo "$module\n";
630             $x->updateData();
631         }
632                 
633     }
634     
635     
636     function updateDataEnums()
637     {
638         
639         $enum = DB_DataObject::Factory('core_enum');
640         //DB_DAtaObject::debugLevel(1);
641         $enum->initEnums(
642             array(
643                 array(
644                     'etype' => '',
645                     'name' => 'COMPTYPE',
646                     'display_name' =>  'Company Types',
647                     'is_system_enum' => 1,
648                     'cn' => array(
649                         array(
650                             'name' => 'OWNER',
651                             'display_name' => 'Owner',
652                             'seqid' => 999, // last...
653                             'is_system_enum' => 1,
654                         )
655                         
656                     )
657                 ),
658                 array(
659                     'etype' => '',
660                     'name' => 'HtmlEditor.font-family',
661                     'display_name' =>  'HTML Editor font families',
662                     'is_system_enum' => 1,
663                     'cn' => array(
664                         array(
665                             'name' => 'Helvetica,Arial,sans-serif',
666                             'display_name' => 'Helvetica',
667                             
668                         ),
669                         
670                         array(
671                             'name' => 'Courier New',
672                             'display_name' => 'Courier',
673                              
674                         ),
675                         array(
676                             'name' => 'Tahoma',
677                             'display_name' => 'Tahoma',
678                             
679                         ),
680                         array(
681                             'name' => 'Times New Roman,serif',
682                             'display_name' => 'Times',
683                            
684                         ),
685                         array(
686                             'name' => 'Verdana',
687                             'display_name' => 'Verdana',
688                             
689                         ),
690                         
691                             
692                         
693                     )
694                 ),
695             )
696         ); 
697         
698     }
699     function updateDataGroups()
700     {
701          
702         $groups = DB_DataObject::factory('groups');
703         $groups->initGroups();
704         
705         $groups->initDatabase($this,array(
706             array(
707                 'name' => 'bcc-email', // group who are bcc'ed on all requests.
708                 'type' => 0, // system
709             ),
710             array(
711                 'name' => 'system-email-from',
712                 'type' => 0, // system
713             ),
714             array(
715                 'name' => 'core-person-signup-bcc',
716                 'type' => 0, // system
717             ),
718         ));
719         
720     }
721     
722     function updateDataCompanies()
723     {
724          
725         // fix comptypes enums..
726         $c = DB_DataObject::Factory('Companies');
727         $c->selectAdd();
728         $c->selectAdd('distinct(comptype) as comptype');
729         $c->whereAdd("comptype != ''");
730         
731         $ctb = array();
732         foreach($c->fetchAll('comptype') as $cts) {
733             
734             
735             
736            $ctb[]= array( 'etype'=>'COMPTYPE', 'name' => $cts, 'display_name' => ucfirst(strtolower($cts)));
737         
738         }
739          $c = DB_DataObject::Factory('core_enum');
740          
741         $c->initEnums($ctb);
742         //DB_DataObject::debugLevel(1);
743         // fix comptypeid
744         $c = DB_DataObject::Factory('Companies');
745         $c->query("
746             UPDATE Companies 
747                 SET
748                     comptype_id = (SELECT id FROM core_enum where etype='comptype' and name=Companies.comptype LIMIT 1)
749                 WHERE
750                     comptype_id = 0
751                     AND
752                     LENGTH(comptype) > 0
753                   
754                   
755                   ");
756          
757         
758         
759     }
760     
761     
762     function initEmails($templateDir, $emails)
763     {
764       
765         $pg = HTML_FlexyFramework::get()->page;
766         foreach($emails as $name=>$data) {
767             $cm = DB_DataObject::factory('core_email');
768             $update = $cm->get('name', $name);
769             $old = clone($cm);
770             
771             if (empty($cm->bcc_group)) {
772                 if (empty($data['bcc_group'])) {
773                     $this->jerr("missing bcc_group for template $name");
774                 }
775                 $g = DB_DataObject::Factory('Groups')->lookup('name',$data['bcc_group']);
776                 
777                 if (!$g) {
778                     $this->jerr("bcc_group {$data['bcc_group']} does not exist when importing template $name");
779                 }
780                 if (!$g->members('email')) {
781                       $this->jerr("bcc_group {$data['bcc_group']} does not have any members");
782                 }
783                 
784                 
785                 $cm->bcc_group = $g->id;
786             }
787             if (empty($cm->test_class)) {
788                 if (empty($data['test_class'])) {
789                     $this->jerr("missing test_class for template $name");
790                 }
791                 $cm->test_class = $data['test_class'];
792             }
793             require_once $cm->test_class . '.php';
794             
795             $clsname = str_replace('/','_', $cm->test_class);
796             try {
797                 $method = new ReflectionMethod($clsname , 'test_'. $name) ;
798                 $got_it = $method->isStatic();
799             } catch(Exception $e) {
800                 $got_it = false;
801                 
802             }
803             if (!$got_it) {
804                 $this->jerr("template {$name} does not have a test method {$clsname}::test_{$name}");
805             }
806             if ($update) {
807                 $cm->update($old);
808                 echo "email: {$name} - checked\n";
809                 continue; /// we do not import the body content of templates that exist...
810             } else {
811                 $cm->insert();
812             }
813             
814             
815     //        $basedir = $this->bootLoader->rootDir . $mail_template_dir;
816             
817             $opts = array(
818                 'update' => 1,
819                 'file' => $templateDir. $name .'.html'
820             );
821             
822             if (!empty($data['master'])) {
823                 $opts['master'] = $templateDir . $master .'.html';
824             }
825             require_once 'Pman/Core/Import/Core_email.php';
826             $x = new Pman_Core_Import_Core_email();
827             $x->get('', $opts);
828             
829             echo "email: {$name} - CREATED\n";
830         }
831     }
832     
833     
834     function updateData()
835     {
836         // fill i18n data..
837         HTML_FlexyFramework::get()->generateDataobjectsCache(true);
838         $this->updateDataEnums();
839         $this->updateDataGroups();
840         $this->updateDataCompanies();
841         
842         $c = DB_DataObject::Factory('I18n');
843         $c->buildDB();
844          
845        
846         
847         
848     }
849     
850     function fixMysqlInnodb()
851     {
852         
853         static $done_check = false;
854         if ($done_check) {
855             return;
856         }
857         // innodb in single files is far more efficient that MYD or one big innodb file.
858         // first check if database is using this format.
859         $db = DB_DataObject::factory('core_enum');
860         $db->query("show variables like 'innodb_file_per_table'");
861         $db->fetch();
862         if ($db->Value == 'OFF') {
863             die("Error: set innodb_file_per_table = 1 in my.cnf\n\n");
864         }
865         
866         $done_check = true;;
867
868  
869         
870         
871         
872         
873         
874     }
875     
876     
877     /** ------------- schema fixing ... there is an issue with data imported having the wrong sequence names... --- */
878     
879     function fixSequencesMysql()
880     {
881         // not required...
882     }
883     
884     function fixSequencesPgsql()
885     {
886      
887      
888         //DB_DataObject::debugLevel(1);
889         $cs = DB_DataObject::factory('core_enum');
890         $cs->query("
891          SELECT
892                     'ALTER SEQUENCE '||
893                     CASE WHEN strpos(seq_name, '.') > 0 THEN
894                         min(seq_name)
895                     ELSE 
896                         quote_ident(min(schema_name)) ||'.'|| quote_ident(min(seq_name))
897                     END 
898                     
899                     ||' OWNED BY '|| quote_ident(min(schema_name)) || '.' ||
900                     quote_ident(min(table_name)) ||'.'|| quote_ident(min(column_name)) ||';' as cmd
901              FROM (
902                       
903                        SELECT 
904                      n.nspname AS schema_name,
905                      c.relname AS table_name,
906                      a.attname AS column_name, 
907                      regexp_replace(regexp_replace(d.adsrc, E'nextval\\\\(+[''\\\"]*', ''),E'[''\\\"]*::.*\$','') AS seq_name 
908                  FROM pg_class c 
909                  JOIN pg_attribute a ON (c.oid=a.attrelid) 
910                  JOIN pg_attrdef d ON (a.attrelid=d.adrelid AND a.attnum=d.adnum) 
911                  JOIN pg_namespace n ON (c.relnamespace=n.oid)
912                  WHERE has_schema_privilege(n.oid,'USAGE')
913                    AND n.nspname NOT LIKE 'pg!_%' escape '!'
914                    AND has_table_privilege(c.oid,'SELECT')
915                    AND (NOT a.attisdropped)
916                    AND d.adsrc ~ '^nextval'
917               
918              ) seq
919              WHERE
920                  CASE WHEN strpos(seq_name, '.') > 0 THEN
921                      substring(seq_name, 1,strpos(seq_name,'.')-1)
922                 ELSE
923                     schema_name
924                 END = schema_name
925              
926              GROUP BY seq_name HAVING count(*)=1
927              ");
928         $cmds = array();
929         while ($cs->fetch()) {
930             $cmds[] = $cs->cmd;
931         }
932         foreach($cmds as $cmd) {
933             $cs = DB_DataObject::factory('core_enum');
934             echo "$cmd\n";
935             $cs->query($cmd);
936         }
937         $cs = DB_DataObject::factory('core_enum');
938          $cs->query("
939                SELECT  'SELECT SETVAL(' ||
940                          quote_literal(quote_ident(nspname) || '.' || quote_ident(S.relname)) ||
941                         ', MAX(' || quote_ident(C.attname)|| ')::integer )  FROM ' || nspname || '.' || quote_ident(T.relname)|| ';' as cmd 
942                 FROM pg_class AS S,
943                     pg_depend AS D,
944                     pg_class AS T,
945                     pg_attribute AS C,
946                     pg_namespace AS NS
947                 WHERE S.relkind = 'S'
948                     AND S.oid = D.objid
949                     AND D.refobjid = T.oid
950                     AND D.refobjid = C.attrelid
951                     AND D.refobjsubid = C.attnum
952                     AND NS.oid = T.relnamespace
953                 ORDER BY S.relname   
954         ");
955          $cmds = array();
956         while ($cs->fetch()) {
957             $cmds[] = $cs->cmd;
958         }
959         foreach($cmds as $cmd) {
960             $cs = DB_DataObject::factory('core_enum');
961             echo "$cmd\n";
962             $cs->query($cmd);
963         }
964        
965     }
966     
967     var $extensions = array(
968         'EngineCharset',
969         'Links',
970     );
971     
972     function runExtensions()
973     {
974         
975         $ff = HTML_Flexyframework::get();
976         
977         $dburl = parse_url($ff->DB_DataObject['database']);
978         
979         $dbtype = $dburl['scheme'];
980        
981         foreach($this->extensions as $ext) {
982        
983             $scls = ucfirst($dbtype). $ext;
984             $cls = __CLASS__ . '_'. $scls;
985             $fn = implode('/',explode('_', $cls)).'.php';
986             if (!file_exists(__DIR__.'/UpdateDatabase/'. $scls .'.php')) {
987                 return;
988             }
989             require_once $fn;
990             $c = new $cls();
991             
992         }
993         
994     }
995     
996     
997     function checkSystem()
998     {
999         // most of these are from File_Convert...
1000         
1001         // these are required - and have simple dependancies.
1002         require_once 'System.php';
1003         $req = array( 
1004             'convert',
1005             'grep',
1006             'pdfinfo',
1007             'pdftoppm',
1008             'rsvg-convert',  //librsvg2-bin
1009             'strings',
1010         );
1011          
1012          
1013          
1014         // these are prefered - but may have complicated depenacies
1015         $pref= array(
1016             'abiword',
1017             'faad',
1018             'ffmpeg',
1019             'html2text', // not availabe in debian squeeze
1020             'pdftocairo',  //poppler-utils - not available in debian squeeze.
1021
1022             'lame',
1023             'ssconvert',
1024             'unoconv',
1025             'wkhtmltopdf',
1026             'xvfb-run',
1027         );
1028         $res = array();
1029         $fail = false;
1030         foreach($req as $r) {
1031             if (!System::which($r)) {
1032                 $res[] = $r;
1033             }
1034             $fail = true;
1035         }
1036         if ($res) {
1037             $this->jerr("Missing these programs - need installing\n" . implode("\n",$res));
1038         }
1039         foreach($pref as $r) {
1040             if (!System::which($r)) {
1041                 $res[] = $r;
1042             }
1043             $fail = true;
1044         }
1045         if ($res) {
1046             echo "WARNING: Missing these programs - they may need installing\n". implode("\n",$res);
1047             sleep(5);
1048         }
1049         
1050         
1051     }
1052     
1053     
1054 }