コード例 #1
0
ファイル: ModuleTool.php プロジェクト: Zunair/xataface
 /**
  * @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
ファイル: PreferencesTool.php プロジェクト: minger11/Pipeline
 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
ファイル: DB_Test.php プロジェクト: Zunair/xataface
 function test_query()
 {
     $sql = "select PubType, BiblioString from Publications where PublicationID='1'";
     $res = $this->DB->query($sql);
     $this->assertTrue($res);
     if (!$res) {
         echo xf_db_error();
     }
     $row = xf_db_fetch_assoc($res);
     $this->assertEquals(array('PubType' => 'Refereed Journal', 'BiblioString' => 'Amit, H. Autonomous, metamorphic technology for B-Trees. In POT NOSSDAV (Dec. 1991).'), $row);
     $sql = "Update Publications set PubType = 'Experimental' where PublicationID='1'";
     $res = $this->DB->query($sql);
     $this->assertTrue($res);
     if (!$res) {
         echo xf_db_error();
     }
     $this->assertTrue(xf_db_affected_rows() === 1);
     $sql = "Insert into Publications (PubType) VALUES ('My new type')";
     $res = $this->DB->query($sql);
     $this->assertTrue($res);
     if (!$res) {
         echo xf_db_error();
     }
     $this->assertTrue(xf_db_affected_rows() === 1);
 }
コード例 #4
0
ファイル: DB_Sync_Test.php プロジェクト: Zunair/xataface
 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']);
 }
コード例 #5
0
/**
 * 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;
}
コード例 #6
0
ファイル: Sync.php プロジェクト: minger11/Pipeline
 /**
  * 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
ファイル: MetadataTool.php プロジェクト: minger11/Pipeline
 /**
  * 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
ファイル: forgot_password.php プロジェクト: Zunair/xataface
    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;
        }
    }
コード例 #9
0
ファイル: QueryTool.php プロジェクト: minger11/Pipeline
 /**
  * 
  * @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;
     }
 }
コード例 #10
0
ファイル: HistoryTool.php プロジェクト: minger11/Pipeline
 /**
  * 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;
 }
コード例 #11
0
ファイル: Index.php プロジェクト: minger11/Pipeline
 /**
  * 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;
     }
 }
コード例 #12
0
ファイル: ConfigTool.php プロジェクト: minger11/Pipeline
 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];
     }
 }
コード例 #13
0
ファイル: Database.php プロジェクト: minger11/Pipeline
 public function getAssocs($sql, $vars = null)
 {
     $out = array();
     $res = $this->query($sql, $vars);
     while ($row = xf_db_fetch_assoc($res)) {
         $out[] = $row;
     }
     @xf_db_free_result($res);
     return $out;
 }
コード例 #14
0
ファイル: TranslationTool.php プロジェクト: Zunair/xataface
 /**
  * The early versions of the Dataface QueryTranslation extension stored even the default language
  * translations in a translation table.  This is not necessary, and even undesired when you consider
  * that the default language should be a fall-back point for records that do not contain the proper
  * translation.  This method copies the translation data from the translation table of a particular
  * language into the main table.  Use this with caution as it will overwrite data from the underlying
  * table.
  * @param string $newDefault The 2-digit language code for the new default language.
  */
 function migrateDefaultLanguage($newDefault, $tables = null)
 {
     import('Dataface/Utilities.php');
     import('Dataface/IO.php');
     $app = Dataface_Application::getInstance();
     $no_fallback = @$app->_conf['default_language_no_fallback'];
     // Whether or not the application is currently set to disable fallback
     // to default language.
     $tables = $this->getMigratableTables();
     $log = array();
     foreach ($tables as $tablename) {
         $table = Dataface_Table::loadTable($tablename);
         $t_tablename = $tablename . '_' . $app->_conf['default_language'];
         if (!$table || PEAR::isError($table)) {
             continue;
         }
         $res = xf_db_query("create table `{$tablename}_bu_" . time() . "` select * from `{$tablename}`", $app->db());
         $sql = "select `" . join('`,`', array_keys($table->keys())) . "` from `" . $tablename . "`";
         $res2 = xf_db_query($sql, $app->db());
         $io = new Dataface_IO($tablename);
         $io->lang = $newDefault;
         while ($rec = xf_db_fetch_assoc($res2)) {
             //foreach (array_keys($rec) as $colkey){
             //	$rec[$colkey] = '='.$rec[$colkey];
             //}
             $app->_conf['default_language_no_fallback'] = 1;
             $record = df_get_record($tablename, $rec, $io);
             //print_r($record->strvals());
             $app->_conf['default_language_no_fallback'] = 0;
             $record2 = new Dataface_Record($tablename, array());
             $record2->setValues($record->vals());
             $r = $io->write($record2);
             if (PEAR::isError($r)) {
                 $log[$tablename] = "Failed to migrate data from table '{$t_tablename}' to '{$tablename}': " . $r->getMessage() . "'";
             } else {
                 $log[$tablename] = "Successfully migrated data from table '{$t_tablename}' to '{$tablename}'.";
             }
             unset($record);
         }
         xf_db_free_result($res2);
         $res = xf_db_query("create table `{$t_tablename}_bu_" . time() . "` select * from `{$t_tablename}`", $app->db());
         $res = xf_db_query("truncate `{$t_tablename}`", $app->db());
         unset($io);
         unset($table);
     }
     return $log;
     $app->_conf['default_language_no_fallback'] = $no_fallback;
 }
