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'));
123 var $disabled = array();
128 var $local_base_url = false;
130 var $emailTemplates = array(
131 'EVENT_ERRORS_REPORT' => array(
132 'bcc_group' => 'Empty Group',
133 'test_class' => 'Pman/Admin/Report/SendEventErrors',
134 'to_group' => 'Administrators',
136 'description' => '9. System Error Messages',
137 'template_dir' => '/Pman/Admin/templates/mail/'
144 $ff = HTML_FlexyFramework::get();
145 if (!empty($ff->cli)) {
150 parent::getAuth(); // load company!
151 $au = $this->getAuthUser();
152 if (!$au || $au->company()->comptype != 'OWNER') {
153 $this->jerr("Not authenticated", array('authFailure' => true));
155 $this->authUser = $au;
159 function get($args, $opts=array())
162 PEAR::setErrorHandling(PEAR_ERROR_CALLBACK, array($this, 'onPearError'));
164 $this->checkSystem();
166 $this->verifyExtensions(array('curl'));
168 if (class_exists('PDO_DataObjects_Introspection')) {
169 PDO_DataObject_Introspection::$cache = array();
171 echo "Generate DB cache\n";
172 HTML_FlexyFramework::get()->generateDataobjectsCache(true);
173 echo "Generated DB cache\n";
174 $ff = HTML_FlexyFramework::get();
176 if(!isset($ff->Pman) || !isset($ff->Pman['local_base_url'])){
177 die("Please setup Pman[local_base_url]\n");
180 $this->local_base_url = $ff->Pman['local_base_url'];
182 if(!empty($ff->Core_Notify)){
183 // require_once 'Pman/Core/NotifySmtpCheck.php';
184 // $x = new Pman_Core_NotifySmtpCheck();
188 $this->disabled = explode(',', $ff->disable);
190 //$this->fixSequencesPgsql();exit;
193 if (!empty($opts['debug'])) {
194 DB_DataObject::DebugLevel($opts['debug']);
197 // ask all the modules to verify the opts
198 echo "Checi options\n";
199 $this->checkOpts($opts);
203 // do this first, so the innodb change + utf8 fixes column max sizes
205 // this will trigger errors about freetext indexes - we will have to remove them manually.?
206 // 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..)
208 $this->runExtensions();
211 if (empty($opts['data-only'])) {
214 if (!empty($opts['only-module-sql'])) {
220 $this->runUpdateModulesData();
222 if (!empty($opts['add-company']) && !in_array('Core', $this->disabled)) {
223 // make sure we have a good cache...?
225 DB_DataObject::factory('core_company')->initCompanies($this, $opts);
228 $this->runExtensions();
230 $this->clearApacheDataobjectsCache();
232 $this->clearApacheAssetCache();
236 echo "\nUpdate Completed SUCCESS\n";
240 * imports SQL files from all DataObjects directories....
242 * except any matching /migrate/
247 // loop through all the modules, and see if they have a importSQL method?
250 $ff = HTML_Flexyframework::get();
252 $dburl = parse_url($ff->database); // used to be DB_DataObject['database'] - but not portable to PDO
254 //$this->{'import' . $url['scheme']}($url);
256 $dbtype = $dburl['scheme'];
259 $dirmethod = 'import' . $dburl['scheme'] . 'dir';
264 $ar = $this->modulesList();
269 if(in_array($m, $this->disabled)){
270 echo "module $m is disabled \n";
274 echo "Importing SQL from module $m\n";
275 if (!empty($this->opts['only-module-sql']) && $m != $this->opts['only-module-sql']) {
280 // check to see if the class has
284 $file = $this->rootDir. "/Pman/$m/UpdateDatabase.php";
285 if($m != 'Core' && file_exists($file)){
288 $class = "Pman_{$m}_UpdateDatabase";
290 if(method_exists($x, 'importModuleSQL')){
291 echo "Importing SQL from module $m using Module::importModuleSQL\n";
292 $x->opts = $this->opts;
293 $x->rootDir = $this->rootDir;
294 $x->importModuleSQL($dburl);
299 echo "Importing SQL from module $m\n";
302 // if init has been called
304 if (!empty($this->opts['init'])) {
305 $this->{$dirmethod}($dburl, $this->rootDir. "/Pman/$m/{$dbtype}.init");
311 $fd = $this->rootDir. "/Pman/$m/DataObjects";
313 $this->{$dirmethod}($dburl, $fd);
316 // new -- sql directory..
317 // new style will not support migrate ... they have to go into mysql-migrate.... directories..
318 // new style will not support pg.sql etc.. naming - that's what the direcotries are for..
319 $dbdir = $dbtype == 'mysqli' ? 'mysql' : $dbtype;
321 $this->{$dirmethod}($dburl, $this->rootDir. "/Pman/$m/sql");
322 $this->{$dirmethod}($dburl, $this->rootDir. "/Pman/$m/{$dbdir}");
326 if (!empty($this->opts['init']) && file_exists($this->rootDir. "/Pman/$m/{$dbtype}.initdata")) {
327 if (class_exists('PDO_DataObjects_Introspection')) {
328 PDO_DataObject_Introspection::$cache = array();
330 HTML_FlexyFramework::get()->generateDataobjectsCache(true);
332 $this->{$dirmethod}($dburl, $this->rootDir. "/Pman/$m/{$dbtype}.initdata");
333 $this->{'fixSequences'. $dbtype}();
346 /** -------------- code to handle importing a whole directory of files into the database ------- **/
349 function importpgsqldir($url, $dir, $disable_triggers = false)
351 $ff = HTML_FlexyFramework::get();
353 require_once 'System.php';
354 $cat = System::which('cat');
355 $psql = System::which('psql');
358 if (!empty($url['pass'])) {
359 putenv("PGPASSWORD=". $url['pass']);
363 ' -h ' . $url['host'] .
364 ' -U' . escapeshellarg($url['user']) .
365 ' ' . basename($url['path']);
368 echo $psql_cmd . "\n" ;
369 echo "scan : $dir\n";
372 $files = array($dir);
377 $files = glob($dir.'/*.sql');
378 uksort($files, 'strcasecmp');
380 //$lsort = create_function('$a,$b','return strlen($a) > strlen($b) ? 1 : -1;');
381 //usort($files, $lsort);
384 foreach($files as $bfn) {
387 if (preg_match('/migrate/i', basename($bfn))) { // skip migration scripts at present..
390 if (preg_match('#\.[a-z]{2}\.sql#i', basename($bfn))
391 && !preg_match('#\.pg\.sql#i', basename($bfn))
392 ) { // skip migration scripts at present..
397 if (!preg_match('/pgsql/', basename($dir) )) {
398 if ( !preg_match('#\.pg\.sql$#', basename($bfn))) {
399 $fn = $this->convertToPG($bfn);
403 // files ending in .pg.sql are native postgres files.. ## depricated
406 $cmd = "$psql_cmd < " . escapeshellarg($fn ? $fn : $bfn) . ' 2>&1' ;
408 echo "$bfn: $cmd ". ($ff->cli ? "\n" : "<BR>\n");
424 * mysql - does not support conversions.
428 function importmysqlidir($dburl, $dir) {
429 return $this->importmysqldir($dburl, $dir);
432 function importmysqldir($dburl, $dir)
435 $this->fixMysqlInnodb(); /// run once
437 echo "Import MYSQL :: $dir\n";
440 require_once 'System.php';
441 $cat = System::which('cat');
442 $mysql = System::which('mysql');
446 $mysql_cmd = $mysql .
447 ' -h ' . $dburl['host'] .
448 ' -u' . escapeshellarg($dburl['user']) .
449 (!empty($dburl['pass']) ? ' -p' . escapeshellarg($dburl['pass']) : '') .
450 ' ' . basename($dburl['path']);
451 //echo $mysql_cmd . "\n" ;
453 $files = glob($dir.'/*.sql');
454 uksort($files, 'strcasecmp');
457 foreach($files as $fn) {
460 if (preg_match('/migrate/i', basename($fn))) { // skip migration scripts at present..
463 // .my.sql but not .pg.sql
464 if (preg_match('#\.[a-z]{2}\.sql#i', basename($fn))
465 && !preg_match('#\.my\.sql#i', basename($fn))
466 ) { // skip migration scripts at present..
469 if (!strlen(trim($fn))) {
473 $cmd = "$mysql_cmd -f < " . escapeshellarg($fn) ." 2>&1" ;
475 echo basename($dir).'/'. basename($fn) . '::' . $cmd. ($this->cli ? "\n" : "<BR>\n");
478 $fp = popen($cmd, "r");
481 // send the current file part to the browser
482 $line = trim(fgets($fp, 1024));
487 if (!preg_match('/^ERROR\s+([0-9]+)/', $line, $matches)) {
488 echo " ---- {$line}\n"; flush();
492 switch($matches[1]) {
493 case 1017: // cause by renaming table -- old one does not exist..
494 case 1050: // create tables triggers this..
495 case 1060: // Duplicate column name
496 case 1061: // Duplicate key name - triggered by add index.. but could hide error. - unlikely though.
497 case 1091: // drop index -- name does not exist.. might hide errors..
499 case 1146: // drop a index on an unknown table.. - happens rarely...
500 case 1054: // Unknown column -- triggered by CHANGE COLUMN - but may hide other errrors..
506 echo " ---- {$line}\n"; flush();
510 // 1051: // Unknown table -- normally drop = add iff exists..
511 echo "File: $fn\n$line\n";
527 * simple regex based convert mysql to pgsql...
529 function convertToPG($src)
531 //echo "Convert $src\n";
533 $fn = $this->tempName('sql');
535 $ret = array( ); // pad it a bit.
536 $extra = array("", "" );
539 foreach(file($src) as $l) {
542 if (!strlen($l) || $l[0] == '#') {
546 if (preg_match('#create\s+table\s+([a-z0-9_]+)#i', $l, $m)) {
549 if (preg_match('#create\s+table\s+\`([a-z0-9_]+)\`#i', $l, $m)) {
550 $tbl = 'shop_' . strtolower($m[1]);
551 $l = preg_replace('#create\s+table\s+\`([a-z0-9_]+)\`#i', "CREATE TABLE {$tbl}", $l);
553 if (preg_match('#\`([a-z0-9_]+)\`#i', $l, $m) && !preg_match('#alter\s+table\s+#i', $l)) {
554 $l = preg_replace('#\`([a-z0-9_]+)\`#i', "{$m[1]}_name", $l);
557 if ($tbl && preg_match('#auto_increment#i', $l, $m)) {
558 $l = preg_replace('#auto_increment#i', "default nextval('{$tbl}_seq')", $l);
559 $extra[] = "create sequence {$tbl}_seq;";
563 if (preg_match('#alter\s+table\s+(\`[a-z0-9_]+\`)#i', $l, $m)){
564 $l = preg_replace('#alter\s+table\s+(\`[a-z0-9_]+\`)#i', "ALTER TABLE {$tbl}", $l);
567 // enum value -- use the text instead..
569 if ($tbl && preg_match('#([\w]+)\s+(enum\([\w|\W]+\))#i', $l, $m)) {
570 $l = preg_replace('#enum\([\w|\W]+\)#i', "TEXT", $l);
572 // ignore the alter enum
573 if ($tbl && preg_match('#alter\s+table\s+([\w|\W]+)\s+enum\([\w|\W]+\)#i', $l, $m)) {
577 // UNIQUE KEY .. ignore
578 if ($tbl && preg_match('#UNIQUE KEY#i', $l, $m)) {
579 $last = array_pop($ret);
580 $ret[] = trim($last, ",");
584 if ($tbl && preg_match('#RENAME\s+TO#i', $l, $m)) {
588 if ($tbl && preg_match('#change\s+column#i', $l, $m)) {
592 // INDEX lookup ..ignore
593 if ($tbl && preg_match('#INDEX lookup+([\w|\W]+)#i', $l, $m)) {
594 $last = array_pop($ret);
595 $ret[] = trim($last, ",");
600 // CREATE INDEX ..ignore
601 if (preg_match('#alter\s+table\s+([a-z0-9_]+)\s+add\s+index\s+#i', $l, $m)) {
602 // $l = "CREATE INDEX {$m[1]}_{$m[2]} ON {$m[1]} {$m[3]}";
607 $l = preg_replace('#int\([0-9]+\)#i', 'INT', $l);
609 $l = preg_replace('# datetime#i', ' TIMESTAMP WITHOUT TIME ZONE', $l);
610 $l = preg_replace('# blob#i', ' TEXT', $l);
611 $l = preg_replace('# longtext#i', ' TEXT', $l);
612 $l = preg_replace('# tinyint#i', ' INT', $l);
618 $ret = array_merge($extra,$ret);
619 // echo implode("\n", $ret); exit;
621 file_put_contents($fn, implode("\n", $ret));
627 function checkOpts($opts)
631 foreach($opts as $o=>$v) {
632 if (!preg_match('/^json-/', $o) || empty($v)) {
635 if (!file_exists($v)) {
636 die("File does not exist : OPTION --{$o} = {$v} \n");
640 $modules = array_reverse($this->modulesList());
642 // move 'project' one to the end...
644 foreach ($modules as $module){
645 $file = $this->rootDir. "/Pman/$module/UpdateDatabase.php";
646 if($module == 'Core' || !file_exists($file)){
650 $class = "Pman_{$module}_UpdateDatabase";
652 if(!method_exists($x, 'checkOpts')){
655 $x->checkOpts($opts);
659 static function jsonImportFromArray($opts)
661 foreach($opts as $o=>$v) {
662 if (!preg_match('/^json-/', $o) || empty($v)) {
665 $type = str_replace('_', '-', substr($o,5));
667 $data= json_decode(file_get_contents($v),true);
668 $pg = HTML_FlexyFramework::get()->page;
669 DB_DataObject::factory($type)->importFromArray($pg ,$data,$opts);
679 function runUpdateModulesData()
681 if (class_exists('PDO_DataObjects_Introspection')) {
682 PDO_DataObject_Introspection::$cache = array();
684 HTML_FlexyFramework::get()->generateDataobjectsCache(true);
686 if(!in_array('Core', $this->disabled)){
687 echo "Running jsonImportFromArray\n";
688 Pman_Core_UpdateDatabase::jsonImportFromArray($this->opts);
691 echo "Running updateData on modules\n";
697 $modules = array_reverse($this->modulesList());
699 // move 'project' one to the end...
701 foreach ($modules as $module){
702 if(in_array($module, $this->disabled)){
705 $file = $this->rootDir. "/Pman/$module/UpdateDatabase.php";
706 if($module == 'Core' || !file_exists($file)){
711 $class = "Pman_{$module}_UpdateDatabase";
713 if(!method_exists($x, 'updateData')){
723 function updateDataEnums()
725 HTML_FlexyFramework::get()->generateDataobjectsCache(true);
727 $enum = DB_DataObject::Factory('core_enum');
728 //DB_DAtaObject::debugLevel(1);
733 'name' => 'COMPTYPE',
734 'display_name' => 'Company Types',
735 'is_system_enum' => 1,
739 'display_name' => 'Owner',
740 'seqid' => 999, // last...
741 'is_system_enum' => 1,
748 'name' => 'HtmlEditor.font-family',
749 'display_name' => 'HTML Editor font families',
750 'is_system_enum' => 1,
753 'name' => 'Helvetica,Arial,sans-serif',
754 'display_name' => 'Helvetica',
759 'name' => 'Courier New',
760 'display_name' => 'Courier',
765 'display_name' => 'Tahoma',
769 'name' => 'Times New Roman,serif',
770 'display_name' => 'Times',
775 'display_name' => 'Verdana',
788 function updateDataGroups()
791 $groups = DB_DataObject::factory('core_group');
792 $groups->initGroups();
794 $groups->initDatabase($this,array(
796 'name' => 'bcc-email', // group who are bcc'ed on all requests.
797 'type' => 0, // system
798 'display_name' => 'Standard BCC Group'
801 'name' => 'system-email-from',
802 'type' => 0, // system
803 'display_name' => 'Standard System Email From Group'
806 'name' => 'core-person-signup-bcc',
807 'type' => 0, // system
808 'display_name' => 'Standard Person Signup BCC Group'
811 'name' => 'Empty Group', // use for no bcc emails.
813 'display_name' => 'Standard Empty Group'
820 function updateDataCompanies()
823 // fix comptypes enums..
824 $c = DB_DataObject::Factory('core_company');
826 $c->selectAdd('distinct(comptype) as comptype');
827 $c->whereAdd("comptype != ''");
830 foreach($c->fetchAll('comptype') as $cts) {
834 $ctb[]= array( 'etype'=>'COMPTYPE', 'name' => $cts, 'display_name' => ucfirst(strtolower($cts)));
837 $c = DB_DataObject::Factory('core_enum');
840 //DB_DataObject::debugLevel(1);
842 $c = DB_DataObject::Factory('core_company');
844 UPDATE {$c->tableName()}
846 comptype_id = (SELECT id FROM core_enum where etype='comptype' and name={$c->tableName()}.comptype LIMIT 1)
859 function updateDataEmails()
861 foreach ($this->emailTemplates as $k => $mail) {
863 $mail_dir = "{$this->rootDir}{$mail['template_dir']}";
873 function initEmails($templateDir, $emails, $mapping = false)
875 HTML_FlexyFramework::get()->generateDataobjectsCache(true);
877 $pg = HTML_FlexyFramework::get()->page;
878 foreach($emails as $name=>$data) {
879 $cm = DB_DataObject::factory('core_email');
880 $update = $cm->get('name', $name);
883 if (empty($cm->bcc_group_id)) {
884 if (empty($data['bcc_group'])) {
885 $this->jerr("missing bcc_group for template $name");
888 $g = DB_DataObject::Factory('core_group')->lookup('name',$data['bcc_group']);
891 $this->jerr("bcc_group {$data['bcc_group']} does not exist when importing template $name");
894 if (!$g->members('email') && $g->name != 'Empty Group') {
895 $this->jerr("bcc_group {$data['bcc_group']} does not have any members");
898 $cm->bcc_group_id = $g->id;
900 // initEmails will always have the latest location of the test class - in theory the user should not be changign the value of this...
901 //if (empty($cm->test_class)) {
902 if (empty($data['test_class'])) {
903 $this->jerr("missing test_class for template $name");
906 $cm->test_class = $data['test_class'];
908 if(isset($cm->to_group_id)) {
913 !empty($data['to_group']) &&
914 (!isset($cm->to_group_id) || !empty($cm->to_group_id))
916 $gp = DB_DataObject::Factory('core_group')->lookup('name',$data['to_group']);
918 if (empty($gp->id)) {
919 $this->jerr("to_group {$data['to_group']} does not exist when importing template $name");
922 $cm->to_group_id = $gp->id;
926 isset($data['active']) && !isset($cm->active)
928 $cm->active = $data['active'];
932 * Set description to email.
933 * However we do not update if it is been set.
935 if(empty($cm->description) && !empty($data['description'])){
936 $cm->description = $cm->escape($data['description']);
939 require_once $cm->test_class . '.php';
941 $clsname = str_replace('/','_', $cm->test_class);
943 $method = new ReflectionMethod($clsname , 'test_'. $name) ;
944 $got_it = $method->isStatic();
945 } catch(Exception $e) {
950 $this->jerr("template {$name} does not have a test method {$clsname}::test_{$name}");
954 echo "email: {$name} - checked\n";
955 continue; /// we do not import the body content of templates that exist...
962 // $basedir = $this->bootLoader->rootDir . $mail_template_dir;
966 'file' => $templateDir. $name .'.html'
969 if (!empty($data['master'])) {
970 $opts['master'] = $templateDir . $master .'.html';
972 require_once 'Pman/Core/Import/Core_email.php';
973 $x = new Pman_Core_Import_Core_email();
975 $x->updateOrCreateEmail('', $opts, $cm, $mapping);
977 echo "email: {$name} - CREATED\n";
982 function updateData()
985 if (class_exists('PDO_DataObjects_Introspection')) {
986 PDO_DataObject_Introspection::$cache = array();
988 HTML_FlexyFramework::get()->generateDataobjectsCache(true);
991 $this->updateDataEnums();
992 $this->updateDataGroups();
993 $this->updateDataCompanies();
995 $this->updateDataEmails();
997 $c = DB_DataObject::Factory('I18n');
1005 function fixMysqlInnodb()
1008 static $done_check = false;
1014 if (!empty($this->opts['skip-mysql-checks'])) {
1017 // innodb in single files is far more efficient that MYD or one big innodb file.
1018 // first check if database is using this format.
1019 $db = DB_DataObject::factory('core_enum');
1020 $db->query("show variables like 'innodb_file_per_table'");
1022 if ($db->Value == 'OFF') {
1023 die("Error: set innodb_file_per_table = 1 in my.cnf (or run with --skip-mysql-checks\n\n");
1026 $db = DB_DataObject::factory('core_enum');
1027 $db->query("select version() as version");
1030 if (version_compare($db->version, '5.7', '>=' )) {
1032 $db = DB_DataObject::factory('core_enum');
1033 $db->query("show variables like 'sql_mode'");
1036 $modes = explode(",", $db->Value);
1038 // these are 'new' problems with mysql.
1040 in_array('NO_ZERO_IN_DATE', $modes) ||
1041 in_array('NO_ZERO_DATE', $modes) ||
1042 in_array('STRICT_TRANS_TABLES', $modes) ||
1043 !in_array('ALLOW_INVALID_DATES', $modes)
1045 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");
1049 $done_check = true;;
1060 /** ------------- schema fixing ... there is an issue with data imported having the wrong sequence names... --- */
1062 function fixSequencesMysql()
1067 function fixSequencesPgsql()
1071 //DB_DataObject::debugLevel(1);
1072 $cs = DB_DataObject::factory('core_enum');
1076 CASE WHEN strpos(seq_name, '.') > 0 THEN
1079 quote_ident(min(schema_name)) ||'.'|| quote_ident(min(seq_name))
1082 ||' OWNED BY '|| quote_ident(min(schema_name)) || '.' ||
1083 quote_ident(min(table_name)) ||'.'|| quote_ident(min(column_name)) ||';' as cmd
1087 n.nspname AS schema_name,
1088 c.relname AS table_name,
1089 a.attname AS column_name,
1090 regexp_replace(regexp_replace(d.adsrc, E'nextval\\\\(+[''\\\"]*', ''),E'[''\\\"]*::.*\$','') AS seq_name
1092 JOIN pg_attribute a ON (c.oid=a.attrelid)
1093 JOIN pg_attrdef d ON (a.attrelid=d.adrelid AND a.attnum=d.adnum)
1094 JOIN pg_namespace n ON (c.relnamespace=n.oid)
1095 WHERE has_schema_privilege(n.oid,'USAGE')
1096 AND n.nspname NOT LIKE 'pg!_%' escape '!'
1097 AND has_table_privilege(c.oid,'SELECT')
1098 AND (NOT a.attisdropped)
1099 AND d.adsrc ~ '^nextval'
1103 CASE WHEN strpos(seq_name, '.') > 0 THEN
1104 substring(seq_name, 1,strpos(seq_name,'.')-1)
1109 GROUP BY seq_name HAVING count(*)=1
1112 while ($cs->fetch()) {
1115 foreach($cmds as $cmd) {
1116 $cs = DB_DataObject::factory('core_enum');
1120 $cs = DB_DataObject::factory('core_enum');
1122 SELECT 'SELECT SETVAL(' ||
1123 quote_literal(quote_ident(nspname) || '.' || quote_ident(S.relname)) ||
1124 ', MAX(' || quote_ident(C.attname)|| ')::integer ) FROM ' || nspname || '.' || quote_ident(T.relname)|| ';' as cmd
1130 WHERE S.relkind = 'S'
1132 AND D.refobjid = T.oid
1133 AND D.refobjid = C.attrelid
1134 AND D.refobjsubid = C.attnum
1135 AND NS.oid = T.relnamespace
1139 while ($cs->fetch()) {
1142 foreach($cmds as $cmd) {
1143 $cs = DB_DataObject::factory('core_enum');
1150 var $extensions = array(
1155 function runExtensions()
1158 $ff = HTML_Flexyframework::get();
1160 $dburl = parse_url($ff->database);
1162 $dbtype = $dburl['scheme'];
1164 foreach($this->extensions as $ext) {
1166 $scls = ucfirst($dbtype). $ext;
1167 $cls = __CLASS__ . '_'. $scls;
1168 $fn = implode('/',explode('_', $cls)).'.php';
1169 if (!file_exists(__DIR__.'/UpdateDatabase/'. $scls .'.php')) {
1180 function checkSystem($req = false, $pref = false)
1182 // most of these are from File_Convert...
1184 // these are required - and have simple dependancies.
1185 require_once 'System.php';
1186 $req = $req !== false ? $req : array(
1191 'rsvg-convert', //librsvg2-bin
1198 // these are prefered - but may have complicated depenacies
1199 $pref = $pref !== false ? $pref : array(
1203 'html2text', // not availabe in debian squeeze
1204 'pdftocairo', //poppler-utils - not available in debian squeeze.
1214 foreach($req as $r) {
1215 if (!System::which($r)) {
1221 die("Missing these programs - need installing\n" . implode("\n",$res). "\n");
1223 foreach($pref as $r) {
1224 if (!System::which($r)) {
1230 echo "WARNING: Missing these programs - they may need installing\n". implode("\n",$res);
1237 function clearApacheDataobjectsCache()
1239 echo "Clearing Database Cache\n";
1240 // this needs to clear it's own cache along with remote one..
1243 $response = $this->curl("http://localhost{$this->local_base_url}/Core/RefreshDatabaseCache");
1245 $json = json_decode($response, true);
1247 if(empty($json['data']) || $json['data'] != 'DONE'){
1248 echo $response. "\n";
1249 echo "Clear DataObjects Cache failed\n";
1256 function clearApacheAssetCache()
1258 echo "Clearing Asset Cache\n";
1259 $response = $this->curl(
1260 "http://localhost{$this->local_base_url}/Core/Asset",
1261 array( '_clear_cache' => 1 ,'returnHTML' => 'NO' ),
1264 $json = json_decode($response, true);
1266 if(empty($json['success']) || !$json['success']) {
1267 echo $response. "\n";
1268 echo "CURL Clear Asset cache failed\n";
1275 function curl($url, $request = array(), $method = 'GET')
1277 if($method == 'GET'){
1278 $request = http_build_query($request);
1279 $url = $url . "?" . $request;
1282 $ch = curl_init($url);
1284 if ($method == 'POST') {
1286 curl_setopt($ch, CURLOPT_POST, 1);
1287 curl_setopt($ch, CURLOPT_POSTFIELDS, $request);
1290 curl_setopt($ch, CURLOPT_HTTPHEADER,
1291 array("Content-Type: application/x-www-form-urlencoded", "Content-Length: " . strlen($request)));
1295 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
1297 curl_setopt($ch, CURLOPT_HEADER, false);
1298 curl_setopt($ch, CURLOPT_VERBOSE, 0);
1299 curl_setopt($ch, CURLOPT_TIMEOUT, 30);
1300 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
1302 $response = curl_exec($ch);
1309 static function verifyExtensions($extensions)
1313 foreach ($extensions as $e){
1315 if(extension_loaded($e)) {
1319 $error[] = "Error: Please install php extension: {$e}";
1325 $ff = HTML_FLexyFramework::get();
1327 $ff->page->jerr(implode('\n', $error));