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