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