alecpl
2010-04-22 3d6c04ddf0383f261331480cf5221e3cb5e95d75
- SQL performance fixes + code formatting


1 files modified
234 ■■■■■ changed files
program/include/rcube_contacts.php 234 ●●●●● patch | view | raw | blame | history
program/include/rcube_contacts.php
@@ -5,7 +5,7 @@
 | program/include/rcube_contacts.php                                    |
 |                                                                       |
 | This file is part of the RoundCube Webmail client                     |
 | Copyright (C) 2006-2009, RoundCube Dev. - Switzerland                 |
 | Copyright (C) 2006-2010, RoundCube Dev. - Switzerland                 |
 | Licensed under the GNU GPL                                            |
 |                                                                       |
 | PURPOSE:                                                              |
@@ -27,14 +27,14 @@
 */
class rcube_contacts extends rcube_addressbook
{
  var $db = null;
  var $db_name = '';
  var $user_id = 0;
  var $filter = null;
  var $result = null;
  var $search_fields;
  var $search_string;
  var $table_cols = array('name', 'email', 'firstname', 'surname', 'vcard');
    private $db = null;
    private $db_name = '';
    private $user_id = 0;
    private $filter = null;
    private $result = null;
    private $search_fields;
    private $search_string;
    private $table_cols = array('name', 'email', 'firstname', 'surname', 'vcard');
  
