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