示例#1
0
 /**
  * @brief Returns the current database version of the module.
  */
 public function getDbVersion($modname)
 {
     if (!isset($this->_db_versions)) {
         $this->_db_versions = array();
         $sql = "select module_name, module_version from dataface__modules";
         $res = xf_db_query($sql, df_db());
         if (!$res) {
             $res = xf_db_query("create table dataface__modules (\n\t\t\t\t\t`module_name` varchar(255) not null primary key,\n\t\t\t\t\t`module_version` int(11)\n\t\t\t\t) ENGINE=InnoDB DEFAULT CHARSET=utf8", df_db());
             if (!$res) {
                 throw new Exception(xf_db_error(df_db()));
             }
             $res = xf_db_query($sql, df_db());
         }
         if (!$res) {
             throw new Exception(xf_db_error(df_db()));
         }
         while ($row = xf_db_fetch_assoc($res)) {
             $this->_db_versions[$row['module_name']] = $row['module_version'];
         }
         @xf_db_free_result($res);
     }
     $out = @$this->_db_versions[$modname];
     if (!$out) {
         return 0;
     }
     return $out;
 }
示例#2
0
 function loadPreferences($table = null)
 {
     if (!isset($table)) {
         $app =& Dataface_Application::getInstance();
         $query =& $app->getQuery();
         $table = $query['-table'];
     }
     $this->prefs[$table] = array();
     if (class_exists('Dataface_AuthenticationTool')) {
         $auth =& Dataface_AuthenticationTool::getInstance();
         $username = $auth->getLoggedInUsername();
     } else {
         $username = '******';
     }
     $sql = "select * from `dataface__preferences` where `username` in ('*','" . addslashes($username) . "') and `table` in ('*','" . addslashes($table) . "')";
     $res = xf_db_query($sql, df_db());
     if (!$res) {
         $this->_createPreferencesTable();
         $res = xf_db_query($sql, df_db());
         if (!$res) {
             trigger_error(xf_db_error(df_db()), E_USER_ERROR);
         }
     }
     while ($row = xf_db_fetch_assoc($res)) {
         if ($row['table'] == '*') {
             $this->prefs['*'][$row['key']] = $row['value'];
         } else {
             $this->prefs[$row['table']][$row['record_id']][$row['key']] = $row['value'];
         }
     }
     @xf_db_free_result($res);
     $this->refreshTimes[$table] = time();
 }
示例#3
0
 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']);
 }
/**
 * 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 testVersions()
 {
     $table = Dataface_Table::loadTable('test_versions');
     $this->assertEquals('version', $table->getVersionField(), 'The version field of test_versions should be version');
     $this->assertEquals(true, $table->isVersioned(), 'test_versioned should be versioned');
     $row1 = df_get_record('test_versions', array('test_versions_id' => '=1'));
     $this->assertEquals(3, $row1->getVersion(), 'Version for row 1 of test_versions (non null)');
     $row2 = df_get_record('test_versions', array('test_versions_id' => '=2'));
     $this->assertEquals(0, $row2->getVersion(), 'Version for row 2 of test_versions (null value)');
     $row3 = df_get_record('test_versions', array('test_versions_id' => '=3'));
     $this->assertEquals(0, $row3->getVersion(), 'Version for row 3 of test_versions (0 value)');
     // Now let's try to make some changes
     $row1->setValue('varchar_field', 'new value');
     $res = $row1->save();
     $this->assertTrue(!PEAR::isError($res), 'Saving row 1 of test_versions with new varchar value');
     $this->assertEquals(4, $row1->getVersion(), 'Version for row 1 should be incremented after save');
     $row1Copy = df_get_record('test_versions', array('test_versions_id' => '=1'));
     $this->assertTrue(4, $row1Copy->getVersion(), 'Version of row 1 copy should be incremented after save');
     $res = xf_db_query("select version from test_versions where test_versions_id=1", df_db());
     $row = xf_db_fetch_row($res);
     $this->assertEquals(4, $row[0], 'Version of row 1 straight out of db with xf_db_query');
     @xf_db_free_result($res);
     $row2->setValue('varchar_field', 'new value for row 2');
     $res = $row2->save();
     $this->assertTrue(!PEAR::isError($res), 'Saving row 2 of test_versions with new varchar value');
     $this->assertEquals(1, $row2->getVersion(), 'Version of row 2 should  be incremented to 1 after save');
     $row2Copy = df_get_record('test_versions', array('test_versions_id', '=2'));
     $this->assertTrue(1, $row2Copy->getVersion(), 'Version of row 2 copy should be 1 after save');
     // Now we'll try making changes to a record, and then try making more changes from the
     // copy... the changes to the copy should fail because it will be working with
     // an old version of the record.
     $this->assertEquals(4, $row1->getVersion(), 'Row 1 version should still be 4');
     $row1->setValue('varchar_field', 'new value number 2 for row 1');
     $res = $row1->save();
     $this->assertTrue(!PEAR::isError($res), 'Row 1 second save');
     if (PEAR::isError($res)) {
         error_log('Error updating row1: ' . $res->getMessage());
     }
     $this->assertEquals(5, $row1->getVersion(), 'Row 1 version after second save');
     $row1Copy->setValue('varchar_field', 'copy of row 1 changed');
     $res = $row1Copy->save();
     $this->assertTrue(PEAR::isError($res), 'Saving out of date version of row 1');
     if (PEAR::isError($res)) {
         $this->assertEquals(DATAFACE_E_VERSION_MISMATCH, $res->getCode(), 'Error code for version check failure should be DATAFACE_E_VERSION_MISMATCH');
     }
 }
示例#6
0
 /**
  * Loads the table data for table 1 and table 2 into table1Data and table2Data respectively.
  */
 function loadTableData()
 {
     $this->checkTableNames();
     $res = xf_db_query("show full fields from `" . $this->table1 . "`", $this->db1);
     if (!$res) {
         trigger_error(xf_db_error($this->db1));
     }
     $this->table1Data = array();
     while ($row = xf_db_fetch_assoc($res)) {
         $this->table1Data[$row['Field']] = $row;
     }
     @xf_db_free_result($res);
     $res = xf_db_query("show columns from `" . $this->table2 . "`", $this->db2);
     if (!$res) {
         trigger_error(xf_db_error($this->db2));
     }
     $this->table2Data = array();
     while ($row = xf_db_fetch_assoc($res)) {
         $this->table2Data[$row['Field']] = $row;
     }
     @xf_db_free_result($res);
 }
