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