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