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