summaryrefslogtreecommitdiff
path: root/classes
diff options
context:
space:
mode:
Diffstat (limited to 'classes')
-rwxr-xr-xclasses/Conversation.php3
-rw-r--r--classes/Fave.php14
-rw-r--r--classes/File.php51
-rw-r--r--classes/Foreign_user.php16
-rw-r--r--classes/Group_member.php3
-rw-r--r--classes/Inbox.php48
-rw-r--r--classes/Local_group.php1
-rw-r--r--classes/Login_token.php2
-rw-r--r--classes/Memcached_DataObject.php119
-rw-r--r--classes/Message.php3
-rw-r--r--classes/Notice.php584
-rw-r--r--classes/Profile.php148
-rw-r--r--classes/Queue_item.php13
-rw-r--r--classes/Remote_profile.php3
-rw-r--r--classes/Reply.php14
-rw-r--r--classes/Safe_DataObject.php95
-rw-r--r--classes/Status_network.php118
-rw-r--r--classes/Status_network_tag.php69
-rw-r--r--classes/Subscription.php23
-rw-r--r--classes/User.php32
-rw-r--r--classes/User_group.php20
-rw-r--r--classes/status_network.ini15
22 files changed, 1136 insertions, 258 deletions
diff --git a/classes/Conversation.php b/classes/Conversation.php
index ea8bd87b5..f540004ef 100755
--- a/classes/Conversation.php
+++ b/classes/Conversation.php
@@ -63,7 +63,8 @@ class Conversation extends Memcached_DataObject
}
$orig = clone($conv);
- $orig->uri = common_local_url('conversation', array('id' => $id));
+ $orig->uri = common_local_url('conversation', array('id' => $id),
+ null, null, false);
$result = $orig->update($conv);
if (empty($result)) {
diff --git a/classes/Fave.php b/classes/Fave.php
index a04f15e9c..ed4f56aee 100644
--- a/classes/Fave.php
+++ b/classes/Fave.php
@@ -21,7 +21,15 @@ class Fave extends Memcached_DataObject
/* the code above is auto generated do not remove the tag below */
###END_AUTOCODE
- static function addNew($profile, $notice) {
+ /**
+ * Save a favorite record.
+ * @fixme post-author notification should be moved here
+ *
+ * @param Profile $profile the local or remote user who likes
+ * @param Notice $notice the notice that is liked
+ * @return mixed false on failure, or Fave record on success
+ */
+ static function addNew(Profile $profile, Notice $notice) {
$fave = null;
@@ -67,13 +75,13 @@ class Fave extends Memcached_DataObject
return Memcached_DataObject::pkeyGet('Fave', $kv);
}
- function stream($user_id, $offset=0, $limit=NOTICES_PER_PAGE, $own=false)
+ function stream($user_id, $offset=0, $limit=NOTICES_PER_PAGE, $own=false, $since_id=0, $max_id=0)
{
$ids = Notice::stream(array('Fave', '_streamDirect'),
array($user_id, $own),
($own) ? 'fave:ids_by_user_own:'.$user_id :
'fave:ids_by_user:'.$user_id,
- $offset, $limit);
+ $offset, $limit, $since_id, $max_id);
return $ids;
}
diff --git a/classes/File.php b/classes/File.php
index 33273bbdc..407fd3211 100644
--- a/classes/File.php
+++ b/classes/File.php
@@ -116,7 +116,11 @@ class File extends Memcached_DataObject
return false;
}
- function processNew($given_url, $notice_id=null) {
+ /**
+ * @fixme refactor this mess, it's gotten pretty scary.
+ * @param bool $followRedirects
+ */
+ function processNew($given_url, $notice_id=null, $followRedirects=true) {
if (empty($given_url)) return -1; // error, no url to process
$given_url = File_redirection::_canonUrl($given_url);
if (empty($given_url)) return -1; // error, no url to process
@@ -124,6 +128,10 @@ class File extends Memcached_DataObject
if (empty($file)) {
$file_redir = File_redirection::staticGet('url', $given_url);
if (empty($file_redir)) {
+ // @fixme for new URLs this also looks up non-redirect data
+ // such as target content type, size, etc, which we need
+ // for File::saveNew(); so we call it even if not following
+ // new redirects.
$redir_data = File_redirection::where($given_url);
if (is_array($redir_data)) {
$redir_url = $redir_data['url'];
@@ -131,14 +139,23 @@ class File extends Memcached_DataObject
$redir_url = $redir_data;
$redir_data = array();
} else {
- throw new ServerException("Can't process url '$given_url'");
+ // TRANS: Server exception thrown when a URL cannot be processed.
+ throw new ServerException(sprintf(_("Cannot process URL '%s'"), $given_url));
}
// TODO: max field length
- if ($redir_url === $given_url || strlen($redir_url) > 255) {
+ if ($redir_url === $given_url || strlen($redir_url) > 255 || !$followRedirects) {
$x = File::saveNew($redir_data, $given_url);
$file_id = $x->id;
} else {
- $x = File::processNew($redir_url, $notice_id);
+ // This seems kind of messed up... for now skipping this part
+ // if we're already under a redirect, so we don't go into
+ // horrible infinite loops if we've been given an unstable
+ // redirect (where the final destination of the first request
+ // doesn't match what we get when we ask for it again).
+ //
+ // Seen in the wild with clojure.org, which redirects through
+ // wikispaces for auth and appends session data in the URL params.
+ $x = File::processNew($redir_url, $notice_id, /*followRedirects*/false);
$file_id = $x->id;
File_redirection::saveNew($redir_data, $file_id, $given_url);
}
@@ -153,7 +170,9 @@ class File extends Memcached_DataObject
if (empty($x)) {
$x = File::staticGet($file_id);
if (empty($x)) {
- throw new ServerException("Robin thinks something is impossible.");
+ // FIXME: This could possibly be a clearer message :)
+ // TRANS: Server exception thrown when... Robin thinks something is impossible!
+ throw new ServerException(_("Robin thinks something is impossible."));
}
}
@@ -166,8 +185,10 @@ class File extends Memcached_DataObject
function isRespectsQuota($user,$fileSize) {
if ($fileSize > common_config('attachments', 'file_quota')) {
- return sprintf(_('No file may be larger than %d bytes ' .
- 'and the file you sent was %d bytes. Try to upload a smaller version.'),
+ // TRANS: Message given if an upload is larger than the configured maximum.
+ // TRANS: %1$d is the byte limit for uploads, %2$d is the byte count for the uploaded file.
+ return sprintf(_('No file may be larger than %1$d bytes ' .
+ 'and the file you sent was %2$d bytes. Try to upload a smaller version.'),
common_config('attachments', 'file_quota'), $fileSize);
}
@@ -176,6 +197,8 @@ class File extends Memcached_DataObject
$this->fetch();
$total = $this->total + $fileSize;
if ($total > common_config('attachments', 'user_quota')) {
+ // TRANS: Message given if an upload would exceed user quota.
+ // TRANS: %d (number) is the user quota in bytes.
return sprintf(_('A file this large would exceed your user quota of %d bytes.'), common_config('attachments', 'user_quota'));
}
$query .= ' AND EXTRACT(month FROM file.modified) = EXTRACT(month FROM now()) and EXTRACT(year FROM file.modified) = EXTRACT(year FROM now())';
@@ -183,6 +206,8 @@ class File extends Memcached_DataObject
$this->fetch();
$total = $this->total + $fileSize;
if ($total > common_config('attachments', 'monthly_quota')) {
+ // TRANS: Message given id an upload would exceed a user's monthly quota.
+ // TRANS: $d (number) is the monthly user quota in bytes.
return sprintf(_('A file this large would exceed your monthly quota of %d bytes.'), common_config('attachments', 'monthly_quota'));
}
return true;
@@ -219,7 +244,8 @@ class File extends Memcached_DataObject
static function path($filename)
{
if (!self::validFilename($filename)) {
- throw new ClientException("Invalid filename");
+ // TRANS: Client exception thrown if a file upload does not have a valid name.
+ throw new ClientException(_("Invalid filename."));
}
$dir = common_config('attachments', 'dir');
@@ -233,7 +259,8 @@ class File extends Memcached_DataObject
static function url($filename)
{
if (!self::validFilename($filename)) {
- throw new ClientException("Invalid filename");
+ // TRANS: Client exception thrown if a file upload does not have a valid name.
+ throw new ClientException(_("Invalid filename."));
}
if(common_config('site','private')) {
@@ -286,7 +313,10 @@ class File extends Memcached_DataObject
if(! isset($this->filename)){
$notEnclosureMimeTypes = array(null,'text/html','application/xhtml+xml');
- $mimetype = strtolower($this->mimetype);
+ $mimetype = $this->mimetype;
+ if($mimetype != null){
+ $mimetype = strtolower($this->mimetype);
+ }
$semicolon = strpos($mimetype,';');
if($semicolon){
$mimetype = substr($mimetype,0,$semicolon);
@@ -323,4 +353,3 @@ class File extends Memcached_DataObject
return !empty($enclosure);
}
}
-
diff --git a/classes/Foreign_user.php b/classes/Foreign_user.php
index 0dd94ffb9..e98a16064 100644
--- a/classes/Foreign_user.php
+++ b/classes/Foreign_user.php
@@ -39,6 +39,22 @@ class Foreign_user extends Memcached_DataObject
return null;
}
+ static function getByNickname($nickname, $service)
+ {
+ if (empty($nickname) || empty($service)) {
+ return null;
+ } else {
+ $fuser = new Foreign_user();
+ $fuser->service = $service;
+ $fuser->nickname = $nickname;
+ $fuser->limit(1);
+
+ $result = $fuser->find(true);
+
+ return empty($result) ? null : $fuser;
+ }
+ }
+
function updateKeys(&$orig)
{
$this->_connect();
diff --git a/classes/Group_member.php b/classes/Group_member.php
index 7b1760f76..2239461be 100644
--- a/classes/Group_member.php
+++ b/classes/Group_member.php
@@ -38,6 +38,7 @@ class Group_member extends Memcached_DataObject
if (!$result) {
common_log_db_error($member, 'INSERT', __FILE__);
+ // TRANS: Exception thrown when joining a group fails.
throw new Exception(_("Group join failed."));
}
@@ -50,6 +51,7 @@ class Group_member extends Memcached_DataObject
'profile_id' => $profile_id));
if (empty($member)) {
+ // TRANS: Exception thrown when trying to leave a group the user is not a member of.
throw new Exception(_("Not part of group."));
}
@@ -57,6 +59,7 @@ class Group_member extends Memcached_DataObject
if (!$result) {
common_log_db_error($member, 'INSERT', __FILE__);
+ // TRANS: Exception thrown when trying to leave a group fails.
throw new Exception(_("Group leave failed."));
}
diff --git a/classes/Inbox.php b/classes/Inbox.php
index 014ba3d82..430419ba5 100644
--- a/classes/Inbox.php
+++ b/classes/Inbox.php
@@ -96,17 +96,31 @@ class Inbox extends Memcached_DataObject
$inbox = new Inbox();
$inbox->user_id = $user_id;
- $inbox->notice_ids = call_user_func_array('pack', array_merge(array('N*'), $ids));
+ $inbox->pack($ids);
$inbox->fake = true;
return $inbox;
}
+ /**
+ * Append the given notice to the given user's inbox.
+ * Caching updates are managed for the inbox itself.
+ *
+ * If the notice is already in this inbox, the second
+ * add will be silently dropped.
+ *
+ * @param int @user_id
+ * @param int $notice_id
+ * @return boolean success
+ */
static function insertNotice($user_id, $notice_id)
{
- $inbox = DB_DataObject::staticGet('inbox', 'user_id', $user_id);
-
- if (empty($inbox)) {
+ // Going straight to the DB rather than trusting our caching
+ // during an update. Note: not using DB_DataObject::staticGet,
+ // which is unsafe to use directly (in-process caching causes
+ // memory leaks, which accumulate in queue processes).
+ $inbox = new Inbox();
+ if (!$inbox->get('user_id', $user_id)) {
$inbox = Inbox::initialize($user_id);
}
@@ -114,6 +128,13 @@ class Inbox extends Memcached_DataObject
return false;
}
+ $ids = $inbox->unpack();
+ if (in_array(intval($notice_id), $ids)) {
+ // Already in there, we probably re-ran some inbox adds
+ // due to an error. Skip the dupe silently.
+ return true;
+ }
+
$result = $inbox->query(sprintf('UPDATE inbox '.
'set notice_ids = concat(cast(0x%08x as binary(4)), '.
'substr(notice_ids, 1, %d)) '.
@@ -150,7 +171,7 @@ class Inbox extends Memcached_DataObject
}
}
- $ids = unpack('N*', $inbox->notice_ids);
+ $ids = $inbox->unpack();
if (!empty($since_id)) {
$newids = array();
@@ -229,4 +250,21 @@ class Inbox extends Memcached_DataObject
}
return new ArrayWrapper($items);
}
+
+ /**
+ * Saves a list of integer notice_ids into a packed blob in this object.
+ * @param array $ids list of integer notice_ids
+ */
+ protected function pack(array $ids)
+ {
+ $this->notice_ids = call_user_func_array('pack', array_merge(array('N*'), $ids));
+ }
+
+ /**
+ * @return array of integer notice_ids
+ */
+ protected function unpack()
+ {
+ return unpack('N*', $this->notice_ids);
+ }
}
diff --git a/classes/Local_group.php b/classes/Local_group.php
index 42312ec63..ccd0125cf 100644
--- a/classes/Local_group.php
+++ b/classes/Local_group.php
@@ -38,6 +38,7 @@ class Local_group extends Memcached_DataObject
$this->encache();
} else {
common_log_db_error($local, 'UPDATE', __FILE__);
+ // TRANS: Server exception thrown when updating a local group fails.
throw new ServerException(_('Could not update local group.'));
}
diff --git a/classes/Login_token.php b/classes/Login_token.php
index 51dc61262..20d5d9dbc 100644
--- a/classes/Login_token.php
+++ b/classes/Login_token.php
@@ -73,6 +73,8 @@ class Login_token extends Memcached_DataObject
if (!$result) {
common_log_db_error($login_token, 'INSERT', __FILE__);
+ // TRANS: Exception thrown when trying creating a login token failed.
+ // TRANS: %s is the user nickname for which token creation failed.
throw new Exception(sprintf(_('Could not create login token for %s'),
$user->nickname));
}
diff --git a/classes/Memcached_DataObject.php b/classes/Memcached_DataObject.php
index bc4c3a000..0f1ed0489 100644
--- a/classes/Memcached_DataObject.php
+++ b/classes/Memcached_DataObject.php
@@ -128,12 +128,13 @@ class Memcached_DataObject extends Safe_DataObject
}
static function cacheKey($cls, $k, $v) {
- if (is_object($cls) || is_object($k) || is_object($v)) {
+ if (is_object($cls) || is_object($k) || (is_object($v) && !($v instanceof DB_DataObject_Cast))) {
$e = new Exception();
common_log(LOG_ERR, __METHOD__ . ' object in param: ' .
str_replace("\n", " ", $e->getTraceAsString()));
}
- return common_cache_key(strtolower($cls).':'.$k.':'.$v);
+ $vstr = self::valueString($v);
+ return common_cache_key(strtolower($cls).':'.$k.':'.$vstr);
}
static function getcached($cls, $k, $v) {
@@ -229,11 +230,12 @@ class Memcached_DataObject extends Safe_DataObject
if (empty($this->$key)) {
continue;
}
- $ckeys[] = $this->cacheKey($this->tableName(), $key, $this->$key);
+ $ckeys[] = $this->cacheKey($this->tableName(), $key, self::valueString($this->$key));
} else if ($type == 'K' || $type == 'N') {
$pkey[] = $key;
- $pval[] = $this->$key;
+ $pval[] = self::valueString($this->$key);
} else {
+ // Low level exception. No need for i18n as discussed with Brion.
throw new Exception("Unknown key type $key => $type for " . $this->tableName());
}
}
@@ -281,6 +283,7 @@ class Memcached_DataObject extends Safe_DataObject
} else if ($type == 'fulltext') {
$search_engine = new MySQLSearch($this, $table);
} else {
+ // Low level exception. No need for i18n as discussed with Brion.
throw new ServerException('Unknown search type: ' . $type);
}
} else {
@@ -330,6 +333,10 @@ class Memcached_DataObject extends Safe_DataObject
*/
function _query($string)
{
+ if (common_config('db', 'annotate_queries')) {
+ $string = $this->annotateQuery($string);
+ }
+
$start = microtime(true);
$result = parent::_query($string);
$delta = microtime(true) - $start;
@@ -342,6 +349,70 @@ class Memcached_DataObject extends Safe_DataObject
return $result;
}
+ /**
+ * Find the first caller in the stack trace that's not a
+ * low-level database function and add a comment to the
+ * query string. This should then be visible in process lists
+ * and slow query logs, to help identify problem areas.
+ *
+ * Also marks whether this was a web GET/POST or which daemon
+ * was running it.
+ *
+ * @param string $string SQL query string
+ * @return string SQL query string, with a comment in it
+ */
+ function annotateQuery($string)
+ {
+ $ignore = array('annotateQuery',
+ '_query',
+ 'query',
+ 'get',
+ 'insert',
+ 'delete',
+ 'update',
+ 'find');
+ $ignoreStatic = array('staticGet',
+ 'pkeyGet',
+ 'cachedQuery');
+ $here = get_class($this); // if we get confused
+ $bt = debug_backtrace();
+
+ // Find the first caller that's not us?
+ foreach ($bt as $frame) {
+ $func = $frame['function'];
+ if (isset($frame['type']) && $frame['type'] == '::') {
+ if (in_array($func, $ignoreStatic)) {
+ continue;
+ }
+ $here = $frame['class'] . '::' . $func;
+ break;
+ } else if (isset($frame['type']) && $frame['type'] == '->') {
+ if ($frame['object'] === $this && in_array($func, $ignore)) {
+ continue;
+ }
+ if (in_array($func, $ignoreStatic)) {
+ continue; // @fixme this shouldn't be needed?
+ }
+ $here = get_class($frame['object']) . '->' . $func;
+ break;
+ }
+ $here = $func;
+ break;
+ }
+
+ if (php_sapi_name() == 'cli') {
+ $context = basename($_SERVER['PHP_SELF']);
+ } else {
+ $context = $_SERVER['REQUEST_METHOD'];
+ }
+
+ // Slip the comment in after the first command,
+ // or DB_DataObject gets confused about handling inserts and such.
+ $parts = explode(' ', $string, 2);
+ $parts[0] .= " /* $context $here */";
+ return implode(' ', $parts);
+ }
+
// Sanitize a query for logging
// @fixme don't trim spaces in string literals
function sanitizeQuery($string)
@@ -458,7 +529,8 @@ class Memcached_DataObject extends Safe_DataObject
}
if (!$dsn) {
- throw new Exception("No database name / dsn found anywhere");
+ // TRANS: Exception thrown when database name or Data Source Name could not be found.
+ throw new Exception(_("No database name or DSN found anywhere."));
}
return $dsn;
@@ -502,9 +574,13 @@ class Memcached_DataObject extends Safe_DataObject
function raiseError($message, $type = null, $behaviour = null)
{
$id = get_class($this);
- if ($this->id) {
+ if (!empty($this->id)) {
$id .= ':' . $this->id;
}
+ if ($message instanceof PEAR_Error) {
+ $message = $message->getMessage();
+ }
+ // Low level exception. No need for i18n as discussed with Brion.
throw new ServerException("[$id] DB_DataObject error [$type]: $message");
}
@@ -521,7 +597,7 @@ class Memcached_DataObject extends Safe_DataObject
return $c->get($cacheKey);
}
- static function cacheSet($keyPart, $value)
+ static function cacheSet($keyPart, $value, $flag=null, $expiry=null)
{
$c = self::memcache();
@@ -531,7 +607,34 @@ class Memcached_DataObject extends Safe_DataObject
$cacheKey = common_cache_key($keyPart);
- return $c->set($cacheKey, $value);
+ return $c->set($cacheKey, $value, $flag, $expiry);
+ }
+
+ static function valueString($v)
+ {
+ $vstr = null;
+ if (is_object($v) && $v instanceof DB_DataObject_Cast) {
+ switch ($v->type) {
+ case 'date':
+ $vstr = $v->year . '-' . $v->month . '-' . $v->day;
+ break;
+ case 'blob':
+ case 'string':
+ case 'sql':
+ case 'datetime':
+ case 'time':
+ // Low level exception. No need for i18n as discussed with Brion.
+ throw new ServerException("Unhandled DB_DataObject_Cast type passed as cacheKey value: '$v->type'");
+ break;
+ default:
+ // Low level exception. No need for i18n as discussed with Brion.
+ throw new ServerException("Unknown DB_DataObject_Cast type passed as cacheKey value: '$v->type'");
+ break;
+ }
+ } else {
+ $vstr = strval($v);
+ }
+ return $vstr;
}
}
diff --git a/classes/Message.php b/classes/Message.php
index 16d0c60b3..fa0c5b318 100644
--- a/classes/Message.php
+++ b/classes/Message.php
@@ -42,6 +42,7 @@ class Message extends Memcached_DataObject
$sender = Profile::staticGet('id', $from);
if (!$sender->hasRight(Right::NEWMESSAGE)) {
+ // TRANS: Client exception thrown when a user tries to send a direct message while being banned from sending them.
throw new ClientException(_('You are banned from sending direct messages.'));
}
@@ -58,6 +59,7 @@ class Message extends Memcached_DataObject
if (!$result) {
common_log_db_error($msg, 'INSERT', __FILE__);
+ // TRANS: Message given when a message could not be stored on the server.
return _('Could not insert message.');
}
@@ -68,6 +70,7 @@ class Message extends Memcached_DataObject
if (!$result) {
common_log_db_error($msg, 'UPDATE', __FILE__);
+ // TRANS: Message given when a message could not be updated on the server.
return _('Could not update message with new URI.');
}
diff --git a/classes/Notice.php b/classes/Notice.php
index f7194e339..0eeebfadf 100644
--- a/classes/Notice.php
+++ b/classes/Notice.php
@@ -29,6 +29,7 @@
* @author Robin Millette <millette@controlyourself.ca>
* @author Sarven Capadisli <csarven@controlyourself.ca>
* @author Tom Adams <tom@holizz.com>
+ * @copyright 2009 Free Software Foundation, Inc http://www.fsf.org
* @license GNU Affero General Public License http://www.gnu.org/licenses/
*/
@@ -41,10 +42,10 @@ if (!defined('STATUSNET') && !defined('LACONICA')) {
*/
require_once INSTALLDIR.'/classes/Memcached_DataObject.php';
-/* We keep the first three 20-notice pages, plus one for pagination check,
+/* We keep 200 notices, the max number of notices available per API request,
* in the memcached cache. */
-define('NOTICE_CACHE_WINDOW', 61);
+define('NOTICE_CACHE_WINDOW', 200);
define('MAX_BOXCARS', 128);
@@ -89,7 +90,15 @@ class Notice extends Memcached_DataObject
function getProfile()
{
- return Profile::staticGet('id', $this->profile_id);
+ $profile = Profile::staticGet('id', $this->profile_id);
+
+ if (empty($profile)) {
+ // TRANS: Server exception thrown when a user profile for a notice cannot be found.
+ // TRANS: %1$d is a profile ID (number), %2$d is a notice ID (number).
+ throw new ServerException(sprintf(_('No such profile (%1$d) for notice (%2$d).'), $this->profile_id, $this->id));
+ }
+
+ return $profile;
}
function delete()
@@ -97,15 +106,20 @@ class Notice extends Memcached_DataObject
// For auditing purposes, save a record that the notice
// was deleted.
- $deleted = new Deleted_notice();
+ // @fixme we have some cases where things get re-run and so the
+ // insert fails.
+ $deleted = Deleted_notice::staticGet('id', $this->id);
+ if (!$deleted) {
+ $deleted = new Deleted_notice();
- $deleted->id = $this->id;
- $deleted->profile_id = $this->profile_id;
- $deleted->uri = $this->uri;
- $deleted->created = $this->created;
- $deleted->deleted = common_sql_now();
+ $deleted->id = $this->id;
+ $deleted->profile_id = $this->profile_id;
+ $deleted->uri = $this->uri;
+ $deleted->created = $this->created;
+ $deleted->deleted = common_sql_now();
- $deleted->insert();
+ $deleted->insert();
+ }
// Clear related records
@@ -148,11 +162,11 @@ class Notice extends Memcached_DataObject
//turn each into their canonical tag
//this is needed to remove dupes before saving e.g. #hash.tag = #hashtag
for($i=0; $i<count($hashtags); $i++) {
+ /* elide characters we don't want in the tag */
$hashtags[$i] = common_canonical_tag($hashtags[$i]);
}
foreach(array_unique($hashtags) as $hashtag) {
- /* elide characters we don't want in the tag */
$this->saveTag($hashtag);
self::blow('profile:notice_ids_tagged:%d:%s', $this->profile_id, $hashtag);
}
@@ -172,7 +186,8 @@ class Notice extends Memcached_DataObject
$id = $tag->insert();
if (!$id) {
- throw new ServerException(sprintf(_('DB error inserting hashtag: %s'),
+ // TRANS: Server exception. %s are the error details.
+ throw new ServerException(sprintf(_('Database error inserting hashtag: %s'),
$last_error->message));
return;
}
@@ -241,28 +256,34 @@ class Notice extends Memcached_DataObject
$final = common_shorten_links($content);
if (Notice::contentTooLong($final)) {
+ // TRANS: Client exception thrown if a notice contains too many characters.
throw new ClientException(_('Problem saving notice. Too long.'));
}
if (empty($profile)) {
+ // TRANS: Client exception thrown when trying to save a notice for an unknown user.
throw new ClientException(_('Problem saving notice. Unknown user.'));
}
if (common_config('throttle', 'enabled') && !Notice::checkEditThrottle($profile_id)) {
common_log(LOG_WARNING, 'Excessive posting by profile #' . $profile_id . '; throttled.');
+ // TRANS: Client exception thrown when a user tries to post too many notices in a given time frame.
throw new ClientException(_('Too many notices too fast; take a breather '.
'and post again in a few minutes.'));
}
if (common_config('site', 'dupelimit') > 0 && !Notice::checkDupes($profile_id, $final)) {
common_log(LOG_WARNING, 'Dupe posting by profile #' . $profile_id . '; throttled.');
+ // TRANS: Client exception thrown when a user tries to post too many duplicate notices in a given time frame.
throw new ClientException(_('Too many duplicate messages too quickly;'.
' take a breather and post again in a few minutes.'));
}
if (!$profile->hasRight(Right::NEWNOTICE)) {
common_log(LOG_WARNING, "Attempted post from user disallowed to post: " . $profile->nickname);
- throw new ClientException(_('You are banned from posting notices on this site.'));
+
+ // TRANS: Client exception thrown when a user tries to post while being banned.
+ throw new ClientException(_('You are banned from posting notices on this site.'), 403);
}
$notice = new Notice();
@@ -328,6 +349,7 @@ class Notice extends Memcached_DataObject
if (!$id) {
common_log_db_error($notice, 'INSERT', __FILE__);
+ // TRANS: Server exception thrown when a notice cannot be saved.
throw new ServerException(_('Problem saving notice.'));
}
@@ -354,6 +376,7 @@ class Notice extends Memcached_DataObject
if ($changed) {
if (!$notice->update($orig)) {
common_log_db_error($notice, 'UPDATE', __FILE__);
+ // TRANS: Server exception thrown when a notice cannot be updated.
throw new ServerException(_('Problem saving notice.'));
}
}
@@ -373,18 +396,20 @@ class Notice extends Memcached_DataObject
$notice->saveReplies();
}
- if (isset($groups)) {
- $notice->saveKnownGroups($groups);
- } else {
- $notice->saveGroups();
- }
-
if (isset($tags)) {
$notice->saveKnownTags($tags);
} else {
$notice->saveTags();
}
+ // Note: groups may save tags, so must be run after tags are saved
+ // to avoid errors on duplicates.
+ if (isset($groups)) {
+ $notice->saveKnownGroups($groups);
+ } else {
+ $notice->saveGroups();
+ }
+
if (isset($urls)) {
$notice->saveKnownUrls($urls);
} else {
@@ -421,7 +446,9 @@ class Notice extends Memcached_DataObject
}
$profile = Profile::staticGet($this->profile_id);
- $profile->blowNoticeCount();
+ if (!empty($profile)) {
+ $profile->blowNoticeCount();
+ }
}
/**
@@ -458,7 +485,7 @@ class Notice extends Memcached_DataObject
function saveKnownUrls($urls)
{
// @fixme validation?
- foreach ($urls as $url) {
+ foreach (array_unique($urls) as $url) {
File::processNew($url, $this->id);
}
}
@@ -698,6 +725,27 @@ class Notice extends Memcached_DataObject
}
/**
+ * Is this notice part of an active conversation?
+ *
+ * @return boolean true if other messages exist in the same
+ * conversation, false if this is the only one
+ */
+ function hasConversation()
+ {
+ if (!empty($this->conversation)) {
+ $conversation = Notice::conversationStream(
+ $this->conversation,
+ 1,
+ 1
+ );
+ if ($conversation->N > 0) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ /**
* @param $groups array of Group *objects*
* @param $recipients array of profile *ids*
*/
@@ -840,11 +888,12 @@ class Notice extends Memcached_DataObject
function saveKnownGroups($group_ids)
{
if (!is_array($group_ids)) {
- throw new ServerException("Bad type provided to saveKnownGroups");
+ // TRANS: Server exception thrown when no array is provided to the method saveKnownGroups().
+ throw new ServerException(_("Bad type provided to saveKnownGroups"));
}
$groups = array();
- foreach ($group_ids as $id) {
+ foreach (array_unique($group_ids) as $id) {
$group = User_group::staticGet('id', $id);
if ($group) {
common_log(LOG_ERR, "Local delivery to group id $id, $group->nickname");
@@ -938,6 +987,7 @@ class Notice extends Memcached_DataObject
if (!$result) {
common_log_db_error($gi, 'INSERT', __FILE__);
+ // TRANS: Server exception thrown when an update for a group inbox fails.
throw new ServerException(_('Problem saving group inbox.'));
}
@@ -955,27 +1005,33 @@ class Notice extends Memcached_DataObject
* messages, we won't deliver to any remote targets as that's the
* source service's responsibility.
*
- * @fixme Unlike saveReplies() there's no mail notification here.
- * Move that to distrib queue handler?
+ * Mail notifications etc will be handled later.
*
* @param array of unique identifier URIs for recipients
*/
function saveKnownReplies($uris)
{
- foreach ($uris as $uri) {
+ if (empty($uris)) {
+ return;
+ }
+ $sender = Profile::staticGet($this->profile_id);
+
+ foreach (array_unique($uris) as $uri) {
$user = User::staticGet('uri', $uri);
if (!empty($user)) {
+ if ($user->hasBlocked($sender)) {
+ continue;
+ }
$reply = new Reply();
$reply->notice_id = $this->id;
$reply->profile_id = $user->id;
+ common_log(LOG_INFO, __METHOD__ . ": saving reply: notice $this->id to profile $user->id");
$id = $reply->insert();
-
- self::blow('reply:stream:%d', $user->id);
}
}
@@ -987,8 +1043,7 @@ class Notice extends Memcached_DataObject
* and save reply records indicating that this message needs to be
* delivered to those users.
*
- * Side effect: local recipients get e-mail notifications here.
- * @fixme move mail notifications to distrib?
+ * Mail notifications to local profiles will be sent later.
*
* @return array of integer profile IDs
*/
@@ -1039,26 +1094,26 @@ class Notice extends Memcached_DataObject
if (!$id) {
common_log_db_error($reply, 'INSERT', __FILE__);
- throw new ServerException("Couldn't save reply for {$this->id}, {$mentioned->id}");
+ // TRANS: Server exception thrown when a reply cannot be saved.
+ // TRANS: %1$d is a notice ID, %2$d is the ID of the mentioned user.
+ throw new ServerException(sprintf(_("Could not save reply for %1$d, %2$d."), $this->id, $mentioned->id));
} else {
$replied[$mentioned->id] = 1;
+ self::blow('reply:stream:%d', $mentioned->id);
}
}
}
$recipientIds = array_keys($replied);
- foreach ($recipientIds as $recipientId) {
- $user = User::staticGet('id', $recipientId);
- if (!empty($user)) {
- self::blow('reply:stream:%d', $reply->profile_id);
- mail_notify_attn($user, $this);
- }
- }
-
return $recipientIds;
}
+ /**
+ * Pull the complete list of @-reply targets for this notice.
+ *
+ * @return array of integer profile ids
+ */
function getReplies()
{
// XXX: cache me
@@ -1082,6 +1137,30 @@ class Notice extends Memcached_DataObject
}
/**
+ * Send e-mail notifications to local @-reply targets.
+ *
+ * Replies must already have been saved; this is expected to be run
+ * from the distrib queue handler.
+ */
+ function sendReplyNotifications()
+ {
+ // Don't send reply notifications for repeats
+
+ if (!empty($this->repeat_of)) {
+ return array();
+ }
+
+ $recipientIds = $this->getReplies();
+
+ foreach ($recipientIds as $recipientId) {
+ $user = User::staticGet('id', $recipientId);
+ if (!empty($user)) {
+ mail_notify_attn($user, $this);
+ }
+ }
+ }
+
+ /**
* Pull list of groups this notice needs to be delivered to,
* as previously recorded by saveGroups() or saveKnownGroups().
*
@@ -1120,7 +1199,10 @@ class Notice extends Memcached_DataObject
return $groups;
}
- function asAtomEntry($namespace=false, $source=false, $author=true)
+ // This has gotten way too long. Needs to be sliced up into functional bits
+ // or ideally exported to a utility class.
+
+ function asAtomEntry($namespace=false, $source=false, $author=true, $cur=null)
{
$profile = $this->getProfile();
@@ -1133,149 +1215,332 @@ class Notice extends Memcached_DataObject
'xmlns:activity' => 'http://activitystrea.ms/spec/1.0/',
'xmlns:media' => 'http://purl.org/syndication/atommedia',
'xmlns:poco' => 'http://portablecontacts.net/spec/1.0',
- 'xmlns:ostatus' => 'http://ostatus.org/schema/1.0');
+ 'xmlns:ostatus' => 'http://ostatus.org/schema/1.0',
+ 'xmlns:statusnet' => 'http://status.net/schema/api/1/');
} else {
$attrs = array();
}
- $xs->elementStart('entry', $attrs);
+ if (Event::handle('StartActivityStart', array(&$this, &$xs, &$attrs))) {
+ $xs->elementStart('entry', $attrs);
+ Event::handle('EndActivityStart', array(&$this, &$xs, &$attrs));
+ }
- if ($source) {
- $xs->elementStart('source');
- $xs->element('id', null, $profile->profileurl);
- $xs->element('title', null, $profile->nickname . " - " . common_config('site', 'name'));
- $xs->element('link', array('href' => $profile->profileurl));
- $user = User::staticGet('id', $profile->id);
- if (!empty($user)) {
- $atom_feed = common_local_url('ApiTimelineUser',
- array('format' => 'atom',
- 'id' => $profile->nickname));
- $xs->element('link', array('rel' => 'self',
- 'type' => 'application/atom+xml',
- 'href' => $profile->profileurl));
- $xs->element('link', array('rel' => 'license',
- 'href' => common_config('license', 'url')));
+ if (Event::handle('StartActivitySource', array(&$this, &$xs))) {
+
+ if ($source) {
+
+ $atom_feed = $profile->getAtomFeed();
+
+ if (!empty($atom_feed)) {
+
+ $xs->elementStart('source');
+
+ // XXX: we should store the actual feed ID
+
+ $xs->element('id', null, $atom_feed);
+
+ // XXX: we should store the actual feed title
+
+ $xs->element('title', null, $profile->getBestName());
+
+ $xs->element('link', array('rel' => 'alternate',
+ 'type' => 'text/html',
+ 'href' => $profile->profileurl));
+
+ $xs->element('link', array('rel' => 'self',
+ 'type' => 'application/atom+xml',
+ 'href' => $atom_feed));
+
+ $xs->element('icon', null, $profile->avatarUrl(AVATAR_PROFILE_SIZE));
+
+ $notice = $profile->getCurrentNotice();
+
+ if (!empty($notice)) {
+ $xs->element('updated', null, self::utcDate($notice->created));
+ }
+
+ $user = User::staticGet('id', $profile->id);
+
+ if (!empty($user)) {
+ $xs->element('link', array('rel' => 'license',
+ 'href' => common_config('license', 'url')));
+ }
+
+ $xs->elementEnd('source');
+ }
}
+ Event::handle('EndActivitySource', array(&$this, &$xs));
+ }
+
+ $title = common_xml_safe_str($this->content);
+
+ if (Event::handle('StartActivityTitle', array(&$this, &$xs, &$title))) {
+ $xs->element('title', null, $title);
+ Event::handle('EndActivityTitle', array($this, &$xs, $title));
+ }
+
+ $atomAuthor = '';
- $xs->element('icon', null, $profile->avatarUrl(AVATAR_PROFILE_SIZE));
- $xs->element('updated', null, common_date_w3dtf($this->created));
+ if ($author) {
+ $atomAuthor = $profile->asAtomAuthor($cur);
}
- if ($source) {
- $xs->elementEnd('source');
+ if (Event::handle('StartActivityAuthor', array(&$this, &$xs, &$atomAuthor))) {
+ if (!empty($atomAuthor)) {
+ $xs->raw($atomAuthor);
+ Event::handle('EndActivityAuthor', array(&$this, &$xs, &$atomAuthor));
+ }
}
- $xs->element('title', null, common_xml_safe_str($this->content));
+ $actor = '';
if ($author) {
- $xs->raw($profile->asAtomAuthor());
- $xs->raw($profile->asActivityActor());
+ $actor = $profile->asActivityActor();
+ }
+
+ if (Event::handle('StartActivityActor', array(&$this, &$xs, &$actor))) {
+ if (!empty($actor)) {
+ $xs->raw($actor);
+ Event::handle('EndActivityActor', array(&$this, &$xs, &$actor));
+ }
+ }
+
+ $url = $this->bestUrl();
+
+ if (Event::handle('StartActivityLink', array(&$this, &$xs, &$url))) {
+ $xs->element('link', array('rel' => 'alternate',
+ 'type' => 'text/html',
+ 'href' => $url));
+ Event::handle('EndActivityLink', array(&$this, &$xs, $url));
+ }
+
+ $id = $this->uri;
+
+ if (Event::handle('StartActivityId', array(&$this, &$xs, &$id))) {
+ $xs->element('id', null, $id);
+ Event::handle('EndActivityId', array(&$this, &$xs, $id));
+ }
+
+ $published = self::utcDate($this->created);
+
+ if (Event::handle('StartActivityPublished', array(&$this, &$xs, &$published))) {
+ $xs->element('published', null, $published);
+ Event::handle('EndActivityPublished', array(&$this, &$xs, $published));
+ }
+
+ $updated = $published; // XXX: notices are usually immutable
+
+ if (Event::handle('StartActivityUpdated', array(&$this, &$xs, &$updated))) {
+ $xs->element('updated', null, $updated);
+ Event::handle('EndActivityUpdated', array(&$this, &$xs, $updated));
+ }
+
+ $content = common_xml_safe_str($this->rendered);
+
+ if (Event::handle('StartActivityContent', array(&$this, &$xs, &$content))) {
+ $xs->element('content', array('type' => 'html'), $content);
+ Event::handle('EndActivityContent', array(&$this, &$xs, $content));
}
- $xs->element('link', array('rel' => 'alternate',
- 'type' => 'text/html',
- 'href' => $this->bestUrl()));
+ // Most of our notices represent POSTing a NOTE. This is the default verb
+ // for activity streams, so we normally just leave it out.
- $xs->element('id', null, $this->uri);
+ $verb = ActivityVerb::POST;
- $xs->element('published', null, common_date_w3dtf($this->created));
- $xs->element('updated', null, common_date_w3dtf($this->created));
+ if (Event::handle('StartActivityVerb', array(&$this, &$xs, &$verb))) {
+ $xs->element('activity:verb', null, $verb);
+ Event::handle('EndActivityVerb', array(&$this, &$xs, $verb));
+ }
+
+ // We use the default behavior for activity streams: if there's no activity:object,
+ // then treat the entry itself as the object. Here, you can set the type of that object,
+ // which is normally a NOTE.
+
+ $type = ActivityObject::NOTE;
+
+ if (Event::handle('StartActivityDefaultObjectType', array(&$this, &$xs, &$type))) {
+ $xs->element('activity:object-type', null, $type);
+ Event::handle('EndActivityDefaultObjectType', array(&$this, &$xs, $type));
+ }
+
+ // Since we usually use the entry itself as an object, we don't have an explicit
+ // object. Some extensions may want to add them (for photo, event, music, etc.).
+
+ $objects = array();
+
+ if (Event::handle('StartActivityObjects', array(&$this, &$xs, &$objects))) {
+ foreach ($objects as $object) {
+ $xs->raw($object->asString());
+ }
+ Event::handle('EndActivityObjects', array(&$this, &$xs, $objects));
+ }
+
+ $noticeInfoAttr = array('local_id' => $this->id); // local notice ID (useful to clients for ordering)
+
+ $ns = $this->getSource();
+
+ if (!empty($ns)) {
+ $noticeInfoAttr['source'] = $ns->code;
+ if (!empty($ns->url)) {
+ $noticeInfoAttr['source_link'] = $ns->url;
+ if (!empty($ns->name)) {
+ $noticeInfoAttr['source'] = '<a href="'
+ . htmlspecialchars($ns->url)
+ . '" rel="nofollow">'
+ . htmlspecialchars($ns->name)
+ . '</a>';
+ }
+ }
+ }
+
+ if (!empty($cur)) {
+ $noticeInfoAttr['favorite'] = ($cur->hasFave($this)) ? "true" : "false";
+ $profile = $cur->getProfile();
+ $noticeInfoAttr['repeated'] = ($profile->hasRepeated($this->id)) ? "true" : "false";
+ }
+
+ if (!empty($this->repeat_of)) {
+ $noticeInfoAttr['repeat_of'] = $this->repeat_of;
+ }
+
+ if (Event::handle('StartActivityNoticeInfo', array(&$this, &$xs, &$noticeInfoAttr))) {
+ $xs->element('statusnet:notice_info', $noticeInfoAttr, null);
+ Event::handle('EndActivityNoticeInfo', array(&$this, &$xs, $noticeInfoAttr));
+ }
+
+ $replyNotice = null;
if ($this->reply_to) {
- $reply_notice = Notice::staticGet('id', $this->reply_to);
- if (!empty($reply_notice)) {
+ $replyNotice = Notice::staticGet('id', $this->reply_to);
+ }
+
+ if (Event::handle('StartActivityInReplyTo', array(&$this, &$xs, &$replyNotice))) {
+ if (!empty($replyNotice)) {
$xs->element('link', array('rel' => 'related',
- 'href' => $reply_notice->bestUrl()));
+ 'href' => $replyNotice->bestUrl()));
$xs->element('thr:in-reply-to',
- array('ref' => $reply_notice->uri,
- 'href' => $reply_notice->bestUrl()));
+ array('ref' => $replyNotice->uri,
+ 'href' => $replyNotice->bestUrl()));
+ Event::handle('EndActivityInReplyTo', array(&$this, &$xs, $replyNotice));
}
}
- if (!empty($this->conversation)) {
+ $conv = null;
+ if (!empty($this->conversation)) {
$conv = Conversation::staticGet('id', $this->conversation);
+ }
+ if (Event::handle('StartActivityConversation', array(&$this, &$xs, &$conv))) {
if (!empty($conv)) {
- $xs->element(
- 'link', array(
- 'rel' => 'ostatus:conversation',
- 'href' => $conv->uri
- )
- );
+ $xs->element('link', array('rel' => 'ostatus:conversation',
+ 'href' => $conv->uri));
}
+ Event::handle('EndActivityConversation', array(&$this, &$xs, $conv));
}
+ $replyProfiles = array();
+
$reply_ids = $this->getReplies();
foreach ($reply_ids as $id) {
$profile = Profile::staticGet('id', $id);
- if (!empty($profile)) {
- $xs->element(
- 'link', array(
- 'rel' => 'ostatus:attention',
- 'href' => $profile->getUri()
- )
- );
+ if (!empty($profile)) {
+ $replyProfiles[] = $profile;
+ }
+ }
+
+ if (Event::handle('StartActivityAttentionProfiles', array(&$this, &$xs, &$replyProfiles))) {
+ foreach ($replyProfiles as $profile) {
+ $xs->element('link', array('rel' => 'ostatus:attention',
+ 'href' => $profile->getUri()));
+ $xs->element('link', array('rel' => 'mentioned',
+ 'href' => $profile->getUri()));
}
+ Event::handle('EndActivityAttentionProfiles', array(&$this, &$xs, $replyProfiles));
}
$groups = $this->getGroups();
- foreach ($groups as $group) {
- $xs->element(
- 'link', array(
- 'rel' => 'ostatus:attention',
- 'href' => $group->permalink()
- )
- );
+ if (Event::handle('StartActivityAttentionGroups', array(&$this, &$xs, &$groups))) {
+ foreach ($groups as $group) {
+ $xs->element('link', array('rel' => 'ostatus:attention',
+ 'href' => $group->permalink()));
+ $xs->element('link', array('rel' => 'mentioned',
+ 'href' => $group->permalink()));
+ }
+ Event::handle('EndActivityAttentionGroups', array(&$this, &$xs, $groups));
}
+ $repeat = null;
+
if (!empty($this->repeat_of)) {
$repeat = Notice::staticGet('id', $this->repeat_of);
+ }
+
+ if (Event::handle('StartActivityForward', array(&$this, &$xs, &$repeat))) {
if (!empty($repeat)) {
- $xs->element(
- 'ostatus:forward',
- array('ref' => $repeat->uri, 'href' => $repeat->bestUrl())
- );
+ $xs->element('ostatus:forward',
+ array('ref' => $repeat->uri,
+ 'href' => $repeat->bestUrl()));
}
+
+ Event::handle('EndActivityForward', array(&$this, &$xs, $repeat));
}
- $xs->element(
- 'content',
- array('type' => 'html'),
- common_xml_safe_str($this->rendered)
- );
+ $tags = $this->getTags();
- $tag = new Notice_tag();
- $tag->notice_id = $this->id;
- if ($tag->find()) {
- while ($tag->fetch()) {
- $xs->element('category', array('term' => $tag->tag));
+ if (Event::handle('StartActivityCategories', array(&$this, &$xs, &$tags))) {
+ foreach ($tags as $tag) {
+ $xs->element('category', array('term' => $tag));
}
+ Event::handle('EndActivityCategories', array(&$this, &$xs, $tags));
}
- $tag->free();
- # Enclosures
+ // Enclosures
+
+ $enclosures = array();
+
$attachments = $this->attachments();
- if($attachments){
- foreach($attachments as $attachment){
- $enclosure=$attachment->getEnclosure();
- if ($enclosure) {
- $attributes = array('rel'=>'enclosure','href'=>$enclosure->url,'type'=>$enclosure->mimetype,'length'=>$enclosure->size);
- if($enclosure->title){
- $attributes['title']=$enclosure->title;
- }
- $xs->element('link', $attributes, null);
+
+ foreach ($attachments as $attachment) {
+ $enclosure = $attachment->getEnclosure();
+ if ($enclosure) {
+ $enclosures[] = $enclosure;
+ }
+ }
+
+ if (Event::handle('StartActivityEnclosures', array(&$this, &$xs, &$enclosures))) {
+ foreach ($enclosures as $enclosure) {
+ $attributes = array('rel' => 'enclosure',
+ 'href' => $enclosure->url,
+ 'type' => $enclosure->mimetype,
+ 'length' => $enclosure->size);
+
+ if ($enclosure->title) {
+ $attributes['title'] = $enclosure->title;
}
+
+ $xs->element('link', $attributes, null);
}
+ Event::handle('EndActivityEnclosures', array(&$this, &$xs, $enclosures));
}
- if (!empty($this->lat) && !empty($this->lon)) {
- $xs->element('georss:point', null, $this->lat . ' ' . $this->lon);
+ $lat = $this->lat;
+ $lon = $this->lon;
+
+ if (Event::handle('StartActivityGeo', array(&$this, &$xs, &$lat, &$lon))) {
+ if (!empty($lat) && !empty($lon)) {
+ $xs->element('georss:point', null, $lat . ' ' . $lon);
+ }
+ Event::handle('EndActivityGeo', array(&$this, &$xs, $lat, $lon));
}
- $xs->elementEnd('entry');
+ if (Event::handle('StartActivityEnd', array(&$this, &$xs))) {
+ $xs->elementEnd('entry');
+ Event::handle('EndActivityEnd', array(&$this, &$xs));
+ }
return $xs->getString();
}
@@ -1476,6 +1741,8 @@ class Notice extends Memcached_DataObject
{
$author = Profile::staticGet('id', $this->profile_id);
+ // TRANS: Message used to repeat a notice. RT is the abbreviation of 'retweet'.
+ // TRANS: %1$s is the repeated user's name, %2$s is the repeated notice.
$content = sprintf(_('RT @%1$s %2$s'),
$author->nickname,
$this->content);
@@ -1745,4 +2012,73 @@ class Notice extends Memcached_DataObject
return $result;
}
+
+ /**
+ * Get the source of the notice
+ *
+ * @return Notice_source $ns A notice source object. 'code' is the only attribute
+ * guaranteed to be populated.
+ */
+ function getSource()
+ {
+ $ns = new Notice_source();
+ if (!empty($this->source)) {
+ switch ($this->source) {
+ case 'web':
+ case 'xmpp':
+ case 'mail':
+ case 'omb':
+ case 'system':
+ case 'api':
+ $ns->code = $this->source;
+ break;
+ default:
+ $ns = Notice_source::staticGet($this->source);
+ if (!$ns) {
+ $ns = new Notice_source();
+ $ns->code = $this->source;
+ $app = Oauth_application::staticGet('name', $this->source);
+ if ($app) {
+ $ns->name = $app->name;
+ $ns->url = $app->source_url;
+ }
+ }
+ break;
+ }
+ }
+ return $ns;
+ }
+
+ /**
+ * Determine whether the notice was locally created
+ *
+ * @return boolean locality
+ */
+
+ public function isLocal()
+ {
+ return ($this->is_local == Notice::LOCAL_PUBLIC ||
+ $this->is_local == Notice::LOCAL_NONPUBLIC);
+ }
+
+ public function getTags()
+ {
+ $tags = array();
+ $tag = new Notice_tag();
+ $tag->notice_id = $this->id;
+ if ($tag->find()) {
+ while ($tag->fetch()) {
+ $tags[] = $tag->tag;
+ }
+ }
+ $tag->free();
+ return $tags;
+ }
+
+ static private function utcDate($dt)
+ {
+ $dateStr = date('d F Y H:i:s', strtotime($dt));
+ $d = new DateTime($dateStr, new DateTimeZone('UTC'));
+ return $d->format(DATE_W3C);
+ }
}
diff --git a/classes/Profile.php b/classes/Profile.php
index eded1ff71..d7617f0b7 100644
--- a/classes/Profile.php
+++ b/classes/Profile.php
@@ -152,17 +152,16 @@ class Profile extends Memcached_DataObject
*
* @return mixed Notice or null
*/
+
function getCurrentNotice()
{
- $notice = new Notice();
- $notice->profile_id = $this->id;
- // @fixme change this to sort on notice.id only when indexes are updated
- $notice->orderBy('created DESC, notice.id DESC');
- $notice->limit(1);
- if ($notice->find(true)) {
+ $notice = $this->getNotices(0, 1);
+
+ if ($notice->fetch()) {
return $notice;
+ } else {
+ return null;
}
- return null;
}
function getTaggedNotices($tag, $offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $max_id=0)
@@ -225,31 +224,62 @@ class Profile extends Memcached_DataObject
{
$notice = new Notice();
- $notice->profile_id = $this->id;
+ // Temporary hack until notice_profile_id_idx is updated
+ // to (profile_id, id) instead of (profile_id, created, id).
+ // It's been falling back to PRIMARY instead, which is really
+ // very inefficient for a profile that hasn't posted in a few
+ // months. Even though forcing the index will cause a filesort,
+ // it's usually going to be better.
+ if (common_config('db', 'type') == 'mysql') {
+ $index = '';
+ $query =
+ "select id from notice force index (notice_profile_id_idx) ".
+ "where profile_id=" . $notice->escape($this->id);
+
+ if ($since_id != 0) {
+ $query .= " and id > $since_id";
+ }
- $notice->selectAdd();
- $notice->selectAdd('id');
+ if ($max_id != 0) {
+ $query .= " and id < $max_id";
+ }
- if ($since_id != 0) {
- $notice->whereAdd('id > ' . $since_id);
- }
+ $query .= ' order by id DESC';
- if ($max_id != 0) {
- $notice->whereAdd('id <= ' . $max_id);
- }
+ if (!is_null($offset)) {
+ $query .= " LIMIT $limit OFFSET $offset";
+ }
- $notice->orderBy('id DESC');
+ $notice->query($query);
+ } else {
+ $index = '';
- if (!is_null($offset)) {
- $notice->limit($offset, $limit);
+ $notice->profile_id = $this->id;
+
+ $notice->selectAdd();
+ $notice->selectAdd('id');
+
+ if ($since_id != 0) {
+ $notice->whereAdd('id > ' . $since_id);
+ }
+
+ if ($max_id != 0) {
+ $notice->whereAdd('id <= ' . $max_id);
+ }
+
+ $notice->orderBy('id DESC');
+
+ if (!is_null($offset)) {
+ $notice->limit($offset, $limit);
+ }
+
+ $notice->find();
}
$ids = array();
- if ($notice->find()) {
- while ($notice->fetch()) {
- $ids[] = $notice->id;
- }
+ while ($notice->fetch()) {
+ $ids[] = $notice->id;
}
return $ids;
@@ -434,11 +464,9 @@ class Profile extends Memcached_DataObject
$sub = new Subscription();
$sub->subscribed = $this->id;
-
+ $sub->whereAdd('subscriber != subscribed');
$cnt = (int) $sub->count('distinct subscriber');
- $cnt = ($cnt > 0) ? $cnt - 1 : $cnt;
-
if (!empty($c)) {
$c->set(common_cache_key('profile:subscriber_count:'.$this->id), $cnt);
}
@@ -577,11 +605,41 @@ class Profile extends Memcached_DataObject
{
$sub = new Subscription();
$sub->subscriber = $this->id;
- $sub->delete();
+
+ $sub->find();
+
+ while ($sub->fetch()) {
+ $other = Profile::staticGet('id', $sub->subscribed);
+ if (empty($other)) {
+ continue;
+ }
+ if ($other->id == $this->id) {
+ continue;
+ }
+ Subscription::cancel($this, $other);
+ }
$subd = new Subscription();
$subd->subscribed = $this->id;
- $subd->delete();
+ $subd->find();
+
+ while ($subd->fetch()) {
+ $other = Profile::staticGet('id', $subd->subscriber);
+ if (empty($other)) {
+ continue;
+ }
+ if ($other->id == $this->id) {
+ continue;
+ }
+ Subscription::cancel($other, $this);
+ }
+
+ $self = new Subscription();
+
+ $self->subscriber = $this->id;
+ $self->subscribed = $this->id;
+
+ $self->delete();
}
function _deleteMessages()
@@ -674,14 +732,18 @@ class Profile extends Memcached_DataObject
'role' => $name));
if (empty($role)) {
- throw new Exception('Cannot revoke role "'.$name.'" for user #'.$this->id.'; does not exist.');
+ // TRANS: Exception thrown when trying to revoke an existing role for a user that does not exist.
+ // TRANS: %1$s is the role name, %2$s is the user ID (number).
+ throw new Exception(sprintf(_('Cannot revoke role "%1$s" for user #%2$d; does not exist.'),$name, $this->id));
}
$result = $role->delete();
if (!$result) {
common_log_db_error($role, 'DELETE', __FILE__);
- throw new Exception('Cannot revoke role "'.$name.'" for user #'.$this->id.'; database error.');
+ // TRANS: Exception thrown when trying to revoke a role for a user with a failing database query.
+ // TRANS: %1$s is the role name, %2$s is the user ID (number).
+ throw new Exception(sprintf(_('Cannot revoke role "%1$s" for user #%2$d; database error.'),$name, $this->id));
}
return true;
@@ -788,15 +850,23 @@ class Profile extends Memcached_DataObject
*
* Assumes that Atom has been previously set up as the base namespace.
*
+ * @param Profile $cur the current authenticated user
+ *
* @return string
*/
- function asAtomAuthor()
+ function asAtomAuthor($cur = null)
{
$xs = new XMLStringer(true);
$xs->elementStart('author');
$xs->element('name', null, $this->nickname);
$xs->element('uri', null, $this->getUri());
+ if ($cur != null) {
+ $attrs = Array();
+ $attrs['following'] = $cur->isSubscribed($this) ? 'true' : 'false';
+ $attrs['blocking'] = $cur->hasBlocked($this) ? 'true' : 'false';
+ $xs->element('statusnet:profile_info', $attrs, null);
+ }
$xs->elementEnd('author');
return $xs->getString();
@@ -874,4 +944,20 @@ class Profile extends Memcached_DataObject
return $result;
}
+
+ function getAtomFeed()
+ {
+ $feed = null;
+
+ if (Event::handle('StartProfileGetAtomFeed', array($this, &$feed))) {
+ $user = User::staticGet('id', $this->id);
+ if (!empty($user)) {
+ $feed = common_local_url('ApiTimelineUser', array('id' => $user->id,
+ 'format' => 'atom'));
+ }
+ Event::handle('EndProfileGetAtomFeed', array($this, $feed));
+ }
+
+ return $feed;
+ }
}
diff --git a/classes/Queue_item.php b/classes/Queue_item.php
index f83c2cef1..c7e17be6e 100644
--- a/classes/Queue_item.php
+++ b/classes/Queue_item.php
@@ -64,4 +64,17 @@ class Queue_item extends Memcached_DataObject
$qi = null;
return null;
}
+
+ /**
+ * Release a claimed item.
+ */
+ function releaseCLaim()
+ {
+ // DB_DataObject doesn't let us save nulls right now
+ $sql = sprintf("UPDATE queue_item SET claimed=NULL WHERE id=%d", $this->id);
+ $this->query($sql);
+
+ $this->claimed = null;
+ $this->encache();
+ }
}
diff --git a/classes/Remote_profile.php b/classes/Remote_profile.php
index 0a1676a6a..77bfbcd99 100644
--- a/classes/Remote_profile.php
+++ b/classes/Remote_profile.php
@@ -50,7 +50,8 @@ class Remote_profile extends Memcached_DataObject
if ($profile) {
return $profile->hasright($right);
} else {
- throw new Exception("Missing profile");
+ // TRANS: Exception thrown when a right for a non-existing user profile is checked.
+ throw new Exception(_("Missing profile."));
}
}
}
diff --git a/classes/Reply.php b/classes/Reply.php
index 659e04c92..dc6296bda 100644
--- a/classes/Reply.php
+++ b/classes/Reply.php
@@ -22,6 +22,20 @@ class Reply extends Memcached_DataObject
/* the code above is auto generated do not remove the tag below */
###END_AUTOCODE
+ /**
+ * Wrapper for record insertion to update related caches
+ */
+ function insert()
+ {
+ $result = parent::insert();
+
+ if ($result) {
+ self::blow('reply:stream:%d', $this->profile_id);
+ }
+
+ return $result;
+ }
+
function stream($user_id, $offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $max_id=0)
{
$ids = Notice::stream(array('Reply', '_streamDirect'),
diff --git a/classes/Safe_DataObject.php b/classes/Safe_DataObject.php
index 08bc6846f..f0ea6b136 100644
--- a/classes/Safe_DataObject.php
+++ b/classes/Safe_DataObject.php
@@ -96,12 +96,37 @@ class Safe_DataObject extends DB_DataObject
$this->_link_loaded = false;
}
+ /**
+ * Magic function called when someone attempts to call a method
+ * that doesn't exist. DB_DataObject uses this to implement
+ * setters and getters for fields, but neglects to throw an error
+ * when you just misspell an actual method name. This leads to
+ * silent failures which can cause all kinds of havoc.
+ *
+ * @param string $method
+ * @param array $params
+ * @return mixed
+ * @throws Exception
+ */
+ function __call($method, $params)
+ {
+ $return = null;
+ // Yes, that's _call with one underscore, which does the
+ // actual implementation.
+ if ($this->_call($method, $params, $return)) {
+ return $return;
+ } else {
+ // Low level exception. No need for i18n as discussed with Brion.
+ throw new Exception('Call to undefined method ' .
+ get_class($this) . '::' . $method);
+ }
+ }
/**
* Work around memory-leak bugs...
* Had to copy-paste the whole function in order to patch a couple lines of it.
* Would be nice if this code was better factored.
- *
+ *
* @param optional string name of database to assign / read
* @param optional array structure of database, and keys
* @param optional array table links
@@ -112,108 +137,103 @@ class Safe_DataObject extends DB_DataObject
*/
function databaseStructure()
{
-
global $_DB_DATAOBJECT;
-
- // Assignment code
-
+
+ // Assignment code
+
if ($args = func_get_args()) {
-
+
if (count($args) == 1) {
-
+
// this returns all the tables and their structure..
if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
$this->debug("Loading Generator as databaseStructure called with args",1);
}
-
+
$x = new DB_DataObject;
$x->_database = $args[0];
$this->_connect();
$DB = &$_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5];
-
+
$tables = $DB->getListOf('tables');
- class_exists('DB_DataObject_Generator') ? '' :
+ class_exists('DB_DataObject_Generator') ? '' :
require_once 'DB/DataObject/Generator.php';
-
+
foreach($tables as $table) {
$y = new DB_DataObject_Generator;
$y->fillTableSchema($x->_database,$table);
}
- return $_DB_DATAOBJECT['INI'][$x->_database];
+ return $_DB_DATAOBJECT['INI'][$x->_database];
} else {
-
+
$_DB_DATAOBJECT['INI'][$args[0]] = isset($_DB_DATAOBJECT['INI'][$args[0]]) ?
$_DB_DATAOBJECT['INI'][$args[0]] + $args[1] : $args[1];
-
+
if (isset($args[1])) {
$_DB_DATAOBJECT['LINKS'][$args[0]] = isset($_DB_DATAOBJECT['LINKS'][$args[0]]) ?
$_DB_DATAOBJECT['LINKS'][$args[0]] + $args[2] : $args[2];
}
return true;
}
-
+
}
-
-
-
+
if (!$this->_database) {
$this->_connect();
}
-
+
// loaded already?
if (!empty($_DB_DATAOBJECT['INI'][$this->_database])) {
-
+
// database loaded - but this is table is not available..
if (
- empty($_DB_DATAOBJECT['INI'][$this->_database][$this->__table])
+ empty($_DB_DATAOBJECT['INI'][$this->_database][$this->__table])
&& !empty($_DB_DATAOBJECT['CONFIG']['proxy'])
) {
if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
$this->debug("Loading Generator to fetch Schema",1);
}
- class_exists('DB_DataObject_Generator') ? '' :
+ class_exists('DB_DataObject_Generator') ? '' :
require_once 'DB/DataObject/Generator.php';
-
-
+
+
$x = new DB_DataObject_Generator;
$x->fillTableSchema($this->_database,$this->__table);
}
return true;
}
-
-
+
if (empty($_DB_DATAOBJECT['CONFIG'])) {
DB_DataObject::_loadConfig();
}
-
+
// if you supply this with arguments, then it will take those
// as the database and links array...
-
+
$schemas = isset($_DB_DATAOBJECT['CONFIG']['schema_location']) ?
array("{$_DB_DATAOBJECT['CONFIG']['schema_location']}/{$this->_database}.ini") :
array() ;
-
+
if (isset($_DB_DATAOBJECT['CONFIG']["ini_{$this->_database}"])) {
$schemas = is_array($_DB_DATAOBJECT['CONFIG']["ini_{$this->_database}"]) ?
$_DB_DATAOBJECT['CONFIG']["ini_{$this->_database}"] :
explode(PATH_SEPARATOR,$_DB_DATAOBJECT['CONFIG']["ini_{$this->_database}"]);
}
-
-
+
/* BEGIN CHANGED FROM UPSTREAM */
$_DB_DATAOBJECT['INI'][$this->_database] = $this->parseIniFiles($schemas);
/* END CHANGED FROM UPSTREAM */
- // now have we loaded the structure..
-
+ // now have we loaded the structure..
+
if (!empty($_DB_DATAOBJECT['INI'][$this->_database][$this->__table])) {
return true;
}
// - if not try building it..
if (!empty($_DB_DATAOBJECT['CONFIG']['proxy'])) {
- class_exists('DB_DataObject_Generator') ? '' :
+ class_exists('DB_DataObject_Generator') ? '' :
require_once 'DB/DataObject/Generator.php';
-
+
$x = new DB_DataObject_Generator;
$x->fillTableSchema($this->_database,$this->__table);
// should this fail!!!???
@@ -221,7 +241,8 @@ class Safe_DataObject extends DB_DataObject
}
$this->debug("Cant find database schema: {$this->_database}/{$this->__table} \n".
"in links file data: " . print_r($_DB_DATAOBJECT['INI'],true),"databaseStructure",5);
- // we have to die here!! - it causes chaos if we dont (including looping forever!)
+ // we have to die here!! - it causes chaos if we don't (including looping forever!)
+ // Low level exception. No need for i18n as discussed with Brion.
$this->raiseError( "Unable to load schema for database and table (turn debugging up to 5 for full error message)", DB_DATAOBJECT_ERROR_INVALIDARGS, PEAR_ERROR_DIE);
return false;
}
@@ -247,7 +268,7 @@ class Safe_DataObject extends DB_DataObject
if (file_exists($ini) && is_file($ini)) {
$data = array_merge($data, parse_ini_file($ini, true));
- if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
+ if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
if (!is_readable ($ini)) {
$this->debug("ini file is not readable: $ini","databaseStructure",1);
} else {
diff --git a/classes/Status_network.php b/classes/Status_network.php
index a452c32ce..5680c1458 100644
--- a/classes/Status_network.php
+++ b/classes/Status_network.php
@@ -27,7 +27,8 @@ class Status_network extends Safe_DataObject
/* the code below is auto generated do not remove the above tag */
public $__table = 'status_network'; // table name
- public $nickname; // varchar(64) primary_key not_null
+ public $site_id; // int(4) primary_key not_null
+ public $nickname; // varchar(64) unique_key not_null
public $hostname; // varchar(255) unique_key
public $pathname; // varchar(255) unique_key
public $dbhost; // varchar(255)
@@ -39,7 +40,6 @@ class Status_network extends Safe_DataObject
public $logo; // varchar(255)
public $created; // datetime() not_null
public $modified; // timestamp() not_null default_CURRENT_TIMESTAMP
- public $tags; // text
/* Static get */
function staticGet($k,$v=NULL) {
@@ -144,26 +144,49 @@ class Status_network extends Safe_DataObject
return parent::update($orig);
}
+ /**
+ * DB_DataObject doesn't allow updating keys (even non-primary)
+ */
+ function updateKeys(&$orig)
+ {
+ $this->_connect();
+ foreach (array('hostname', 'pathname') as $k) {
+ if (strcmp($this->$k, $orig->$k) != 0) {
+ $parts[] = $k . ' = ' . $this->_quote($this->$k);
+ }
+ }
+ if (count($parts) == 0) {
+ // No changes
+ return true;
+ }
+
+ $toupdate = implode(', ', $parts);
+
+ $table = common_database_tablename($this->tableName());
+ $qry = 'UPDATE ' . $table . ' SET ' . $toupdate .
+ ' WHERE nickname = ' . $this->_quote($this->nickname);
+ $orig->decache();
+ $result = $this->query($qry);
+ if ($result) {
+ $this->encache();
+ }
+ return $result;
+ }
+
function delete()
{
$this->decache(); # while we still have the values!
return parent::delete();
}
-
+
/**
* @param string $servername hostname
- * @param string $pathname URL base path
* @param string $wildcard hostname suffix to match wildcard config
+ * @return mixed Status_network or null
*/
- static function setupSite($servername, $pathname, $wildcard)
+ static function getFromHostname($servername, $wildcard)
{
- global $config;
-
$sn = null;
-
- // XXX I18N, probably not crucial for hostnames
- // XXX This probably needs a tune up
-
if (0 == strncasecmp(strrev($wildcard), strrev($servername), strlen($wildcard))) {
// special case for exact match
if (0 == strcasecmp($servername, $wildcard)) {
@@ -182,6 +205,23 @@ class Status_network extends Safe_DataObject
}
}
}
+ return $sn;
+ }
+
+ /**
+ * @param string $servername hostname
+ * @param string $pathname URL base path
+ * @param string $wildcard hostname suffix to match wildcard config
+ */
+ static function setupSite($servername, $pathname, $wildcard)
+ {
+ global $config;
+
+ $sn = null;
+
+ // XXX I18N, probably not crucial for hostnames
+ // XXX This probably needs a tune up
+ $sn = self::getFromHostname($servername, $wildcard);
if (!empty($sn)) {
@@ -268,10 +308,64 @@ class Status_network extends Safe_DataObject
*/
function getTags()
{
- return array_filter(explode("|", strval($this->tags)));
+ $result = array();
+
+ $tags = new Status_network_tag();
+ $tags->site_id = $this->site_id;
+ if ($tags->find()) {
+ while ($tags->fetch()) {
+ $result[] = $tags->tag;
+ }
+ }
+
+ // XXX : for backwards compatibility
+ if (empty($result)) {
+ return explode('|', $this->tags);
+ }
+
+ return $result;
}
/**
+ * Save a given set of tags
+ * @param array tags
+ */
+ function setTags($tags)
+ {
+ $this->clearTags();
+ foreach ($tags as $tag) {
+ if (!empty($tag)) {
+ $snt = new Status_network_tag();
+ $snt->site_id = $this->site_id;
+ $snt->tag = $tag;
+ $snt->created = common_sql_now();
+
+ $id = $snt->insert();
+ if (!$id) {
+ // TRANS: Exception thrown when a tag cannot be saved.
+ throw new Exception(_("Unable to save tag."));
+ }
+ }
+ }
+
+ return true;
+ }
+
+ function clearTags()
+ {
+ $tag = new Status_network_tag();
+ $tag->site_id = $this->site_id;
+
+ if ($tag->find()) {
+ while($tag->fetch()) {
+ $tag->delete();
+ }
+ }
+
+ $tag->free();
+ }
+
+ /**
* Check if this site record has a particular meta-info tag attached.
* @param string $tag
* @return bool
diff --git a/classes/Status_network_tag.php b/classes/Status_network_tag.php
new file mode 100644
index 000000000..18c508bc8
--- /dev/null
+++ b/classes/Status_network_tag.php
@@ -0,0 +1,69 @@
+<?php
+/*
+ * StatusNet - the distributed open-source microblogging tool
+ * Copyright (C) 2008, 2009, 2010 StatusNet, Inc.
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+
+if (!defined('STATUSNET')) { exit(1); }
+
+class Status_network_tag extends Safe_DataObject
+{
+ ###START_AUTOCODE
+ /* the code below is auto generated do not remove the above tag */
+
+ public $__table = 'status_network_tag'; // table name
+ public $site_id; // int(4) primary_key not_null
+ public $tag; // varchar(64) primary_key not_null
+ public $created; // datetime() not_null
+
+
+ function __construct()
+ {
+ global $config;
+ global $_DB_DATAOBJECT;
+
+ $sn = new Status_network();
+ $sn->_connect();
+
+ $config['db']['table_'. $this->__table] = $sn->_database;
+
+ $this->_connect();
+ }
+
+
+ /* Static get */
+ function staticGet($k,$v=null)
+ {
+ $i = DB_DataObject::staticGet('Status_network_tag',$k,$v);
+
+ // Don't use local process cache; if we're fetching multiple
+ // times it's because we're reloading it in a long-running
+ // process; we need a fresh copy!
+ global $_DB_DATAOBJECT;
+ unset($_DB_DATAOBJECT['CACHE']['status_network_tag']);
+ return $i;
+ }
+
+ /* the code above is auto generated do not remove the tag below */
+ ###END_AUTOCODE
+
+
+
+ function pkeyGet($kv)
+ {
+ return Memcached_DataObject::pkeyGet('Status_network_tag', $kv);
+ }
+}
diff --git a/classes/Subscription.php b/classes/Subscription.php
index 60c12cccc..0225ed4df 100644
--- a/classes/Subscription.php
+++ b/classes/Subscription.php
@@ -71,14 +71,17 @@ class Subscription extends Memcached_DataObject
}
if (!$subscriber->hasRight(Right::SUBSCRIBE)) {
+ // TRANS: Exception thrown when trying to subscribe while being banned from subscribing.
throw new Exception(_('You have been banned from subscribing.'));
}
if (self::exists($subscriber, $other)) {
+ // TRANS: Exception thrown when trying to subscribe while already subscribed.
throw new Exception(_('Already subscribed!'));
}
if ($other->hasBlocked($subscriber)) {
+ // TRANS: Exception thrown when trying to subscribe to a user who has blocked the subscribing user.
throw new Exception(_('User has blocked you.'));
}
@@ -88,8 +91,8 @@ class Subscription extends Memcached_DataObject
self::blow('user:notices_with_friends:%d', $subscriber->id);
- $subscriber->blowSubscriptionsCount();
- $other->blowSubscribersCount();
+ $subscriber->blowSubscriptionCount();
+ $other->blowSubscriberCount();
$otherUser = User::staticGet('id', $other->id);
@@ -129,6 +132,7 @@ class Subscription extends Memcached_DataObject
if (!$result) {
common_log_db_error($sub, 'INSERT', __FILE__);
+ // TRANS: Exception thrown when a subscription could not be stored on the server.
throw new Exception(_('Could not save subscription.'));
}
@@ -160,17 +164,18 @@ class Subscription extends Memcached_DataObject
* Cancel a subscription
*
*/
-
function cancel($subscriber, $other)
{
if (!self::exists($subscriber, $other)) {
+ // TRANS: Exception thrown when trying to unsibscribe without a subscription.
throw new Exception(_('Not subscribed!'));
}
// Don't allow deleting self subs
if ($subscriber->id == $other->id) {
- throw new Exception(_('Couldn\'t delete self-subscription.'));
+ // TRANS: Exception thrown when trying to unsubscribe a user from themselves.
+ throw new Exception(_('Could not delete self-subscription.'));
}
if (Event::handle('StartUnsubscribe', array($subscriber, $other))) {
@@ -197,7 +202,8 @@ class Subscription extends Memcached_DataObject
if (!$result) {
common_log_db_error($token, 'DELETE', __FILE__);
- throw new Exception(_('Couldn\'t delete subscription OMB token.'));
+ // TRANS: Exception thrown when the OMB token for a subscription could not deleted on the server.
+ throw new Exception(_('Could not delete subscription OMB token.'));
}
} else {
common_log(LOG_ERR, "Couldn't find credentials with token {$token->tok}");
@@ -208,13 +214,14 @@ class Subscription extends Memcached_DataObject
if (!$result) {
common_log_db_error($sub, 'DELETE', __FILE__);
- throw new Exception(_('Couldn\'t delete subscription.'));
+ // TRANS: Exception thrown when a subscription could not be deleted on the server.
+ throw new Exception(_('Could not delete subscription.'));
}
self::blow('user:notices_with_friends:%d', $subscriber->id);
- $subscriber->blowSubscriptionsCount();
- $other->blowSubscribersCount();
+ $subscriber->blowSubscriptionCount();
+ $other->blowSubscriberCount();
Event::handle('EndUnsubscribe', array($subscriber, $other));
}
diff --git a/classes/User.php b/classes/User.php
index 8ad2ec63d..8033229c4 100644
--- a/classes/User.php
+++ b/classes/User.php
@@ -360,11 +360,12 @@ class User extends Memcached_DataObject
__FILE__);
} else {
$notice = Notice::saveNew($welcomeuser->id,
+ // TRANS: Notice given on user registration.
+ // TRANS: %1$s is the sitename, $2$s is the registering user's nickname.
sprintf(_('Welcome to %1$s, @%2$s!'),
common_config('site', 'name'),
$user->nickname),
'system');
-
}
}
@@ -375,7 +376,6 @@ class User extends Memcached_DataObject
}
// Things we do when the email changes
-
function emailChanged()
{
@@ -464,9 +464,9 @@ class User extends Memcached_DataObject
return $profile->getNotices($offset, $limit, $since_id, $before_id);
}
- function favoriteNotices($offset=0, $limit=NOTICES_PER_PAGE, $own=false)
+ function favoriteNotices($own=false, $offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $max_id=0)
{
- $ids = Fave::stream($this->id, $offset, $limit, $own);
+ $ids = Fave::stream($this->id, $offset, $limit, $own, $since_id, $max_id);
return Notice::getStreamByIds($ids);
}
@@ -524,9 +524,9 @@ class User extends Memcached_DataObject
if ($this->id == $other->id) {
common_log(LOG_WARNING,
sprintf(
- "Profile ID %d (%s) tried to block his or herself.",
- $profile->id,
- $profile->nickname
+ "Profile ID %d (%s) tried to block themself.",
+ $this->id,
+ $this->nickname
)
);
return false;
@@ -548,12 +548,9 @@ class User extends Memcached_DataObject
return false;
}
- // Cancel their subscription, if it exists
-
- $otherUser = User::staticGet('id', $other->id);
-
- if (!empty($otherUser)) {
- subs_unsubscribe_to($otherUser, $this->getProfile());
+ $self = $this->getProfile();
+ if (Subscription::exists($other, $self)) {
+ Subscription::cancel($other, $self);
}
$block->query('COMMIT');
@@ -670,8 +667,12 @@ class User extends Memcached_DataObject
function delete()
{
- $profile = $this->getProfile();
- $profile->delete();
+ try {
+ $profile = $this->getProfile();
+ $profile->delete();
+ } catch (UserNoProfileException $unp) {
+ common_log(LOG_INFO, "User {$this->nickname} has no profile; continuing deletion.");
+ }
$related = array('Fave',
'Confirm_address',
@@ -679,6 +680,7 @@ class User extends Memcached_DataObject
'Foreign_link',
'Invitation',
);
+
Event::handle('UserDeleteRelated', array($this, &$related));
foreach ($related as $cls) {
diff --git a/classes/User_group.php b/classes/User_group.php
index 110f08301..0b83cfd47 100644
--- a/classes/User_group.php
+++ b/classes/User_group.php
@@ -154,6 +154,21 @@ class User_group extends Memcached_DataObject
return $members;
}
+ function getMemberCount()
+ {
+ // XXX: WORM cache this
+
+ $members = $this->getMembers();
+ $member_count = 0;
+
+ /** $member->count() doesn't work. */
+ while ($members->fetch()) {
+ $member_count++;
+ }
+
+ return $member_count;
+ }
+
function getAdmins($offset=0, $limit=null)
{
$qry =
@@ -477,6 +492,7 @@ class User_group extends Memcached_DataObject
if (!$result) {
common_log_db_error($group, 'INSERT', __FILE__);
+ // TRANS: Server exception thrown when creating a group failed.
throw new ServerException(_('Could not create group.'));
}
@@ -486,6 +502,7 @@ class User_group extends Memcached_DataObject
$result = $group->update($orig);
if (!$result) {
common_log_db_error($group, 'UPDATE', __FILE__);
+ // TRANS: Server exception thrown when updating a group URI failed.
throw new ServerException(_('Could not set group URI.'));
}
}
@@ -493,6 +510,7 @@ class User_group extends Memcached_DataObject
$result = $group->setAliases($aliases);
if (!$result) {
+ // TRANS: Server exception thrown when creating group aliases failed.
throw new ServerException(_('Could not create aliases.'));
}
@@ -507,6 +525,7 @@ class User_group extends Memcached_DataObject
if (!$result) {
common_log_db_error($member, 'INSERT', __FILE__);
+ // TRANS: Server exception thrown when setting group membership failed.
throw new ServerException(_('Could not set group membership.'));
}
@@ -521,6 +540,7 @@ class User_group extends Memcached_DataObject
if (!$result) {
common_log_db_error($local_group, 'INSERT', __FILE__);
+ // TRANS: Server exception thrown when saving local group information failed.
throw new ServerException(_('Could not save local group info.'));
}
}
diff --git a/classes/status_network.ini b/classes/status_network.ini
index adb71cba7..b298daae4 100644
--- a/classes/status_network.ini
+++ b/classes/status_network.ini
@@ -1,4 +1,5 @@
[status_network]
+site_id = 129
nickname = 130
hostname = 2
pathname = 2
@@ -11,9 +12,19 @@ theme = 2
logo = 2
created = 142
modified = 384
-tags = 34
[status_network__keys]
-nickname = K
+site_id = K
+nickname = U
hostname = U
pathname = U
+
+[status_network_tag]
+site_id = 129
+tag = 130
+created = 142
+
+[status_network_tag__keys]
+site_id = K
+tag = K
+