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