3 * StatusNet - the distributed open-source microblogging tool
4 * Copyright (C) 2008, 2009, 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 Memcached_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 */
88 const LOCAL_PUBLIC = 1;
90 const LOCAL_NONPUBLIC = -1;
93 const PUBLIC_SCOPE = 0; // Useful fake constant
95 const ADDRESSEE_SCOPE = 2;
96 const GROUP_SCOPE = 4;
97 const FOLLOWER_SCOPE = 8;
101 $profile = Profile::staticGet('id', $this->profile_id);
103 if (empty($profile)) {
104 // TRANS: Server exception thrown when a user profile for a notice cannot be found.
105 // TRANS: %1$d is a profile ID (number), %2$d is a notice ID (number).
106 throw new ServerException(sprintf(_('No such profile (%1$d) for notice (%2$d).'), $this->profile_id, $this->id));
114 // For auditing purposes, save a record that the notice
117 // @fixme we have some cases where things get re-run and so the
119 $deleted = Deleted_notice::staticGet('id', $this->id);
122 $deleted = Deleted_notice::staticGet('uri', $this->uri);
126 $deleted = new Deleted_notice();
128 $deleted->id = $this->id;
129 $deleted->profile_id = $this->profile_id;
130 $deleted->uri = $this->uri;
131 $deleted->created = $this->created;
132 $deleted->deleted = common_sql_now();
137 if (Event::handle('NoticeDeleteRelated', array($this))) {
139 // Clear related records
141 $this->clearReplies();
142 $this->clearRepeats();
145 $this->clearGroupInboxes();
148 // NOTE: we don't clear inboxes
149 // NOTE: we don't clear queue items
152 $result = parent::delete();
154 $this->blowOnDelete();
159 * Extract #hashtags from this notice's content and save them to the database.
163 /* extract all #hastags */
164 $count = preg_match_all('/(?:^|\s)#([\pL\pN_\-\.]{1,64})/u', strtolower($this->content), $match);
169 /* Add them to the database */
170 return $this->saveKnownTags($match[1]);
174 * Record the given set of hash tags in the db for this notice.
175 * Given tag strings will be normalized and checked for dupes.
177 function saveKnownTags($hashtags)
179 //turn each into their canonical tag
180 //this is needed to remove dupes before saving e.g. #hash.tag = #hashtag
181 for($i=0; $i<count($hashtags); $i++) {
182 /* elide characters we don't want in the tag */
183 $hashtags[$i] = common_canonical_tag($hashtags[$i]);
186 foreach(array_unique($hashtags) as $hashtag) {
187 $this->saveTag($hashtag);
188 self::blow('profile:notice_ids_tagged:%d:%s', $this->profile_id, $hashtag);
194 * Record a single hash tag as associated with this notice.
195 * Tag format and uniqueness must be validated by caller.
197 function saveTag($hashtag)
199 $tag = new Notice_tag();
200 $tag->notice_id = $this->id;
201 $tag->tag = $hashtag;
202 $tag->created = $this->created;
203 $id = $tag->insert();
206 // TRANS: Server exception. %s are the error details.
207 throw new ServerException(sprintf(_('Database error inserting hashtag: %s'),
208 $last_error->message));
212 // if it's saved, blow its cache
213 $tag->blowCache(false);
217 * Save a new notice and push it out to subscribers' inboxes.
218 * Poster's permissions are checked before sending.
220 * @param int $profile_id Profile ID of the poster
221 * @param string $content source message text; links may be shortened
222 * per current user's preference
223 * @param string $source source key ('web', 'api', etc)
224 * @param array $options Associative array of optional properties:
225 * string 'created' timestamp of notice; defaults to now
226 * int 'is_local' source/gateway ID, one of:
227 * Notice::LOCAL_PUBLIC - Local, ok to appear in public timeline
228 * Notice::REMOTE_OMB - Sent from a remote OMB service;
229 * hide from public timeline but show in
230 * local "and friends" timelines
231 * Notice::LOCAL_NONPUBLIC - Local, but hide from public timeline
232 * Notice::GATEWAY - From another non-OMB service;
233 * will not appear in public views
234 * float 'lat' decimal latitude for geolocation
235 * float 'lon' decimal longitude for geolocation
236 * int 'location_id' geoname identifier
237 * int 'location_ns' geoname namespace to interpret location_id
238 * int 'reply_to'; notice ID this is a reply to
239 * int 'repeat_of'; notice ID this is a repeat of
240 * string 'uri' unique ID for notice; defaults to local notice URL
241 * string 'url' permalink to notice; defaults to local notice URL
242 * string 'rendered' rendered HTML version of content
243 * array 'replies' list of profile URIs for reply delivery in
244 * place of extracting @-replies from content.
245 * array 'groups' list of group IDs to deliver to, in place of
246 * extracting ! tags from content
247 * array 'tags' list of hashtag strings to save with the notice
248 * in place of extracting # tags from content
249 * array 'urls' list of attached/referred URLs to save with the
250 * notice in place of extracting links from content
251 * boolean 'distribute' whether to distribute the notice, default true
252 * string 'object_type' URL of the associated object type (default ActivityObject::NOTE)
253 * int 'scope' Scope bitmask; default to SITE_SCOPE on private sites, 0 otherwise
255 * @fixme tag override
258 * @throws ClientException
260 static function saveNew($profile_id, $content, $source, $options=null) {
261 $defaults = array('uri' => null,
266 'distribute' => true);
268 if (!empty($options)) {
269 $options = $options + $defaults;
275 if (!isset($is_local)) {
276 $is_local = Notice::LOCAL_PUBLIC;
279 $profile = Profile::staticGet('id', $profile_id);
280 $user = User::staticGet('id', $profile_id);
282 // Use the local user's shortening preferences, if applicable.
283 $final = $user->shortenLinks($content);
285 $final = common_shorten_links($content);
288 if (Notice::contentTooLong($final)) {
289 // TRANS: Client exception thrown if a notice contains too many characters.
290 throw new ClientException(_('Problem saving notice. Too long.'));
293 if (empty($profile)) {
294 // TRANS: Client exception thrown when trying to save a notice for an unknown user.
295 throw new ClientException(_('Problem saving notice. Unknown user.'));
298 if (common_config('throttle', 'enabled') && !Notice::checkEditThrottle($profile_id)) {
299 common_log(LOG_WARNING, 'Excessive posting by profile #' . $profile_id . '; throttled.');
300 // TRANS: Client exception thrown when a user tries to post too many notices in a given time frame.
301 throw new ClientException(_('Too many notices too fast; take a breather '.
302 'and post again in a few minutes.'));
305 if (common_config('site', 'dupelimit') > 0 && !Notice::checkDupes($profile_id, $final)) {
306 common_log(LOG_WARNING, 'Dupe posting by profile #' . $profile_id . '; throttled.');
307 // TRANS: Client exception thrown when a user tries to post too many duplicate notices in a given time frame.
308 throw new ClientException(_('Too many duplicate messages too quickly;'.
309 ' take a breather and post again in a few minutes.'));
312 if (!$profile->hasRight(Right::NEWNOTICE)) {
313 common_log(LOG_WARNING, "Attempted post from user disallowed to post: " . $profile->nickname);
315 // TRANS: Client exception thrown when a user tries to post while being banned.
316 throw new ClientException(_('You are banned from posting notices on this site.'), 403);
319 $notice = new Notice();
320 $notice->profile_id = $profile_id;
322 $autosource = common_config('public', 'autosource');
324 // Sandboxed are non-false, but not 1, either
326 if (!$profile->hasRight(Right::PUBLICNOTICE) ||
327 ($source && $autosource && in_array($source, $autosource))) {
328 $notice->is_local = Notice::LOCAL_NONPUBLIC;
330 $notice->is_local = $is_local;
333 if (!empty($created)) {
334 $notice->created = $created;
336 $notice->created = common_sql_now();
339 $notice->content = $final;
341 $notice->source = $source;
345 // Handle repeat case
347 if (isset($repeat_of)) {
349 // Check for a private one
351 $repeat = Notice::staticGet('id', $repeat_of);
353 if (!empty($repeat) &&
354 $repeat->scope != Notice::SITE_SCOPE &&
355 $repeat->scope != Notice::PUBLIC_SCOPE) {
356 // TRANS: Client exception thrown when trying to repeat a private notice.
357 throw new ClientException(_('Cannot repeat a private notice.'), 403);
360 // XXX: Check for access...?
362 $notice->repeat_of = $repeat_of;
364 $notice->reply_to = self::getReplyTo($reply_to, $profile_id, $source, $final);
367 if (!empty($notice->reply_to)) {
368 $reply = Notice::staticGet('id', $notice->reply_to);
369 if (!$reply->inScope($profile)) {
370 // TRANS: Client error displayed when trying to reply to a notice a the target has no access to.
371 // TRANS: %1$s is a user nickname, %2$d is a notice ID (number).
372 throw new ClientException(sprintf(_('%1$s has no access to notice %2$d.'),
373 $profile->nickname, $reply->id), 403);
375 $notice->conversation = $reply->conversation;
378 if (!empty($lat) && !empty($lon)) {
383 if (!empty($location_ns) && !empty($location_id)) {
384 $notice->location_id = $location_id;
385 $notice->location_ns = $location_ns;
388 if (!empty($rendered)) {
389 $notice->rendered = $rendered;
391 $notice->rendered = common_render_content($final, $notice);
394 if (empty($object_type)) {
395 $notice->object_type = (empty($notice->reply_to)) ? ActivityObject::NOTE : ActivityObject::COMMENT;
397 $notice->object_type = $object_type;
400 if (is_null($scope)) { // 0 is a valid value
401 $notice->scope = common_config('notice', 'defaultscope');
403 $notice->scope = $scope;
406 if (Event::handle('StartNoticeSave', array(&$notice))) {
408 // XXX: some of these functions write to the DB
410 $id = $notice->insert();
413 common_log_db_error($notice, 'INSERT', __FILE__);
414 // TRANS: Server exception thrown when a notice cannot be saved.
415 throw new ServerException(_('Problem saving notice.'));
418 // Update ID-dependent columns: URI, conversation
420 $orig = clone($notice);
425 $notice->uri = common_notice_uri($notice);
429 // If it's not part of a conversation, it's
430 // the beginning of a new conversation.
432 if (empty($notice->conversation)) {
433 $conv = Conversation::create();
434 $notice->conversation = $conv->id;
439 if (!$notice->update($orig)) {
440 common_log_db_error($notice, 'UPDATE', __FILE__);
441 // TRANS: Server exception thrown when a notice cannot be updated.
442 throw new ServerException(_('Problem saving notice.'));
448 // Clear the cache for subscribed users, so they'll update at next request
449 // XXX: someone clever could prepend instead of clearing the cache
451 $notice->blowOnInsert();
453 // Save per-notice metadata...
455 if (isset($replies)) {
456 $notice->saveKnownReplies($replies);
458 $notice->saveReplies();
462 $notice->saveKnownTags($tags);
467 // Note: groups may save tags, so must be run after tags are saved
468 // to avoid errors on duplicates.
469 if (isset($groups)) {
470 $notice->saveKnownGroups($groups);
472 $notice->saveGroups();
476 $notice->saveKnownUrls($urls);
482 // Prepare inbox delivery, may be queued to background.
483 $notice->distribute();
489 function blowOnInsert($conversation = false)
491 self::blow('profile:notice_ids:%d', $this->profile_id);
493 if ($this->isPublic()) {
494 self::blow('public');
497 // XXX: Before we were blowing the casche only if the notice id
498 // was not the root of the conversation. What to do now?
500 self::blow('notice:conversation_ids:%d', $this->conversation);
502 if (!empty($this->repeat_of)) {
503 self::blow('notice:repeats:%d', $this->repeat_of);
506 $original = Notice::staticGet('id', $this->repeat_of);
508 if (!empty($original)) {
509 $originalUser = User::staticGet('id', $original->profile_id);
510 if (!empty($originalUser)) {
511 self::blow('user:repeats_of_me:%d', $originalUser->id);
515 $profile = Profile::staticGet($this->profile_id);
516 if (!empty($profile)) {
517 $profile->blowNoticeCount();
522 * Clear cache entries related to this notice at delete time.
523 * Necessary to avoid breaking paging on public, profile timelines.
525 function blowOnDelete()
527 $this->blowOnInsert();
529 self::blow('profile:notice_ids:%d;last', $this->profile_id);
531 if ($this->isPublic()) {
532 self::blow('public;last');
535 self::blow('fave:by_notice', $this->id);
537 if ($this->conversation) {
538 // In case we're the first, will need to calc a new root.
539 self::blow('notice:conversation_root:%d', $this->conversation);
543 /** save all urls in the notice to the db
545 * follow redirects and save all available file information
546 * (mimetype, date, size, oembed, etc.)
550 function saveUrls() {
551 if (common_config('attachments', 'process_links')) {
552 common_replace_urls_callback($this->content, array($this, 'saveUrl'), $this->id);
557 * Save the given URLs as related links/attachments to the db
559 * follow redirects and save all available file information
560 * (mimetype, date, size, oembed, etc.)
564 function saveKnownUrls($urls)
566 if (common_config('attachments', 'process_links')) {
567 // @fixme validation?
568 foreach (array_unique($urls) as $url) {
569 File::processNew($url, $this->id);
577 function saveUrl($url, $notice_id) {
578 File::processNew($url, $notice_id);
581 static function checkDupes($profile_id, $content) {
582 $profile = Profile::staticGet($profile_id);
583 if (empty($profile)) {
586 $notice = $profile->getNotices(0, CachingNoticeStream::CACHE_WINDOW);
587 if (!empty($notice)) {
589 while ($notice->fetch()) {
590 if (time() - strtotime($notice->created) >= common_config('site', 'dupelimit')) {
592 } else if ($notice->content == $content) {
597 // If we get here, oldest item in cache window is not
598 // old enough for dupe limit; do direct check against DB
599 $notice = new Notice();
600 $notice->profile_id = $profile_id;
601 $notice->content = $content;
602 $threshold = common_sql_date(time() - common_config('site', 'dupelimit'));
603 $notice->whereAdd(sprintf("created > '%s'", $notice->escape($threshold)));
605 $cnt = $notice->count();
609 static function checkEditThrottle($profile_id) {
610 $profile = Profile::staticGet($profile_id);
611 if (empty($profile)) {
614 // Get the Nth notice
615 $notice = $profile->getNotices(common_config('throttle', 'count') - 1, 1);
616 if ($notice && $notice->fetch()) {
617 // If the Nth notice was posted less than timespan seconds ago
618 if (time() - strtotime($notice->created) <= common_config('throttle', 'timespan')) {
623 // Either not N notices in the stream, OR the Nth was not posted within timespan seconds
627 function getUploadedAttachment() {
629 $query = 'select file.url as up, file.id as i from file join file_to_post on file.id = file_id where post_id=' . $post->escape($post->id) . ' and url like "%/notice/%/file"';
630 $post->query($query);
632 if (empty($post->up) || empty($post->i)) {
635 $ret = array($post->up, $post->i);
641 function hasAttachments() {
643 $query = "select count(file_id) as n_attachments from file join file_to_post on (file_id = file.id) join notice on (post_id = notice.id) where post_id = " . $post->escape($post->id);
644 $post->query($query);
646 $n_attachments = intval($post->n_attachments);
648 return $n_attachments;
651 function attachments() {
654 $f2p = new File_to_post;
655 $f2p->post_id = $this->id;
657 while ($f2p->fetch()) {
658 $f = File::staticGet($f2p->file_id);
668 function publicStream($offset=0, $limit=20, $since_id=0, $max_id=0)
670 $stream = new PublicNoticeStream();
671 return $stream->getNotices($offset, $limit, $since_id, $max_id);
675 function conversationStream($id, $offset=0, $limit=20, $since_id=0, $max_id=0)
677 $stream = new ConversationNoticeStream($id);
679 return $stream->getNotices($offset, $limit, $since_id, $max_id);
683 * Is this notice part of an active conversation?
685 * @return boolean true if other messages exist in the same
686 * conversation, false if this is the only one
688 function hasConversation()
690 if (!empty($this->conversation)) {
691 $conversation = Notice::conversationStream(
697 if ($conversation->N > 0) {
705 * Grab the earliest notice from this conversation.
707 * @return Notice or null
709 function conversationRoot()
711 if (!empty($this->conversation)) {
712 $c = self::memcache();
714 $key = Cache::key('notice:conversation_root:' . $this->conversation);
715 $notice = $c->get($key);
720 $notice = new Notice();
721 $notice->conversation = $this->conversation;
722 $notice->orderBy('CREATED');
727 $c->set($key, $notice);
734 * Pull up a full list of local recipients who will be getting
735 * this notice in their inbox. Results will be cached, so don't
736 * change the input data wily-nilly!
738 * @param array $groups optional list of Group objects;
739 * if left empty, will be loaded from group_inbox records
740 * @param array $recipient optional list of reply profile ids
741 * if left empty, will be loaded from reply records
742 * @return array associating recipient user IDs with an inbox source constant
744 function whoGets($groups=null, $recipients=null)
746 $c = self::memcache();
749 $ni = $c->get(Cache::key('notice:who_gets:'.$this->id));
755 if (is_null($groups)) {
756 $groups = $this->getGroups();
759 if (is_null($recipients)) {
760 $recipients = $this->getReplies();
763 $users = $this->getSubscribedUsers();
765 // FIXME: kind of ignoring 'transitional'...
766 // we'll probably stop supporting inboxless mode
771 // Give plugins a chance to add folks in at start...
772 if (Event::handle('StartNoticeWhoGets', array($this, &$ni))) {
774 foreach ($users as $id) {
775 $ni[$id] = NOTICE_INBOX_SOURCE_SUB;
778 foreach ($groups as $group) {
779 $users = $group->getUserMembers();
780 foreach ($users as $id) {
781 if (!array_key_exists($id, $ni)) {
782 $ni[$id] = NOTICE_INBOX_SOURCE_GROUP;
787 foreach ($recipients as $recipient) {
788 if (!array_key_exists($recipient, $ni)) {
789 $ni[$recipient] = NOTICE_INBOX_SOURCE_REPLY;
793 // Exclude any deleted, non-local, or blocking recipients.
794 $profile = $this->getProfile();
795 $originalProfile = null;
796 if ($this->repeat_of) {
797 // Check blocks against the original notice's poster as well.
798 $original = Notice::staticGet('id', $this->repeat_of);
800 $originalProfile = $original->getProfile();
803 foreach ($ni as $id => $source) {
804 $user = User::staticGet('id', $id);
805 if (empty($user) || $user->hasBlocked($profile) ||
806 ($originalProfile && $user->hasBlocked($originalProfile))) {
811 // Give plugins a chance to filter out...
812 Event::handle('EndNoticeWhoGets', array($this, &$ni));
816 // XXX: pack this data better
817 $c->set(Cache::key('notice:who_gets:'.$this->id), $ni);
824 * Adds this notice to the inboxes of each local user who should receive
825 * it, based on author subscriptions, group memberships, and @-replies.
827 * Warning: running a second time currently will make items appear
828 * multiple times in users' inboxes.
830 * @fixme make more robust against errors
831 * @fixme break up massive deliveries to smaller background tasks
833 * @param array $groups optional list of Group objects;
834 * if left empty, will be loaded from group_inbox records
835 * @param array $recipient optional list of reply profile ids
836 * if left empty, will be loaded from reply records
838 function addToInboxes($groups=null, $recipients=null)
840 $ni = $this->whoGets($groups, $recipients);
842 $ids = array_keys($ni);
844 // We remove the author (if they're a local user),
845 // since we'll have already done this in distribute()
847 $i = array_search($this->profile_id, $ids);
855 Inbox::bulkInsert($this->id, $ids);
860 function getSubscribedUsers()
864 if(common_config('db','quote_identifiers'))
865 $user_table = '"user"';
866 else $user_table = 'user';
870 'FROM '. $user_table .' JOIN subscription '.
871 'ON '. $user_table .'.id = subscription.subscriber ' .
872 'WHERE subscription.subscribed = %d ';
874 $user->query(sprintf($qry, $this->profile_id));
878 while ($user->fetch()) {
888 * Record this notice to the given group inboxes for delivery.
889 * Overrides the regular parsing of !group markup.
891 * @param string $group_ids
892 * @fixme might prefer URIs as identifiers, as for replies?
893 * best with generalizations on user_group to support
894 * remote groups better.
896 function saveKnownGroups($group_ids)
898 if (!is_array($group_ids)) {
899 // TRANS: Server exception thrown when no array is provided to the method saveKnownGroups().
900 throw new ServerException(_('Bad type provided to saveKnownGroups.'));
904 foreach (array_unique($group_ids) as $id) {
905 $group = User_group::staticGet('id', $id);
907 common_log(LOG_ERR, "Local delivery to group id $id, $group->nickname");
908 $result = $this->addToGroupInbox($group);
910 common_log_db_error($gi, 'INSERT', __FILE__);
913 // @fixme should we save the tags here or not?
914 $groups[] = clone($group);
916 common_log(LOG_ERR, "Local delivery to group id $id skipped, doesn't exist");
924 * Parse !group delivery and record targets into group_inbox.
925 * @return array of Group objects
927 function saveGroups()
929 // Don't save groups for repeats
931 if (!empty($this->repeat_of)) {
937 /* extract all !group */
938 $count = preg_match_all('/(?:^|\s)!(' . Nickname::DISPLAY_FMT . ')/',
939 strtolower($this->content),
945 $profile = $this->getProfile();
947 /* Add them to the database */
949 foreach (array_unique($match[1]) as $nickname) {
950 /* XXX: remote groups. */
951 $group = User_group::getForNickname($nickname, $profile);
957 // we automatically add a tag for every group name, too
959 $tag = Notice_tag::pkeyGet(array('tag' => common_canonical_tag($nickname),
960 'notice_id' => $this->id));
963 $this->saveTag($nickname);
966 if ($profile->isMember($group)) {
968 $result = $this->addToGroupInbox($group);
971 common_log_db_error($gi, 'INSERT', __FILE__);
974 $groups[] = clone($group);
981 function addToGroupInbox($group)
983 $gi = Group_inbox::pkeyGet(array('group_id' => $group->id,
984 'notice_id' => $this->id));
988 $gi = new Group_inbox();
990 $gi->group_id = $group->id;
991 $gi->notice_id = $this->id;
992 $gi->created = $this->created;
994 $result = $gi->insert();
997 common_log_db_error($gi, 'INSERT', __FILE__);
998 // TRANS: Server exception thrown when an update for a group inbox fails.
999 throw new ServerException(_('Problem saving group inbox.'));
1002 self::blow('user_group:notice_ids:%d', $gi->group_id);
1009 * Save reply records indicating that this notice needs to be
1010 * delivered to the local users with the given URIs.
1012 * Since this is expected to be used when saving foreign-sourced
1013 * messages, we won't deliver to any remote targets as that's the
1014 * source service's responsibility.
1016 * Mail notifications etc will be handled later.
1018 * @param array of unique identifier URIs for recipients
1020 function saveKnownReplies($uris)
1026 $sender = Profile::staticGet($this->profile_id);
1028 foreach (array_unique($uris) as $uri) {
1030 $profile = Profile::fromURI($uri);
1032 if (empty($profile)) {
1033 common_log(LOG_WARNING, "Unable to determine profile for URI '$uri'");
1037 if ($profile->hasBlocked($sender)) {
1038 common_log(LOG_INFO, "Not saving reply to profile {$profile->id} ($uri) from sender {$sender->id} because of a block.");
1042 $reply = new Reply();
1044 $reply->notice_id = $this->id;
1045 $reply->profile_id = $profile->id;
1046 $reply->modified = $this->created;
1048 common_log(LOG_INFO, __METHOD__ . ": saving reply: notice $this->id to profile $profile->id");
1050 $id = $reply->insert();
1057 * Pull @-replies from this message's content in StatusNet markup format
1058 * and save reply records indicating that this message needs to be
1059 * delivered to those users.
1061 * Mail notifications to local profiles will be sent later.
1063 * @return array of integer profile IDs
1066 function saveReplies()
1068 // Don't save reply data for repeats
1070 if (!empty($this->repeat_of)) {
1074 $sender = Profile::staticGet($this->profile_id);
1076 // @todo ideally this parser information would only
1077 // be calculated once.
1079 $mentions = common_find_mentions($this->content, $this);
1083 // store replied only for first @ (what user/notice what the reply directed,
1084 // we assume first @ is it)
1086 foreach ($mentions as $mention) {
1088 foreach ($mention['mentioned'] as $mentioned) {
1090 // skip if they're already covered
1092 if (!empty($replied[$mentioned->id])) {
1096 // Don't save replies from blocked profile to local user
1098 $mentioned_user = User::staticGet('id', $mentioned->id);
1099 if (!empty($mentioned_user) && $mentioned_user->hasBlocked($sender)) {
1103 $reply = new Reply();
1105 $reply->notice_id = $this->id;
1106 $reply->profile_id = $mentioned->id;
1107 $reply->modified = $this->created;
1109 $id = $reply->insert();
1112 common_log_db_error($reply, 'INSERT', __FILE__);
1113 // TRANS: Server exception thrown when a reply cannot be saved.
1114 // TRANS: %1$d is a notice ID, %2$d is the ID of the mentioned user.
1115 throw new ServerException(sprintf(_('Could not save reply for %1$d, %2$d.'), $this->id, $mentioned->id));
1117 $replied[$mentioned->id] = 1;
1118 self::blow('reply:stream:%d', $mentioned->id);
1123 $recipientIds = array_keys($replied);
1125 return $recipientIds;
1129 * Pull the complete list of @-reply targets for this notice.
1131 * @return array of integer profile ids
1133 function getReplies()
1139 $reply = new Reply();
1140 $reply->selectAdd();
1141 $reply->selectAdd('profile_id');
1142 $reply->notice_id = $this->id;
1144 if ($reply->find()) {
1145 while($reply->fetch()) {
1146 $ids[] = $reply->profile_id;
1156 * Send e-mail notifications to local @-reply targets.
1158 * Replies must already have been saved; this is expected to be run
1159 * from the distrib queue handler.
1161 function sendReplyNotifications()
1163 // Don't send reply notifications for repeats
1165 if (!empty($this->repeat_of)) {
1169 $recipientIds = $this->getReplies();
1171 foreach ($recipientIds as $recipientId) {
1172 $user = User::staticGet('id', $recipientId);
1173 if (!empty($user)) {
1174 mail_notify_attn($user, $this);
1180 * Pull list of groups this notice needs to be delivered to,
1181 * as previously recorded by saveGroups() or saveKnownGroups().
1183 * @return array of Group objects
1185 function getGroups()
1187 // Don't save groups for repeats
1189 if (!empty($this->repeat_of)) {
1197 $gi = new Group_inbox();
1200 $gi->selectAdd('group_id');
1202 $gi->notice_id = $this->id;
1205 while ($gi->fetch()) {
1206 $group = User_group::staticGet('id', $gi->group_id);
1219 * Convert a notice into an activity for export.
1221 * @param User $cur Current user
1223 * @return Activity activity object representing this Notice.
1226 function asActivity($cur)
1228 $act = self::cacheGet(Cache::codeKey('notice:as-activity:'.$this->id));
1233 $act = new Activity();
1235 if (Event::handle('StartNoticeAsActivity', array($this, &$act))) {
1237 $profile = $this->getProfile();
1239 $act->actor = ActivityObject::fromProfile($profile);
1240 $act->actor->extra[] = $profile->profileInfo($cur);
1241 $act->verb = ActivityVerb::POST;
1242 $act->objects[] = ActivityObject::fromNotice($this);
1244 // XXX: should this be handled by default processing for object entry?
1246 $act->time = strtotime($this->created);
1247 $act->link = $this->bestUrl();
1249 $act->content = common_xml_safe_str($this->rendered);
1250 $act->id = $this->uri;
1251 $act->title = common_xml_safe_str($this->content);
1255 $tags = $this->getTags();
1257 foreach ($tags as $tag) {
1258 $cat = new AtomCategory();
1261 $act->categories[] = $cat;
1265 // XXX: use Atom Media and/or File activity objects instead
1267 $attachments = $this->attachments();
1269 foreach ($attachments as $attachment) {
1270 $enclosure = $attachment->getEnclosure();
1272 $act->enclosures[] = $enclosure;
1276 $ctx = new ActivityContext();
1278 if (!empty($this->reply_to)) {
1279 $reply = Notice::staticGet('id', $this->reply_to);
1280 if (!empty($reply)) {
1281 $ctx->replyToID = $reply->uri;
1282 $ctx->replyToUrl = $reply->bestUrl();
1286 $ctx->location = $this->getLocation();
1290 if (!empty($this->conversation)) {
1291 $conv = Conversation::staticGet('id', $this->conversation);
1292 if (!empty($conv)) {
1293 $ctx->conversation = $conv->uri;
1297 $reply_ids = $this->getReplies();
1299 foreach ($reply_ids as $id) {
1300 $profile = Profile::staticGet('id', $id);
1301 if (!empty($profile)) {
1302 $ctx->attention[] = $profile->getUri();
1306 $groups = $this->getGroups();
1308 foreach ($groups as $group) {
1309 $ctx->attention[] = $group->getUri();
1312 // XXX: deprecated; use ActivityVerb::SHARE instead
1316 if (!empty($this->repeat_of)) {
1317 $repeat = Notice::staticGet('id', $this->repeat_of);
1318 $ctx->forwardID = $repeat->uri;
1319 $ctx->forwardUrl = $repeat->bestUrl();
1322 $act->context = $ctx;
1326 $atom_feed = $profile->getAtomFeed();
1328 if (!empty($atom_feed)) {
1330 $act->source = new ActivitySource();
1332 // XXX: we should store the actual feed ID
1334 $act->source->id = $atom_feed;
1336 // XXX: we should store the actual feed title
1338 $act->source->title = $profile->getBestName();
1340 $act->source->links['alternate'] = $profile->profileurl;
1341 $act->source->links['self'] = $atom_feed;
1343 $act->source->icon = $profile->avatarUrl(AVATAR_PROFILE_SIZE);
1345 $notice = $profile->getCurrentNotice();
1347 if (!empty($notice)) {
1348 $act->source->updated = self::utcDate($notice->created);
1351 $user = User::staticGet('id', $profile->id);
1353 if (!empty($user)) {
1354 $act->source->links['license'] = common_config('license', 'url');
1358 if ($this->isLocal()) {
1359 $act->selfLink = common_local_url('ApiStatusesShow', array('id' => $this->id,
1360 'format' => 'atom'));
1361 $act->editLink = $act->selfLink;
1364 Event::handle('EndNoticeAsActivity', array($this, &$act));
1367 self::cacheSet(Cache::codeKey('notice:as-activity:'.$this->id), $act);
1372 // This has gotten way too long. Needs to be sliced up into functional bits
1373 // or ideally exported to a utility class.
1375 function asAtomEntry($namespace=false,
1380 $act = $this->asActivity($cur);
1381 $act->extra[] = $this->noticeInfo($cur);
1382 return $act->asString($namespace, $author, $source);
1386 * Extra notice info for atom entries
1388 * Clients use some extra notice info in the atom stream.
1389 * This gives it to them.
1391 * @param User $cur Current user
1393 * @return array representation of <statusnet:notice_info> element
1396 function noticeInfo($cur)
1398 // local notice ID (useful to clients for ordering)
1400 $noticeInfoAttr = array('local_id' => $this->id);
1404 $ns = $this->getSource();
1407 $noticeInfoAttr['source'] = $ns->code;
1408 if (!empty($ns->url)) {
1409 $noticeInfoAttr['source_link'] = $ns->url;
1410 if (!empty($ns->name)) {
1411 $noticeInfoAttr['source'] = '<a href="'
1412 . htmlspecialchars($ns->url)
1413 . '" rel="nofollow">'
1414 . htmlspecialchars($ns->name)
1420 // favorite and repeated
1423 $noticeInfoAttr['favorite'] = ($cur->hasFave($this)) ? "true" : "false";
1424 $cp = $cur->getProfile();
1425 $noticeInfoAttr['repeated'] = ($cp->hasRepeated($this->id)) ? "true" : "false";
1428 if (!empty($this->repeat_of)) {
1429 $noticeInfoAttr['repeat_of'] = $this->repeat_of;
1432 return array('statusnet:notice_info', $noticeInfoAttr, null);
1436 * Returns an XML string fragment with a reference to a notice as an
1437 * Activity Streams noun object with the given element type.
1439 * Assumes that 'activity' namespace has been previously defined.
1441 * @param string $element one of 'subject', 'object', 'target'
1445 function asActivityNoun($element)
1447 $noun = ActivityObject::fromNotice($this);
1448 return $noun->asString('activity:' . $element);
1453 if (!empty($this->url)) {
1455 } else if (!empty($this->uri) && preg_match('/^https?:/', $this->uri)) {
1458 return common_local_url('shownotice',
1459 array('notice' => $this->id));
1465 * Determine which notice, if any, a new notice is in reply to.
1467 * For conversation tracking, we try to see where this notice fits
1468 * in the tree. Rough algorithm is:
1470 * if (reply_to is set and valid) {
1472 * } else if ((source not API or Web) and (content starts with "T NAME" or "@name ")) {
1473 * return ID of last notice by initial @name in content;
1476 * Note that all @nickname instances will still be used to save "reply" records,
1477 * so the notice shows up in the mentioned users' "replies" tab.
1479 * @param integer $reply_to ID passed in by Web or API
1480 * @param integer $profile_id ID of author
1481 * @param string $source Source tag, like 'web' or 'gwibber'
1482 * @param string $content Final notice content
1484 * @return integer ID of replied-to notice, or null for not a reply.
1487 static function getReplyTo($reply_to, $profile_id, $source, $content)
1489 static $lb = array('xmpp', 'mail', 'sms', 'omb');
1491 // If $reply_to is specified, we check that it exists, and then
1492 // return it if it does
1494 if (!empty($reply_to)) {
1495 $reply_notice = Notice::staticGet('id', $reply_to);
1496 if (!empty($reply_notice)) {
1501 // If it's not a "low bandwidth" source (one where you can't set
1502 // a reply_to argument), we return. This is mostly web and API
1505 if (!in_array($source, $lb)) {
1509 // Is there an initial @ or T?
1511 if (preg_match('/^T ([A-Z0-9]{1,64}) /', $content, $match) ||
1512 preg_match('/^@([a-z0-9]{1,64})\s+/', $content, $match)) {
1513 $nickname = common_canonical_nickname($match[1]);
1518 // Figure out who that is.
1520 $sender = Profile::staticGet('id', $profile_id);
1521 if (empty($sender)) {
1525 $recipient = common_relative_profile($sender, $nickname, common_sql_now());
1527 if (empty($recipient)) {
1531 // Get their last notice
1533 $last = $recipient->getCurrentNotice();
1535 if (!empty($last)) {
1540 static function maxContent()
1542 $contentlimit = common_config('notice', 'contentlimit');
1543 // null => use global limit (distinct from 0!)
1544 if (is_null($contentlimit)) {
1545 $contentlimit = common_config('site', 'textlimit');
1547 return $contentlimit;
1550 static function contentTooLong($content)
1552 $contentlimit = self::maxContent();
1553 return ($contentlimit > 0 && !empty($content) && (mb_strlen($content) > $contentlimit));
1556 function getLocation()
1560 if (!empty($this->location_id) && !empty($this->location_ns)) {
1561 $location = Location::fromId($this->location_id, $this->location_ns);
1564 if (is_null($location)) { // no ID, or Location::fromId() failed
1565 if (!empty($this->lat) && !empty($this->lon)) {
1566 $location = Location::fromLatLon($this->lat, $this->lon);
1573 function repeat($repeater_id, $source)
1575 $author = Profile::staticGet('id', $this->profile_id);
1577 // TRANS: Message used to repeat a notice. RT is the abbreviation of 'retweet'.
1578 // TRANS: %1$s is the repeated user's name, %2$s is the repeated notice.
1579 $content = sprintf(_('RT @%1$s %2$s'),
1583 $maxlen = common_config('site', 'textlimit');
1584 if ($maxlen > 0 && mb_strlen($content) > $maxlen) {
1585 // Web interface and current Twitter API clients will
1586 // pull the original notice's text, but some older
1587 // clients and RSS/Atom feeds will see this trimmed text.
1589 // Unfortunately this is likely to lose tags or URLs
1590 // at the end of long notices.
1591 $content = mb_substr($content, 0, $maxlen - 4) . ' ...';
1594 // Scope is same as this one's
1596 return self::saveNew($repeater_id,
1599 array('repeat_of' => $this->id,
1600 'scope' => $this->scope));
1603 // These are supposed to be in chron order!
1605 function repeatStream($limit=100)
1607 $cache = Cache::instance();
1609 if (empty($cache)) {
1610 $ids = $this->_repeatStreamDirect($limit);
1612 $idstr = $cache->get(Cache::key('notice:repeats:'.$this->id));
1613 if ($idstr !== false) {
1614 $ids = explode(',', $idstr);
1616 $ids = $this->_repeatStreamDirect(100);
1617 $cache->set(Cache::key('notice:repeats:'.$this->id), implode(',', $ids));
1620 // We do a max of 100, so slice down to limit
1621 $ids = array_slice($ids, 0, $limit);
1625 return NoticeStream::getStreamByIds($ids);
1628 function _repeatStreamDirect($limit)
1630 $notice = new Notice();
1632 $notice->selectAdd(); // clears it
1633 $notice->selectAdd('id');
1635 $notice->repeat_of = $this->id;
1637 $notice->orderBy('created, id'); // NB: asc!
1639 if (!is_null($limit)) {
1640 $notice->limit(0, $limit);
1645 if ($notice->find()) {
1646 while ($notice->fetch()) {
1647 $ids[] = $notice->id;
1657 function locationOptions($lat, $lon, $location_id, $location_ns, $profile = null)
1661 if (!empty($location_id) && !empty($location_ns)) {
1662 $options['location_id'] = $location_id;
1663 $options['location_ns'] = $location_ns;
1665 $location = Location::fromId($location_id, $location_ns);
1667 if (!empty($location)) {
1668 $options['lat'] = $location->lat;
1669 $options['lon'] = $location->lon;
1672 } else if (!empty($lat) && !empty($lon)) {
1673 $options['lat'] = $lat;
1674 $options['lon'] = $lon;
1676 $location = Location::fromLatLon($lat, $lon);
1678 if (!empty($location)) {
1679 $options['location_id'] = $location->location_id;
1680 $options['location_ns'] = $location->location_ns;
1682 } else if (!empty($profile)) {
1683 if (isset($profile->lat) && isset($profile->lon)) {
1684 $options['lat'] = $profile->lat;
1685 $options['lon'] = $profile->lon;
1688 if (isset($profile->location_id) && isset($profile->location_ns)) {
1689 $options['location_id'] = $profile->location_id;
1690 $options['location_ns'] = $profile->location_ns;
1697 function clearReplies()
1699 $replyNotice = new Notice();
1700 $replyNotice->reply_to = $this->id;
1702 //Null any notices that are replies to this notice
1704 if ($replyNotice->find()) {
1705 while ($replyNotice->fetch()) {
1706 $orig = clone($replyNotice);
1707 $replyNotice->reply_to = null;
1708 $replyNotice->update($orig);
1714 $reply = new Reply();
1715 $reply->notice_id = $this->id;
1717 if ($reply->find()) {
1718 while($reply->fetch()) {
1719 self::blow('reply:stream:%d', $reply->profile_id);
1727 function clearFiles()
1729 $f2p = new File_to_post();
1731 $f2p->post_id = $this->id;
1734 while ($f2p->fetch()) {
1738 // FIXME: decide whether to delete File objects
1739 // ...and related (actual) files
1742 function clearRepeats()
1744 $repeatNotice = new Notice();
1745 $repeatNotice->repeat_of = $this->id;
1747 //Null any notices that are repeats of this notice
1749 if ($repeatNotice->find()) {
1750 while ($repeatNotice->fetch()) {
1751 $orig = clone($repeatNotice);
1752 $repeatNotice->repeat_of = null;
1753 $repeatNotice->update($orig);
1758 function clearFaves()
1761 $fave->notice_id = $this->id;
1763 if ($fave->find()) {
1764 while ($fave->fetch()) {
1765 self::blow('fave:ids_by_user_own:%d', $fave->user_id);
1766 self::blow('fave:ids_by_user_own:%d;last', $fave->user_id);
1767 self::blow('fave:ids_by_user:%d', $fave->user_id);
1768 self::blow('fave:ids_by_user:%d;last', $fave->user_id);
1776 function clearTags()
1778 $tag = new Notice_tag();
1779 $tag->notice_id = $this->id;
1782 while ($tag->fetch()) {
1783 self::blow('profile:notice_ids_tagged:%d:%s', $this->profile_id, Cache::keyize($tag->tag));
1784 self::blow('profile:notice_ids_tagged:%d:%s;last', $this->profile_id, Cache::keyize($tag->tag));
1785 self::blow('notice_tag:notice_ids:%s', Cache::keyize($tag->tag));
1786 self::blow('notice_tag:notice_ids:%s;last', Cache::keyize($tag->tag));
1794 function clearGroupInboxes()
1796 $gi = new Group_inbox();
1798 $gi->notice_id = $this->id;
1801 while ($gi->fetch()) {
1802 self::blow('user_group:notice_ids:%d', $gi->group_id);
1810 function distribute()
1812 // We always insert for the author so they don't
1814 Event::handle('StartNoticeDistribute', array($this));
1816 $user = User::staticGet('id', $this->profile_id);
1817 if (!empty($user)) {
1818 Inbox::insertNotice($user->id, $this->id);
1821 if (common_config('queue', 'inboxes')) {
1822 // If there's a failure, we want to _force_
1823 // distribution at this point.
1825 $qm = QueueManager::get();
1826 $qm->enqueue($this, 'distrib');
1827 } catch (Exception $e) {
1828 // If the exception isn't transient, this
1829 // may throw more exceptions as DQH does
1830 // its own enqueueing. So, we ignore them!
1832 $handler = new DistribQueueHandler();
1833 $handler->handle($this);
1834 } catch (Exception $e) {
1835 common_log(LOG_ERR, "emergency redistribution resulted in " . $e->getMessage());
1837 // Re-throw so somebody smarter can handle it.
1841 $handler = new DistribQueueHandler();
1842 $handler->handle($this);
1848 $result = parent::insert();
1851 // Profile::hasRepeated() abuses pkeyGet(), so we
1852 // have to clear manually
1853 if (!empty($this->repeat_of)) {
1854 $c = self::memcache();
1856 $ck = self::multicacheKey('Notice',
1857 array('profile_id' => $this->profile_id,
1858 'repeat_of' => $this->repeat_of));
1868 * Get the source of the notice
1870 * @return Notice_source $ns A notice source object. 'code' is the only attribute
1871 * guaranteed to be populated.
1873 function getSource()
1875 $ns = new Notice_source();
1876 if (!empty($this->source)) {
1877 switch ($this->source) {
1884 $ns->code = $this->source;
1887 $ns = Notice_source::staticGet($this->source);
1889 $ns = new Notice_source();
1890 $ns->code = $this->source;
1891 $app = Oauth_application::staticGet('name', $this->source);
1893 $ns->name = $app->name;
1894 $ns->url = $app->source_url;
1904 * Determine whether the notice was locally created
1906 * @return boolean locality
1909 public function isLocal()
1911 return ($this->is_local == Notice::LOCAL_PUBLIC ||
1912 $this->is_local == Notice::LOCAL_NONPUBLIC);
1916 * Get the list of hash tags saved with this notice.
1918 * @return array of strings
1920 public function getTags()
1923 $tag = new Notice_tag();
1924 $tag->notice_id = $this->id;
1926 while ($tag->fetch()) {
1927 $tags[] = $tag->tag;
1934 static private function utcDate($dt)
1936 $dateStr = date('d F Y H:i:s', strtotime($dt));
1937 $d = new DateTime($dateStr, new DateTimeZone('UTC'));
1938 return $d->format(DATE_W3C);
1942 * Look up the creation timestamp for a given notice ID, even
1943 * if it's been deleted.
1946 * @return mixed string recorded creation timestamp, or false if can't be found
1948 public static function getAsTimestamp($id)
1954 $notice = Notice::staticGet('id', $id);
1956 return $notice->created;
1959 $deleted = Deleted_notice::staticGet('id', $id);
1961 return $deleted->created;
1968 * Build an SQL 'where' fragment for timestamp-based sorting from a since_id
1969 * parameter, matching notices posted after the given one (exclusive).
1971 * If the referenced notice can't be found, will return false.
1974 * @param string $idField
1975 * @param string $createdField
1976 * @return mixed string or false if no match
1978 public static function whereSinceId($id, $idField='id', $createdField='created')
1980 $since = Notice::getAsTimestamp($id);
1982 return sprintf("($createdField = '%s' and $idField > %d) or ($createdField > '%s')", $since, $id, $since);
1988 * Build an SQL 'where' fragment for timestamp-based sorting from a since_id
1989 * parameter, matching notices posted after the given one (exclusive), and
1990 * if necessary add it to the data object's query.
1992 * @param DB_DataObject $obj
1994 * @param string $idField
1995 * @param string $createdField
1996 * @return mixed string or false if no match
1998 public static function addWhereSinceId(DB_DataObject $obj, $id, $idField='id', $createdField='created')
2000 $since = self::whereSinceId($id, $idField, $createdField);
2002 $obj->whereAdd($since);
2007 * Build an SQL 'where' fragment for timestamp-based sorting from a max_id
2008 * parameter, matching notices posted before the given one (inclusive).
2010 * If the referenced notice can't be found, will return false.
2013 * @param string $idField
2014 * @param string $createdField
2015 * @return mixed string or false if no match
2017 public static function whereMaxId($id, $idField='id', $createdField='created')
2019 $max = Notice::getAsTimestamp($id);
2021 return sprintf("($createdField < '%s') or ($createdField = '%s' and $idField <= %d)", $max, $max, $id);
2027 * Build an SQL 'where' fragment for timestamp-based sorting from a max_id
2028 * parameter, matching notices posted before the given one (inclusive), and
2029 * if necessary add it to the data object's query.
2031 * @param DB_DataObject $obj
2033 * @param string $idField
2034 * @param string $createdField
2035 * @return mixed string or false if no match
2037 public static function addWhereMaxId(DB_DataObject $obj, $id, $idField='id', $createdField='created')
2039 $max = self::whereMaxId($id, $idField, $createdField);
2041 $obj->whereAdd($max);
2047 if (common_config('public', 'localonly')) {
2048 return ($this->is_local == Notice::LOCAL_PUBLIC);
2050 return (($this->is_local != Notice::LOCAL_NONPUBLIC) &&
2051 ($this->is_local != Notice::GATEWAY));
2056 * Check that the given profile is allowed to read, respond to, or otherwise
2057 * act on this notice.
2059 * The $scope member is a bitmask of scopes, representing a logical AND of the
2060 * scope requirement. So, 0x03 (Notice::ADDRESSEE_SCOPE | Notice::SITE_SCOPE) means
2061 * "only visible to people who are mentioned in the notice AND are users on this site."
2062 * Users on the site who are not mentioned in the notice will not be able to see the
2065 * @param Profile $profile The profile to check
2067 * @return boolean whether the profile is in the notice's scope
2069 function inScope($profile)
2071 // If there's no scope, anyone (even anon) is in scope.
2073 if ($this->scope == 0) {
2077 // If there's scope, anon cannot be in scope
2079 if (empty($profile)) {
2083 // Author is always in scope
2085 if ($this->profile_id == $profile->id) {
2089 // Only for users on this site
2091 if ($this->scope & Notice::SITE_SCOPE) {
2092 $user = $profile->getUser();
2098 // Only for users mentioned in the notice
2100 if ($this->scope & Notice::ADDRESSEE_SCOPE) {
2102 // XXX: just query for the single reply
2104 $replies = $this->getReplies();
2106 if (!in_array($profile->id, $replies)) {
2111 // Only for members of the given group
2113 if ($this->scope & Notice::GROUP_SCOPE) {
2115 // XXX: just query for the single membership
2117 $groups = $this->getGroups();
2121 foreach ($groups as $group) {
2122 if ($profile->isMember($group)) {
2133 // Only for followers of the author
2135 if ($this->scope & Notice::FOLLOWER_SCOPE) {
2136 $author = $this->getProfile();
2137 if (!Subscription::exists($profile, $author)) {