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