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