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