示例#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;
 }
 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;
 }
示例#9
0
文件: DB.php 项目: Zunair/xataface
 /**
  * Queries the database with the given sql query.
  * This currently passes the query straight through to
  * xf_db_query, but it will be modified in the future to
  * automatically filter out blobs (because normally we don't want to 
  * retrieve blob columns.
  */
 function query($sql, $db = null, $lang = null, $as_array = false, $enumerated = false)
 {
     $app =& Dataface_Application::getInstance();
     $refreshModTimes = false;
     if ($as_array and $isSelect = strpos(strtolower(trim($sql)), 'select ') === 0) {
         if ($results = $this->memcache_get($sql, $lang) or is_array($results)) {
             if (@$this->app->_conf['cache_queries_log']) {
                 $fp = fopen('/tmp/querylog.log', 'a');
                 fwrite($fp, "\n[" . date('Y-m-d H:i:s') . "] Cached: " . $sql);
                 fclose($fp);
             }
             $this->cache_hits++;
             return $results;
         } else {
             if (@$this->app->_conf['cache_queries_log']) {
                 $fp = fopen('/tmp/querylog.log', 'a');
                 fwrite($fp, "\n[" . date('Y-m-d H:i:s') . "] Failed cached: " . $sql);
                 fclose($fp);
             }
             $this->cache_fails++;
             $orig_sql = $sql;
             // save the original sql before it is translated
         }
     } else {
         if (@$app->_conf['cache_queries']) {
             $refreshModTimes = true;
         }
     }
     //$fp = fopen('/tmp/querylog.log', 'a');
     //fwrite($fp, "\n[".date('Y-m-d H:i:s')."] Uncached: ".$sql);
     //fclose($fp);
     $this->count++;
     if ($this->app->_conf['multilingual_content']) {
         if (@$app->_conf['debug_sql']) {
             error_log("Before translation: " . $sql);
         }
         $sql = $this->translate_query($sql, $lang);
         if (PEAR::isError($sql)) {
             return $sql;
         }
         if (@$app->_conf['debug_sql']) {
             if (is_array($sql)) {
                 foreach ($sql as $sqli) {
                     error_log("After translation: " . $sqli);
                 }
             } else {
                 error_log("After translation: " . $sql);
             }
         }
     }
     if (!isset($db)) {
         $db = $this->app->db();
     }
     $update_insert_id = true;
     if (is_array($sql)) {
         $loopctr = 0;
         foreach ($sql as $q) {
             if ($loopctr++ > 0 and xf_db_insert_id($db)) {
                 $this->_insert_id = xf_db_insert_id($db);
                 $update_insert_id = false;
                 $q = str_replace("'%%%%%__MYSQL_INSERT_ID__%%%%%'", xf_db_insert_id($db), $q);
             }
             if (defined('DATAFACE_DEBUG_DB') or @$app->_conf['debug_sql']) {
                 echo "Performing query: '{$q}' <br>";
             }
             $res = xf_db_query($q, $db);
         }
     } else {
         if (defined('DATAFACE_DEBUG_DB') or @$app->_conf['debug_sql']) {
             echo "Performing query: '{$sql}' <br>";
         }
         $this->db_hits++;
         $res = xf_db_query($sql, $db);
     }
     if ($update_insert_id) {
         $this->_insert_id = xf_db_insert_id($db);
     }
     if ($res and $refreshModTimes) {
         Dataface_Table::getTableModificationTimes(true);
     }
     if ($as_array and $isSelect) {
         if (!$res) {
             return $res;
         }
         // We want to return this as an array rather than a resource
         $out = array();
         while ($row = $enumerated ? xf_db_fetch_row($res) : xf_db_fetch_assoc($res)) {
             $out[] = $row;
         }
         $this->memcache_set($orig_sql, $lang, $out);
         @xf_db_free_result($res);
         return $out;
     }
     return $res;
 }
