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         $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 = trim(fgets($fp, 1024));
405                     $matches = array();
406                     if (!preg_match('/^ERROR\s+([0-9]+)/', $line, $matches)) {
407                         echo "OK - {$line}\n"; flush();
408                         continue;
409                     }
410                     switch($matches[1]) {
411                         case 1050: // create tables triggers this..
412                             
413                             echo "IGNORE - {$line}\n"; flush();
414                             continue;
415                         
416                     }
417                     // real errors...
418                     // 1051: // Unknown table -- normally drop = add iff exists..
419                     
420                     print_r(array($line,$matches));exit;
421                     
422                     
423                 } 
424                 
425             
426                 
427         }
428        
429         
430         
431     }
432     
433     
434     /**
435      * simple regex based convert mysql to pgsql...
436      */
437     function convertToPG($src)
438     {
439         //echo "Convert $src\n";
440                
441         $fn = $this->tempName('sql');
442         
443         $ret = array( ); // pad it a bit.
444         $extra = array("", "" );
445         
446         $tbl = false;
447         foreach(file($src) as $l) {
448             $l = trim($l);
449             
450             if (!strlen($l) || $l[0] == '#') {
451                 continue;
452             }
453             $m = array();
454             if (preg_match('#create\s+table\s+([a-z0-9_]+)#i',  $l, $m)) {
455                 $tbl = $m[1];
456              }
457             if (preg_match('#create\s+table\s+\`([a-z0-9_]+)\`#i',  $l, $m)) {
458                 $tbl = 'shop_' . strtolower($m[1]);
459                 $l = preg_replace('#create\s+table\s+\`([a-z0-9_]+)\`#i', "CREATE TABLE {$tbl}", $l);
460             }
461             if (preg_match('#\`([a-z0-9_]+)\`#i',  $l, $m) && !preg_match('#alter\s+table\s+#i',  $l)) {
462                 $l = preg_replace('#\`([a-z0-9_]+)\`#i', "{$m[1]}_name", $l);
463             }
464             // autoinc
465             if ($tbl && preg_match('#auto_increment#i',  $l, $m)) {
466                 $l = preg_replace('#auto_increment#i', "default nextval('{$tbl}_seq')", $l);
467                 $extra[]  =   "create sequence {$tbl}_seq;";
468               
469             }
470             
471             if (preg_match('#alter\s+table\s+(\`[a-z0-9_]+\`)#i',  $l, $m)){
472                 $l = preg_replace('#alter\s+table\s+(\`[a-z0-9_]+\`)#i', "ALTER TABLE {$tbl}", $l);
473             }
474             
475             // enum value -- use the text instead..
476             
477             if ($tbl && preg_match('#([\w]+)\s+(enum\([\w|\W]+\))#i',  $l, $m)) {
478                 $l = preg_replace('#enum\([\w|\W]+\)#i', "TEXT", $l);
479             }
480             // ignore the alter enum
481             if ($tbl && preg_match('#alter\s+table\s+([\w|\W]+)\s+enum\([\w|\W]+\)#i',  $l, $m)) {
482                 continue;
483             }
484             
485             // UNIQUE KEY .. ignore
486             if ($tbl && preg_match('#UNIQUE KEY#i',  $l, $m)) {
487                 $last = array_pop($ret);
488                 $ret[] = trim($last, ",");
489                 continue;
490             }
491             
492             if ($tbl && preg_match('#RENAME\s+TO#i',  $l, $m)) {
493                 continue;
494             }
495             
496             if ($tbl && preg_match('#change\s+column#i',  $l, $m)) {
497                 continue;
498             }
499             
500             // INDEX lookup ..ignore
501             if ($tbl && preg_match('#INDEX lookup+([\w|\W]+)#i',  $l, $m)) {
502                $last = array_pop($ret);
503                $ret[] = trim($last, ",");
504                continue;
505                
506             }
507             
508             // CREATE INDEX ..ignore
509             if (preg_match('#alter\s+table\s+([a-z0-9_]+)\s+add\s+index\s+#i',  $l, $m)) {
510 //               $l = "CREATE INDEX  {$m[1]}_{$m[2]} ON {$m[1]} {$m[3]}";
511                 continue;
512              }
513              
514             // basic types..
515             $l = preg_replace('#int\([0-9]+\)#i', 'INT', $l);
516             
517             $l = preg_replace('# datetime#i', ' TIMESTAMP WITHOUT TIME ZONE', $l);
518             $l = preg_replace('# blob#i', ' TEXT', $l);
519             $l = preg_replace('# longtext#i', ' TEXT', $l);
520             $l = preg_replace('# tinyint#i', ' INT', $l);
521             
522             $ret[] = $l;
523             
524         }
525         
526         $ret = array_merge($extra,$ret);
527 //        echo implode("\n", $ret); exit;
528         
529         file_put_contents($fn, implode("\n", $ret));
530         
531         return $fn;
532     }
533     
534     
535     function checkOpts($opts)
536     {
537         
538         
539         foreach($opts as $o=>$v) {
540             if (!preg_match('/^json-/', $o) || empty($v)) {
541                 continue;
542             }
543             if (!file_exists($v)) {
544                 die("File does not exist : OPTION --{$o} = {$v} \n");
545             }
546         }
547         
548         $modules = array_reverse($this->modulesList());
549         
550         // move 'project' one to the end...
551         
552         foreach ($modules as $module){
553             $file = $this->rootDir. "/Pman/$module/UpdateDatabase.php";
554             if($module == 'Core' || !file_exists($file)){
555                 continue;
556             }
557             require_once $file;
558             $class = "Pman_{$module}_UpdateDatabase";
559             $x = new $class;
560             if(!method_exists($x, 'checkOpts')){
561                 continue;
562             };
563             $x->checkOpts($opts);
564         }
565                 
566     }
567     static function jsonImportFromArray($opts)
568     {
569         foreach($opts as $o=>$v) {
570             if (!preg_match('/^json-/', $o) || empty($v)) {
571                 continue;
572             }
573             $type = str_replace('_', '-', substr($o,5));
574             
575             $data= json_decode(file_get_contents($v),true);
576             $pg = HTML_FlexyFramework::get()->page;
577             DB_DataObject::factory($type)->importFromArray($pg ,$data,$opts);
578             
579         }
580         
581         
582         
583     }
584     
585     
586     
587     function runUpdateModulesData()
588     {
589         HTML_FlexyFramework::get()->generateDataobjectsCache(true);
590         
591         if(!in_array('Core', $this->disabled)){
592             echo "Running jsonImportFromArray\n";
593             Pman_Core_UpdateDatabase::jsonImportFromArray($this->opts);
594
595
596             echo "Running updateData on modules\n";
597             // runs core...
598             echo "Core\n";
599             $this->updateData(); 
600         }
601         
602         $modules = array_reverse($this->modulesList());
603         
604         // move 'project' one to the end...
605         
606         foreach ($modules as $module){
607             if(in_array($module, $this->disabled)){
608                 continue;
609             }
610             $file = $this->rootDir. "/Pman/$module/UpdateDatabase.php";
611             if($module == 'Core' || !file_exists($file)){
612                 continue;
613             }
614             
615             require_once $file;
616             $class = "Pman_{$module}_UpdateDatabase";
617             $x = new $class;
618             if(!method_exists($x, 'updateData')){
619                 continue;
620             };
621             echo "$module\n";
622             $x->updateData();
623         }
624                 
625     }
626     
627     
628     function updateDataEnums()
629     {
630         
631         $enum = DB_DataObject::Factory('core_enum');
632         //DB_DAtaObject::debugLevel(1);
633         $enum->initEnums(
634             array(
635                 array(
636                     'etype' => '',
637                     'name' => 'COMPTYPE',
638                     'display_name' =>  'Company Types',
639                     'is_system_enum' => 1,
640                     'cn' => array(
641                         array(
642                             'name' => 'OWNER',
643                             'display_name' => 'Owner',
644                             'seqid' => 999, // last...
645                             'is_system_enum' => 1,
646                         )
647                         
648                     )
649                 ),
650                 array(
651                     'etype' => '',
652                     'name' => 'HtmlEditor.font-family',
653                     'display_name' =>  'HTML Editor font families',
654                     'is_system_enum' => 1,
655                     'cn' => array(
656                         array(
657                             'name' => 'Helvetica,Arial,sans-serif',
658                             'display_name' => 'Helvetica',
659                             
660                         ),
661                         
662                         array(
663                             'name' => 'Courier New',
664                             'display_name' => 'Courier',
665                              
666                         ),
667                         array(
668                             'name' => 'Tahoma',
669                             'display_name' => 'Tahoma',
670                             
671                         ),
672                         array(
673                             'name' => 'Times New Roman,serif',
674                             'display_name' => 'Times',
675                            
676                         ),
677                         array(
678                             'name' => 'Verdana',
679                             'display_name' => 'Verdana',
680                             
681                         ),
682                         
683                             
684                         
685                     )
686                 ),
687             )
688         ); 
689         
690     }
691     function updateDataGroups()
692     {
693          
694         $groups = DB_DataObject::factory('groups');
695         $groups->initGroups();
696         
697         $groups->initDatabase($this,array(
698             array(
699                 'name' => 'bcc-email', // group who are bcc'ed on all requests.
700                 'type' => 0, // system
701             ),
702             array(
703                 'name' => 'system-email-from',
704                 'type' => 0, // system
705             ),
706             array(
707                 'name' => 'core-person-signup-bcc',
708                 'type' => 0, // system
709             ),
710         ));
711         
712     }
713     
714     function updateDataCompanies()
715     {
716          
717         // fix comptypes enums..
718         $c = DB_DataObject::Factory('Companies');
719         $c->selectAdd();
720         $c->selectAdd('distinct(comptype) as comptype');
721         $c->whereAdd("comptype != ''");
722         
723         $ctb = array();
724         foreach($c->fetchAll('comptype') as $cts) {
725             
726             
727             
728            $ctb[]= array( 'etype'=>'COMPTYPE', 'name' => $cts, 'display_name' => ucfirst(strtolower($cts)));
729         
730         }
731          $c = DB_DataObject::Factory('core_enum');
732          
733         $c->initEnums($ctb);
734         //DB_DataObject::debugLevel(1);
735         // fix comptypeid
736         $c = DB_DataObject::Factory('Companies');
737         $c->query("
738             UPDATE Companies 
739                 SET
740                     comptype_id = (SELECT id FROM core_enum where etype='comptype' and name=Companies.comptype LIMIT 1)
741                 WHERE
742                     comptype_id = 0
743                     AND
744                     LENGTH(comptype) > 0
745                   
746                   
747                   ");
748          
749         
750         
751     }
752     
753     
754     function initEmails($templateDir, $emails)
755     {
756       
757         $pg = HTML_FlexyFramework::get()->page;
758         foreach($emails as $name=>$data) {
759             $cm = DB_DataObject::factory('core_email');
760             $update = $cm->get('name', $name);
761             $old = clone($cm);
762             
763             if (empty($cm->bcc_group)) {
764                 if (empty($data['bcc_group'])) {
765                     $this->jerr("missing bcc_group for template $name");
766                 }
767                 $g = DB_DataObject::Factory('Groups')->lookup('name',$data['bcc_group']);
768                 
769                 if (!$g) {
770                     $this->jerr("bcc_group {$data['bcc_group']} does not exist when importing template $name");
771                 }
772                 if (!$g->members('email')) {
773                       $this->jerr("bcc_group {$data['bcc_group']} does not have any members");
774                 }
775                 
776                 
777                 $cm->bcc_group = $g->id;
778             }
779             if (empty($cm->test_class)) {
780                 if (empty($data['test_class'])) {
781                     $this->jerr("missing test_class for template $name");
782                 }
783                 $cm->test_class = $data['test_class'];
784             }
785             require_once $cm->test_class . '.php';
786             
787             $clsname = str_replace('/','_', $cm->test_class);
788             try {
789                 $method = new ReflectionMethod($clsname , 'test_'. $name) ;
790                 $got_it = $method->isStatic();
791             } catch(Exception $e) {
792                 $got_it = false;
793                 
794             }
795             if (!$got_it) {
796                 $this->jerr("template {$name} does not have a test method {$clsname}::test_{$name}");
797             }
798             if ($update) {
799                 $cm->update($old);
800                 echo "email: {$name} - checked\n";
801                 continue; /// we do not import the body content of templates that exist...
802             } else {
803                 $cm->insert();
804             }
805             
806             
807     //        $basedir = $this->bootLoader->rootDir . $mail_template_dir;
808             
809             $opts = array(
810                 'update' => 1,
811                 'file' => $templateDir. $name .'.html'
812             );
813             
814             if (!empty($data['master'])) {
815                 $opts['master'] = $templateDir . $master .'.html';
816             }
817             require_once 'Pman/Core/Import/Core_email.php';
818             $x = new Pman_Core_Import_Core_email();
819             $x->get('', $opts);
820             
821             echo "email: {$name} - CREATED\n";
822         }
823     }
824     
825     
826     function updateData()
827     {
828         // fill i18n data..
829         HTML_FlexyFramework::get()->generateDataobjectsCache(true);
830         $this->updateDataEnums();
831         $this->updateDataGroups();
832         $this->updateDataCompanies();
833         
834         $c = DB_DataObject::Factory('I18n');
835         $c->buildDB();
836          
837        
838         
839         
840     }
841     
842     function fixMysqlInnodb()
843     {
844         
845         static $done_check = false;
846         if ($done_check) {
847             return;
848         }
849         // innodb in single files is far more efficient that MYD or one big innodb file.
850         // first check if database is using this format.
851         $db = DB_DataObject::factory('core_enum');
852         $db->query("show variables like 'innodb_file_per_table'");
853         $db->fetch();
854         if ($db->Value == 'OFF') {
855             die("Error: set innodb_file_per_table = 1 in my.cnf\n\n");
856         }
857         
858         $done_check = true;;
859
860  
861         
862         
863         
864         
865         
866     }
867     
868     
869     /** ------------- schema fixing ... there is an issue with data imported having the wrong sequence names... --- */
870     
871     function fixSequencesMysql()
872     {
873         // not required...
874     }
875     
876     function fixSequencesPgsql()
877     {
878      
879      
880         //DB_DataObject::debugLevel(1);
881         $cs = DB_DataObject::factory('core_enum');
882         $cs->query("
883          SELECT
884                     'ALTER SEQUENCE '||
885                     CASE WHEN strpos(seq_name, '.') > 0 THEN
886                         min(seq_name)
887                     ELSE 
888                         quote_ident(min(schema_name)) ||'.'|| quote_ident(min(seq_name))
889                     END 
890                     
891                     ||' OWNED BY '|| quote_ident(min(schema_name)) || '.' ||
892                     quote_ident(min(table_name)) ||'.'|| quote_ident(min(column_name)) ||';' as cmd
893              FROM (
894                       
895                        SELECT 
896                      n.nspname AS schema_name,
897                      c.relname AS table_name,
898                      a.attname AS column_name, 
899                      regexp_replace(regexp_replace(d.adsrc, E'nextval\\\\(+[''\\\"]*', ''),E'[''\\\"]*::.*\$','') AS seq_name 
900                  FROM pg_class c 
901                  JOIN pg_attribute a ON (c.oid=a.attrelid) 
902                  JOIN pg_attrdef d ON (a.attrelid=d.adrelid AND a.attnum=d.adnum) 
903                  JOIN pg_namespace n ON (c.relnamespace=n.oid)
904                  WHERE has_schema_privilege(n.oid,'USAGE')
905                    AND n.nspname NOT LIKE 'pg!_%' escape '!'
906                    AND has_table_privilege(c.oid,'SELECT')
907                    AND (NOT a.attisdropped)
908                    AND d.adsrc ~ '^nextval'
909               
910              ) seq
911              WHERE
912                  CASE WHEN strpos(seq_name, '.') > 0 THEN
913                      substring(seq_name, 1,strpos(seq_name,'.')-1)
914                 ELSE
915                     schema_name
916                 END = schema_name
917              
918              GROUP BY seq_name HAVING count(*)=1
919              ");
920         $cmds = array();
921         while ($cs->fetch()) {
922             $cmds[] = $cs->cmd;
923         }
924         foreach($cmds as $cmd) {
925             $cs = DB_DataObject::factory('core_enum');
926             echo "$cmd\n";
927             $cs->query($cmd);
928         }
929         $cs = DB_DataObject::factory('core_enum');
930          $cs->query("
931                SELECT  'SELECT SETVAL(' ||
932                          quote_literal(quote_ident(nspname) || '.' || quote_ident(S.relname)) ||
933                         ', MAX(' || quote_ident(C.attname)|| ')::integer )  FROM ' || nspname || '.' || quote_ident(T.relname)|| ';' as cmd 
934                 FROM pg_class AS S,
935                     pg_depend AS D,
936                     pg_class AS T,
937                     pg_attribute AS C,
938                     pg_namespace AS NS
939                 WHERE S.relkind = 'S'
940                     AND S.oid = D.objid
941                     AND D.refobjid = T.oid
942                     AND D.refobjid = C.attrelid
943                     AND D.refobjsubid = C.attnum
944                     AND NS.oid = T.relnamespace
945                 ORDER BY S.relname   
946         ");
947          $cmds = array();
948         while ($cs->fetch()) {
949             $cmds[] = $cs->cmd;
950         }
951         foreach($cmds as $cmd) {
952             $cs = DB_DataObject::factory('core_enum');
953             echo "$cmd\n";
954             $cs->query($cmd);
955         }
956        
957     }
958     
959     var $extensions = array(
960         'EngineCharset',
961         'Links',
962     );
963     
964     function runExtensions()
965     {
966         
967         $ff = HTML_Flexyframework::get();
968         
969         $dburl = parse_url($ff->DB_DataObject['database']);
970         
971         $dbtype = $dburl['scheme'];
972        
973         foreach($this->extensions as $ext) {
974        
975             $scls = ucfirst($dbtype). $ext;
976             $cls = __CLASS__ . '_'. $scls;
977             $fn = implode('/',explode('_', $cls)).'.php';
978             if (!file_exists(__DIR__.'/UpdateDatabase/'. $scls .'.php')) {
979                 return;
980             }
981             require_once $fn;
982             $c = new $cls();
983             
984         }
985         
986     }
987     
988     
989     function checkSystem()
990     {
991         // most of these are from File_Convert...
992         
993         // these are required - and have simple dependancies.
994         require_once 'System.php';
995         $req = array( 
996             'convert',
997             'grep',
998             'pdfinfo',
999             'pdftoppm',
1000             'rsvg-convert',  //librsvg2-bin
1001             'strings',
1002         );
1003          
1004          
1005          
1006         // these are prefered - but may have complicated depenacies
1007         $pref= array(
1008             'abiword',
1009             'faad',
1010             'ffmpeg',
1011             'html2text', // not availabe in debian squeeze
1012             'pdftocairo',  //poppler-utils - not available in debian squeeze.
1013
1014             'lame',
1015             'ssconvert',
1016             'unoconv',
1017             'wkhtmltopdf',
1018             'xvfb-run',
1019         );
1020         $res = array();
1021         $fail = false;
1022         foreach($req as $r) {
1023             if (!System::which($r)) {
1024                 $res[] = $r;
1025             }
1026             $fail = true;
1027         }
1028         if ($res) {
1029             $this->jerr("Missing these programs - need installing\n" . implode("\n",$res));
1030         }
1031         foreach($pref as $r) {
1032             if (!System::which($r)) {
1033                 $res[] = $r;
1034             }
1035             $fail = true;
1036         }
1037         if ($res) {
1038             echo "WARNING: Missing these programs - they may need installing\n". implode("\n",$res);
1039             sleep(5);
1040         }
1041         
1042         
1043     }
1044     
1045     
1046 }