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