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