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