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