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