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