コード例 #15
0
ファイル: builder.php プロジェクト: minger11/Pipeline
 /**
  * Updates the database table schema and config files to match the state 
  * of the table object.
  */
 function update()
 {
     $app =& Dataface_Application::getInstance();
     $res = xf_db_query("show columns from `" . str_replace('`', '\\`', $this->table->tablename) . "`", $app->db());
     $existing_fields = array();
     while ($row = xf_db_fetch_assoc($res)) {
         $existing_fields[$row['Field']] = $row;
     }
     // add new / modify existing fields
     foreach ($this->table->fields() as $field) {
         if (!isset($existing_fields[$field['Field']])) {
             // the field does not exist yet.. let's add it
             $res = $this->addFieldToDB($field);
             if (PEAR::isError($res)) {
                 return $res;
             }
         } else {
             if ($this->compareFields($field, $existing_fields[$field['Field']]) !== 0) {
                 $res = $this->alterFieldInDB($field, $existing_fields[$field['Field']]);
                 if (PEAR::isError($res)) {
                     return $res;
                 }
             }
         }
     }
     // remove fields that are no longer there
     $table_fields =& $this->table->fields();
     foreach ($existing_fields as $field) {
         if (!isset($table_fields[$field['Field']])) {
             $res = $this->removeFieldFromDB($field);
             if (PEAR::isError($res)) {
                 return $res;
             }
         }
     }
     // now we can write the config files
     $res = $this->writeConfigFiles();
     if (PEAR::isError($res)) {
         return $res;
     }
 }
コード例 #16
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;
 }
コード例 #17
0
 function test_migrateDefaultLanguage()
 {
     $app =& Dataface_Application::getInstance();
     $vals = xf_db_fetch_assoc(xf_db_query("select * from PeopleIntl where PersonID=1", $app->db()));
     $this->assertEquals("Default Position", $vals['Position']);
     $vals2 = xf_db_fetch_assoc(xf_db_query("select * from PeopleIntl where PersonID=2", $app->db()));
     $this->assertEquals("Default Position 2", $vals2['Position']);
     $tt = new Dataface_TranslationTool();
     $tt->migrateDefaultLanguage('en', array('PeopleIntl'));
     $vals = xf_db_fetch_assoc(xf_db_query("select * from PeopleIntl where PersonID=1", $app->db()));
     $this->assertEquals("My English Position", $vals['Position']);
     $vals2 = xf_db_fetch_assoc(xf_db_query("select * from PeopleIntl where PersonID=2", $app->db()));
     $this->assertEquals("Default Position 2", $vals2['Position']);
 }
