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 'skip-mysql-checks' => array(
65 'desc' => 'Skip mysql checks',
70 'procedures-only' => array(
71 'desc' => 'Only import procedures (not supported by most modules yet) - ignores sql directory',
77 'json-person' => array(
78 'desc' => 'Person JSON file',
85 'desc' => 'Debug the database',
94 static function cli_opts()
97 $ret = self::$cli_opts;
98 $ff = HTML_FlexyFramework::get();
100 $mods = $a->modulesList();
101 foreach($mods as $m) {
103 $fd = $ff->rootDir. "/Pman/$m/UpdateDatabase.php";
104 if (!file_exists($fd)) {
110 $cls = new ReflectionClass('Pman_'. $m . '_UpdateDatabase');
111 $ar = $cls->getStaticProperties();
112 if (isset($ar['cli_opts'])) {
114 $ret = array_merge($ret, $cls->getStaticPropertyValue('cli_opts'));
122 var $disabled = array();
127 var $local_base_url = false;
129 var $emailTemplates = array(
130 'EVENT_ERRORS_REPORT' => array(
131 'bcc_group' => 'Empty Group',
132 'test_class' => 'Pman/Admin/Report/SendEventErrors',
133 'to_group' => 'Administrators',
135 'description' => '9. System Error Messages',
136 'template_dir' => '/Pman/Admin/templates/mail/'
143 $ff = HTML_FlexyFramework::get();
144 if (!empty($ff->cli)) {
149 parent::getAuth(); // load company!
150 $au = $this->getAuthUser();
151 if (!$au || $au->company()->comptype != 'OWNER') {
152 $this->jerr("Not authenticated", array('authFailure' => true));
154 $this->authUser = $au;
158 function get($args, $opts=array())
160 PEAR::setErrorHandling(PEAR_ERROR_CALLBACK, array($this, 'onPearError'));
162 $this->checkSystem();
164 $this->verifyExtensions(array('curl'));
166 if (class_exists('PDO_DataObjects_Introspection')) {
167 PDO_DataObject_Introspection::$cache = array();
169 echo "Generate DB cache\n";
170 HTML_FlexyFramework::get()->generateDataobjectsCache(true);
171 echo "Generated DB cache\n";
172 $ff = HTML_FlexyFramework::get();
174 if(!isset($ff->Pman) || !isset($ff->Pman['local_base_url'])){
175 die("Please setup Pman[local_base_url]\n");
178 $this->local_base_url = $ff->Pman['local_base_url'];
180 if(!empty($ff->Core_Notify)){
181 // require_once 'Pman/Core/NotifySmtpCheck.php';
182 // $x = new Pman_Core_NotifySmtpCheck();
186 $this->disabled = explode(',', $ff->disable);
188 //$this->fixSequencesPgsql();exit;
191 if (!empty($opts['debug'])) {
192 DB_DataObject::DebugLevel($opts['debug']);
195 // ask all the modules to verify the opts
196 echo "Checking options\n";
197 $this->checkOpts($opts);
199 $response = $this->curl("http://localhost{$this->local_base_url}/Core/UpdateDatabase/VerifyExtensions");
200 $json = json_decode($response, true);
202 if(empty($json['data']) || $json['data'] != 'DONE'){
203 echo "\nError: Missing php extensions:\n";
204 print_r($json['errorMsg']);
205 echo "Please install the above extensions and restart the apache.\n";
209 echo "Checking Setup Requirements\n";
210 require_once 'Pman/Core/UpdateDatabase/VerifyVariable.php';
211 $sq = new Pman_Core_UpdateDatabase_VerifyVariable();
214 // do this first, so the innodb change + utf8 fixes column max sizes
216 // this will trigger errors about freetext indexes - we will have to remove them manually.?
217 // 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..)
219 $this->runExtensions();
222 if (empty($opts['data-only'])) {
225 if (!empty($opts['only-module-sql'])) {
231 $this->runUpdateModulesData();
233 if (!empty($opts['add-company']) && !in_array('Core', $this->disabled)) {
234 // make sure we have a good cache...?
236 DB_DataObject::factory('core_company')->initCompanies($this, $opts);
239 $this->runExtensions();
241 $this->clearApacheDataobjectsCache();
243 $this->clearApacheAssetCache();
247 echo "\nUpdate Completed SUCCESS\n";
251 * imports SQL files from all DataObjects directories....
253 * except any matching /migrate/
258 // loop through all the modules, and see if they have a importSQL method?
261 $ff = HTML_Flexyframework::get();
263 $dburl = parse_url($ff->database); // used to be DB_DataObject['database'] - but not portable to PDO
265 //$this->{'import' . $url['scheme']}($url);
267 $dbtype = $dburl['scheme'];
270 $dirmethod = 'import' . $dburl['scheme'] . 'dir';
275 $ar = $this->modulesList();
280 if(in_array($m, $this->disabled)){
281 echo "module $m is disabled \n";
285 echo "Importing SQL from module $m\n";
286 if (!empty($this->opts['only-module-sql']) && $m != $this->opts['only-module-sql']) {
291 // check to see if the class has
295 $file = $this->rootDir. "/Pman/$m/UpdateDatabase.php";
296 if($m != 'Core' && file_exists($file)){
299 $class = "Pman_{$m}_UpdateDatabase";
301 if(method_exists($x, 'importModuleSQL')){
302 echo "Importing SQL from module $m using Module::importModuleSQL\n";
303 $x->opts = $this->opts;
304 $x->rootDir = $this->rootDir;
305 $x->importModuleSQL($dburl);
310 echo "Importing SQL from module $m\n";
313 // if init has been called
315 if (!empty($this->opts['init'])) {
316 $this->{$dirmethod}($dburl, $this->rootDir. "/Pman/$m/{$dbtype}.init");
322 $fd = $this->rootDir. "/Pman/$m/DataObjects";
324 $this->{$dirmethod}($dburl, $fd);
327 // new -- sql directory..
328 // new style will not support migrate ... they have to go into mysql-migrate.... directories..
329 // new style will not support pg.sql etc.. naming - that's what the direcotries are for..
330 $dbdir = $dbtype == 'mysqli' ? 'mysql' : $dbtype;
332 $this->{$dirmethod}($dburl, $this->rootDir. "/Pman/$m/sql");
333 $this->{$dirmethod}($dburl, $this->rootDir. "/Pman/$m/{$dbdir}");
337 if (!empty($this->opts['init']) && file_exists($this->rootDir. "/Pman/$m/{$dbtype}.initdata")) {
338 if (class_exists('PDO_DataObjects_Introspection')) {
339 PDO_DataObject_Introspection::$cache = array();
341 HTML_FlexyFramework::get()->generateDataobjectsCache(true);
343 $this->{$dirmethod}($dburl, $this->rootDir. "/Pman/$m/{$dbtype}.initdata");
344 $this->{'fixSequences'. $dbtype}();
357 /** -------------- code to handle importing a whole directory of files into the database ------- **/
360 function importpgsqldir($url, $dir, $disable_triggers = false)
362 $ff = HTML_FlexyFramework::get();
364 require_once 'System.php';
365 $cat = System::which('cat');
366 $psql = System::which('psql');
369 if (!empty($url['pass'])) {
370 putenv("PGPASSWORD=". $url['pass']);
374 ' -h ' . $url['host'] .
375 ' -U' . escapeshellarg($url['user']) .
376 ' ' . basename($url['path']);
379 echo $psql_cmd . "\n" ;
380 echo "scan : $dir\n";
383 $files = array($dir);
388 $files = glob($dir.'/*.sql');
389 uksort($files, 'strcasecmp');
391 //$lsort = create_function('$a,$b','return strlen($a) > strlen($b) ? 1 : -1;');
392 //usort($files, $lsort);
395 foreach($files as $bfn) {
398 if (preg_match('/migrate/i', basename($bfn))) { // skip migration scripts at present..
401 if (preg_match('#\.[a-z]{2}\.sql#i', basename($bfn))
402 && !preg_match('#\.pg\.sql#i', basename($bfn))
403 ) { // skip migration scripts at present..
408 if (!preg_match('/pgsql/', basename($dir) )) {
409 if ( !preg_match('#\.pg\.sql$#', basename($bfn))) {
410 $fn = $this->convertToPG($bfn);
414 // files ending in .pg.sql are native postgres files.. ## depricated
417 $cmd = "$psql_cmd < " . escapeshellarg($fn ? $fn : $bfn) . ' 2>&1' ;
419 echo "$bfn: $cmd ". ($ff->cli ? "\n" : "<BR>\n");
435 * mysql - does not support conversions.
439 function importmysqlidir($dburl, $dir) {
440 return $this->importmysqldir($dburl, $dir);
443 function importmysqldir($dburl, $dir)
446 $this->fixMysqlInnodb(); /// run once
448 echo "Import MYSQL :: $dir\n";
451 require_once 'System.php';
452 $cat = System::which('cat');
453 $mysql = System::which('mysql');
457 $mysql_cmd = $mysql .
458 ' -h ' . $dburl['host'] .
459 ' -u' . escapeshellarg($dburl['user']) .
460 (!empty($dburl['pass']) ? ' -p' . escapeshellarg($dburl['pass']) : '') .
461 ' ' . basename($dburl['path']);
462 //echo $mysql_cmd . "\n" ;
464 $files = glob($dir.'/*.sql');
465 uksort($files, 'strcasecmp');
468 foreach($files as $fn) {
471 if (preg_match('/migrate/i', basename($fn))) { // skip migration scripts at present..
474 // .my.sql but not .pg.sql
475 if (preg_match('#\.[a-z]{2}\.sql#i', basename($fn))
476 && !preg_match('#\.my\.sql#i', basename($fn))
477 ) { // skip migration scripts at present..
480 if (!strlen(trim($fn))) {
484 $cmd = "$mysql_cmd -f < " . escapeshellarg($fn) ." 2>&1" ;
486 echo basename($dir).'/'. basename($fn) . '::' . $cmd. ($this->cli ? "\n" : "<BR>\n");
489 $fp = popen($cmd, "r");
492 // send the current file part to the browser
493 $line = trim(fgets($fp, 1024));
498 if (!preg_match('/^ERROR\s+([0-9]+)/', $line, $matches)) {
499 echo " ---- {$line}\n"; flush();
503 switch($matches[1]) {
504 case 1017: // cause by renaming table -- old one does not exist..
505 case 1050: // create tables triggers this..
506 case 1060: // Duplicate column name
507 case 1061: // Duplicate key name - triggered by add index.. but could hide error. - unlikely though.
508 case 1091: // drop index -- name does not exist.. might hide errors..
510 case 1146: // drop a index on an unknown table.. - happens rarely...
511 case 1054: // Unknown column -- triggered by CHANGE COLUMN - but may hide other errrors..
517 echo " ---- {$line}\n"; flush();
521 // 1051: // Unknown table -- normally drop = add iff exists..
522 echo "File: $fn\n$line\n";
538 * simple regex based convert mysql to pgsql...
540 function convertToPG($src)
542 //echo "Convert $src\n";
544 $fn = $this->tempName('sql');
546 $ret = array( ); // pad it a bit.
547 $extra = array("", "" );
550 foreach(file($src) as $l) {
553 if (!strlen($l) || $l[0] == '#') {
557 if (preg_match('#create\s+table\s+([a-z0-9_]+)#i', $l, $m)) {
560 if (preg_match('#create\s+table\s+\`([a-z0-9_]+)\`#i', $l, $m)) {
561 $tbl = 'shop_' . strtolower($m[1]);
562 $l = preg_replace('#create\s+table\s+\`([a-z0-9_]+)\`#i', "CREATE TABLE {$tbl}", $l);
564 if (preg_match('#\`([a-z0-9_]+)\`#i', $l, $m) && !preg_match('#alter\s+table\s+#i', $l)) {
565 $l = preg_replace('#\`([a-z0-9_]+)\`#i', "{$m[1]}_name", $l);
568 if ($tbl && preg_match('#auto_increment#i', $l, $m)) {
569 $l = preg_replace('#auto_increment#i', "default nextval('{$tbl}_seq')", $l);
570 $extra[] = "create sequence {$tbl}_seq;";
574 if (preg_match('#alter\s+table\s+(\`[a-z0-9_]+\`)#i', $l, $m)){
575 $l = preg_replace('#alter\s+table\s+(\`[a-z0-9_]+\`)#i', "ALTER TABLE {$tbl}", $l);
578 // enum value -- use the text instead..
580 if ($tbl && preg_match('#([\w]+)\s+(enum\([\w|\W]+\))#i', $l, $m)) {
581 $l = preg_replace('#enum\([\w|\W]+\)#i', "TEXT", $l);
583 // ignore the alter enum
584 if ($tbl && preg_match('#alter\s+table\s+([\w|\W]+)\s+enum\([\w|\W]+\)#i', $l, $m)) {
588 // UNIQUE KEY .. ignore
589 if ($tbl && preg_match('#UNIQUE KEY#i', $l, $m)) {
590 $last = array_pop($ret);
591 $ret[] = trim($last, ",");
595 if ($tbl && preg_match('#RENAME\s+TO#i', $l, $m)) {
599 if ($tbl && preg_match('#change\s+column#i', $l, $m)) {
603 // INDEX lookup ..ignore
604 if ($tbl && preg_match('#INDEX lookup+([\w|\W]+)#i', $l, $m)) {
605 $last = array_pop($ret);
606 $ret[] = trim($last, ",");
611 // CREATE INDEX ..ignore
612 if (preg_match('#alter\s+table\s+([a-z0-9_]+)\s+add\s+index\s+#i', $l, $m)) {
613 // $l = "CREATE INDEX {$m[1]}_{$m[2]} ON {$m[1]} {$m[3]}";
618 $l = preg_replace('#int\([0-9]+\)#i', 'INT', $l);
620 $l = preg_replace('# datetime#i', ' TIMESTAMP WITHOUT TIME ZONE', $l);
621 $l = preg_replace('# blob#i', ' TEXT', $l);
622 $l = preg_replace('# longtext#i', ' TEXT', $l);
623 $l = preg_replace('# tinyint#i', ' INT', $l);
629 $ret = array_merge($extra,$ret);
630 // echo implode("\n", $ret); exit;
632 file_put_contents($fn, implode("\n", $ret));
638 function checkOpts($opts)
642 foreach($opts as $o=>$v) {
643 if (!preg_match('/^json-/', $o) || empty($v)) {
646 if (!file_exists($v)) {
647 die("File does not exist : OPTION --{$o} = {$v} \n");
651 $modules = array_reverse($this->modulesList());
653 // move 'project' one to the end...
655 foreach ($modules as $module){
656 $file = $this->rootDir. "/Pman/$module/UpdateDatabase.php";
657 if($module == 'Core' || !file_exists($file)){
661 $class = "Pman_{$module}_UpdateDatabase";
663 if(!method_exists($x, 'checkOpts')){
666 $x->checkOpts($opts);
670 static function jsonImportFromArray($opts)
672 foreach($opts as $o=>$v) {
673 if (!preg_match('/^json-/', $o) || empty($v)) {
676 $type = str_replace('_', '-', substr($o,5));
678 $data= json_decode(file_get_contents($v),true);
679 $pg = HTML_FlexyFramework::get()->page;
680 DB_DataObject::factory($type)->importFromArray($pg ,$data,$opts);
690 function runUpdateModulesData()
692 if (class_exists('PDO_DataObjects_Introspection')) {
693 PDO_DataObject_Introspection::$cache = array();
695 HTML_FlexyFramework::get()->generateDataobjectsCache(true);
697 if(!in_array('Core', $this->disabled)){
698 echo "Running jsonImportFromArray\n";
699 Pman_Core_UpdateDatabase::jsonImportFromArray($this->opts);
702 echo "Running updateData on modules\n";
708 $modules = array_reverse($this->modulesList());
710 // move 'project' one to the end...
712 foreach ($modules as $module){
713 if(in_array($module, $this->disabled)){
716 $file = $this->rootDir. "/Pman/$module/UpdateDatabase.php";
717 if($module == 'Core' || !file_exists($file)){
722 $class = "Pman_{$module}_UpdateDatabase";
724 if(!method_exists($x, 'updateData')){
734 function updateDataEnums()
736 HTML_FlexyFramework::get()->generateDataobjectsCache(true);
738 $enum = DB_DataObject::Factory('core_enum');
739 //DB_DAtaObject::debugLevel(1);
744 'name' => 'COMPTYPE',
745 'display_name' => 'Company Types',
746 'is_system_enum' => 1,
750 'display_name' => 'Owner',
751 'seqid' => 999, // last...
752 'is_system_enum' => 1,
759 'name' => 'HtmlEditor.font-family',
760 'display_name' => 'HTML Editor font families',
761 'is_system_enum' => 1,
764 'name' => 'Helvetica,Arial,sans-serif',
765 'display_name' => 'Helvetica',
770 'name' => 'Courier New',
771 'display_name' => 'Courier',
776 'display_name' => 'Tahoma',
780 'name' => 'Times New Roman,serif',
781 'display_name' => 'Times',
786 'display_name' => 'Verdana',
799 function updateDataGroups()
802 $groups = DB_DataObject::factory('core_group');
803 $groups->initGroups();
805 $groups->initDatabase($this,array(
807 'name' => 'bcc-email', // group who are bcc'ed on all requests.
808 'type' => 0, // system
809 'display_name' => 'Standard BCC Group'
812 'name' => 'system-email-from',
813 'type' => 0, // system
814 'display_name' => 'Standard System Email From Group'
817 'name' => 'core-person-signup-bcc',
818 'type' => 0, // system
819 'display_name' => 'Standard Person Signup BCC Group'
822 'name' => 'Empty Group', // use for no bcc emails.
824 'display_name' => 'Standard Empty Group'
831 function updateDataCompanies()
834 // fix comptypes enums..
835 $c = DB_DataObject::Factory('core_company');
837 $c->selectAdd('distinct(comptype) as comptype');
838 $c->whereAdd("comptype != ''");
841 foreach($c->fetchAll('comptype') as $cts) {
845 $ctb[]= array( 'etype'=>'COMPTYPE', 'name' => $cts, 'display_name' => ucfirst(strtolower($cts)));
848 $c = DB_DataObject::Factory('core_enum');
851 //DB_DataObject::debugLevel(1);
853 $c = DB_DataObject::Factory('core_company');
855 UPDATE {$c->tableName()}
857 comptype_id = (SELECT id FROM core_enum where etype='comptype' and name={$c->tableName()}.comptype LIMIT 1)
870 function updateDataEmails()
872 foreach ($this->emailTemplates as $k => $mail) {
874 $mail_dir = "{$this->rootDir}{$mail['template_dir']}";
884 function initEmails($templateDir, $emails, $mapping = false)
886 HTML_FlexyFramework::get()->generateDataobjectsCache(true);
888 $pg = HTML_FlexyFramework::get()->page;
889 foreach($emails as $name=>$data) {
890 $cm = DB_DataObject::factory('core_email');
891 $update = $cm->get('name', $name);
894 if (empty($cm->bcc_group_id)) {
895 if (empty($data['bcc_group'])) {
896 $this->jerr("missing bcc_group for template $name");
899 $g = DB_DataObject::Factory('core_group')->lookup('name',$data['bcc_group']);
902 $this->jerr("bcc_group {$data['bcc_group']} does not exist when importing template $name");
905 if (!$g->members('email') && $g->name != 'Empty Group') {
906 $this->jerr("bcc_group {$data['bcc_group']} does not have any members");
909 $cm->bcc_group_id = $g->id;
911 // initEmails will always have the latest location of the test class - in theory the user should not be changign the value of this...
912 //if (empty($cm->test_class)) {
913 if (empty($data['test_class'])) {
914 $this->jerr("missing test_class for template $name");
917 $cm->test_class = $data['test_class'];
919 if(isset($cm->to_group_id)) {
924 !empty($data['to_group']) &&
925 (!isset($cm->to_group_id) || !empty($cm->to_group_id))
927 $gp = DB_DataObject::Factory('core_group')->lookup('name',$data['to_group']);
929 if (empty($gp->id)) {
930 $this->jerr("to_group {$data['to_group']} does not exist when importing template $name");
933 $cm->to_group_id = $gp->id;
937 isset($data['active']) && !isset($cm->active)
939 $cm->active = $data['active'];
943 * Set description to email.
944 * However we do not update if it is been set.
946 if(empty($cm->description) && !empty($data['description'])){
947 $cm->description = $cm->escape($data['description']);
950 require_once $cm->test_class . '.php';
952 $clsname = str_replace('/','_', $cm->test_class);
954 $method = new ReflectionMethod($clsname , 'test_'. $name) ;
955 $got_it = $method->isStatic();
956 } catch(Exception $e) {
961 $this->jerr("template {$name} does not have a test method {$clsname}::test_{$name}");
965 echo "email: {$name} - checked\n";
966 continue; /// we do not import the body content of templates that exist...
973 // $basedir = $this->bootLoader->rootDir . $mail_template_dir;
977 'file' => $templateDir. $name .'.html'
980 if (!empty($data['master'])) {
981 $opts['master'] = $templateDir . $master .'.html';
983 require_once 'Pman/Core/Import/Core_email.php';
984 $x = new Pman_Core_Import_Core_email();
986 $x->updateOrCreateEmail('', $opts, $cm, $mapping);
988 echo "email: {$name} - CREATED\n";
993 function updateData()
996 if (class_exists('PDO_DataObjects_Introspection')) {
997 PDO_DataObject_Introspection::$cache = array();
999 HTML_FlexyFramework::get()->generateDataobjectsCache(true);
1001 $this->updateDataEnums();
1002 $this->updateDataGroups();
1003 $this->updateDataCompanies();
1005 $this->updateDataEmails();
1007 $c = DB_DataObject::Factory('I18n');
1011 function fixMysqlInnodb()
1014 static $done_check = false;
1020 if (!empty($this->opts['skip-mysql-checks'])) {
1023 // innodb in single files is far more efficient that MYD or one big innodb file.
1024 // first check if database is using this format.
1025 $db = DB_DataObject::factory('core_enum');
1026 $db->query("show variables like 'innodb_file_per_table'");
1028 if ($db->Value == 'OFF') {
1029 die("Error: set innodb_file_per_table = 1 in my.cnf (or run with --skip-mysql-checks\n\n");
1032 $db = DB_DataObject::factory('core_enum');
1033 $db->query("select version() as version");
1036 if (version_compare($db->version, '5.7', '>=' )) {
1038 $db = DB_DataObject::factory('core_enum');
1039 $db->query("show variables like 'sql_mode'");
1042 $modes = explode(",", $db->Value);
1044 // these are 'new' problems with mysql.
1046 in_array('NO_ZERO_IN_DATE', $modes) ||
1047 in_array('NO_ZERO_DATE', $modes) ||
1048 in_array('STRICT_TRANS_TABLES', $modes) ||
1049 !in_array('ALLOW_INVALID_DATES', $modes)
1051 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");
1055 $done_check = true;;
1066 /** ------------- schema fixing ... there is an issue with data imported having the wrong sequence names... --- */
1068 function fixSequencesMysql()
1073 function fixSequencesPgsql()
1077 //DB_DataObject::debugLevel(1);
1078 $cs = DB_DataObject::factory('core_enum');
1082 CASE WHEN strpos(seq_name, '.') > 0 THEN
1085 quote_ident(min(schema_name)) ||'.'|| quote_ident(min(seq_name))
1088 ||' OWNED BY '|| quote_ident(min(schema_name)) || '.' ||
1089 quote_ident(min(table_name)) ||'.'|| quote_ident(min(column_name)) ||';' as cmd
1093 n.nspname AS schema_name,
1094 c.relname AS table_name,
1095 a.attname AS column_name,
1096 regexp_replace(regexp_replace(d.adsrc, E'nextval\\\\(+[''\\\"]*', ''),E'[''\\\"]*::.*\$','') AS seq_name
1098 JOIN pg_attribute a ON (c.oid=a.attrelid)
1099 JOIN pg_attrdef d ON (a.attrelid=d.adrelid AND a.attnum=d.adnum)
1100 JOIN pg_namespace n ON (c.relnamespace=n.oid)
1101 WHERE has_schema_privilege(n.oid,'USAGE')
1102 AND n.nspname NOT LIKE 'pg!_%' escape '!'
1103 AND has_table_privilege(c.oid,'SELECT')
1104 AND (NOT a.attisdropped)
1105 AND d.adsrc ~ '^nextval'
1109 CASE WHEN strpos(seq_name, '.') > 0 THEN
1110 substring(seq_name, 1,strpos(seq_name,'.')-1)
1115 GROUP BY seq_name HAVING count(*)=1
1118 while ($cs->fetch()) {
1121 foreach($cmds as $cmd) {
1122 $cs = DB_DataObject::factory('core_enum');
1126 $cs = DB_DataObject::factory('core_enum');
1128 SELECT 'SELECT SETVAL(' ||
1129 quote_literal(quote_ident(nspname) || '.' || quote_ident(S.relname)) ||
1130 ', MAX(' || quote_ident(C.attname)|| ')::integer ) FROM ' || nspname || '.' || quote_ident(T.relname)|| ';' as cmd
1136 WHERE S.relkind = 'S'
1138 AND D.refobjid = T.oid
1139 AND D.refobjid = C.attrelid
1140 AND D.refobjsubid = C.attnum
1141 AND NS.oid = T.relnamespace
1145 while ($cs->fetch()) {
1148 foreach($cmds as $cmd) {
1149 $cs = DB_DataObject::factory('core_enum');
1156 var $extensions = array(
1161 function runExtensions()
1164 $ff = HTML_Flexyframework::get();
1166 $dburl = parse_url($ff->database);
1168 $dbtype = $dburl['scheme'];
1170 foreach($this->extensions as $ext) {
1172 $scls = ucfirst($dbtype). $ext;
1173 $cls = __CLASS__ . '_'. $scls;
1174 $fn = implode('/',explode('_', $cls)).'.php';
1175 if (!file_exists(__DIR__.'/UpdateDatabase/'. $scls .'.php')) {
1186 function checkSystem($req = false, $pref = false)
1188 // most of these are from File_Convert...
1190 // these are required - and have simple dependancies.
1191 require_once 'System.php';
1192 $req = $req !== false ? $req : array(
1197 'rsvg-convert', //librsvg2-bin
1204 // these are prefered - but may have complicated depenacies
1205 $pref = $pref !== false ? $pref : array(
1209 'html2text', // not availabe in debian squeeze
1210 'pdftocairo', //poppler-utils - not available in debian squeeze.
1220 foreach($req as $r) {
1221 if (!System::which($r)) {
1227 die("Missing these programs - need installing\n" . implode("\n",$res). "\n");
1229 foreach($pref as $r) {
1230 if (!System::which($r)) {
1236 echo "WARNING: Missing these programs - they may need installing\n". implode("\n",$res);
1243 function clearApacheDataobjectsCache()
1245 echo "Clearing Database Cache\n";
1246 // this needs to clear it's own cache along with remote one..
1249 $response = $this->curl("http://localhost{$this->local_base_url}/Core/RefreshDatabaseCache");
1251 $json = json_decode($response, true);
1253 if(empty($json['data']) || $json['data'] != 'DONE'){
1254 echo $response. "\n";
1255 echo "Clear DataObjects Cache failed\n";
1262 function clearApacheAssetCache()
1264 echo "Clearing Asset Cache\n";
1265 $response = $this->curl(
1266 "http://localhost{$this->local_base_url}/Core/Asset",
1267 array( '_clear_cache' => 1 ,'returnHTML' => 'NO' ),
1270 $json = json_decode($response, true);
1272 if(empty($json['success']) || !$json['success']) {
1273 echo $response. "\n";
1274 echo "CURL Clear Asset cache failed\n";
1281 function curl($url, $request = array(), $method = 'GET')
1283 if($method == 'GET'){
1284 $request = http_build_query($request);
1285 $url = $url . "?" . $request;
1288 $ch = curl_init($url);
1290 if ($method == 'POST') {
1292 curl_setopt($ch, CURLOPT_POST, 1);
1293 curl_setopt($ch, CURLOPT_POSTFIELDS, $request);
1296 curl_setopt($ch, CURLOPT_HTTPHEADER,
1297 array("Content-Type: application/x-www-form-urlencoded", "Content-Length: " . strlen($request)));
1301 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
1303 curl_setopt($ch, CURLOPT_HEADER, false);
1304 curl_setopt($ch, CURLOPT_VERBOSE, 0);
1305 curl_setopt($ch, CURLOPT_TIMEOUT, 30);
1306 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
1308 $response = curl_exec($ch);
1315 static function verifyExtensions($extensions)
1319 foreach ($extensions as $e){
1321 if(extension_loaded($e)) {
1325 $error[] = "Error: Please install php extension: {$e}";
1331 $ff = HTML_FLexyFramework::get();
1333 $ff->page->jerr(implode('\n', $error));