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