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             'bcc_group' => 'Empty Group',
133             'test_class' => 'Pman/Admin/Report/SendEventErrors',
134             'to_group' => 'Administrators',
135             'active' => 1,
136             'description' => '9. System Error Messages',
137             'template_dir' => '/Pman/Admin/templates/mail/'
138         )
139     );
140     
141     function getAuth() {
142         
143         
144         $ff = HTML_FlexyFramework::get();
145         if (!empty($ff->cli)) {
146             $this->cli = true;
147             return true;
148         }
149         
150         parent::getAuth(); // load company!
151         $au = $this->getAuthUser();
152         if (!$au || $au->company()->comptype != 'OWNER') {
153             $this->jerr("Not authenticated", array('authFailure' => true));
154         }
155         $this->authUser = $au;
156         return true;
157     }
158     
159     function get($args, $opts=array())
160     {
161          
162         PEAR::setErrorHandling(PEAR_ERROR_CALLBACK, array($this, 'onPearError'));
163    
164         $this->checkSystem();
165         
166         $this->verifyExtensions(array('curl'));
167         
168         if (class_exists('PDO_DataObjects_Introspection')) {
169             PDO_DataObject_Introspection::$cache = array();
170         }
171         echo "Generate DB cache\n";
172         HTML_FlexyFramework::get()->generateDataobjectsCache(true);
173         echo "Generated DB cache\n";
174         $ff = HTML_FlexyFramework::get();
175         
176         if(!isset($ff->Pman) || !isset($ff->Pman['local_base_url'])){
177             die("Please setup Pman[local_base_url]\n");
178         }
179         
180         $this->local_base_url = $ff->Pman['local_base_url'];
181         
182         if(!empty($ff->Core_Notify)){
183 //            require_once 'Pman/Core/NotifySmtpCheck.php';
184 //            $x = new Pman_Core_NotifySmtpCheck();
185 //            $x->check();
186         }
187         
188         $this->disabled = explode(',', $ff->disable);
189         
190         //$this->fixSequencesPgsql();exit;
191         $this->opts = $opts;
192         
193         if (!empty($opts['debug'])) {
194              DB_DataObject::DebugLevel($opts['debug']);
195         }
196         
197         // ask all the modules to verify the opts
198         echo "Checi options\n";
199         $this->checkOpts($opts);
200         
201           
202         
203         // do this first, so the innodb change + utf8 fixes column max sizes
204         
205         // this will trigger errors about freetext indexes - we will have to remove them manually.?
206         // 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..)
207         
208         $this->runExtensions(); 
209
210         
211         if (empty($opts['data-only'])) {
212             $this->importSQL();
213         }
214         if (!empty($opts['only-module-sql'])) {
215             return;
216         }
217         
218         
219
220         $this->runUpdateModulesData();
221         
222         if (!empty($opts['add-company']) && !in_array('Core', $this->disabled)) {
223             // make sure we have a good cache...?
224            
225             DB_DataObject::factory('core_company')->initCompanies($this, $opts);
226         }
227         
228         $this->runExtensions();
229         
230         $this->clearApacheDataobjectsCache();
231         
232         $this->clearApacheAssetCache();
233     }
234     
235     function output() {
236         echo "\nUpdate Completed SUCCESS\n";
237         return '';
238     }
239      /**
240      * imports SQL files from all DataObjects directories....
241      * 
242      * except any matching /migrate/
243      */
244     function importSQL()
245     {
246         
247         // loop through all the modules, and see if they have a importSQL method?
248         
249         
250         $ff = HTML_Flexyframework::get();
251         
252         $dburl = parse_url($ff->database); // used to be DB_DataObject['database'] - but not portable to PDO
253         
254         //$this->{'import' . $url['scheme']}($url);
255         
256         $dbtype = $dburl['scheme'];
257         
258         
259         $dirmethod = 'import' . $dburl['scheme'] . 'dir';
260         
261         
262        
263         
264         $ar = $this->modulesList();
265         
266         
267         foreach($ar as $m) {
268             
269             if(in_array($m, $this->disabled)){
270                 echo "module $m is disabled \n";
271                 continue;
272             }
273             
274             echo "Importing SQL from module $m\n";
275             if (!empty($this->opts['only-module-sql']) && $m != $this->opts['only-module-sql']) {
276                 continue;
277             }
278             
279             
280             // check to see if the class has
281             
282             
283             
284             $file = $this->rootDir. "/Pman/$m/UpdateDatabase.php";
285             if($m != 'Core' && file_exists($file)){
286                 
287                 require_once $file;
288                 $class = "Pman_{$m}_UpdateDatabase";
289                 $x = new $class;
290                 if(method_exists($x, 'importModuleSQL')){
291                     echo "Importing SQL from module $m using Module::importModuleSQL\n";
292                     $x->opts = $this->opts;
293                     $x->rootDir = $this->rootDir;
294                     $x->importModuleSQL($dburl);
295                     continue;
296                 }
297             };
298
299             echo "Importing SQL from module $m\n";
300             
301             
302             // if init has been called
303             // look in pgsql.ini
304             if (!empty($this->opts['init'])) {
305                 $this->{$dirmethod}($dburl, $this->rootDir. "/Pman/$m/{$dbtype}.init");
306                 
307             }
308             
309             
310             
311             $fd = $this->rootDir. "/Pman/$m/DataObjects";
312             
313             $this->{$dirmethod}($dburl, $fd);
314             
315             
316             // new -- sql directory..
317             // new style will not support migrate ... they have to go into mysql-migrate.... directories..
318             // new style will not support pg.sql etc.. naming - that's what the direcotries are for..
319             $dbdir = $dbtype == 'mysqli' ? 'mysql' : $dbtype;
320             
321             $this->{$dirmethod}($dburl, $this->rootDir. "/Pman/$m/sql");
322             $this->{$dirmethod}($dburl, $this->rootDir. "/Pman/$m/{$dbdir}");
323             
324            
325             
326             if (!empty($this->opts['init']) && file_exists($this->rootDir. "/Pman/$m/{$dbtype}.initdata")) {
327                 if (class_exists('PDO_DataObjects_Introspection')) {
328                     PDO_DataObject_Introspection::$cache = array();
329                 }
330                 HTML_FlexyFramework::get()->generateDataobjectsCache(true);
331                 
332                 $this->{$dirmethod}($dburl, $this->rootDir. "/Pman/$m/{$dbtype}.initdata");
333                 $this->{'fixSequences'. $dbtype}();
334                 
335             }
336               
337             
338         }
339         
340         
341     }
342     
343     
344     
345      
346     /** -------------- code to handle importing a whole directory of files into the database  -------  **/
347     
348     
349     function importpgsqldir($url, $dir, $disable_triggers = false)
350     {
351         $ff = HTML_FlexyFramework::get();
352         
353         require_once 'System.php';
354         $cat = System::which('cat');
355         $psql = System::which('psql');
356         
357          
358         if (!empty($url['pass'])) { 
359             putenv("PGPASSWORD=". $url['pass']);
360         }
361            
362         $psql_cmd = $psql .
363             ' -h ' . $url['host'] .
364             ' -U' . escapeshellarg($url['user']) .
365              ' ' . basename($url['path']);
366         
367         
368         echo $psql_cmd . "\n" ;
369         echo "scan : $dir\n";
370         
371         if (is_file($dir)) {
372             $files = array($dir);
373
374         } else {
375         
376         
377             $files = glob($dir.'/*.sql');
378             uksort($files, 'strcasecmp');
379         }
380         //$lsort = create_function('$a,$b','return strlen($a) > strlen($b) ? 1 : -1;');
381         //usort($files, $lsort);
382         
383         
384         foreach($files as $bfn) {
385
386
387             if (preg_match('/migrate/i', basename($bfn))) { // skip migration scripts at present..
388                 continue;
389             }
390             if (preg_match('#\.[a-z]{2}\.sql#i', basename($bfn))
391                 && !preg_match('#\.pg\.sql#i', basename($bfn))
392             ) { // skip migration scripts at present..
393                 continue;
394             }
395             $fn = false;
396
397             if (!preg_match('/pgsql/', basename($dir) )) {
398                  if ( !preg_match('#\.pg\.sql$#', basename($bfn))) {
399                     $fn = $this->convertToPG($bfn);
400                 }
401             }
402
403             // files ending in .pg.sql are native postgres files.. ## depricated
404
405
406             $cmd = "$psql_cmd  < " . escapeshellarg($fn ? $fn : $bfn) . ' 2>&1' ;
407
408             echo "$bfn:   $cmd ". ($ff->cli ? "\n" : "<BR>\n");
409
410             passthru($cmd);
411
412             if ($fn) {
413                 unlink($fn);
414             }
415         }
416
417               
418              
419         
420     }
421     
422     
423     /**
424      * mysql - does not support conversions.
425      * 
426      *
427      */
428     function importmysqlidir($dburl, $dir) {
429         return $this->importmysqldir($dburl, $dir);
430     }
431     
432     function importmysqldir($dburl, $dir)
433     {
434         
435         $this->fixMysqlInnodb(); /// run once 
436         
437         echo "Import MYSQL :: $dir\n";
438         
439         
440         require_once 'System.php';
441         $cat = System::which('cat');
442         $mysql = System::which('mysql');
443         
444        
445            
446         $mysql_cmd = $mysql .
447             ' -h ' . $dburl['host'] .
448             ' -u' . escapeshellarg($dburl['user']) .
449             (!empty($dburl['pass']) ? ' -p' . escapeshellarg($dburl['pass'])  :  '') .
450             ' ' . basename($dburl['path']);
451         //echo $mysql_cmd . "\n" ;
452         
453         $files = glob($dir.'/*.sql');
454         uksort($files, 'strcasecmp');
455         
456        
457         foreach($files as $fn) {
458                 
459                  
460                 if (preg_match('/migrate/i', basename($fn))) { // skip migration scripts at present..
461                     continue;
462                 }
463                 // .my.sql but not .pg.sql
464                 if (preg_match('#\.[a-z]{2}\.sql#i', basename($fn))
465                     && !preg_match('#\.my\.sql#i', basename($fn))
466                 ) { // skip migration scripts at present..
467                     continue;
468                 }
469                 if (!strlen(trim($fn))) {
470                     continue;
471                 }
472                 
473                 $cmd = "$mysql_cmd -f < " . escapeshellarg($fn) ." 2>&1" ;
474                 
475                 echo basename($dir).'/'. basename($fn) .    '::' .  $cmd. ($this->cli ? "\n" : "<BR>\n");
476                 
477                 
478                 $fp = popen($cmd, "r"); 
479                 while(!feof($fp)) 
480                 { 
481                     // send the current file part to the browser 
482                     $line = trim(fgets($fp, 1024));
483                     if (empty($line)) {
484                         continue;
485                     }
486                     $matches = array();
487                     if (!preg_match('/^ERROR\s+([0-9]+)/', $line, $matches)) {
488                         echo " ---- {$line}\n"; flush();
489                         continue;
490                     }
491                     $continue =0;
492                     switch($matches[1]) {
493                         case 1017: // cause by renaming table -- old one does not exist..
494                         case 1050: // create tables triggers this..
495                         case 1060: //    Duplicate column name
496                         case 1061: // Duplicate key name - triggered by add index.. but could hide error. - unlikely though.
497                         case 1091: // drop index -- name does not exist.. might hide errors..
498                         
499                         case 1146: // drop a index on an unknown table.. - happens rarely...
500                         case 1054: // Unknown column -- triggered by CHANGE COLUMN - but may hide other errrors..
501                             $continue = 1;
502                             break;
503                         
504                     }
505                     if ($continue) {
506                         echo " ---- {$line}\n"; flush();
507                         continue;
508                     }
509                     // real errors...
510                     // 1051: // Unknown table -- normally drop = add iff exists..
511                     echo "File: $fn\n$line\n";
512                     exit;
513                     
514                     
515                 } 
516                 
517             
518                 
519         }
520        
521         
522         
523     }
524     
525     
526     /**
527      * simple regex based convert mysql to pgsql...
528      */
529     function convertToPG($src)
530     {
531         //echo "Convert $src\n";
532                
533         $fn = $this->tempName('sql');
534         
535         $ret = array( ); // pad it a bit.
536         $extra = array("", "" );
537         
538         $tbl = false;
539         foreach(file($src) as $l) {
540             $l = trim($l);
541             
542             if (!strlen($l) || $l[0] == '#') {
543                 continue;
544             }
545             $m = array();
546             if (preg_match('#create\s+table\s+([a-z0-9_]+)#i',  $l, $m)) {
547                 $tbl = $m[1];
548              }
549             if (preg_match('#create\s+table\s+\`([a-z0-9_]+)\`#i',  $l, $m)) {
550                 $tbl = 'shop_' . strtolower($m[1]);
551                 $l = preg_replace('#create\s+table\s+\`([a-z0-9_]+)\`#i', "CREATE TABLE {$tbl}", $l);
552             }
553             if (preg_match('#\`([a-z0-9_]+)\`#i',  $l, $m) && !preg_match('#alter\s+table\s+#i',  $l)) {
554                 $l = preg_replace('#\`([a-z0-9_]+)\`#i', "{$m[1]}_name", $l);
555             }
556             // autoinc
557             if ($tbl && preg_match('#auto_increment#i',  $l, $m)) {
558                 $l = preg_replace('#auto_increment#i', "default nextval('{$tbl}_seq')", $l);
559                 $extra[]  =   "create sequence {$tbl}_seq;";
560               
561             }
562             
563             if (preg_match('#alter\s+table\s+(\`[a-z0-9_]+\`)#i',  $l, $m)){
564                 $l = preg_replace('#alter\s+table\s+(\`[a-z0-9_]+\`)#i', "ALTER TABLE {$tbl}", $l);
565             }
566             
567             // enum value -- use the text instead..
568             
569             if ($tbl && preg_match('#([\w]+)\s+(enum\([\w|\W]+\))#i',  $l, $m)) {
570                 $l = preg_replace('#enum\([\w|\W]+\)#i', "TEXT", $l);
571             }
572             // ignore the alter enum
573             if ($tbl && preg_match('#alter\s+table\s+([\w|\W]+)\s+enum\([\w|\W]+\)#i',  $l, $m)) {
574                 continue;
575             }
576             
577             // UNIQUE KEY .. ignore
578             if ($tbl && preg_match('#UNIQUE KEY#i',  $l, $m)) {
579                 $last = array_pop($ret);
580                 $ret[] = trim($last, ",");
581                 continue;
582             }
583             
584             if ($tbl && preg_match('#RENAME\s+TO#i',  $l, $m)) {
585                 continue;
586             }
587             
588             if ($tbl && preg_match('#change\s+column#i',  $l, $m)) {
589                 continue;
590             }
591             
592             // INDEX lookup ..ignore
593             if ($tbl && preg_match('#INDEX lookup+([\w|\W]+)#i',  $l, $m)) {
594                $last = array_pop($ret);
595                $ret[] = trim($last, ",");
596                continue;
597                
598             }
599             
600             // CREATE INDEX ..ignore
601             if (preg_match('#alter\s+table\s+([a-z0-9_]+)\s+add\s+index\s+#i',  $l, $m)) {
602 //               $l = "CREATE INDEX  {$m[1]}_{$m[2]} ON {$m[1]} {$m[3]}";
603                 continue;
604              }
605              
606             // basic types..
607             $l = preg_replace('#int\([0-9]+\)#i', 'INT', $l);
608             
609             $l = preg_replace('# datetime#i', ' TIMESTAMP WITHOUT TIME ZONE', $l);
610             $l = preg_replace('# blob#i', ' TEXT', $l);
611             $l = preg_replace('# longtext#i', ' TEXT', $l);
612             $l = preg_replace('# tinyint#i', ' INT', $l);
613             
614             $ret[] = $l;
615             
616         }
617         
618         $ret = array_merge($extra,$ret);
619 //        echo implode("\n", $ret); exit;
620         
621         file_put_contents($fn, implode("\n", $ret));
622         
623         return $fn;
624     }
625     
626     
627     function checkOpts($opts)
628     {
629         
630         
631         foreach($opts as $o=>$v) {
632             if (!preg_match('/^json-/', $o) || empty($v)) {
633                 continue;
634             }
635             if (!file_exists($v)) {
636                 die("File does not exist : OPTION --{$o} = {$v} \n");
637             }
638         }
639         
640         $modules = array_reverse($this->modulesList());
641         
642         // move 'project' one to the end...
643         
644         foreach ($modules as $module){
645             $file = $this->rootDir. "/Pman/$module/UpdateDatabase.php";
646             if($module == 'Core' || !file_exists($file)){
647                 continue;
648             }
649             require_once $file;
650             $class = "Pman_{$module}_UpdateDatabase";
651             $x = new $class;
652             if(!method_exists($x, 'checkOpts')){
653                 continue;
654             };
655             $x->checkOpts($opts);
656         }
657                 
658     }
659     static function jsonImportFromArray($opts)
660     {
661         foreach($opts as $o=>$v) {
662             if (!preg_match('/^json-/', $o) || empty($v)) {
663                 continue;
664             }
665             $type = str_replace('_', '-', substr($o,5));
666             
667             $data= json_decode(file_get_contents($v),true);
668             $pg = HTML_FlexyFramework::get()->page;
669             DB_DataObject::factory($type)->importFromArray($pg ,$data,$opts);
670             
671         }
672         
673         
674         
675     }
676     
677     
678     
679     function runUpdateModulesData()
680     {
681         if (class_exists('PDO_DataObjects_Introspection')) {
682             PDO_DataObject_Introspection::$cache = array();
683         }
684         HTML_FlexyFramework::get()->generateDataobjectsCache(true);
685         
686         if(!in_array('Core', $this->disabled)){
687             echo "Running jsonImportFromArray\n";
688             Pman_Core_UpdateDatabase::jsonImportFromArray($this->opts);
689             
690
691             echo "Running updateData on modules\n";
692             // runs core...
693             echo "Core\n";
694             $this->updateData(); 
695         }
696         
697         $modules = array_reverse($this->modulesList());
698         
699         // move 'project' one to the end...
700         
701         foreach ($modules as $module){
702             if(in_array($module, $this->disabled)){
703                 continue;
704             }
705             $file = $this->rootDir. "/Pman/$module/UpdateDatabase.php";
706             if($module == 'Core' || !file_exists($file)){
707                 continue;
708             }
709             
710             require_once $file;
711             $class = "Pman_{$module}_UpdateDatabase";
712             $x = new $class;
713             if(!method_exists($x, 'updateData')){
714                 continue;
715             };
716             echo "$module\n";
717             $x->updateData();
718         }
719         
720     }
721     
722     
723     function updateDataEnums()
724     {
725         HTML_FlexyFramework::get()->generateDataobjectsCache(true);
726
727         $enum = DB_DataObject::Factory('core_enum');
728         //DB_DAtaObject::debugLevel(1);
729         $enum->initEnums(
730             array(
731                 array(
732                     'etype' => '',
733                     'name' => 'COMPTYPE',
734                     'display_name' =>  'Company Types',
735                     'is_system_enum' => 1,
736                     'cn' => array(
737                         array(
738                             'name' => 'OWNER',
739                             'display_name' => 'Owner',
740                             'seqid' => 999, // last...
741                             'is_system_enum' => 1,
742                         )
743                         
744                     )
745                 ),
746                 array(
747                     'etype' => '',
748                     'name' => 'HtmlEditor.font-family',
749                     'display_name' =>  'HTML Editor font families',
750                     'is_system_enum' => 1,
751                     'cn' => array(
752                         array(
753                             'name' => 'Helvetica,Arial,sans-serif',
754                             'display_name' => 'Helvetica',
755                             
756                         ),
757                         
758                         array(
759                             'name' => 'Courier New',
760                             'display_name' => 'Courier',
761                              
762                         ),
763                         array(
764                             'name' => 'Tahoma',
765                             'display_name' => 'Tahoma',
766                             
767                         ),
768                         array(
769                             'name' => 'Times New Roman,serif',
770                             'display_name' => 'Times',
771                            
772                         ),
773                         array(
774                             'name' => 'Verdana',
775                             'display_name' => 'Verdana',
776                             
777                         ),
778                         
779                             
780                         
781                     )
782                 )
783                
784             )
785         ); 
786         
787     }
788     function updateDataGroups()
789     {
790          
791         $groups = DB_DataObject::factory('core_group');
792         $groups->initGroups();
793         
794         $groups->initDatabase($this,array(
795             array(
796                 'name' => 'bcc-email', // group who are bcc'ed on all requests.
797                 'type' => 0, // system
798                 'display_name' => 'Standard BCC Group'
799             ),
800             array(
801                 'name' => 'system-email-from',
802                 'type' => 0, // system
803                 'display_name' => 'Standard System Email From Group'
804             ),
805             array(
806                 'name' => 'core-person-signup-bcc',
807                 'type' => 0, // system
808                 'display_name' => 'Standard Person Signup BCC Group'
809             ),
810             array(
811                 'name' => 'Empty Group', // use for no bcc emails.
812                 'type' => 0,
813                 'display_name' => 'Standard Empty Group'
814             )
815
816         ));
817         
818     }
819     
820     function updateDataCompanies()
821     {
822          
823         // fix comptypes enums..
824         $c = DB_DataObject::Factory('core_company');
825         $c->selectAdd();
826         $c->selectAdd('distinct(comptype) as comptype');
827         $c->whereAdd("comptype != ''");
828         
829         $ctb = array();
830         foreach($c->fetchAll('comptype') as $cts) {
831             
832             
833             
834            $ctb[]= array( 'etype'=>'COMPTYPE', 'name' => $cts, 'display_name' => ucfirst(strtolower($cts)));
835         
836         }
837          $c = DB_DataObject::Factory('core_enum');
838          
839         $c->initEnums($ctb);
840         //DB_DataObject::debugLevel(1);
841         // fix comptypeid
842         $c = DB_DataObject::Factory('core_company');
843         $c->query("
844             UPDATE {$c->tableName()} 
845                 SET
846                     comptype_id = (SELECT id FROM core_enum where etype='comptype' and name={$c->tableName()}.comptype LIMIT 1)
847                 WHERE
848                     comptype_id = 0
849                     AND
850                     LENGTH(comptype) > 0
851                   
852                   
853                   ");
854          
855         
856         
857     }
858     
859     function updateDataEmails()
860     {
861         foreach ($this->emailTemplates as $k => $mail) {
862             
863             $mail_dir = "{$this->rootDir}{$mail['template_dir']}";
864
865             $this->initEmails(
866                 $mail_dir,
867                 array($k => $mail),
868                 false
869             );
870         }
871     }
872     
873     function initEmails($templateDir, $emails, $mapping = false)
874     {
875         HTML_FlexyFramework::get()->generateDataobjectsCache(true);
876
877         $pg = HTML_FlexyFramework::get()->page;
878         foreach($emails as $name=>$data) {
879             $cm = DB_DataObject::factory('core_email');
880             $update = $cm->get('name', $name);
881             $old = clone($cm);
882             
883             if (empty($cm->bcc_group_id)) {
884                 if (empty($data['bcc_group'])) {
885                     $this->jerr("missing bcc_group for template $name");
886                 }
887                 
888                 $g = DB_DataObject::Factory('core_group')->lookup('name',$data['bcc_group']);
889                 
890                 if (empty($g->id)) {
891                     $this->jerr("bcc_group {$data['bcc_group']} does not exist when importing template $name");
892                 }
893                 
894                 if (!$g->members('email') && $g->name != 'Empty Group') {
895                     $this->jerr("bcc_group {$data['bcc_group']} does not have any members");
896                 }
897                 
898                 $cm->bcc_group_id = $g->id;
899             }
900             // initEmails will always have the latest location of the test class - in theory the user should not be changign the value of this...
901             //if (empty($cm->test_class)) {
902             if (empty($data['test_class'])) {
903                 $this->jerr("missing test_class for template $name");
904             }
905             
906             $cm->test_class = $data['test_class'];
907             //}
908             if(isset($cm->to_group_id)) {
909                 print_r('isset');
910             }
911             
912             if (
913                 !empty($data['to_group']) &&
914                 (!isset($cm->to_group_id) || !empty($cm->to_group_id)) 
915             ) {
916                 $gp = DB_DataObject::Factory('core_group')->lookup('name',$data['to_group']);
917                 
918                 if (empty($gp->id)) {
919                     $this->jerr("to_group {$data['to_group']} does not exist when importing template $name");
920                 }
921                 
922                 $cm->to_group_id = $gp->id;
923             }
924             
925             if(
926                 isset($data['active']) && !isset($cm->active)
927             ) {
928                 $cm->active = $data['active'];
929             }
930             
931             /*
932              * Set description to email.
933              * However we do not update if it is been set.
934              */
935             if(empty($cm->description) && !empty($data['description'])){
936                 $cm->description = $cm->escape($data['description']);
937             }
938             
939             require_once $cm->test_class . '.php';
940             
941             $clsname = str_replace('/','_', $cm->test_class);
942             try {
943                 $method = new ReflectionMethod($clsname , 'test_'. $name) ;
944                 $got_it = $method->isStatic();
945             } catch(Exception $e) {
946                 $got_it = false;
947                 
948             }
949             if (!$got_it) {
950                 $this->jerr("template {$name} does not have a test method {$clsname}::test_{$name}");
951             }
952             if ($update) {
953                 $cm->update($old);
954                 echo "email: {$name} - checked\n";
955                 continue; /// we do not import the body content of templates that exist...
956             } else {
957                 
958                 //$cm->insert();
959             }
960             
961             
962     //        $basedir = $this->bootLoader->rootDir . $mail_template_dir;
963             
964             $opts = array(
965                 'update' => 1,
966                 'file' => $templateDir. $name .'.html'
967             );
968             
969             if (!empty($data['master'])) {
970                 $opts['master'] = $templateDir . $master .'.html';
971             }
972             require_once 'Pman/Core/Import/Core_email.php';
973             $x = new Pman_Core_Import_Core_email();
974             
975             $x->updateOrCreateEmail('', $opts, $cm, $mapping);
976             
977             echo "email: {$name} - CREATED\n";
978         }
979     }
980     
981     
982     function updateData()
983     {
984         // fill i18n data..
985         if (class_exists('PDO_DataObjects_Introspection')) {
986             PDO_DataObject_Introspection::$cache = array();
987         }
988         HTML_FlexyFramework::get()->generateDataobjectsCache(true);
989         
990          
991         $this->updateDataEnums();
992         $this->updateDataGroups();
993         $this->updateDataCompanies();
994         
995         $this->updateDataEmails();
996         
997         $c = DB_DataObject::Factory('I18n');
998         $c->buildDB();
999          
1000        
1001         
1002         
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 }