示例#10
0
    public function reset_password_with_uuid($uuid)
    {
        $auth = Dataface_AuthenticationTool::getInstance();
        $app = Dataface_Application::getInstance();
        $del = $app->getDelegate();
        $this->create_reset_password_table();
        $this->clear_expired();
        $table = self::$TABLE_RESET_PASSWORD;
        $res = xf_db_query("select * from `{$table}` where request_uuid='" . addslashes($uuid) . "' limit 1", df_db());
        if (!$res) {
            throw new Exception(xf_db_error(df_db()));
        }
        $row = xf_db_fetch_assoc($res);
        if (!$row) {
            throw new Exception(df_translate('actions.forgot_password.no_such_reset_request_found', "No such reset request could be found"), self::$EX_NO_SUCH_UUID);
        }
        if (!$row['username']) {
            throw new Exception(df_translate('actions.forgot_password.attempt_to_reset_for_null_username', "Attempt to reset password for user with null username"), self::$EX_NO_USERNAME_FOR_USER);
        }
        $username = $row['username'];
        @xf_db_free_result($res);
        // now that we have the username, let's reset the password.
        //$rand = strval(rand())."".$uuid;
        $rand = md5($uuid);
        error_log("Rand is " . $rand);
        $pw = '';
        for ($i = 0; $i <= 16; $i += 2) {
            $pw .= $rand[$i];
        }
        $password = $pw;
        if (isset($del) and method_exists($del, 'generateTemporaryPassword')) {
            $pw = $del->generateTemporaryPassword();
            if ($pw) {
                $password = $pw;
            }
        }
        //error_log("Password is $password");
        $user = df_get_record($auth->usersTable, array($auth->usernameColumn => '=' . $username));
        if (!$user) {
            throw new Exception(df_translate('actions.forgot_password.no_account_for_username', "No user account found with that username"), self::$EX_USER_NOT_FOUND);
        }
        $emailColumn = $auth->getEmailColumn();
        if (!$emailColumn) {
            throw new Exception(df_translate('actions.forgot_password.no_email_column_found_short', "No email column found in the users table"), self::$EX_NO_EMAIL_COLUMN_FOUND);
        }
        $email = $user->val($emailColumn);
        if (!$email) {
            throw new Exception(df_translate('actions.forgot_password.user_without_email_long', "User has account has no email address on record.  Please contact support to reset the password"), self::$EX_NO_EMAIL_FOR_USER);
        }
        $user->setValue($auth->passwordColumn, $password);
        $res = $user->save();
        if (PEAR::isError($res)) {
            throw new Exception($res->getMessage());
        }
        // Let's delete this request from the password reset requests.
        $this->delete_request_with_uuid($uuid);
        // Now let's send the email.
        $del = $app->getDelegate();
        $info = array();
        if (isset($del) and method_exists($del, 'getPasswordChangedEmailInfo')) {
            $info = $del->getPasswordChangedEmailInfo($user, $password);
        }
        $subject = df_translate('actions.forgot_password.password_changed', "Password Changed");
        if (isset($info['subject'])) {
            $subject = $info['subject'];
        }
        $site_url = df_absolute_url(DATAFACE_SITE_HREF);
        $msg = df_translate('actions.forgot_password.new_temporary_password_email_body', <<<END
Your new temporary password is
{$password}

You can change your password as follows:

1. Log in with your temporary password at <{$site_url}?-action=login>
2. Click on the "My Profile" link in the upper right of the page
3. Click on the "Edit" tab.
4. Change your password in the edit form and click "Save" when done.
END
, array('password' => $password, 'site_url' => $site_url));
        if (isset($info['message'])) {
            $msg = $info['message'];
        }
        $parameters = null;
        if (isset($info['parameters'])) {
            $parameters = $info['parameters'];
        }
        $site_title = $app->getSiteTitle();
        $support_email = $_SERVER['SERVER_ADMIN'];
        if (isset($app->_conf['admin_email'])) {
            $support_email = $app->_conf['admin_email'];
        }
        if (isset($app->_conf['support_email'])) {
            $support_email = $app->_conf['support_email'];
        }
        $headers = 'From: ' . $site_title . ' <' . $support_email . '>' . "\r\nReply-to: " . $site_title . " <" . $support_email . ">" . "\r\nContent-type: text/plain; charset=" . $app->_conf['oe'];
        if (isset($info['headers'])) {
            $headers = $info['headers'];
        }
        if (@$app->_conf['_mail']['func']) {
            $func = $app->_conf['_mail']['func'];
        } else {
            $func = 'mail';
        }
        $res = $func($email, $subject, $msg, $headers, $parameters);
        if (!$res) {
            return PEAR::raiseError(df_translate('actions.forgot_password.failed_send_activation', "Failed to send activation email.  Please try again later."), DATAFACE_E_ERROR);
        } else {
            return true;
        }
    }
