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