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