示例#11
0
 /**
  * 
  * @param array $columns
  * @return type
  * @throws Exception@brief Load the totals for the current found set using MySQL's aggregate 
  * operators.  This method will always query the database directly (no caching).  
  * 
  * <p>This method was developed to make it easier to create "totals" rows in the 
  *    list view.</p>
  * 
  * <h3>Example</h3>
  * 
  * @code
  * $resultSet = Dataface_Application::getInstance()->getResultSet();
  * $results = $resultSet->loadTotals(array(
  *    'age#avg',
  *    'age#std',
  *    'income#sum'
  * ));
  * print_r($results);
  * @endcode
  * 
  * <p>Output:</p>
  * 
  * @code
  * array(
  *    'age_AVG' => 74.4,
  *    'age_STD' => 13.2,
  *    'income_SUM' => 100567
  * );
  * @endcode
  * 
  * @param array $columns A list of strings of the form {fieldname}#{operator} where 
  *  where {fieldname} is the name of a field and {operator} is the name of an operator
  *  to apply to the field.
  * 
  * <h3>Available Operators</h3>
  * <table>
  *    <tr>
  *     <th>Operator</th><th>Description</th>
  *    </tr>
  *    <tr>
  *       <td>sum</td><td>The sum of field values for result set.</td>
  *    </tr>
  *    <tr>
  *       <td>avg</td><td>The average value of field in result set.</td>
  *    <tr>
  *       <td>max</td><td>The max value of field in result set.</td>
  *    </tr>
  *    <tr>
  *       <td>min</td><td>The minimum value of field result set.</td>
  *    </tr>
  *    <tr>
  *       <td>bit_and</td><td>Result of bitwise AND on field for all found records.</td>
  *    </tr>
  *    <tr>
  *       <td>bit_or</td><td>Result of bitwise OR on field for all found records.</td>
  *    </tr>
  *    <tr>
  *       <td>bit_xor</td><td>Result of bitwise XOR on field for all found records.</td>
  *    </tr>
  *    <tr>
  *       <td>group_concat</td><td>The concatenation of all rows in found set for field.  Joined with a comma.</td>
  *    </tr>
  *    <tr>
  *       <td>std</td><td>Population Standard deviation of field values for result set.</td>
  *    </tr>
  *    <tr>
  *       <td>stddev_samp</td><td>Sample Standard deviation of field values for result set.</td>
  *    </tr>
  *    <tr>
  *       <td>stddev_pop</td><td>Same as stddev</td>
  *    </tr>
  *    <tr>
  *       <td>var_pop<td><td>Population standard variance for field values for result set.</td>
  *    </tr>
  *    <tr>
  *       <td>var_samp</td><td>Sample standard deviation for field values for result set.</td>
  *    </tr>
  *    <tr>
  *       <td>variance</td><td>Same as var_pop</td>
  *    </tr>
  * </table>
  * 
  *    
  * @return Associative array where the keys have the form {fieldname}_{operator|uppercase} and the values
  *  are the corresponding result of the operator on that field.  E.g. If your input was array('field1#sum', 'field2#avg')
  *  the output woult be array('field1_SUM' => {some number}, 'field2_AVG' => {some_number})
  * 
  * @since 2.0.4
  * @see Dataface_QueryBuilder::select_totals()
  */
 function loadTotals($columns = array())
 {
     $builder = new Dataface_QueryBuilder($this->_tablename, $this->_query);
     $sql = $builder->select_totals(array(), null, $columns);
     $res = df_query($sql);
     if (!$res) {
         throw new Exception(xf_db_error(df_db()));
     } else {
         $out = xf_db_fetch_assoc($res);
         @xf_db_free_result($res);
         return $out;
     }
 }
