3 require_once 'Pman.php';
5 class Pman_Core_NotifySmtpCheck extends Pman
9 $ff = HTML_FlexyFramework::get();
10 if (!empty($ff->cli)) {
19 function get($args, $opts)
21 PEAR::setErrorHandling(PEAR_ERROR_CALLBACK, array($this, 'onPearError'));
23 // $this->checkSystem();
25 $ff = HTML_FlexyFramework::get();
27 if(!empty($ff->Core_Notify)){
28 $x = new Pman_Core_NotifySmtpCheck();
33 $this->disabled = explode(',', $ff->disable);
35 //$this->fixSequencesPgsql();exit;
38 // ask all the modules to verify the opts
40 $this->checkOpts($opts);
42 if (empty($opts['data-only'])) {
45 if (!empty($opts['only-module-sql'])) {
49 $this->runUpdateModulesData();
52 if (!empty($opts['add-company']) && !in_array('Core', $this->disabled)) {
53 // make sure we have a good cache...?
55 DB_DataObject::factory('companies')->initCompanies($this, $opts);
58 $this->runExtensions();
66 * imports SQL files from all DataObjects directories....
68 * except any matching /migrate/
73 // loop through all the modules, and see if they have a importSQL method?
76 $ff = HTML_Flexyframework::get();
78 $dburl = parse_url($ff->DB_DataObject['database']);
80 //$this->{'import' . $url['scheme']}($url);
82 $dbtype = $dburl['scheme'];
83 $dirmethod = 'import' . $dburl['scheme'] . 'dir';
88 $ar = $this->modulesList();
92 if(in_array($m, $this->disabled)){
93 echo "module $m is disabled \n";
97 echo "Importing SQL from module $m\n";
98 if (!empty($this->opts['only-module-sql']) && $m != $this->opts['only-module-sql']) {
103 // check to see if the class has
107 $file = $this->rootDir. "/Pman/$m/UpdateDatabase.php";
108 if($m != 'Core' && file_exists($file)){
111 $class = "Pman_{$m}_UpdateDatabase";
113 if(method_exists($x, 'importModuleSQL')){
114 echo "Importing SQL from module $m using Module::importModuleSQL\n";
115 $x->opts = $this->opts;
116 $x->rootDir = $this->rootDir;
117 $x->importModuleSQL($dburl);
122 echo "Importing SQL from module $m\n";
125 // if init has been called
127 if (!empty($this->opts['init'])) {
128 $this->{$dirmethod}($dburl, $this->rootDir. "/Pman/$m/{$dbtype}.init");
134 $fd = $this->rootDir. "/Pman/$m/DataObjects";
136 $this->{$dirmethod}($dburl, $fd);
139 // new -- sql directory..
140 // new style will not support migrate ... they have to go into mysql-migrate.... directories..
141 // new style will not support pg.sql etc.. naming - that's what the direcotries are for..
143 $this->{$dirmethod}($dburl, $this->rootDir. "/Pman/$m/sql");
144 $this->{$dirmethod}($dburl, $this->rootDir. "/Pman/$m/{$dbtype}");
148 if (!empty($this->opts['init']) && file_exists($this->rootDir. "/Pman/$m/{$dbtype}.initdata")) {
149 HTML_FlexyFramework::get()->generateDataobjectsCache(true);
151 $this->{$dirmethod}($dburl, $this->rootDir. "/Pman/$m/{$dbtype}.initdata");
152 $this->{'fixSequences'. $dbtype}();
164 /** -------------- code to handle importing a whole directory of files into the database ------- **/
167 function importpgsqldir($url, $dir, $disable_triggers = false)
169 $ff = HTML_FlexyFramework::get();
171 require_once 'System.php';
172 $cat = System::which('cat');
173 $psql = System::which('psql');
176 if (!empty($url['pass'])) {
177 putenv("PGPASSWORD=". $url['pass']);
181 ' -h ' . $url['host'] .
182 ' -U' . escapeshellarg($url['user']) .
183 ' ' . basename($url['path']);
186 echo $psql_cmd . "\n" ;
187 echo "scan : $dir\n";
190 $files = array($dir);
195 $files = glob($dir.'/*.sql');
196 uksort($files, 'strcasecmp');
198 //$lsort = create_function('$a,$b','return strlen($a) > strlen($b) ? 1 : -1;');
199 //usort($files, $lsort);
202 foreach($files as $bfn) {
205 if (preg_match('/migrate/i', basename($bfn))) { // skip migration scripts at present..
208 if (preg_match('#\.[a-z]{2}\.sql#i', basename($bfn))
209 && !preg_match('#\.pg\.sql#i', basename($bfn))
210 ) { // skip migration scripts at present..
215 if (!preg_match('/pgsql/', basename($dir) )) {
216 if ( !preg_match('#\.pg\.sql$#', basename($bfn))) {
217 $fn = $this->convertToPG($bfn);
221 // files ending in .pg.sql are native postgres files.. ## depricated
224 $cmd = "$psql_cmd < " . escapeshellarg($fn ? $fn : $bfn) . ' 2>&1' ;
226 echo "$bfn: $cmd ". ($ff->cli ? "\n" : "<BR>\n");
242 * mysql - does not support conversions.
248 function importmysqldir($dburl, $dir)
251 $this->fixMysqlInnodb(); /// run once
253 echo "Import MYSQL :: $dir\n";
256 require_once 'System.php';
257 $cat = System::which('cat');
258 $mysql = System::which('mysql');
262 $mysql_cmd = $mysql .
263 ' -h ' . $dburl['host'] .
264 ' -u' . escapeshellarg($dburl['user']) .
265 (!empty($dburl['pass']) ? ' -p' . escapeshellarg($dburl['pass']) : '') .
266 ' ' . basename($dburl['path']);
267 //echo $mysql_cmd . "\n" ;
269 $files = glob($dir.'/*.sql');
270 uksort($files, 'strcasecmp');
273 foreach($files as $fn) {
276 if (preg_match('/migrate/i', basename($fn))) { // skip migration scripts at present..
279 // .my.sql but not .pg.sql
280 if (preg_match('#\.[a-z]{2}\.sql#i', basename($fn))
281 && !preg_match('#\.my\.sql#i', basename($fn))
282 ) { // skip migration scripts at present..
285 if (!strlen(trim($fn))) {
289 $cmd = "$mysql_cmd -f < " . escapeshellarg($fn) ;
291 echo basename($dir).'/'. basename($fn) . '::' . $cmd. ($this->cli ? "\n" : "<BR>\n");
304 * simple regex based convert mysql to pgsql...
306 function convertToPG($src)
308 //echo "Convert $src\n";
310 $fn = $this->tempName('sql');
312 $ret = array( ); // pad it a bit.
313 $extra = array("", "" );
316 foreach(file($src) as $l) {
319 if (!strlen($l) || $l[0] == '#') {
323 if (preg_match('#create\s+table\s+([a-z0-9_]+)#i', $l, $m)) {
326 if (preg_match('#create\s+table\s+\`([a-z0-9_]+)\`#i', $l, $m)) {
327 $tbl = 'shop_' . strtolower($m[1]);
328 $l = preg_replace('#create\s+table\s+\`([a-z0-9_]+)\`#i', "CREATE TABLE {$tbl}", $l);
330 if (preg_match('#\`([a-z0-9_]+)\`#i', $l, $m) && !preg_match('#alter\s+table\s+#i', $l)) {
331 $l = preg_replace('#\`([a-z0-9_]+)\`#i', "{$m[1]}_name", $l);
334 if ($tbl && preg_match('#auto_increment#i', $l, $m)) {
335 $l = preg_replace('#auto_increment#i', "default nextval('{$tbl}_seq')", $l);
336 $extra[] = "create sequence {$tbl}_seq;";
340 if (preg_match('#alter\s+table\s+(\`[a-z0-9_]+\`)#i', $l, $m)){
341 $l = preg_replace('#alter\s+table\s+(\`[a-z0-9_]+\`)#i', "ALTER TABLE {$tbl}", $l);
344 // enum value -- use the text instead..
346 if ($tbl && preg_match('#([\w]+)\s+(enum\([\w|\W]+\))#i', $l, $m)) {
347 $l = preg_replace('#enum\([\w|\W]+\)#i', "TEXT", $l);
349 // ignore the alter enum
350 if ($tbl && preg_match('#alter\s+table\s+([\w|\W]+)\s+enum\([\w|\W]+\)#i', $l, $m)) {
354 // UNIQUE KEY .. ignore
355 if ($tbl && preg_match('#UNIQUE KEY#i', $l, $m)) {
356 $last = array_pop($ret);
357 $ret[] = trim($last, ",");
361 if ($tbl && preg_match('#RENAME\s+TO#i', $l, $m)) {
365 if ($tbl && preg_match('#change\s+column#i', $l, $m)) {
369 // INDEX lookup ..ignore
370 if ($tbl && preg_match('#INDEX lookup+([\w|\W]+)#i', $l, $m)) {
371 $last = array_pop($ret);
372 $ret[] = trim($last, ",");
377 // CREATE INDEX ..ignore
378 if (preg_match('#alter\s+table\s+([a-z0-9_]+)\s+add\s+index\s+#i', $l, $m)) {
379 // $l = "CREATE INDEX {$m[1]}_{$m[2]} ON {$m[1]} {$m[3]}";
384 $l = preg_replace('#int\([0-9]+\)#i', 'INT', $l);
386 $l = preg_replace('# datetime#i', ' TIMESTAMP WITHOUT TIME ZONE', $l);
387 $l = preg_replace('# blob#i', ' TEXT', $l);
388 $l = preg_replace('# longtext#i', ' TEXT', $l);
389 $l = preg_replace('# tinyint#i', ' INT', $l);
395 $ret = array_merge($extra,$ret);
396 // echo implode("\n", $ret); exit;
398 file_put_contents($fn, implode("\n", $ret));
404 function checkOpts($opts)
408 foreach($opts as $o=>$v) {
409 if (!preg_match('/^json-/', $o) || empty($v)) {
412 if (!file_exists($v)) {
413 die("File does not exist : OPTION --{$o} = {$v} \n");
417 $modules = array_reverse($this->modulesList());
419 // move 'project' one to the end...
421 foreach ($modules as $module){
422 $file = $this->rootDir. "/Pman/$module/UpdateDatabase.php";
423 if($module == 'Core' || !file_exists($file)){
427 $class = "Pman_{$module}_UpdateDatabase";
429 if(!method_exists($x, 'checkOpts')){
432 $x->checkOpts($opts);
436 static function jsonImportFromArray($opts)
438 foreach($opts as $o=>$v) {
439 if (!preg_match('/^json-/', $o) || empty($v)) {
442 $type = str_replace('_', '-', substr($o,5));
444 $data= json_decode(file_get_contents($v),true);
445 $pg = HTML_FlexyFramework::get()->page;
446 DB_DataObject::factory($type)->importFromArray($pg ,$data,$opts);
456 function runUpdateModulesData()
458 HTML_FlexyFramework::get()->generateDataobjectsCache(true);
460 if(!in_array('Core', $this->disabled)){
461 echo "Running jsonImportFromArray\n";
462 Pman_Core_UpdateDatabase::jsonImportFromArray($this->opts);
465 echo "Running updateData on modules\n";
471 $modules = array_reverse($this->modulesList());
473 // move 'project' one to the end...
475 foreach ($modules as $module){
476 if(in_array($module, $this->disabled)){
479 $file = $this->rootDir. "/Pman/$module/UpdateDatabase.php";
480 if($module == 'Core' || !file_exists($file)){
485 $class = "Pman_{$module}_UpdateDatabase";
487 if(!method_exists($x, 'updateData')){
497 function updateDataEnums()
500 $enum = DB_DataObject::Factory('core_enum');
501 //DB_DAtaObject::debugLevel(1);
506 'name' => 'COMPTYPE',
507 'display_name' => 'Company Types',
508 'is_system_enum' => 1,
512 'display_name' => 'Owner',
513 'seqid' => 999, // last...
514 'is_system_enum' => 1,
521 'name' => 'HtmlEditor.font-family',
522 'display_name' => 'HTML Editor font families',
523 'is_system_enum' => 1,
526 'name' => 'Helvetica,Arial,sans-serif',
527 'display_name' => 'Helvetica',
532 'name' => 'Courier New',
533 'display_name' => 'Courier',
538 'display_name' => 'Tahoma',
542 'name' => 'Times New Roman,serif',
543 'display_name' => 'Times',
548 'display_name' => 'Verdana',
560 function updateDataGroups()
563 $groups = DB_DataObject::factory('groups');
564 $groups->initGroups();
566 $groups->initDatabase($this,array(
568 'name' => 'bcc-email', // group who are bcc'ed on all requests.
569 'type' => 0, // system
572 'name' => 'system-email-from',
573 'type' => 0, // system
576 'name' => 'core-person-signup-bcc',
577 'type' => 0, // system
583 function updateDataCompanies()
586 // fix comptypes enums..
587 $c = DB_DataObject::Factory('Companies');
589 $c->selectAdd('distinct(comptype) as comptype');
590 $c->whereAdd("comptype != ''");
593 foreach($c->fetchAll('comptype') as $cts) {
597 $ctb[]= array( 'etype'=>'COMPTYPE', 'name' => $cts, 'display_name' => ucfirst(strtolower($cts)));
600 $c = DB_DataObject::Factory('core_enum');
603 //DB_DataObject::debugLevel(1);
605 $c = DB_DataObject::Factory('Companies');
609 comptype_id = (SELECT id FROM core_enum where etype='comptype' and name=Companies.comptype LIMIT 1)
623 function initEmails($templateDir, $emails)
626 $pg = HTML_FlexyFramework::get()->page;
627 foreach($emails as $name=>$data) {
628 $cm = DB_DataObject::factory('core_email');
629 $update = $cm->get('name', $name);
632 if (empty($cm->bcc_group)) {
633 if (empty($data['bcc_group'])) {
634 $this->jerr("missing bcc_group for template $name");
636 $g = DB_DataObject::Factory('Groups')->lookup('name',$data['bcc_group']);
639 $this->jerr("bcc_group {$data['bcc_group']} does not exist when importing template $name");
641 if (!$g->members('email')) {
642 $this->jerr("bcc_group {$data['bcc_group']} does not have any members");
646 $cm->bcc_group = $g->id;
648 if (empty($cm->test_class)) {
649 if (empty($data['test_class'])) {
650 $this->jerr("missing test_class for template $name");
652 $cm->test_class = $data['test_class'];
654 require_once $cm->test_class . '.php';
656 $clsname = str_replace('/','_', $cm->test_class);
658 $method = new ReflectionMethod($clsname , 'test_'. $name) ;
659 $got_it = $method->isStatic();
660 } catch(Exception $e) {
665 $this->jerr("template {$name} does not have a test method {$clsname}::test_{$name}");
669 echo "email: {$name} - checked\n";
670 continue; /// we do not import the body content of templates that exist...
676 // $basedir = $this->bootLoader->rootDir . $mail_template_dir;
680 'file' => $templateDir. $name .'.html'
683 if (!empty($data['master'])) {
684 $opts['master'] = $templateDir . $master .'.html';
686 require_once 'Pman/Core/Import/Core_email.php';
687 $x = new Pman_Core_Import_Core_email();
690 echo "email: {$name} - CREATED\n";
695 function updateData()
698 HTML_FlexyFramework::get()->generateDataobjectsCache(true);
699 $this->updateDataEnums();
700 $this->updateDataGroups();
701 $this->updateDataCompanies();
703 $c = DB_DataObject::Factory('I18n');
711 function fixMysqlInnodb()
714 static $done_check = false;
718 // innodb in single files is far more efficient that MYD or one big innodb file.
719 // first check if database is using this format.
720 $db = DB_DataObject::factory('core_enum');
721 $db->query("show variables like 'innodb_file_per_table'");
723 if ($db->Value == 'OFF') {
724 die("Error: set innodb_file_per_table = 1 in my.cnf\n\n");
738 /** ------------- schema fixing ... there is an issue with data imported having the wrong sequence names... --- */
740 function fixSequencesMysql()
745 function fixSequencesPgsql()
749 //DB_DataObject::debugLevel(1);
750 $cs = DB_DataObject::factory('core_enum');
754 CASE WHEN strpos(seq_name, '.') > 0 THEN
757 quote_ident(min(schema_name)) ||'.'|| quote_ident(min(seq_name))
760 ||' OWNED BY '|| quote_ident(min(schema_name)) || '.' ||
761 quote_ident(min(table_name)) ||'.'|| quote_ident(min(column_name)) ||';' as cmd
765 n.nspname AS schema_name,
766 c.relname AS table_name,
767 a.attname AS column_name,
768 regexp_replace(regexp_replace(d.adsrc, E'nextval\\\\(+[''\\\"]*', ''),E'[''\\\"]*::.*\$','') AS seq_name
770 JOIN pg_attribute a ON (c.oid=a.attrelid)
771 JOIN pg_attrdef d ON (a.attrelid=d.adrelid AND a.attnum=d.adnum)
772 JOIN pg_namespace n ON (c.relnamespace=n.oid)
773 WHERE has_schema_privilege(n.oid,'USAGE')
774 AND n.nspname NOT LIKE 'pg!_%' escape '!'
775 AND has_table_privilege(c.oid,'SELECT')
776 AND (NOT a.attisdropped)
777 AND d.adsrc ~ '^nextval'
781 CASE WHEN strpos(seq_name, '.') > 0 THEN
782 substring(seq_name, 1,strpos(seq_name,'.')-1)
787 GROUP BY seq_name HAVING count(*)=1
790 while ($cs->fetch()) {
793 foreach($cmds as $cmd) {
794 $cs = DB_DataObject::factory('core_enum');
798 $cs = DB_DataObject::factory('core_enum');
800 SELECT 'SELECT SETVAL(' ||
801 quote_literal(quote_ident(nspname) || '.' || quote_ident(S.relname)) ||
802 ', MAX(' || quote_ident(C.attname)|| ')::integer ) FROM ' || nspname || '.' || quote_ident(T.relname)|| ';' as cmd
808 WHERE S.relkind = 'S'
810 AND D.refobjid = T.oid
811 AND D.refobjid = C.attrelid
812 AND D.refobjsubid = C.attnum
813 AND NS.oid = T.relnamespace
817 while ($cs->fetch()) {
820 foreach($cmds as $cmd) {
821 $cs = DB_DataObject::factory('core_enum');
828 var $extensions = array(
833 function runExtensions()
836 $ff = HTML_Flexyframework::get();
838 $dburl = parse_url($ff->DB_DataObject['database']);
840 $dbtype = $dburl['scheme'];
842 foreach($this->extensions as $ext) {
844 $scls = ucfirst($dbtype). $ext;
845 $cls = __CLASS__ . '_'. $scls;
846 $fn = implode('/',explode('_', $cls)).'.php';
847 if (!file_exists(__DIR__.'/UpdateDatabase/'. $scls .'.php')) {
858 function checkSystem()
860 // most of these are from File_Convert...
862 // these are required - and have simple dependancies.
863 require_once 'System.php';
869 'rsvg-convert', //librsvg2-bin
875 // these are prefered - but may have complicated depenacies
880 'html2text', // not availabe in debian squeeze
881 'pdftocairo', //poppler-utils - not available in debian squeeze.
891 foreach($req as $r) {
892 if (!System::which($r)) {
898 $this->jerr("Missing these programs - need installing\n" . implode("\n",$res));
900 foreach($pref as $r) {
901 if (!System::which($r)) {
907 echo "WARNING: Missing these programs - they may need installing\n". implode("\n",$res);