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       
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                             
414                             $continue = 1;
415                             break;
416                         
417                     }
418                     if ($continue) {
419                         echo "IGNORE - {$line}\n"; flush();
420                         continue;
421                     }
422                     // real errors...
423                     // 1051: // Unknown table -- normally drop = add iff exists..
424                     
425                     print_r(array($line,$matches));exit;
426                     
427                     
428                 } 
429                 
430             
431                 
432         }
433        
434         
435         
436     }
437     
438     
439     /**
440      * simple regex based convert mysql to pgsql...
441      */
442     function convertToPG($src)
443     {
444         //echo "Convert $src\n";
445                
446         $fn = $this->tempName('sql');
447         
448         $ret = array( ); // pad it a bit.
449         $extra = array("", "" );
450         
451         $tbl = false;
452         foreach(file($src) as $l) {
453             $l = trim($l);
454             
455             if (!strlen($l) || $l[0] == '#') {
456                 continue;
457             }
458             $m = array();
459             if (preg_match('#create\s+table\s+([a-z0-9_]+)#i',  $l, $m)) {
460                 $tbl = $m[1];
461              }
462             if (preg_match('#create\s+table\s+\`([a-z0-9_]+)\`#i',  $l, $m)) {
463                 $tbl = 'shop_' . strtolower($m[1]);
464                 $l = preg_replace('#create\s+table\s+\`([a-z0-9_]+)\`#i', "CREATE TABLE {$tbl}", $l);
465             }
466             if (preg_match('#\`([a-z0-9_]+)\`#i',  $l, $m) && !preg_match('#alter\s+table\s+#i',  $l)) {
467                 $l = preg_replace('#\`([a-z0-9_]+)\`#i', "{$m[1]}_name", $l);
468             }
469             // autoinc
470             if ($tbl && preg_match('#auto_increment#i',  $l, $m)) {
471                 $l = preg_replace('#auto_increment#i', "default nextval('{$tbl}_seq')", $l);
472                 $extra[]  =   "create sequence {$tbl}_seq;";
473               
474             }
475             
476             if (preg_match('#alter\s+table\s+(\`[a-z0-9_]+\`)#i',  $l, $m)){
477                 $l = preg_replace('#alter\s+table\s+(\`[a-z0-9_]+\`)#i', "ALTER TABLE {$tbl}", $l);
478             }
479             
480             // enum value -- use the text instead..
481             
482             if ($tbl && preg_match('#([\w]+)\s+(enum\([\w|\W]+\))#i',  $l, $m)) {
483                 $l = preg_replace('#enum\([\w|\W]+\)#i', "TEXT", $l);
484             }
485             // ignore the alter enum
486             if ($tbl && preg_match('#alter\s+table\s+([\w|\W]+)\s+enum\([\w|\W]+\)#i',  $l, $m)) {
487                 continue;
488             }
489             
490             // UNIQUE KEY .. ignore
491             if ($tbl && preg_match('#UNIQUE KEY#i',  $l, $m)) {
492                 $last = array_pop($ret);
493                 $ret[] = trim($last, ",");
494                 continue;
495             }
496             
497             if ($tbl && preg_match('#RENAME\s+TO#i',  $l, $m)) {
498                 continue;
499             }
500             
501             if ($tbl && preg_match('#change\s+column#i',  $l, $m)) {
502                 continue;
503             }
504             
505             // INDEX lookup ..ignore
506             if ($tbl && preg_match('#INDEX lookup+([\w|\W]+)#i',  $l, $m)) {
507                $last = array_pop($ret);
508                $ret[] = trim($last, ",");
509                continue;
510                
511             }
512             
513             // CREATE INDEX ..ignore
514             if (preg_match('#alter\s+table\s+([a-z0-9_]+)\s+add\s+index\s+#i',  $l, $m)) {
515 //               $l = "CREATE INDEX  {$m[1]}_{$m[2]} ON {$m[1]} {$m[3]}";
516                 continue;
517              }
518              
519             // basic types..
520             $l = preg_replace('#int\([0-9]+\)#i', 'INT', $l);
521             
522             $l = preg_replace('# datetime#i', ' TIMESTAMP WITHOUT TIME ZONE', $l);
523             $l = preg_replace('# blob#i', ' TEXT', $l);
524             $l = preg_replace('# longtext#i', ' TEXT', $l);
525             $l = preg_replace('# tinyint#i', ' INT', $l);
526             
527             $ret[] = $l;
528             
529         }
530         
531         $ret = array_merge($extra,$ret);
532 //        echo implode("\n", $ret); exit;
533         
534         file_put_contents($fn, implode("\n", $ret));
535         
536         return $fn;
537     }
538     
539     
540     function checkOpts($opts)
541     {
542         
543         
544         foreach($opts as $o=>$v) {
545             if (!preg_match('/^json-/', $o) || empty($v)) {
546                 continue;
547             }
548             if (!file_exists($v)) {
549                 die("File does not exist : OPTION --{$o} = {$v} \n");
550             }
551         }
552         
553         $modules = array_reverse($this->modulesList());
554         
555         // move 'project' one to the end...
556         
557         foreach ($modules as $module){
558             $file = $this->rootDir. "/Pman/$module/UpdateDatabase.php";
559             if($module == 'Core' || !file_exists($file)){
560                 continue;
561             }
562             require_once $file;
563             $class = "Pman_{$module}_UpdateDatabase";
564             $x = new $class;
565             if(!method_exists($x, 'checkOpts')){
566                 continue;
567             };
568             $x->checkOpts($opts);
569         }
570                 
571     }
572     static function jsonImportFromArray($opts)
573     {
574         foreach($opts as $o=>$v) {
575             if (!preg_match('/^json-/', $o) || empty($v)) {
576                 continue;
577             }
578             $type = str_replace('_', '-', substr($o,5));
579             
580             $data= json_decode(file_get_contents($v),true);
581             $pg = HTML_FlexyFramework::get()->page;
582             DB_DataObject::factory($type)->importFromArray($pg ,$data,$opts);
583             
584         }
585         
586         
587         
588     }
589     
590     
591     
592     function runUpdateModulesData()
593     {
594         HTML_FlexyFramework::get()->generateDataobjectsCache(true);
595         
596         if(!in_array('Core', $this->disabled)){
597             echo "Running jsonImportFromArray\n";
598             Pman_Core_UpdateDatabase::jsonImportFromArray($this->opts);
599
600
601             echo "Running updateData on modules\n";
602             // runs core...
603             echo "Core\n";
604             $this->updateData(); 
605         }
606         
607         $modules = array_reverse($this->modulesList());
608         
609         // move 'project' one to the end...
610         
611         foreach ($modules as $module){
612             if(in_array($module, $this->disabled)){
613                 continue;
614             }
615             $file = $this->rootDir. "/Pman/$module/UpdateDatabase.php";
616             if($module == 'Core' || !file_exists($file)){
617                 continue;
618             }
619             
620             require_once $file;
621             $class = "Pman_{$module}_UpdateDatabase";
622             $x = new $class;
623             if(!method_exists($x, 'updateData')){
624                 continue;
625             };
626             echo "$module\n";
627             $x->updateData();
628         }
629                 
630     }
631     
632     
633     function updateDataEnums()
634     {
635         
636         $enum = DB_DataObject::Factory('core_enum');
637         //DB_DAtaObject::debugLevel(1);
638         $enum->initEnums(
639             array(
640                 array(
641                     'etype' => '',
642                     'name' => 'COMPTYPE',
643                     'display_name' =>  'Company Types',
644                     'is_system_enum' => 1,
645                     'cn' => array(
646                         array(
647                             'name' => 'OWNER',
648                             'display_name' => 'Owner',
649                             'seqid' => 999, // last...
650                             'is_system_enum' => 1,
651                         )
652                         
653                     )
654                 ),
655                 array(
656                     'etype' => '',
657                     'name' => 'HtmlEditor.font-family',
658                     'display_name' =>  'HTML Editor font families',
659                     'is_system_enum' => 1,
660                     'cn' => array(
661                         array(
662                             'name' => 'Helvetica,Arial,sans-serif',
663                             'display_name' => 'Helvetica',
664                             
665                         ),
666                         
667                         array(
668                             'name' => 'Courier New',
669                             'display_name' => 'Courier',
670                              
671                         ),
672                         array(
673                             'name' => 'Tahoma',
674                             'display_name' => 'Tahoma',
675                             
676                         ),
677                         array(
678                             'name' => 'Times New Roman,serif',
679                             'display_name' => 'Times',
680                            
681                         ),
682                         array(
683                             'name' => 'Verdana',
684                             'display_name' => 'Verdana',
685                             
686                         ),
687                         
688                             
689                         
690                     )
691                 ),
692             )
693         ); 
694         
695     }
696     function updateDataGroups()
697     {
698          
699         $groups = DB_DataObject::factory('groups');
700         $groups->initGroups();
701         
702         $groups->initDatabase($this,array(
703             array(
704                 'name' => 'bcc-email', // group who are bcc'ed on all requests.
705                 'type' => 0, // system
706             ),
707             array(
708                 'name' => 'system-email-from',
709                 'type' => 0, // system
710             ),
711             array(
712                 'name' => 'core-person-signup-bcc',
713                 'type' => 0, // system
714             ),
715         ));
716         
717     }
718     
719     function updateDataCompanies()
720     {
721          
722         // fix comptypes enums..
723         $c = DB_DataObject::Factory('Companies');
724         $c->selectAdd();
725         $c->selectAdd('distinct(comptype) as comptype');
726         $c->whereAdd("comptype != ''");
727         
728         $ctb = array();
729         foreach($c->fetchAll('comptype') as $cts) {
730             
731             
732             
733            $ctb[]= array( 'etype'=>'COMPTYPE', 'name' => $cts, 'display_name' => ucfirst(strtolower($cts)));
734         
735         }
736          $c = DB_DataObject::Factory('core_enum');
737          
738         $c->initEnums($ctb);
739         //DB_DataObject::debugLevel(1);
740         // fix comptypeid
741         $c = DB_DataObject::Factory('Companies');
742         $c->query("
743             UPDATE Companies 
744                 SET
745                     comptype_id = (SELECT id FROM core_enum where etype='comptype' and name=Companies.comptype LIMIT 1)
746                 WHERE
747                     comptype_id = 0
748                     AND
749                     LENGTH(comptype) > 0
750                   
751                   
752                   ");
753          
754         
755         
756     }
757     
758     
759     function initEmails($templateDir, $emails)
760     {
761       
762         $pg = HTML_FlexyFramework::get()->page;
763         foreach($emails as $name=>$data) {
764             $cm = DB_DataObject::factory('core_email');
765             $update = $cm->get('name', $name);
766             $old = clone($cm);
767             
768             if (empty($cm->bcc_group)) {
769                 if (empty($data['bcc_group'])) {
770                     $this->jerr("missing bcc_group for template $name");
771                 }
772                 $g = DB_DataObject::Factory('Groups')->lookup('name',$data['bcc_group']);
773                 
774                 if (!$g) {
775                     $this->jerr("bcc_group {$data['bcc_group']} does not exist when importing template $name");
776                 }
777                 if (!$g->members('email')) {
778                       $this->jerr("bcc_group {$data['bcc_group']} does not have any members");
779                 }
780                 
781                 
782                 $cm->bcc_group = $g->id;
783             }
784             if (empty($cm->test_class)) {
785                 if (empty($data['test_class'])) {
786                     $this->jerr("missing test_class for template $name");
787                 }
788                 $cm->test_class = $data['test_class'];
789             }
790             require_once $cm->test_class . '.php';
791             
792             $clsname = str_replace('/','_', $cm->test_class);
793             try {
794                 $method = new ReflectionMethod($clsname , 'test_'. $name) ;
795                 $got_it = $method->isStatic();
796             } catch(Exception $e) {
797                 $got_it = false;
798                 
799             }
800             if (!$got_it) {
801                 $this->jerr("template {$name} does not have a test method {$clsname}::test_{$name}");
802             }
803             if ($update) {
804                 $cm->update($old);
805                 echo "email: {$name} - checked\n";
806                 continue; /// we do not import the body content of templates that exist...
807             } else {
808                 $cm->insert();
809             }
810             
811             
812     //        $basedir = $this->bootLoader->rootDir . $mail_template_dir;
813             
814             $opts = array(
815                 'update' => 1,
816                 'file' => $templateDir. $name .'.html'
817             );
818             
819             if (!empty($data['master'])) {
820                 $opts['master'] = $templateDir . $master .'.html';
821             }
822             require_once 'Pman/Core/Import/Core_email.php';
823             $x = new Pman_Core_Import_Core_email();
824             $x->get('', $opts);
825             
826             echo "email: {$name} - CREATED\n";
827         }
828     }
829     
830     
831     function updateData()
832     {
833         // fill i18n data..
834         HTML_FlexyFramework::get()->generateDataobjectsCache(true);
835         $this->updateDataEnums();
836         $this->updateDataGroups();
837         $this->updateDataCompanies();
838         
839         $c = DB_DataObject::Factory('I18n');
840         $c->buildDB();
841          
842        
843         
844         
845     }
846     
847     function fixMysqlInnodb()
848     {
849         
850         static $done_check = false;
851         if ($done_check) {
852             return;
853         }
854         // innodb in single files is far more efficient that MYD or one big innodb file.
855         // first check if database is using this format.
856         $db = DB_DataObject::factory('core_enum');
857         $db->query("show variables like 'innodb_file_per_table'");
858         $db->fetch();
859         if ($db->Value == 'OFF') {
860             die("Error: set innodb_file_per_table = 1 in my.cnf\n\n");
861         }
862         
863         $done_check = true;;
864
865  
866         
867         
868         
869         
870         
871     }
872     
873     
874     /** ------------- schema fixing ... there is an issue with data imported having the wrong sequence names... --- */
875     
876     function fixSequencesMysql()
877     {
878         // not required...
879     }
880     
881     function fixSequencesPgsql()
882     {
883      
884      
885         //DB_DataObject::debugLevel(1);
886         $cs = DB_DataObject::factory('core_enum');
887         $cs->query("
888          SELECT
889                     'ALTER SEQUENCE '||
890                     CASE WHEN strpos(seq_name, '.') > 0 THEN
891                         min(seq_name)
892                     ELSE 
893                         quote_ident(min(schema_name)) ||'.'|| quote_ident(min(seq_name))
894                     END 
895                     
896                     ||' OWNED BY '|| quote_ident(min(schema_name)) || '.' ||
897                     quote_ident(min(table_name)) ||'.'|| quote_ident(min(column_name)) ||';' as cmd
898              FROM (
899                       
900                        SELECT 
901                      n.nspname AS schema_name,
902                      c.relname AS table_name,
903                      a.attname AS column_name, 
904                      regexp_replace(regexp_replace(d.adsrc, E'nextval\\\\(+[''\\\"]*', ''),E'[''\\\"]*::.*\$','') AS seq_name 
905                  FROM pg_class c 
906                  JOIN pg_attribute a ON (c.oid=a.attrelid) 
907                  JOIN pg_attrdef d ON (a.attrelid=d.adrelid AND a.attnum=d.adnum) 
908                  JOIN pg_namespace n ON (c.relnamespace=n.oid)
909                  WHERE has_schema_privilege(n.oid,'USAGE')
910                    AND n.nspname NOT LIKE 'pg!_%' escape '!'
911                    AND has_table_privilege(c.oid,'SELECT')
912                    AND (NOT a.attisdropped)
913                    AND d.adsrc ~ '^nextval'
914               
915              ) seq
916              WHERE
917                  CASE WHEN strpos(seq_name, '.') > 0 THEN
918                      substring(seq_name, 1,strpos(seq_name,'.')-1)
919                 ELSE
920                     schema_name
921                 END = schema_name
922              
923              GROUP BY seq_name HAVING count(*)=1
924              ");
925         $cmds = array();
926         while ($cs->fetch()) {
927             $cmds[] = $cs->cmd;
928         }
929         foreach($cmds as $cmd) {
930             $cs = DB_DataObject::factory('core_enum');
931             echo "$cmd\n";
932             $cs->query($cmd);
933         }
934         $cs = DB_DataObject::factory('core_enum');
935          $cs->query("
936                SELECT  'SELECT SETVAL(' ||
937                          quote_literal(quote_ident(nspname) || '.' || quote_ident(S.relname)) ||
938                         ', MAX(' || quote_ident(C.attname)|| ')::integer )  FROM ' || nspname || '.' || quote_ident(T.relname)|| ';' as cmd 
939                 FROM pg_class AS S,
940                     pg_depend AS D,
941                     pg_class AS T,
942                     pg_attribute AS C,
943                     pg_namespace AS NS
944                 WHERE S.relkind = 'S'
945                     AND S.oid = D.objid
946                     AND D.refobjid = T.oid
947                     AND D.refobjid = C.attrelid
948                     AND D.refobjsubid = C.attnum
949                     AND NS.oid = T.relnamespace
950                 ORDER BY S.relname   
951         ");
952          $cmds = array();
953         while ($cs->fetch()) {
954             $cmds[] = $cs->cmd;
955         }
956         foreach($cmds as $cmd) {
957             $cs = DB_DataObject::factory('core_enum');
958             echo "$cmd\n";
959             $cs->query($cmd);
960         }
961        
962     }
963     
964     var $extensions = array(
965         'EngineCharset',
966         'Links',
967     );
968     
969     function runExtensions()
970     {
971         
972         $ff = HTML_Flexyframework::get();
973         
974         $dburl = parse_url($ff->DB_DataObject['database']);
975         
976         $dbtype = $dburl['scheme'];
977        
978         foreach($this->extensions as $ext) {
979        
980             $scls = ucfirst($dbtype). $ext;
981             $cls = __CLASS__ . '_'. $scls;
982             $fn = implode('/',explode('_', $cls)).'.php';
983             if (!file_exists(__DIR__.'/UpdateDatabase/'. $scls .'.php')) {
984                 return;
985             }
986             require_once $fn;
987             $c = new $cls();
988             
989         }
990         
991     }
992     
993     
994     function checkSystem()
995     {
996         // most of these are from File_Convert...
997         
998         // these are required - and have simple dependancies.
999         require_once 'System.php';
1000         $req = array( 
1001             'convert',
1002             'grep',
1003             'pdfinfo',
1004             'pdftoppm',
1005             'rsvg-convert',  //librsvg2-bin
1006             'strings',
1007         );
1008          
1009          
1010          
1011         // these are prefered - but may have complicated depenacies
1012         $pref= array(
1013             'abiword',
1014             'faad',
1015             'ffmpeg',
1016             'html2text', // not availabe in debian squeeze
1017             'pdftocairo',  //poppler-utils - not available in debian squeeze.
1018
1019             'lame',
1020             'ssconvert',
1021             'unoconv',
1022             'wkhtmltopdf',
1023             'xvfb-run',
1024         );
1025         $res = array();
1026         $fail = false;
1027         foreach($req as $r) {
1028             if (!System::which($r)) {
1029                 $res[] = $r;
1030             }
1031             $fail = true;
1032         }
1033         if ($res) {
1034             $this->jerr("Missing these programs - need installing\n" . implode("\n",$res));
1035         }
1036         foreach($pref as $r) {
1037             if (!System::which($r)) {
1038                 $res[] = $r;
1039             }
1040             $fail = true;
1041         }
1042         if ($res) {
1043             echo "WARNING: Missing these programs - they may need installing\n". implode("\n",$res);
1044             sleep(5);
1045         }
1046         
1047         
1048     }
1049     
1050     
1051 }