3 * StatusNet - the distributed open-source microblogging tool
4 * Copyright (C) 2008-2011 StatusNet, Inc.
6 * This program is free software: you can redistribute it and/or modify
7 * it under the terms of the GNU Affero General Public License as published by
8 * the Free Software Foundation, either version 3 of the License, or
9 * (at your option) any later version.
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU Affero General Public License for more details.
16 * You should have received a copy of the GNU Affero General Public License
17 * along with this program. If not, see <http://www.gnu.org/licenses/>.
21 * @author Brenda Wallace <shiny@cpan.org>
22 * @author Christopher Vollick <psycotica0@gmail.com>
23 * @author CiaranG <ciaran@ciarang.com>
24 * @author Craig Andrews <candrews@integralblue.com>
25 * @author Evan Prodromou <evan@controlezvous.ca>
26 * @author Gina Haeussge <osd@foosel.net>
27 * @author Jeffery To <jeffery.to@gmail.com>
28 * @author Mike Cochrane <mikec@mikenz.geek.nz>
29 * @author Robin Millette <millette@controlyourself.ca>
30 * @author Sarven Capadisli <csarven@controlyourself.ca>
31 * @author Tom Adams <tom@holizz.com>
32 * @copyright 2009 Free Software Foundation, Inc http://www.fsf.org
33 * @license GNU Affero General Public License http://www.gnu.org/licenses/
36 if (!defined('STATUSNET') && !defined('LACONICA')) {
41 * Table Definition for notice
43 require_once INSTALLDIR.'/classes/Memcached_DataObject.php';
45 /* We keep 200 notices, the max number of notices available per API request,
46 * in the memcached cache. */
48 define('NOTICE_CACHE_WINDOW', CachingNoticeStream::CACHE_WINDOW);
50 define('MAX_BOXCARS', 128);
52 class Notice extends Managed_DataObject
55 /* the code below is auto generated do not remove the above tag */
57 public $__table = 'notice'; // table name
58 public $id; // int(4) primary_key not_null
59 public $profile_id; // int(4) multiple_key not_null
60 public $uri; // varchar(255) unique_key
61 public $content; // text
62 public $rendered; // text
63 public $url; // varchar(255)
64 public $created; // datetime multiple_key not_null default_0000-00-00%2000%3A00%3A00
65 public $modified; // timestamp not_null default_CURRENT_TIMESTAMP
66 public $reply_to; // int(4)
67 public $is_local; // int(4)
68 public $source; // varchar(32)
69 public $conversation; // int(4)
70 public $lat; // decimal(10,7)
71 public $lon; // decimal(10,7)
72 public $location_id; // int(4)
73 public $location_ns; // int(4)
74 public $repeat_of; // int(4)
75 public $object_type; // varchar(255)
76 public $scope; // int(4)
79 function staticGet($k,$v=NULL)
81 return Memcached_DataObject::staticGet('Notice',$k,$v);
84 /* the code above is auto generated do not remove the tag below */
87 public static function schemaDef()
91 'id' => array('type' => 'serial', 'not null' => true, 'description' => 'unique identifier'),
92 'profile_id' => array('type' => 'int', 'not null' => true, 'description' => 'who made the update'),
93 'uri' => array('type' => 'varchar', 'length' => 255, 'description' => 'universally unique identifier, usually a tag URI'),
94 'content' => array('type' => 'text', 'description' => 'update content'),
95 'rendered' => array('type' => 'text', 'description' => 'HTML version of the content'),
96 'url' => array('type' => 'varchar', 'length' => 255, 'description' => 'URL of any attachment (image, video, bookmark, whatever)'),
97 'created' => array('type' => 'datetime', 'not null' => true, 'description' => 'date this record was created'),
98 'modified' => array('type' => 'timestamp', 'not null' => true, 'description' => 'date this record was modified'),
99 'reply_to' => array('type' => 'int', 'description' => 'notice replied to (usually a guess)'),
100 'is_local' => array('type' => 'int', 'size' => 'tiny', 'default' => 0, 'description' => 'notice was generated by a user'),
101 'source' => array('type' => 'varchar', 'length' => 32, 'description' => 'source of comment, like "web", "im", or "clientname"'),
102 'conversation' => array('type' => 'int', 'description' => 'id of root notice in this conversation'),
103 'lat' => array('type' => 'numeric', 'precision' => 10, 'scale' => 7, 'description' => 'latitude'),
104 'lon' => array('type' => 'numeric', 'precision' => 10, 'scale' => 7, 'description' => 'longitude'),
105 'location_id' => array('type' => 'int', 'description' => 'location id if possible'),
106 'location_ns' => array('type' => 'int', 'description' => 'namespace for location'),
107 'repeat_of' => array('type' => 'int', 'description' => 'notice this is a repeat of'),
108 'object_type' => array('type' => 'varchar', 'length' => 255, 'description' => 'URI representing activity streams object type', 'default' => 'http://activitystrea.ms/schema/1.0/note'),
109 'scope' => array('type' => 'int',
111 'description' => 'bit map for distribution scope; 0 = everywhere; 1 = this server only; 2 = addressees; 4 = followers'),
113 'primary key' => array('id'),
114 'unique keys' => array(
115 'notice_uri_key' => array('uri'),
117 'foreign keys' => array(
118 'notice_profile_id_fkey' => array('profile', array('profile_id' => 'id')),
119 'notice_reply_to_fkey' => array('notice', array('reply_to' => 'id')),
120 'notice_conversation_fkey' => array('conversation', array('conversation' => 'id')), # note... used to refer to notice.id
121 'notice_repeat_of_fkey' => array('notice', array('repeat_of' => 'id')), # @fixme: what about repeats of deleted notices?
124 'notice_profile_id_idx' => array('profile_id', 'created', 'id'),
125 'notice_conversation_idx' => array('conversation'),
126 'notice_created_idx' => array('created'),
127 'notice_replyto_idx' => array('reply_to'),
128 'notice_repeatof_idx' => array('repeat_of'),
130 'fulltext indexes' => array(
131 'content' => array('content'),
136 function multiGet($kc, $kvs, $skipNulls=true)
138 return Memcached_DataObject::multiGet('Notice', $kc, $kvs, $skipNulls);
142 const LOCAL_PUBLIC = 1;
144 const LOCAL_NONPUBLIC = -1;
147 const PUBLIC_SCOPE = 0; // Useful fake constant
148 const SITE_SCOPE = 1;
149 const ADDRESSEE_SCOPE = 2;
150 const GROUP_SCOPE = 4;
151 const FOLLOWER_SCOPE = 8;
153 protected $_profile = -1;
155 function getProfile()
157 if (is_int($this->_profile) && $this->_profile == -1) {
158 $this->_setProfile(Profile::staticGet('id', $this->profile_id));
160 if (empty($this->_profile)) {
161 // TRANS: Server exception thrown when a user profile for a notice cannot be found.
162 // TRANS: %1$d is a profile ID (number), %2$d is a notice ID (number).
163 throw new ServerException(sprintf(_('No such profile (%1$d) for notice (%2$d).'), $this->profile_id, $this->id));
167 return $this->_profile;
170 function _setProfile($profile)
172 $this->_profile = $profile;
177 // For auditing purposes, save a record that the notice
180 // @fixme we have some cases where things get re-run and so the
182 $deleted = Deleted_notice::staticGet('id', $this->id);
185 $deleted = Deleted_notice::staticGet('uri', $this->uri);
189 $deleted = new Deleted_notice();
191 $deleted->id = $this->id;
192 $deleted->profile_id = $this->profile_id;
193 $deleted->uri = $this->uri;
194 $deleted->created = $this->created;
195 $deleted->deleted = common_sql_now();
200 if (Event::handle('NoticeDeleteRelated', array($this))) {
202 // Clear related records
204 $this->clearReplies();
205 $this->clearRepeats();
208 $this->clearGroupInboxes();
211 // NOTE: we don't clear inboxes
212 // NOTE: we don't clear queue items
215 $result = parent::delete();
217 $this->blowOnDelete();
222 * Extract #hashtags from this notice's content and save them to the database.
226 /* extract all #hastags */
227 $count = preg_match_all('/(?:^|\s)#([\pL\pN_\-\.]{1,64})/u', strtolower($this->content), $match);
232 /* Add them to the database */
233 return $this->saveKnownTags($match[1]);
237 * Record the given set of hash tags in the db for this notice.
238 * Given tag strings will be normalized and checked for dupes.
240 function saveKnownTags($hashtags)
242 //turn each into their canonical tag
243 //this is needed to remove dupes before saving e.g. #hash.tag = #hashtag
244 for($i=0; $i<count($hashtags); $i++) {
245 /* elide characters we don't want in the tag */
246 $hashtags[$i] = common_canonical_tag($hashtags[$i]);
249 foreach(array_unique($hashtags) as $hashtag) {
250 $this->saveTag($hashtag);
251 self::blow('profile:notice_ids_tagged:%d:%s', $this->profile_id, $hashtag);
257 * Record a single hash tag as associated with this notice.
258 * Tag format and uniqueness must be validated by caller.
260 function saveTag($hashtag)
262 $tag = new Notice_tag();
263 $tag->notice_id = $this->id;
264 $tag->tag = $hashtag;
265 $tag->created = $this->created;
266 $id = $tag->insert();
269 // TRANS: Server exception. %s are the error details.
270 throw new ServerException(sprintf(_('Database error inserting hashtag: %s.'),
271 $last_error->message));
275 // if it's saved, blow its cache
276 $tag->blowCache(false);
280 * Save a new notice and push it out to subscribers' inboxes.
281 * Poster's permissions are checked before sending.
283 * @param int $profile_id Profile ID of the poster
284 * @param string $content source message text; links may be shortened
285 * per current user's preference
286 * @param string $source source key ('web', 'api', etc)
287 * @param array $options Associative array of optional properties:
288 * string 'created' timestamp of notice; defaults to now
289 * int 'is_local' source/gateway ID, one of:
290 * Notice::LOCAL_PUBLIC - Local, ok to appear in public timeline
291 * Notice::REMOTE - Sent from a remote service;
292 * hide from public timeline but show in
293 * local "and friends" timelines
294 * Notice::LOCAL_NONPUBLIC - Local, but hide from public timeline
295 * Notice::GATEWAY - From another non-OStatus service;
296 * will not appear in public views
297 * float 'lat' decimal latitude for geolocation
298 * float 'lon' decimal longitude for geolocation
299 * int 'location_id' geoname identifier
300 * int 'location_ns' geoname namespace to interpret location_id
301 * int 'reply_to'; notice ID this is a reply to
302 * int 'repeat_of'; notice ID this is a repeat of
303 * string 'uri' unique ID for notice; defaults to local notice URL
304 * string 'url' permalink to notice; defaults to local notice URL
305 * string 'rendered' rendered HTML version of content
306 * array 'replies' list of profile URIs for reply delivery in
307 * place of extracting @-replies from content.
308 * array 'groups' list of group IDs to deliver to, in place of
309 * extracting ! tags from content
310 * array 'tags' list of hashtag strings to save with the notice
311 * in place of extracting # tags from content
312 * array 'urls' list of attached/referred URLs to save with the
313 * notice in place of extracting links from content
314 * boolean 'distribute' whether to distribute the notice, default true
315 * string 'object_type' URL of the associated object type (default ActivityObject::NOTE)
316 * int 'scope' Scope bitmask; default to SITE_SCOPE on private sites, 0 otherwise
318 * @fixme tag override
321 * @throws ClientException
323 static function saveNew($profile_id, $content, $source, $options=null) {
324 $defaults = array('uri' => null,
329 'distribute' => true);
331 if (!empty($options) && is_array($options)) {
332 $options = array_merge($defaults, $options);
338 if (!isset($is_local)) {
339 $is_local = Notice::LOCAL_PUBLIC;
342 $profile = Profile::staticGet('id', $profile_id);
343 $user = User::staticGet('id', $profile_id);
345 // Use the local user's shortening preferences, if applicable.
346 $final = $user->shortenLinks($content);
348 $final = common_shorten_links($content);
351 if (Notice::contentTooLong($final)) {
352 // TRANS: Client exception thrown if a notice contains too many characters.
353 throw new ClientException(_('Problem saving notice. Too long.'));
356 if (empty($profile)) {
357 // TRANS: Client exception thrown when trying to save a notice for an unknown user.
358 throw new ClientException(_('Problem saving notice. Unknown user.'));
361 if (common_config('throttle', 'enabled') && !Notice::checkEditThrottle($profile_id)) {
362 common_log(LOG_WARNING, 'Excessive posting by profile #' . $profile_id . '; throttled.');
363 // TRANS: Client exception thrown when a user tries to post too many notices in a given time frame.
364 throw new ClientException(_('Too many notices too fast; take a breather '.
365 'and post again in a few minutes.'));
368 if (common_config('site', 'dupelimit') > 0 && !Notice::checkDupes($profile_id, $final)) {
369 common_log(LOG_WARNING, 'Dupe posting by profile #' . $profile_id . '; throttled.');
370 // TRANS: Client exception thrown when a user tries to post too many duplicate notices in a given time frame.
371 throw new ClientException(_('Too many duplicate messages too quickly;'.
372 ' take a breather and post again in a few minutes.'));
375 if (!$profile->hasRight(Right::NEWNOTICE)) {
376 common_log(LOG_WARNING, "Attempted post from user disallowed to post: " . $profile->nickname);
378 // TRANS: Client exception thrown when a user tries to post while being banned.
379 throw new ClientException(_('You are banned from posting notices on this site.'), 403);
382 $notice = new Notice();
383 $notice->profile_id = $profile_id;
385 $autosource = common_config('public', 'autosource');
387 // Sandboxed are non-false, but not 1, either
389 if (!$profile->hasRight(Right::PUBLICNOTICE) ||
390 ($source && $autosource && in_array($source, $autosource))) {
391 $notice->is_local = Notice::LOCAL_NONPUBLIC;
393 $notice->is_local = $is_local;
396 if (!empty($created)) {
397 $notice->created = $created;
399 $notice->created = common_sql_now();
402 $notice->content = $final;
404 $notice->source = $source;
408 // Get the groups here so we can figure out replies and such
410 if (!isset($groups)) {
411 $groups = self::groupsFromText($notice->content, $profile);
416 // Handle repeat case
418 if (isset($repeat_of)) {
420 // Check for a private one
422 $repeat = Notice::staticGet('id', $repeat_of);
424 if (empty($repeat)) {
425 // TRANS: Client exception thrown in notice when trying to repeat a missing or deleted notice.
426 throw new ClientException(_('Cannot repeat; original notice is missing or deleted.'));
429 if ($profile->id == $repeat->profile_id) {
430 // TRANS: Client error displayed when trying to repeat an own notice.
431 throw new ClientException(_('You cannot repeat your own notice.'));
434 if ($repeat->scope != Notice::SITE_SCOPE &&
435 $repeat->scope != Notice::PUBLIC_SCOPE) {
436 // TRANS: Client error displayed when trying to repeat a non-public notice.
437 throw new ClientException(_('Cannot repeat a private notice.'), 403);
440 if (!$repeat->inScope($profile)) {
441 // The generic checks above should cover this, but let's be sure!
442 // TRANS: Client error displayed when trying to repeat a notice you cannot access.
443 throw new ClientException(_('Cannot repeat a notice you cannot read.'), 403);
446 if ($profile->hasRepeated($repeat->id)) {
447 // TRANS: Client error displayed when trying to repeat an already repeated notice.
448 throw new ClientException(_('You already repeated that notice.'));
451 $notice->repeat_of = $repeat_of;
453 $reply = self::getReplyTo($reply_to, $profile_id, $source, $final);
455 if (!empty($reply)) {
457 if (!$reply->inScope($profile)) {
458 // TRANS: Client error displayed when trying to reply to a notice a the target has no access to.
459 // TRANS: %1$s is a user nickname, %2$d is a notice ID (number).
460 throw new ClientException(sprintf(_('%1$s has no access to notice %2$d.'),
461 $profile->nickname, $reply->id), 403);
464 $notice->reply_to = $reply->id;
465 $notice->conversation = $reply->conversation;
467 // If the original is private to a group, and notice has no group specified,
468 // make it to the same group(s)
470 if (empty($groups) && ($reply->scope | Notice::GROUP_SCOPE)) {
472 $replyGroups = $reply->getGroups();
473 foreach ($replyGroups as $group) {
474 if ($profile->isMember($group)) {
475 $groups[] = $group->id;
484 if (!empty($lat) && !empty($lon)) {
489 if (!empty($location_ns) && !empty($location_id)) {
490 $notice->location_id = $location_id;
491 $notice->location_ns = $location_ns;
494 if (!empty($rendered)) {
495 $notice->rendered = $rendered;
497 $notice->rendered = common_render_content($final, $notice);
500 if (empty($object_type)) {
501 $notice->object_type = (empty($notice->reply_to)) ? ActivityObject::NOTE : ActivityObject::COMMENT;
503 $notice->object_type = $object_type;
506 if (is_null($scope)) { // 0 is a valid value
507 if (!empty($reply)) {
508 $notice->scope = $reply->scope;
510 $notice->scope = self::defaultScope();
513 $notice->scope = $scope;
516 // For private streams
518 $user = $profile->getUser();
521 if ($user->private_stream &&
522 ($notice->scope == Notice::PUBLIC_SCOPE ||
523 $notice->scope == Notice::SITE_SCOPE)) {
524 $notice->scope |= Notice::FOLLOWER_SCOPE;
528 // Force the scope for private groups
530 foreach ($groups as $groupId) {
531 $group = User_group::staticGet('id', $groupId);
532 if (!empty($group)) {
533 if ($group->force_scope) {
534 $notice->scope |= Notice::GROUP_SCOPE;
540 if (Event::handle('StartNoticeSave', array(&$notice))) {
542 // XXX: some of these functions write to the DB
544 $id = $notice->insert();
547 common_log_db_error($notice, 'INSERT', __FILE__);
548 // TRANS: Server exception thrown when a notice cannot be saved.
549 throw new ServerException(_('Problem saving notice.'));
552 // Update ID-dependent columns: URI, conversation
554 $orig = clone($notice);
559 $notice->uri = common_notice_uri($notice);
563 // If it's not part of a conversation, it's
564 // the beginning of a new conversation.
566 if (empty($notice->conversation)) {
567 $conv = Conversation::create();
568 $notice->conversation = $conv->id;
573 if (!$notice->update($orig)) {
574 common_log_db_error($notice, 'UPDATE', __FILE__);
575 // TRANS: Server exception thrown when a notice cannot be updated.
576 throw new ServerException(_('Problem saving notice.'));
582 // Clear the cache for subscribed users, so they'll update at next request
583 // XXX: someone clever could prepend instead of clearing the cache
585 $notice->blowOnInsert();
587 // Save per-notice metadata...
589 if (isset($replies)) {
590 $notice->saveKnownReplies($replies);
592 $notice->saveReplies();
596 $notice->saveKnownTags($tags);
601 // Note: groups may save tags, so must be run after tags are saved
602 // to avoid errors on duplicates.
603 // Note: groups should always be set.
605 $notice->saveKnownGroups($groups);
608 $notice->saveKnownUrls($urls);
614 // Prepare inbox delivery, may be queued to background.
615 $notice->distribute();
621 function blowOnInsert($conversation = false)
623 $this->blowStream('profile:notice_ids:%d', $this->profile_id);
625 if ($this->isPublic()) {
626 $this->blowStream('public');
629 self::blow('notice:list-ids:conversation:%s', $this->conversation);
630 self::blow('conversation::notice_count:%d', $this->conversation);
632 if (!empty($this->repeat_of)) {
633 // XXX: we should probably only use one of these
634 $this->blowStream('notice:repeats:%d', $this->repeat_of);
635 self::blow('notice:list-ids:repeat_of:%d', $this->repeat_of);
638 $original = Notice::staticGet('id', $this->repeat_of);
640 if (!empty($original)) {
641 $originalUser = User::staticGet('id', $original->profile_id);
642 if (!empty($originalUser)) {
643 $this->blowStream('user:repeats_of_me:%d', $originalUser->id);
647 $profile = Profile::staticGet($this->profile_id);
649 if (!empty($profile)) {
650 $profile->blowNoticeCount();
653 $ptags = $this->getProfileTags();
654 foreach ($ptags as $ptag) {
655 $ptag->blowNoticeStreamCache();
660 * Clear cache entries related to this notice at delete time.
661 * Necessary to avoid breaking paging on public, profile timelines.
663 function blowOnDelete()
665 $this->blowOnInsert();
667 self::blow('profile:notice_ids:%d;last', $this->profile_id);
669 if ($this->isPublic()) {
670 self::blow('public;last');
673 self::blow('fave:by_notice', $this->id);
675 if ($this->conversation) {
676 // In case we're the first, will need to calc a new root.
677 self::blow('notice:conversation_root:%d', $this->conversation);
680 $ptags = $this->getProfileTags();
681 foreach ($ptags as $ptag) {
682 $ptag->blowNoticeStreamCache(true);
686 function blowStream()
688 $c = self::memcache();
694 $args = func_get_args();
696 $format = array_shift($args);
698 $keyPart = vsprintf($format, $args);
700 $cacheKey = Cache::key($keyPart);
702 $c->delete($cacheKey);
704 // delete the "last" stream, too, if this notice is
705 // older than the top of that stream
707 $lastKey = $cacheKey.';last';
709 $lastStr = $c->get($lastKey);
711 if ($lastStr !== false) {
712 $window = explode(',', $lastStr);
713 $lastID = $window[0];
714 $lastNotice = Notice::staticGet('id', $lastID);
715 if (empty($lastNotice) // just weird
716 || strtotime($lastNotice->created) >= strtotime($this->created)) {
717 $c->delete($lastKey);
722 /** save all urls in the notice to the db
724 * follow redirects and save all available file information
725 * (mimetype, date, size, oembed, etc.)
729 function saveUrls() {
730 if (common_config('attachments', 'process_links')) {
731 common_replace_urls_callback($this->content, array($this, 'saveUrl'), $this->id);
736 * Save the given URLs as related links/attachments to the db
738 * follow redirects and save all available file information
739 * (mimetype, date, size, oembed, etc.)
743 function saveKnownUrls($urls)
745 if (common_config('attachments', 'process_links')) {
746 // @fixme validation?
747 foreach (array_unique($urls) as $url) {
748 File::processNew($url, $this->id);
756 function saveUrl($url, $notice_id) {
757 File::processNew($url, $notice_id);
760 static function checkDupes($profile_id, $content) {
761 $profile = Profile::staticGet($profile_id);
762 if (empty($profile)) {
765 $notice = $profile->getNotices(0, CachingNoticeStream::CACHE_WINDOW);
766 if (!empty($notice)) {
768 while ($notice->fetch()) {
769 if (time() - strtotime($notice->created) >= common_config('site', 'dupelimit')) {
771 } else if ($notice->content == $content) {
776 // If we get here, oldest item in cache window is not
777 // old enough for dupe limit; do direct check against DB
778 $notice = new Notice();
779 $notice->profile_id = $profile_id;
780 $notice->content = $content;
781 $threshold = common_sql_date(time() - common_config('site', 'dupelimit'));
782 $notice->whereAdd(sprintf("created > '%s'", $notice->escape($threshold)));
784 $cnt = $notice->count();
788 static function checkEditThrottle($profile_id) {
789 $profile = Profile::staticGet($profile_id);
790 if (empty($profile)) {
793 // Get the Nth notice
794 $notice = $profile->getNotices(common_config('throttle', 'count') - 1, 1);
795 if ($notice && $notice->fetch()) {
796 // If the Nth notice was posted less than timespan seconds ago
797 if (time() - strtotime($notice->created) <= common_config('throttle', 'timespan')) {
802 // Either not N notices in the stream, OR the Nth was not posted within timespan seconds
806 protected $_attachments = -1;
808 function attachments() {
810 if ($this->_attachments != -1) {
811 return $this->_attachments;
814 $f2ps = Memcached_DataObject::listGet('File_to_post', 'post_id', array($this->id));
818 foreach ($f2ps[$this->id] as $f2p) {
819 $ids[] = $f2p->file_id;
822 $files = Memcached_DataObject::multiGet('File', 'id', $ids);
824 $this->_attachments = $files->fetchAll();
826 return $this->_attachments;
829 function _setAttachments($attachments)
831 $this->_attachments = $attachments;
834 function publicStream($offset=0, $limit=20, $since_id=0, $max_id=0)
836 $stream = new PublicNoticeStream();
837 return $stream->getNotices($offset, $limit, $since_id, $max_id);
841 function conversationStream($id, $offset=0, $limit=20, $since_id=0, $max_id=0)
843 $stream = new ConversationNoticeStream($id);
845 return $stream->getNotices($offset, $limit, $since_id, $max_id);
849 * Is this notice part of an active conversation?
851 * @return boolean true if other messages exist in the same
852 * conversation, false if this is the only one
854 function hasConversation()
856 if (!empty($this->conversation)) {
857 $conversation = Notice::conversationStream(
863 if ($conversation->N > 0) {
871 * Grab the earliest notice from this conversation.
873 * @return Notice or null
875 function conversationRoot($profile=-1)
877 // XXX: can this happen?
879 if (empty($this->conversation)) {
883 // Get the current profile if not specified
885 if (is_int($profile) && $profile == -1) {
886 $profile = Profile::current();
889 // If this notice is out of scope, no root for you!
891 if (!$this->inScope($profile)) {
895 // If this isn't a reply to anything, then it's its own
898 if (empty($this->reply_to)) {
902 if (is_null($profile)) {
903 $keypart = sprintf('notice:conversation_root:%d:null', $this->id);
905 $keypart = sprintf('notice:conversation_root:%d:%d',
910 $root = self::cacheGet($keypart);
912 if ($root !== false && $root->inScope($profile)) {
918 $parent = $last->getOriginal();
919 if (!empty($parent) && $parent->inScope($profile)) {
926 } while (!empty($parent));
928 self::cacheSet($keypart, $root);
935 * Pull up a full list of local recipients who will be getting
936 * this notice in their inbox. Results will be cached, so don't
937 * change the input data wily-nilly!
939 * @param array $groups optional list of Group objects;
940 * if left empty, will be loaded from group_inbox records
941 * @param array $recipient optional list of reply profile ids
942 * if left empty, will be loaded from reply records
943 * @return array associating recipient user IDs with an inbox source constant
945 function whoGets($groups=null, $recipients=null)
947 $c = self::memcache();
950 $ni = $c->get(Cache::key('notice:who_gets:'.$this->id));
956 if (is_null($groups)) {
957 $groups = $this->getGroups();
960 if (is_null($recipients)) {
961 $recipients = $this->getReplies();
964 $users = $this->getSubscribedUsers();
965 $ptags = $this->getProfileTags();
967 // FIXME: kind of ignoring 'transitional'...
968 // we'll probably stop supporting inboxless mode
973 // Give plugins a chance to add folks in at start...
974 if (Event::handle('StartNoticeWhoGets', array($this, &$ni))) {
976 foreach ($users as $id) {
977 $ni[$id] = NOTICE_INBOX_SOURCE_SUB;
980 foreach ($groups as $group) {
981 $users = $group->getUserMembers();
982 foreach ($users as $id) {
983 if (!array_key_exists($id, $ni)) {
984 $ni[$id] = NOTICE_INBOX_SOURCE_GROUP;
989 foreach ($ptags as $ptag) {
990 $users = $ptag->getUserSubscribers();
991 foreach ($users as $id) {
992 if (!array_key_exists($id, $ni)) {
993 $user = User::staticGet('id', $id);
994 if (!$user->hasBlocked($profile)) {
995 $ni[$id] = NOTICE_INBOX_SOURCE_PROFILE_TAG;
1001 foreach ($recipients as $recipient) {
1002 if (!array_key_exists($recipient, $ni)) {
1003 $ni[$recipient] = NOTICE_INBOX_SOURCE_REPLY;
1006 // Exclude any deleted, non-local, or blocking recipients.
1007 $profile = $this->getProfile();
1008 $originalProfile = null;
1009 if ($this->repeat_of) {
1010 // Check blocks against the original notice's poster as well.
1011 $original = Notice::staticGet('id', $this->repeat_of);
1013 $originalProfile = $original->getProfile();
1016 foreach ($ni as $id => $source) {
1017 $user = User::staticGet('id', $id);
1018 if (empty($user) || $user->hasBlocked($profile) ||
1019 ($originalProfile && $user->hasBlocked($originalProfile))) {
1025 // Give plugins a chance to filter out...
1026 Event::handle('EndNoticeWhoGets', array($this, &$ni));
1030 // XXX: pack this data better
1031 $c->set(Cache::key('notice:who_gets:'.$this->id), $ni);
1038 * Adds this notice to the inboxes of each local user who should receive
1039 * it, based on author subscriptions, group memberships, and @-replies.
1041 * Warning: running a second time currently will make items appear
1042 * multiple times in users' inboxes.
1044 * @fixme make more robust against errors
1045 * @fixme break up massive deliveries to smaller background tasks
1047 * @param array $groups optional list of Group objects;
1048 * if left empty, will be loaded from group_inbox records
1049 * @param array $recipient optional list of reply profile ids
1050 * if left empty, will be loaded from reply records
1052 function addToInboxes($groups=null, $recipients=null)
1054 $ni = $this->whoGets($groups, $recipients);
1056 $ids = array_keys($ni);
1058 // We remove the author (if they're a local user),
1059 // since we'll have already done this in distribute()
1061 $i = array_search($this->profile_id, $ids);
1069 Inbox::bulkInsert($this->id, $ids);
1074 function getSubscribedUsers()
1078 if(common_config('db','quote_identifiers'))
1079 $user_table = '"user"';
1080 else $user_table = 'user';
1084 'FROM '. $user_table .' JOIN subscription '.
1085 'ON '. $user_table .'.id = subscription.subscriber ' .
1086 'WHERE subscription.subscribed = %d ';
1088 $user->query(sprintf($qry, $this->profile_id));
1092 while ($user->fetch()) {
1101 function getProfileTags()
1103 $profile = $this->getProfile();
1104 $list = $profile->getOtherTags($profile);
1107 while($list->fetch()) {
1108 $ptags[] = clone($list);
1115 * Record this notice to the given group inboxes for delivery.
1116 * Overrides the regular parsing of !group markup.
1118 * @param string $group_ids
1119 * @fixme might prefer URIs as identifiers, as for replies?
1120 * best with generalizations on user_group to support
1121 * remote groups better.
1123 function saveKnownGroups($group_ids)
1125 if (!is_array($group_ids)) {
1126 // TRANS: Server exception thrown when no array is provided to the method saveKnownGroups().
1127 throw new ServerException(_('Bad type provided to saveKnownGroups.'));
1131 foreach (array_unique($group_ids) as $id) {
1132 $group = User_group::staticGet('id', $id);
1134 common_log(LOG_ERR, "Local delivery to group id $id, $group->nickname");
1135 $result = $this->addToGroupInbox($group);
1137 common_log_db_error($gi, 'INSERT', __FILE__);
1140 if (common_config('group', 'addtag')) {
1141 // we automatically add a tag for every group name, too
1143 $tag = Notice_tag::pkeyGet(array('tag' => common_canonical_tag($group->nickname),
1144 'notice_id' => $this->id));
1146 if (is_null($tag)) {
1147 $this->saveTag($group->nickname);
1151 $groups[] = clone($group);
1153 common_log(LOG_ERR, "Local delivery to group id $id skipped, doesn't exist");
1161 * Parse !group delivery and record targets into group_inbox.
1162 * @return array of Group objects
1164 function saveGroups()
1166 // Don't save groups for repeats
1168 if (!empty($this->repeat_of)) {
1172 $profile = $this->getProfile();
1174 $groups = self::groupsFromText($this->content, $profile);
1176 /* Add them to the database */
1178 foreach ($groups as $group) {
1179 /* XXX: remote groups. */
1181 if (empty($group)) {
1186 if ($profile->isMember($group)) {
1188 $result = $this->addToGroupInbox($group);
1191 common_log_db_error($gi, 'INSERT', __FILE__);
1194 $groups[] = clone($group);
1201 function addToGroupInbox($group)
1203 $gi = Group_inbox::pkeyGet(array('group_id' => $group->id,
1204 'notice_id' => $this->id));
1208 $gi = new Group_inbox();
1210 $gi->group_id = $group->id;
1211 $gi->notice_id = $this->id;
1212 $gi->created = $this->created;
1214 $result = $gi->insert();
1217 common_log_db_error($gi, 'INSERT', __FILE__);
1218 // TRANS: Server exception thrown when an update for a group inbox fails.
1219 throw new ServerException(_('Problem saving group inbox.'));
1222 self::blow('user_group:notice_ids:%d', $gi->group_id);
1229 * Save reply records indicating that this notice needs to be
1230 * delivered to the local users with the given URIs.
1232 * Since this is expected to be used when saving foreign-sourced
1233 * messages, we won't deliver to any remote targets as that's the
1234 * source service's responsibility.
1236 * Mail notifications etc will be handled later.
1238 * @param array of unique identifier URIs for recipients
1240 function saveKnownReplies($uris)
1246 $sender = Profile::staticGet($this->profile_id);
1248 foreach (array_unique($uris) as $uri) {
1250 $profile = Profile::fromURI($uri);
1252 if (empty($profile)) {
1253 common_log(LOG_WARNING, "Unable to determine profile for URI '$uri'");
1257 if ($profile->hasBlocked($sender)) {
1258 common_log(LOG_INFO, "Not saving reply to profile {$profile->id} ($uri) from sender {$sender->id} because of a block.");
1262 $this->saveReply($profile->id);
1263 self::blow('reply:stream:%d', $profile->id);
1270 * Pull @-replies from this message's content in StatusNet markup format
1271 * and save reply records indicating that this message needs to be
1272 * delivered to those users.
1274 * Mail notifications to local profiles will be sent later.
1276 * @return array of integer profile IDs
1279 function saveReplies()
1281 // Don't save reply data for repeats
1283 if (!empty($this->repeat_of)) {
1287 $sender = Profile::staticGet($this->profile_id);
1291 // If it's a reply, save for the replied-to author
1293 if (!empty($this->reply_to)) {
1294 $original = $this->getOriginal();
1295 if (!empty($original)) { // that'd be weird
1296 $author = $original->getProfile();
1297 if (!empty($author)) {
1298 $this->saveReply($author->id);
1299 $replied[$author->id] = 1;
1300 self::blow('reply:stream:%d', $author->id);
1305 // @todo ideally this parser information would only
1306 // be calculated once.
1308 $mentions = common_find_mentions($this->content, $this);
1310 // store replied only for first @ (what user/notice what the reply directed,
1311 // we assume first @ is it)
1313 foreach ($mentions as $mention) {
1315 foreach ($mention['mentioned'] as $mentioned) {
1317 // skip if they're already covered
1319 if (!empty($replied[$mentioned->id])) {
1323 // Don't save replies from blocked profile to local user
1325 $mentioned_user = User::staticGet('id', $mentioned->id);
1326 if (!empty($mentioned_user) && $mentioned_user->hasBlocked($sender)) {
1330 $this->saveReply($mentioned->id);
1331 $replied[$mentioned->id] = 1;
1332 self::blow('reply:stream:%d', $mentioned->id);
1336 $recipientIds = array_keys($replied);
1338 return $recipientIds;
1341 function saveReply($profileId)
1343 $reply = new Reply();
1345 $reply->notice_id = $this->id;
1346 $reply->profile_id = $profileId;
1347 $reply->modified = $this->created;
1354 protected $_replies = -1;
1357 * Pull the complete list of @-reply targets for this notice.
1359 * @return array of integer profile ids
1361 function getReplies()
1363 if ($this->_replies != -1) {
1364 return $this->_replies;
1367 $replyMap = Memcached_DataObject::listGet('Reply', 'notice_id', array($this->id));
1371 foreach ($replyMap[$this->id] as $reply) {
1372 $ids[] = $reply->profile_id;
1375 $this->_replies = $ids;
1380 function _setReplies($replies)
1382 $this->_replies = $replies;
1386 * Pull the complete list of @-reply targets for this notice.
1388 * @return array of Profiles
1390 function getReplyProfiles()
1392 $ids = $this->getReplies();
1394 $profiles = Profile::multiGet('id', $ids);
1396 return $profiles->fetchAll();
1400 * Send e-mail notifications to local @-reply targets.
1402 * Replies must already have been saved; this is expected to be run
1403 * from the distrib queue handler.
1405 function sendReplyNotifications()
1407 // Don't send reply notifications for repeats
1409 if (!empty($this->repeat_of)) {
1413 $recipientIds = $this->getReplies();
1415 foreach ($recipientIds as $recipientId) {
1416 $user = User::staticGet('id', $recipientId);
1417 if (!empty($user)) {
1418 mail_notify_attn($user, $this);
1424 * Pull list of groups this notice needs to be delivered to,
1425 * as previously recorded by saveGroups() or saveKnownGroups().
1427 * @return array of Group objects
1430 protected $_groups = -1;
1432 function getGroups()
1434 // Don't save groups for repeats
1436 if (!empty($this->repeat_of)) {
1440 if ($this->_groups != -1)
1442 return $this->_groups;
1445 $gis = Memcached_DataObject::listGet('Group_inbox', 'notice_id', array($this->id));
1449 foreach ($gis[$this->id] as $gi)
1451 $ids[] = $gi->group_id;
1454 $groups = User_group::multiGet('id', $ids);
1456 $this->_groups = $groups->fetchAll();
1458 return $this->_groups;
1461 function _setGroups($groups)
1463 $this->_groups = $groups;
1467 * Convert a notice into an activity for export.
1469 * @param User $cur Current user
1471 * @return Activity activity object representing this Notice.
1474 function asActivity($cur)
1476 $act = self::cacheGet(Cache::codeKey('notice:as-activity:'.$this->id));
1481 $act = new Activity();
1483 if (Event::handle('StartNoticeAsActivity', array($this, &$act))) {
1485 $act->id = $this->uri;
1486 $act->time = strtotime($this->created);
1487 $act->link = $this->bestUrl();
1488 $act->content = common_xml_safe_str($this->rendered);
1489 $act->title = common_xml_safe_str($this->content);
1491 $profile = $this->getProfile();
1493 $act->actor = ActivityObject::fromProfile($profile);
1494 $act->actor->extra[] = $profile->profileInfo($cur);
1496 if ($this->repeat_of) {
1498 $repeated = Notice::staticGet('id', $this->repeat_of);
1500 $act->verb = ActivityVerb::SHARE;
1501 $act->objects[] = $repeated->asActivity($cur);
1505 $act->verb = ActivityVerb::POST;
1506 $act->objects[] = ActivityObject::fromNotice($this);
1510 // XXX: should this be handled by default processing for object entry?
1514 $tags = $this->getTags();
1516 foreach ($tags as $tag) {
1517 $cat = new AtomCategory();
1520 $act->categories[] = $cat;
1524 // XXX: use Atom Media and/or File activity objects instead
1526 $attachments = $this->attachments();
1528 foreach ($attachments as $attachment) {
1529 $enclosure = $attachment->getEnclosure();
1531 $act->enclosures[] = $enclosure;
1535 $ctx = new ActivityContext();
1537 if (!empty($this->reply_to)) {
1538 $reply = Notice::staticGet('id', $this->reply_to);
1539 if (!empty($reply)) {
1540 $ctx->replyToID = $reply->uri;
1541 $ctx->replyToUrl = $reply->bestUrl();
1545 $ctx->location = $this->getLocation();
1549 if (!empty($this->conversation)) {
1550 $conv = Conversation::staticGet('id', $this->conversation);
1551 if (!empty($conv)) {
1552 $ctx->conversation = $conv->uri;
1556 $reply_ids = $this->getReplies();
1558 foreach ($reply_ids as $id) {
1559 $rprofile = Profile::staticGet('id', $id);
1560 if (!empty($rprofile)) {
1561 $ctx->attention[] = $rprofile->getUri();
1565 $groups = $this->getGroups();
1567 foreach ($groups as $group) {
1568 $ctx->attention[] = $group->getUri();
1571 // XXX: deprecated; use ActivityVerb::SHARE instead
1575 if (!empty($this->repeat_of)) {
1576 $repeat = Notice::staticGet('id', $this->repeat_of);
1577 $ctx->forwardID = $repeat->uri;
1578 $ctx->forwardUrl = $repeat->bestUrl();
1581 $act->context = $ctx;
1585 $atom_feed = $profile->getAtomFeed();
1587 if (!empty($atom_feed)) {
1589 $act->source = new ActivitySource();
1591 // XXX: we should store the actual feed ID
1593 $act->source->id = $atom_feed;
1595 // XXX: we should store the actual feed title
1597 $act->source->title = $profile->getBestName();
1599 $act->source->links['alternate'] = $profile->profileurl;
1600 $act->source->links['self'] = $atom_feed;
1602 $act->source->icon = $profile->avatarUrl(AVATAR_PROFILE_SIZE);
1604 $notice = $profile->getCurrentNotice();
1606 if (!empty($notice)) {
1607 $act->source->updated = self::utcDate($notice->created);
1610 $user = User::staticGet('id', $profile->id);
1612 if (!empty($user)) {
1613 $act->source->links['license'] = common_config('license', 'url');
1617 if ($this->isLocal()) {
1618 $act->selfLink = common_local_url('ApiStatusesShow', array('id' => $this->id,
1619 'format' => 'atom'));
1620 $act->editLink = $act->selfLink;
1623 Event::handle('EndNoticeAsActivity', array($this, &$act));
1626 self::cacheSet(Cache::codeKey('notice:as-activity:'.$this->id), $act);
1631 // This has gotten way too long. Needs to be sliced up into functional bits
1632 // or ideally exported to a utility class.
1634 function asAtomEntry($namespace=false,
1639 $act = $this->asActivity($cur);
1640 $act->extra[] = $this->noticeInfo($cur);
1641 return $act->asString($namespace, $author, $source);
1645 * Extra notice info for atom entries
1647 * Clients use some extra notice info in the atom stream.
1648 * This gives it to them.
1650 * @param User $cur Current user
1652 * @return array representation of <statusnet:notice_info> element
1655 function noticeInfo($cur)
1657 // local notice ID (useful to clients for ordering)
1659 $noticeInfoAttr = array('local_id' => $this->id);
1663 $ns = $this->getSource();
1666 $noticeInfoAttr['source'] = $ns->code;
1667 if (!empty($ns->url)) {
1668 $noticeInfoAttr['source_link'] = $ns->url;
1669 if (!empty($ns->name)) {
1670 $noticeInfoAttr['source'] = '<a href="'
1671 . htmlspecialchars($ns->url)
1672 . '" rel="nofollow">'
1673 . htmlspecialchars($ns->name)
1679 // favorite and repeated
1682 $noticeInfoAttr['favorite'] = ($cur->hasFave($this)) ? "true" : "false";
1683 $cp = $cur->getProfile();
1684 $noticeInfoAttr['repeated'] = ($cp->hasRepeated($this->id)) ? "true" : "false";
1687 if (!empty($this->repeat_of)) {
1688 $noticeInfoAttr['repeat_of'] = $this->repeat_of;
1691 return array('statusnet:notice_info', $noticeInfoAttr, null);
1695 * Returns an XML string fragment with a reference to a notice as an
1696 * Activity Streams noun object with the given element type.
1698 * Assumes that 'activity' namespace has been previously defined.
1700 * @param string $element one of 'subject', 'object', 'target'
1704 function asActivityNoun($element)
1706 $noun = ActivityObject::fromNotice($this);
1707 return $noun->asString('activity:' . $element);
1712 if (!empty($this->url)) {
1714 } else if (!empty($this->uri) && preg_match('/^https?:/', $this->uri)) {
1717 return common_local_url('shownotice',
1718 array('notice' => $this->id));
1724 * Determine which notice, if any, a new notice is in reply to.
1726 * For conversation tracking, we try to see where this notice fits
1727 * in the tree. Rough algorithm is:
1729 * if (reply_to is set and valid) {
1731 * } else if ((source not API or Web) and (content starts with "T NAME" or "@name ")) {
1732 * return ID of last notice by initial @name in content;
1735 * Note that all @nickname instances will still be used to save "reply" records,
1736 * so the notice shows up in the mentioned users' "replies" tab.
1738 * @param integer $reply_to ID passed in by Web or API
1739 * @param integer $profile_id ID of author
1740 * @param string $source Source tag, like 'web' or 'gwibber'
1741 * @param string $content Final notice content
1743 * @return integer ID of replied-to notice, or null for not a reply.
1746 static function getReplyTo($reply_to, $profile_id, $source, $content)
1748 static $lb = array('xmpp', 'mail', 'sms', 'omb');
1750 // If $reply_to is specified, we check that it exists, and then
1751 // return it if it does
1753 if (!empty($reply_to)) {
1754 $reply_notice = Notice::staticGet('id', $reply_to);
1755 if (!empty($reply_notice)) {
1756 return $reply_notice;
1760 // If it's not a "low bandwidth" source (one where you can't set
1761 // a reply_to argument), we return. This is mostly web and API
1764 if (!in_array($source, $lb)) {
1768 // Is there an initial @ or T?
1770 if (preg_match('/^T ([A-Z0-9]{1,64}) /', $content, $match) ||
1771 preg_match('/^@([a-z0-9]{1,64})\s+/', $content, $match)) {
1772 $nickname = common_canonical_nickname($match[1]);
1777 // Figure out who that is.
1779 $sender = Profile::staticGet('id', $profile_id);
1780 if (empty($sender)) {
1784 $recipient = common_relative_profile($sender, $nickname, common_sql_now());
1786 if (empty($recipient)) {
1790 // Get their last notice
1792 $last = $recipient->getCurrentNotice();
1794 if (!empty($last)) {
1801 static function maxContent()
1803 $contentlimit = common_config('notice', 'contentlimit');
1804 // null => use global limit (distinct from 0!)
1805 if (is_null($contentlimit)) {
1806 $contentlimit = common_config('site', 'textlimit');
1808 return $contentlimit;
1811 static function contentTooLong($content)
1813 $contentlimit = self::maxContent();
1814 return ($contentlimit > 0 && !empty($content) && (mb_strlen($content) > $contentlimit));
1817 function getLocation()
1821 if (!empty($this->location_id) && !empty($this->location_ns)) {
1822 $location = Location::fromId($this->location_id, $this->location_ns);
1825 if (is_null($location)) { // no ID, or Location::fromId() failed
1826 if (!empty($this->lat) && !empty($this->lon)) {
1827 $location = Location::fromLatLon($this->lat, $this->lon);
1835 * Convenience function for posting a repeat of an existing message.
1837 * @param int $repeater_id: profile ID of user doing the repeat
1838 * @param string $source: posting source key, eg 'web', 'api', etc
1841 * @throws Exception on failure or permission problems
1843 function repeat($repeater_id, $source)
1845 $author = Profile::staticGet('id', $this->profile_id);
1847 // TRANS: Message used to repeat a notice. RT is the abbreviation of 'retweet'.
1848 // TRANS: %1$s is the repeated user's name, %2$s is the repeated notice.
1849 $content = sprintf(_('RT @%1$s %2$s'),
1853 $maxlen = common_config('site', 'textlimit');
1854 if ($maxlen > 0 && mb_strlen($content) > $maxlen) {
1855 // Web interface and current Twitter API clients will
1856 // pull the original notice's text, but some older
1857 // clients and RSS/Atom feeds will see this trimmed text.
1859 // Unfortunately this is likely to lose tags or URLs
1860 // at the end of long notices.
1861 $content = mb_substr($content, 0, $maxlen - 4) . ' ...';
1864 // Scope is same as this one's
1866 return self::saveNew($repeater_id,
1869 array('repeat_of' => $this->id,
1870 'scope' => $this->scope));
1873 // These are supposed to be in chron order!
1875 function repeatStream($limit=100)
1877 $cache = Cache::instance();
1879 if (empty($cache)) {
1880 $ids = $this->_repeatStreamDirect($limit);
1882 $idstr = $cache->get(Cache::key('notice:repeats:'.$this->id));
1883 if ($idstr !== false) {
1884 if (empty($idstr)) {
1887 $ids = explode(',', $idstr);
1890 $ids = $this->_repeatStreamDirect(100);
1891 $cache->set(Cache::key('notice:repeats:'.$this->id), implode(',', $ids));
1894 // We do a max of 100, so slice down to limit
1895 $ids = array_slice($ids, 0, $limit);
1899 return NoticeStream::getStreamByIds($ids);
1902 function _repeatStreamDirect($limit)
1904 $notice = new Notice();
1906 $notice->selectAdd(); // clears it
1907 $notice->selectAdd('id');
1909 $notice->repeat_of = $this->id;
1911 $notice->orderBy('created, id'); // NB: asc!
1913 if (!is_null($limit)) {
1914 $notice->limit(0, $limit);
1917 return $notice->fetchAll('id');
1920 function locationOptions($lat, $lon, $location_id, $location_ns, $profile = null)
1924 if (!empty($location_id) && !empty($location_ns)) {
1925 $options['location_id'] = $location_id;
1926 $options['location_ns'] = $location_ns;
1928 $location = Location::fromId($location_id, $location_ns);
1930 if (!empty($location)) {
1931 $options['lat'] = $location->lat;
1932 $options['lon'] = $location->lon;
1935 } else if (!empty($lat) && !empty($lon)) {
1936 $options['lat'] = $lat;
1937 $options['lon'] = $lon;
1939 $location = Location::fromLatLon($lat, $lon);
1941 if (!empty($location)) {
1942 $options['location_id'] = $location->location_id;
1943 $options['location_ns'] = $location->location_ns;
1945 } else if (!empty($profile)) {
1946 if (isset($profile->lat) && isset($profile->lon)) {
1947 $options['lat'] = $profile->lat;
1948 $options['lon'] = $profile->lon;
1951 if (isset($profile->location_id) && isset($profile->location_ns)) {
1952 $options['location_id'] = $profile->location_id;
1953 $options['location_ns'] = $profile->location_ns;
1960 function clearReplies()
1962 $replyNotice = new Notice();
1963 $replyNotice->reply_to = $this->id;
1965 //Null any notices that are replies to this notice
1967 if ($replyNotice->find()) {
1968 while ($replyNotice->fetch()) {
1969 $orig = clone($replyNotice);
1970 $replyNotice->reply_to = null;
1971 $replyNotice->update($orig);
1977 $reply = new Reply();
1978 $reply->notice_id = $this->id;
1980 if ($reply->find()) {
1981 while($reply->fetch()) {
1982 self::blow('reply:stream:%d', $reply->profile_id);
1990 function clearFiles()
1992 $f2p = new File_to_post();
1994 $f2p->post_id = $this->id;
1997 while ($f2p->fetch()) {
2001 // FIXME: decide whether to delete File objects
2002 // ...and related (actual) files
2005 function clearRepeats()
2007 $repeatNotice = new Notice();
2008 $repeatNotice->repeat_of = $this->id;
2010 //Null any notices that are repeats of this notice
2012 if ($repeatNotice->find()) {
2013 while ($repeatNotice->fetch()) {
2014 $orig = clone($repeatNotice);
2015 $repeatNotice->repeat_of = null;
2016 $repeatNotice->update($orig);
2021 function clearFaves()
2024 $fave->notice_id = $this->id;
2026 if ($fave->find()) {
2027 while ($fave->fetch()) {
2028 self::blow('fave:ids_by_user_own:%d', $fave->user_id);
2029 self::blow('fave:ids_by_user_own:%d;last', $fave->user_id);
2030 self::blow('fave:ids_by_user:%d', $fave->user_id);
2031 self::blow('fave:ids_by_user:%d;last', $fave->user_id);
2039 function clearTags()
2041 $tag = new Notice_tag();
2042 $tag->notice_id = $this->id;
2045 while ($tag->fetch()) {
2046 self::blow('profile:notice_ids_tagged:%d:%s', $this->profile_id, Cache::keyize($tag->tag));
2047 self::blow('profile:notice_ids_tagged:%d:%s;last', $this->profile_id, Cache::keyize($tag->tag));
2048 self::blow('notice_tag:notice_ids:%s', Cache::keyize($tag->tag));
2049 self::blow('notice_tag:notice_ids:%s;last', Cache::keyize($tag->tag));
2057 function clearGroupInboxes()
2059 $gi = new Group_inbox();
2061 $gi->notice_id = $this->id;
2064 while ($gi->fetch()) {
2065 self::blow('user_group:notice_ids:%d', $gi->group_id);
2073 function distribute()
2075 // We always insert for the author so they don't
2077 Event::handle('StartNoticeDistribute', array($this));
2079 $user = User::staticGet('id', $this->profile_id);
2080 if (!empty($user)) {
2081 Inbox::insertNotice($user->id, $this->id);
2084 if (common_config('queue', 'inboxes')) {
2085 // If there's a failure, we want to _force_
2086 // distribution at this point.
2088 $qm = QueueManager::get();
2089 $qm->enqueue($this, 'distrib');
2090 } catch (Exception $e) {
2091 // If the exception isn't transient, this
2092 // may throw more exceptions as DQH does
2093 // its own enqueueing. So, we ignore them!
2095 $handler = new DistribQueueHandler();
2096 $handler->handle($this);
2097 } catch (Exception $e) {
2098 common_log(LOG_ERR, "emergency redistribution resulted in " . $e->getMessage());
2100 // Re-throw so somebody smarter can handle it.
2104 $handler = new DistribQueueHandler();
2105 $handler->handle($this);
2111 $result = parent::insert();
2114 // Profile::hasRepeated() abuses pkeyGet(), so we
2115 // have to clear manually
2116 if (!empty($this->repeat_of)) {
2117 $c = self::memcache();
2119 $ck = self::multicacheKey('Notice',
2120 array('profile_id' => $this->profile_id,
2121 'repeat_of' => $this->repeat_of));
2131 * Get the source of the notice
2133 * @return Notice_source $ns A notice source object. 'code' is the only attribute
2134 * guaranteed to be populated.
2136 function getSource()
2138 $ns = new Notice_source();
2139 if (!empty($this->source)) {
2140 switch ($this->source) {
2147 $ns->code = $this->source;
2150 $ns = Notice_source::staticGet($this->source);
2152 $ns = new Notice_source();
2153 $ns->code = $this->source;
2154 $app = Oauth_application::staticGet('name', $this->source);
2156 $ns->name = $app->name;
2157 $ns->url = $app->source_url;
2167 * Determine whether the notice was locally created
2169 * @return boolean locality
2172 public function isLocal()
2174 return ($this->is_local == Notice::LOCAL_PUBLIC ||
2175 $this->is_local == Notice::LOCAL_NONPUBLIC);
2179 * Get the list of hash tags saved with this notice.
2181 * @return array of strings
2183 public function getTags()
2187 $keypart = sprintf('notice:tags:%d', $this->id);
2189 $tagstr = self::cacheGet($keypart);
2191 if ($tagstr !== false) {
2192 $tags = explode(',', $tagstr);
2194 $tag = new Notice_tag();
2195 $tag->notice_id = $this->id;
2197 while ($tag->fetch()) {
2198 $tags[] = $tag->tag;
2201 self::cacheSet($keypart, implode(',', $tags));
2207 static private function utcDate($dt)
2209 $dateStr = date('d F Y H:i:s', strtotime($dt));
2210 $d = new DateTime($dateStr, new DateTimeZone('UTC'));
2211 return $d->format(DATE_W3C);
2215 * Look up the creation timestamp for a given notice ID, even
2216 * if it's been deleted.
2219 * @return mixed string recorded creation timestamp, or false if can't be found
2221 public static function getAsTimestamp($id)
2227 $notice = Notice::staticGet('id', $id);
2229 return $notice->created;
2232 $deleted = Deleted_notice::staticGet('id', $id);
2234 return $deleted->created;
2241 * Build an SQL 'where' fragment for timestamp-based sorting from a since_id
2242 * parameter, matching notices posted after the given one (exclusive).
2244 * If the referenced notice can't be found, will return false.
2247 * @param string $idField
2248 * @param string $createdField
2249 * @return mixed string or false if no match
2251 public static function whereSinceId($id, $idField='id', $createdField='created')
2253 $since = Notice::getAsTimestamp($id);
2255 return sprintf("($createdField = '%s' and $idField > %d) or ($createdField > '%s')", $since, $id, $since);
2261 * Build an SQL 'where' fragment for timestamp-based sorting from a since_id
2262 * parameter, matching notices posted after the given one (exclusive), and
2263 * if necessary add it to the data object's query.
2265 * @param DB_DataObject $obj
2267 * @param string $idField
2268 * @param string $createdField
2269 * @return mixed string or false if no match
2271 public static function addWhereSinceId(DB_DataObject $obj, $id, $idField='id', $createdField='created')
2273 $since = self::whereSinceId($id, $idField, $createdField);
2275 $obj->whereAdd($since);
2280 * Build an SQL 'where' fragment for timestamp-based sorting from a max_id
2281 * parameter, matching notices posted before the given one (inclusive).
2283 * If the referenced notice can't be found, will return false.
2286 * @param string $idField
2287 * @param string $createdField
2288 * @return mixed string or false if no match
2290 public static function whereMaxId($id, $idField='id', $createdField='created')
2292 $max = Notice::getAsTimestamp($id);
2294 return sprintf("($createdField < '%s') or ($createdField = '%s' and $idField <= %d)", $max, $max, $id);
2300 * Build an SQL 'where' fragment for timestamp-based sorting from a max_id
2301 * parameter, matching notices posted before the given one (inclusive), and
2302 * if necessary add it to the data object's query.
2304 * @param DB_DataObject $obj
2306 * @param string $idField
2307 * @param string $createdField
2308 * @return mixed string or false if no match
2310 public static function addWhereMaxId(DB_DataObject $obj, $id, $idField='id', $createdField='created')
2312 $max = self::whereMaxId($id, $idField, $createdField);
2314 $obj->whereAdd($max);
2320 if (common_config('public', 'localonly')) {
2321 return ($this->is_local == Notice::LOCAL_PUBLIC);
2323 return (($this->is_local != Notice::LOCAL_NONPUBLIC) &&
2324 ($this->is_local != Notice::GATEWAY));
2329 * Check that the given profile is allowed to read, respond to, or otherwise
2330 * act on this notice.
2332 * The $scope member is a bitmask of scopes, representing a logical AND of the
2333 * scope requirement. So, 0x03 (Notice::ADDRESSEE_SCOPE | Notice::SITE_SCOPE) means
2334 * "only visible to people who are mentioned in the notice AND are users on this site."
2335 * Users on the site who are not mentioned in the notice will not be able to see the
2338 * @param Profile $profile The profile to check; pass null to check for public/unauthenticated users.
2340 * @return boolean whether the profile is in the notice's scope
2342 function inScope($profile)
2344 if (is_null($profile)) {
2345 $keypart = sprintf('notice:in-scope-for:%d:null', $this->id);
2347 $keypart = sprintf('notice:in-scope-for:%d:%d', $this->id, $profile->id);
2350 $result = self::cacheGet($keypart);
2352 if ($result === false) {
2353 $bResult = $this->_inScope($profile);
2354 $result = ($bResult) ? 1 : 0;
2355 self::cacheSet($keypart, $result, 0, 300);
2358 return ($result == 1) ? true : false;
2361 protected function _inScope($profile)
2363 // If there's no scope, anyone (even anon) is in scope.
2365 if ($this->scope == 0) {
2369 // If there's scope, anon cannot be in scope
2371 if (empty($profile)) {
2375 // Author is always in scope
2377 if ($this->profile_id == $profile->id) {
2381 // Only for users on this site
2383 if ($this->scope & Notice::SITE_SCOPE) {
2384 $user = $profile->getUser();
2390 // Only for users mentioned in the notice
2392 if ($this->scope & Notice::ADDRESSEE_SCOPE) {
2394 $repl = Reply::pkeyGet(array('notice_id' => $this->id,
2395 'profile_id' => $profile->id));
2402 // Only for members of the given group
2404 if ($this->scope & Notice::GROUP_SCOPE) {
2406 // XXX: just query for the single membership
2408 $groups = $this->getGroups();
2412 foreach ($groups as $group) {
2413 if ($profile->isMember($group)) {
2424 // Only for followers of the author
2426 if ($this->scope & Notice::FOLLOWER_SCOPE) {
2427 $author = $this->getProfile();
2428 if (!Subscription::exists($profile, $author)) {
2436 static function groupsFromText($text, $profile)
2440 /* extract all !group */
2441 $count = preg_match_all('/(?:^|\s)!(' . Nickname::DISPLAY_FMT . ')/',
2449 foreach (array_unique($match[1]) as $nickname) {
2450 $group = User_group::getForNickname($nickname, $profile);
2451 if (!empty($group) && $profile->isMember($group)) {
2452 $groups[] = $group->id;
2459 protected $_original = -1;
2461 function getOriginal()
2463 if (is_int($this->_original) && $this->_original == -1) {
2464 if (empty($this->reply_to)) {
2465 $this->_original = null;
2467 $this->_original = Notice::staticGet('id', $this->reply_to);
2470 return $this->_original;
2474 * Magic function called at serialize() time.
2476 * We use this to drop a couple process-specific references
2477 * from DB_DataObject which can cause trouble in future
2480 * @return array of variable names to include in serialization.
2485 $vars = parent::__sleep();
2486 $skip = array('_original', '_profile', '_groups', '_attachments', '_faves', '_replies', '_repeats');
2487 return array_diff($vars, $skip);
2490 static function defaultScope()
2492 $scope = common_config('notice', 'defaultscope');
2493 if (is_null($scope)) {
2494 if (common_config('site', 'private')) {
2503 static function fillProfiles($notices)
2505 $map = self::getProfiles($notices);
2507 foreach ($notices as $notice) {
2508 if (array_key_exists($notice->profile_id, $map)) {
2509 $notice->_setProfile($map[$notice->profile_id]);
2513 return array_values($map);
2516 static function getProfiles(&$notices)
2519 foreach ($notices as $notice) {
2520 $ids[] = $notice->profile_id;
2523 $ids = array_unique($ids);
2525 return Memcached_DataObject::pivotGet('Profile', 'id', $ids);
2528 static function fillGroups(&$notices)
2530 $ids = self::_idsOf($notices);
2532 $gis = Memcached_DataObject::listGet('Group_inbox', 'notice_id', $ids);
2536 foreach ($gis as $id => $gi)
2540 $gids[] = $g->group_id;
2544 $gids = array_unique($gids);
2546 $group = Memcached_DataObject::pivotGet('User_group', 'id', $gids);
2548 foreach ($notices as $notice)
2551 $gi = $gis[$notice->id];
2552 foreach ($gi as $g) {
2553 $grps[] = $group[$g->group_id];
2555 $notice->_setGroups($grps);
2559 static function _idsOf(&$notices)
2562 foreach ($notices as $notice) {
2563 $ids[] = $notice->id;
2565 $ids = array_unique($ids);
2569 static function fillAttachments(&$notices)
2571 $ids = self::_idsOf($notices);
2573 $f2pMap = Memcached_DataObject::listGet('File_to_post', 'post_id', $ids);
2577 foreach ($f2pMap as $noticeId => $f2ps) {
2578 foreach ($f2ps as $f2p) {
2579 $fileIds[] = $f2p->file_id;
2583 $fileIds = array_unique($fileIds);
2585 $fileMap = Memcached_DataObject::pivotGet('File', 'id', $fileIds);
2587 foreach ($notices as $notice)
2590 $f2ps = $f2pMap[$notice->id];
2591 foreach ($f2ps as $f2p) {
2592 $files[] = $fileMap[$f2p->file_id];
2594 $notice->_setAttachments($files);
2601 * All faves of this notice
2603 * @return array Array of Fave objects
2608 if (isset($this->_faves) && is_array($this->_faves)) {
2609 return $this->_faves;
2611 $faveMap = Memcached_DataObject::listGet('Fave', 'notice_id', array($this->id));
2612 $this->_faves = $faveMap[$this->id];
2613 return $this->_faves;
2616 function _setFaves(&$faves)
2618 $this->_faves = $faves;
2621 static function fillFaves(&$notices)
2623 $ids = self::_idsOf($notices);
2624 $faveMap = Memcached_DataObject::listGet('Fave', 'notice_id', $ids);
2627 foreach ($faveMap as $id => $faves) {
2628 $cnt += count($faves);
2629 if (count($faves) > 0) {
2633 foreach ($notices as $notice) {
2634 $notice->_setFaves($faveMap[$notice->id]);
2638 static function fillReplies(&$notices)
2640 $ids = self::_idsOf($notices);
2641 $replyMap = Memcached_DataObject::listGet('Reply', 'notice_id', $ids);
2642 foreach ($notices as $notice) {
2643 $replies = $replyMap[$notice->id];
2645 foreach ($replies as $reply) {
2646 $ids[] = $reply->profile_id;
2648 $notice->_setReplies($ids);
2652 protected $_repeats;
2654 function getRepeats()
2656 if (isset($this->_repeats) && is_array($this->_repeats)) {
2657 return $this->_repeats;
2659 $repeatMap = Memcached_DataObject::listGet('Notice', 'repeat_of', array($this->id));
2660 $this->_repeats = $repeatMap[$this->id];
2661 return $this->_repeats;
2664 function _setRepeats(&$repeats)
2666 $this->_repeats = $repeats;
2669 static function fillRepeats(&$notices)
2671 $ids = self::_idsOf($notices);
2672 $repeatMap = Memcached_DataObject::listGet('Notice', 'repeat_of', $ids);
2673 foreach ($notices as $notice) {
2674 $notice->_setRepeats($repeatMap[$notice->id]);