5 * This applies database files from
6 * a) OLD - {MODULE}/DataObjects/XXXX.{dbtype}.sql
8 * b) NEW - {MODULE}/sql/XXX.sql (SHARED or translable)
9 * and {MODULE}/{dbtype}/XXX.sql (SHARED or translable)
14 require_once 'Pman.php';
15 class Pman_Core_UpdateDatabase extends Pman
18 static $cli_desc = "Update SQL - Beta (it will run updateData of all modules)";
20 static $cli_opts = array(
23 'desc' => 'prefix for the password (eg. fred > xxx4fred - prefix is xxx4)',
30 'desc' => 'only run the updateData - do not run import the tables and procedures.',
37 'add-company' => array(
38 'desc' => 'add a company name of the company',
44 'add-company-with-type' => array(
45 'desc' => 'the type of company (default OWNER)',
52 'desc' => 'Initialize the database (pg only supported)',
58 'only-module-sql' => array(
59 'desc' => 'Only run sql import on this modules - eg. Core',
64 'procedures-only' => array(
65 'desc' => 'Only import procedures (not supported by most modules yet) - ignores sql directory',
71 'json-person' => array(
72 'desc' => 'Person JSON file',
80 static function cli_opts()
83 $ret = self::$cli_opts;
84 $ff = HTML_FlexyFramework::get();
86 $mods = $a->modulesList();
87 foreach($mods as $m) {
89 $fd = $ff->rootDir. "/Pman/$m/UpdateDatabase.php";
90 if (!file_exists($fd)) {
96 $cls = new ReflectionClass('Pman_'. $m . '_UpdateDatabase');
98 $ret = array_merge($ret, $cls->getStaticPropertyValue('cli_opts'));
107 var $disabled = array();
114 $ff = HTML_FlexyFramework::get();
115 if (!empty($ff->cli)) {
120 parent::getAuth(); // load company!
121 $au = $this->getAuthUser();
122 if (!$au || $au->company()->comptype != 'OWNER') {
123 $this->jerr("Not authenticated", array('authFailure' => true));
125 $this->authUser = $au;
129 function get($args, $opts=array())
131 PEAR::setErrorHandling(PEAR_ERROR_CALLBACK, array($this, 'onPearError'));
133 $this->checkSystem();
135 if (class_exists('PDO_DataObjects_Introspection')) {
136 PDO_DataObject_Introspection::$cache = array();
138 HTML_FlexyFramework::get()->generateDataobjectsCache(true);
140 $ff = HTML_FlexyFramework::get();
142 if(!empty($ff->Core_Notify)){
143 // require_once 'Pman/Core/NotifySmtpCheck.php';
144 // $x = new Pman_Core_NotifySmtpCheck();
148 $this->disabled = explode(',', $ff->disable);
150 //$this->fixSequencesPgsql();exit;
153 // ask all the modules to verify the opts
155 $this->checkOpts($opts);
158 // do this first, so the innodb change + utf8 fixes column max sizes
160 // this will trigger errors about freetext indexes - we will have to remove them manually.?
161 // 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..)
163 $this->runExtensions();
166 if (empty($opts['data-only'])) {
169 if (!empty($opts['only-module-sql'])) {
173 $this->runUpdateModulesData();
176 if (!empty($opts['add-company']) && !in_array('Core', $this->disabled)) {
177 // make sure we have a good cache...?
179 DB_DataObject::factory('core_company')->initCompanies($this, $opts);
182 $this->runExtensions();
190 * imports SQL files from all DataObjects directories....
192 * except any matching /migrate/
197 // loop through all the modules, and see if they have a importSQL method?
200 $ff = HTML_Flexyframework::get();
202 $dburl = parse_url($ff->database); // used to be DB_DataObject['database'] - but not portable to PDO
204 //$this->{'import' . $url['scheme']}($url);
206 $dbtype = $dburl['scheme'];
209 $dirmethod = 'import' . $dburl['scheme'] . 'dir';
214 $ar = $this->modulesList();
219 if(in_array($m, $this->disabled)){
220 echo "module $m is disabled \n";
224 echo "Importing SQL from module $m\n";
225 if (!empty($this->opts['only-module-sql']) && $m != $this->opts['only-module-sql']) {
230 // check to see if the class has
234 $file = $this->rootDir. "/Pman/$m/UpdateDatabase.php";
235 if($m != 'Core' && file_exists($file)){
238 $class = "Pman_{$m}_UpdateDatabase";
240 if(method_exists($x, 'importModuleSQL')){
241 echo "Importing SQL from module $m using Module::importModuleSQL\n";
242 $x->opts = $this->opts;
243 $x->rootDir = $this->rootDir;
244 $x->importModuleSQL($dburl);
249 echo "Importing SQL from module $m\n";
252 // if init has been called
254 if (!empty($this->opts['init'])) {
255 $this->{$dirmethod}($dburl, $this->rootDir. "/Pman/$m/{$dbtype}.init");
261 $fd = $this->rootDir. "/Pman/$m/DataObjects";
263 $this->{$dirmethod}($dburl, $fd);
266 // new -- sql directory..
267 // new style will not support migrate ... they have to go into mysql-migrate.... directories..
268 // new style will not support pg.sql etc.. naming - that's what the direcotries are for..
270 $this->{$dirmethod}($dburl, $this->rootDir. "/Pman/$m/sql");
271 $this->{$dirmethod}($dburl, $this->rootDir. "/Pman/$m/{$dbtype}");
275 if (!empty($this->opts['init']) && file_exists($this->rootDir. "/Pman/$m/{$dbtype}.initdata")) {
276 if (class_exists('PDO_DataObjects_Introspection')) {
277 PDO_DataObject_Introspection::$cache = array();
279 HTML_FlexyFramework::get()->generateDataobjectsCache(true);
281 $this->{$dirmethod}($dburl, $this->rootDir. "/Pman/$m/{$dbtype}.initdata");
282 $this->{'fixSequences'. $dbtype}();
295 /** -------------- code to handle importing a whole directory of files into the database ------- **/
298 function importpgsqldir($url, $dir, $disable_triggers = false)
300 $ff = HTML_FlexyFramework::get();
302 require_once 'System.php';
303 $cat = System::which('cat');
304 $psql = System::which('psql');
307 if (!empty($url['pass'])) {
308 putenv("PGPASSWORD=". $url['pass']);
312 ' -h ' . $url['host'] .
313 ' -U' . escapeshellarg($url['user']) .
314 ' ' . basename($url['path']);
317 echo $psql_cmd . "\n" ;
318 echo "scan : $dir\n";
321 $files = array($dir);
326 $files = glob($dir.'/*.sql');
327 uksort($files, 'strcasecmp');
329 //$lsort = create_function('$a,$b','return strlen($a) > strlen($b) ? 1 : -1;');
330 //usort($files, $lsort);
333 foreach($files as $bfn) {
336 if (preg_match('/migrate/i', basename($bfn))) { // skip migration scripts at present..
339 if (preg_match('#\.[a-z]{2}\.sql#i', basename($bfn))
340 && !preg_match('#\.pg\.sql#i', basename($bfn))
341 ) { // skip migration scripts at present..
346 if (!preg_match('/pgsql/', basename($dir) )) {
347 if ( !preg_match('#\.pg\.sql$#', basename($bfn))) {
348 $fn = $this->convertToPG($bfn);
352 // files ending in .pg.sql are native postgres files.. ## depricated
355 $cmd = "$psql_cmd < " . escapeshellarg($fn ? $fn : $bfn) . ' 2>&1' ;
357 echo "$bfn: $cmd ". ($ff->cli ? "\n" : "<BR>\n");
373 * mysql - does not support conversions.
377 function importmysqlidir($dburl, $dir) {
378 return $this->importmysqldir($dburl, $dir);
381 function importmysqldir($dburl, $dir)
384 $this->fixMysqlInnodb(); /// run once
386 echo "Import MYSQL :: $dir\n";
389 require_once 'System.php';
390 $cat = System::which('cat');
391 $mysql = System::which('mysql');
395 $mysql_cmd = $mysql .
396 ' -h ' . $dburl['host'] .
397 ' -u' . escapeshellarg($dburl['user']) .
398 (!empty($dburl['pass']) ? ' -p' . escapeshellarg($dburl['pass']) : '') .
399 ' ' . basename($dburl['path']);
400 //echo $mysql_cmd . "\n" ;
402 $files = glob($dir.'/*.sql');
403 uksort($files, 'strcasecmp');
406 foreach($files as $fn) {
409 if (preg_match('/migrate/i', basename($fn))) { // skip migration scripts at present..
412 // .my.sql but not .pg.sql
413 if (preg_match('#\.[a-z]{2}\.sql#i', basename($fn))
414 && !preg_match('#\.my\.sql#i', basename($fn))
415 ) { // skip migration scripts at present..
418 if (!strlen(trim($fn))) {
422 $cmd = "$mysql_cmd -f < " . escapeshellarg($fn) ." 2>&1" ;
424 echo basename($dir).'/'. basename($fn) . '::' . $cmd. ($this->cli ? "\n" : "<BR>\n");
427 $fp = popen($cmd, "r");
430 // send the current file part to the browser
431 $line = trim(fgets($fp, 1024));
436 if (!preg_match('/^ERROR\s+([0-9]+)/', $line, $matches)) {
437 echo " ---- {$line}\n"; flush();
441 switch($matches[1]) {
442 case 1017: // cause by renaming table -- old one does not exist..
443 case 1050: // create tables triggers this..
444 case 1060: // Duplicate column name
445 case 1061: // Duplicate key name - triggered by add index.. but could hide error. - unlikely though.
446 case 1091: // drop index -- name does not exist.. might hide errors..
448 case 1146: // drop a index on an unknown table.. - happens rarely...
449 case 1054: // Unknown column -- triggered by CHANGE COLUMN - but may hide other errrors..
455 echo " ---- {$line}\n"; flush();
459 // 1051: // Unknown table -- normally drop = add iff exists..
460 echo "File: $fn\n$line\n";
476 * simple regex based convert mysql to pgsql...
478 function convertToPG($src)
480 //echo "Convert $src\n";
482 $fn = $this->tempName('sql');
484 $ret = array( ); // pad it a bit.
485 $extra = array("", "" );
488 foreach(file($src) as $l) {
491 if (!strlen($l) || $l[0] == '#') {
495 if (preg_match('#create\s+table\s+([a-z0-9_]+)#i', $l, $m)) {
498 if (preg_match('#create\s+table\s+\`([a-z0-9_]+)\`#i', $l, $m)) {
499 $tbl = 'shop_' . strtolower($m[1]);
500 $l = preg_replace('#create\s+table\s+\`([a-z0-9_]+)\`#i', "CREATE TABLE {$tbl}", $l);
502 if (preg_match('#\`([a-z0-9_]+)\`#i', $l, $m) && !preg_match('#alter\s+table\s+#i', $l)) {
503 $l = preg_replace('#\`([a-z0-9_]+)\`#i', "{$m[1]}_name", $l);
506 if ($tbl && preg_match('#auto_increment#i', $l, $m)) {
507 $l = preg_replace('#auto_increment#i', "default nextval('{$tbl}_seq')", $l);
508 $extra[] = "create sequence {$tbl}_seq;";
512 if (preg_match('#alter\s+table\s+(\`[a-z0-9_]+\`)#i', $l, $m)){
513 $l = preg_replace('#alter\s+table\s+(\`[a-z0-9_]+\`)#i', "ALTER TABLE {$tbl}", $l);
516 // enum value -- use the text instead..
518 if ($tbl && preg_match('#([\w]+)\s+(enum\([\w|\W]+\))#i', $l, $m)) {
519 $l = preg_replace('#enum\([\w|\W]+\)#i', "TEXT", $l);
521 // ignore the alter enum
522 if ($tbl && preg_match('#alter\s+table\s+([\w|\W]+)\s+enum\([\w|\W]+\)#i', $l, $m)) {
526 // UNIQUE KEY .. ignore
527 if ($tbl && preg_match('#UNIQUE KEY#i', $l, $m)) {
528 $last = array_pop($ret);
529 $ret[] = trim($last, ",");
533 if ($tbl && preg_match('#RENAME\s+TO#i', $l, $m)) {
537 if ($tbl && preg_match('#change\s+column#i', $l, $m)) {
541 // INDEX lookup ..ignore
542 if ($tbl && preg_match('#INDEX lookup+([\w|\W]+)#i', $l, $m)) {
543 $last = array_pop($ret);
544 $ret[] = trim($last, ",");
549 // CREATE INDEX ..ignore
550 if (preg_match('#alter\s+table\s+([a-z0-9_]+)\s+add\s+index\s+#i', $l, $m)) {
551 // $l = "CREATE INDEX {$m[1]}_{$m[2]} ON {$m[1]} {$m[3]}";
556 $l = preg_replace('#int\([0-9]+\)#i', 'INT', $l);
558 $l = preg_replace('# datetime#i', ' TIMESTAMP WITHOUT TIME ZONE', $l);
559 $l = preg_replace('# blob#i', ' TEXT', $l);
560 $l = preg_replace('# longtext#i', ' TEXT', $l);
561 $l = preg_replace('# tinyint#i', ' INT', $l);
567 $ret = array_merge($extra,$ret);
568 // echo implode("\n", $ret); exit;
570 file_put_contents($fn, implode("\n", $ret));
576 function checkOpts($opts)
580 foreach($opts as $o=>$v) {
581 if (!preg_match('/^json-/', $o) || empty($v)) {
584 if (!file_exists($v)) {
585 die("File does not exist : OPTION --{$o} = {$v} \n");
589 $modules = array_reverse($this->modulesList());
591 // move 'project' one to the end...
593 foreach ($modules as $module){
594 $file = $this->rootDir. "/Pman/$module/UpdateDatabase.php";
595 if($module == 'Core' || !file_exists($file)){
599 $class = "Pman_{$module}_UpdateDatabase";
601 if(!method_exists($x, 'checkOpts')){
604 $x->checkOpts($opts);
608 static function jsonImportFromArray($opts)
610 foreach($opts as $o=>$v) {
611 if (!preg_match('/^json-/', $o) || empty($v)) {
614 $type = str_replace('_', '-', substr($o,5));
616 $data= json_decode(file_get_contents($v),true);
617 $pg = HTML_FlexyFramework::get()->page;
618 DB_DataObject::factory($type)->importFromArray($pg ,$data,$opts);
628 function runUpdateModulesData()
630 if (class_exists('PDO_DataObjects_Introspection')) {
631 PDO_DataObject_Introspection::$cache = array();
633 HTML_FlexyFramework::get()->generateDataobjectsCache(true);
635 if(!in_array('Core', $this->disabled)){
636 echo "Running jsonImportFromArray\n";
637 Pman_Core_UpdateDatabase::jsonImportFromArray($this->opts);
640 echo "Running updateData on modules\n";
646 $modules = array_reverse($this->modulesList());
648 // move 'project' one to the end...
650 foreach ($modules as $module){
651 if(in_array($module, $this->disabled)){
654 $file = $this->rootDir. "/Pman/$module/UpdateDatabase.php";
655 if($module == 'Core' || !file_exists($file)){
660 $class = "Pman_{$module}_UpdateDatabase";
662 if(!method_exists($x, 'updateData')){
672 function updateDataEnums()
675 $enum = DB_DataObject::Factory('core_enum');
676 //DB_DAtaObject::debugLevel(1);
681 'name' => 'COMPTYPE',
682 'display_name' => 'Company Types',
683 'is_system_enum' => 1,
687 'display_name' => 'Owner',
688 'seqid' => 999, // last...
689 'is_system_enum' => 1,
696 'name' => 'HtmlEditor.font-family',
697 'display_name' => 'HTML Editor font families',
698 'is_system_enum' => 1,
701 'name' => 'Helvetica,Arial,sans-serif',
702 'display_name' => 'Helvetica',
707 'name' => 'Courier New',
708 'display_name' => 'Courier',
713 'display_name' => 'Tahoma',
717 'name' => 'Times New Roman,serif',
718 'display_name' => 'Times',
723 'display_name' => 'Verdana',
735 function updateDataGroups()
738 $groups = DB_DataObject::factory('core_group');
739 $groups->initGroups();
741 $groups->initDatabase($this,array(
743 'name' => 'bcc-email', // group who are bcc'ed on all requests.
744 'type' => 0, // system
747 'name' => 'system-email-from',
748 'type' => 0, // system
751 'name' => 'core-person-signup-bcc',
752 'type' => 0, // system
758 function updateDataCompanies()
761 // fix comptypes enums..
762 $c = DB_DataObject::Factory('core_company');
764 $c->selectAdd('distinct(comptype) as comptype');
765 $c->whereAdd("comptype != ''");
768 foreach($c->fetchAll('comptype') as $cts) {
772 $ctb[]= array( 'etype'=>'COMPTYPE', 'name' => $cts, 'display_name' => ucfirst(strtolower($cts)));
775 $c = DB_DataObject::Factory('core_enum');
778 //DB_DataObject::debugLevel(1);
780 $c = DB_DataObject::Factory('core_company');
782 UPDATE {$c->tableName()}
784 comptype_id = (SELECT id FROM core_enum where etype='comptype' and name={$c->tableName()}.comptype LIMIT 1)
798 function initEmails($templateDir, $emails)
801 $pg = HTML_FlexyFramework::get()->page;
802 foreach($emails as $name=>$data) {
803 $cm = DB_DataObject::factory('core_email');
804 $update = $cm->get('name', $name);
807 if (empty($cm->bcc_group)) {
808 if (empty($data['bcc_group'])) {
809 $this->jerr("missing bcc_group for template $name");
811 $g = DB_DataObject::Factory('core_group')->lookup('name',$data['bcc_group']);
814 $this->jerr("bcc_group {$data['bcc_group']} does not exist when importing template $name");
818 if (!$g->members('email')) {
819 $this->jerr("bcc_group {$data['bcc_group']} does not have any members");
822 $cm->bcc_group = $g->id;
824 if (empty($cm->test_class)) {
825 if (empty($data['test_class'])) {
826 $this->jerr("missing test_class for template $name");
828 $cm->test_class = $data['test_class'];
830 require_once $cm->test_class . '.php';
832 $clsname = str_replace('/','_', $cm->test_class);
834 $method = new ReflectionMethod($clsname , 'test_'. $name) ;
835 $got_it = $method->isStatic();
836 } catch(Exception $e) {
841 $this->jerr("template {$name} does not have a test method {$clsname}::test_{$name}");
845 echo "email: {$name} - checked\n";
846 continue; /// we do not import the body content of templates that exist...
853 // $basedir = $this->bootLoader->rootDir . $mail_template_dir;
857 'file' => $templateDir. $name .'.html'
860 if (!empty($data['master'])) {
861 $opts['master'] = $templateDir . $master .'.html';
863 require_once 'Pman/Core/Import/Core_email.php';
864 $x = new Pman_Core_Import_Core_email();
865 $x->updateOrCreateEmail('', $opts, $cm);
867 echo "email: {$name} - CREATED\n";
872 function updateData()
875 if (class_exists('PDO_DataObjects_Introspection')) {
876 PDO_DataObject_Introspection::$cache = array();
878 HTML_FlexyFramework::get()->generateDataobjectsCache(true);
879 $this->updateDataEnums();
880 $this->updateDataGroups();
881 $this->updateDataCompanies();
883 $c = DB_DataObject::Factory('I18n');
891 function fixMysqlInnodb()
894 static $done_check = false;
898 // innodb in single files is far more efficient that MYD or one big innodb file.
899 // first check if database is using this format.
900 $db = DB_DataObject::factory('core_enum');
901 $db->query("show variables like 'innodb_file_per_table'");
903 if ($db->Value == 'OFF') {
904 die("Error: set innodb_file_per_table = 1 in my.cnf\n\n");
907 $db = DB_DataObject::factory('core_enum');
908 $db->query("select version() as version");
911 if (version_compare($db->version, '5.7', '>=' )) {
913 $db = DB_DataObject::factory('core_enum');
914 $db->query("show variables like 'sql_mode'");
917 $modes = explode(",", $db->Value);
919 // these are 'new' problems with mysql.
921 in_array('NO_ZERO_IN_DATE', $modes) ||
922 in_array('NO_ZERO_DATE', $modes) ||
923 in_array('STRICT_TRANS_TABLES', $modes) ||
924 !in_array('ALLOW_INVALID_DATES', $modes)
926 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");
941 /** ------------- schema fixing ... there is an issue with data imported having the wrong sequence names... --- */
943 function fixSequencesMysql()
948 function fixSequencesPgsql()
952 //DB_DataObject::debugLevel(1);
953 $cs = DB_DataObject::factory('core_enum');
957 CASE WHEN strpos(seq_name, '.') > 0 THEN
960 quote_ident(min(schema_name)) ||'.'|| quote_ident(min(seq_name))
963 ||' OWNED BY '|| quote_ident(min(schema_name)) || '.' ||
964 quote_ident(min(table_name)) ||'.'|| quote_ident(min(column_name)) ||';' as cmd
968 n.nspname AS schema_name,
969 c.relname AS table_name,
970 a.attname AS column_name,
971 regexp_replace(regexp_replace(d.adsrc, E'nextval\\\\(+[''\\\"]*', ''),E'[''\\\"]*::.*\$','') AS seq_name
973 JOIN pg_attribute a ON (c.oid=a.attrelid)
974 JOIN pg_attrdef d ON (a.attrelid=d.adrelid AND a.attnum=d.adnum)
975 JOIN pg_namespace n ON (c.relnamespace=n.oid)
976 WHERE has_schema_privilege(n.oid,'USAGE')
977 AND n.nspname NOT LIKE 'pg!_%' escape '!'
978 AND has_table_privilege(c.oid,'SELECT')
979 AND (NOT a.attisdropped)
980 AND d.adsrc ~ '^nextval'
984 CASE WHEN strpos(seq_name, '.') > 0 THEN
985 substring(seq_name, 1,strpos(seq_name,'.')-1)
990 GROUP BY seq_name HAVING count(*)=1
993 while ($cs->fetch()) {
996 foreach($cmds as $cmd) {
997 $cs = DB_DataObject::factory('core_enum');
1001 $cs = DB_DataObject::factory('core_enum');
1003 SELECT 'SELECT SETVAL(' ||
1004 quote_literal(quote_ident(nspname) || '.' || quote_ident(S.relname)) ||
1005 ', MAX(' || quote_ident(C.attname)|| ')::integer ) FROM ' || nspname || '.' || quote_ident(T.relname)|| ';' as cmd
1011 WHERE S.relkind = 'S'
1013 AND D.refobjid = T.oid
1014 AND D.refobjid = C.attrelid
1015 AND D.refobjsubid = C.attnum
1016 AND NS.oid = T.relnamespace
1020 while ($cs->fetch()) {
1023 foreach($cmds as $cmd) {
1024 $cs = DB_DataObject::factory('core_enum');
1031 var $extensions = array(
1036 function runExtensions()
1039 $ff = HTML_Flexyframework::get();
1041 $dburl = parse_url($ff->database);
1043 $dbtype = $dburl['scheme'];
1045 foreach($this->extensions as $ext) {
1047 $scls = ucfirst($dbtype). $ext;
1048 $cls = __CLASS__ . '_'. $scls;
1049 $fn = implode('/',explode('_', $cls)).'.php';
1050 if (!file_exists(__DIR__.'/UpdateDatabase/'. $scls .'.php')) {
1061 function checkSystem()
1063 // most of these are from File_Convert...
1065 // these are required - and have simple dependancies.
1066 require_once 'System.php';
1072 'rsvg-convert', //librsvg2-bin
1078 // these are prefered - but may have complicated depenacies
1083 'html2text', // not availabe in debian squeeze
1084 'pdftocairo', //poppler-utils - not available in debian squeeze.
1094 foreach($req as $r) {
1095 if (!System::which($r)) {
1101 die("Missing these programs - need installing\n" . implode("\n",$res). "\n");
1103 foreach($pref as $r) {
1104 if (!System::which($r)) {
1110 echo "WARNING: Missing these programs - they may need installing\n". implode("\n",$res);