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