fix #8131 - chinese translations
[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             $x->rootDir =  $this->rootDir;
771             echo "$module\n";
772             $x->updateData();
773         }
774         
775     }
776     
777     
778     function updateDataEnums()
779     {
780         HTML_FlexyFramework::get()->generateDataobjectsCache(true);
781
782         $enum = DB_DataObject::Factory('core_enum');
783         //DB_DAtaObject::debugLevel(1);
784         $enum->initEnums(
785             array(
786                 array(
787                     'etype' => '',
788                     'name' => 'COMPTYPE',
789                     'display_name' =>  'Company Types',
790                     'is_system_enum' => 1,
791                     'cn' => array(
792                         array(
793                             'name' => 'OWNER',
794                             'display_name' => 'Owner',
795                             'seqid' => 999, // last...
796                             'is_system_enum' => 1,
797                         )
798                         
799                     )
800                 ),
801                 array(
802                     'etype' => '',
803                     'name' => 'HtmlEditor.font-family',
804                     'display_name' =>  'HTML Editor font families',
805                     'is_system_enum' => 1,
806                     'cn' => array(
807                         array(
808                             'name' => 'Helvetica,Arial,sans-serif',
809                             'display_name' => 'Helvetica',
810                             
811                         ),
812                         
813                         array(
814                             'name' => 'Courier New',
815                             'display_name' => 'Courier',
816                              
817                         ),
818                         array(
819                             'name' => 'Tahoma',
820                             'display_name' => 'Tahoma',
821                             
822                         ),
823                         array(
824                             'name' => 'Times New Roman,serif',
825                             'display_name' => 'Times',
826                            
827                         ),
828                         array(
829                             'name' => 'Verdana',
830                             'display_name' => 'Verdana',
831                             
832                         ),
833                         
834                             
835                         
836                     )
837                 )
838                
839             )
840         ); 
841         
842     }
843     function updateDataGroups()
844     {
845          
846         $groups = DB_DataObject::factory('core_group');
847         $groups->initGroups();
848         
849         $groups->initDatabase($this,array(
850             array(
851                 'name' => 'bcc-email', // group who are bcc'ed on all requests.
852                 'type' => 0, // system
853                 'is_system' => 1,
854                 'display_name' => 'Standard BCC Group'
855             ),
856             array(
857                 'name' => 'system-email-from',
858                 'type' => 0, // system
859                 'is_system' => 1,
860                 'display_name' => 'Standard System Email From Group'
861             ),
862             array(
863                 'name' => 'core-person-signup-bcc',
864                 'type' => 0, // system
865                 'is_system' => 1,
866                 'display_name' => 'Standard Person Signup BCC Group'
867             ),
868             array(
869                 'name' => 'Empty Group', // use for no bcc emails.
870                 'type' => 0,
871                 'is_system' => 1,
872                 'display_name' => 'Standard Empty Group'
873             )
874
875         ));
876         
877     }
878     
879     function updateDataCompanies()
880     {
881          
882         // fix comptypes enums..
883         $c = DB_DataObject::Factory('core_company');
884         $c->selectAdd();
885         $c->selectAdd('distinct(comptype) as comptype');
886         $c->whereAdd("
887                 comptype != '' 
888             AND 
889                 comptype != 'undefined' 
890             AND 
891                 comptype != 'undefine'
892         ");
893         
894         $ctb = array();
895         foreach($c->fetchAll('comptype') as $cts) {
896             
897             $ctb[]= array( 'etype'=>'COMPTYPE', 'name' => $cts, 'display_name' => ucfirst(strtolower($cts)));
898         
899         }
900         $c = DB_DataObject::Factory('core_enum');
901          
902         $c->initEnums($ctb);
903         //DB_DataObject::debugLevel(1);
904         // fix comptypeid
905         $c = DB_DataObject::Factory('core_company');
906         $c->query("
907             UPDATE {$c->tableName()} 
908                 SET
909                     comptype_id = (SELECT id FROM core_enum where etype='comptype' and name={$c->tableName()}.comptype LIMIT 1)
910                 WHERE
911                     comptype_id = 0
912                     AND
913                     LENGTH(comptype) > 0
914                   
915                   
916                   ");
917          
918         
919         
920     }
921     
922     function updateDataEmails()
923     {
924         if (!empty($this->opts['skip-email-import'])) {
925             return;
926         }
927         foreach ($this->emailTemplates as $k => $mail) {
928             
929             $this->initEmails(
930                 !empty($mail['template_dir']) ? "{$this->rootDir}{$mail['template_dir']}" : '',
931                 array($k => $mail),
932                 false
933             );
934         }
935     }
936     
937     function initEmails($templateDir, $emails, $mapping = false)
938     {
939         HTML_FlexyFramework::get()->generateDataobjectsCache(true);
940
941         $pg = HTML_FlexyFramework::get()->page;
942         foreach($emails as $name=>$data) {
943             $cm = DB_DataObject::factory('core_email');
944             $update = $cm->get('name', $name);
945             $old = clone($cm);
946             
947             if (empty($cm->bcc_group_id)) {
948                 if (empty($data['bcc_group'])) {
949                     $this->jerr("missing bcc_group for template $name");
950                 }
951                 
952                 $g = DB_DataObject::Factory('core_group')->lookup('name',$data['bcc_group']);
953                 
954                 if (empty($g->id)) {
955                     $this->jerr("bcc_group {$data['bcc_group']} does not exist when importing template $name");
956                 }
957                 
958                 if (!$g->members('email') && $g->name != 'Empty Group') {
959                     $this->jerr("bcc_group {$data['bcc_group']} does not have any members");
960                 }
961                 
962                 $cm->bcc_group_id = $g->id;
963             }
964             // initEmails will always have the latest location of the test class - in theory the user should not be changign the value of this...
965             //if (empty($cm->test_class)) {
966             if (empty($data['test_class'])) {
967                 $this->jerr("missing test_class for template $name");
968             }
969             
970             $cm->test_class = $data['test_class'];
971             //}
972             if(isset($cm->to_group_id)) {
973                 print_r('isset');
974             }
975             
976             if (
977                 !empty($data['to_group']) &&
978                 (!isset($cm->to_group_id) || !empty($cm->to_group_id)) 
979             ) {
980                 $gp = DB_DataObject::Factory('core_group')->lookup('name',$data['to_group']);
981                 
982                 if (empty($gp->id)) {
983                     $this->jerr("to_group {$data['to_group']} does not exist when importing template $name");
984                 }
985                 
986                 $cm->to_group_id = $gp->id;
987             }
988             
989             if(
990                 isset($data['active']) && !isset($cm->active)
991             ) {
992                 $cm->active = $data['active'];
993             }
994             
995             /*
996              * Set description to email.
997              * However we do not update if it is been set.
998              */
999             if(empty($cm->description) && !empty($data['description'])){
1000                 $cm->description = $cm->escape($data['description']);
1001             }
1002             
1003             require_once $cm->test_class . '.php';
1004             
1005             $clsname = str_replace('/','_', $cm->test_class);
1006             try {
1007                 $method = new ReflectionMethod($clsname , 'test_'. $name) ;
1008                 $got_it = $method->isStatic();
1009             } catch(Exception $e) {
1010                 $got_it = false;
1011                 
1012             }
1013             if (!$got_it) {
1014                 $this->jerr("template {$name} does not have a test method {$clsname}::test_{$name}");
1015             }
1016             if ($update) {
1017                 $cm->update($old);
1018                 echo "email: {$name} - checked\n";
1019                 continue; /// we do not import the body content of templates that exist...
1020             } else {
1021                 
1022                 //$cm->insert();
1023             }
1024             
1025             
1026     //        $basedir = $this->bootLoader->rootDir . $mail_template_dir;
1027             
1028             $opts = array(
1029                 'update' => 1,
1030             );
1031             if (!empty($templateDir)) {
1032                 $opts['file'] = $templateDir. $name .'.html';
1033             }
1034             if (!empty($data['raw_content'])) {
1035                 $opts['raw_content'] = $data['raw_content'];
1036                 $opts['name'] = $name;
1037             }
1038             if (!empty($data['master'])) {
1039                 $opts['master'] = $templateDir . $master .'.html';
1040             }
1041             require_once 'Pman/Core/Import/Core_email.php';
1042             $x = new Pman_Core_Import_Core_email();
1043             
1044             $x->updateOrCreateEmail('', $opts, $cm, $mapping);
1045             
1046             echo "email: {$name} - CREATED\n";
1047         }
1048     }
1049     
1050     
1051     function updateData()
1052     {
1053         // fill i18n data..
1054         if (class_exists('PDO_DataObjects_Introspection')) {
1055             PDO_DataObject_Introspection::$cache = array();
1056         }
1057         HTML_FlexyFramework::get()->generateDataobjectsCache(true);
1058         
1059         $this->updateDataEnums();
1060         $this->updateDataGroups();
1061         $this->updateDataCompanies();
1062         
1063         $this->updateDataEmails();
1064         
1065         $c = DB_DataObject::Factory('I18n');
1066         $c->buildDB();
1067     }
1068     
1069     function fixMysqlInnodb()
1070     {
1071         
1072         static $done_check = false;
1073         if ($done_check) {
1074             return;
1075         }
1076         
1077         
1078         if (!empty($this->opts['skip-mysql-checks'])) {
1079             return;
1080         }
1081         // innodb in single files is far more efficient that MYD or one big innodb file.
1082         // first check if database is using this format.
1083         $db = DB_DataObject::factory('core_enum');
1084         $db->query("show variables like 'innodb_file_per_table'");
1085         $db->fetch();
1086         if ($db->Value == 'OFF') {
1087             die("Error: set innodb_file_per_table = 1 in my.cnf (or run with --skip-mysql-checks\n\n");
1088         }
1089         
1090         $db = DB_DataObject::factory('core_enum');
1091         $db->query("select version() as version");
1092         $db->fetch();
1093         
1094         if (version_compare($db->version, '5.7', '>=' )) {
1095                 
1096             $db = DB_DataObject::factory('core_enum');
1097             $db->query("show variables like 'sql_mode'");
1098             $db->fetch();
1099             
1100             $modes = explode(",", $db->Value);
1101             
1102             // these are 'new' problems with mysql.
1103             if(
1104                     in_array('NO_ZERO_IN_DATE', $modes) ||
1105                     in_array('NO_ZERO_DATE', $modes) ||
1106                     in_array('STRICT_TRANS_TABLES', $modes) || 
1107                     !in_array('ALLOW_INVALID_DATES', $modes)
1108             ){
1109                 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".
1110                     "Recommended line: \n\nsql_mode = ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION,ALLOW_INVALID_DATES\n\n"
1111                 );
1112             }
1113         }
1114         
1115         $done_check = true;;
1116
1117  
1118         
1119         
1120         
1121         
1122         
1123     }
1124     
1125     
1126     /** ------------- schema fixing ... there is an issue with data imported having the wrong sequence names... --- */
1127     
1128     function fixSequencesMysql()
1129     {
1130         // not required...
1131     }
1132     
1133     function fixSequencesPgsql()
1134     {
1135      
1136      
1137         //DB_DataObject::debugLevel(1);
1138         $cs = DB_DataObject::factory('core_enum');
1139         $cs->query("
1140          SELECT
1141                     'ALTER SEQUENCE '||
1142                     CASE WHEN strpos(seq_name, '.') > 0 THEN
1143                         min(seq_name)
1144                     ELSE 
1145                         quote_ident(min(schema_name)) ||'.'|| quote_ident(min(seq_name))
1146                     END 
1147                     
1148                     ||' OWNED BY '|| quote_ident(min(schema_name)) || '.' ||
1149                     quote_ident(min(table_name)) ||'.'|| quote_ident(min(column_name)) ||';' as cmd
1150              FROM (
1151                       
1152                        SELECT 
1153                      n.nspname AS schema_name,
1154                      c.relname AS table_name,
1155                      a.attname AS column_name, 
1156                      regexp_replace(regexp_replace(d.adsrc, E'nextval\\\\(+[''\\\"]*', ''),E'[''\\\"]*::.*\$','') AS seq_name 
1157                  FROM pg_class c 
1158                  JOIN pg_attribute a ON (c.oid=a.attrelid) 
1159                  JOIN pg_attrdef d ON (a.attrelid=d.adrelid AND a.attnum=d.adnum) 
1160                  JOIN pg_namespace n ON (c.relnamespace=n.oid)
1161                  WHERE has_schema_privilege(n.oid,'USAGE')
1162                    AND n.nspname NOT LIKE 'pg!_%' escape '!'
1163                    AND has_table_privilege(c.oid,'SELECT')
1164                    AND (NOT a.attisdropped)
1165                    AND d.adsrc ~ '^nextval'
1166               
1167              ) seq
1168              WHERE
1169                  CASE WHEN strpos(seq_name, '.') > 0 THEN
1170                      substring(seq_name, 1,strpos(seq_name,'.')-1)
1171                 ELSE
1172                     schema_name
1173                 END = schema_name
1174              
1175              GROUP BY seq_name HAVING count(*)=1
1176              ");
1177         $cmds = array();
1178         while ($cs->fetch()) {
1179             $cmds[] = $cs->cmd;
1180         }
1181         foreach($cmds as $cmd) {
1182             $cs = DB_DataObject::factory('core_enum');
1183             echo "$cmd\n";
1184             $cs->query($cmd);
1185         }
1186         $cs = DB_DataObject::factory('core_enum');
1187          $cs->query("
1188                SELECT  'SELECT SETVAL(' ||
1189                          quote_literal(quote_ident(nspname) || '.' || quote_ident(S.relname)) ||
1190                         ', MAX(' || quote_ident(C.attname)|| ')::integer )  FROM ' || nspname || '.' || quote_ident(T.relname)|| ';' as cmd 
1191                 FROM pg_class AS S,
1192                     pg_depend AS D,
1193                     pg_class AS T,
1194                     pg_attribute AS C,
1195                     pg_namespace AS NS
1196                 WHERE S.relkind = 'S'
1197                     AND S.oid = D.objid
1198                     AND D.refobjid = T.oid
1199                     AND D.refobjid = C.attrelid
1200                     AND D.refobjsubid = C.attnum
1201                     AND NS.oid = T.relnamespace
1202                 ORDER BY S.relname   
1203         ");
1204          $cmds = array();
1205         while ($cs->fetch()) {
1206             $cmds[] = $cs->cmd;
1207         }
1208         foreach($cmds as $cmd) {
1209             $cs = DB_DataObject::factory('core_enum');
1210             echo "$cmd\n";
1211             $cs->query($cmd);
1212         }
1213        
1214     }
1215     
1216     var $extensions = array(
1217         'EngineCharset',
1218         'Links',
1219     );
1220     
1221     function runExtensions()
1222     {
1223         
1224         $ff = HTML_Flexyframework::get();
1225         
1226         $dburl = parse_url($ff->database);
1227         
1228         $dbtype = $dburl['scheme'];
1229         $dbtype  = ($dbtype == 'mysqli') ? 'mysql' : $dbtype;
1230         
1231         foreach($this->extensions as $ext) {
1232        
1233             $scls = ucfirst($dbtype). $ext;
1234             $cls = __CLASS__ . '_'. $scls;
1235             $fn = implode('/',explode('_', $cls)).'.php';
1236             
1237             if (!file_exists(__DIR__.'/UpdateDatabase/'. $scls .'.php')) {
1238                 return;
1239             }
1240             echo "Running : {$fn}\n";
1241             require_once $fn;
1242             $c = new $cls();
1243             
1244         }
1245         
1246     }
1247     
1248     
1249     function checkSystem($req = false, $pref = false)
1250     {
1251         // most of these are from File_Convert...
1252         
1253         // these are required - and have simple dependancies.
1254         require_once 'System.php';
1255         $req = $req !== false ? $req : array( 
1256             'convert',
1257             'grep',
1258             'pdfinfo',
1259             'pdftoppm',
1260             'rsvg-convert',  //librsvg2-bin
1261             'strings',
1262             'oathtool',
1263             'gifsicle', // used for gif conversions
1264         );
1265          
1266           
1267         // these are prefered - but may have complicated depenacies
1268         $pref = $pref !== false ? $pref :  array(
1269             'abiword',
1270             //'faad',
1271             'ffmpeg',
1272             'html2text', // not availabe in debian squeeze
1273             'pdftocairo',  //poppler-utils - not available in debian squeeze.
1274
1275             //'lame',
1276             'ssconvert',
1277             'unoconv',
1278             'wkhtmltopdf',
1279             'xvfb-run',
1280         );
1281         $res = array();
1282         $fail = false;
1283         foreach($req as $r) {
1284             if (!System::which($r)) {
1285                 $res[] = $r;
1286             }
1287             $fail = true;
1288         }
1289         if ($res) {
1290             die("Missing these programs - need installing\n" . implode("\n",$res). "\n");
1291         }
1292         foreach($pref as $r) {
1293             if (!System::which($r)) {
1294                 $res[] = $r;
1295             }
1296             $fail = true;
1297         }
1298         if ($res) {
1299             echo "WARNING: Missing these programs - they may need installing\n". implode("\n",$res);
1300             sleep(5);
1301         }
1302         
1303         
1304     }
1305     
1306     function clearApacheDataobjectsCache()
1307     {
1308         
1309         // this needs to clear it's own cache along with remote one..
1310   
1311         $url = "http://localhost{$this->local_base_url}/Core/RefreshDatabaseCache";
1312         
1313         echo "Clearing Database Cache : http://localhost{$this->local_base_url}/Core/RefreshDatabaseCache\n";
1314         
1315         $response = $this->curl($url);
1316         
1317         $json = json_decode($response, true);
1318         
1319         if(empty($json['data']) || $json['data'] != 'DONE'){
1320             echo "fetching $url\n";
1321             echo "GOT:" . $response. "\n";
1322             echo "Clear DataObjects Cache failed\n";
1323             exit;
1324         }
1325         
1326     }
1327     
1328     
1329     function clearApacheAssetCache()
1330     {
1331         echo "Clearing Asset Cache : http://localhost{$this->local_base_url}/Core/Asset\n";
1332         $response = $this->curl(
1333             "http://localhost{$this->local_base_url}/Core/Asset",
1334             array( '_clear_cache' => 1 ,'returnHTML' => 'NO' ),
1335             'POST'
1336         );
1337         $json = json_decode($response, true);
1338         
1339         if(empty($json['success']) || !$json['success']) {
1340             echo $response. "\n";
1341             echo "CURL Clear Asset cache failed\n";
1342             exit;
1343         }
1344         
1345     }
1346     
1347     
1348     function curl($url, $request = array(), $method = 'GET') 
1349     {
1350         if($method == 'GET'){
1351             $request = http_build_query($request);
1352             $url = $url . "?" . $request;  
1353         }
1354         
1355         $ch = curl_init($url);
1356         
1357         if ($method == 'POST') {
1358             
1359             curl_setopt($ch, CURLOPT_POST, 1);
1360             curl_setopt($ch, CURLOPT_POSTFIELDS, $request);
1361             
1362         } else {
1363             curl_setopt($ch, CURLOPT_HTTPHEADER,
1364                     array("Content-Type: application/x-www-form-urlencoded", "Content-Length: " . strlen($request)));
1365             
1366         }
1367         
1368         curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
1369         
1370         curl_setopt($ch, CURLOPT_HEADER, false);
1371         curl_setopt($ch, CURLOPT_VERBOSE, 0);
1372         curl_setopt($ch, CURLOPT_TIMEOUT, 30);
1373         curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
1374
1375         $response = curl_exec($ch);
1376         
1377         curl_close($ch);
1378         
1379         return $response;
1380     }
1381     
1382     static function verifyExtensions($extensions)
1383     {
1384         $error = array();
1385         
1386         foreach ($extensions as $e){
1387             
1388             if(empty($e) || extension_loaded($e)) {
1389                 continue;
1390             }
1391             
1392             $error[] = "Error: Please install php extension: {$e}";
1393         }
1394         
1395         if(empty($error)){
1396            return true; 
1397         }
1398         $ff = HTML_FLexyFramework::get();
1399         
1400         $ff->page->jerr(implode('\n', $error));
1401     }
1402     
1403 }