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();
139 HTML_FlexyFramework::get()->generateDataobjectsCache(true);
141 $ff = HTML_FlexyFramework::get();
145 if(!empty($ff->Core_Notify)){
146 // require_once 'Pman/Core/NotifySmtpCheck.php';
147 // $x = new Pman_Core_NotifySmtpCheck();
151 $this->disabled = explode(',', $ff->disable);
153 //$this->fixSequencesPgsql();exit;
156 // ask all the modules to verify the opts
158 $this->checkOpts($opts);
161 // do this first, so the innodb change + utf8 fixes column max sizes
163 // this will trigger errors about freetext indexes - we will have to remove them manually.?
164 // 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..)
166 $this->runExtensions();
169 if (empty($opts['data-only'])) {
172 if (!empty($opts['only-module-sql'])) {
176 $this->runUpdateModulesData();
179 if (!empty($opts['add-company']) && !in_array('Core', $this->disabled)) {
180 // make sure we have a good cache...?
182 DB_DataObject::factory('core_company')->initCompanies($this, $opts);
185 $this->runExtensions();
193 * imports SQL files from all DataObjects directories....
195 * except any matching /migrate/
200 // loop through all the modules, and see if they have a importSQL method?
203 $ff = HTML_Flexyframework::get();
205 $dburl = parse_url($ff->database); // used to be DB_DataObject['database'] - but not portable to PDO
207 //$this->{'import' . $url['scheme']}($url);
209 $dbtype = $dburl['scheme'];
212 $dirmethod = 'import' . $dburl['scheme'] . 'dir';
217 $ar = $this->modulesList();
222 if(in_array($m, $this->disabled)){
223 echo "module $m is disabled \n";
227 echo "Importing SQL from module $m\n";
228 if (!empty($this->opts['only-module-sql']) && $m != $this->opts['only-module-sql']) {
233 // check to see if the class has
237 $file = $this->rootDir. "/Pman/$m/UpdateDatabase.php";
238 if($m != 'Core' && file_exists($file)){
241 $class = "Pman_{$m}_UpdateDatabase";
243 if(method_exists($x, 'importModuleSQL')){
244 echo "Importing SQL from module $m using Module::importModuleSQL\n";
245 $x->opts = $this->opts;
246 $x->rootDir = $this->rootDir;
247 $x->importModuleSQL($dburl);
252 echo "Importing SQL from module $m\n";
255 // if init has been called
257 if (!empty($this->opts['init'])) {
258 $this->{$dirmethod}($dburl, $this->rootDir. "/Pman/$m/{$dbtype}.init");
264 $fd = $this->rootDir. "/Pman/$m/DataObjects";
266 $this->{$dirmethod}($dburl, $fd);
269 // new -- sql directory..
270 // new style will not support migrate ... they have to go into mysql-migrate.... directories..
271 // new style will not support pg.sql etc.. naming - that's what the direcotries are for..
273 $this->{$dirmethod}($dburl, $this->rootDir. "/Pman/$m/sql");
274 $this->{$dirmethod}($dburl, $this->rootDir. "/Pman/$m/{$dbtype}");
278 if (!empty($this->opts['init']) && file_exists($this->rootDir. "/Pman/$m/{$dbtype}.initdata")) {
279 if (class_exists('PDO_DataObjects_Introspection')) {
280 PDO_DataObject_Introspection::$cache = array();
282 HTML_FlexyFramework::get()->generateDataobjectsCache(true);
284 $this->{$dirmethod}($dburl, $this->rootDir. "/Pman/$m/{$dbtype}.initdata");
285 $this->{'fixSequences'. $dbtype}();
298 /** -------------- code to handle importing a whole directory of files into the database ------- **/
301 function importpgsqldir($url, $dir, $disable_triggers = false)
303 $ff = HTML_FlexyFramework::get();
305 require_once 'System.php';
306 $cat = System::which('cat');
307 $psql = System::which('psql');
310 if (!empty($url['pass'])) {
311 putenv("PGPASSWORD=". $url['pass']);
315 ' -h ' . $url['host'] .
316 ' -U' . escapeshellarg($url['user']) .
317 ' ' . basename($url['path']);
320 echo $psql_cmd . "\n" ;
321 echo "scan : $dir\n";
324 $files = array($dir);
329 $files = glob($dir.'/*.sql');
330 uksort($files, 'strcasecmp');
332 //$lsort = create_function('$a,$b','return strlen($a) > strlen($b) ? 1 : -1;');
333 //usort($files, $lsort);
336 foreach($files as $bfn) {
339 if (preg_match('/migrate/i', basename($bfn))) { // skip migration scripts at present..
342 if (preg_match('#\.[a-z]{2}\.sql#i', basename($bfn))
343 && !preg_match('#\.pg\.sql#i', basename($bfn))
344 ) { // skip migration scripts at present..
349 if (!preg_match('/pgsql/', basename($dir) )) {
350 if ( !preg_match('#\.pg\.sql$#', basename($bfn))) {
351 $fn = $this->convertToPG($bfn);
355 // files ending in .pg.sql are native postgres files.. ## depricated
358 $cmd = "$psql_cmd < " . escapeshellarg($fn ? $fn : $bfn) . ' 2>&1' ;
360 echo "$bfn: $cmd ". ($ff->cli ? "\n" : "<BR>\n");
376 * mysql - does not support conversions.
380 function importmysqlidir($dburl, $dir) {
381 return $this->importmysqldir($dburl, $dir);
384 function importmysqldir($dburl, $dir)
387 $this->fixMysqlInnodb(); /// run once
389 echo "Import MYSQL :: $dir\n";
392 require_once 'System.php';
393 $cat = System::which('cat');
394 $mysql = System::which('mysql');
398 $mysql_cmd = $mysql .
399 ' -h ' . $dburl['host'] .
400 ' -u' . escapeshellarg($dburl['user']) .
401 (!empty($dburl['pass']) ? ' -p' . escapeshellarg($dburl['pass']) : '') .
402 ' ' . basename($dburl['path']);
403 //echo $mysql_cmd . "\n" ;
405 $files = glob($dir.'/*.sql');
406 uksort($files, 'strcasecmp');
409 foreach($files as $fn) {
412 if (preg_match('/migrate/i', basename($fn))) { // skip migration scripts at present..
415 // .my.sql but not .pg.sql
416 if (preg_match('#\.[a-z]{2}\.sql#i', basename($fn))
417 && !preg_match('#\.my\.sql#i', basename($fn))
418 ) { // skip migration scripts at present..
421 if (!strlen(trim($fn))) {
425 $cmd = "$mysql_cmd -f < " . escapeshellarg($fn) ." 2>&1" ;
427 echo basename($dir).'/'. basename($fn) . '::' . $cmd. ($this->cli ? "\n" : "<BR>\n");
430 $fp = popen($cmd, "r");
433 // send the current file part to the browser
434 $line = trim(fgets($fp, 1024));
439 if (!preg_match('/^ERROR\s+([0-9]+)/', $line, $matches)) {
440 echo " ---- {$line}\n"; flush();
444 switch($matches[1]) {
445 case 1017: // cause by renaming table -- old one does not exist..
446 case 1050: // create tables triggers this..
447 case 1060: // Duplicate column name
448 case 1061: // Duplicate key name - triggered by add index.. but could hide error. - unlikely though.
449 case 1091: // drop index -- name does not exist.. might hide errors..
451 case 1146: // drop a index on an unknown table.. - happens rarely...
452 case 1054: // Unknown column -- triggered by CHANGE COLUMN - but may hide other errrors..
458 echo " ---- {$line}\n"; flush();
462 // 1051: // Unknown table -- normally drop = add iff exists..
463 echo "File: $fn\n$line\n";
479 * simple regex based convert mysql to pgsql...
481 function convertToPG($src)
483 //echo "Convert $src\n";
485 $fn = $this->tempName('sql');
487 $ret = array( ); // pad it a bit.
488 $extra = array("", "" );
491 foreach(file($src) as $l) {
494 if (!strlen($l) || $l[0] == '#') {
498 if (preg_match('#create\s+table\s+([a-z0-9_]+)#i', $l, $m)) {
501 if (preg_match('#create\s+table\s+\`([a-z0-9_]+)\`#i', $l, $m)) {
502 $tbl = 'shop_' . strtolower($m[1]);
503 $l = preg_replace('#create\s+table\s+\`([a-z0-9_]+)\`#i', "CREATE TABLE {$tbl}", $l);
505 if (preg_match('#\`([a-z0-9_]+)\`#i', $l, $m) && !preg_match('#alter\s+table\s+#i', $l)) {
506 $l = preg_replace('#\`([a-z0-9_]+)\`#i', "{$m[1]}_name", $l);
509 if ($tbl && preg_match('#auto_increment#i', $l, $m)) {
510 $l = preg_replace('#auto_increment#i', "default nextval('{$tbl}_seq')", $l);
511 $extra[] = "create sequence {$tbl}_seq;";
515 if (preg_match('#alter\s+table\s+(\`[a-z0-9_]+\`)#i', $l, $m)){
516 $l = preg_replace('#alter\s+table\s+(\`[a-z0-9_]+\`)#i', "ALTER TABLE {$tbl}", $l);
519 // enum value -- use the text instead..
521 if ($tbl && preg_match('#([\w]+)\s+(enum\([\w|\W]+\))#i', $l, $m)) {
522 $l = preg_replace('#enum\([\w|\W]+\)#i', "TEXT", $l);
524 // ignore the alter enum
525 if ($tbl && preg_match('#alter\s+table\s+([\w|\W]+)\s+enum\([\w|\W]+\)#i', $l, $m)) {
529 // UNIQUE KEY .. ignore
530 if ($tbl && preg_match('#UNIQUE KEY#i', $l, $m)) {
531 $last = array_pop($ret);
532 $ret[] = trim($last, ",");
536 if ($tbl && preg_match('#RENAME\s+TO#i', $l, $m)) {
540 if ($tbl && preg_match('#change\s+column#i', $l, $m)) {
544 // INDEX lookup ..ignore
545 if ($tbl && preg_match('#INDEX lookup+([\w|\W]+)#i', $l, $m)) {
546 $last = array_pop($ret);
547 $ret[] = trim($last, ",");
552 // CREATE INDEX ..ignore
553 if (preg_match('#alter\s+table\s+([a-z0-9_]+)\s+add\s+index\s+#i', $l, $m)) {
554 // $l = "CREATE INDEX {$m[1]}_{$m[2]} ON {$m[1]} {$m[3]}";
559 $l = preg_replace('#int\([0-9]+\)#i', 'INT', $l);
561 $l = preg_replace('# datetime#i', ' TIMESTAMP WITHOUT TIME ZONE', $l);
562 $l = preg_replace('# blob#i', ' TEXT', $l);
563 $l = preg_replace('# longtext#i', ' TEXT', $l);
564 $l = preg_replace('# tinyint#i', ' INT', $l);
570 $ret = array_merge($extra,$ret);
571 // echo implode("\n", $ret); exit;
573 file_put_contents($fn, implode("\n", $ret));
579 function checkOpts($opts)
583 foreach($opts as $o=>$v) {
584 if (!preg_match('/^json-/', $o) || empty($v)) {
587 if (!file_exists($v)) {
588 die("File does not exist : OPTION --{$o} = {$v} \n");
592 $modules = array_reverse($this->modulesList());
594 // move 'project' one to the end...
596 foreach ($modules as $module){
597 $file = $this->rootDir. "/Pman/$module/UpdateDatabase.php";
598 if($module == 'Core' || !file_exists($file)){
602 $class = "Pman_{$module}_UpdateDatabase";
604 if(!method_exists($x, 'checkOpts')){
607 $x->checkOpts($opts);
611 static function jsonImportFromArray($opts)
613 foreach($opts as $o=>$v) {
614 if (!preg_match('/^json-/', $o) || empty($v)) {
617 $type = str_replace('_', '-', substr($o,5));
619 $data= json_decode(file_get_contents($v),true);
620 $pg = HTML_FlexyFramework::get()->page;
621 DB_DataObject::factory($type)->importFromArray($pg ,$data,$opts);
631 function runUpdateModulesData()
633 if (class_exists('PDO_DataObjects_Introspection')) {
634 PDO_DataObject_Introspection::$cache = array();
636 HTML_FlexyFramework::get()->generateDataobjectsCache(true);
638 if(!in_array('Core', $this->disabled)){
639 echo "Running jsonImportFromArray\n";
640 Pman_Core_UpdateDatabase::jsonImportFromArray($this->opts);
643 echo "Running updateData on modules\n";
649 $modules = array_reverse($this->modulesList());
651 // move 'project' one to the end...
653 foreach ($modules as $module){
654 if(in_array($module, $this->disabled)){
657 $file = $this->rootDir. "/Pman/$module/UpdateDatabase.php";
658 if($module == 'Core' || !file_exists($file)){
663 $class = "Pman_{$module}_UpdateDatabase";
665 if(!method_exists($x, 'updateData')){
675 function updateDataEnums()
678 $enum = DB_DataObject::Factory('core_enum');
679 //DB_DAtaObject::debugLevel(1);
684 'name' => 'COMPTYPE',
685 'display_name' => 'Company Types',
686 'is_system_enum' => 1,
690 'display_name' => 'Owner',
691 'seqid' => 999, // last...
692 'is_system_enum' => 1,
699 'name' => 'HtmlEditor.font-family',
700 'display_name' => 'HTML Editor font families',
701 'is_system_enum' => 1,
704 'name' => 'Helvetica,Arial,sans-serif',
705 'display_name' => 'Helvetica',
710 'name' => 'Courier New',
711 'display_name' => 'Courier',
716 'display_name' => 'Tahoma',
720 'name' => 'Times New Roman,serif',
721 'display_name' => 'Times',
726 'display_name' => 'Verdana',
738 function updateDataGroups()
741 $groups = DB_DataObject::factory('core_group');
742 $groups->initGroups();
744 $groups->initDatabase($this,array(
746 'name' => 'bcc-email', // group who are bcc'ed on all requests.
747 'type' => 0, // system
750 'name' => 'system-email-from',
751 'type' => 0, // system
754 'name' => 'core-person-signup-bcc',
755 'type' => 0, // system
761 function updateDataCompanies()
764 // fix comptypes enums..
765 $c = DB_DataObject::Factory('core_company');
767 $c->selectAdd('distinct(comptype) as comptype');
768 $c->whereAdd("comptype != ''");
771 foreach($c->fetchAll('comptype') as $cts) {
775 $ctb[]= array( 'etype'=>'COMPTYPE', 'name' => $cts, 'display_name' => ucfirst(strtolower($cts)));
778 $c = DB_DataObject::Factory('core_enum');
781 //DB_DataObject::debugLevel(1);
783 $c = DB_DataObject::Factory('core_company');
785 UPDATE {$c->tableName()}
787 comptype_id = (SELECT id FROM core_enum where etype='comptype' and name={$c->tableName()}.comptype LIMIT 1)
801 function initEmails($templateDir, $emails)
804 $pg = HTML_FlexyFramework::get()->page;
805 foreach($emails as $name=>$data) {
806 $cm = DB_DataObject::factory('core_email');
807 $update = $cm->get('name', $name);
810 if (empty($cm->bcc_group)) {
811 if (empty($data['bcc_group'])) {
812 $this->jerr("missing bcc_group for template $name");
814 $g = DB_DataObject::Factory('core_group')->lookup('name',$data['bcc_group']);
817 $this->jerr("bcc_group {$data['bcc_group']} does not exist when importing template $name");
821 if (!$g->members('email')) {
822 $this->jerr("bcc_group {$data['bcc_group']} does not have any members");
825 $cm->bcc_group = $g->id;
827 if (empty($cm->test_class)) {
828 if (empty($data['test_class'])) {
829 $this->jerr("missing test_class for template $name");
831 $cm->test_class = $data['test_class'];
833 require_once $cm->test_class . '.php';
835 $clsname = str_replace('/','_', $cm->test_class);
837 $method = new ReflectionMethod($clsname , 'test_'. $name) ;
838 $got_it = $method->isStatic();
839 } catch(Exception $e) {
844 $this->jerr("template {$name} does not have a test method {$clsname}::test_{$name}");
848 echo "email: {$name} - checked\n";
849 continue; /// we do not import the body content of templates that exist...
856 // $basedir = $this->bootLoader->rootDir . $mail_template_dir;
860 'file' => $templateDir. $name .'.html'
863 if (!empty($data['master'])) {
864 $opts['master'] = $templateDir . $master .'.html';
866 require_once 'Pman/Core/Import/Core_email.php';
867 $x = new Pman_Core_Import_Core_email();
868 $x->updateOrCreateEmail('', $opts, $cm);
870 echo "email: {$name} - CREATED\n";
875 function updateData()
878 if (class_exists('PDO_DataObjects_Introspection')) {
879 PDO_DataObject_Introspection::$cache = array();
881 HTML_FlexyFramework::get()->generateDataobjectsCache(true);
882 $this->updateDataEnums();
883 $this->updateDataGroups();
884 $this->updateDataCompanies();
886 $c = DB_DataObject::Factory('I18n');
894 function fixMysqlInnodb()
897 static $done_check = false;
901 // innodb in single files is far more efficient that MYD or one big innodb file.
902 // first check if database is using this format.
903 $db = DB_DataObject::factory('core_enum');
904 $db->query("show variables like 'innodb_file_per_table'");
906 if ($db->Value == 'OFF') {
907 die("Error: set innodb_file_per_table = 1 in my.cnf\n\n");
910 $db = DB_DataObject::factory('core_enum');
911 $db->query("select version() as version");
914 if (version_compare($db->version, '5.7', '>=' )) {
916 $db = DB_DataObject::factory('core_enum');
917 $db->query("show variables like 'sql_mode'");
920 $modes = explode(",", $db->Value);
922 // these are 'new' problems with mysql.
924 in_array('NO_ZERO_IN_DATE', $modes) ||
925 in_array('NO_ZERO_DATE', $modes) ||
926 in_array('STRICT_TRANS_TABLES', $modes) ||
927 !in_array('ALLOW_INVALID_DATES', $modes)
929 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");
944 /** ------------- schema fixing ... there is an issue with data imported having the wrong sequence names... --- */
946 function fixSequencesMysql()
951 function fixSequencesPgsql()
955 //DB_DataObject::debugLevel(1);
956 $cs = DB_DataObject::factory('core_enum');
960 CASE WHEN strpos(seq_name, '.') > 0 THEN
963 quote_ident(min(schema_name)) ||'.'|| quote_ident(min(seq_name))
966 ||' OWNED BY '|| quote_ident(min(schema_name)) || '.' ||
967 quote_ident(min(table_name)) ||'.'|| quote_ident(min(column_name)) ||';' as cmd
971 n.nspname AS schema_name,
972 c.relname AS table_name,
973 a.attname AS column_name,
974 regexp_replace(regexp_replace(d.adsrc, E'nextval\\\\(+[''\\\"]*', ''),E'[''\\\"]*::.*\$','') AS seq_name
976 JOIN pg_attribute a ON (c.oid=a.attrelid)
977 JOIN pg_attrdef d ON (a.attrelid=d.adrelid AND a.attnum=d.adnum)
978 JOIN pg_namespace n ON (c.relnamespace=n.oid)
979 WHERE has_schema_privilege(n.oid,'USAGE')
980 AND n.nspname NOT LIKE 'pg!_%' escape '!'
981 AND has_table_privilege(c.oid,'SELECT')
982 AND (NOT a.attisdropped)
983 AND d.adsrc ~ '^nextval'
987 CASE WHEN strpos(seq_name, '.') > 0 THEN
988 substring(seq_name, 1,strpos(seq_name,'.')-1)
993 GROUP BY seq_name HAVING count(*)=1
996 while ($cs->fetch()) {
999 foreach($cmds as $cmd) {
1000 $cs = DB_DataObject::factory('core_enum');
1004 $cs = DB_DataObject::factory('core_enum');
1006 SELECT 'SELECT SETVAL(' ||
1007 quote_literal(quote_ident(nspname) || '.' || quote_ident(S.relname)) ||
1008 ', MAX(' || quote_ident(C.attname)|| ')::integer ) FROM ' || nspname || '.' || quote_ident(T.relname)|| ';' as cmd
1014 WHERE S.relkind = 'S'
1016 AND D.refobjid = T.oid
1017 AND D.refobjid = C.attrelid
1018 AND D.refobjsubid = C.attnum
1019 AND NS.oid = T.relnamespace
1023 while ($cs->fetch()) {
1026 foreach($cmds as $cmd) {
1027 $cs = DB_DataObject::factory('core_enum');
1034 var $extensions = array(
1039 function runExtensions()
1042 $ff = HTML_Flexyframework::get();
1044 $dburl = parse_url($ff->database);
1046 $dbtype = $dburl['scheme'];
1048 foreach($this->extensions as $ext) {
1050 $scls = ucfirst($dbtype). $ext;
1051 $cls = __CLASS__ . '_'. $scls;
1052 $fn = implode('/',explode('_', $cls)).'.php';
1053 if (!file_exists(__DIR__.'/UpdateDatabase/'. $scls .'.php')) {
1064 function checkSystem()
1066 // most of these are from File_Convert...
1068 // these are required - and have simple dependancies.
1069 require_once 'System.php';
1075 'rsvg-convert', //librsvg2-bin
1081 // these are prefered - but may have complicated depenacies
1086 'html2text', // not availabe in debian squeeze
1087 'pdftocairo', //poppler-utils - not available in debian squeeze.
1097 foreach($req as $r) {
1098 if (!System::which($r)) {
1104 die("Missing these programs - need installing\n" . implode("\n",$res). "\n");
1106 foreach($pref as $r) {
1107 if (!System::which($r)) {
1113 echo "WARNING: Missing these programs - they may need installing\n". implode("\n",$res);