示例#12
0
 function isLockedOut()
 {
     $this->_createFailedLoginsTable();
     $res = xf_db_query("delete from `dataface__failed_logins` where `time_of_attempt` < " . (time() - 60 * 30), df_db());
     if (!$res) {
         throw new Exception(xf_db_error(df_db()), E_USER_ERROR);
     }
     $res = xf_db_query("select count(*) from `dataface__failed_logins` where `ip_address`='" . addslashes($_SERVER['REMOTE_ADDR']) . "'", df_db());
     if (!$res) {
         throw new Exception(xf_db_error(df_db()), E_USER_ERROR);
     }
     list($num) = xf_db_fetch_row($res);
     @xf_db_free_result($res);
     return $num > 20;
 }
示例#13
0
 /**
  * Returns an array of history ids of history records that match the 
  * given query.
  */
 function findMatchingSnapshots($record, $query, $idsOnly = true)
 {
     $app =& Dataface_Application::getInstance();
     $htablename = $record->_table->tablename . '__history';
     if (!Dataface_Table::tableExists($htablename)) {
         return array();
     }
     $keys = $record->strvals(array_keys($record->_table->keys()));
     foreach ($keys as $key => $val) {
         $query[$key] = '=' . $val;
     }
     if ($idsOnly) {
         $qbuilder = new Dataface_QueryBuilder($htablename, $query);
         $sql = $qbuilder->select(array('history__id'), $query);
         $res = xf_db_query($sql, df_db());
         $ids = array();
         while ($row = xf_db_fetch_row($res)) {
             $ids[] = $row[0];
         }
         @xf_db_free_result($res);
         return $ids;
     } else {
         return df_get_records_array($htablename, $query);
     }
 }
示例#14
0
 public function addLanguageTables($lang)
 {
     $res = df_q("show tables like '%_en'");
     while ($row = xf_db_fetch_row($res)) {
         if (preg_match('/^(.*)_en$/', $row[0], $matches)) {
             $this->addLanguageTable($matches[1], $lang);
         }
     }
     @xf_db_free_result($res);
 }
示例#15
0
 public function getObjects($sql, $vars = null)
 {
     $out = array();
     $res = $this->query($sql, $vars);
     while ($row = xf_db_fetch_object($res)) {
         $out[] = $row;
     }
     @xf_db_free_result($res);
     return $out;
 }
示例#16
0
 /**
  * @brief Returns the last modified time of the record.
  *
  * @return long Unix timestamp marking the last time the record was modified.
  *
  * @since 0.8
  *
  * @section Synopsis
  *
  * This method will first check to see if the delegate class implements a method
  * named getLastModified() and return its result.  If none can be found it will 
  * attempt to guess which field is used to store the last modified date 
  * (based on the Dataface_Table::getLastUpdatedField() method).  Otherwise it will
  * simply return 0.
  *
  * This method is used throughout Xataface to mark the modification times of records.
  *
  * @see http://www.xataface.com/wiki/Delegate_class_methods
  * @see http://xataface.com/documentation/tutorial/getting_started/delegate_classes
  * @see Dataface_Table::getLastUpdatedField()
  */
 function getLastModified()
 {
     if ($res = $this->callDelegateFunction('getLastModified')) {
         return $res;
     } else {
         if ($lastModifiedField = $this->_table->getLastUpdatedField()) {
             if (strcasecmp($this->_table->getType($lastModifiedField), 'timestamp') === 0) {
                 $date = $this->val($lastModifiedField);
                 return strtotime($date['year'] . '-' . $date['month'] . '-' . $date['day'] . ' ' . $date['hours'] . ':' . $date['minutes'] . ':' . $date['seconds']);
             }
             $strtime = $this->strval($lastModifiedField);
             if ($strtime) {
                 return strtotime($strtime);
             }
         }
     }
     if (!isset($this->pouch['__mtime'])) {
         $sql = "select mtime from dataface__record_mtimes where recordhash='" . addslashes(md5($this->getId())) . "'";
         try {
             try {
                 $res = df_q($sql);
             } catch (Exception $ex) {
                 Dataface_IO::createRecordMtimes();
                 $res = df_q($sql);
             }
             list($mtime) = xf_db_fetch_row($res);
             @xf_db_free_result($res);
             $this->pouch['__mtime'] = intval($mtime);
         } catch (Exception $ex) {
             error_log("Failed SQL query {$sql}");
             $this->pouch['__mtime'] = 0;
         }
     }
     return $this->pouch['__mtime'];
 }