  /** public properties */
  var $primary_key = 'contact_id';
@@ -104,6 +104,7 @@
    $this->search_string = null;
  }
  
  /**
   * List all active contact groups of this source
   *
@@ -120,11 +121,11 @@
    $sql_filter = $search ? "AND " . $this->db->ilike('name', '%'.$search.'%') : '';
    $sql_result = $this->db->query(
      "SELECT * FROM ".get_table_name('contactgroups')."
       WHERE  del<>1
       AND    user_id=?
       $sql_filter
       ORDER BY name",
            "SELECT * FROM ".get_table_name('contactgroups').
            " WHERE del<>1".
            " AND user_id=?".
            $sql_filter.
            " ORDER BY name",
      $this->user_id);
    while ($sql_result && ($sql_arr = $this->db->fetch_assoc($sql_result))) {
@@ -134,6 +135,7 @@
    
    return $results;
  }
  
  /**
   * List the current set of contact records
@@ -145,24 +147,25 @@
   */
  function list_records($cols=null, $subset=0, $nocount=false)
  {
    // count contacts for this user
    $this->result = $nocount ? new rcube_result_set(1) : $this->count();
    $sql_result = NULL;
    // get contacts from DB
    if ($this->result->count)
    {
      if ($this->group_id)
        $join = "LEFT JOIN ".get_table_name('contactgroupmembers')." AS m".
          " ON (m.contact_id=c.".$this->primary_key.")";
        if ($nocount || $this->list_page <= 1) {
            // create dummy result, we don't need a count now
            $this->result = new rcube_result_set();
        } else {
            // count all records
            $this->result = $this->count();
        }
      
      $start_row = $subset < 0 ? $this->result->first + $this->page_size + $subset : $this->result->first;
      $length = $subset != 0 ? abs($subset) : $this->page_size;
      
        if ($this->group_id)
            $join = "LEFT JOIN ".get_table_name('contactgroupmembers')." AS m".
                " ON (m.contact_id = c.".$this->primary_key.")";
      $sql_result = $this->db->limitquery(
        "SELECT * FROM ".$this->db_name." AS c ".$join."
         WHERE  c.del<>1
         AND    c.user_id=?" .
            "SELECT * FROM ".$this->db_name." AS c ".$join .
            " WHERE c.del<>1" .
            " AND c.user_id=?" .
        ($this->group_id ? " AND m.contactgroup_id=?" : "").
        ($this->filter ? " AND (".$this->filter.")" : "") .
        " ORDER BY c.name",
@@ -170,10 +173,8 @@
        $length,
        $this->user_id,
        $this->group_id);
    }
    
    while ($sql_result && ($sql_arr = $this->db->fetch_assoc($sql_result)))
    {
        while ($sql_result && ($sql_arr = $this->db->fetch_assoc($sql_result))) {
      $sql_arr['ID'] = $sql_arr[$this->primary_key];
      // make sure we have a name to display
      if (empty($sql_arr['name']))
@@ -181,8 +182,17 @@
      $this->result->add($sql_arr);
    }
    
        $cnt = count($this->result->records);
        // update counter
    if ($nocount)
      $this->result->count = count($this->result->records);
            $this->result->count = $cnt;
        else if ($this->list_page <= 1) {
            if ($cnt < $this->page_size && $subset == 0)
                $this->result->count = $cnt;
            else
                $this->result->count = $this->_count();
        }
    
    return $this->result;
  }
@@ -204,10 +214,8 @@
      $fields = array($fields);
      
    $add_where = array();
    foreach ($fields as $col)
    {
      if ($col == 'ID' || $col == $this->primary_key)
      {
        foreach ($fields as $col) {
            if ($col == 'ID' || $col == $this->primary_key) {
        $ids = !is_array($value) ? explode(',', $value) : $value;
        $add_where[] = 'c.' . $this->primary_key.' IN ('.join(',', $ids).')';
      }
@@ -217,8 +225,7 @@
        $add_where[] = $this->db->ilike($col, '%'.$value.'%');
    }
    
    if (!empty($add_where))
    {
        if (!empty($add_where)) {
      $this->set_search_set(join(' OR ', $add_where));
      if ($select)
        $this->list_records(null, 0, $nocount);
@@ -233,9 +240,20 @@
  /**
   * Count number of available contacts in database
   *
   * @return Result array with values for 'count' and 'first'
     * @return rcube_result_set Result object
   */
  function count()
    {
        return new rcube_result_set($this->_count(), ($this->list_page-1) * $this->page_size);
    }
    /**
     * Count number of available contacts in database
     *
     * @return int Contacts count
     */
    private function _count()
  {
    if ($this->group_id)
      $join = "LEFT JOIN ".get_table_name('contactgroupmembers')." AS m".
@@ -243,17 +261,18 @@
      
    // count contacts for this user
    $sql_result = $this->db->query(
      "SELECT COUNT(c.contact_id) AS rows
       FROM ".$this->db_name." AS c ".$join."
       WHERE  c.del<>1
       AND    c.user_id=?".
            "SELECT COUNT(c.contact_id) AS rows".
            " FROM ".$this->db_name." AS c ".$join.
            " WHERE  c.del<>1".
            " AND c.user_id=?".
       ($this->group_id ? " AND m.contactgroup_id=?" : "").
       ($this->filter ? " AND (".$this->filter.")" : ""),
      $this->user_id,
      $this->group_id);
            $this->group_id
        );
    $sql_arr = $this->db->fetch_assoc($sql_result);
    return new rcube_result_set($sql_arr['rows'], ($this->list_page-1) * $this->page_size);;
        return (int) $sql_arr['rows'];
  }
@@ -281,15 +300,15 @@
      return $assoc ? $first : $this->result;
      
    $this->db->query(
      "SELECT * FROM ".$this->db_name."
       WHERE  contact_id=?
       AND    user_id=?
       AND    del<>1",
            "SELECT * FROM ".$this->db_name.
            " WHERE contact_id=?".
                " AND user_id=?".
                " AND del<>1",
      $id,
      $this->user_id);
            $this->user_id
        );
    if ($sql_arr = $this->db->fetch_assoc())
    {
        if ($sql_arr = $this->db->fetch_assoc()) {
      $sql_arr['ID'] = $sql_arr[$this->primary_key];
      $this->result = new rcube_result_set(1);
      $this->result->add($sql_arr);
@@ -316,19 +335,18 @@
      $existing = $this->search('email', $save_data['email'], true, false);
    $a_insert_cols = $a_insert_values = array();
    foreach ($this->table_cols as $col)
      if (isset($save_data[$col]))
      {
            if (isset($save_data[$col])) {
        $a_insert_cols[] = $this->db->quoteIdentifier($col);
        $a_insert_values[] = $this->db->quote($save_data[$col]);
      }
    if (!$existing->count && !empty($a_insert_cols))
    {
        if (!$existing->count && !empty($a_insert_cols)) {
      $this->db->query(
        "INSERT INTO ".$this->db_name."
         (user_id, changed, del, ".join(', ', $a_insert_cols).")
         VALUES (".intval($this->user_id).", ".$this->db->now().", 0, ".join(', ', $a_insert_values).")"
                "INSERT INTO ".$this->db_name.
                " (user_id, changed, del, ".join(', ', $a_insert_cols).")".
                " VALUES (".intval($this->user_id).", ".$this->db->now().", 0, ".join(', ', $a_insert_values).")"
        );
        
      $insert_id = $this->db->insert_id('contacts');
@@ -348,8 +366,7 @@
  function insert_recset($result, $check=false)
  {
    $ids = array();
    while ($row = $result->next())
    {
        while ($row = $result->next()) {
      if ($insert = $this->insert($row, $check))
        $ids[] = $insert;
    }
@@ -368,20 +385,22 @@
  {
    $updated = false;
    $write_sql = array();
    foreach ($this->table_cols as $col)
      if (isset($save_cols[$col]))
        $write_sql[] = sprintf("%s=%s", $this->db->quoteIdentifier($col), $this->db->quote($save_cols[$col]));
                $write_sql[] = sprintf("%s=%s", $this->db->quoteIdentifier($col),
                    $this->db->quote($save_cols[$col]));
    if (!empty($write_sql))
    {
        if (!empty($write_sql)) {
      $this->db->query(
        "UPDATE ".$this->db_name."
         SET    changed=".$this->db->now().", ".join(', ', $write_sql)."
         WHERE  contact_id=?
         AND    user_id=?
         AND    del<>1",
                "UPDATE ".$this->db_name.
                " SET changed=".$this->db->now().", ".join(', ', $write_sql).
                " WHERE contact_id=?".
                    " AND user_id=?".
                    " AND del<>1",
        $id,
        $this->user_id);
                $this->user_id
            );
      $updated = $this->db->affected_rows();
    }
@@ -400,13 +419,16 @@
    if (is_array($ids))
      $ids = join(',', $ids);
        $ids = join(',', array_map(array($this->db, 'quote'), $ids));
    // flag record as deleted
    $this->db->query(
      "UPDATE ".$this->db_name."
       SET    del=1, changed=".$this->db->now()."
       WHERE  user_id=?
       AND    contact_id IN (".$ids.")",
      $this->user_id);
            "UPDATE ".$this->db_name.
            " SET del=1, changed=".$this->db->now().
            " WHERE user_id=?".
                " AND contact_id IN ($ids)",
            $this->user_id
        );
    return $this->db->affected_rows();
  }
@@ -436,8 +458,9 @@
    $name = $this->unique_groupname($name);
    
    $this->db->query(
      "INSERT INTO ".get_table_name('contactgroups')." (user_id, changed, name)
       VALUES (".intval($this->user_id).", ".$this->db->now().", ".$this->db->quote($name).")"
            "INSERT INTO ".get_table_name('contactgroups').
            " (user_id, changed, name)".
            " VALUES (".intval($this->user_id).", ".$this->db->now().", ".$this->db->quote($name).")"
      );
    
    if ($insert_id = $this->db->insert_id('contactgroups'))
@@ -445,6 +468,7 @@
    
    return $result;
  }
  /**
   * Delete the given group (and all linked group members)
@@ -456,13 +480,15 @@
  {
    // flag group record as deleted
    $sql_result = $this->db->query(
      "UPDATE ".get_table_name('contactgroups')."
       SET del=1, changed=".$this->db->now()."
       WHERE  contactgroup_id=?",
      $gid);
            "UPDATE ".get_table_name('contactgroups').
            " SET del=1, changed=".$this->db->now().
            " WHERE contactgroup_id=?",
            $gid
        );
    
    return $this->db->affected_rows();
  }
  
  /**
   * Rename a specific contact group
@@ -477,13 +503,15 @@
    $name = $this->unique_groupname($newname);
    
    $sql_result = $this->db->query(
      "UPDATE ".get_table_name('contactgroups')."
       SET name=".$this->db->quote($name).", changed=".$this->db->now()."
       WHERE  contactgroup_id=?",
      $gid);
            "UPDATE ".get_table_name('contactgroups').
            " SET name=?, changed=".$this->db->now().
            " WHERE contactgroup_id=?",
            $name, $gid
        );
    
    return $this->db->affected_rows() ? $name : false;
  }
  /**
   * Add the given contact records the a certain group
@@ -501,17 +529,22 @@
    
    foreach ($ids as $contact_id) {
      $sql_result = $this->db->query(
        "SELECT 1 FROM ".get_table_name('contactgroupmembers')."
         WHERE  contactgroup_id=?
         AND    contact_id=?",
                "SELECT 1 FROM ".get_table_name('contactgroupmembers').
                " WHERE contactgroup_id=?".
                    " AND contact_id=?",
      $group_id,
      $contact_id);
                $contact_id
            );
      
      if (!$this->db->num_rows($sql_result)) {
        $this->db->query(
          "INSERT INTO ".get_table_name('contactgroupmembers')." (contactgroup_id, contact_id, created)
           VALUES (".intval($group_id).", ".intval($contact_id).", ".$this->db->now().")"
                    "INSERT INTO ".get_table_name('contactgroupmembers').
                    " (contactgroup_id, contact_id, created)".
                    " VALUES (?, ?, ".$this->db->now().")",
                    $group_id,
                    $contact_id
        );
        if (!$this->db->db_error)
          $added++;
      }
@@ -533,14 +566,18 @@
    if (!is_array($ids))
      $ids = explode(',', $ids);
    
        $ids = join(',', array_map(array($this->db, 'quote'), $ids));
    $sql_result = $this->db->query(
      "DELETE FROM ".get_table_name('contactgroupmembers')."
       WHERE  contactgroup_id=?
       AND    contact_id IN (".join(',', array_map(array($this->db, 'quote'), $ids)).")",
      $group_id);
            "DELETE FROM ".get_table_name('contactgroupmembers').
            " WHERE contactgroup_id=?".
                " AND contact_id IN ($ids)",
            $group_id
        );
    
    return $this->db->affected_rows();
  }
  
  /**
   * Check for existing groups with the same name
@@ -555,10 +592,10 @@
    
    do {
      $sql_result = $this->db->query(
        "SELECT 1 FROM ".get_table_name('contactgroups')."
         WHERE  del<>1
         AND    user_id=?
         AND    name LIKE ?",
                "SELECT 1 FROM ".get_table_name('contactgroups').
                " WHERE del<>1".
                    " AND user_id=?".
                    " AND name LIKE ?",
        $this->user_id,
        $checkname);
    
@@ -569,4 +606,5 @@
    
    return $checkname;
  }
}