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