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