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