示例#1
0
 function test_create()
 {
     $profile =& df_get_record('Profiles', array('id' => 10));
     $ht = new Dataface_HistoryTool();
     $ht->createHistoryTable($profile->_table->tablename);
     $this->assertTrue(xf_db_num_rows(xf_db_query("show tables like '" . $ht->logTableName($profile->_table->tablename) . "'")) > 0);
 }
示例#2
0
 function Dataface_Table_builder($name)
 {
     $app =& Dataface_Application::getInstance();
     $this->name = $name;
     if (xf_db_num_rows(xf_db_query('show tables like \'' . addslashes($name) . '\'', $app->db())) > 0) {
         $this->table =& Dataface_Table::loadTable($name);
     }
 }
示例#3
0
 function test_add_value()
 {
     $vt = Dataface_ValuelistTool::getInstance();
     $people = Dataface_Table::loadTable('People');
     $vt->addValueToValuelist($people, 'Publications', 'My Test Publication');
     $res = xf_db_query("select * from Publications where `BiblioString` = 'My Test Publication'");
     $this->assertTrue(xf_db_num_rows($res) === 1);
 }
/**
 * 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;
}
示例#5
0
 function test_save()
 {
     $app =& Dataface_Application::getInstance();
     $builder = new Dataface_Table_builder($this->mytable);
     $this->assertTrue(!isset($builder->table));
     $this->assertEquals(0, xf_db_num_rows(xf_db_query("show tables like '" . $this->mytable . "'", $app->db())));
     $builder->addField(array('Field' => 'name', 'Type' => 'varchar(32)'));
     $res = $builder->save();
     if (PEAR::isError($res)) {
         trigger_error($res->toString(), E_USER_ERROR);
     }
     $this->assertEquals(array('name', 'id'), array_keys($builder->table->fields()));
     $this->assertEquals(1, xf_db_num_rows(xf_db_query("show tables like '" . $this->mytable . "'", $app->db())));
     $builder->addField(array('Field' => 'email', 'Type' => 'varchar(28)'));
     $res = $builder->save();
     if (PEAR::isError($res)) {
         trigger_error($res->toString(), E_USER_ERROR);
     }
     $this->assertEquals(array('name', 'id', 'email'), array_keys($builder->table->fields()));
     $this->assertEquals(1, xf_db_num_rows(xf_db_query("show tables like '" . $this->mytable . "'", $app->db())));
 }
 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;
 }
示例#7
0
 /**
  * Gets the column definitions of the metadata table as produced by show columns SQL query.
  * @param string $tablename The name of the subject table.
  * @param boolean $usecache Whether to use cached results or to forcefully obtain up-to-date data.
  * @returns array Associative array of column definitions.
  */
 function &getColumns($tablename = null, $usecache = true)
 {
     $app =& Dataface_Application::getInstance();
     if (!isset($tablename)) {
         $tablename = $this->tablename;
     }
     $md_tablename = $tablename . '__metadata';
     if (!isset($this->columns) || !$usecache) {
         $this->columns = array();
         $sql = "show columns from `" . $md_tablename . "`";
         $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("No metadata table '{$md_tablename}' could be found.", E_USER_ERROR);
         }
         while ($row = xf_db_fetch_assoc($res)) {
             $this->columns[$row['Field']] = $row;
         }
         @xf_db_free_result($res);
     }
     return $this->columns;
 }
