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