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