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             $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         var_dump(DB_DataObject::DebugLevel());exit;
184         
185         // ask all the modules to verify the opts
186         
187         $this->checkOpts($opts);
188         
189           
190         
191         // do this first, so the innodb change + utf8 fixes column max sizes
192         
193         // this will trigger errors about freetext indexes - we will have to remove them manually.?
194         // 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..)
195         
196         $this->runExtensions(); 
197
198         
199         if (empty($opts['data-only'])) {
200             $this->importSQL();
201         }
202         if (!empty($opts['only-module-sql'])) {
203             return;
204         }
205         if (!empty($opts['debug'])) {
206             DB_DataObject::DebugLevel($opts['debug']);
207         }
208       
209         $this->runUpdateModulesData();
210         
211         if (!empty($opts['add-company']) && !in_array('Core', $this->disabled)) {
212             // make sure we have a good cache...?
213            
214             DB_DataObject::factory('core_company')->initCompanies($this, $opts);
215         }
216         
217         $this->runExtensions();
218         
219         $this->clearApacheDataobjectsCache();
220         
221          
222     }
223     function output() {
224         echo "\nUpdate Completed SUCCESS\n";
225         return '';
226     }
227      /**
228      * imports SQL files from all DataObjects directories....
229      * 
230      * except any matching /migrate/
231      */
232     function importSQL()
233     {
234         
235         // loop through all the modules, and see if they have a importSQL method?
236         
237         
238         $ff = HTML_Flexyframework::get();
239         
240         $dburl = parse_url($ff->database); // used to be DB_DataObject['database'] - but not portable to PDO
241         
242         //$this->{'import' . $url['scheme']}($url);
243         
244         $dbtype = $dburl['scheme'];
245         
246         
247         $dirmethod = 'import' . $dburl['scheme'] . 'dir';
248         
249         
250        
251         
252         $ar = $this->modulesList();
253         
254         
255         foreach($ar as $m) {
256             
257             if(in_array($m, $this->disabled)){
258                 echo "module $m is disabled \n";
259                 continue;
260             }
261             
262             echo "Importing SQL from module $m\n";
263             if (!empty($this->opts['only-module-sql']) && $m != $this->opts['only-module-sql']) {
264                 continue;
265             }
266             
267             
268             // check to see if the class has
269             
270             
271             
272             $file = $this->rootDir. "/Pman/$m/UpdateDatabase.php";
273             if($m != 'Core' && file_exists($file)){
274                 
275                 require_once $file;
276                 $class = "Pman_{$m}_UpdateDatabase";
277                 $x = new $class;
278                 if(method_exists($x, 'importModuleSQL')){
279                     echo "Importing SQL from module $m using Module::importModuleSQL\n";
280                     $x->opts = $this->opts;
281                     $x->rootDir = $this->rootDir;
282                     $x->importModuleSQL($dburl);
283                     continue;
284                 }
285             };
286
287             echo "Importing SQL from module $m\n";
288             
289             
290             // if init has been called
291             // look in pgsql.ini
292             if (!empty($this->opts['init'])) {
293                 $this->{$dirmethod}($dburl, $this->rootDir. "/Pman/$m/{$dbtype}.init");
294                 
295             }
296             
297             
298             
299             $fd = $this->rootDir. "/Pman/$m/DataObjects";
300             
301             $this->{$dirmethod}($dburl, $fd);
302             
303             
304             // new -- sql directory..
305             // new style will not support migrate ... they have to go into mysql-migrate.... directories..
306             // new style will not support pg.sql etc.. naming - that's what the direcotries are for..
307             
308             $this->{$dirmethod}($dburl, $this->rootDir. "/Pman/$m/sql");
309             $this->{$dirmethod}($dburl, $this->rootDir. "/Pman/$m/{$dbtype}");
310             
311            
312             
313             if (!empty($this->opts['init']) && file_exists($this->rootDir. "/Pman/$m/{$dbtype}.initdata")) {
314                 if (class_exists('PDO_DataObjects_Introspection')) {
315                     PDO_DataObject_Introspection::$cache = array();
316                 }
317                 HTML_FlexyFramework::get()->generateDataobjectsCache(true);
318                 
319                 $this->{$dirmethod}($dburl, $this->rootDir. "/Pman/$m/{$dbtype}.initdata");
320                 $this->{'fixSequences'. $dbtype}();
321                 
322             }
323               
324             
325         }
326         
327         
328     }
329     
330     
331     
332      
333     /** -------------- code to handle importing a whole directory of files into the database  -------  **/
334     
335     
336     function importpgsqldir($url, $dir, $disable_triggers = false)
337     {
338         $ff = HTML_FlexyFramework::get();
339         
340         require_once 'System.php';
341         $cat = System::which('cat');
342         $psql = System::which('psql');
343         
344          
345         if (!empty($url['pass'])) { 
346             putenv("PGPASSWORD=". $url['pass']);
347         }
348            
349         $psql_cmd = $psql .
350             ' -h ' . $url['host'] .
351             ' -U' . escapeshellarg($url['user']) .
352              ' ' . basename($url['path']);
353         
354         
355         echo $psql_cmd . "\n" ;
356         echo "scan : $dir\n";
357         
358         if (is_file($dir)) {
359             $files = array($dir);
360
361         } else {
362         
363         
364             $files = glob($dir.'/*.sql');
365             uksort($files, 'strcasecmp');
366         }
367         //$lsort = create_function('$a,$b','return strlen($a) > strlen($b) ? 1 : -1;');
368         //usort($files, $lsort);
369         
370         
371         foreach($files as $bfn) {
372
373
374             if (preg_match('/migrate/i', basename($bfn))) { // skip migration scripts at present..
375                 continue;
376             }
377             if (preg_match('#\.[a-z]{2}\.sql#i', basename($bfn))
378                 && !preg_match('#\.pg\.sql#i', basename($bfn))
379             ) { // skip migration scripts at present..
380                 continue;
381             }
382             $fn = false;
383
384             if (!preg_match('/pgsql/', basename($dir) )) {
385                  if ( !preg_match('#\.pg\.sql$#', basename($bfn))) {
386                     $fn = $this->convertToPG($bfn);
387                 }
388             }
389
390             // files ending in .pg.sql are native postgres files.. ## depricated
391
392
393             $cmd = "$psql_cmd  < " . escapeshellarg($fn ? $fn : $bfn) . ' 2>&1' ;
394
395             echo "$bfn:   $cmd ". ($ff->cli ? "\n" : "<BR>\n");
396
397             passthru($cmd);
398
399             if ($fn) {
400                 unlink($fn);
401             }
402         }
403
404               
405              
406         
407     }
408     
409     
410     /**
411      * mysql - does not support conversions.
412      * 
413      *
414      */
415     function importmysqlidir($dburl, $dir) {
416         return $this->importmysqldir($dburl, $dir);
417     }
418     
419     function importmysqldir($dburl, $dir)
420     {
421         
422         $this->fixMysqlInnodb(); /// run once 
423         
424         echo "Import MYSQL :: $dir\n";
425         
426         
427         require_once 'System.php';
428         $cat = System::which('cat');
429         $mysql = System::which('mysql');
430         
431        
432            
433         $mysql_cmd = $mysql .
434             ' -h ' . $dburl['host'] .
435             ' -u' . escapeshellarg($dburl['user']) .
436             (!empty($dburl['pass']) ? ' -p' . escapeshellarg($dburl['pass'])  :  '') .
437             ' ' . basename($dburl['path']);
438         //echo $mysql_cmd . "\n" ;
439         
440         $files = glob($dir.'/*.sql');
441         uksort($files, 'strcasecmp');
442         
443        
444         foreach($files as $fn) {
445                 
446                  
447                 if (preg_match('/migrate/i', basename($fn))) { // skip migration scripts at present..
448                     continue;
449                 }
450                 // .my.sql but not .pg.sql
451                 if (preg_match('#\.[a-z]{2}\.sql#i', basename($fn))
452                     && !preg_match('#\.my\.sql#i', basename($fn))
453                 ) { // skip migration scripts at present..
454                     continue;
455                 }
456                 if (!strlen(trim($fn))) {
457                     continue;
458                 }
459                 
460                 $cmd = "$mysql_cmd -f < " . escapeshellarg($fn) ." 2>&1" ;
461                 
462                 echo basename($dir).'/'. basename($fn) .    '::' .  $cmd. ($this->cli ? "\n" : "<BR>\n");
463                 
464                 
465                 $fp = popen($cmd, "r"); 
466                 while(!feof($fp)) 
467                 { 
468                     // send the current file part to the browser 
469                     $line = trim(fgets($fp, 1024));
470                     if (empty($line)) {
471                         continue;
472                     }
473                     $matches = array();
474                     if (!preg_match('/^ERROR\s+([0-9]+)/', $line, $matches)) {
475                         echo " ---- {$line}\n"; flush();
476                         continue;
477                     }
478                     $continue =0;
479                     switch($matches[1]) {
480                         case 1017: // cause by renaming table -- old one does not exist..
481                         case 1050: // create tables triggers this..
482                         case 1060: //    Duplicate column name
483                         case 1061: // Duplicate key name - triggered by add index.. but could hide error. - unlikely though.
484                         case 1091: // drop index -- name does not exist.. might hide errors..
485                         
486                         case 1146: // drop a index on an unknown table.. - happens rarely...
487                         case 1054: // Unknown column -- triggered by CHANGE COLUMN - but may hide other errrors..
488                             $continue = 1;
489                             break;
490                         
491                     }
492                     if ($continue) {
493                         echo " ---- {$line}\n"; flush();
494                         continue;
495                     }
496                     // real errors...
497                     // 1051: // Unknown table -- normally drop = add iff exists..
498                     echo "File: $fn\n$line\n";
499                     exit;
500                     
501                     
502                 } 
503                 
504             
505                 
506         }
507        
508         
509         
510     }
511     
512     
513     /**
514      * simple regex based convert mysql to pgsql...
515      */
516     function convertToPG($src)
517     {
518         //echo "Convert $src\n";
519                
520         $fn = $this->tempName('sql');
521         
522         $ret = array( ); // pad it a bit.
523         $extra = array("", "" );
524         
525         $tbl = false;
526         foreach(file($src) as $l) {
527             $l = trim($l);
528             
529             if (!strlen($l) || $l[0] == '#') {
530                 continue;
531             }
532             $m = array();
533             if (preg_match('#create\s+table\s+([a-z0-9_]+)#i',  $l, $m)) {
534                 $tbl = $m[1];
535              }
536             if (preg_match('#create\s+table\s+\`([a-z0-9_]+)\`#i',  $l, $m)) {
537                 $tbl = 'shop_' . strtolower($m[1]);
538                 $l = preg_replace('#create\s+table\s+\`([a-z0-9_]+)\`#i', "CREATE TABLE {$tbl}", $l);
539             }
540             if (preg_match('#\`([a-z0-9_]+)\`#i',  $l, $m) && !preg_match('#alter\s+table\s+#i',  $l)) {
541                 $l = preg_replace('#\`([a-z0-9_]+)\`#i', "{$m[1]}_name", $l);
542             }
543             // autoinc
544             if ($tbl && preg_match('#auto_increment#i',  $l, $m)) {
545                 $l = preg_replace('#auto_increment#i', "default nextval('{$tbl}_seq')", $l);
546                 $extra[]  =   "create sequence {$tbl}_seq;";
547               
548             }
549             
550             if (preg_match('#alter\s+table\s+(\`[a-z0-9_]+\`)#i',  $l, $m)){
551                 $l = preg_replace('#alter\s+table\s+(\`[a-z0-9_]+\`)#i', "ALTER TABLE {$tbl}", $l);
552             }
553             
554             // enum value -- use the text instead..
555             
556             if ($tbl && preg_match('#([\w]+)\s+(enum\([\w|\W]+\))#i',  $l, $m)) {
557                 $l = preg_replace('#enum\([\w|\W]+\)#i', "TEXT", $l);
558             }
559             // ignore the alter enum
560             if ($tbl && preg_match('#alter\s+table\s+([\w|\W]+)\s+enum\([\w|\W]+\)#i',  $l, $m)) {
561                 continue;
562             }
563             
564             // UNIQUE KEY .. ignore
565             if ($tbl && preg_match('#UNIQUE KEY#i',  $l, $m)) {
566                 $last = array_pop($ret);
567                 $ret[] = trim($last, ",");
568                 continue;
569             }
570             
571             if ($tbl && preg_match('#RENAME\s+TO#i',  $l, $m)) {
572                 continue;
573             }
574             
575             if ($tbl && preg_match('#change\s+column#i',  $l, $m)) {
576                 continue;
577             }
578             
579             // INDEX lookup ..ignore
580             if ($tbl && preg_match('#INDEX lookup+([\w|\W]+)#i',  $l, $m)) {
581                $last = array_pop($ret);
582                $ret[] = trim($last, ",");
583                continue;
584                
585             }
586             
587             // CREATE INDEX ..ignore
588             if (preg_match('#alter\s+table\s+([a-z0-9_]+)\s+add\s+index\s+#i',  $l, $m)) {
589 //               $l = "CREATE INDEX  {$m[1]}_{$m[2]} ON {$m[1]} {$m[3]}";
590                 continue;
591              }
592              
593             // basic types..
594             $l = preg_replace('#int\([0-9]+\)#i', 'INT', $l);
595             
596             $l = preg_replace('# datetime#i', ' TIMESTAMP WITHOUT TIME ZONE', $l);
597             $l = preg_replace('# blob#i', ' TEXT', $l);
598             $l = preg_replace('# longtext#i', ' TEXT', $l);
599             $l = preg_replace('# tinyint#i', ' INT', $l);
600             
601             $ret[] = $l;
602             
603         }
604         
605         $ret = array_merge($extra,$ret);
606 //        echo implode("\n", $ret); exit;
607         
608         file_put_contents($fn, implode("\n", $ret));
609         
610         return $fn;
611     }
612     
613     
614     function checkOpts($opts)
615     {
616         
617         
618         foreach($opts as $o=>$v) {
619             if (!preg_match('/^json-/', $o) || empty($v)) {
620                 continue;
621             }
622             if (!file_exists($v)) {
623                 die("File does not exist : OPTION --{$o} = {$v} \n");
624             }
625         }
626         
627         $modules = array_reverse($this->modulesList());
628         
629         // move 'project' one to the end...
630         
631         foreach ($modules as $module){
632             $file = $this->rootDir. "/Pman/$module/UpdateDatabase.php";
633             if($module == 'Core' || !file_exists($file)){
634                 continue;
635             }
636             require_once $file;
637             $class = "Pman_{$module}_UpdateDatabase";
638             $x = new $class;
639             if(!method_exists($x, 'checkOpts')){
640                 continue;
641             };
642             $x->checkOpts($opts);
643         }
644                 
645     }
646     static function jsonImportFromArray($opts)
647     {
648         foreach($opts as $o=>$v) {
649             if (!preg_match('/^json-/', $o) || empty($v)) {
650                 continue;
651             }
652             $type = str_replace('_', '-', substr($o,5));
653             
654             $data= json_decode(file_get_contents($v),true);
655             $pg = HTML_FlexyFramework::get()->page;
656             DB_DataObject::factory($type)->importFromArray($pg ,$data,$opts);
657             
658         }
659         
660         
661         
662     }
663     
664     
665     
666     function runUpdateModulesData()
667     {
668         if (class_exists('PDO_DataObjects_Introspection')) {
669             PDO_DataObject_Introspection::$cache = array();
670         }
671         HTML_FlexyFramework::get()->generateDataobjectsCache(true);
672         
673         if(!in_array('Core', $this->disabled)){
674             echo "Running jsonImportFromArray\n";
675             Pman_Core_UpdateDatabase::jsonImportFromArray($this->opts);
676             
677
678             echo "Running updateData on modules\n";
679             // runs core...
680             echo "Core\n";
681             $this->updateData(); 
682         }
683         
684         $modules = array_reverse($this->modulesList());
685         
686         // move 'project' one to the end...
687         
688         foreach ($modules as $module){
689             if(in_array($module, $this->disabled)){
690                 continue;
691             }
692             $file = $this->rootDir. "/Pman/$module/UpdateDatabase.php";
693             if($module == 'Core' || !file_exists($file)){
694                 continue;
695             }
696             
697             require_once $file;
698             $class = "Pman_{$module}_UpdateDatabase";
699             $x = new $class;
700             if(!method_exists($x, 'updateData')){
701                 continue;
702             };
703             echo "$module\n";
704             $x->updateData();
705         }
706         
707     }
708     
709     
710     function updateDataEnums()
711     {
712         HTML_FlexyFramework::get()->generateDataobjectsCache(true);
713
714         $enum = DB_DataObject::Factory('core_enum');
715         //DB_DAtaObject::debugLevel(1);
716         $enum->initEnums(
717             array(
718                 array(
719                     'etype' => '',
720                     'name' => 'COMPTYPE',
721                     'display_name' =>  'Company Types',
722                     'is_system_enum' => 1,
723                     'cn' => array(
724                         array(
725                             'name' => 'OWNER',
726                             'display_name' => 'Owner',
727                             'seqid' => 999, // last...
728                             'is_system_enum' => 1,
729                         )
730                         
731                     )
732                 ),
733                 array(
734                     'etype' => '',
735                     'name' => 'HtmlEditor.font-family',
736                     'display_name' =>  'HTML Editor font families',
737                     'is_system_enum' => 1,
738                     'cn' => array(
739                         array(
740                             'name' => 'Helvetica,Arial,sans-serif',
741                             'display_name' => 'Helvetica',
742                             
743                         ),
744                         
745                         array(
746                             'name' => 'Courier New',
747                             'display_name' => 'Courier',
748                              
749                         ),
750                         array(
751                             'name' => 'Tahoma',
752                             'display_name' => 'Tahoma',
753                             
754                         ),
755                         array(
756                             'name' => 'Times New Roman,serif',
757                             'display_name' => 'Times',
758                            
759                         ),
760                         array(
761                             'name' => 'Verdana',
762                             'display_name' => 'Verdana',
763                             
764                         ),
765                         
766                             
767                         
768                     )
769                 )
770                
771             )
772         ); 
773         
774     }
775     function updateDataGroups()
776     {
777          
778         $groups = DB_DataObject::factory('core_group');
779         $groups->initGroups();
780         
781         $groups->initDatabase($this,array(
782             array(
783                 'name' => 'bcc-email', // group who are bcc'ed on all requests.
784                 'type' => 0, // system
785             ),
786             array(
787                 'name' => 'system-email-from',
788                 'type' => 0, // system
789             ),
790             array(
791                 'name' => 'core-person-signup-bcc',
792                 'type' => 0, // system
793             ),
794         
795
796         ));
797         
798     }
799     
800     function updateDataCompanies()
801     {
802          
803         // fix comptypes enums..
804         $c = DB_DataObject::Factory('core_company');
805         $c->selectAdd();
806         $c->selectAdd('distinct(comptype) as comptype');
807         $c->whereAdd("comptype != ''");
808         
809         $ctb = array();
810         foreach($c->fetchAll('comptype') as $cts) {
811             
812             
813             
814            $ctb[]= array( 'etype'=>'COMPTYPE', 'name' => $cts, 'display_name' => ucfirst(strtolower($cts)));
815         
816         }
817          $c = DB_DataObject::Factory('core_enum');
818          
819         $c->initEnums($ctb);
820         //DB_DataObject::debugLevel(1);
821         // fix comptypeid
822         $c = DB_DataObject::Factory('core_company');
823         $c->query("
824             UPDATE {$c->tableName()} 
825                 SET
826                     comptype_id = (SELECT id FROM core_enum where etype='comptype' and name={$c->tableName()}.comptype LIMIT 1)
827                 WHERE
828                     comptype_id = 0
829                     AND
830                     LENGTH(comptype) > 0
831                   
832                   
833                   ");
834          
835         
836         
837     }
838     
839     
840     function initEmails($templateDir, $emails, $mapping = false)
841     {
842         HTML_FlexyFramework::get()->generateDataobjectsCache(true);
843
844         $pg = HTML_FlexyFramework::get()->page;
845         foreach($emails as $name=>$data) {
846             $cm = DB_DataObject::factory('core_email');
847             $update = $cm->get('name', $name);
848             $old = clone($cm);
849             
850             if (empty($cm->bcc_group_id)) {
851                 if (empty($data['bcc_group'])) {
852                     $this->jerr("missing bcc_group for template $name");
853                 }
854                 $g = DB_DataObject::Factory('core_group')->lookup('name',$data['bcc_group']);
855                 
856                 if (empty($g->id)) {
857                     $this->jerr("bcc_group {$data['bcc_group']} does not exist when importing template $name");
858                 }
859                 
860                 if (!$g->members('email')) {
861                     $this->jerr("bcc_group {$data['bcc_group']} does not have any members");
862                 }
863                 
864                 $cm->bcc_group_id = $g->id;
865             }
866             // initEmails will always have the latest location of the test class - in theory the user should not be changign the value of this...
867             //if (empty($cm->test_class)) {
868                 if (empty($data['test_class'])) {
869                     $this->jerr("missing test_class for template $name");
870                 }
871                 $cm->test_class = $data['test_class'];
872             //}
873             if(isset($cm->to_group_id)) {
874                 print_r('isset');
875             }
876             
877             if (
878                 !empty($data['to_group']) &&
879                 (!isset($cm->to_group_id) || !empty($cm->to_group_id)) 
880             ) {
881                 $gp = DB_DataObject::Factory('core_group')->lookup('name',$data['to_group']);
882                 
883                 if (empty($gp->id)) {
884                     $this->jerr("to_group {$data['to_group']} does not exist when importing template $name");
885                 }
886                 
887                 $cm->to_group_id = $gp->id;
888             }
889             
890             if(
891                 isset($data['active']) && !isset($cm->active)
892             ) {
893                 $cm->active = $data['active'];
894             }
895             
896             require_once $cm->test_class . '.php';
897             
898             $clsname = str_replace('/','_', $cm->test_class);
899             try {
900                 $method = new ReflectionMethod($clsname , 'test_'. $name) ;
901                 $got_it = $method->isStatic();
902             } catch(Exception $e) {
903                 $got_it = false;
904                 
905             }
906             if (!$got_it) {
907                 $this->jerr("template {$name} does not have a test method {$clsname}::test_{$name}");
908             }
909             if ($update) {
910                 $cm->update($old);
911                 echo "email: {$name} - checked\n";
912                 continue; /// we do not import the body content of templates that exist...
913             } else {
914                 
915                 //$cm->insert();
916             }
917             
918             
919     //        $basedir = $this->bootLoader->rootDir . $mail_template_dir;
920             
921             $opts = array(
922                 'update' => 1,
923                 'file' => $templateDir. $name .'.html'
924             );
925             
926             if (!empty($data['master'])) {
927                 $opts['master'] = $templateDir . $master .'.html';
928             }
929             require_once 'Pman/Core/Import/Core_email.php';
930             $x = new Pman_Core_Import_Core_email();
931             
932             $x->updateOrCreateEmail('', $opts, $cm, $mapping);
933             
934             echo "email: {$name} - CREATED\n";
935         }
936     }
937     
938     
939     function updateData()
940     {
941         // fill i18n data..
942         if (class_exists('PDO_DataObjects_Introspection')) {
943             PDO_DataObject_Introspection::$cache = array();
944         }
945         HTML_FlexyFramework::get()->generateDataobjectsCache(true);
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         $this->curl($url);
1197         
1198     }
1199     
1200     function curl($url, $request = array(), $method = 'GET') 
1201     {
1202         if($method == 'GET'){
1203             $request = http_build_query($request);
1204             $url = $url . "?" . $request;  
1205         }
1206         
1207         $ch = curl_init($url);
1208         
1209         if ($method == 'POST') {
1210             
1211             curl_setopt($ch, CURLOPT_POST, 1);
1212             curl_setopt($ch, CURLOPT_POSTFIELDS, $request);
1213             
1214         } else {
1215             
1216             curl_setopt($ch, CURLOPT_HTTPHEADER,
1217                     array("Content-Type: application/x-www-form-urlencoded", "Content-Length: " . strlen($request)));
1218             
1219         }
1220         
1221         curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
1222         
1223         curl_setopt($ch, CURLOPT_HEADER, false);
1224         curl_setopt($ch, CURLOPT_VERBOSE, 0);
1225         curl_setopt($ch, CURLOPT_TIMEOUT, 30);
1226         curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
1227
1228         $response = curl_exec($ch);
1229         
1230         curl_close($ch);
1231         
1232         return $response;
1233     }
1234     
1235     
1236     
1237 }