示例#8
0
文件: Table.php 项目: Zunair/xataface
 /**
  * @brief Returns associative array of translations where the key is the 2-digit
  * language code and the value is an array of column names in the translation.
  * 
  * @return array(string=>array(string))
  *
  */
 function &getTranslations()
 {
     if ($this->translations === null) {
         $this->translations = array();
         $res = xf_db_query("SHOW TABLES LIKE '" . addslashes($this->tablename) . "%'", $this->db);
         if (!$res) {
             throw new Exception(Dataface_LanguageTool::translate('MySQL query error loading translation tables', 'MySQL query error while trying to find translation tables for table "' . addslashes($this->tablename) . '". ' . xf_db_error($this->db) . '. ', array('sql_error' => xf_db_error($this->db), 'stack_trace' => '', 'table' => $this->tablename)), E_USER_ERROR);
         }
         if (xf_db_num_rows($res) <= 0) {
             // there should at least be the current table returned.. there is a problem
             // if nothing was returned.
             throw new Exception(Dataface_LanguageTool::translate('Not enough results returned loading translation tables', 'No tables were returned when trying to load translation tables for table "' . $this->tablename . '".  This query should have at least returned one record (the current table) so there must be a problem with the query.', array('table' => $this->tablename)), E_USER_ERROR);
         }
         while ($row = xf_db_fetch_array($res)) {
             $tablename = $row[0];
             if ($tablename == $this->tablename) {
                 continue;
             }
             $matches = array();
             if (preg_match('/^' . $this->tablename . '_([a-zA-Z]{2})$/', $tablename, $matches)) {
                 $this->translations[$matches[1]] = 0;
             }
         }
         xf_db_free_result($res);
     }
     return $this->translations;
 }
示例#9
0
 function test_removeRelatedRecord()
 {
     $this->assertTrue(xf_db_num_rows(xf_db_query("SELECT * FROM `Appointments` where `id`=2")) == 1);
     $record =& Dataface_IO::loadRecordById('Profiles/appointments?id=10&appointments::id=2');
     $res = Dataface_IO::removeRelatedRecord($record);
     // This should fail to remove the record because it is a one-to-many relationship,
     // and you can only remove the record if you add the 'delete' flag to allow it
     // to delete the domain record.
     $this->assertTrue(!$res);
     $this->assertTrue(xf_db_num_rows(xf_db_query("SELECT * FROM `Appointments` where `id`=2")) == 1);
     $res = Dataface_IO::removeRelatedRecord($record, true);
     $this->assertTrue($res);
     $this->assertTrue(xf_db_num_rows(xf_db_query("SELECT * FROM `Appointments` where `id`=2")) == 0);
 }
示例#10
0
 function test_refreshMetadataTable()
 {
     $app =& Dataface_Application::getInstance();
     $sql = "create table `md_test3` (\n\t\t\t\tfname varchar(32) NOT NULL,\n\t\t\t\tlname varchar(32) NOT NULL,\n\t\t\t\tage int(11) default 10,\n\t\t\t\tprimary key (`fname`,`lname`))";
     $res = xf_db_query($sql, $app->db());
     if (!$res) {
         trigger_error(xf_db_error($app->db()), E_USER_ERROR);
     }
     $mt = new Dataface_MetadataTool('md_test3');
     $this->assertTrue($mt->refreshMetadataTable());
     $this->assertEquals(1, xf_db_num_rows(xf_db_query("show tables like 'md_test3__metadata'", $app->db())));
     $cols = $mt->getColumns(null, false);
     $this->assertEquals(array('fname', 'lname', '__translation_state', '__published_state'), array_keys($cols));
     $mt->fieldDefs['__test_col'] = array('Type' => 'varchar(32)', 'Default' => 'Null', 'Field' => '__test_col');
     $this->assertTrue($mt->refreshMetadataTable());
     $cols = $mt->getColumns(null, false);
     $this->assertEquals(array('fname', 'lname', '__translation_state', '__published_state', '__test_col'), array_keys($cols));
 }
