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