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