示例#11
0
 /**
  * Returns the tables that are eligible to be migrated.
  */
 function getMigratableTables()
 {
     $app = Dataface_Application::getInstance();
     if (@$app->_conf['default_language_no_fallback']) {
         return false;
     }
     // We are still using the old style of translations, so there is no migration required.
     $migrations = array();
     $res = xf_db_query("show tables", $app->db());
     $tables = array();
     while ($row = xf_db_fetch_row($res)) {
         $tables[] = $row[0];
     }
     xf_db_free_result($res);
     foreach ($tables as $tablename) {
         $translation_tablename = $tablename . "_" . $app->_conf['default_language'];
         if (xf_db_num_rows($res = xf_db_query("show tables like '" . addslashes($translation_tablename) . "'", $app->db())) > 0) {
             @xf_db_free_result($res);
             list($num) = xf_db_fetch_row($res = xf_db_query("select count(*) from `" . $translation_tablename . "`", $app->db()));
             if ($num > 0) {
                 $migrations[] = $tablename;
             }
         } else {
         }
         xf_db_free_result($res);
     }
     return $migrations;
 }
示例#12
0
文件: IO.php 项目: minger11/Pipeline
 /**
  * Returns true if the record currently represented in the Table already exists 
  * in the database.
  *
  * @param tablename Alternative table where records may be stored.  This is useful if we are reading form import or delete tables.
  *
  */
 function recordExists(&$record, $keys = null, $tablename = null)
 {
     $this->lastVersionNumber = null;
     if (!is_a($record, "Dataface_Record")) {
         throw new Exception(df_translate('scripts.Dataface.IO.recordExists.ERROR_PARAMETER_1', "In Dataface_IO::recordExists() the first argument is expected to be either a 'Dataface_Record' object or an array of key values, but received neither.\n<br>"), E_USER_ERROR);
     }
     if ($tablename === null and $this->_altTablename !== null) {
         $tablename = $this->_altTablename;
     }
     $tempRecordCreated = false;
     if ($record->snapshotExists()) {
         $tempRecord = new Dataface_Record($record->_table->tablename, $record->getSnapshot());
         $tempRecordCreated = true;
     } else {
         $tempRecord =& $record;
     }
     if ($keys == null) {
         // Had to put in userialize(serialize(...)) because getValues() returns by reference
         // and we don't want to change actual values.
         $query = unserialize(serialize($tempRecord->getValues(array_keys($record->_table->keys()))));
     } else {
         $query = $keys;
     }
     $table_keys = array_keys($this->_table->keys());
     foreach ($table_keys as $key) {
         if (!isset($query[$key]) or !$query[$key]) {
             return false;
         }
     }
     foreach (array_keys($query) as $key) {
         //$query[$key] = '='.$this->_serializer->serialize($key, $tempRecord->getValue($key) );
         $query[$key] = $this->_serializer->serialize($key, $tempRecord->getValue($key));
     }
     if ($tempRecordCreated) {
         $tempRecord->__destruct();
     }
     //$qb = new Dataface_QueryBuilder($this->_table->tablename, $query);
     //$sql = $qb->select_num_rows(array(), $this->tablename($tablename));
     if ($record->table()->isVersioned()) {
         $versionField = "`" . $record->table()->getVersionField() . "`";
     } else {
         $versionField = "NULL";
     }
     $sql = "select `" . $table_keys[0] . "`, {$versionField} from `" . $this->tablename($tablename) . "` where ";
     $where = array();
     foreach ($query as $key => $val) {
         $where[] = '`' . $key . "`='" . addslashes($val) . "'";
     }
     $sql .= implode(' AND ', $where) . ' limit 1';
     $res = df_q($sql, $this->_table->db);
     $num = xf_db_num_rows($res);
     $row = xf_db_fetch_row($res);
     @xf_db_free_result($res);
     if ($num === 1) {
         // We have the correct number...
         // let's check the version
         $this->lastVersionNumber = intval($row[1]);
         return true;
     }
     if ($num > 1) {
         $err = PEAR::raiseError(Dataface_LanguageTool::translate('recordExists failure. Too many rows returned.', "Test for existence of record in recordExists() returned {$rows} records.  \n\t\t\t\t\tIt should have max 1 record.  \n\t\t\t\t\tThe query must be incorrect.  \n\t\t\t\t\tThe query used was '{$sql}'. ", array('table' => $this->_table->tablename, 'line' => 0, 'file' => '_', 'sql' => $sql)), DATAFACE_E_IO_ERROR);
         throw new Exception($err->toString(), E_USER_ERROR);
     }
     return false;
 }
