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