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