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