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