示例#17
0
文件: Table.php 项目: Zunair/xataface
 /**
  * @brief Gets the tables from the database that are explicitly for importing data.
  * They are tables of the form Tablename__import__<timestamp> where <timestamp>
  * is the unix timestamp of when the import table was created.
  *
  * @return array Array of string table names.
  *
  * @see createImportTable()
  */
 function getImportTables()
 {
     $res = xf_db_query("SHOW TABLES LIKE '" . $this->tablename . "__import_%'", $this->db);
     if (!$res) {
         throw new Exception("Error getting import table list for table '" . $this->tablename . "'.", E_USER_ERROR);
     }
     $tables = array();
     while ($row = xf_db_fetch_row($res)) {
         $tables[] = $row[0];
     }
     xf_db_free_result($res);
     return $tables;
 }
示例#18
0
}
$parsed_url_src = parse_url(@$_GET['src']);
if ($phpThumb->config_nohotlink_enabled && $phpThumb->config_nohotlink_erase_image && eregi('^(f|ht)tps?://', @$_GET['src']) && !in_array(@$parsed_url_src['host'], $phpThumb->config_nohotlink_valid_domains)) {
    $phpThumb->ErrorImage($phpThumb->config_nohotlink_text_message);
}
if ($phpThumb->config_xf_db_query) {
    if ($cid = @xf_db_connect($phpThumb->config_mysql_hostname, $phpThumb->config_mysql_username, $phpThumb->config_mysql_password)) {
        if (@xf_db_select_db($phpThumb->config_mysql_database, $cid)) {
            if ($result = @xf_db_query($phpThumb->config_xf_db_query, $cid)) {
                if ($row = @xf_db_fetch_array($result)) {
                    xf_db_free_result($result);
                    xf_db_close($cid);
                    $phpThumb->setSourceData($row[0]);
                    unset($row);
                } else {
                    xf_db_free_result($result);
                    xf_db_close($cid);
                    $phpThumb->ErrorImage('no matching data in database.');
                }
            } else {
                xf_db_close($cid);
                $phpThumb->ErrorImage('Error in MySQL query: "' . xf_db_error($cid) . '"');
            }
        } else {
            xf_db_close($cid);
            $phpThumb->ErrorImage('cannot select MySQL database: "' . xf_db_error($cid) . '"');
        }
    } else {
        $phpThumb->ErrorImage('cannot connect to MySQL server');
    }
    unset($_GET['id']);
示例#19
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;
 }
示例#20
0
function fnSQLtoXML($sSQL, $oConn = '')
{
    //Returns an XML data island from an SQL statement or an error string
    if (!$oConn and !($oConn = @xf_db_connect(DB_HOST, DB_USER, DB_PASSWORD))) {
        $sRetVal = xf_db_error();
    } else {
        if (!mysql_selectdb(DB_NAME, $oConn)) {
            $sRetVal = xf_db_error();
        } else {
            if (!($result = xf_db_query($sSQL, $oConn))) {
                $sRetVal = xf_db_error();
            } else {
                while ($line = xf_db_fetch_array($result, MYSQL_ASSOC)) {
                    $sRetVal = "\n<" . mysql_field_table($result, 0) . ">";
                    $iThisField = 0;
                    foreach ($line as $col_value) {
                        $oTMP = mysql_fetch_field($result, $iThisField);
                        $iThisField++;
                        $sThisFieldName = $oTMP->name;
                        $sRetVal .= "\n\t<{$sThisFieldName} value=" . $col_value . ">";
                        $sRetVal .= "</{$sThisFieldName}>";
                    }
                    $sRetVal .= "\n</" . mysql_field_table($result, 0) . ">\n";
                }
                xf_db_free_result($result);
            }
        }
        xf_db_close($oConn);
    }
    return $sRetVal;
}
示例#21
0
文件: mysql.php 项目: Zunair/xataface
 /**
  * Returns information about a table or a result set
  *
  * @param object|string  $result  DB_result object from a query or a
  *                                 string containing the name of a table.
  *                                 While this also accepts a query result
  *                                 resource identifier, this behavior is
  *                                 deprecated.
  * @param int            $mode    a valid tableInfo mode
  *
  * @return array  an associative array with the information requested.
  *                 A DB_Error object on failure.
  *
  * @see DB_common::tableInfo()
  */
 function tableInfo($result, $mode = null)
 {
     if (is_string($result)) {
         /*
          * Probably received a table name.
          * Create a result resource identifier.
          */
         $id = @mysql_list_fields($this->dsn['database'], $result, $this->connection);
         $got_string = true;
     } elseif (isset($result->result)) {
         /*
          * Probably received a result object.
          * Extract the result resource identifier.
          */
         $id = $result->result;
         $got_string = false;
     } else {
         /*
          * Probably received a result resource identifier.
          * Copy it.
          * Deprecated.  Here for compatibility only.
          */
         $id = $result;
         $got_string = false;
     }
     if (!is_resource($id)) {
         return $this->mysqlRaiseError(DB_ERROR_NEED_MORE_DATA);
     }
     if ($this->options['portability'] & DB_PORTABILITY_LOWERCASE) {
         $case_func = 'strtolower';
     } else {
         $case_func = 'strval';
     }
     $count = @mysql_num_fields($id);
     $res = array();
     if ($mode) {
         $res['num_fields'] = $count;
     }
     for ($i = 0; $i < $count; $i++) {
         $res[$i] = array('table' => $case_func(@mysql_field_table($id, $i)), 'name' => $case_func(@mysql_field_name($id, $i)), 'type' => @mysql_field_type($id, $i), 'len' => @mysql_field_len($id, $i), 'flags' => @mysql_field_flags($id, $i));
         if ($mode & DB_TABLEINFO_ORDER) {
             $res['order'][$res[$i]['name']] = $i;
         }
         if ($mode & DB_TABLEINFO_ORDERTABLE) {
             $res['ordertable'][$res[$i]['table']][$res[$i]['name']] = $i;
         }
     }
     // free the result only if we were called on a table
     if ($got_string) {
         @xf_db_free_result($id);
     }
     return $res;
 }
