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