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