4 require_once 'Pman.php';
5 class Pman_Core_UpdateCurrencyRate extends Pman
8 static $cli_desc = "Update Currency Exchange Rate";
10 static $cli_opts = array(
14 static function cli_opts()
17 $ret = self::$cli_opts;
18 $ff = HTML_FlexyFramework::get();
20 $mods = $a->modulesList();
21 foreach($mods as $m) {
23 $fd = $ff->rootDir. "/Pman/$m/UpdateDatabase.php";
24 if (!file_exists($fd)) {
30 $cls = new ReflectionClass('Pman_'. $m . '_UpdateDatabase');
32 $ret = array_merge($ret, $cls->getStaticPropertyValue('cli_opts'));
47 $ff = HTML_FlexyFramework::get();
48 if (!empty($ff->cli)) {
53 parent::getAuth(); // load company!
54 $au = $this->getAuthUser();
55 if (!$au || $au->company()->comptype != 'OWNER') {
56 $this->jerr("Not authenticated", array('authFailure' => true));
58 $this->authUser = $au;
62 function get($args, $opts)
64 PEAR::setErrorHandling(PEAR_ERROR_CALLBACK, array($this, 'onPearError'));
67 //$this->fixSequencesPgsql();exit;
70 // ask all the modules to verify the opts
72 $this->checkOpts($opts);
76 if (empty($opts['data-only'])) {
79 if (!empty($opts['only-module-sql'])) {
83 $this->runUpdateModulesData();
86 if (!empty($opts['add-company'])) {
87 // make sure we have a good cache...?
89 DB_DataObject::factory('companies')->initCompanies($this, $opts);
97 * imports SQL files from all DataObjects directories....
99 * except any matching /migrate/
104 // loop through all the modules, and see if they have a importSQL method?
107 $ff = HTML_Flexyframework::get();
109 $dburl = parse_url($ff->DB_DataObject['database']);
111 //$this->{'import' . $url['scheme']}($url);
113 $dbtype = $dburl['scheme'];
114 $dirmethod = 'import' . $dburl['scheme'] . 'dir';
119 $ar = $this->modulesList();
123 echo "Importing SQL from module $m\n";
124 if (!empty($this->opts['only-module-sql']) && $m != $this->opts['only-module-sql']) {
129 // check to see if the class has
133 $file = $this->rootDir. "/Pman/$m/UpdateDatabase.php";
134 if($m != 'Core' && file_exists($file)){
137 $class = "Pman_{$m}_UpdateDatabase";
139 if(method_exists($x, 'importModuleSQL')){
140 echo "Importing SQL from module $m using Module::importModuleSQL\n";
141 $x->opts = $this->opts;
142 $x->rootDir = $this->rootDir;
143 $x->importModuleSQL($dburl);
148 echo "Importing SQL from module $m\n";
151 // if init has been called
153 if (!empty($this->opts['init'])) {
154 $this->{$dirmethod}($dburl, $this->rootDir. "/Pman/$m/{$dbtype}.init");
160 $fd = $this->rootDir. "/Pman/$m/DataObjects";
162 $this->{$dirmethod}($dburl, $fd);
164 // new -- sql directory..
165 // new style will not support migrate ... they have to go into mysql-migrate.... directories..
166 // new style will not support pg.sql etc.. naming - that's what the direcotries are for..
168 $this->{$dirmethod}($dburl, $this->rootDir. "/Pman/$m/sql");
169 $this->{$dirmethod}($dburl, $this->rootDir. "/Pman/$m/{$dbtype}");
173 if (!empty($this->opts['init']) && file_exists($this->rootDir. "/Pman/$m/{$dbtype}.initdata")) {
174 HTML_FlexyFramework::get()->generateDataobjectsCache(true);
176 $this->{$dirmethod}($dburl, $this->rootDir. "/Pman/$m/{$dbtype}.initdata");
177 $this->{'fixSequences'. $dbtype}();
189 /** -------------- code to handle importing a whole directory of files into the database ------- **/
192 function importpgsqldir($url, $dir, $disable_triggers = false)
194 $ff = HTML_FlexyFramework::get();
196 require_once 'System.php';
197 $cat = System::which('cat');
198 $psql = System::which('psql');
201 if (!empty($url['pass'])) {
202 putenv("PGPASSWORD=". $url['pass']);
206 ' -h ' . $url['host'] .
207 ' -U' . escapeshellarg($url['user']) .
208 ' ' . basename($url['path']);
211 echo $psql_cmd . "\n" ;
212 echo "scan : $dir\n";
214 $files = array($dir);
219 $files = glob($dir.'/*.sql');
220 uksort($files, 'strcasecmp');
222 //$lsort = create_function('$a,$b','return strlen($a) > strlen($b) ? 1 : -1;');
223 //usort($files, $lsort);
227 foreach($files as $bfn) {
230 if (preg_match('/migrate/i', basename($bfn))) { // skip migration scripts at present..
233 if (preg_match('#\.[a-z]{2}\.sql#i', basename($bfn))
234 && !preg_match('#\.pg\.sql#i', basename($bfn))
235 ) { // skip migration scripts at present..
240 if (!preg_match('/pgsql/', basename($dir) )) {
241 if ( !preg_match('#\.pg\.sql$#', basename($bfn))) {
242 $fn = $this->convertToPG($bfn);
246 // files ending in .pg.sql are native postgres files.. ## depricated
249 $cmd = "$psql_cmd < " . escapeshellarg($fn ? $fn : $bfn) . ' 2>&1' ;
251 echo "$bfn: $cmd ". ($ff->cli ? "\n" : "<BR>\n");
268 * mysql - does not support conversions.
274 function importmysqldir($dburl, $dir)
276 echo "Import MYSQL :: $dir\n";
279 require_once 'System.php';
280 $cat = System::which('cat');
281 $mysql = System::which('mysql');
285 $mysql_cmd = $mysql .
286 ' -h ' . $dburl['host'] .
287 ' -u' . escapeshellarg($dburl['user']) .
288 (!empty($dburl['pass']) ? ' -p' . escapeshellarg($dburl['pass']) : '') .
289 ' ' . basename($dburl['path']);
290 //echo $mysql_cmd . "\n" ;
292 $files = glob($dir.'/*.sql');
293 uksort($files, 'strcasecmp');
296 foreach($files as $fn) {
299 if (preg_match('/migrate/i', basename($fn))) { // skip migration scripts at present..
302 // .my.sql but not .pg.sql
303 if (preg_match('#\.[a-z]{2}\.sql#i', basename($fn))
304 && !preg_match('#\.my\.sql#i', basename($fn))
305 ) { // skip migration scripts at present..
308 if (!strlen(trim($fn))) {
312 $cmd = "$mysql_cmd -f < " . escapeshellarg($fn) ;
314 echo basename($dir).'/'. basename($fn) . '::' . $cmd. ($this->cli ? "\n" : "<BR>\n");
327 * simple regex based convert mysql to pgsql...
329 function convertToPG($src)
331 //echo "Convert $src\n";
333 $fn = $this->tempName('sql');
335 $ret = array( ); // pad it a bit.
336 $extra = array("", "" );
339 foreach(file($src) as $l) {
342 if (!strlen($l) || $l[0] == '#') {
346 if (preg_match('#create\s+table\s+([a-z0-9_]+)#i', $l, $m)) {
349 if (preg_match('#create\s+table\s+\`([a-z0-9_]+)\`#i', $l, $m)) {
350 $tbl = 'shop_' . strtolower($m[1]);
351 $l = preg_replace('#create\s+table\s+\`([a-z0-9_]+)\`#i', "CREATE TABLE {$tbl}", $l);
353 if (preg_match('#\`([a-z0-9_]+)\`#i', $l, $m) && !preg_match('#alter\s+table\s+#i', $l)) {
354 $l = preg_replace('#\`([a-z0-9_]+)\`#i', "{$m[1]}_name", $l);
357 if ($tbl && preg_match('#auto_increment#i', $l, $m)) {
358 $l = preg_replace('#auto_increment#i', "default nextval('{$tbl}_seq')", $l);
359 $extra[] = "create sequence {$tbl}_seq;";
363 if (preg_match('#alter\s+table\s+(\`[a-z0-9_]+\`)#i', $l, $m)){
364 $l = preg_replace('#alter\s+table\s+(\`[a-z0-9_]+\`)#i', "ALTER TABLE {$tbl}", $l);
367 // enum value -- use the text instead..
369 if ($tbl && preg_match('#([\w]+)\s+(enum\([\w|\W]+\))#i', $l, $m)) {
370 $l = preg_replace('#enum\([\w|\W]+\)#i', "TEXT", $l);
372 // ignore the alter enum
373 if ($tbl && preg_match('#alter\s+table\s+([\w|\W]+)\s+enum\([\w|\W]+\)#i', $l, $m)) {
377 // UNIQUE KEY .. ignore
378 if ($tbl && preg_match('#UNIQUE KEY#i', $l, $m)) {
379 $last = array_pop($ret);
380 $ret[] = trim($last, ",");
384 if ($tbl && preg_match('#RENAME\s+TO#i', $l, $m)) {
388 if ($tbl && preg_match('#change\s+column#i', $l, $m)) {
392 // INDEX lookup ..ignore
393 if ($tbl && preg_match('#INDEX lookup+([\w|\W]+)#i', $l, $m)) {
394 $last = array_pop($ret);
395 $ret[] = trim($last, ",");
400 // CREATE INDEX ..ignore
401 if (preg_match('#alter\s+table\s+([a-z0-9_]+)\s+add\s+index\s+#i', $l, $m)) {
402 // $l = "CREATE INDEX {$m[1]}_{$m[2]} ON {$m[1]} {$m[3]}";
407 $l = preg_replace('#int\([0-9]+\)#i', 'INT', $l);
409 $l = preg_replace('# datetime#i', ' TIMESTAMP WITHOUT TIME ZONE', $l);
410 $l = preg_replace('# blob#i', ' TEXT', $l);
411 $l = preg_replace('# longtext#i', ' TEXT', $l);
412 $l = preg_replace('# tinyint#i', ' INT', $l);
418 $ret = array_merge($extra,$ret);
419 // echo implode("\n", $ret); exit;
421 file_put_contents($fn, implode("\n", $ret));
427 function checkOpts($opts)
431 foreach($opts as $o=>$v) {
432 if (!preg_match('/^json-/', $o) || empty($v)) {
435 if (!file_exists($v)) {
436 die("File does not exist : OPTION --{$o} = {$v} \n");
440 $modules = array_reverse($this->modulesList());
442 // move 'project' one to the end...
444 foreach ($modules as $module){
445 $file = $this->rootDir. "/Pman/$module/UpdateDatabase.php";
446 if($module == 'Core' || !file_exists($file)){
450 $class = "Pman_{$module}_UpdateDatabase";
452 if(!method_exists($x, 'checkOpts')){
455 $x->checkOpts($opts);
459 static function jsonImportFromArray($opts)
461 foreach($opts as $o=>$v) {
462 if (!preg_match('/^json-/', $o) || empty($v)) {
465 $type = str_replace('_', '-', substr($o,5));
467 $data= json_decode(file_get_contents($v),true);
468 $pg = HTML_FlexyFramework::get()->page;
469 DB_DataObject::factory($type)->importFromArray($pg ,$data,$opts);
479 function runUpdateModulesData()
483 HTML_FlexyFramework::get()->generateDataobjectsCache(true);
484 echo "Running jsonImportFromArray\n";
485 Pman_Core_UpdateDatabase::jsonImportFromArray($this->opts);
488 echo "Running updateData on modules\n";
492 $modules = array_reverse($this->modulesList());
494 // move 'project' one to the end...
496 foreach ($modules as $module){
497 $file = $this->rootDir. "/Pman/$module/UpdateDatabase.php";
498 if($module == 'Core' || !file_exists($file)){
503 $class = "Pman_{$module}_UpdateDatabase";
505 if(!method_exists($x, 'updateData')){
515 function updateDataEnums()
518 $enum = DB_DataObject::Factory('core_enum');
519 //DB_DAtaObject::debugLevel(1);
524 'name' => 'COMPTYPE',
525 'display_name' => 'Company Types',
526 'is_system_enum' => 1,
530 'display_name' => 'Owner',
531 'seqid' => 999, // last...
532 'is_system_enum' => 1,
539 'name' => 'HtmlEditor.font-family',
540 'display_name' => 'HTML Editor font families',
541 'is_system_enum' => 1,
544 'name' => 'Helvetica,Arial,sans-serif',
545 'display_name' => 'Helvetica',
550 'name' => 'Courier New',
551 'display_name' => 'Courier',
556 'display_name' => 'Tahoma',
560 'name' => 'Times New Roman,serif',
561 'display_name' => 'Times',
566 'display_name' => 'Verdana',
578 function updateDataGroups()
581 $groups = DB_DataObject::factory('groups');
582 $groups->initGroups();
584 $groups->initDatabase($this,array(
586 'name' => 'bcc-email', // group who are bcc'ed on all requests.
587 'type' => 0, // system
590 'name' => 'system-email-from',
591 'type' => 0, // system
597 function updateDataCompanies()
600 // fix comptypes enums..
601 $c = DB_DataObject::Factory('Companies');
603 $c->selectAdd('distinct(comptype) as comptype');
604 $c->whereAdd("comptype != ''");
607 foreach($c->fetchAll('comptype') as $cts) {
611 $ctb[]= array( 'etype'=>'COMPTYPE', 'name' => $cts, 'display_name' => ucfirst(strtolower($cts)));
614 $c = DB_DataObject::Factory('core_enum');
617 //DB_DataObject::debugLevel(1);
619 $c = DB_DataObject::Factory('Companies');
623 comptype_id = (SELECT id FROM core_enum where etype='comptype' and name=Companies.comptype LIMIT 1)
636 function updateData()
639 HTML_FlexyFramework::get()->generateDataobjectsCache(true);
640 $this->updateDataEnums();
641 $this->updateDataGroups();
642 $this->updateDataCompanies();
644 $c = DB_DataObject::Factory('I18n');
652 /** ------------- schema fixing ... there is an issue with data imported having the wrong sequence names... --- */
654 function fixSequencesMysql()
659 function fixSequencesPgsql()
663 //DB_DataObject::debugLevel(1);
664 $cs = DB_DataObject::factory('core_enum');
668 CASE WHEN strpos(seq_name, '.') > 0 THEN
671 quote_ident(min(schema_name)) ||'.'|| quote_ident(min(seq_name))
674 ||' OWNED BY '|| quote_ident(min(schema_name)) || '.' ||
675 quote_ident(min(table_name)) ||'.'|| quote_ident(min(column_name)) ||';' as cmd
679 n.nspname AS schema_name,
680 c.relname AS table_name,
681 a.attname AS column_name,
682 regexp_replace(regexp_replace(d.adsrc, E'nextval\\\\(+[''\\\"]*', ''),E'[''\\\"]*::.*\$','') AS seq_name
684 JOIN pg_attribute a ON (c.oid=a.attrelid)
685 JOIN pg_attrdef d ON (a.attrelid=d.adrelid AND a.attnum=d.adnum)
686 JOIN pg_namespace n ON (c.relnamespace=n.oid)
687 WHERE has_schema_privilege(n.oid,'USAGE')
688 AND n.nspname NOT LIKE 'pg!_%' escape '!'
689 AND has_table_privilege(c.oid,'SELECT')
690 AND (NOT a.attisdropped)
691 AND d.adsrc ~ '^nextval'
695 CASE WHEN strpos(seq_name, '.') > 0 THEN
696 substring(seq_name, 1,strpos(seq_name,'.')-1)
701 GROUP BY seq_name HAVING count(*)=1
704 while ($cs->fetch()) {
707 foreach($cmds as $cmd) {
708 $cs = DB_DataObject::factory('core_enum');
712 $cs = DB_DataObject::factory('core_enum');
714 SELECT 'SELECT SETVAL(' ||
715 quote_literal(quote_ident(nspname) || '.' || quote_ident(S.relname)) ||
716 ', MAX(' || quote_ident(C.attname)|| ')::integer ) FROM ' || nspname || '.' || quote_ident(T.relname)|| ';' as cmd
722 WHERE S.relkind = 'S'
724 AND D.refobjid = T.oid
725 AND D.refobjid = C.attrelid
726 AND D.refobjsubid = C.attnum
727 AND NS.oid = T.relnamespace
731 while ($cs->fetch()) {
734 foreach($cmds as $cmd) {
735 $cs = DB_DataObject::factory('core_enum');