/** * This function acts as a member method of the PreferencesTool class. It has * been factored out for efficiency because it only needs to be run once. * @see Dataface_PreferncesTool::_createPreferencesTable() */ function Dataface_PreferencesTool__createPreferencesTable() { $res = xf_db_query("create table if not exists `dataface__preferences` (\n\t\t\t`pref_id` int(11) unsigned not null auto_increment,\n\t\t\t`username` varchar(64) not null,\n\t\t\t`table` varchar(128) not null,\n\t\t\t`record_id` varchar(255) not null,\n\t\t\t`key` varchar(128) not null,\n\t\t\t`value` varchar(255) not null,\n\t\t\tprimary key (pref_id),\n\t\t\tindex `username` (`username`),\n\t\t\tindex `table` (`table`),\n\t\t\tindex `record_id` (`record_id`))", df_db()); if (!$res) { throw new Exception(xf_db_error(df_db()), E_USER_ERROR); } }
function test_updateTranslationsTable() { $app =& Dataface_Application::getInstance(); $tt = new Dataface_TranslationTool(); $tt->updateTranslationsTable(); $sql = "show columns from `dataface__translations`"; $res = xf_db_query($sql, $app->db()); if (!$res) { trigger_error(xf_db_error($app->db()), E_USER_ERROR); } $cols = array(); while ($row = xf_db_fetch_assoc($res)) { $cols[$row['Field']] = $row; } $this->assertEquals(array_keys($tt->schema), array_keys($cols)); $tt->schema['test_col'] = array('Field' => 'test_col', 'Type' => "int(11)", 'Extra' => '', 'Null' => ''); $tt->updateTranslationsTable(); $sql = "show columns from `dataface__translations`"; $res = xf_db_query($sql, $app->db()); if (!$res) { trigger_error(xf_db_error($app->db()), E_USER_ERROR); } $cols = array(); while ($row = xf_db_fetch_assoc($res)) { $cols[$row['Field']] = $row; } $this->assertEquals(array_keys($tt->schema), array_keys($cols)); }
public static function createRecordsTable() { $sql = sprintf("create table `%s` (\n\t\t\t\tid int(11) not null auto_increment,\n\t\t\t\tschema_id int(11) not null,\n\t\t\t\t`base_record_id_hash` varchar(32) not null,\n\t\t\t\t`base_record_id` text not null,\n\t\t\t\t`version_hash` varchar(32) not null,\n\t\t\t\t`lang` varchar(2) not null,\n\t\t\t\t`record_data` text not null,\n\t\t\t\tprimary key (`id`),\n\t\t\t\tkey (`schema_id`, `base_record_id_hash`, `version_hash`)\n\t\t\t)", self::$RECORDS_TABLE); $res = xf_db_query($sql, df_db()); if (!$res) { throw new Exception(xf_db_error(df_db())); } true; }
function handle(&$params) { $app =& Dataface_Application::getInstance(); if (df_get_database_version() == df_get_file_system_version()) { $app->redirect(DATAFACE_SITE_HREF . '?--msg=' . urlencode('The application database is up to date at version ' . df_get_database_version())); } if (df_get_database_version() > df_get_file_system_version()) { $app->redirect(DATAFACE_SITE_HREF . '?--msg=' . urlencode('The database version is greater than the file system version. Please upgrade your application to match the version in the database (version ' . df_get_database_version())); } $res = xf_db_query("select count(*) from dataface__version", df_db()); if (!$res) { throw new Exception(xf_db_error(df_db())); } $row = xf_db_fetch_row($res); if ($row[0] == 0) { $res2 = xf_db_query("insert into dataface__version (`version`) values (0)", df_db()); if (!$res2) { throw new Exception(xf_db_error(df_db())); } } if (file_exists('conf/Installer.php')) { import('conf/Installer.php'); $installer = new conf_Installer(); $methods = get_class_methods('conf_Installer'); $methods = preg_grep('/^update_([0-9]+)$/', $methods); $updates = array(); foreach ($methods as $method) { preg_match('/^update_([0-9]+)$/', $method, $matches); $version = intval($matches[1]); if ($version > df_get_database_version() and $version <= df_get_file_system_version()) { $updates[] = $version; } } sort($updates); foreach ($updates as $update) { $method = 'update_' . $update; $res = $installer->{$method}(); if (PEAR::isError($res)) { return $res; } $res = xf_db_query("update dataface__version set `version`='" . addslashes($update) . "'", df_db()); if (!$res) { throw new Exception(xf_db_error(df_db()), E_USER_ERROR); } } } $res = xf_db_query("update dataface__version set `version`='" . addslashes(df_get_file_system_version()) . "'", df_db()); if (!$res) { throw new Exception(xf_db_error(df_db()), E_USER_ERROR); } if (function_exists('apc_clear_cache')) { apc_clear_cache('user'); } df_clear_views(); df_clear_cache(); $app->redirect(DATAFACE_SITE_HREF . '?--msg=' . urlencode('The database has been successfully updated to version ' . df_get_file_system_version())); }
function setUp() { $app =& Dataface_Application::getInstance(); $path = DATAFACE_SITE_PATH . '/tables/' . $this->mytable; if (file_exists($path)) { @rmdir($path); } xf_db_query('drop table if exists `' . $this->mytable . '`', $app->db()) or die(xf_db_error() . ' on line ' . __LINE__ . ' of file ' . __FILE__); parent::setUp(); }
/** * A method to create the configuration table in the database. The configuration * table is where configuration (e.g. fields.ini etc..) may be stored. This is * a new feature in 0.6.14. * * @author Steve Hannah <*****@*****.**> * @created Feb. 26, 2007 */ function Dataface_ConfigTool_createConfigTable() { $self =& Dataface_ConfigTool::getInstance(); if (!Dataface_Table::tableExists($self->configTableName, false)) { $sql = "CREATE TABLE `" . $self->configTableName . "` (\n\t\t\t\t\tconfig_id int(11) NOT NULL auto_increment primary key,\n\t\t\t\t\t`file` varchar(255) NOT NULL,\n\t\t\t\t\t`section` varchar(128),\n\t\t\t\t\t`key` varchar(128) NOT NULL,\n\t\t\t\t\t`value` text NOT NULL,\n\t\t\t\t\t`lang` varchar(2),\n\t\t\t\t\t`username` varchar(32),\n\t\t\t\t\t`priority` int(5) default 5\n\t\t\t\t\t)"; $res = xf_db_query($sql, df_db()); if (!$res) { throw new Exception(xf_db_error(df_db()), E_USER_ERROR); } } }
function testSync1() { $app =& Dataface_Application::getInstance(); $s = new DB_Sync($app->db(), $app->db(), 'a', 'b'); $s->syncTables(); $res = xf_db_query("show create table b", $app->db()); if (!$res) { trigger_error(xf_db_error($app->db()), E_USER_ERROR); } $row = xf_db_fetch_assoc($res); @xf_db_free_result($res); $this->assertEquals("CREATE TABLE `b` (\n `id` int(11) NOT NULL auto_increment,\n `a` varchar(32) default 'b',\n `b` datetime default '0000-00-00 00:00:00',\n PRIMARY KEY (`id`)\n) ENGINE=MyISAM DEFAULT CHARSET=latin1", $row['Create Table']); }
function setUp() { parent::setUp(); xf_db_query("CREATE TABLE `Pages` (\n\t\t\t`PageID` INT(11) auto_increment NOT NULL,\n\t\t\t`ParentID` INT(11),\n\t\t\t`ShortName` VARCHAR(32) NOT NULL,\n\t\t\t`Description` TEXT,\n\t\t\tPRIMARY KEY (`PageID`),\n\t\t\tUNIQUE (`ParentID`,`ShortName`))") or trigger_error(xf_db_error() . __LINE__); xf_db_query("INSERT INTO `Pages` (`PageID`,`ShortName`,`Description`)\n\t\t\tVALUES (1,'index_page','Main page')") or trigger_error(xf_db_error() . __LINE__); xf_db_query("INSERT INTO `Pages` (`ParentID`,`ShortName`,`Description`)\n\t\t\tVALUES \n\t\t\t(1,'about','About us'),\n\t\t\t(1,'jobs','Now hiring'),\n\t\t\t(1,'products','About our products'),\n\t\t\t(1,'services','About our services'),\n\t\t\t(1,'contact','Contact us')") or trigger_error(xf_db_error() . __LINE__); xf_db_query("INSERT INTO `Pages` (`ParentID`,`ShortName`,`Description`)\n\t\t\tVALUES\n\t\t\t(2,'history','Our history'),\n\t\t\t(2,'future', 'The direction of the company'),\n\t\t\t(3,'application', 'Job application'),\n\t\t\t(3,'current_listing', 'Current job listings'),\n\t\t\t(4,'awards','Product awards'),\n\t\t\t(4,'downloads','Product downlaods'),\n\t\t\t(5,'consultation','Free consultation')") or trigger_error(xf_db_error() . __LINE__); $table =& Dataface_Table::loadTable('Pages'); $r =& $table->relationships(); if (!isset($r['children'])) { $table->addRelationship('children', array('__sql__' => 'select * from Pages where ParentID=\'$PageID\'', 'meta:class' => 'children')); } $this->indexpage =& df_get_record('Pages', array('PageID' => 1)); $this->t = new Dataface_TreeTable($this->indexpage); }
/** * Sets a configuration parameter in the configuration table. * This should not be called directly. It should be called through the * Dataface_ConfigTool class as its setConfigParam method. * * @param string $file The name of the ini file in which the config value is being set. * @param string $section The name of the section (could be null). * @param string $key The name of the parameter's key (not null) * @param string $value The value to set (not null) * @param string $username The username for which the parameter is being set (null for all users) * @param string $lang The 2-digit language code for which the parameter is being set (null for all languages). * @param integer $priority The priority of this config variable (priority dictates which * parameters take priority. Default vallue of 5. * @returns true if success or PEAR_Error if failure. * * This will create the configuration table if it doesn't already exist. * * @author Steve Hannah <*****@*****.**> * @created Feb. 26, 2007 */ function Dataface_ConfigTool_setConfigParam($file, $section, $key, $value, $username = null, $lang = null, $priority = 5) { $self =& Dataface_ConfigTool::getInstance(); // See if this parameter has already been set: $where = array(); $where[] = "`key`='" . addslashes($key) . "'"; $where[] = "`file`='" . addslashes($file) . "'"; $where[] = "`section`" . (isset($section) ? "='" . addslashes($section) . "'" : ' IS NULL'); $where[] = "`username`" . (isset($username) ? "='" . addslashes($username) . "'" : ' IS NULL'); $where[] = "`lang`" . (isset($lang) ? "='" . addslashes($lang) . "'" : ' IS NULL'); $where = implode(' and ', $where); $sql = "select `config_id` from `" . $self->configTableName . "` where {$where} limit 1"; $res = xf_db_query($sql, df_db()); if (!$res) { $self->createConfigTable(); $res = xf_db_query($sql, df_db()); } if (!$res) { return PEAR::raiseError("Failed to get config parameter: " . xf_db_error(df_db())); } $vals = array("section" => isset($section) ? "'" . addslashes($section) . "'" : 'NULL', "key" => "'" . addslashes($key) . "'", "value" => "'" . addslashes($value) . "'", "username" => "'" . addslashes($username) . "'", "lang" => "'" . addslashes($lang) . "'", "priority" => $priority); if (xf_db_num_rows($res) > 0) { $row = xf_db_fetch_assoc($res); // We need to perform an update $updates = array(); foreach ($vals as $vkey => $vval) { $updates[] = '`' . $vkey . '`=' . $vval; } $sets = implode(' and ', $updates); $sql = "update `" . $self->configTableName . "` set " . $sets . " where `config_id`='" . $row['config_id'] . "' limit 1"; } else { $values = array(); $cols = array(); foreach ($vals as $vkey => $vval) { $cols[] = "`{$vkey}`"; $values[] = $vval; } $cols = implode(',', $cols); $values = implode(',', $values); $sql = "insert into `" . $self->configTableName . "` ({$cols}) VALUES ({$values})"; } @xf_db_free_result($res); $res = xf_db_query($sql, df_db()); if (!$res) { return PEAR::raiseError("Could not write config value: " . xf_db_error(df_db())); } return true; }
function handle(&$params) { $res = xf_db_query("show tables like 'dataface__view_%'", df_db()); $views = array(); while ($row = xf_db_fetch_row($res)) { $views[] = $row[0]; } if ($views) { $sql = "drop view `" . implode('`,`', $views) . "`"; echo $sql; echo "<br/>"; $res = xf_db_query("drop view `" . implode('`,`', $views) . "`", df_db()); if (!$res) { throw new Exception(xf_db_error(df_db())); } } echo "done"; }
function copy($record, $vals = array(), $force = true) { foreach ($vals as $k => $v) { if (strpos($v, '=') === 0) { $vals[$k] = $this->evaluate($v, $k, $record); } } $del = $record->_table->getDelegate(); if (isset($del) and method_exists($del, 'beforeCopy')) { $res = $del->beforeCopy($record, $vals); if (PEAR::isError($res)) { return $res; } } $this->warnings = array(); // Step 1: Load the record - it has been passed // Step 2: build sql query to copy the record $query = $this->buildCopyQuery($record, $vals, $force); if (PEAR::isError($query)) { return $query; } $res = df_query($query); if (!$res) { return PEAR::raiseError("Failed to copy record '" . $record->getTitle() . "' due to an SQL error:" . xf_db_error()); } if (PEAR::isError($res)) { return $res; } $ret = null; if ($auto_field_id = $record->_table->getAutoIncrementField()) { $insert_id = df_insert_id(); $copied =& df_get_record($record->_table->tablename, array($auto_field_id => $insert_id)); $ret = $copied; } else { $ret = new Dataface_Record($record->_table->tablename, array_merge($record->vals(), $vals)); } if (isset($del) and method_exists($del, 'afterCopy')) { $res = $del->afterCopy($record, $ret); if (PEAR::isError($res)) { return $res; } } return $ret; }
function afterCopy(Dataface_Record $orig, Dataface_Record $copy) { $rand = md5(rand(0, 1000000)); $copytable = 'copy_' . $rand; $res = xf_db_query("create temporary table `{$copytable}` select * from formula_ingredients where formula_id='" . addslashes($orig->val('formula_id')) . "'", df_db()); if (!$res) { throw new Exception(xf_db_error(df_db())); } $res = xf_db_query("update `{$copytable}` set formula_id='" . addslashes($copy->val('formula_id')) . "'", df_db()); if (!$res) { throw new Exception(xf_db_error(df_db())); } $res = xf_db_query("insert into formula_ingredients select * from `{$copytable}`", df_db()); if (!$res) { throw new Exception(xf_db_error(df_db())); } $res = xf_db_query("drop table `{$copytable}`", df_db()); if (!$res) { throw new Exception(xf_db_error(df_db())); } }
function handle(&$params) { $app =& Dataface_Application::getInstance(); $context = array(); if (!is_array(@$app->_conf['_output_cache']) or !@$app->_conf['_output_cache']['enabled']) { $context['enabled'] = false; //return PEAR::raiseError('The output cache is currently disabled. You can enable it by adding an [_output_cache] section to your conf.ini file with a value \'enabled=1\''); } else { $context['enabled'] = true; } if (@$_POST['--clear-cache']) { // We should clear the cache @xf_db_query("delete from `__output_cache`", df_db()); $app->redirect($app->url('') . '&--msg=' . urlencode('The output cache has been successfully cleared.')); } $res = xf_db_query("select count(*) from `__output_cache`", df_db()); if (!$res) { throw new Exception(xf_db_error(df_db()), E_USER_ERROR); } list($numrows) = xf_db_fetch_row($res); $context['numrows'] = $numrows; df_display($context, 'manage_output_cache.html'); }
function handle($params) { $app =& Dataface_Application::getInstance(); if (!isset($_GET['key'])) { trigger_error("No key specified", E_USER_ERROR); } $sql = "select `value` from `" . TRANSLATION_PAGE_TABLE . "` where `key` = '" . addslashes($_GET['key']) . "'"; $res = xf_db_query($sql, $app->db()); if (!$res) { trigger_error(xf_db_error($app->db()), E_USER_ERROR); } if (xf_db_num_rows($res) == 0) { trigger_error("Sorry the specified key was invalid.", E_USER_ERROR); } list($content) = xf_db_fetch_row($res); @xf_db_free_result($res); if (function_exists('tidy_parse_string')) { $config = array('show-body-only' => true, 'output-encoding' => 'utf8'); $html = tidy_repair_string($content, $config, "utf8"); $content = trim($html); } df_display(array('content' => $content), 'TranslationPageTemplate.html'); return true; }
function handle(&$params) { import('Dataface/TranslationForm.php'); $app =& Dataface_Application::getInstance(); $query =& $app->getQuery(); $resultSet =& $app->getResultSet(); $source = isset($_REQUEST['-sourceLanguage']) ? $_REQUEST['-sourceLanguage'] : $app->_conf['default_language']; $dest = isset($_REQUEST['-destinationLanguage']) ? $_REQUEST['-destinationLanguage'] : null; if ($resultSet->found() > 0) { $form = new Dataface_TranslationForm($query['-table'], $source, $dest); /* * There is either a result to edit, or we are creating a new record. * */ $res = $form->_build(); if (PEAR::isError($res)) { throw new Exception($res->toString() . Dataface_Error::printStackTrace(), E_USER_ERROR); } /* * * We need to add the current GET parameter flags (the GET vars starting with '-') so * that the controller knows to pass control to this method again upon form submission. * */ foreach ($query as $key => $value) { if (strpos($key, '-') === 0) { $form->addElement('hidden', $key); $form->setDefaults(array($key => $value)); } } /* * Store the current query string (the portion after the '?') in the form, so we * can retrieve it after and redirect back to our original location. */ $form->addElement('hidden', '-query'); $form->setDefaults(array('-action' => $query['-action'], '-query' => $_SERVER['QUERY_STRING'])); /* * * We have to deal with 3 cases. * 1) The form has not been submitted. * 2) The form was submitted but didn't validate (ie: it had some bad input) * 3) The form was submitted and was validated. * * We deal with Case 3 first... * */ if ($form->validate()) { /* * * The form was submitted and it validated ok. We now process it (ie: save its contents). * */ $app->clearMessages(); $result = $form->process(array(&$form, 'save')); $success = true; $response =& Dataface_Application::getResponse(); if (!$result) { error_log("Error occurred in save: " . xf_db_error($app->db()) . Dataface_Error::printStackTrace()); throw new Exception("Error occurred in save. See error log for details."); } else { if (PEAR::isError($result) && !Dataface_Error::isNotice($result)) { //echo "Error.."; if (Dataface_Error::isDuplicateEntry($result)) { return $result; } else { //echo "not dup entry"; exit; throw new Exception($result->toString(), E_USER_ERROR); } } else { if (Dataface_Error::isNotice($result)) { $app->addError($result); //$response['--msg'] = @$response['--msg'] ."\n".$result->getMessage(); $success = false; } } } if ($success) { /* * * The original query string will have the -new flag set. We need to remove this * flag so that we don't redirect the user to create another new record. * */ $vals = $form->exportValues(); $vals['-query'] = preg_replace('/[&\\?]-new=[^&]+/i', '', $vals['-query']); $msg = implode("\n", $app->getMessages()); //$msg =@$response['--msg']; $msg = urlencode(Dataface_LanguageTool::translate('Record successfully translated', "Record successfully translated.<br>") . $msg); $link = $_SERVER['HOST_URI'] . DATAFACE_SITE_HREF . '?' . $vals['-query'] . '&--msg=' . $msg; /* * * Redirect the user to the appropriate record. * */ $app->redirect($link); } } ob_start(); $form->display(); $out = ob_get_contents(); ob_end_clean(); $context = array('form' => $out, 'formObj' => $form); } else { // no records were found $context = array('form' => '', 'formObj' => $form); $app->addMessage(Dataface_LanguageTool::translate('No records matched request', 'No records matched your request')); } if (isset($query['-template'])) { $template = $query['-template']; } else { if (isset($params['action']['template'])) { $template = $params['action']['template']; } else { $template = 'Dataface_Translate_Record.html'; } } df_display($context, $template, true); }
function &loadCurrent($columns = null, $loadText = true, $loadBlobs = false, $loadPasswords = false) { $app =& Dataface_Application::getInstance(); $false = false; // boolean placeholders for values needing to be returned by reference $true = true; if ($this->_currentRecord === null) { //require_once 'Dataface/IO.php'; //$io = new Dataface_IO($this->_table->tablename); //$query = array_merge( $this->_query, array('-skip'=>$this->_data['cursor'], '-limit'=>1) ); $this->_currentRecord = new Dataface_Record($this->_table->tablename, array()); //$io->read($query, $this->_currentRecord); } //return $this->_currentRecord; $unloaded = array(); $fields =& $this->_table->fields(false, true); if ($columns === null) { $names = array_keys($fields); } else { $names = $columns; } foreach ($names as $name) { if (!$this->_currentRecord->isLoaded($name)) { if (!$loadText and $this->_table->isText($name)) { continue; } if (!$loadBlobs and $this->_table->isBlob($name)) { continue; } if (!$loadPasswords and $this->_table->isPassword($name)) { continue; } $unloaded[] = $name; } } if (sizeof($unloaded) > 0) { $query = array_merge($this->_query, array('-skip' => $this->_data['cursor'], '-limit' => 1)); $builder = new Dataface_QueryBuilder($this->_tablename, $query); $builder->selectMetaData = true; $builder->_omitBlobs = false; $sql = $builder->select($unloaded); //echo $sql; if (PEAR::isError($sql)) { throw new Exception($sql->toString(), E_USER_ERROR); } //echo $sql; $res = $this->dbObj->query($sql, $this->_db, null, true); if (!$res and !is_array($res)) { $app->refreshSchemas($this->_table->tablename); $res = $this->dbObj->query($sql, $this->_db, null, true); if (!$res and !is_array($res)) { error_log(df_translate('scripts.Dataface.QueryTool.loadCurrent.ERROR_COULD_NOT_LOAD_CURRENT_RECORD', "Error: Could not load current record: ") . xf_db_error($this->_db) . "\n{$sql}"); throw new Exception("Failed to load current record due to an SQL error"); } } if (count($res) <= 0) { return $false; } $row = $res[0]; //xf_db_fetch_assoc($res); //@xf_db_free_result($row); if (!isset($this->_currentRecord)) { $this->_currentRecord = new Dataface_Record($this->_table->tablename, $row); } else { $this->_currentRecord->setValues($row); } //$this->_table->setValues($row); //$this->_table->setSnapshot(); //$this->_table->deserialize(); } return $this->_currentRecord; }
function delete_request_with_uuid($uuid) { $table = self::$TABLE_RESET_PASSWORD; $res = xf_db_query("delete from `{$table}` where request_uuid='" . addslashes($uuid) . "' limit 1", df_db()); if (!$res) { throw new Exception(xf_db_error(df_db())); } }
function test_translateDeleteQuery() { $app =& Dataface_Application::getInstance(); // Try to insert only values into both the base table and the // translated table. $sql = 'Delete FROM PeopleIntl where PersonID=5'; $translator = new Dataface_QueryTranslator('en'); $tsql = $translator->translateQuery($sql); //print_r($tsql);exit; $affected_rows = array(); foreach ($tsql as $q) { $res = xf_db_query($q, $app->db()); if (!$res) { die(xf_db_error($app->db())); } $affected_rows[$q] = xf_db_affected_rows($app->db()); } $this->assertEquals(array("delete from `PeopleIntl` where `PersonID` = 5", "delete from `PeopleIntl_en` where `PersonID` = 5", "delete from `PeopleIntl_fr` where `PersonID` = 5"), $tsql); $this->assertEquals(array("delete from `PeopleIntl` where `PersonID` = 5" => 1, "delete from `PeopleIntl_en` where `PersonID` = 5" => 0, "delete from `PeopleIntl_fr` where `PersonID` = 5" => 0), $affected_rows); }
function handle(&$params) { import('Dataface/FormTool.php'); import('Dataface/QuickForm.php'); $formTool =& Dataface_FormTool::getInstance(); $app =& Dataface_Application::getInstance(); $query =& $app->getQuery(); $resultSet =& $app->getResultSet(); $currentRecord =& $app->getRecord(); $currentTable =& Dataface_Table::loadTable($query['-table']); if (!isset($query['--tab']) and count($currentTable->tabs($currentRecord)) > 1) { $tabs = $currentTable->tabs($currentRecord); uasort($tabs, array($formTool, '_sortTabs')); list($query['--tab']) = array_keys($tabs); } else { if (count($currentTable->tabs($currentRecord)) <= 1) { unset($query['--tab']); } } $includedFields = null; // Null for all fields if (@$query['-fields']) { $includedFields = explode(' ', $query['-fields']); } /* * * Create the quickform for the current record. * */ //$form = new Dataface_QuickForm($query['-table'], $app->db(), $query); if ($resultSet->found() > @$query['-cursor']) { $form = $formTool->createRecordForm($currentRecord, false, @$query['--tab'], $query, $includedFields); /* * There is either a result to edit, or we are creating a new record. * */ $res = $form->_build(); if (PEAR::isError($res)) { error_log($res->toString() . implode("\n", $res->getBacktrace())); throw new Exception("An error occurred while building the edit form. See error log for details.", E_USER_ERROR); } $formTool->decorateRecordForm($currentRecord, $form, false, @$query['--tab']); /* * * We need to add the current GET parameter flags (the GET vars starting with '-') so * that the controller knows to pass control to this method again upon form submission. * */ foreach ($query as $key => $value) { if (strpos($key, '-') === 0) { $form->addElement('hidden', $key); $form->setDefaults(array($key => $value)); } } /* * Store the current query string (the portion after the '?') in the form, so we * can retrieve it after and redirect back to our original location. */ $form->addElement('hidden', '-query'); $form->setDefaults(array('-action' => $query['-action'], '-query' => $_SERVER['QUERY_STRING'])); /* * * We have to deal with 3 cases. * 1) The form has not been submitted. * 2) The form was submitted but didn't validate (ie: it had some bad input) * 3) The form was submitted and was validated. * * We deal with Case 3 first... * */ if ($formTool->validateRecordForm($currentRecord, $form, false, @$query['--tab'])) { /* * * The form was submitted and it validated ok. We now process it (ie: save its contents). * */ $app->clearMessages(); $formTool->handleTabSubmit($currentRecord, $form, @$query['--tab']); if (!isset($query['--tab'])) { // If we aren't using tabs we just do it the old way. // (If it ain't broke don't fix it $result = $form->process(array(&$form, 'save')); } else { // If we are using tabs, we will use the formtool's // session aware saving function $result = $formTool->saveSession($currentRecord); } $success = true; $response =& Dataface_Application::getResponse(); if (!$result) { error_log("Error occurred in save: " . xf_db_error($app->db()) . Dataface_Error::printStackTrace()); throw new Exception("An error occurred while attempting to save the record. See error log for details.", E_USER_ERROR); } else { if (PEAR::isError($result) && !Dataface_Error::isNotice($result)) { if (Dataface_Error::isDuplicateEntry($result)) { $app->addError($result); $success = false; } else { error_log($result->toString() . implode("\n", $result->getBacktrace())); throw new Exception("An error occurred while attempting to save the record. See error log for details.", E_USER_ERROR); } } else { if (Dataface_Error::isNotice($result)) { $app->addError($result); //$response['--msg'] = @$response['--msg'] ."\n".$result->getMessage(); $success = false; } } } if ($success) { if (@$query['-response'] == 'json') { //header('Content-type: text/html; charset="'.$app->_conf['oe'].'"'); $rvals = $currentRecord->strvals(); $rvals['__title__'] = $currentRecord->getTitle(); $rvals['__id__'] = $currentRecord->getId(); echo df_escape(json_encode(array('response_code' => 200, 'record_data' => $rvals, 'response_message' => df_translate('Record Successfully Saved', 'Record Successfully Saved')))); return; } import('Dataface/Utilities.php'); Dataface_Utilities::fireEvent('after_action_edit', array('record' => $form->_record)); /* * * The original query string will have the -new flag set. We need to remove this * flag so that we don't redirect the user to create another new record. * */ $vals = $form->exportValues(); $vals['-query'] = preg_replace('/[&\\?]-new=[^&]+/i', '', $vals['-query']); $_SESSION['--last_modified_record_url'] = $form->_record->getURL(); $_SESSION['--last_modified_record_title'] = $form->_record->getTitle(); $msg = implode("\n", $app->getMessages()); //$msg =@$response['--msg']; $msg = urlencode(Dataface_LanguageTool::translate('Record successfully saved', "Record successfully saved.<br>") . $msg); if (preg_match('/[&\\?]-action=edit&/', $vals['-query']) and !$form->_record->checkPermission('edit')) { $vals['-query'] = preg_replace('/([&\\?])-action=edit&/', '$1-action=view&', $vals['-query']); } else { if (preg_match('/[&\\?]-action=edit$/', $vals['-query']) and !$form->_record->checkPermission('edit')) { $vals['-query'] = preg_replace('/([&\\?])-action=edit$/', '$1-action=view', $vals['-query']); } } $vals['-query'] = preg_replace('/&?--msg=[^&]*/', '', $vals['-query']); if (@$query['--lang']) { $vals['-query'] .= '&--lang=' . $query['--lang']; } $link = $_SERVER['HOST_URI'] . DATAFACE_SITE_HREF . '?' . $vals['-query'] . '&--saved=1&--msg=' . $msg; /* * * Redirect the user to the appropriate record. * */ $app->redirect("{$link}"); } } ob_start(); $form->display(); $out = ob_get_contents(); ob_end_clean(); if (count($form->_errors) > 0) { $app->clearMessages(); $app->addError(PEAR::raiseError("Some errors occurred while processing this form: <ul><li>" . implode('</li><li>', $form->_errors) . "</li></ul>")); } $context = array('form' => $out); // Now let's add the tabs to the context $context['tabs'] = $formTool->createHTMLTabs($currentRecord, $form, @$query['--tab']); } else { // no records were found $context = array('form' => ''); if (isset($_SESSION['--last_modified_record_url'])) { $lastModifiedURL = $_SESSION['--last_modified_record_url']; $lastModifiedTitle = $_SESSION['--last_modified_record_title']; unset($_SESSION['--last_modified_record_title']); unset($_SESSION['--last_modified_record_url']); $app->addMessage(df_translate('Return to last modified record', 'No records matched your request. Click <a href="' . $lastModifiedURL . '">here</a> to return to <em>' . df_escape($lastModifiedTitle) . '</em>.', array('lastModifiedURL' => $lastModifiedURL, 'lastModifiedTitle' => $lastModifiedTitle))); } else { $app->addMessage(Dataface_LanguageTool::translate('No records matched request', 'No records matched your request')); } $query['-template'] = 'Dataface_Main_Template.html'; } if (isset($query['-template'])) { $template = $query['-template']; } else { if (@$query['-headless']) { $template = 'Dataface_Edit_Record_headless.html'; } else { if (isset($params['action']['template'])) { $template = $params['action']['template']; } else { $template = 'Dataface_Edit_Record.html'; } } } df_display($context, $template, true); }
function handle(&$params) { $app = Dataface_Application::getInstance(); header('Content-type: text/html; charset=' . $app->_conf['oe']); $record =& $app->getRecord(); $query =& $app->getQuery(); if (isset($_REQUEST['-form-id'])) { $formid = $_REQUEST['-form-id']; } else { $formid = 'ajax-form-' . rand(); } // First let's figure out what kind of form this is $form_type = @$_REQUEST['-form-type']; $form = null; if (isset($_REQUEST['-fields'])) { $fields = explode(',', $_REQUEST['-fields']); } else { $fields = null; } switch ($form_type) { case 'new': $form = df_create_new_record_form($query['-table'], $fields); $form->_build(); break; case 'edit': $form = df_create_edit_record_form($query['-table'], $fields); break; case 'new_related_record': $form = df_create_new_related_record_form($record, $query['-relationship'], $fields); break; case 'existing_related_record': $form = df_create_existing_related_record_form($record, $query['-relationship']); break; case 'composite': import('Dataface/CompositeForm.php'); $form = new Dataface_CompositeForm($fields); $form->build(); break; default: @(include_once 'forms/' . $form_type . '.php'); if (!class_exists('forms_' . $form_type)) { return PEAR::raiseError('Could not find form of type "' . $form_type . '".', DATAFACE_E_ERROR); } $classname = 'forms_' . $form_type; $form = new $classname($fields); break; } // We want the form to be submitted to the embedded iframe $form->updateAttributes(array('target' => $formid . '-target', 'accept-charset' => $app->_conf['ie'])); $formparams = preg_grep('/^-[^\\-].*/', array_keys($query)); foreach ($formparams as $param) { $form->addElement('hidden', $param); $form->setDefaults(array($param => $query[$param])); } $form->addElement('hidden', '-form-id'); $form->setDefaults(array('-form-id' => $formid)); // Now that we have our form, we can do our thing with it. if ($form->validate()) { /* * * The form was submitted and it validated ok. We now process it (ie: save its contents). * */ $app->clearMessages(); $result = $form->process(array(&$form, 'save')); $success = true; $response =& Dataface_Application::getResponse(); if (!$result) { trigger_error("Error occurred in save: " . xf_db_error($app->db()) . Dataface_Error::printStackTrace(), E_USER_ERROR); exit; } else { if (PEAR::isError($result) && !Dataface_Error::isNotice($result)) { if (Dataface_Error::isDuplicateEntry($result)) { return $result; } else { trigger_error($result->toString() . Dataface_Error::printStackTrace(), E_USER_ERROR); exit; } } else { if (Dataface_Error::isNotice($result)) { $app->addError($result); $success = false; } } } if ($success) { import('Dataface/Utilities.php'); Dataface_Utilities::fireEvent('after_action_ajax_form'); $msg = implode("\n", $app->getMessages()); //$msg =@$response['--msg']; $msg = urlencode(Dataface_LanguageTool::translate('Record successfully saved', "Record successfully saved.<br>") . $msg); // We need to output the success content. // This could be in any of the following formats: // 1. HTML --- actually not yet.. let's just do JSON // 2. JSON // 3. XML --- not yet.. just JSON for now. $targetid = @$_REQUEST['-target-id']; // This should: // 1. Get the target element. // 2. Go through the element's subtree and replace // values that have been changed. How do we know what // values have been changed. // if (method_exists($form, 'htmlValues')) { if (method_exists($form, 'changedFields')) { $changed_fields = $form->changedFields(); } else { $changed_fields = null; } // Convert the values to JSON $changed_values = $form->htmlValues($changed_fields); import('Services/JSON.php'); $json = new Services_JSON(); $changed_values_json = $json->encode($changed_values); } else { $changed_values_json = '{}'; } echo <<<END <html><body><script language="javascript"><!-- \t \t//self.onload = function(){ \t\t//parent.handleEditableResponse('{$targetid}', {$changed_values_json}); \t\tvar targetel = parent.document.getElementById('{$targetid}'); \t\ttargetel.handleResponse('{$targetid}', {$changed_values_json}); \t\ttargetel.onclick=parent.makeEditable; \t\ttargetel.onmouseover=targetel.old_onmouseover; \t\ttargetel.edit_form.parentNode.removeChild(targetel.edit_form); \t \t//} \t \t //--></script></body></html> END; exit; } } import('Dataface/FormTool.php'); $formTool = new Dataface_FormTool(); ob_start(); if (is_array($fields) and count($fields) == 1 and strpos($fields[0], '#') !== false) { $singleField = $fields[0]; } else { $singleField = false; } $formTool->display($form, null, $singleField); $out = ob_get_contents(); ob_end_clean(); echo <<<END \t\t \t\t<div id="{$formid}-wrapper"> \t\t\t<iframe id="{$formid}-target" name="{$formid}-target" style="width:0px; height:0px; border: 0px"></iframe> \t\t\t{$out} \t\t</div> END; if ($form->isSubmitted()) { // The form has already been submitted so we must be displaying some // errors. We need to remove this stuff from inside the iframe // that we are going to be inside of, and place them on the page // in the correct place echo <<<END <script language="javascript"><!-- var targetel = parent.document.getElementById('{$formid}-wrapper'); var sourceel = document.getElementById('{$formid}-wrapper'); targetel.innerHTML = sourceel.innerHTML; //--></script> END; } exit; }
/** * Returns an array of the meta fields from the history table in descending order * of modified date. * @param Dataface_Record &$record The record we wish to obtain history for. * @param string $lang The 2-digit language code. * @param integer $limit The maximum number of records to return. null for unlimited. * @returns Array of Associative arrays. */ function getHistoryLog(&$record, $lang = null, $limit = 100) { $app =& Dataface_Application::getInstance(); $history_tablename = $record->_table->tablename . '__history'; if (!Dataface_Table::tableExists($history_tablename)) { return array(); } $keys = $record->strvals(array_keys($record->_table->keys())); $clauses = array(); foreach ($keys as $key => $val) { $clauses[] = "`{$key}`='" . addslashes($val) . "'"; } if (isset($lang)) { $clauses[] = "`history__language` = '" . addslashes($lang) . "'"; } $where = implode(' and ', $clauses); if (isset($limit)) { $limit = "LIMIT {$limit}"; } else { $limit = ''; } $sql = "select `" . implode('`,`', array_keys($this->meta_fields)) . "` from `{$history_tablename}` where {$where} order by `history__modified` desc {$limit}"; //echo $sql; $res = xf_db_query($sql, $app->db()); if (!$res) { trigger_error(xf_db_error($app->db()), E_USER_ERROR); } $out = array(); while ($row = xf_db_fetch_assoc($res)) { $out[] = $row; } @xf_db_free_result($res); return $out; }
function handle(&$params) { $app = Dataface_Application::getInstance(); if (!isset($_GET['code'])) { // We need this parameter or we can do nothing. return PEAR::raiseError(df_translate('actions.activate.MESSAGE_MISSING_CODE_PARAMETER', 'The code parameter is missing from your request. Validation cannot take place. Please check your url and try again.'), DATAFACE_E_ERROR); } // Step 0: Find out what the redirect URL will be // We accept --redirect markers to specify which page to redirect // to after we're done. This will usually be the page that the // user was on before they went to the login page. if (isset($_SESSION['--redirect'])) { $url = $_SESSION['--redirect']; } else { if (isset($_SESSION['-redirect'])) { $url = $_SESSION['-redirect']; } else { if (isset($_REQUEST['--redirect'])) { $url = $_REQUEST['--redirect']; } else { if (isset($_REQUEST['-redirect'])) { $url = $_REQUEST['-redirect']; } else { $url = $app->url('-action=' . $app->_conf['default_action']); } } } } if (strpos($url, '?') === false) { $url .= '?'; } // Step 1: Delete all registrations older than time limit $time_limit = 24 * 60 * 60; // 1 day if (isset($params['time_limit'])) { $time_limit = intval($params['time_limit']); } $res = xf_db_query("delete from dataface__registrations \n\t\t\t\twhere registration_date < '" . addslashes(date('Y-m-d H:i:s', time() - $time_limit)) . "'", df_db()); if (!$res) { error_log(xf_db_error(df_db())); throw new Exception("Failed to delete registrations due to an SQL error. See error log for details.", E_USER_ERROR); } // Step 2: Load the specified registration information $res = xf_db_query("select registration_data from dataface__registrations\n\t\t\t\twhere registration_code = '" . addslashes($_GET['code']) . "'", df_db()); if (!$res) { error_log(xf_db_error(df_db())); throw new Exception("Failed to load registration information due to an SQL error. See error log for details.", E_USER_ERROR); } if (xf_db_num_rows($res) == 0) { // We didn't find any records matching the prescribed code, so // we redirect the user to their desired page and inform them // that the registration didn't work. $msg = df_translate('actions.activate.MESSAGE_REGISTRATION_NOT_FOUND', 'No registration information could be found to match this code. Please try registering again.'); $app->redirect($url . '&--msg=' . urlencode($msg)); } // Step 3: Check to make sure that there are no other users with the // same name. list($raw_data) = xf_db_fetch_row($res); $values = unserialize($raw_data); $appdel = $app->getDelegate(); if (isset($appdel) and method_exists($appdel, 'validateRegistrationForm')) { $res = $appdel->validateRegistrationForm($values); if (PEAR::isError($res)) { $msg = $res->getMessage(); $app->redirect($url . '&--msg=' . urlencode($msg)); } } else { $res = xf_db_query("select count(*) from \n\t\t\t\t`" . str_replace('`', '', $app->_conf['_auth']['users_table']) . "` \n\t\t\t\twhere `" . str_replace('`', '', $app->_conf['_auth']['username_column']) . "` = '" . addslashes($values[$app->_conf['_auth']['username_column']]) . "'\n\t\t\t\t", df_db()); if (!$res) { error_log(xf_db_error(df_db())); throw new Exception("Failed to find user records due to an SQL error. See error log for details.", E_USER_ERROR); } list($num) = xf_db_fetch_row($res); if ($num > 0) { $msg = df_translate('actions.activate.MESSAGE_DUPLICATE_USER', 'Registration failed because a user already exists by that name. Try registering again with a different name.'); $app->redirect($url . '&--msg=' . urlencode($msg)); } } // Step 4: Save the registration data and log the user in. $record = new Dataface_Record($app->_conf['_auth']['users_table'], array()); $record->setValues($values); $res = $record->save(); if (PEAR::isError($res)) { $app->redirect($url . '&--msg=' . urlencode($res->getMessage())); } else { $res = xf_db_query("delete from dataface__registrations\n\t\t\t\t\twhere registration_code = '" . addslashes($_GET['code']) . "'", df_db()); if (!$res) { error_log(xf_db_error(df_db())); throw new Exception("Failed to clean up old registrations due to an SQL error. See error log for details.", E_USER_ERROR); } $msg = df_translate('actions.activate.MESSAGE_REGISTRATION_COMPLETE', 'Registration complete. You are now logged in.'); $_SESSION['UserName'] = $record->strval($app->_conf['_auth']['username_column']); import('Dataface/Utilities.php'); Dataface_Utilities::fireEvent('after_action_activate', array('record' => $record)); $app->redirect($url . '&--msg=' . urlencode($msg)); } }
/** * @brief Cleans up old import tables. Any import tables older (in seconds) than the * garbage collector threshold (as defined in $app->_conf['garbage_collector_threshold']) * will be dropped. * * * */ function cleanImportTables() { $tables = $this->getImportTables(); $app =& Dataface_Application::getInstance(); $garbageLifetime = $app->_conf['garbage_collector_threshold']; foreach ($tables as $table) { $matches = array(); if (preg_match('/^' . $this->tablename . '__import_(\\d+)_(\\d)$/', $table, $matches)) { if (time() - intval($matches[1]) > intval($garbageLifetime)) { $res = xf_db_query("DROP TABLE `{$table}`", $this->db); if (!$res) { throw new Exception("Problem occurred attemtping to clean up old import table '{$table}'. MySQL returned an error: " . xf_db_error($this->db) . "\n", E_USER_ERROR); } } } } }
/** * @brief Returns the total number of related records for a given relationship. * * @section Examples * @subsection default_usage Default Usage * @code * if ( $record->numRelatedRecords('books') > 0 ){ * echo "There are ".$record->numRelatedRecords('books')." books."; * } else { * echo "There are no books."; * } * @endcode * * @subsection where_clause Using 'Where' Clause * * The following example counts the number of books in the relationship that * where published in 1986. * @code * $numBooksIn1986 = $record->numRelatedRecords('books', "year='1986'"); * @endcode * * @param string $relname The relationship name. * @param mixed $where * (optional) String where clause that can be used to filter the records. * * @return Integer number of records in this relationship. * * @since 0.5 * * @see http://xataface.com/documentation/tutorial/getting_started/relationships * @see http://www.xataface.com/wiki/relationships.ini_file */ function numRelatedRecords($relname, $where = 0) { if (!isset($this->_numRelatedRecords[$relname][$where])) { $relationship =& $this->_table->getRelationship($relname); if (PEAR::isError($relationship)) { throw new Exception($relationship->getMessage()); } //if ( $where !== 0 ){ $sql = $this->parseString($relationship->getSQL($this->loadBlobs, $where)); //} else { // $sql = $this->parseString($relationship->_schema['sql']); //} $sql = stristr($sql, ' FROM '); $sql = "SELECT COUNT(*) as num" . $sql; //$dbObj = //$res = xf_db_query($sql, $this->_table->db); //$res = xf_db_query($sql, $this->_table->db); $db =& Dataface_DB::getInstance(); $res = $db->query($sql, $this->_table->db, null, true); if (!$res and !is_array($res)) { //if ( !$res ){ throw new Exception(df_translate('scripts.Dataface.Record.numRelatedRecords.ERROR_CALCULATING_NUM_RELATED_RECORDS', "Error calculating the number of related records there are for the relationship '{$relname}' in the table '" . $this->_table->tablename . "'. There was a problem performing the sql query '{$sql}'. The MYSQL error returned was '" . xf_db_error($this->_table->db) . "'.\n<br>", array('relationship' => $relname, 'table' => $this->_table->tablename, 'xf_db_error' => xf_db_error($this->_table->db), 'sql' => $sql)), E_USER_ERROR); } $this->_numRelatedRecords[$relname][$where] = $res[0]['num']; } return $this->_numRelatedRecords[$relname][$where]; }
function _loadValuelistsIniFile_old() { if (!isset($this->_valuelists)) { $this->_valuelists = array(); } $valuelists =& $this->_valuelists; if ($this->_hasValuelistsIniFile()) { $conf = parse_ini_file($this->_valuelistsIniFilePath(), true); foreach ($conf as $vlname => $vllist) { $valuelists[$vlname] = array(); if (is_array($vllist)) { foreach ($vllist as $key => $value) { if ($key == '__sql__') { // we perform the sql query specified to produce our valuelist. // the sql query should return two columns only. If more are // returned, only the first two will be used. If one is returned // it will be used as both the key and value. $res = df_query($value, null, true, true); if (is_array($res)) { //while ($row = xf_db_fetch_row($res) ){ foreach ($res as $row) { $valuekey = $row[0]; $valuevalue = count($row) > 1 ? $row[1] : $row[0]; $valuelists[$vlname][$valuekey] = $valuevalue; if (count($row) > 2) { $valuelists[$vlname . '__meta'][$valuekey] = $row[2]; } } } else { throw new Exception('Valuelist sql query failed: ' . $value . ': ' . xf_db_error(), E_USER_NOTICE); } } else { $valuelists[$vlname][$key] = $value; } } } } } }
/** * @brief Updates a module so that the database version is the same * as the file system version. * @param string $modname The name of the module. * @param string $path The path to the module. */ public function updateModule($modname, $path) { $installpath = dirname($path) . DIRECTORY_SEPARATOR . 'installer.php'; if (file_exists($installpath)) { import($installpath); $classname = $modname . '_installer'; $installer = new $classname(); $methods = get_class_methods($classname); $methods = preg_grep('/^update_([0-9]+)$/', $methods); $updates = array(); $fsversion = $this->getFsVersion($modname, $path); $dbversion = $this->getDbVersion($modname); foreach ($methods as $method) { preg_match('/^update_([0-9]+)$/', $method, $matches); $version = intval($matches[1]); if ($version > $dbversion and $version <= $fsversion) { $updates[] = $version; } } sort($updates); if ($dbversion == 0) { $res = xf_db_query("insert into dataface__modules (module_name,module_version)\n\t\t\t\t\tvalues ('" . addslashes($modname) . "',-1)", df_db()); if (!$res) { throw new Exception(xf_db_error(df_db())); } } foreach ($updates as $update) { $method = 'update_' . $update; $res = $installer->{$method}(); if (PEAR::isError($res)) { return $res; } $res = xf_db_query("update dataface__modules set `module_version`='" . addslashes($update) . "'", df_db()); if (!$res) { throw new Exception(xf_db_error(df_db()), E_USER_ERROR); } } $res = xf_db_query("update dataface__modules set `module_version`='" . addslashes($fsversion) . "'", df_db()); if (!$res) { throw new Exception(xf_db_error(df_db()), E_USER_ERROR); } } }
function &getRecords() { if (!isset($this->_records)) { $this->_records = array(); $sql = $this->_queryBuilder->select(); $sqlStats = $this->_queryBuilder->select_num_rows(); $db =& Dataface_DB::getInstance(); $res = $db->query($sqlStats, $this->_table->db, null, true); //if ( !$res and !is_array($res) ){ $this->_totalRecords = $res[0]['num']; //list($this->_totalRecords) = xf_db_fetch_row( xf_db_query( $sqlStats, $this->_db ) ); //$res = xf_db_query($sql, $this->_db); $res = $db->query($sql, $this->_table->db, null, true); if (!$res and !is_array($res)) { throw new Exception("An error occurred attempting to retrieve records from the database.: " . xf_db_error($this->db), E_USER_ERROR); } $this->_displayedRecords = count($res); //while ( $row = xf_db_fetch_array($res) ){ foreach ($res as $row) { $this->_records[] = $row; } } return $this->_records; }
function writeConfigToDB() { import('Dataface/Table.php'); import('Dataface/Record.php'); import('Dataface/IO.php'); if (!is_a($this, 'Dataface_ConfigTool')) { throw new Exception('ConfigWriter methods are only to be used via the Dataface_ConfigTool class.', E_USER_ERROR); } $this->loadAllConfig(); $app =& Dataface_Application::getInstance(); // first let's make copies of the current configuration. $timestamp = time(); foreach ($this->configTypes as $type) { $res = xf_db_query("CREATE TABLE `__" . addslashes($type) . "__" . $timestamp . "` SELECT * FROM `__" . addslashes($type) . "__`", $app->db()); if (!$res) { throw new Exception("Failed to make backup of table '__" . $type . "__'." . xf_db_error($app->db()), E_USER_ERROR); } } $res = xf_db_query("CREATE TABLE `__properties__" . $timestamp . "` SELECT * FROM `__properties__`", $app->db()); if (!$res) { throw new Exception("Failed to make backup of table '__properties__'.", $app->db()); } // Now that we have made our backups, we can continue to write the configuration to the database. //print_r($this->config); foreach ($this->configTypes as $type) { $res = xf_db_query("DELETE FROM `__" . addslashes($type) . "__`", $app->db()); if (!$res) { throw new Exception("Failed to delete all records from table '__" . $type . "__'", $app->db()); } foreach ($this->config[$type] as $tablename => $tableConfig) { foreach ($tableConfig as $sectionname => $section) { $tableObj =& Dataface_Table::loadTable('__' . $type . '__'); $record = new Dataface_Record('__' . $type . '__', array()); $record->useMetaData = false; // some of the field names begin with '__' which would conflict with dataface's handling of MetaData fields. foreach (array_keys($tableObj->fields()) as $fieldname) { $record->setValue($fieldname, @$section[$fieldname]); unset($section[$fieldname]); } $record->setValue('name', $sectionname); $record->setValue('table', $tablename); //echo nl2br("Section name: $sectionname\nTable: $tablename\n"); //print_r($record->strvals()); echo nl2br("\nWriting section: {$sectionname} : "); print_r($record->strvals()); // now that we have created the record, we write the record $io = new Dataface_IO('__' . $type . '__'); $res = $io->write($record); if (PEAR::isError($res)) { throw new Exception($res->toString(), E_USER_ERROR); } else { if (!$res) { throw new Exception("Failure to write to database for unknown reason.", E_USER_ERROR); } } // now for the rest of the properties. foreach ($section as $propertyName => $propertyValue) { $res = xf_db_query("\n\t\t\t\t\t\t\tINSERT INTO \n\t\t\t\t\t\t\t `__properties__` \n\t\t\t\t\t\t\t (`parent_id`,`parent_type`,`property_name`,`property_value`)\n\t\t\t\t\t\t\tVALUES\n\t\t\t\t\t\t\t ('" . $record->val($type . '_id') . "', \n\t\t\t\t\t\t\t '" . addslashes($type) . "',\n\t\t\t\t\t\t\t '" . addslashes($propertyName) . "',\n\t\t\t\t\t\t\t '" . addslashes($propertyValue) . "')", $app->db()); if (!$res) { throw new Exception("Failed to add property '{$propertyName}' to table '__properties__' with value '{$propertyValue}'" . xf_db_error($app->db()), E_USER_ERROR); } } unset($tableObj); unset($record); unset($io); } } } }
/** * Refreshes the metadata table for a given table. This means that missing * columns and keys are created so that the schema matches the schema of * the current table structure. * * @param string $tablename The name of the table for which the metadata is being * stored. */ function refreshMetadataTable($tablename = null) { if (!isset($tablename)) { $tablename = $this->tablename; } if (Dataface_MetadataTool::isMetadataTable($tablename)) { return false; } $app =& Dataface_Application::getInstance(); $table =& Dataface_Table::loadTable($tablename); $md_tablename = $tablename . '__metadata'; if (!Dataface_Table::tableExists($md_tablename, false)) { if ($this->createMetadataTable($tablename)) { return true; } } $cols =& $this->getColumns($tablename, false); // First we have to go through all of the key fields of the subject table // and make sure that they appear in the metadata table. $updatePrimaryKey = false; foreach ($table->keys() as $field) { if (!isset($cols[$field['Field']])) { $updatePrimaryKey = true; $default = @$field['Default'] ? " DEFAULT {$field['Default']}" : ''; $sql = "alter table `{$md_tablename}` add column `{$field['Field']}` {$field['Type']}{$default}"; $res = xf_db_query($sql, $app->db()); if (!$res) { trigger_error(xf_db_error($app->db()), E_USER_ERROR); } } } $table_keys =& $table->keys(); //Next we have to go through all of the key fields in the metadata table ane make sure that they // appear in the subject table primary keys. foreach ($this->getKeyColumns($tablename, false) as $field) { if (!isset($table_keys[$field['Field']])) { $updatePrimaryKey = true; $sql = "alter table `{$md_tablename}` drop column `{$field['Field']}`"; $res = xf_db_query($sql, $app->db()); if (!$res) { trigger_error(xf_db_error($app->db()), E_USER_ERROR); } } } // If the primary key needed to be updated, we will update it now. if ($updatePrimaryKey) { // The primary key needs to be updated $sql = "drop primary key"; @xf_db_query($sql, $app->db()); $sql = "alter table `{$md_tablename}` add primary key (`" . implode('`,`', array_keys($table->keys())) . "`)"; $res = xf_db_query($sql, $app->db()); if (!$res) { trigger_error(xf_db_error($app->db()), E_USER_ERROR); } } // Now we need to make sure that all of the prescribed meta fields are // in the metadata field. $fielddefs = $this->loadMetadataFieldDefs($tablename); $cols = $this->getColumns($tablename, false); foreach ($fielddefs as $field) { if (!isset($cols[$field['Field']])) { $default = @$field['Default'] ? " DEFAULT {$field['Default']}" : ''; $sql = "alter table `{$md_tablename}` add column `{$field['Field']}` {$field['Type']}{$default}"; $res = xf_db_query($sql, $app->db()); if (!$res) { trigger_error(xf_db_error($app->db()), E_USER_ERROR); } } } return true; }
function df_q($sql) { if (is_array($sql)) { foreach ($sql as $q) { $res = df_q($q); } return $res; } else { $res = xf_db_query($sql, df_db()); if (!$res) { error_log("Error executing SQL: {$sql}"); error_log(xf_db_error(df_db())); throw new Exception(xf_db_error(df_db())); } return $res; } }