コード例 #18
0
    function testTranslateSelect()
    {
        $app =& Dataface_Application::getInstance();
        $translator = new Dataface_QueryTranslator('fr');
        $sql = 'select PersonID, Name, Position, Blurb from PeopleIntl limit 1';
        $tsql = $translator->translateQuery($sql);
        $this->assertEquals(array("select `PeopleIntl`.`PersonID`, `PeopleIntl`.`Name`, ifnull(`PeopleIntl__fr`.`Position`, `PeopleIntl`.`Position`) as `Position`, ifnull(`PeopleIntl__fr`.`Blurb`, `PeopleIntl`.`Blurb`) as `Blurb` from `PeopleIntl` left join `PeopleIntl_fr` as `PeopleIntl__fr` on `PeopleIntl`.`PersonID` = `PeopleIntl__fr`.`PersonID` limit 1"), $tsql);
        $res = xf_db_query($tsql[0], $app->db());
        if (!$res) {
            die(xf_db_error($app->db()));
        }
        $row = xf_db_fetch_assoc($res);
        $this->assertEquals(array('PersonID' => '1', 'Name' => 'Angelia Darla Jacobs', 'Position' => 'Default Position', 'Blurb' => 'My French Blurb'), $row);
        // Now try translating the same query in english
        $translator = new Dataface_QueryTranslator('en');
        $tsql = $translator->translateQuery($sql);
        $this->assertEquals(array("select `PeopleIntl`.`PersonID`, `PeopleIntl`.`Name`, ifnull(`PeopleIntl__en`.`Position`, `PeopleIntl`.`Position`) as `Position`, ifnull(`PeopleIntl__en`.`Blurb`, `PeopleIntl`.`Blurb`) as `Blurb` from `PeopleIntl` left join `PeopleIntl_en` as `PeopleIntl__en` on `PeopleIntl`.`PersonID` = `PeopleIntl__en`.`PersonID` limit 1"), $tsql);
        $res = xf_db_query($tsql[0], $app->db());
        if (!$res) {
            die(xf_db_error($app->db()));
        }
        $row = xf_db_fetch_assoc($res);
        $this->assertEquals(array('PersonID' => '1', 'Name' => 'Angelia Darla Jacobs', 'Position' => 'My English Position', 'Blurb' => 'Default Blurb'), $row);
        // try a glob query
        $sql = 'select * from PeopleIntl limit 1';
        $translator = new Dataface_QueryTranslator('en');
        $tsql = $translator->translateQuery($sql);
        $res = xf_db_query($tsql[0], $app->db());
        if (!$res) {
            die(xf_db_error($app->db()));
        }
        $row = xf_db_fetch_assoc($res);
        $this->assertEquals(array("select `PeopleIntl`.`PersonID`, `PeopleIntl`.`Name`, ifnull(`PeopleIntl__en`.`Position`, `PeopleIntl`.`Position`) as `Position`, ifnull(`PeopleIntl__en`.`Blurb`, `PeopleIntl`.`Blurb`) as `Blurb`, `PeopleIntl`.`Photo`, `PeopleIntl`.`Photo_mimetype` from `PeopleIntl` left join `PeopleIntl_en` as `PeopleIntl__en` on `PeopleIntl`.`PersonID` = `PeopleIntl__en`.`PersonID` limit 1"), $tsql);
        $this->assertEquals(array('PersonID' => '1', 'Name' => 'Angelia Darla Jacobs', 'Photo' => 'Angelia_Darla_Jacobs.jpg', 'Photo_mimetype' => null, 'Position' => 'My English Position', 'Blurb' => 'Default Blurb'), $row);
        // Now the same query with french translation
        $translator = new Dataface_QueryTranslator('fr');
        $tsql = $translator->translateQuery($sql);
        $res = xf_db_query($tsql[0], $app->db());
        if (!$res) {
            die(xf_db_error($app->db()));
        }
        $row = xf_db_fetch_assoc($res);
        $this->assertEquals(array("select `PeopleIntl`.`PersonID`, `PeopleIntl`.`Name`, ifnull(`PeopleIntl__fr`.`Position`, `PeopleIntl`.`Position`) as `Position`, ifnull(`PeopleIntl__fr`.`Blurb`, `PeopleIntl`.`Blurb`) as `Blurb`, `PeopleIntl`.`Photo`, `PeopleIntl`.`Photo_mimetype` from `PeopleIntl` left join `PeopleIntl_fr` as `PeopleIntl__fr` on `PeopleIntl`.`PersonID` = `PeopleIntl__fr`.`PersonID` limit 1"), $tsql);
        $this->assertEquals(array('PersonID' => '1', 'Name' => 'Angelia Darla Jacobs', 'Photo' => 'Angelia_Darla_Jacobs.jpg', 'Photo_mimetype' => null, 'Position' => 'Default Position', 'Blurb' => 'My French Blurb'), $row);
        // try a simple query with a where clause
        $sql = 'select * from PeopleIntl where PersonID=\'1\' limit 1';
        $translator = new Dataface_QueryTranslator('en');
        $tsql = $translator->translateQuery($sql);
        $res = xf_db_query($tsql[0], $app->db());
        if (!$res) {
            die(xf_db_error($app->db()));
        }
        $row = xf_db_fetch_assoc($res);
        $this->assertEquals(array("select `PeopleIntl`.`PersonID`, `PeopleIntl`.`Name`, ifnull(`PeopleIntl__en`.`Position`, `PeopleIntl`.`Position`) as `Position`, ifnull(`PeopleIntl__en`.`Blurb`, `PeopleIntl`.`Blurb`) as `Blurb`, `PeopleIntl`.`Photo`, `PeopleIntl`.`Photo_mimetype` from `PeopleIntl` left join `PeopleIntl_en` as `PeopleIntl__en` on `PeopleIntl`.`PersonID` = `PeopleIntl__en`.`PersonID` where `PeopleIntl`.`PersonID` = '1' limit 1"), $tsql);
        $this->assertEquals(array('PersonID' => '1', 'Name' => 'Angelia Darla Jacobs', 'Photo' => 'Angelia_Darla_Jacobs.jpg', 'Photo_mimetype' => null, 'Position' => 'My English Position', 'Blurb' => 'Default Blurb'), $row);
        // Try the same query in french
        $translator = new Dataface_QueryTranslator('fr');
        $tsql = $translator->translateQuery($sql);
        $res = xf_db_query($tsql[0], $app->db());
        if (!$res) {
            die(xf_db_error($app->db()));
        }
        $row = xf_db_fetch_assoc($res);
        $this->assertEquals(array("select `PeopleIntl`.`PersonID`, `PeopleIntl`.`Name`, ifnull(`PeopleIntl__fr`.`Position`, `PeopleIntl`.`Position`) as `Position`, ifnull(`PeopleIntl__fr`.`Blurb`, `PeopleIntl`.`Blurb`) as `Blurb`, `PeopleIntl`.`Photo`, `PeopleIntl`.`Photo_mimetype` from `PeopleIntl` left join `PeopleIntl_fr` as `PeopleIntl__fr` on `PeopleIntl`.`PersonID` = `PeopleIntl__fr`.`PersonID` where `PeopleIntl`.`PersonID` = '1' limit 1"), $tsql);
        $this->assertEquals(array('PersonID' => '1', 'Name' => 'Angelia Darla Jacobs', 'Photo' => 'Angelia_Darla_Jacobs.jpg', 'Photo_mimetype' => null, 'Position' => 'Default Position', 'Blurb' => 'My French Blurb'), $row);
        // Now try a where clause on a translated field
        $sql = 'select PersonID, Name, Position from PeopleIntl where Position = \'My English Position\' limit 1';
        $translator = new Dataface_QueryTranslator('en');
        $tsql = $translator->translateQuery($sql);
        $res = xf_db_query($tsql[0], $app->db());
        if (!$res) {
            die(xf_db_error($app->db()));
        }
        $row = xf_db_fetch_assoc($res);
        $this->assertEquals(array("select `PeopleIntl`.`PersonID`, `PeopleIntl`.`Name`, ifnull(`PeopleIntl__en`.`Position`, `PeopleIntl`.`Position`) as `Position` from `PeopleIntl` left join `PeopleIntl_en` as `PeopleIntl__en` on `PeopleIntl`.`PersonID` = `PeopleIntl__en`.`PersonID` where ifnull(`PeopleIntl__en`.`Position`, `PeopleIntl`.`Position`) = 'My English Position' limit 1"), $tsql);
        $this->assertEquals(array('PersonID' => '1', 'Name' => 'Angelia Darla Jacobs', 'Position' => 'My English Position'), $row);
        // See if our parser can handle backticks:
        $sql = 'select `PeopleIntl`.`PersonID`, Name, Position from PeopleIntl where Position = \'My English Position\' limit 1';
        $translator = new Dataface_QueryTranslator('en');
        $tsql = $translator->translateQuery($sql);
        $res = xf_db_query($tsql[0], $app->db());
        if (!$res) {
            die(xf_db_error($app->db()));
        }
        $row = xf_db_fetch_assoc($res);
        $this->assertEquals(array("select `PeopleIntl`.`PersonID`, `PeopleIntl`.`Name`, ifnull(`PeopleIntl__en`.`Position`, `PeopleIntl`.`Position`) as `Position` from `PeopleIntl` left join `PeopleIntl_en` as `PeopleIntl__en` on `PeopleIntl`.`PersonID` = `PeopleIntl__en`.`PersonID` where ifnull(`PeopleIntl__en`.`Position`, `PeopleIntl`.`Position`) = 'My English Position' limit 1"), $tsql);
        $this->assertEquals(array('PersonID' => '1', 'Name' => 'Angelia Darla Jacobs', 'Position' => 'My English Position'), $row);
        // Now for some set functions
        $sql = 'select count(*) from PeopleIntl';
        $translator = new Dataface_QueryTranslator('en');
        $tsql = $translator->translateQuery($sql);
        $res = xf_db_query($tsql[0], $app->db());
        if (!$res) {
            die(xf_db_error($app->db()));
        }
        $row = xf_db_fetch_assoc($res);
        $this->assertEquals(array("select count(*) from `PeopleIntl`"), $tsql);
        $this->assertEquals(array('count(*)' => '250'), $row);
        // Try subselects
        $sql = 'select `PeopleIntl`.`PersonID`, Name, Position from PeopleIntl where Position = \'My English Position\' and Position in (select Position from PeopleIntl) limit 1';
        $translator = new Dataface_QueryTranslator('en');
        $tsql = $translator->translateQuery($sql);
        //print_r($translator->_data);
        //print_r($translator->_data_translated);
        $res = xf_db_query($tsql[0], $app->db());
        if (!$res) {
            die(xf_db_error($app->db()));
        }
        $row = xf_db_fetch_assoc($res);
        $this->assertEquals(array("select `PeopleIntl`.`PersonID`, `PeopleIntl`.`Name`, ifnull(`PeopleIntl__en`.`Position`, `PeopleIntl`.`Position`) as `Position` from `PeopleIntl` left join `PeopleIntl_en` as `PeopleIntl__en` on `PeopleIntl`.`PersonID` = `PeopleIntl__en`.`PersonID` where ifnull(`PeopleIntl__en`.`Position`, `PeopleIntl`.`Position`) = 'My English Position' and ifnull(`PeopleIntl__en`.`Position`, `PeopleIntl`.`Position`) in (select ifnull(`PeopleIntl__en`.`Position`, `PeopleIntl`.`Position`) as `Position` from `PeopleIntl` left join `PeopleIntl_en` as `PeopleIntl__en` on `PeopleIntl`.`PersonID` = `PeopleIntl__en`.`PersonID`) limit 1"), $tsql);
        $this->assertEquals(array('PersonID' => '1', 'Name' => 'Angelia Darla Jacobs', 'Position' => 'My English Position'), $row);
        // Try order by clause
        $sql = 'select PersonID, Name, Position, Blurb from PeopleIntl limit 1 order by Position desc';
        $translator = new Dataface_QueryTranslator('fr');
        $tsql = $translator->translateQuery($sql);
        //print_r($tsql);exit;
        $this->assertEquals(array("select `PeopleIntl`.`PersonID`, `PeopleIntl`.`Name`, ifnull(`PeopleIntl__fr`.`Position`, `PeopleIntl`.`Position`) as `Position`, ifnull(`PeopleIntl__fr`.`Blurb`, `PeopleIntl`.`Blurb`) as `Blurb` from `PeopleIntl` left join `PeopleIntl_fr` as `PeopleIntl__fr` on `PeopleIntl`.`PersonID` = `PeopleIntl__fr`.`PersonID` order by ifnull(`PeopleIntl__fr`.`Position`, `PeopleIntl`.`Position`) desc limit 1"), $tsql);
        $res = xf_db_query($tsql[0], $app->db());
        if (!$res) {
            die(xf_db_error($app->db()));
        }
        $row = xf_db_fetch_assoc($res);
        $this->assertEquals(array('PersonID' => '2', 'Name' => 'Antoinette Terri Mccoy', 'Position' => 'My French Position', 'Blurb' => ''), $row);
        /*
        // Try Match clause
        
        $sql = 'select PersonID, Name, Position, Blurb from PeopleIntl where match (Position) against (\'French\' in boolean mode) limit 1 order by Position desc';
        $translator = new Dataface_QueryTranslator('fr');
        $tsql = $translator->translateQuery($sql);
        //print_r($translator->_data_translated);exit;
        print_r($tsql);exit;
        $this->assertEquals(
        	array("select `PeopleIntl`.`PersonID`, `PeopleIntl`.`Name`, ifnull(`PeopleIntl__fr`.`Position`, `PeopleIntl`.`Position`) as `Position`, ifnull(`PeopleIntl__fr`.`Blurb`, `PeopleIntl`.`Blurb`) as `Blurb` from `PeopleIntl` left join `PeopleIntl_fr` as `PeopleIntl__fr` on `PeopleIntl`.`PersonID` = `PeopleIntl__fr`.`PersonID` order by ifnull(`PeopleIntl__fr`.`Position`, `PeopleIntl`.`Position`) desc limit 1"),
        	$tsql
        	);
        
        	
        $res = xf_db_query($tsql[0], $app->db());
        if ( !$res ) die(xf_db_error($app->db()));
        $row = xf_db_fetch_assoc($res);
        $this->assertEquals(
        	array(
        		'PersonID'=>'2',
        		'Name'=> 'Antoinette Terri Mccoy',
        		'Position'=>'My French Position',
        		'Blurb'=>''
        		),
        	$row
        	);
        	
        $sql = "SELECT COUNT(*) FROM `quiz` WHERE MATCH (`question`,`answer_a`,`answer_b`,`answer_c`,`answer_d`,`answer`) AGAINST ('Quelle' IN BOOLEAN MODE) AND MATCH (`question`,`answer_a`,`answer_b`,`answer_c`,`answer_d`,`answer`) AGAINST ('Quelle' IN BOOLEAN MODE)";
        $translator = new Dataface_QueryTranslator('fr');
        $tsql = $translator->translateQuery($sql);
        print_r($translator->_data_translated);
        //print_r($tsql);exit;
        */
        // Try subselect in Tables list
        $sql = 'select 
					p1.PersonID, 
					p1.Name, 
					p1.Position, 
					p1.Blurb, 
					f.PersonID as FriendID, 
					f.Name as FriendName, 
					f.Position as FriendPosition 
				from 
					PeopleIntl p1
					left join 
						( select PersonID, Name, Position from PeopleIntl where PersonID=\'2\') as f
					on
						p1.PersonID = f.PersonID
				limit 1';
        $tsql = $translator->translateQuery($sql);
        print_r($translator->_data_translated);
        print_r($tsql);
        exit;
        $this->assertEquals(array("select `PeopleIntl`.`PersonID`, `PeopleIntl`.`Name`, ifnull(`PeopleIntl__fr`.`Position`, `PeopleIntl`.`Position`) as `Position`, ifnull(`PeopleIntl__fr`.`Blurb`, `PeopleIntl`.`Blurb`) as `Blurb` from `PeopleIntl` left join `PeopleIntl_fr` as `PeopleIntl__fr` on `PeopleIntl`.`PersonID` = `PeopleIntl__fr`.`PersonID` limit 1"), $tsql);
        $res = xf_db_query($tsql[0], $app->db());
        if (!$res) {
            die(xf_db_error($app->db()));
        }
        $row = xf_db_fetch_assoc($res);
        $this->assertEquals(array('PersonID' => '1', 'Name' => 'Angelia Darla Jacobs', 'Position' => 'Default Position', 'Blurb' => 'My French Blurb'), $row);
    }
コード例 #19
0
ファイル: Table.php プロジェクト: Zunair/xataface
 /**
  * @brief Neither INNODB tables nor views store the last updated time
  * inside of MySQL.  This wreaks havoc on caching, so we create
  * our own backup table called dataface__mtimes as a fallback
  * mechanism to track uptime times of tables.  The down side
  * is that it only updates the timestamp when a change is made
  * via Xataface.  Outside changes aren't tracked.
  *
  * @param boolean $refresh This outputs the value from cache if possible.  Setting this parameter to true
  *		overrides this to check the database again.
  * @return array(string=>long) Array of all of the table modification times in the system. Format:
  * @code
  *	array(
  *		'table1' => 123456789078668
  *		'table2' => 987654345678967
  *		...
  * )
  * @endcode
  *
  * @see Dataface_IO::createModificationTimesTable()
  * @see Dataface_IO::touchTable($tablename)
  */
 public static function &getBackupModificationTimes($refresh = false)
 {
     static $backup_times = 0;
     if ($backup_times === 0 or $refresh) {
         $res = xf_db_query("select * from dataface__mtimes", df_db());
         if (!$res) {
             import('Dataface/IO.php');
             Dataface_IO::createModificationTimesTable();
             $res = xf_db_query("select * from dataface__mtimes", df_db());
             if (!$res) {
                 throw new Exception(xf_db_error(df_db()));
             }
         }
         $backup_times = array();
         while ($row = xf_db_fetch_assoc($res)) {
             $backup_times[$row['name']] = $row['mtime'];
         }
         @xf_db_free_result($res);
     }
     return $backup_times;
 }
コード例 #20
0
ファイル: MySQLDataSource.php プロジェクト: minger11/Pipeline
 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);
 }