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