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