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