示例#13
0
 function display()
 {
     $this->_build();
     $showform = true;
     $b = new Dataface_QueryBuilder($this->_tablename, $this->_query);
     if (isset($this->_query['-delete-one'])) {
         $q = array('-skip' => $this->_query['-cursor'], '-limit' => 1);
         $sql = $b->select('', $q);
         $res = xf_db_query($sql, $this->_db);
         if (!$res) {
             throw new Exception(df_translate('scripts.Dataface.DeleteForm._build.ERROR_TRYING_TO_FETCH', "Error trying to fetch element to be deleted.: ") . xf_db_error($this->_db), E_USER_ERROR);
         }
         if (xf_db_num_rows($res) == 0) {
             $msg = df_translate('scripts.Dataface.DeleteForm._build.ERROR_NO_RECORD_SELECTED', "No record is currently selected so no record can be deleted.");
             $showform = false;
         } else {
             $row = xf_db_fetch_array($res);
             $rowRec = new Dataface_Record($this->_tablename, $row);
             $displayCol = $rowRec->getTitle();
             $msg = df_translate('scripts.Dataface.DeleteForm.display.ARE_YOU_SURE', "Are you sure you want to delete this record: &quot;{$displayCol}&quot;?", array('displayCol' => $displayCol));
         }
     } else {
         if (isset($this->_query['-delete-found'])) {
             $q = $b->select_num_rows();
             $res = xf_db_query($q, $this->_db);
             if (!$res) {
                 throw new Exception(df_translate('scripts.Dataface.DeleteForm.display.ERROR_ESTIMATING', "Error estimating number of rows that will be deleted: ") . xf_db_error($this->_db), E_USER_ERROR);
             }
             list($num) = xf_db_fetch_row($res);
             if ($num <= 0) {
                 $msg = df_translate('scripts.Dataface.DeleteForm.display.ERROR_NO_RECORDS_FOUND', "There are no records in the current found set so no records can be deleted.");
                 $showform = false;
             } else {
                 $msg = df_translate('scripts.Dataface.DeleteForm.display.ARE_YOU_SURE_MULTIPLE', "Are you sure you want to delete the found records.  {$num} records will be deleted.", array('num' => $num));
             }
         } else {
             $msg = df_translate('scripts.Dataface.DeleteForm.display.ERROR_GET_VARS', "Error: You must specify either '-delete-one' or '-delete-found' in GET vars.");
             $showform = false;
         }
     }
     if ($showform) {
         ob_start();
         parent::display();
         $form = ob_get_contents();
         ob_end_clean();
     } else {
         $form = '';
     }
     $context = array('msg' => $msg, 'form' => $form);
     import('Dataface/SkinTool.php');
     $skinTool =& Dataface_SkinTool::getInstance();
     //$smarty = new Smarty;
     //$smarty->template_dir = $GLOBALS['Dataface_Globals_Templates'];
     //$smarty->compile_dir = $GLOBALS['Dataface_Globals_Templates_c'];
     //$smarty->assign($context);
     //$smarty->display('Dataface_DeleteForm.html');
     $skinTool->display($context, 'Dataface_DeleteForm.html');
 }