示例#22
0
 function parse_ini_file($path, $sections = false)
 {
     static $config = 0;
     if (!is_array($config)) {
         $config = array();
     }
     $app =& Dataface_Application::getInstance();
     //echo "Checking for $path";
     if (strstr($path, 'db:') == $path) {
         $path = substr($path, 3);
         if (!is_array($config)) {
             $config = array();
             if (class_exists('Dataface_AuthenticationTool')) {
                 $auth =& Dataface_AuthenticationTool::getInstance();
                 $username = $auth->getLoggedInUsername();
             } else {
                 $username = null;
             }
             $sql = $this->buildConfigQuery($path, $username, $app->_conf['lang']);
             $res = @xf_db_query($sql, $app->db());
             if (!$res) {
                 $this->createConfigTable();
                 $res = xf_db_query($sql, $app->db());
             }
             if (!$res) {
                 return $config;
             }
             while ($row = xf_db_fetch_assoc($res)) {
                 if (!$row['section']) {
                     $config[$row['file']][$row['key']] = $row['value'];
                 } else {
                     $config[$row['file']][$row['section']][$row['key']] = $row['value'];
                 }
             }
             @xf_db_free_result($res);
         }
         if (!@$config[$path]) {
             return array();
         }
         return $config[$path];
     } else {
         if (@$_GET['--refresh-apc'] or !(DATAFACE_EXTENSION_LOADED_APC && filemtime($path) < apc_fetch($this->apc_hash() . $path . '__mtime') && ($config[$path] = apc_fetch($this->apc_hash() . $path)))) {
             //$config[$path] =  parse_ini_file($path, $sections);
             $config[$path] = INIParser::parse_ini_file($path, $sections);
             if (DATAFACE_EXTENSION_LOADED_APC) {
                 apc_store($this->apc_hash() . $path, $config[$path]);
                 apc_store($this->apc_hash() . $path . '__mtime', time());
             }
         } else {
             //
         }
         return $config[$path];
     }
 }
