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