示例#14
0
 function checkCredentials()
 {
     $app =& Dataface_Application::getInstance();
     if (!$this->authEnabled) {
         return true;
     }
     if (isset($this->delegate) and method_exists($this->delegate, 'checkCredentials')) {
         return $this->delegate->checkCredentials();
     } else {
         // The user is attempting to log in.
         $creds = $this->getCredentials();
         if (!isset($creds['UserName']) || !isset($creds['Password'])) {
             // The user did not submit a username of password for login.. trigger error.
             //throw new Exception("Username or Password Not specified", E_USER_ERROR);
             return false;
         }
         import('Dataface/Serializer.php');
         $serializer = new Dataface_Serializer($this->usersTable);
         //$res = xf_db_query(
         $sql = "SELECT `" . $this->usernameColumn . "` FROM `" . $this->usersTable . "`\n\t\t\t\t WHERE `" . $this->usernameColumn . "`='" . addslashes($serializer->serialize($this->usernameColumn, $creds['UserName'])) . "'\n\t\t\t\t AND `" . $this->passwordColumn . "`=" . $serializer->encrypt($this->passwordColumn, "'" . addslashes($serializer->serialize($this->passwordColumn, $creds['Password'])) . "'");
         $res = xf_db_query($sql, $app->db());
         if (!$res) {
             throw new Exception(xf_db_error($app->db()), E_USER_ERROR);
         }
         if (xf_db_num_rows($res) === 0) {
             return false;
         }
         $found = false;
         while ($row = xf_db_fetch_row($res)) {
             if (strcmp($row[0], $creds['UserName']) === 0) {
                 $found = true;
                 break;
             }
         }
         @xf_db_free_result($res);
         return $found;
     }
 }
示例#15
0
 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));
     }
 }
示例#16
0
 /**
  * Returns a previous version of the given record.
  * @param Dataface_Record &$record The record whose previous version we are interested in.
  * @param string $date The MySQL date to obtain.  Returns the most recent record on or before this date. (e.g. YYYY-MM-DD HH:MM:SS)
  * @param string $fieldname If we only want the previous version of a single field we can include it here.
  * @param boolean $idonly  If this is set to true then only the history id of the appropriate record will be returned.
  * @returns mixed If $idonly is true then an integer is returned corresponding to the value of the history__id field for the matching record.
  *                If The $fieldname field was specified then the value of that field will be returned.
  *                Otherwise a Dataface_Record will be returned.
  */
 function getPreviousVersion(&$record, $date, $lang = null, $fieldname = null, $idonly = false)
 {
     $app =& Dataface_Application::getInstance();
     if (!isset($lang)) {
         $lang = $app->_conf['lang'];
     }
     $htablename = $record->_table->tablename . '__history';
     if (!Dataface_Table::tableExists($htablename)) {
         return PEAR::raiseError(df_translate('scripts.Dataface.HistoryTool.getDiffs.ERROR_HISTORY_TABLE_DOES_NOT_EXIST', "History table for '{$record->_table->tablename}' does not exist, so we cannot obtain changes for records of that table.", array('tablename' => $record->_table->tablename)), DATAFACE_E_ERROR);
     }
     $clauses = array();
     $keyvals = $record->strvals(array_keys($record->_table->keys()));
     foreach ($keyvals as $key => $val) {
         $clauses[] = "`{$key}`='" . addslashes($val) . "'";
     }
     $clauses[] = "`history__language`='" . addslashes($lang) . "'";
     $sql = "select `history__id` from `{$htablename}` where " . implode(' and ', $clauses) . "\n\t\t\t\tand `history__modified` <= '" . addslashes($date) . "' order by `history__modified` desc limit 1";
     $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) {
         return null;
     }
     list($id) = xf_db_fetch_row($res);
     @xf_db_free_result($res);
     if ($idonly) {
         return $id;
     }
     $out = $this->getRecordById($record->_table->tablename, $id);
     if (isset($fieldname)) {
         return $out->val($fieldname);
     }
     return $out;
 }
