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