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 $x = new Pman_Core_NotifySmtpCheck();
145 $this->disabled = explode(',', $ff->disable);
147 //$this->fixSequencesPgsql();exit;
150 // ask all the modules to verify the opts
152 $this->checkOpts($opts);
154 if (empty($opts['data-only'])) {
157 if (!empty($opts['only-module-sql'])) {
161 $this->runUpdateModulesData();
164 if (!empty($opts['add-company']) && !in_array('Core', $this->disabled)) {
165 // make sure we have a good cache...?
167 DB_DataObject::factory('companies')->initCompanies($this, $opts);
170 $this->runExtensions();
178 * imports SQL files from all DataObjects directories....
180 * except any matching /migrate/
185 // loop through all the modules, and see if they have a importSQL method?
188 $ff = HTML_Flexyframework::get();
190 $dburl = parse_url($ff->DB_DataObject['database']);
192 //$this->{'import' . $url['scheme']}($url);
194 $dbtype = $dburl['scheme'];
195 $dirmethod = 'import' . $dburl['scheme'] . 'dir';
200 $ar = $this->modulesList();
204 if(in_array($m, $this->disabled)){
205 echo "module $m is disabled \n";
209 echo "Importing SQL from module $m\n";
210 if (!empty($this->opts['only-module-sql']) && $m != $this->opts['only-module-sql']) {
215 // check to see if the class has
219 $file = $this->rootDir. "/Pman/$m/UpdateDatabase.php";
220 if($m != 'Core' && file_exists($file)){
223 $class = "Pman_{$m}_UpdateDatabase";
225 if(method_exists($x, 'importModuleSQL')){
226 echo "Importing SQL from module $m using Module::importModuleSQL\n";
227 $x->opts = $this->opts;
228 $x->rootDir = $this->rootDir;
229 $x->importModuleSQL($dburl);
234 echo "Importing SQL from module $m\n";
237 // if init has been called
239 if (!empty($this->opts['init'])) {
240 $this->{$dirmethod}($dburl, $this->rootDir. "/Pman/$m/{$dbtype}.init");
246 $fd = $this->rootDir. "/Pman/$m/DataObjects";
248 $this->{$dirmethod}($dburl, $fd);
251 // new -- sql directory..
252 // new style will not support migrate ... they have to go into mysql-migrate.... directories..
253 // new style will not support pg.sql etc.. naming - that's what the direcotries are for..
255 $this->{$dirmethod}($dburl, $this->rootDir. "/Pman/$m/sql");
256 $this->{$dirmethod}($dburl, $this->rootDir. "/Pman/$m/{$dbtype}");
260 if (!empty($this->opts['init']) && file_exists($this->rootDir. "/Pman/$m/{$dbtype}.initdata")) {
261 HTML_FlexyFramework::get()->generateDataobjectsCache(true);
263 $this->{$dirmethod}($dburl, $this->rootDir. "/Pman/$m/{$dbtype}.initdata");
264 $this->{'fixSequences'. $dbtype}();
276 /** -------------- code to handle importing a whole directory of files into the database ------- **/
279 function importpgsqldir($url, $dir, $disable_triggers = false)
281 $ff = HTML_FlexyFramework::get();
283 require_once 'System.php';
284 $cat = System::which('cat');
285 $psql = System::which('psql');
288 if (!empty($url['pass'])) {
289 putenv("PGPASSWORD=". $url['pass']);
293 ' -h ' . $url['host'] .
294 ' -U' . escapeshellarg($url['user']) .
295 ' ' . basename($url['path']);
298 echo $psql_cmd . "\n" ;
299 echo "scan : $dir\n";
302 $files = array($dir);
307 $files = glob($dir.'/*.sql');
308 uksort($files, 'strcasecmp');
310 //$lsort = create_function('$a,$b','return strlen($a) > strlen($b) ? 1 : -1;');
311 //usort($files, $lsort);
314 foreach($files as $bfn) {
317 if (preg_match('/migrate/i', basename($bfn))) { // skip migration scripts at present..
320 if (preg_match('#\.[a-z]{2}\.sql#i', basename($bfn))
321 && !preg_match('#\.pg\.sql#i', basename($bfn))
322 ) { // skip migration scripts at present..
327 if (!preg_match('/pgsql/', basename($dir) )) {
328 if ( !preg_match('#\.pg\.sql$#', basename($bfn))) {
329 $fn = $this->convertToPG($bfn);
333 // files ending in .pg.sql are native postgres files.. ## depricated
336 $cmd = "$psql_cmd < " . escapeshellarg($fn ? $fn : $bfn) . ' 2>&1' ;
338 echo "$bfn: $cmd ". ($ff->cli ? "\n" : "<BR>\n");
354 * mysql - does not support conversions.
360 function importmysqldir($dburl, $dir)
363 $this->fixMysqlInnodb(); /// run once
365 echo "Import MYSQL :: $dir\n";
368 require_once 'System.php';
369 $cat = System::which('cat');
370 $mysql = System::which('mysql');
374 $mysql_cmd = $mysql .
375 ' -h ' . $dburl['host'] .
376 ' -u' . escapeshellarg($dburl['user']) .
377 (!empty($dburl['pass']) ? ' -p' . escapeshellarg($dburl['pass']) : '') .
378 ' ' . basename($dburl['path']);
379 //echo $mysql_cmd . "\n" ;
381 $files = glob($dir.'/*.sql');
382 uksort($files, 'strcasecmp');
385 foreach($files as $fn) {
388 if (preg_match('/migrate/i', basename($fn))) { // skip migration scripts at present..
391 // .my.sql but not .pg.sql
392 if (preg_match('#\.[a-z]{2}\.sql#i', basename($fn))
393 && !preg_match('#\.my\.sql#i', basename($fn))
394 ) { // skip migration scripts at present..
397 if (!strlen(trim($fn))) {
401 $cmd = "$mysql_cmd -f < " . escapeshellarg($fn) ;
403 echo basename($dir).'/'. basename($fn) . '::' . $cmd. ($this->cli ? "\n" : "<BR>\n");
416 * simple regex based convert mysql to pgsql...
418 function convertToPG($src)
420 //echo "Convert $src\n";
422 $fn = $this->tempName('sql');
424 $ret = array( ); // pad it a bit.
425 $extra = array("", "" );
428 foreach(file($src) as $l) {
431 if (!strlen($l) || $l[0] == '#') {
435 if (preg_match('#create\s+table\s+([a-z0-9_]+)#i', $l, $m)) {
438 if (preg_match('#create\s+table\s+\`([a-z0-9_]+)\`#i', $l, $m)) {
439 $tbl = 'shop_' . strtolower($m[1]);
440 $l = preg_replace('#create\s+table\s+\`([a-z0-9_]+)\`#i', "CREATE TABLE {$tbl}", $l);
442 if (preg_match('#\`([a-z0-9_]+)\`#i', $l, $m) && !preg_match('#alter\s+table\s+#i', $l)) {
443 $l = preg_replace('#\`([a-z0-9_]+)\`#i', "{$m[1]}_name", $l);
446 if ($tbl && preg_match('#auto_increment#i', $l, $m)) {
447 $l = preg_replace('#auto_increment#i', "default nextval('{$tbl}_seq')", $l);
448 $extra[] = "create sequence {$tbl}_seq;";
452 if (preg_match('#alter\s+table\s+(\`[a-z0-9_]+\`)#i', $l, $m)){
453 $l = preg_replace('#alter\s+table\s+(\`[a-z0-9_]+\`)#i', "ALTER TABLE {$tbl}", $l);
456 // enum value -- use the text instead..
458 if ($tbl && preg_match('#([\w]+)\s+(enum\([\w|\W]+\))#i', $l, $m)) {
459 $l = preg_replace('#enum\([\w|\W]+\)#i', "TEXT", $l);
461 // ignore the alter enum
462 if ($tbl && preg_match('#alter\s+table\s+([\w|\W]+)\s+enum\([\w|\W]+\)#i', $l, $m)) {
466 // UNIQUE KEY .. ignore
467 if ($tbl && preg_match('#UNIQUE KEY#i', $l, $m)) {
468 $last = array_pop($ret);
469 $ret[] = trim($last, ",");
473 if ($tbl && preg_match('#RENAME\s+TO#i', $l, $m)) {
477 if ($tbl && preg_match('#change\s+column#i', $l, $m)) {
481 // INDEX lookup ..ignore
482 if ($tbl && preg_match('#INDEX lookup+([\w|\W]+)#i', $l, $m)) {
483 $last = array_pop($ret);
484 $ret[] = trim($last, ",");
489 // CREATE INDEX ..ignore
490 if (preg_match('#alter\s+table\s+([a-z0-9_]+)\s+add\s+index\s+#i', $l, $m)) {
491 // $l = "CREATE INDEX {$m[1]}_{$m[2]} ON {$m[1]} {$m[3]}";
496 $l = preg_replace('#int\([0-9]+\)#i', 'INT', $l);
498 $l = preg_replace('# datetime#i', ' TIMESTAMP WITHOUT TIME ZONE', $l);
499 $l = preg_replace('# blob#i', ' TEXT', $l);
500 $l = preg_replace('# longtext#i', ' TEXT', $l);
501 $l = preg_replace('# tinyint#i', ' INT', $l);
507 $ret = array_merge($extra,$ret);
508 // echo implode("\n", $ret); exit;
510 file_put_contents($fn, implode("\n", $ret));
516 function checkOpts($opts)
520 foreach($opts as $o=>$v) {
521 if (!preg_match('/^json-/', $o) || empty($v)) {
524 if (!file_exists($v)) {
525 die("File does not exist : OPTION --{$o} = {$v} \n");
529 $modules = array_reverse($this->modulesList());
531 // move 'project' one to the end...
533 foreach ($modules as $module){
534 $file = $this->rootDir. "/Pman/$module/UpdateDatabase.php";
535 if($module == 'Core' || !file_exists($file)){
539 $class = "Pman_{$module}_UpdateDatabase";
541 if(!method_exists($x, 'checkOpts')){
544 $x->checkOpts($opts);
548 static function jsonImportFromArray($opts)
550 foreach($opts as $o=>$v) {
551 if (!preg_match('/^json-/', $o) || empty($v)) {
554 $type = str_replace('_', '-', substr($o,5));
556 $data= json_decode(file_get_contents($v),true);
557 $pg = HTML_FlexyFramework::get()->page;
558 DB_DataObject::factory($type)->importFromArray($pg ,$data,$opts);
568 function runUpdateModulesData()
570 HTML_FlexyFramework::get()->generateDataobjectsCache(true);
572 if(!in_array('Core', $this->disabled)){
573 echo "Running jsonImportFromArray\n";
574 Pman_Core_UpdateDatabase::jsonImportFromArray($this->opts);
577 echo "Running updateData on modules\n";
583 $modules = array_reverse($this->modulesList());
585 // move 'project' one to the end...
587 foreach ($modules as $module){
588 if(in_array($module, $this->disabled)){
591 $file = $this->rootDir. "/Pman/$module/UpdateDatabase.php";
592 if($module == 'Core' || !file_exists($file)){
597 $class = "Pman_{$module}_UpdateDatabase";
599 if(!method_exists($x, 'updateData')){
609 function updateDataEnums()
612 $enum = DB_DataObject::Factory('core_enum');
613 //DB_DAtaObject::debugLevel(1);
618 'name' => 'COMPTYPE',
619 'display_name' => 'Company Types',
620 'is_system_enum' => 1,
624 'display_name' => 'Owner',
625 'seqid' => 999, // last...
626 'is_system_enum' => 1,
633 'name' => 'HtmlEditor.font-family',
634 'display_name' => 'HTML Editor font families',
635 'is_system_enum' => 1,
638 'name' => 'Helvetica,Arial,sans-serif',
639 'display_name' => 'Helvetica',
644 'name' => 'Courier New',
645 'display_name' => 'Courier',
650 'display_name' => 'Tahoma',
654 'name' => 'Times New Roman,serif',
655 'display_name' => 'Times',
660 'display_name' => 'Verdana',
672 function updateDataGroups()
675 $groups = DB_DataObject::factory('groups');
676 $groups->initGroups();
678 $groups->initDatabase($this,array(
680 'name' => 'bcc-email', // group who are bcc'ed on all requests.
681 'type' => 0, // system
684 'name' => 'system-email-from',
685 'type' => 0, // system
688 'name' => 'core-person-signup-bcc',
689 'type' => 0, // system
695 function updateDataCompanies()
698 // fix comptypes enums..
699 $c = DB_DataObject::Factory('Companies');
701 $c->selectAdd('distinct(comptype) as comptype');
702 $c->whereAdd("comptype != ''");
705 foreach($c->fetchAll('comptype') as $cts) {
709 $ctb[]= array( 'etype'=>'COMPTYPE', 'name' => $cts, 'display_name' => ucfirst(strtolower($cts)));
712 $c = DB_DataObject::Factory('core_enum');
715 //DB_DataObject::debugLevel(1);
717 $c = DB_DataObject::Factory('Companies');
721 comptype_id = (SELECT id FROM core_enum where etype='comptype' and name=Companies.comptype LIMIT 1)
735 function initEmails($templateDir, $emails)
738 $pg = HTML_FlexyFramework::get()->page;
739 foreach($emails as $name=>$data) {
740 $cm = DB_DataObject::factory('core_email');
741 $update = $cm->get('name', $name);
744 if (empty($cm->bcc_group)) {
745 if (empty($data['bcc_group'])) {
746 $this->jerr("missing bcc_group for template $name");
748 $g = DB_DataObject::Factory('Groups')->lookup('name',$data['bcc_group']);
751 $this->jerr("bcc_group {$data['bcc_group']} does not exist when importing template $name");
753 if (!$g->members('email')) {
754 $this->jerr("bcc_group {$data['bcc_group']} does not have any members");
758 $cm->bcc_group = $g->id;
760 if (empty($cm->test_class)) {
761 if (empty($data['test_class'])) {
762 $this->jerr("missing test_class for template $name");
764 $cm->test_class = $data['test_class'];
766 require_once $cm->test_class . '.php';
768 $clsname = str_replace('/','_', $cm->test_class);
770 $method = new ReflectionMethod($clsname , 'test_'. $name) ;
771 $got_it = $method->isStatic();
772 } catch(Exception $e) {
777 $this->jerr("template {$name} does not have a test method {$clsname}::test_{$name}");
781 echo "email: {$name} - checked\n";
782 continue; /// we do not import the body content of templates that exist...
788 // $basedir = $this->bootLoader->rootDir . $mail_template_dir;
792 'file' => $templateDir. $name .'.html'
795 if (!empty($data['master'])) {
796 $opts['master'] = $templateDir . $master .'.html';
798 require_once 'Pman/Core/Import/Core_email.php';
799 $x = new Pman_Core_Import_Core_email();
802 echo "email: {$name} - CREATED\n";
807 function updateData()
810 HTML_FlexyFramework::get()->generateDataobjectsCache(true);
811 $this->updateDataEnums();
812 $this->updateDataGroups();
813 $this->updateDataCompanies();
815 $c = DB_DataObject::Factory('I18n');
823 function fixMysqlInnodb()
826 static $done_check = false;
830 // innodb in single files is far more efficient that MYD or one big innodb file.
831 // first check if database is using this format.
832 $db = DB_DataObject::factory('core_enum');
833 $db->query("show variables like 'innodb_file_per_table'");
835 if ($db->Value == 'OFF') {
836 die("Error: set innodb_file_per_table = 1 in my.cnf\n\n");
850 /** ------------- schema fixing ... there is an issue with data imported having the wrong sequence names... --- */
852 function fixSequencesMysql()
857 function fixSequencesPgsql()
861 //DB_DataObject::debugLevel(1);
862 $cs = DB_DataObject::factory('core_enum');
866 CASE WHEN strpos(seq_name, '.') > 0 THEN
869 quote_ident(min(schema_name)) ||'.'|| quote_ident(min(seq_name))
872 ||' OWNED BY '|| quote_ident(min(schema_name)) || '.' ||
873 quote_ident(min(table_name)) ||'.'|| quote_ident(min(column_name)) ||';' as cmd
877 n.nspname AS schema_name,
878 c.relname AS table_name,
879 a.attname AS column_name,
880 regexp_replace(regexp_replace(d.adsrc, E'nextval\\\\(+[''\\\"]*', ''),E'[''\\\"]*::.*\$','') AS seq_name
882 JOIN pg_attribute a ON (c.oid=a.attrelid)
883 JOIN pg_attrdef d ON (a.attrelid=d.adrelid AND a.attnum=d.adnum)
884 JOIN pg_namespace n ON (c.relnamespace=n.oid)
885 WHERE has_schema_privilege(n.oid,'USAGE')
886 AND n.nspname NOT LIKE 'pg!_%' escape '!'
887 AND has_table_privilege(c.oid,'SELECT')
888 AND (NOT a.attisdropped)
889 AND d.adsrc ~ '^nextval'
893 CASE WHEN strpos(seq_name, '.') > 0 THEN
894 substring(seq_name, 1,strpos(seq_name,'.')-1)
899 GROUP BY seq_name HAVING count(*)=1
902 while ($cs->fetch()) {
905 foreach($cmds as $cmd) {
906 $cs = DB_DataObject::factory('core_enum');
910 $cs = DB_DataObject::factory('core_enum');
912 SELECT 'SELECT SETVAL(' ||
913 quote_literal(quote_ident(nspname) || '.' || quote_ident(S.relname)) ||
914 ', MAX(' || quote_ident(C.attname)|| ')::integer ) FROM ' || nspname || '.' || quote_ident(T.relname)|| ';' as cmd
920 WHERE S.relkind = 'S'
922 AND D.refobjid = T.oid
923 AND D.refobjid = C.attrelid
924 AND D.refobjsubid = C.attnum
925 AND NS.oid = T.relnamespace
929 while ($cs->fetch()) {
932 foreach($cmds as $cmd) {
933 $cs = DB_DataObject::factory('core_enum');
940 var $extensions = array(
945 function runExtensions()
948 $ff = HTML_Flexyframework::get();
950 $dburl = parse_url($ff->DB_DataObject['database']);
952 $dbtype = $dburl['scheme'];
954 foreach($this->extensions as $ext) {
956 $scls = ucfirst($dbtype). $ext;
957 $cls = __CLASS__ . '_'. $scls;
958 $fn = implode('/',explode('_', $cls)).'.php';
959 if (!file_exists(__DIR__.'/UpdateDatabase/'. $scls .'.php')) {
970 function checkSystem()
972 // most of these are from File_Convert...
974 // these are required - and have simple dependancies.
975 require_once 'System.php';
981 'rsvg-convert', //librsvg2-bin
987 // these are prefered - but may have complicated depenacies
992 'html2text', // not availabe in debian squeeze
993 'pdftocairo', //poppler-utils - not available in debian squeeze.
1003 foreach($req as $r) {
1004 if (!System::which($r)) {
1010 $this->jerr("Missing these programs - need installing\n" . implode("\n",$res));
1012 foreach($pref as $r) {
1013 if (!System::which($r)) {
1019 echo "WARNING: Missing these programs - they may need installing\n". implode("\n",$res);