sync
[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' : $dbdir;
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                 $cm->test_class = $data['test_class'];
874             //}
875             if(isset($cm->to_group_id)) {
876                 print_r('isset');
877             }
878             
879             if (
880                 !empty($data['to_group']) &&
881                 (!isset($cm->to_group_id) || !empty($cm->to_group_id)) 
882             ) {
883                 $gp = DB_DataObject::Factory('core_group')->lookup('name',$data['to_group']);
884                 
885                 if (empty($gp->id)) {
886                     $this->jerr("to_group {$data['to_group']} does not exist when importing template $name");
887                 }
888                 
889                 $cm->to_group_id = $gp->id;
890             }
891             
892             if(
893                 isset($data['active']) && !isset($cm->active)
894             ) {
895                 $cm->active = $data['active'];
896             }
897             
898             require_once $cm->test_class . '.php';
899             
900             $clsname = str_replace('/','_', $cm->test_class);
901             try {
902                 $method = new ReflectionMethod($clsname , 'test_'. $name) ;
903                 $got_it = $method->isStatic();
904             } catch(Exception $e) {
905                 $got_it = false;
906                 
907             }
908             if (!$got_it) {
909                 $this->jerr("template {$name} does not have a test method {$clsname}::test_{$name}");
910             }
911             if ($update) {
912                 $cm->update($old);
913                 echo "email: {$name} - checked\n";
914                 continue; /// we do not import the body content of templates that exist...
915             } else {
916                 
917                 //$cm->insert();
918             }
919             
920             
921     //        $basedir = $this->bootLoader->rootDir . $mail_template_dir;
922             
923             $opts = array(
924                 'update' => 1,
925                 'file' => $templateDir. $name .'.html'
926             );
927             
928             if (!empty($data['master'])) {
929                 $opts['master'] = $templateDir . $master .'.html';
930             }
931             require_once 'Pman/Core/Import/Core_email.php';
932             $x = new Pman_Core_Import_Core_email();
933             
934             $x->updateOrCreateEmail('', $opts, $cm, $mapping);
935             
936             echo "email: {$name} - CREATED\n";
937         }
938     }
939     
940     
941     function updateData()
942     {
943         // fill i18n data..
944         if (class_exists('PDO_DataObjects_Introspection')) {
945             PDO_DataObject_Introspection::$cache = array();
946         }
947         HTML_FlexyFramework::get()->generateDataobjectsCache(true);
948         
949          
950         $this->updateDataEnums();
951         $this->updateDataGroups();
952         $this->updateDataCompanies();
953         
954         $c = DB_DataObject::Factory('I18n');
955         $c->buildDB();
956          
957        
958         
959         
960     }
961     
962     function fixMysqlInnodb()
963     {
964         
965         static $done_check = false;
966         if ($done_check) {
967             return;
968         }
969         
970         
971         if (!empty($this->opts['skip-mysql-checks'])) {
972             return;
973         }
974         // innodb in single files is far more efficient that MYD or one big innodb file.
975         // first check if database is using this format.
976         $db = DB_DataObject::factory('core_enum');
977         $db->query("show variables like 'innodb_file_per_table'");
978         $db->fetch();
979         if ($db->Value == 'OFF') {
980             die("Error: set innodb_file_per_table = 1 in my.cnf (or run with --skip-mysql-checks\n\n");
981         }
982         
983         $db = DB_DataObject::factory('core_enum');
984         $db->query("select version() as version");
985         $db->fetch();
986         
987         if (version_compare($db->version, '5.7', '>=' )) {
988                 
989             $db = DB_DataObject::factory('core_enum');
990             $db->query("show variables like 'sql_mode'");
991             $db->fetch();
992             
993             $modes = explode(",", $db->Value);
994             
995             // these are 'new' problems with mysql.
996             if(
997                     in_array('NO_ZERO_IN_DATE', $modes) ||
998                     in_array('NO_ZERO_DATE', $modes) ||
999                     in_array('STRICT_TRANS_TABLES', $modes) || 
1000                     !in_array('ALLOW_INVALID_DATES', $modes)
1001             ){
1002                 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");
1003             }
1004         }
1005         
1006         $done_check = true;;
1007
1008  
1009         
1010         
1011         
1012         
1013         
1014     }
1015     
1016     
1017     /** ------------- schema fixing ... there is an issue with data imported having the wrong sequence names... --- */
1018     
1019     function fixSequencesMysql()
1020     {
1021         // not required...
1022     }
1023     
1024     function fixSequencesPgsql()
1025     {
1026      
1027      
1028         //DB_DataObject::debugLevel(1);
1029         $cs = DB_DataObject::factory('core_enum');
1030         $cs->query("
1031          SELECT
1032                     'ALTER SEQUENCE '||
1033                     CASE WHEN strpos(seq_name, '.') > 0 THEN
1034                         min(seq_name)
1035                     ELSE 
1036                         quote_ident(min(schema_name)) ||'.'|| quote_ident(min(seq_name))
1037                     END 
1038                     
1039                     ||' OWNED BY '|| quote_ident(min(schema_name)) || '.' ||
1040                     quote_ident(min(table_name)) ||'.'|| quote_ident(min(column_name)) ||';' as cmd
1041              FROM (
1042                       
1043                        SELECT 
1044                      n.nspname AS schema_name,
1045                      c.relname AS table_name,
1046                      a.attname AS column_name, 
1047                      regexp_replace(regexp_replace(d.adsrc, E'nextval\\\\(+[''\\\"]*', ''),E'[''\\\"]*::.*\$','') AS seq_name 
1048                  FROM pg_class c 
1049                  JOIN pg_attribute a ON (c.oid=a.attrelid) 
1050                  JOIN pg_attrdef d ON (a.attrelid=d.adrelid AND a.attnum=d.adnum) 
1051                  JOIN pg_namespace n ON (c.relnamespace=n.oid)
1052                  WHERE has_schema_privilege(n.oid,'USAGE')
1053                    AND n.nspname NOT LIKE 'pg!_%' escape '!'
1054                    AND has_table_privilege(c.oid,'SELECT')
1055                    AND (NOT a.attisdropped)
1056                    AND d.adsrc ~ '^nextval'
1057               
1058              ) seq
1059              WHERE
1060                  CASE WHEN strpos(seq_name, '.') > 0 THEN
1061                      substring(seq_name, 1,strpos(seq_name,'.')-1)
1062                 ELSE
1063                     schema_name
1064                 END = schema_name
1065              
1066              GROUP BY seq_name HAVING count(*)=1
1067              ");
1068         $cmds = array();
1069         while ($cs->fetch()) {
1070             $cmds[] = $cs->cmd;
1071         }
1072         foreach($cmds as $cmd) {
1073             $cs = DB_DataObject::factory('core_enum');
1074             echo "$cmd\n";
1075             $cs->query($cmd);
1076         }
1077         $cs = DB_DataObject::factory('core_enum');
1078          $cs->query("
1079                SELECT  'SELECT SETVAL(' ||
1080                          quote_literal(quote_ident(nspname) || '.' || quote_ident(S.relname)) ||
1081                         ', MAX(' || quote_ident(C.attname)|| ')::integer )  FROM ' || nspname || '.' || quote_ident(T.relname)|| ';' as cmd 
1082                 FROM pg_class AS S,
1083                     pg_depend AS D,
1084                     pg_class AS T,
1085                     pg_attribute AS C,
1086                     pg_namespace AS NS
1087                 WHERE S.relkind = 'S'
1088                     AND S.oid = D.objid
1089                     AND D.refobjid = T.oid
1090                     AND D.refobjid = C.attrelid
1091                     AND D.refobjsubid = C.attnum
1092                     AND NS.oid = T.relnamespace
1093                 ORDER BY S.relname   
1094         ");
1095          $cmds = array();
1096         while ($cs->fetch()) {
1097             $cmds[] = $cs->cmd;
1098         }
1099         foreach($cmds as $cmd) {
1100             $cs = DB_DataObject::factory('core_enum');
1101             echo "$cmd\n";
1102             $cs->query($cmd);
1103         }
1104        
1105     }
1106     
1107     var $extensions = array(
1108         'EngineCharset',
1109         'Links',
1110     );
1111     
1112     function runExtensions()
1113     {
1114         
1115         $ff = HTML_Flexyframework::get();
1116         
1117         $dburl = parse_url($ff->database);
1118         
1119         $dbtype = $dburl['scheme'];
1120        
1121         foreach($this->extensions as $ext) {
1122        
1123             $scls = ucfirst($dbtype). $ext;
1124             $cls = __CLASS__ . '_'. $scls;
1125             $fn = implode('/',explode('_', $cls)).'.php';
1126             if (!file_exists(__DIR__.'/UpdateDatabase/'. $scls .'.php')) {
1127                 return;
1128             }
1129             require_once $fn;
1130             $c = new $cls();
1131             
1132         }
1133         
1134     }
1135     
1136     
1137     function checkSystem($req = false, $pref = false)
1138     {
1139         // most of these are from File_Convert...
1140         
1141         // these are required - and have simple dependancies.
1142         require_once 'System.php';
1143         $req = $req !== false ? $req : array( 
1144             'convert',
1145             'grep',
1146             'pdfinfo',
1147             'pdftoppm',
1148             'rsvg-convert',  //librsvg2-bin
1149             'strings',
1150             'oathtool'
1151         );
1152          
1153          
1154          
1155         // these are prefered - but may have complicated depenacies
1156         $pref = $pref !== false ? $pref :  array(
1157             'abiword',
1158             'faad',
1159             'ffmpeg',
1160             'html2text', // not availabe in debian squeeze
1161             'pdftocairo',  //poppler-utils - not available in debian squeeze.
1162
1163             'lame',
1164             'ssconvert',
1165             'unoconv',
1166             'wkhtmltopdf',
1167             'xvfb-run',
1168         );
1169         $res = array();
1170         $fail = false;
1171         foreach($req as $r) {
1172             if (!System::which($r)) {
1173                 $res[] = $r;
1174             }
1175             $fail = true;
1176         }
1177         if ($res) {
1178             die("Missing these programs - need installing\n" . implode("\n",$res). "\n");
1179         }
1180         foreach($pref as $r) {
1181             if (!System::which($r)) {
1182                 $res[] = $r;
1183             }
1184             $fail = true;
1185         }
1186         if ($res) {
1187             echo "WARNING: Missing these programs - they may need installing\n". implode("\n",$res);
1188             sleep(5);
1189         }
1190         
1191         
1192     }
1193     
1194     function clearApacheDataobjectsCache()
1195     {
1196         echo "Clearing Database Cache\n";
1197         // this needs to clear it's own cache along with remote one..
1198   
1199         
1200         $response = $this->curl("http://localhost{$this->local_base_url}/Core/RefreshDatabaseCache");
1201         
1202         $json = json_decode($response, true);
1203         
1204         if(empty($json['data']) || $json['data'] != 'DONE'){
1205             echo $response. "\n";
1206             echo "Clear DataObjects Cache failed\n";
1207             exit;
1208         }
1209         
1210     }
1211     
1212     
1213     function clearApacheAssetCache()
1214     {
1215         echo "Clearing Asset Cache\n";
1216         $response = $this->curl(
1217             "http://localhost{$this->local_base_url}/Core/Asset",
1218             array( '_clear_cache' => 1 ,'returnHTML' => 'NO' ),
1219             'POST'
1220         );
1221         $json = json_decode($response, true);
1222         
1223         if(empty($json['success']) || !$json['success']) {
1224             echo $response. "\n";
1225             echo "CURL Clear Asset cache failed\n";
1226             exit;
1227         }
1228         
1229     }
1230     
1231     
1232     function curl($url, $request = array(), $method = 'GET') 
1233     {
1234         if($method == 'GET'){
1235             $request = http_build_query($request);
1236             $url = $url . "?" . $request;  
1237         }
1238         
1239         $ch = curl_init($url);
1240         
1241         if ($method == 'POST') {
1242             
1243             curl_setopt($ch, CURLOPT_POST, 1);
1244             curl_setopt($ch, CURLOPT_POSTFIELDS, $request);
1245             
1246         } else {
1247             curl_setopt($ch, CURLOPT_HTTPHEADER,
1248                     array("Content-Type: application/x-www-form-urlencoded", "Content-Length: " . strlen($request)));
1249             
1250         }
1251         
1252         curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
1253         
1254         curl_setopt($ch, CURLOPT_HEADER, false);
1255         curl_setopt($ch, CURLOPT_VERBOSE, 0);
1256         curl_setopt($ch, CURLOPT_TIMEOUT, 30);
1257         curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
1258
1259         $response = curl_exec($ch);
1260         
1261         curl_close($ch);
1262         
1263         return $response;
1264     }
1265     
1266     static function verifyExtensions($extensions)
1267     {
1268         $error = array();
1269         
1270         foreach ($extensions as $e){
1271             
1272             if(extension_loaded($e)) {
1273                 continue;
1274             }
1275             
1276             $error[] = "Error: Please install php extension: {$e}";
1277         }
1278         
1279         if(empty($error)){
1280            return true; 
1281         }
1282         $ff = HTML_FLexyFramework::get();
1283         
1284         $ff->page->jerr(implode('\n', $error));
1285     }
1286     
1287 }