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