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