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