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