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