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