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