/** * Set the location of the specified event _id * * @see Kronolith_Geo_Base#setLocation() * @throws Kronolith_Exception */ public function setLocation($event_id, $point) { /* First make sure it doesn't already exist */ $sql = 'SELECT COUNT(*) FROM kronolith_events_geo WHERE event_id = ?'; try { $count = $this->_db->selectValue($sql, array($event_id)); } catch (Horde_Db_Exception $e) { throw new Kronolith_Exception($e); } /* Do we actually have data? If not, see if we are deleting an * existing entry. */ if ((empty($point['lat']) || empty($point['lon'])) && $count) { // Delete the record. $this->deleteLocation($event_id); return; } elseif (empty($point['lat']) || empty($point['lon'])) { return; } if (empty($point['zoom'])) { $point['zoom'] = 0; } /* INSERT or UPDATE */ $params = array($point['lat'], $point['lon'], $point['zoom'], $event_id); try { if ($count) { $sql = 'UPDATE kronolith_events_geo SET event_lat = ?, event_lon = ?, event_zoom = ? WHERE event_id = ?'; $this->_db->update($sql, $params); } else { $sql = 'INSERT into kronolith_events_geo (event_lat, event_lon, event_zoom, event_id) VALUES(?, ?, ?, ?)'; $this->_db->insert($sql, $params); } } catch (Horde_Db_Exception $e) { throw new Horde_Exception($e); } }
/** * Save the provided sync_cache. * * @param array $cache The cache to save. * @param string $devid The device id. * @param string $user The user id. * @param array $dirty An array of dirty properties. @since 2.9.0 * * @throws Horde_ActiveSync_Exception */ public function saveSyncCache(array $cache, $devid, $user, array $dirty = null) { $cache['timestamp'] = strval($cache['timestamp']); $sql = 'SELECT count(*) FROM ' . $this->_syncCacheTable . ' WHERE cache_devid = ? AND cache_user = ?'; try { $have = $this->_db->selectValue($sql, array($devid, $user)); } catch (Horde_Db_Exception $e) { $this->_logger->err(sprintf('[%s] %s', $this->_procid, $e->getMessage())); throw new Horde_ActiveSync_Exception($e); } $cache = serialize($cache); if ($have) { $this->_logger->info(sprintf('[%s] Replacing SYNC_CACHE entry for user %s and device %s: %s', $this->_procid, $user, $devid, $cache)); $sql = 'UPDATE ' . $this->_syncCacheTable . ' SET cache_data = ? WHERE cache_devid = ? AND cache_user = ?'; try { $this->_db->update($sql, array($cache, $devid, $user)); } catch (Horde_Db_Exception $e) { $this->_logger->err(sprintf('[%s] %s', $this->_procid, $e->getMessage())); throw new Horde_ActiveSync_Exception($e); } } else { $this->_logger->info(sprintf('[%s] Adding new SYNC_CACHE entry for user %s and device %s: %s', $this->_procid, $user, $devid, $cache)); $sql = 'INSERT INTO ' . $this->_syncCacheTable . ' (cache_data, cache_devid, cache_user) VALUES (?, ?, ?)'; try { $this->_db->insert($sql, array($cache, $devid, $user)); } catch (Horde_Db_Exception $e) { $this->_logger->err(sprintf('[%s] %s', $this->_procid, $e->getMessage())); throw new Horde_ActiveSync_Exception($e); } } }
/** */ public function write($id, $session_data) { if (!$this->_db->isActive()) { $this->_db->reconnect(); $this->_db->beginDbTransaction(); } /* Check if session exists. */ try { $exists = $this->_db->selectValue(sprintf('SELECT 1 FROM %s WHERE session_id = ?', $this->_params['table']), array($id)); } catch (Horde_Db_Exception $e) { return false; } /* Update or insert session data. */ $session_data = new Horde_Db_Value_Binary($session_data); try { if ($exists) { $query = sprintf('UPDATE %s ' . 'SET session_data = ?, session_lastmodified = ? ' . 'WHERE session_id = ?', $this->_params['table']); $values = array($session_data, time(), $id); $this->_db->update($query, $values); } else { $query = sprintf('INSERT INTO %s ' . '(session_id, session_data, session_lastmodified) ' . 'VALUES (?, ?, ?)', $this->_params['table']); $values = array($id, $session_data, time()); $this->_db->insert($query, $values); } $this->_db->commitDbTransaction(); } catch (Horde_Db_Exception $e) { try { $this->_db->rollbackDbTransaction(); } catch (Horde_Db_Exception $e) { } return false; } return true; }
/** */ public function setMetaData($mailbox, $data) { if (!($uid = $this->_getUid($mailbox))) { $uid = $this->_createUid($mailbox); } $query = sprintf('SELECT field FROM %s where messageid = ?', self::MD_TABLE); $values = array($uid); try { $fields = $this->_db->selectValues($query, $values); } catch (Horde_Db_Exception $e) { return; } foreach ($data as $key => $val) { $val = new Horde_Db_Value_Binary($key == 'uidvalid' ? $val : serialize($val)); if (in_array($key, $fields)) { /* Update */ try { $this->_db->update(sprintf('UPDATE %s SET data = ? WHERE field = ? AND messageid = ?', self::MD_TABLE), array($val, $key, $uid)); } catch (Horde_Db_Exception $e) { } } else { /* Insert */ try { $this->_db->insert(sprintf('INSERT INTO %s (data, field, messageid) VALUES (?, ?, ?)', self::MD_TABLE), array($val, $key, $uid)); } catch (Horde_Db_Exception $e) { } } } }
/** * Modifies a SQL password record for a user. * * @param string $user The user whose record we will udpate. * @param string $newpass The new password value to set. * * @throws Passwd_Exception */ protected function _modify($user, $newpass) { /* Only split up username if domain is set in backend. */ if ($this->_params['domain']) { list($name, $domain) = explode('@', $user); } else { $name = $user; } /* Encrypt the password. */ $clear_password = $newpass; $newpass = $this->_encryptPassword($newpass); /* Build the SQL query. */ $sql = 'UPDATE ' . $this->_params['table'] . ' SET ' . $this->_params['passwd'] . ' = ?'; $values = array($newpass); if ($this->_params['use_clear_passwd']) { $sql .= ', ' . $this->_params['clear_passwd'] . ' = ?'; $values[] = $clear_password; } $sql .= ' WHERE ' . $this->_params['name'] . ' = ?'; $values[] = $name; if ($this->_params['domain']) { $sql .= ' AND ' . $this->_params['domain'] . ' = ?'; $values[] = $domain; } /* Execute the query. */ try { $this->_db->update($sql, $values); } catch (Horde_Db_Exception $e) { throw new Passwd_Exception($e); } }
/** * @TODO * * @param <type> $clientID * @param <type> $enterDescription * @param string $exportID * @return <type> */ public function updateClientSettings($clientID, $enterDescription = 1, $exportID = null) { if (empty($exportID)) { $exportID = null; } $sql = 'SELECT clientjob_id FROM hermes_clientjobs WHERE clientjob_id = ?'; $values = array($clientID); if ($this->_db->selectValue($sql, $values) !== $clientID) { $sql = 'INSERT INTO hermes_clientjobs (clientjob_id,' . ' clientjob_enterdescription, clientjob_exportid)' . ' VALUES (?, ?, ?)'; $values = array($clientID, (int) $enterDescription, $this->_convertToDriver($exportID)); try { return $this->_db->insert($sql, $values); } catch (Horde_Db_Exception $e) { throw new Hermes_Exception($e); } } else { $sql = 'UPDATE hermes_clientjobs SET' . ' clientjob_exportid = ?, clientjob_enterdescription = ?' . ' WHERE clientjob_id = ?'; $values = array($this->_convertToDriver($exportID), (int) $enterDescription, $clientID); try { return $this->_db->update($sql, $values); } catch (Horde_Db_Exception $e) { throw new Hermes_Exception($e); } } }
/** */ public function set($mailbox, $data, $uidvalid) { if ($uid = $this->_getUid($mailbox)) { $res = $this->get($mailbox, array_keys($data), array(), $uidvalid); } else { $res = array(); $uid = $this->_createUid($mailbox); } $compress = new Horde_Compress_Fast(); foreach ($data as $key => $val) { if (isset($res[$key])) { try { /* Update */ $this->_db->updateBlob(self::MSG_TABLE, array('data' => new Horde_Db_Value_Binary($compress->compress(serialize(array_merge($res[$key], $val))))), array('messageid = ? AND msguid = ?', array($uid, strval($key)))); } catch (Horde_Db_Exception $e) { } } else { /* Insert */ try { $this->_db->insertBlob(self::MSG_TABLE, array('data' => new Horde_Db_Value_Binary($compress->compress(serialize($val))), 'msguid' => strval($key), 'messageid' => $uid)); } catch (Horde_Db_Exception $e) { } } } /* Update modified time. */ try { $this->_db->update(sprintf('UPDATE %s SET modified = ? WHERE messageid = ?', self::BASE_TABLE), array(time(), $uid)); } catch (Horde_Db_Exception $e) { } /* Update uidvalidity. */ $this->setMetaData($mailbox, array('uidvalid' => $uidvalid)); }
/** * Renames a share in the shares system. * * @param Horde_Share_Object $share The share to rename. * @param string $name The share's new name. * * @throws Horde_Share_Exception */ protected function _renameShare(Horde_Share_Object $share, $name) { try { $this->_db->update('UPDATE ' . $this->_table . ' SET share_name = ? WHERE share_id = ?', array($name, $share->getId())); } catch (Horde_Db_Exception $e) { throw new Horde_Share_Exception($e); } }
/** * Set the gallery id for a set of images. Useful for bulk updating images * when moving from one gallery to another. * * @param array $image_ids An array of image ids * @param integer $gallery_id The gallery id to move the images to. * * @throws Ansel_Exception */ public function setImagesGallery(array $image_ids, $gallery_id) { try { $this->_db->update('UPDATE ansel_images SET gallery_id = ' . $gallery_id . ' WHERE image_id IN (' . implode(',', $image_ids) . ')'); } catch (Horde_Db_Exception $e) { Horde::log($e->getMessage(), 'ERR'); throw new Ansel_Exception($e); } }
/** * Executes the update statement and returns the number of rows affected. * * @param string $sql SQL statement. * @param mixed $arg1 Either an array of bound parameters or a query * name. * @param string $arg2 If $arg1 contains bound parameters, the query * name. * * @return integer Number of rows affected. * @throws Horde_Db_Exception */ public function update($sql, $arg1 = null, $arg2 = null) { $result = $this->_write->update($sql, $arg1, $arg2); $this->_lastQuery = $this->_write->getLastQuery(); // Once doing writes, keep using the write backend even for reads // at least during the same request, to help against stale data. $this->_read = $this->_write; return $result; }
/** * Dismisses an alarm. * * @param string $id The alarm's unique id. * @param string $user The alarm's user * * @throws Horde_Alarm_Exception */ protected function _dismiss($id, $user) { $query = sprintf('UPDATE %s set alarm_dismissed = 1 WHERE alarm_id = ? AND %s', $this->_params['table'], !empty($user) ? 'alarm_uid = ?' : '(alarm_uid = ? OR alarm_uid IS NULL)'); $values = array($id, $user); try { $this->_db->update($query, $values); } catch (Horde_Db_Exception $e) { throw new Horde_Alarm_Exception(Horde_Alarm_Translation::t("Server error when querying database.")); } }
/** * Sets one or more attributes of a group. * * @param mixed $gid A group ID. * @param array|string $attribute An attribute name or a hash of * attributes. * @param string $value An attribute value if $attribute is a * string. * * @throws Horde_Group_Exception */ public function setData($gid, $attribute, $value = null) { $attributes = is_array($attribute) ? $attribute : array($attribute => $value); $updates = array(); foreach ($attributes as $attribute => $value) { $updates[] = $this->_db->quoteColumnName('group_' . $attribute) . ' = ' . $this->_db->quote($value); } try { $this->_db->update('UPDATE horde_groups SET ' . implode(', ', $updates) . ' WHERE group_uid = ?', array($gid)); } catch (Horde_Db_Exception $e) { throw new Horde_Group_Exception($e); } }
/** * Moves an event to a new calendar. * * @param string $eventId The event to move. * @param string $newCalendar The new calendar. * * @return Kronolith_Event The old event. * @throws Kronolith_Exception * @throws Horde_Exception_NotFound */ protected function _move($eventId, $newCalendar) { /* Fetch the event for later use. */ $event = $this->getEvent($eventId); $query = 'UPDATE kronolith_events SET calendar_id = ? WHERE calendar_id = ? AND event_id = ?'; $values = array($newCalendar, $this->calendar, $eventId); /* Attempt the move query. */ try { $this->_db->update($query, $values); } catch (Horde_Db_Exception $e) { throw new Kronolith_Exception($e); } return $event; }
/** * Extend the valid lifetime of a valid lock to now + $lifetime. * * @see Horde_Lock_Base::resetLock() */ public function resetLock($lockid, $lifetime) { $now = time(); if (!$this->getLockInfo($lockid)) { return false; } $expiration = $lifetime == Horde_Lock::PERMANENT ? Horde_Lock::PERMANENT : $now + $lifetime; $sql = 'UPDATE ' . $this->_params['table'] . ' SET ' . 'lock_update_timestamp = ?, lock_expiry_timestamp = ? ' . 'WHERE lock_id = ? AND lock_expiry_timestamp <> ?'; $values = array($now, $expiration, $lockid, Horde_Lock::PERMANENT); try { $this->_db->update($sql, $values); } catch (Horde_Db_Exception $e) { throw new Horde_Lock_Exception($e); } return true; }
/** */ public function sort($rules) { $old = $this->_filters; parent::sort($rules); $query = sprintf('UPDATE %s SET rule_order = ? WHERE rule_id = ?', $this->_params['table_rules']); $this->_db->beginDbTransaction(); try { foreach ($this->_filters as $key => $val) { $this->_db->update($query, array($key, $val['id'])); } } catch (Horde_Db_Exception $e) { $this->_db->rollbackDbTransaction(); $this->_filters = $old; throw new Ingo_Exception($e); } $this->_db->commitDbTransaction(); }
/** */ public function store($scope_ob) { if (!$this->_db->isActive()) { $this->_db->reconnect(); } $charset = $this->_db->getOption('charset'); // For each preference, check for an existing table row and // update it if it's there, or create a new one if it's not. foreach ($scope_ob->getDirty() as $name) { $value = $scope_ob->get($name); if (is_null($value)) { $this->remove($scope_ob->scope, $name); } else { $values = array($this->_params['user'], $name, $scope_ob->scope); // Does a row already exist for this preference? $query = 'SELECT 1 FROM ' . $this->_params['table'] . ' WHERE pref_uid = ? AND pref_name = ?' . ' AND pref_scope = ?'; try { $check = $this->_db->selectValue($query, $values); } catch (Horde_Db_Exception $e) { throw new Horde_Prefs_Exception($e); } /* Driver has no support for storing locked status. */ $value = Horde_String::convertCharset($value, 'UTF-8', $charset); $value = new Horde_Db_Value_Binary($value); if (empty($check)) { // Insert a new row. $query = 'INSERT INTO ' . $this->_params['table'] . ' ' . '(pref_uid, pref_scope, pref_name, pref_value) VALUES' . '(?, ?, ?, ?)'; $values = array($this->_params['user'], $scope_ob->scope, $name, $value); try { $this->_db->insert($query, $values); } catch (Horde_Db_Exception $e) { throw new Horde_Prefs_Exception($e); } } else { // Update the existing row. $query = 'UPDATE ' . $this->_params['table'] . ' SET pref_value = ?' . ' WHERE pref_uid = ?' . ' AND pref_name = ?' . ' AND pref_scope = ?'; $values = array($value, $this->_params['user'], $name, $scope_ob->scope); try { $this->_db->update($query, $values); } catch (Horde_Db_Exception $e) { throw new Horde_Prefs_Exception($e); } } } } }
/** * Sets the specified sort order to the fields in a form. * * @param array $info An array with the field ids in * a specific order. * * @return boolean True on success. * @throws Horde_Exception_NotFound * @throws Ulaform_Exception */ public function sortFields(&$info) { if (empty($info['form_id'])) { throw new Horde_Exception_NotFound(_("Missing form")); } foreach ($info['field_order'] as $field_order => $field_id) { $sql = 'UPDATE ulaform_fields SET field_order = ? WHERE field_id = ?'; try { $this->_db->update($sql, array((int) $field_order, (int) $field_id)); } catch (Horde_Db_Exception $e) { throw new Ulaform_Exception($e->getMessage()); } } return true; }
/** * Modifies a SQL password record for a user. * * @param string $user The user whose record we will udpate. * @param string $newpass The new password value to set. * * @throws Passwd_Exception */ protected function _modify($user, $newpass) { if (!empty($this->_params['query_modify'])) { list($sql, $values) = $this->_parseQuery($this->_params['query_modify'], $user, $newpass); } else { /* Encrypt the password. */ $newpass = $this->_encryptPassword($newpass); /* Build the SQL query. */ $sql = 'UPDATE ' . $this->_params['table'] . ' SET ' . $this->_params['pass_col'] . ' = ?' . ' WHERE ' . $this->_params['user_col'] . ' = ?'; $values = array($newpass, $user); } /* Execute the query. */ try { $this->_db->update($sql, $values); } catch (Horde_Db_Exception $e) { throw new Passwd_Exception($e); } }
/** * Saves the specified object in the SQL database. * * @param Turba_Object $object The object to save. * * @return string The object id, possibly updated. * @throws Turba_Exception */ protected function _save(Turba_Object $object) { list($object_key, $object_id) = each($this->toDriverKeys(array('__key' => $object->getValue('__key')))); $attributes = $this->toDriverKeys($object->getAttributes()); $blob_fields = $this->toDriverKeys($this->getBlobs()); $date_fields = $this->toDriverKeys($this->getDateFields()); $where = $object_key . ' = ?'; unset($attributes[$object_key]); list($fields, $values) = $this->_prepareWrite($attributes, $blob_fields, $date_fields); $values[] = $object_id; $query = 'UPDATE ' . $this->_params['table'] . ' SET ' . implode(' = ?, ', $fields) . ' = ? WHERE ' . $where; try { $this->_db->update($query, $values); } catch (Horde_Db_Exception $e) { throw new Turba_Exception(_("Server error when saving data.")); } return $object_id; }
/** * Saves any changes to this object to the backend permanently. New * objects are added instead. * * @throws Horde_Perms_Exception */ public function save() { if (!isset($this->_db)) { throw new Horde_Perms_Exception('Cannot save because the DB instances has not been set in this object.'); } $name = $this->getName(); if (empty($name)) { throw new Horde_Perms_Exception('Permission names must be non-empty'); } $query = 'UPDATE horde_perms SET perm_data = ? WHERE perm_id = ?'; $params = array(serialize($this->data), $this->getId()); try { $this->_db->update($query, $params); } catch (Horde_Db_Exception $e) { throw new Horde_Perms_Exception($e); } $this->_cache->expire('perm_sql_' . $this->_cacheVersion . $name); $this->_cache->expire('perm_sql_exists_' . $this->_cacheVersion . $name); }
/** * Remove all occurrences of a specific tag from an object regardless of * the username who tagged the object originally. * * @param mixed $obejctId The object identifier @see Content_Tagger::tag() * @param mixed $tags The tags to remove. @see Content_Tagger::tag() * * @return void */ public function removeTagFromObject($objectId, $tags) { $objectId = $this->_ensureObject($objectId); if (!is_array($tags)) { $tags = array($tags); } foreach ($this->ensureTags($tags) as $tagId) { // Get the users who have tagged this so we can update the stats $users = $this->_db->selectValues('SELECT user_id, tag_id FROM ' . $this->_t('tagged') . ' WHERE object_id = ? AND tag_id = ?', array($objectId, $tagId)); // Delete the tags if ($this->_db->delete('DELETE FROM ' . $this->_t('tagged') . ' WHERE object_id = ? AND tag_id = ?', array($objectId, $tagId))) { // Update the stats $this->_db->update('UPDATE ' . $this->_t('tag_stats') . ' SET count = count - ' . count($users) . ' WHERE tag_id = ?', array($tagId)); $this->_db->update('UPDATE ' . $this->_t('user_tag_stats') . ' SET count = count - 1 WHERE user_id IN(' . str_repeat('?, ', count($users) - 1) . '?) AND tag_id = ?', array_merge($users, array($tagId))); // Housekeeping $this->_db->delete('DELETE FROM ' . $this->_t('tag_stats') . ' WHERE count = 0'); $this->_db->delete('DELETE FROM ' . $this->_t('user_tag_stats') . ' WHERE count = 0'); } } }
/** */ public function removeVersion($pagename, $version) { $values = array($this->_convertToDriver($pagename), (int) $version); /* We need to know if we're deleting the current version. */ try { $result = $this->_db->selectValue('SELECT 1 FROM ' . $this->_params['table'] . ' WHERE page_name = ? AND page_version = ?', $values); } catch (Horde_Db_Exception $e) { $result = false; } if (!$result) { /* Removing a historical revision - we can just slice it out of the * history table. $values is unchanged. */ try { $this->_db->delete('DELETE FROM ' . $this->_params['historytable'] . ' WHERE page_name = ? and page_version = ?', $values); } catch (Horde_Db_Exception $e) { throw new Wicked_Exception($e); } return; } /* We're deleting the current version. Have to promote the next-most * revision from the history table. */ try { $query = 'SELECT * FROM ' . $this->_params['historytable'] . ' WHERE page_name = ? ORDER BY page_version DESC'; $query = $this->_db->addLimitOffset($query, array('limit' => 1)); $revision = $this->_db->selectOne($query, array($this->_convertToDriver($pagename))); /* Replace the current version of the page with the version being * promoted. */ $this->_db->beginDbTransaction(); $this->_db->update('UPDATE ' . $this->_params['table'] . ' SET' . ' page_text = ?, page_version = ?,' . ' version_created = ?, change_author = ?, change_log = ?' . ' WHERE page_name = ?', array($revision['page_text'], (int) $revision['page_version'], (int) $revision['version_created'], $revision['change_author'], $revision['change_log'], $this->_convertToDriver($pagename))); /* Finally, remove the version that we promoted from the history * table. */ $this->_db->delete('DELETE FROM ' . $this->_params['historytable'] . ' WHERE page_name = ? and page_version = ?', array($this->_convertToDriver($pagename), (int) $revision['page_version'])); $this->_db->commitDbTransaction(); } catch (Horde_Db_Exception $e) { $this->_db->rollbackDbTransaction(); throw new Wicked_Exception($e); } }
/** * Logs an event to an item's history log. Any other details about the * event are passed in $attributes. * * @param Horde_History_Log $history The history item to add to. * @param array $attributes The hash of name => value * entries that describe this * event. * @param boolean $replaceAction If $attributes['action'] is * already present in the item's * history log, update that entry * instead of creating a new one. * * @throws Horde_History_Exception */ protected function _log(Horde_History_Log $history, array $attributes, $replaceAction = false) { /* If we want to replace an entry with the same action, try and find * one. Track whether or not we succeed in $done, so we know whether or * not to add the entry later. */ $done = false; if ($replaceAction && !empty($attributes['action'])) { foreach ($history as $entry) { if (!empty($entry['action']) && $entry['action'] == $attributes['action']) { $values = array($attributes['ts'], $attributes['who'], isset($attributes['desc']) ? $attributes['desc'] : null); unset($attributes['ts'], $attributes['who'], $attributes['desc'], $attributes['action']); $values[] = $attributes ? serialize($attributes) : null; $values[] = $this->_nextModSeq(); $values[] = $entry['id']; try { $this->_db->update('UPDATE horde_histories SET history_ts = ?,' . ' history_who = ?,' . ' history_desc = ?,' . ' history_extra = ?,' . ' history_modseq = ? WHERE history_id = ?', $values); } catch (Horde_Db_Exception $e) { throw new Horde_History_Exception($e); } $done = true; break; } } } /* If we're not replacing by action, or if we didn't find an entry to * replace, insert a new row. */ if (!$done) { $values = array($history->uid, $attributes['ts'], $attributes['who'], isset($attributes['desc']) ? $attributes['desc'] : null, isset($attributes['action']) ? $attributes['action'] : null, $this->_nextModSeq()); unset($attributes['ts'], $attributes['who'], $attributes['desc'], $attributes['action']); $values[] = $attributes ? serialize($attributes) : null; try { $this->_db->insert('INSERT INTO horde_histories (object_uid, history_ts, history_who, history_desc, history_action, history_modseq, history_extra)' . ' VALUES (?, ?, ?, ?, ?, ?, ?)', $values); } catch (Horde_Db_Exception $e) { throw new Horde_History_Exception($e); } } }
/** * Reset a user's password. Used for example when the user does not * remember the existing password. * * @param string $userId The user id for which to reset the password. * * @return string The new password on success. * @throws Horde_Auth_Exception */ public function resetPassword($userId) { /* Get a new random password. */ $password = Horde_Auth::genRandomPassword(); /* Build the SQL query. */ $query = sprintf('UPDATE %s SET %s = ?', $this->_params['table'], $this->_params['password_field']); $values = array(Horde_Auth::getCryptedPassword($password, '', $this->_params['encryption'], $this->_params['show_encryption'])); if (!empty($this->_params['soft_expiration_field'])) { $query .= ', ' . $this->_params['soft_expiration_field'] . ' = ?'; $values[] = $this->_calc_expiration('soft'); } if (!empty($this->_params['hard_expiration_field'])) { $query .= ', ' . $this->_params['hard_expiration_field'] . ' = ?'; $values[] = $this->_calc_expiration('hard'); } $query .= sprintf(' WHERE %s = ?', $this->_params['username_field']); $values[] = $userId; try { $this->_db->update($query, $values); } catch (Horde_Db_Exception $e) { throw new Horde_Auth_Exception($e); } return $password; }
/** * * @param array $row Hash of the note data, db keys. * @param string $passphrase The encryption passphrase. * * @return array a Task hash. * @throws Mnemo_Exception */ protected function _buildNote($row, $passphrase = null) { // Make sure notes always have a UID. if (empty($row['memo_uid'])) { $row['memo_uid'] = strval(new Horde_Support_Guid()); $query = 'UPDATE ' . $this->_table . ' SET memo_uid = ?' . ' WHERE memo_owner = ? AND memo_id = ?'; $values = array($row['memo_uid'], $row['memo_owner'], $row['memo_id']); try { $this->_db->update($query, $values); } catch (Horde_Db_Exception $e) { throw new Mnemo_Exception($e->getMessage()); } } // Decrypt note if requested. $encrypted = false; $body = $this->_column->binaryToString($row['memo_body']); $body = Horde_String::convertCharset($body, $this->_charset, 'UTF-8'); if (strpos($body, '-----BEGIN PGP MESSAGE-----') === 0) { $encrypted = true; if (empty($passphrase)) { $passphrase = Mnemo::getPassphrase($row['memo_id']); } if (empty($passphrase)) { $body = new Mnemo_Exception(_("This note has been encrypted."), Mnemo::ERR_NO_PASSPHRASE); } else { try { $body = $this->_decrypt($body, $passphrase); $body = $body->message; } catch (Mnemo_Exception $e) { $body = $e; } Mnemo::storePassphrase($row['memo_id'], $passphrase); } } // Create a new note based on $row's values. $uid = Horde_String::convertCharset($row['memo_uid'], $this->_charset, 'UTF-8'); $memo = array('memolist_id' => $row['memo_owner'], 'memo_id' => $row['memo_id'], 'uid' => $uid, 'desc' => Horde_String::convertCharset($row['memo_desc'], $this->_charset, 'UTF-8'), 'body' => $body, 'tags' => $GLOBALS['injector']->getInstance('Mnemo_Tagger')->getTags($uid, 'note'), 'encrypted' => $encrypted); try { $userId = $GLOBALS['registry']->getAuth(); $log = $GLOBALS['injector']->getInstance('Horde_History')->getHistory('mnemo:' . $row['memo_owner'] . ':' . $row['memo_uid']); foreach ($log as $entry) { switch ($entry['action']) { case 'add': $memo['created'] = new Horde_Date($entry['ts']); if ($userId != $entry['who']) { $memo['createdby'] = sprintf(_("by %s"), Mnemo::getUserName($entry['who'])); } else { $memo['createdby'] = _("by me"); } break; case 'modify': $memo['modified'] = new Horde_Date($entry['ts']); if ($userId != $entry['who']) { $memo['modifiedby'] = sprintf(_("by %s"), Mnemo::getUserName($entry['who'])); } else { $memo['modifiedby'] = _("by me"); } break; } } } catch (Horde_Exception $e) { } return $memo; }
/** * Return an array describing this task from the provided backend data. * * @param array $row The backend data * @param boolean $include_history Include history data. * * @return array The task data. */ protected function _buildTask($row, $include_history = true) { // Make sure tasks always have a UID. if (empty($row['task_uid'])) { $row['task_uid'] = strval(new Horde_Support_Guid()); $query = 'UPDATE ' . $this->_params['table'] . ' SET task_uid = ?' . ' WHERE task_owner = ? AND task_id = ?'; $values = array($row['task_uid'], $row['task_owner'], $row['task_id']); try { $this->_db->update($query, $values); } catch (Horde_Db_Exception $e) { } } if (!$row['task_due'] || !$row['task_recurtype']) { $recurrence = null; } else { $recurrence = new Horde_Date_Recurrence($row['task_due']); $recurrence->setRecurType((int) $row['task_recurtype']); $recurrence->setRecurInterval((int) $row['task_recurinterval']); if (isset($row['task_recurenddate']) && $row['task_recurenddate'] != '9999-12-31 23:59:59') { $recur_end = new Horde_Date($row['task_recurenddate'], 'UTC'); $recur_end->setTimezone(date_default_timezone_get()); $recurrence->setRecurEnd($recur_end); } if (isset($row['task_recurcount'])) { $recurrence->setRecurCount((int) $row['task_recurcount']); } if (isset($row['task_recurdays'])) { $recurrence->recurData = (int) $row['task_recurdays']; } if (!empty($row['task_exceptions'])) { $recurrence->exceptions = explode(',', $row['task_exceptions']); } if (!empty($row['task_completions'])) { $recurrence->completions = explode(',', $row['task_completions']); } } /* Create a new task based on $row's values. */ $task = array('tasklist_id' => $row['task_owner'], 'task_id' => $row['task_id'], 'uid' => Horde_String::convertCharset($row['task_uid'], $this->_params['charset'], 'UTF-8'), 'parent' => $row['task_parent'], 'owner' => $row['task_creator'], 'assignee' => $row['task_assignee'], 'name' => Horde_String::convertCharset($row['task_name'], $this->_params['charset'], 'UTF-8'), 'desc' => Horde_String::convertCharset($row['task_desc'], $this->_params['charset'], 'UTF-8'), 'start' => $row['task_start'], 'due' => $row['task_due'], 'priority' => $row['task_priority'], 'estimate' => (double) $row['task_estimate'], 'completed' => $row['task_completed'], 'completed_date' => isset($row['task_completed_date']) ? $row['task_completed_date'] : null, 'alarm' => $row['task_alarm'], 'methods' => Horde_String::convertCharset(@unserialize($row['task_alarm_methods']), $this->_params['charset'], 'UTF-8'), 'private' => $row['task_private'], 'recurrence' => $recurrence); if ($include_history) { try { $userId = $GLOBALS['registry']->getAuth(); $log = $GLOBALS['injector']->getInstance('Horde_History')->getHistory('nag:' . $row['task_owner'] . ':' . $row['task_uid']); foreach ($log as $entry) { switch ($entry['action']) { case 'add': $task['created'] = new Horde_Date($entry['ts']); if ($userId != $entry['who']) { $task['createdby'] = sprintf(_("by %s"), Nag::getUserName($entry['who'])); } else { $task['createdby'] = _("by me"); } break; case 'modify': $task['modified'] = new Horde_Date($entry['ts']); if ($userId != $entry['who']) { $task['modifiedby'] = sprintf(_("by %s"), Nag::getUserName($entry['who'])); } else { $task['modifiedby'] = _("by me"); } break; } } } catch (Horde_Exception $e) { } } return $task; }
/** * Stores user preferences and default values in the backend. * * @param boolean $defaults Whether to store the global defaults instead * of user options. Unused. * * @throws Sam_Exception */ public function store($defaults = false) { /* Check if the policy already exists. */ $policyID = $this->_lookupPolicyID(); /* Delete existing policy. */ if ($policyID !== false) { try { $this->_db->delete(sprintf('DELETE FROM %s WHERE %s = ?', $this->_mapNameToTable('policies'), $this->_mapAttributeToField('policies', 'name')), array($this->_user)); } catch (Horde_Db_Exception $e) { throw new Sam_Exception($e); } } /* Insert new policy (everything but whitelists and blacklists). */ $insertKeys = $insertVals = array(); foreach ($this->_options as $attribute => $value) { if ($attribute != 'whitelist_from' && $attribute != 'blacklist_from') { $insertKeys[] = $this->_mapAttributeToField('policies', $attribute); $insertVals[] = strlen($value) ? $value : null; } } if (count($insertKeys)) { try { $this->_db->insert(sprintf('INSERT INTO %s (%s, %s) VALUES (%s)', $this->_mapNameToTable('policies'), $this->_mapAttributeToField('policies', 'name'), implode(', ', $insertKeys), implode(', ', array_fill(0, count($insertVals) + 1, '?'))), array_merge(array($this->_user), $insertVals)); } catch (Horde_Db_Exception $e) { throw new Sam_Exception($e); } } /* Get the new policy id for the recipients table. */ $policyID = $this->_lookupPolicyID(); /* Update recipients with new policy id. */ try { $this->_db->update(sprintf('UPDATE %s SET %s = ? WHERE %s = ?', $this->_mapNameToTable('recipients'), $this->_mapAttributeToField('recipients', 'policy_id'), $this->_mapAttributeToField('recipients', 'email')), array($policyID, $this->_user)); } catch (Horde_Db_Exception $e) { throw new Sam_Exception($e); } /* Find the user id. */ $userID = $this->_lookupUserID(); /* Query for whitelists and blacklists. */ try { $result = $this->_db->select(sprintf('SELECT %s, %s FROM %s WHERE %s = ?', $this->_mapAttributeToField('wblists', 'sender'), $this->_mapAttributeToField('wblists', 'type'), $this->_mapNameToTable('wblists'), $this->_mapAttributeToField('wblists', 'recipient')), array($userID)); } catch (Horde_Db_Exception $e) { throw new Sam_Exception($e); } /* Loop through results, retrieving whitelists and blacklists. */ $existing = array('whitelist_from' => array(), 'blacklist_from' => array()); foreach ($result as $row) { $type = $row[$this->_mapAttributeToField('wblists', 'type')]; $senderID = $row[$this->_mapAttributeToField('wblists', 'sender')]; /* Only proceed if sender is listed white or black. */ if (preg_match('/[WYBN]/i', $type)) { try { $sender = $this->_db->selectValue(sprintf('SELECT %s FROM %s WHERE %s = ?', $this->_mapAttributeToField('senders', 'email'), $this->_mapNameToTable('senders'), $this->_mapAttributeToField('senders', 'id')), array($senderID)); } catch (Horde_Db_Exception $e) { throw new Sam_Exception($e); } $list = preg_match('/[WY]/i', $type) ? 'whitelist_from' : 'blacklist_from'; if (isset($this->_options[$list]) && in_array($sender, $this->_options[$list])) { $existing[$list][] = $sender; } else { /* User removed an address from a list. */ try { $this->_db->delete(sprintf('DELETE FROM %s WHERE %s = ? AND %s = ?', $this->_mapNameToTable('wblists'), $this->_mapAttributeToField('wblists', 'sender'), $this->_mapAttributeToField('wblists', 'recipient')), array($senderID, $userID)); } catch (Horde_Db_Exception $e) { throw new Sam_Exception($e); } /* Check if there is anyone else using this sender * address. */ $query = sprintf('SELECT 1 FROM %s WHERE %s = ?', $this->_mapNameToTable('wblists'), $this->_mapAttributeToField('wblists', 'sender')); if (!$this->_db->selectValue($query, array($senderID))) { /* No one else needs this sender address, delete it * from senders table. */ try { $this->_db->delete(sprintf('DELETE FROM %s WHERE %s = ?', $this->_mapNameToTable('senders'), $this->_mapAttributeToField('senders', 'id')), array($senderID)); } catch (Horde_Db_Exception $e) { throw new Sam_Exception($e); } } } } } /* Check any additions to the lists. */ foreach (array('whitelist_from' => 'W', 'blacklist_from' => 'B') as $list => $type) { if (!isset($this->_options[$list])) { continue; } foreach ($this->_options[$list] as $sender) { if (in_array($sender, $existing[$list])) { continue; } /* Check if this sender address exists already. */ $wb_result = $this->_db->selectValue(sprintf('SELECT %s FROM %s WHERE %s = ?', $this->_mapAttributeToField('senders', 'id'), $this->_mapNameToTable('senders'), $this->_mapAttributeToField('senders', 'email')), array($sender)); if ($wb_result !== false) { /* Address exists, use it's ID */ $senderID = $wb_result; } else { /* Address doesn't exist, add it. */ try { $this->_db->insert(sprintf('INSERT INTO %s (%s) VALUES (?)', $this->_mapNameToTable('senders'), $this->_mapAttributeToField('senders', 'email')), array($sender)); } catch (Horde_Db_Exception $e) { throw new Sam_Exception($e); } try { $senderID = $this->_db->selectValue(sprintf('SELECT %s FROM %s WHERE %s = ?', $this->_mapAttributeToField('senders', 'id'), $this->_mapNameToTable('senders'), $this->_mapAttributeToField('senders', 'email')), array($sender)); } catch (Horde_Db_Exception $e) { throw new Sam_Exception($e); } } try { $this->_db->insert(sprintf('INSERT INTO %s (%s, %s, %s) VALUES (?, ?, ?)', $this->_mapNameToTable('wblists'), $this->_mapAttributeToField('wblists', 'recipient'), $this->_mapAttributeToField('wblists', 'sender'), $this->_mapAttributeToField('wblists', 'type')), array($userID, $senderID, $type)); } catch (Horde_Db_Exception $e) { throw new Sam_Exception($e); } } } /* Remove any disjoined sender IDs. */ try { $this->_db->delete(sprintf('DELETE FROM %s WHERE %s = ?', $this->_mapNameToTable('wblists'), $this->_mapAttributeToField('wblists', 'recipient')), array('')); } catch (Horde_Db_Exception $e) { throw new Sam_Exception($e); } }