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