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',
72 'json-person' => array(
73 'desc' => 'Person JSON file',
81 static function cli_opts()
84 $ret = self::$cli_opts;
85 $ff = HTML_FlexyFramework::get();
87 $mods = $a->modulesList();
88 foreach($mods as $m) {
90 $fd = $ff->rootDir. "/Pman/$m/UpdateDatabase.php";
91 if (!file_exists($fd)) {
97 $cls = new ReflectionClass('Pman_'. $m . '_UpdateDatabase');
99 $ret = array_merge($ret, $cls->getStaticPropertyValue('cli_opts'));
108 var $disabled = array();
115 $ff = HTML_FlexyFramework::get();
116 if (!empty($ff->cli)) {
121 parent::getAuth(); // load company!
122 $au = $this->getAuthUser();
123 if (!$au || $au->company()->comptype != 'OWNER') {
124 $this->jerr("Not authenticated", array('authFailure' => true));
126 $this->authUser = $au;
130 function get($args, $opts)
132 PEAR::setErrorHandling(PEAR_ERROR_CALLBACK, array($this, 'onPearError'));
134 $this->checkSystem();
136 $ff = HTML_FlexyFramework::get();
138 // if(!empty($ff->Core_Notify)){
139 // require_once 'Pman/Core/NotifySmtpCheck.php';
140 // $x = new Pman_Core_NotifySmtpCheck();
146 $this->disabled = explode(',', $ff->disable);
148 //$this->fixSequencesPgsql();exit;
151 // ask all the modules to verify the opts
153 $this->checkOpts($opts);
155 if (empty($opts['data-only'])) {
158 if (!empty($opts['only-module-sql'])) {
162 $this->runUpdateModulesData();
165 if (!empty($opts['add-company']) && !in_array('Core', $this->disabled)) {
166 // make sure we have a good cache...?
168 DB_DataObject::factory('companies')->initCompanies($this, $opts);
171 $this->runExtensions();
179 * imports SQL files from all DataObjects directories....
181 * except any matching /migrate/
186 // loop through all the modules, and see if they have a importSQL method?
189 $ff = HTML_Flexyframework::get();
191 $dburl = parse_url($ff->DB_DataObject['database']);
193 //$this->{'import' . $url['scheme']}($url);
195 $dbtype = $dburl['scheme'];
196 $dirmethod = 'import' . $dburl['scheme'] . 'dir';
201 $ar = $this->modulesList();
205 if(in_array($m, $this->disabled)){
206 echo "module $m is disabled \n";
210 echo "Importing SQL from module $m\n";
211 if (!empty($this->opts['only-module-sql']) && $m != $this->opts['only-module-sql']) {
216 // check to see if the class has
220 $file = $this->rootDir. "/Pman/$m/UpdateDatabase.php";
221 if($m != 'Core' && file_exists($file)){
224 $class = "Pman_{$m}_UpdateDatabase";
226 if(method_exists($x, 'importModuleSQL')){
227 echo "Importing SQL from module $m using Module::importModuleSQL\n";
228 $x->opts = $this->opts;
229 $x->rootDir = $this->rootDir;
230 $x->importModuleSQL($dburl);
235 echo "Importing SQL from module $m\n";
238 // if init has been called
240 if (!empty($this->opts['init'])) {
241 $this->{$dirmethod}($dburl, $this->rootDir. "/Pman/$m/{$dbtype}.init");
247 $fd = $this->rootDir. "/Pman/$m/DataObjects";
249 $this->{$dirmethod}($dburl, $fd);
252 // new -- sql directory..
253 // new style will not support migrate ... they have to go into mysql-migrate.... directories..
254 // new style will not support pg.sql etc.. naming - that's what the direcotries are for..
256 $this->{$dirmethod}($dburl, $this->rootDir. "/Pman/$m/sql");
257 $this->{$dirmethod}($dburl, $this->rootDir. "/Pman/$m/{$dbtype}");
261 if (!empty($this->opts['init']) && file_exists($this->rootDir. "/Pman/$m/{$dbtype}.initdata")) {
262 HTML_FlexyFramework::get()->generateDataobjectsCache(true);
264 $this->{$dirmethod}($dburl, $this->rootDir. "/Pman/$m/{$dbtype}.initdata");
265 $this->{'fixSequences'. $dbtype}();
277 /** -------------- code to handle importing a whole directory of files into the database ------- **/
280 function importpgsqldir($url, $dir, $disable_triggers = false)
282 $ff = HTML_FlexyFramework::get();
284 require_once 'System.php';
285 $cat = System::which('cat');
286 $psql = System::which('psql');
289 if (!empty($url['pass'])) {
290 putenv("PGPASSWORD=". $url['pass']);
294 ' -h ' . $url['host'] .
295 ' -U' . escapeshellarg($url['user']) .
296 ' ' . basename($url['path']);
299 echo $psql_cmd . "\n" ;
300 echo "scan : $dir\n";
303 $files = array($dir);
308 $files = glob($dir.'/*.sql');
309 uksort($files, 'strcasecmp');
311 //$lsort = create_function('$a,$b','return strlen($a) > strlen($b) ? 1 : -1;');
312 //usort($files, $lsort);
315 foreach($files as $bfn) {
318 if (preg_match('/migrate/i', basename($bfn))) { // skip migration scripts at present..
321 if (preg_match('#\.[a-z]{2}\.sql#i', basename($bfn))
322 && !preg_match('#\.pg\.sql#i', basename($bfn))
323 ) { // skip migration scripts at present..
328 if (!preg_match('/pgsql/', basename($dir) )) {
329 if ( !preg_match('#\.pg\.sql$#', basename($bfn))) {
330 $fn = $this->convertToPG($bfn);
334 // files ending in .pg.sql are native postgres files.. ## depricated
337 $cmd = "$psql_cmd < " . escapeshellarg($fn ? $fn : $bfn) . ' 2>&1' ;
339 echo "$bfn: $cmd ". ($ff->cli ? "\n" : "<BR>\n");
355 * mysql - does not support conversions.
361 function importmysqldir($dburl, $dir)
364 $this->fixMysqlInnodb(); /// run once
366 echo "Import MYSQL :: $dir\n";
369 require_once 'System.php';
370 $cat = System::which('cat');
371 $mysql = System::which('mysql');
375 $mysql_cmd = $mysql .
376 ' -h ' . $dburl['host'] .
377 ' -u' . escapeshellarg($dburl['user']) .
378 (!empty($dburl['pass']) ? ' -p' . escapeshellarg($dburl['pass']) : '') .
379 ' ' . basename($dburl['path']);
380 //echo $mysql_cmd . "\n" ;
382 $files = glob($dir.'/*.sql');
383 uksort($files, 'strcasecmp');
386 foreach($files as $fn) {
389 if (preg_match('/migrate/i', basename($fn))) { // skip migration scripts at present..
392 // .my.sql but not .pg.sql
393 if (preg_match('#\.[a-z]{2}\.sql#i', basename($fn))
394 && !preg_match('#\.my\.sql#i', basename($fn))
395 ) { // skip migration scripts at present..
398 if (!strlen(trim($fn))) {
402 $cmd = "$mysql_cmd -f < " . escapeshellarg($fn) ;
404 echo basename($dir).'/'. basename($fn) . '::' . $cmd. ($this->cli ? "\n" : "<BR>\n");
417 * simple regex based convert mysql to pgsql...
419 function convertToPG($src)
421 //echo "Convert $src\n";
423 $fn = $this->tempName('sql');
425 $ret = array( ); // pad it a bit.
426 $extra = array("", "" );
429 foreach(file($src) as $l) {
432 if (!strlen($l) || $l[0] == '#') {
436 if (preg_match('#create\s+table\s+([a-z0-9_]+)#i', $l, $m)) {
439 if (preg_match('#create\s+table\s+\`([a-z0-9_]+)\`#i', $l, $m)) {
440 $tbl = 'shop_' . strtolower($m[1]);
441 $l = preg_replace('#create\s+table\s+\`([a-z0-9_]+)\`#i', "CREATE TABLE {$tbl}", $l);
443 if (preg_match('#\`([a-z0-9_]+)\`#i', $l, $m) && !preg_match('#alter\s+table\s+#i', $l)) {
444 $l = preg_replace('#\`([a-z0-9_]+)\`#i', "{$m[1]}_name", $l);
447 if ($tbl && preg_match('#auto_increment#i', $l, $m)) {
448 $l = preg_replace('#auto_increment#i', "default nextval('{$tbl}_seq')", $l);
449 $extra[] = "create sequence {$tbl}_seq;";
453 if (preg_match('#alter\s+table\s+(\`[a-z0-9_]+\`)#i', $l, $m)){
454 $l = preg_replace('#alter\s+table\s+(\`[a-z0-9_]+\`)#i', "ALTER TABLE {$tbl}", $l);
457 // enum value -- use the text instead..
459 if ($tbl && preg_match('#([\w]+)\s+(enum\([\w|\W]+\))#i', $l, $m)) {
460 $l = preg_replace('#enum\([\w|\W]+\)#i', "TEXT", $l);
462 // ignore the alter enum
463 if ($tbl && preg_match('#alter\s+table\s+([\w|\W]+)\s+enum\([\w|\W]+\)#i', $l, $m)) {
467 // UNIQUE KEY .. ignore
468 if ($tbl && preg_match('#UNIQUE KEY#i', $l, $m)) {
469 $last = array_pop($ret);
470 $ret[] = trim($last, ",");
474 if ($tbl && preg_match('#RENAME\s+TO#i', $l, $m)) {
478 if ($tbl && preg_match('#change\s+column#i', $l, $m)) {
482 // INDEX lookup ..ignore
483 if ($tbl && preg_match('#INDEX lookup+([\w|\W]+)#i', $l, $m)) {
484 $last = array_pop($ret);
485 $ret[] = trim($last, ",");
490 // CREATE INDEX ..ignore
491 if (preg_match('#alter\s+table\s+([a-z0-9_]+)\s+add\s+index\s+#i', $l, $m)) {
492 // $l = "CREATE INDEX {$m[1]}_{$m[2]} ON {$m[1]} {$m[3]}";
497 $l = preg_replace('#int\([0-9]+\)#i', 'INT', $l);
499 $l = preg_replace('# datetime#i', ' TIMESTAMP WITHOUT TIME ZONE', $l);
500 $l = preg_replace('# blob#i', ' TEXT', $l);
501 $l = preg_replace('# longtext#i', ' TEXT', $l);
502 $l = preg_replace('# tinyint#i', ' INT', $l);
508 $ret = array_merge($extra,$ret);
509 // echo implode("\n", $ret); exit;
511 file_put_contents($fn, implode("\n", $ret));
517 function checkOpts($opts)
521 foreach($opts as $o=>$v) {
522 if (!preg_match('/^json-/', $o) || empty($v)) {
525 if (!file_exists($v)) {
526 die("File does not exist : OPTION --{$o} = {$v} \n");
530 $modules = array_reverse($this->modulesList());
532 // move 'project' one to the end...
534 foreach ($modules as $module){
535 $file = $this->rootDir. "/Pman/$module/UpdateDatabase.php";
536 if($module == 'Core' || !file_exists($file)){
540 $class = "Pman_{$module}_UpdateDatabase";
542 if(!method_exists($x, 'checkOpts')){
545 $x->checkOpts($opts);
549 static function jsonImportFromArray($opts)
551 foreach($opts as $o=>$v) {
552 if (!preg_match('/^json-/', $o) || empty($v)) {
555 $type = str_replace('_', '-', substr($o,5));
557 $data= json_decode(file_get_contents($v),true);
558 $pg = HTML_FlexyFramework::get()->page;
559 DB_DataObject::factory($type)->importFromArray($pg ,$data,$opts);
569 function runUpdateModulesData()
571 HTML_FlexyFramework::get()->generateDataobjectsCache(true);
573 if(!in_array('Core', $this->disabled)){
574 echo "Running jsonImportFromArray\n";
575 Pman_Core_UpdateDatabase::jsonImportFromArray($this->opts);
578 echo "Running updateData on modules\n";
584 $modules = array_reverse($this->modulesList());
586 // move 'project' one to the end...
588 foreach ($modules as $module){
589 if(in_array($module, $this->disabled)){
592 $file = $this->rootDir. "/Pman/$module/UpdateDatabase.php";
593 if($module == 'Core' || !file_exists($file)){
598 $class = "Pman_{$module}_UpdateDatabase";
600 if(!method_exists($x, 'updateData')){
610 function updateDataEnums()
613 $enum = DB_DataObject::Factory('core_enum');
614 //DB_DAtaObject::debugLevel(1);
619 'name' => 'COMPTYPE',
620 'display_name' => 'Company Types',
621 'is_system_enum' => 1,
625 'display_name' => 'Owner',
626 'seqid' => 999, // last...
627 'is_system_enum' => 1,
634 'name' => 'HtmlEditor.font-family',
635 'display_name' => 'HTML Editor font families',
636 'is_system_enum' => 1,
639 'name' => 'Helvetica,Arial,sans-serif',
640 'display_name' => 'Helvetica',
645 'name' => 'Courier New',
646 'display_name' => 'Courier',
651 'display_name' => 'Tahoma',
655 'name' => 'Times New Roman,serif',
656 'display_name' => 'Times',
661 'display_name' => 'Verdana',
673 function updateDataGroups()
676 $groups = DB_DataObject::factory('groups');
677 $groups->initGroups();
679 $groups->initDatabase($this,array(
681 'name' => 'bcc-email', // group who are bcc'ed on all requests.
682 'type' => 0, // system
685 'name' => 'system-email-from',
686 'type' => 0, // system
689 'name' => 'core-person-signup-bcc',
690 'type' => 0, // system
696 function updateDataCompanies()
699 // fix comptypes enums..
700 $c = DB_DataObject::Factory('Companies');
702 $c->selectAdd('distinct(comptype) as comptype');
703 $c->whereAdd("comptype != ''");
706 foreach($c->fetchAll('comptype') as $cts) {
710 $ctb[]= array( 'etype'=>'COMPTYPE', 'name' => $cts, 'display_name' => ucfirst(strtolower($cts)));
713 $c = DB_DataObject::Factory('core_enum');
716 //DB_DataObject::debugLevel(1);
718 $c = DB_DataObject::Factory('Companies');
722 comptype_id = (SELECT id FROM core_enum where etype='comptype' and name=Companies.comptype LIMIT 1)
736 function initEmails($templateDir, $emails)
739 $pg = HTML_FlexyFramework::get()->page;
740 foreach($emails as $name=>$data) {
741 $cm = DB_DataObject::factory('core_email');
742 $update = $cm->get('name', $name);
745 if (empty($cm->bcc_group)) {
746 if (empty($data['bcc_group'])) {
747 $this->jerr("missing bcc_group for template $name");
749 $g = DB_DataObject::Factory('Groups')->lookup('name',$data['bcc_group']);
752 $this->jerr("bcc_group {$data['bcc_group']} does not exist when importing template $name");
754 if (!$g->members('email')) {
755 $this->jerr("bcc_group {$data['bcc_group']} does not have any members");
759 $cm->bcc_group = $g->id;
761 if (empty($cm->test_class)) {
762 if (empty($data['test_class'])) {
763 $this->jerr("missing test_class for template $name");
765 $cm->test_class = $data['test_class'];
767 require_once $cm->test_class . '.php';
769 $clsname = str_replace('/','_', $cm->test_class);
771 $method = new ReflectionMethod($clsname , 'test_'. $name) ;
772 $got_it = $method->isStatic();
773 } catch(Exception $e) {
778 $this->jerr("template {$name} does not have a test method {$clsname}::test_{$name}");
782 echo "email: {$name} - checked\n";
783 continue; /// we do not import the body content of templates that exist...
789 // $basedir = $this->bootLoader->rootDir . $mail_template_dir;
793 'file' => $templateDir. $name .'.html'
796 if (!empty($data['master'])) {
797 $opts['master'] = $templateDir . $master .'.html';
799 require_once 'Pman/Core/Import/Core_email.php';
800 $x = new Pman_Core_Import_Core_email();
803 echo "email: {$name} - CREATED\n";
808 function updateData()
811 HTML_FlexyFramework::get()->generateDataobjectsCache(true);
812 $this->updateDataEnums();
813 $this->updateDataGroups();
814 $this->updateDataCompanies();
816 $c = DB_DataObject::Factory('I18n');
824 function fixMysqlInnodb()
827 static $done_check = false;
831 // innodb in single files is far more efficient that MYD or one big innodb file.
832 // first check if database is using this format.
833 $db = DB_DataObject::factory('core_enum');
834 $db->query("show variables like 'innodb_file_per_table'");
836 if ($db->Value == 'OFF') {
837 die("Error: set innodb_file_per_table = 1 in my.cnf\n\n");
851 /** ------------- schema fixing ... there is an issue with data imported having the wrong sequence names... --- */
853 function fixSequencesMysql()
858 function fixSequencesPgsql()
862 //DB_DataObject::debugLevel(1);
863 $cs = DB_DataObject::factory('core_enum');
867 CASE WHEN strpos(seq_name, '.') > 0 THEN
870 quote_ident(min(schema_name)) ||'.'|| quote_ident(min(seq_name))
873 ||' OWNED BY '|| quote_ident(min(schema_name)) || '.' ||
874 quote_ident(min(table_name)) ||'.'|| quote_ident(min(column_name)) ||';' as cmd
878 n.nspname AS schema_name,
879 c.relname AS table_name,
880 a.attname AS column_name,
881 regexp_replace(regexp_replace(d.adsrc, E'nextval\\\\(+[''\\\"]*', ''),E'[''\\\"]*::.*\$','') AS seq_name
883 JOIN pg_attribute a ON (c.oid=a.attrelid)
884 JOIN pg_attrdef d ON (a.attrelid=d.adrelid AND a.attnum=d.adnum)
885 JOIN pg_namespace n ON (c.relnamespace=n.oid)
886 WHERE has_schema_privilege(n.oid,'USAGE')
887 AND n.nspname NOT LIKE 'pg!_%' escape '!'
888 AND has_table_privilege(c.oid,'SELECT')
889 AND (NOT a.attisdropped)
890 AND d.adsrc ~ '^nextval'
894 CASE WHEN strpos(seq_name, '.') > 0 THEN
895 substring(seq_name, 1,strpos(seq_name,'.')-1)
900 GROUP BY seq_name HAVING count(*)=1
903 while ($cs->fetch()) {
906 foreach($cmds as $cmd) {
907 $cs = DB_DataObject::factory('core_enum');
911 $cs = DB_DataObject::factory('core_enum');
913 SELECT 'SELECT SETVAL(' ||
914 quote_literal(quote_ident(nspname) || '.' || quote_ident(S.relname)) ||
915 ', MAX(' || quote_ident(C.attname)|| ')::integer ) FROM ' || nspname || '.' || quote_ident(T.relname)|| ';' as cmd
921 WHERE S.relkind = 'S'
923 AND D.refobjid = T.oid
924 AND D.refobjid = C.attrelid
925 AND D.refobjsubid = C.attnum
926 AND NS.oid = T.relnamespace
930 while ($cs->fetch()) {
933 foreach($cmds as $cmd) {
934 $cs = DB_DataObject::factory('core_enum');
941 var $extensions = array(
946 function runExtensions()
949 $ff = HTML_Flexyframework::get();
951 $dburl = parse_url($ff->DB_DataObject['database']);
953 $dbtype = $dburl['scheme'];
955 foreach($this->extensions as $ext) {
957 $scls = ucfirst($dbtype). $ext;
958 $cls = __CLASS__ . '_'. $scls;
959 $fn = implode('/',explode('_', $cls)).'.php';
960 if (!file_exists(__DIR__.'/UpdateDatabase/'. $scls .'.php')) {
971 function checkSystem()
973 // most of these are from File_Convert...
975 // these are required - and have simple dependancies.
976 require_once 'System.php';
982 'rsvg-convert', //librsvg2-bin
988 // these are prefered - but may have complicated depenacies
993 'html2text', // not availabe in debian squeeze
994 'pdftocairo', //poppler-utils - not available in debian squeeze.
1004 foreach($req as $r) {
1005 if (!System::which($r)) {
1011 $this->jerr("Missing these programs - need installing\n" . implode("\n",$res));
1013 foreach($pref as $r) {
1014 if (!System::which($r)) {
1020 echo "WARNING: Missing these programs - they may need installing\n". implode("\n",$res);