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