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