示例#23
0
 /**
  * This will find , in relevance sorted order the records from the index.
  * @param array $query  Query array.  Important parameters are '-search', '-skip', and '-limit'
  * @returns array
  */
 function find($query, $returnMetadata = false, $lang = null)
 {
     if (!$lang) {
         $lang = @Dataface_Application::getInstance()->_conf['lang'];
     }
     if (!$lang) {
         $lang = 'en';
     }
     if (!isset($query['-search'])) {
         $query['-search'] = '';
     }
     $words = explode(' ', $query['-search']);
     $soundexAddons = array();
     foreach ($words as $word) {
         $soundexAddons[] = soundex($word);
     }
     $orig_search = $query['-search'];
     $query['-search'] .= ' ' . implode(' ', $soundexAddons);
     $select = "select record_id,`table`,record_url,record_title,record_description, `searchable_text`, `lang`,match(searchable_text) against ('" . addslashes($query['-search']) . "') as `relevance`";
     $sql = "\n\t\t\t\n\t\t\tfrom dataface__index\n\t\t\twhere `lang`='" . addslashes($lang) . "' and \n\t\t\tmatch(searchable_text)\n\t\t\tagainst ('" . addslashes($query['-search']) . "')";
     $countsql = "select count(record_id), `table` as num " . $sql . " group by `table`";
     if (isset($query['-table'])) {
         $sql .= " and `table` = '" . addslashes($query['-table']) . "'";
     }
     if (!isset($query['-limit'])) {
         $query['-limit'] = 30;
     }
     if (!isset($query['-skip'])) {
         $query['-skip'] = 0;
     }
     $skip = intval($query['-skip']);
     $limit = intval($query['-limit']);
     $sql .= " limit {$skip}, {$limit}";
     $sql = $select . $sql;
     $res = @xf_db_query($sql, df_db());
     if (!$res) {
         $this->createIndexTable();
         $res = xf_db_query($sql, df_db());
         if (!$res) {
             trigger_error(xf_db_error(df_db()), E_USER_ERROR);
         }
     }
     $query['-search'] = $orig_search;
     $out = array();
     $phrases = array();
     $words = explode(' ', str_replace('"', '', $query['-search']));
     if (preg_match_all('/"([^"]+)"/', $query['-search'], $matches, PREG_PATTERN_ORDER)) {
         foreach ($matches[1] as $m) {
             $phrases[] = $m;
         }
     }
     $numWords = count($words);
     if ($numWords > 1) {
         $words2 = array(implode(' ', $words));
         for ($i = 0; $i < $numWords; $i++) {
             for ($j = $i; $j < $numWords; $j++) {
                 $temp = $words;
                 for ($k = $i; $k <= $j; $k++) {
                     unset($temp[$k]);
                 }
                 $words2[] = implode(' ', $temp);
             }
         }
         $words = $words2;
     }
     usort($words, array($this, '_cmp_words_by_length'));
     while ($row = xf_db_fetch_assoc($res)) {
         $st = strip_tags($row['searchable_text']);
         $st = html_entity_decode($st, ENT_COMPAT, Dataface_Application::getInstance()->_conf['oe']);
         unset($row['searchable_text']);
         $summary = array();
         foreach ($phrases as $p) {
             if (preg_match_all('/.{0,50}' . preg_quote($p, '/') . '.{0,50}/', $st, $matches, PREG_PATTERN_ORDER)) {
                 //print_r($matches);
                 foreach ($matches[0] as $m) {
                     $summary[] = $m;
                     if (count($summary) > 5) {
                         break;
                     }
                 }
                 //print_r($summary);
             }
         }
         if (!$summary) {
             foreach ($words as $p) {
                 if (!trim($p)) {
                     continue;
                 }
                 if (preg_match_all('/.{0,50}' . preg_quote($p, '/') . '.{0,50}/', $st, $matches, PREG_PATTERN_ORDER)) {
                     foreach ($matches[0] as $m) {
                         $summary[] = $m;
                         if (count($summary) > 5) {
                             break;
                         }
                     }
                 }
             }
         }
         if ($summary) {
             $row['record_description'] = '...' . implode(' ... ', $summary) . ' ...';
         }
         $out[] = $row;
     }
     @xf_db_free_result($res);
     if ($returnMetadata) {
         $app =& Dataface_Application::getInstance();
         $res = @xf_db_query($countsql, df_db());
         if (!$res) {
             trigger_error(xf_db_error(df_db()), E_USER_ERROR);
         }
         $found = 0;
         $total_found = 0;
         $tables_matches = array();
         while ($row = xf_db_fetch_row($res)) {
             $label = @$app->_conf['table_labels'][$row[1]];
             if (!$label) {
                 $label = @$app->tables[$row[1]];
             }
             if (!$label) {
                 $label = $row[1];
             }
             $tables_matches[$row[1]] = array('found' => $row[0], 'label' => $label);
             $total_found += intval($row[0]);
             if (!@$query['-table'] or $query['-table'] == $row[1]) {
                 $found += intval($row[0]);
             }
         }
         @xf_db_free_result($res);
         $meta = array();
         $meta['found'] = $found;
         $meta['skip'] = $query['-skip'];
         $meta['limit'] = $query['-limit'];
         $meta['start'] = $query['-skip'];
         $meta['end'] = min($meta['start'] + $meta['limit'], $meta['found']);
         $meta['tables'] = $tables_matches;
         $meta['table'] = @$query['-table'];
         $meta['table_objects'] =& $table_objects;
         $meta['total_found'] = $total_found;
         return array('results' => $out, 'metadata' => @$meta);
     } else {
         return $out;
     }
 }
示例#24
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;
 }