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