示例#17
0
    function processRegistrationForm($values)
    {
        $app =& Dataface_Application::getInstance();
        $conf =& $app->_conf['_auth'];
        $appConf =& $app->conf();
        $table =& Dataface_Table::loadTable($conf['users_table']);
        if (@$this->params['email_validation']) {
            // Let's try to create the registration table if it doesn't already
            // exist
            $this->createRegistrationTable();
            // Now we will store the registration attempt
            // A unique code to be used as an id
            $code = null;
            do {
                $code = md5(rand());
            } while (xf_db_num_rows(xf_db_query("select registration_code \n\t\t\t\t\t\tfrom dataface__registrations \n\t\t\t\t\t\twhere registration_code='" . addslashes($code) . "'", df_db())));
            // Now that we have a unique id, we can insert the value
            $sql = "insert into dataface__registrations \n\t\t\t\t\t(registration_code, registration_data) values\n\t\t\t\t\t('" . addslashes($code) . "',\n\t\t\t\t\t'" . addslashes(serialize($this->form->_record->getValues())) . "')";
            $res = xf_db_query($sql, df_db());
            if (!$res) {
                throw new Exception(xf_db_error(df_db()), E_USER_ERROR);
            }
            $activation_url = $_SERVER['HOST_URI'] . DATAFACE_SITE_HREF . '?-action=activate&code=' . urlencode($code);
            // Now that the registration information has been inserted, we need
            // to send the confirmation email
            // Let's try to send the email if possible.
            $res = $this->_fireDelegateMethod('sendRegistrationActivationEmail', $this->form->_record, $activation_url);
            if (!PEAR::isError($res) or $res->getCode() != DATAFACE_E_REQUEST_NOT_HANDLED) {
                return $res;
            }
            // If we got this far, that means that we haven't sent the email yet... Rather
            // let's send it outselves.
            // We use the Person Ontology to work with the users table record in a more
            // generic way.
            $registrant =& $this->ontology->newIndividual($this->form->_record);
            // We now have the user's email address
            $email = $registrant->strval('email');
            // Let's get the email info. This will return an associative array
            // of the parameters involved in the registration email.  The keys
            // are:
            // 1. subject
            // 2. message
            // 3. headers
            // 4. parameters
            // These are such that they can be passed directly to the mail function
            $info = $this->_fireDelegateMethod('getRegistrationActivationEmailInfo', $this->form->_record, $activation_url);
            if (PEAR::isError($info)) {
                $info = array();
            }
            $info['to'] = $email;
            // Override specific parts of the message if delegate class wants it.
            $subject = $this->_fireDelegateMethod('getRegistrationActivationEmailSubject', $this->form->_record, $activation_url);
            if (!PEAR::isError($subject)) {
                $info['subject'] = $subject;
            }
            $message = $this->_fireDelegateMethod('getRegistrationActivationEmailMessage', $this->form->_record, $activation_url);
            if (!PEAR::isError($message)) {
                $info['message'] = $message;
            }
            $parameters = $this->_fireDelegateMethod('getRegistrationActivationEmailParameters', $this->form->_record, $activation_url);
            if (!PEAR::isError($parameters)) {
                $info['parameters'] = $parameters;
            }
            $headers = $this->_fireDelegateMethod('getRegistrationActivationEmailHeaders', $this->form->_record, $activation_url);
            if (!PEAR::isError($headers)) {
                $info['headers'] = $headers;
            }
            // Now we fill in the missing information with defaults
            if (!@$info['subject']) {
                $info['subject'] = df_translate('actions.register.MESSAGE_REGISTRATION_ACTIVATION_EMAIL_SUBJECT', $app->getSiteTitle() . ': Activate your account', array('site_title' => $app->getSiteTitle()));
            }
            if (!@$info['message']) {
                $site_title = $app->getSiteTitle();
                if (isset($appConf['abuse_email'])) {
                    $admin_email = $appConf['abuse_email'];
                } else {
                    if (isset($appConf['admin_email'])) {
                        $admin_email = $appConf['admin_email'];
                    } else {
                        $admin_email = $_SERVER['SERVER_ADMIN'];
                    }
                }
                if (isset($appConf['application_name'])) {
                    $application_name = $appConf['application_name'];
                } else {
                    $application_name = df_translate('actions.register.LABEL_A_DATAFACE_APPLICATION', 'a Dataface Application');
                }
                if (file_exists('version.txt')) {
                    $application_version = trim(file_get_contents('version.txt'));
                } else {
                    $application_version = '0.1';
                }
                if (file_exists(DATAFACE_PATH . '/version.txt')) {
                    $dataface_version = trim(file_get_contents(DATAFACE_PATH . '/version.txt'));
                } else {
                    $dataface_version = 'unknown';
                }
                $msg = <<<END
Thank you for registering for an account on {$site_title} .  In order to complete your registration,
please visit {$activation_url} .

If you have not registered for an account on this web site and believe that you have received
this email eroneously, please report this to {$admin_email} .
-----------------------------------------------------------
This message was sent by {$site_title} which is powered by {$application_name} version {$application_version}
{$application_name} built using Dataface version {$dataface_version} (http://fas.sfu.ca/dataface).
END;
                $info['message'] = df_translate('actions.register.MESSAGE_REGISTRATION_ACTIVATION_EMAIL_MESSAGE', $msg, array('site_title' => $site_title, 'activation_url' => $activation_url, 'admin_email' => $admin_email, 'application_name' => $application_name, 'application_version' => $application_version, 'dataface_version' => $dataface_version));
            }
            // Now that we have all of the information ready to send.  Let's send
            // the email message.
            if (@$conf['_mail']['func']) {
                $func = $conf['_mail']['func'];
            } else {
                $func = 'mail';
            }
            $res = $func($info['to'], $info['subject'], $info['message'], @$info['headers'], @$info['parameters']);
            if (!$res) {
                return PEAR::raiseError('Failed to send activation email.  Please try again later.', DATAFACE_E_ERROR);
            } else {
                return true;
            }
        } else {
            // We aren't using email validation.. let's just pass it to the
            // form's standard processing function.
            return $this->form->process(array(&$this->form, 'save'), true);
        }
    }
示例#18
0
文件: mysql.php 项目: Zunair/xataface
 /**
  * Gets the number of rows in a result set
  *
  * This method is not meant to be called directly.  Use
  * DB_result::numRows() instead.  It can't be declared "protected"
  * because DB_result is a separate object.
  *
  * @param resource $result  PHP's query result resource
  *
  * @return int  the number of rows.  A DB_Error object on failure.
  *
  * @see DB_result::numRows()
  */
 function numRows($result)
 {
     $rows = @xf_db_num_rows($result);
     if ($rows === null) {
         return $this->mysqlRaiseError();
     }
     return $rows;
 }
示例#19
0
 public function loadRecord(xatacard_layout_Schema $schema, array $query)
 {
     if (isset($query['__id__'])) {
         $id = $query['__id__'];
         $res = $this->query(sprintf("select schema_id, base_record_id from `%s` where `id`=%d", str_replace('`', '', self::$RECORDS_TABLE), intval($id)));
         if (xf_db_num_rows($res) == 0) {
             return null;
         } else {
             $row = xf_db_fetch_assoc($res);
             if ($row['schema_id'] != $schema->getId()) {
                 throw new Exception(sprintf("The record with id %d failed to load because it uses a different schema than expected.  Expected schema id %d but found %d", intval($id), intval($schema->getId()), intval($row['schema_id'])));
             }
             $rec = df_get_record_by_id($row['base_record_id']);
             if (!$rec) {
                 return null;
             }
             if (PEAR::isError($rec)) {
                 throw new Exception(sprintf("Failed to load record is %d because there was problem loading its base record ('%s'): %s", intval($id), $row['base_record_id'], $rec->getMessage()));
             }
             return $this->buildRecord($schema, $rec);
         }
     }
     $tablename = $schema->getProperty('table');
     if (!$tablename) {
         throw new Exception(sprintf("MySQL datasource cannot load a record from schema '%s' because the schema does not specify a table", $schema->getLabel()));
     }
     $rec = df_get_record($tablename, $query);
     if (PEAR::isError($rec)) {
         throw new Exception(sprintf("MySQL datasource failed to load a record for the given query because an error occurred: %s", $rec->toString()));
     }
     if (!$rec) {
         return null;
     }
     return $this->buildRecord($schema, $rec);
 }