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;
99 protected $_profile = -1;
101 function getProfile()
103 if (is_int($this->_profile) && $this->_profile == -1) {
104 $this->_profile = Profile::staticGet('id', $this->profile_id);
106 if (empty($this->_profile)) {
107 // TRANS: Server exception thrown when a user profile for a notice cannot be found.
108 // TRANS: %1$d is a profile ID (number), %2$d is a notice ID (number).
109 throw new ServerException(sprintf(_('No such profile (%1$d) for notice (%2$d).'), $this->profile_id, $this->id));
113 return $this->_profile;
118 // For auditing purposes, save a record that the notice
121 // @fixme we have some cases where things get re-run and so the
123 $deleted = Deleted_notice::staticGet('id', $this->id);
126 $deleted = Deleted_notice::staticGet('uri', $this->uri);
130 $deleted = new Deleted_notice();
132 $deleted->id = $this->id;
133 $deleted->profile_id = $this->profile_id;
134 $deleted->uri = $this->uri;
135 $deleted->created = $this->created;
136 $deleted->deleted = common_sql_now();
141 if (Event::handle('NoticeDeleteRelated', array($this))) {
143 // Clear related records
145 $this->clearReplies();
146 $this->clearRepeats();
149 $this->clearGroupInboxes();
152 // NOTE: we don't clear inboxes
153 // NOTE: we don't clear queue items
156 $result = parent::delete();
158 $this->blowOnDelete();
163 * Extract #hashtags from this notice's content and save them to the database.
167 /* extract all #hastags */
168 $count = preg_match_all('/(?:^|\s)#([\pL\pN_\-\.]{1,64})/u', strtolower($this->content), $match);
173 /* Add them to the database */
174 return $this->saveKnownTags($match[1]);
178 * Record the given set of hash tags in the db for this notice.
179 * Given tag strings will be normalized and checked for dupes.
181 function saveKnownTags($hashtags)
183 //turn each into their canonical tag
184 //this is needed to remove dupes before saving e.g. #hash.tag = #hashtag
185 for($i=0; $i<count($hashtags); $i++) {
186 /* elide characters we don't want in the tag */
187 $hashtags[$i] = common_canonical_tag($hashtags[$i]);
190 foreach(array_unique($hashtags) as $hashtag) {
191 $this->saveTag($hashtag);
192 self::blow('profile:notice_ids_tagged:%d:%s', $this->profile_id, $hashtag);
198 * Record a single hash tag as associated with this notice.
199 * Tag format and uniqueness must be validated by caller.
201 function saveTag($hashtag)
203 $tag = new Notice_tag();
204 $tag->notice_id = $this->id;
205 $tag->tag = $hashtag;
206 $tag->created = $this->created;
207 $id = $tag->insert();
210 // TRANS: Server exception. %s are the error details.
211 throw new ServerException(sprintf(_('Database error inserting hashtag: %s.'),
212 $last_error->message));
216 // if it's saved, blow its cache
217 $tag->blowCache(false);
221 * Save a new notice and push it out to subscribers' inboxes.
222 * Poster's permissions are checked before sending.
224 * @param int $profile_id Profile ID of the poster
225 * @param string $content source message text; links may be shortened
226 * per current user's preference
227 * @param string $source source key ('web', 'api', etc)
228 * @param array $options Associative array of optional properties:
229 * string 'created' timestamp of notice; defaults to now
230 * int 'is_local' source/gateway ID, one of:
231 * Notice::LOCAL_PUBLIC - Local, ok to appear in public timeline
232 * Notice::REMOTE_OMB - Sent from a remote OMB service;
233 * hide from public timeline but show in
234 * local "and friends" timelines
235 * Notice::LOCAL_NONPUBLIC - Local, but hide from public timeline
236 * Notice::GATEWAY - From another non-OMB service;
237 * will not appear in public views
238 * float 'lat' decimal latitude for geolocation
239 * float 'lon' decimal longitude for geolocation
240 * int 'location_id' geoname identifier
241 * int 'location_ns' geoname namespace to interpret location_id
242 * int 'reply_to'; notice ID this is a reply to
243 * int 'repeat_of'; notice ID this is a repeat of
244 * string 'uri' unique ID for notice; defaults to local notice URL
245 * string 'url' permalink to notice; defaults to local notice URL
246 * string 'rendered' rendered HTML version of content
247 * array 'replies' list of profile URIs for reply delivery in
248 * place of extracting @-replies from content.
249 * array 'groups' list of group IDs to deliver to, in place of
250 * extracting ! tags from content
251 * array 'tags' list of hashtag strings to save with the notice
252 * in place of extracting # tags from content
253 * array 'urls' list of attached/referred URLs to save with the
254 * notice in place of extracting links from content
255 * boolean 'distribute' whether to distribute the notice, default true
256 * string 'object_type' URL of the associated object type (default ActivityObject::NOTE)
257 * int 'scope' Scope bitmask; default to SITE_SCOPE on private sites, 0 otherwise
259 * @fixme tag override
262 * @throws ClientException
264 static function saveNew($profile_id, $content, $source, $options=null) {
265 $defaults = array('uri' => null,
270 'distribute' => true);
272 if (!empty($options)) {
273 $options = $options + $defaults;
279 if (!isset($is_local)) {
280 $is_local = Notice::LOCAL_PUBLIC;
283 $profile = Profile::staticGet('id', $profile_id);
284 $user = User::staticGet('id', $profile_id);
286 // Use the local user's shortening preferences, if applicable.
287 $final = $user->shortenLinks($content);
289 $final = common_shorten_links($content);
292 if (Notice::contentTooLong($final)) {
293 // TRANS: Client exception thrown if a notice contains too many characters.
294 throw new ClientException(_('Problem saving notice. Too long.'));
297 if (empty($profile)) {
298 // TRANS: Client exception thrown when trying to save a notice for an unknown user.
299 throw new ClientException(_('Problem saving notice. Unknown user.'));
302 if (common_config('throttle', 'enabled') && !Notice::checkEditThrottle($profile_id)) {
303 common_log(LOG_WARNING, 'Excessive posting by profile #' . $profile_id . '; throttled.');
304 // TRANS: Client exception thrown when a user tries to post too many notices in a given time frame.
305 throw new ClientException(_('Too many notices too fast; take a breather '.
306 'and post again in a few minutes.'));
309 if (common_config('site', 'dupelimit') > 0 && !Notice::checkDupes($profile_id, $final)) {
310 common_log(LOG_WARNING, 'Dupe posting by profile #' . $profile_id . '; throttled.');
311 // TRANS: Client exception thrown when a user tries to post too many duplicate notices in a given time frame.
312 throw new ClientException(_('Too many duplicate messages too quickly;'.
313 ' take a breather and post again in a few minutes.'));
316 if (!$profile->hasRight(Right::NEWNOTICE)) {
317 common_log(LOG_WARNING, "Attempted post from user disallowed to post: " . $profile->nickname);
319 // TRANS: Client exception thrown when a user tries to post while being banned.
320 throw new ClientException(_('You are banned from posting notices on this site.'), 403);
323 $notice = new Notice();
324 $notice->profile_id = $profile_id;
326 $autosource = common_config('public', 'autosource');
328 // Sandboxed are non-false, but not 1, either
330 if (!$profile->hasRight(Right::PUBLICNOTICE) ||
331 ($source && $autosource && in_array($source, $autosource))) {
332 $notice->is_local = Notice::LOCAL_NONPUBLIC;
334 $notice->is_local = $is_local;
337 if (!empty($created)) {
338 $notice->created = $created;
340 $notice->created = common_sql_now();
343 $notice->content = $final;
345 $notice->source = $source;
349 // Get the groups here so we can figure out replies and such
351 if (!isset($groups)) {
352 $groups = self::groupsFromText($notice->content, $profile);
357 // Handle repeat case
359 if (isset($repeat_of)) {
361 // Check for a private one
363 $repeat = Notice::staticGet('id', $repeat_of);
365 if (empty($repeat)) {
366 // TRANS: Client exception thrown in notice when trying to repeat a missing or deleted notice.
367 throw new ClientException(_('Cannot repeat; original notice is missing or deleted.'));
370 if ($profile->id == $repeat->profile_id) {
371 // TRANS: Client error displayed when trying to repeat an own notice.
372 throw new ClientException(_('You cannot repeat your own notice.'));
375 if ($repeat->scope != Notice::SITE_SCOPE &&
376 $repeat->scope != Notice::PUBLIC_SCOPE) {
377 // TRANS: Client error displayed when trying to repeat a non-public notice.
378 throw new ClientException(_('Cannot repeat a private notice.'), 403);
381 if (!$repeat->inScope($profile)) {
382 // The generic checks above should cover this, but let's be sure!
383 // TRANS: Client error displayed when trying to repeat a notice you cannot access.
384 throw new ClientException(_('Cannot repeat a notice you cannot read.'), 403);
387 if ($profile->hasRepeated($repeat->id)) {
388 // TRANS: Client error displayed when trying to repeat an already repeated notice.
389 throw new ClientException(_('You already repeated that notice.'));
392 $notice->repeat_of = $repeat_of;
394 $reply = self::getReplyTo($reply_to, $profile_id, $source, $final);
396 if (!empty($reply)) {
398 if (!$reply->inScope($profile)) {
399 // TRANS: Client error displayed when trying to reply to a notice a the target has no access to.
400 // TRANS: %1$s is a user nickname, %2$d is a notice ID (number).
401 throw new ClientException(sprintf(_('%1$s has no access to notice %2$d.'),
402 $profile->nickname, $reply->id), 403);
405 $notice->reply_to = $reply->id;
406 $notice->conversation = $reply->conversation;
408 // If the original is private to a group, and notice has no group specified,
409 // make it to the same group(s)
411 if (empty($groups) && ($reply->scope | Notice::GROUP_SCOPE)) {
413 $replyGroups = $reply->getGroups();
414 foreach ($replyGroups as $group) {
415 if ($profile->isMember($group)) {
416 $groups[] = $group->id;
425 if (!empty($lat) && !empty($lon)) {
430 if (!empty($location_ns) && !empty($location_id)) {
431 $notice->location_id = $location_id;
432 $notice->location_ns = $location_ns;
435 if (!empty($rendered)) {
436 $notice->rendered = $rendered;
438 $notice->rendered = common_render_content($final, $notice);
441 if (empty($object_type)) {
442 $notice->object_type = (empty($notice->reply_to)) ? ActivityObject::NOTE : ActivityObject::COMMENT;
444 $notice->object_type = $object_type;
447 if (is_null($scope)) { // 0 is a valid value
448 if (!empty($reply)) {
449 $notice->scope = $reply->scope;
451 $notice->scope = common_config('notice', 'defaultscope');
454 $notice->scope = $scope;
457 // For private streams
459 $user = $profile->getUser();
462 if ($user->private_stream &&
463 ($notice->scope == Notice::PUBLIC_SCOPE ||
464 $notice->scope == Notice::SITE_SCOPE)) {
465 $notice->scope |= Notice::FOLLOWER_SCOPE;
469 // Force the scope for private groups
471 foreach ($groups as $groupId) {
472 $group = User_group::staticGet('id', $groupId);
473 if (!empty($group)) {
474 if ($group->force_scope) {
475 $notice->scope |= Notice::GROUP_SCOPE;
481 if (Event::handle('StartNoticeSave', array(&$notice))) {
483 // XXX: some of these functions write to the DB
485 $id = $notice->insert();
488 common_log_db_error($notice, 'INSERT', __FILE__);
489 // TRANS: Server exception thrown when a notice cannot be saved.
490 throw new ServerException(_('Problem saving notice.'));
493 // Update ID-dependent columns: URI, conversation
495 $orig = clone($notice);
500 $notice->uri = common_notice_uri($notice);
504 // If it's not part of a conversation, it's
505 // the beginning of a new conversation.
507 if (empty($notice->conversation)) {
508 $conv = Conversation::create();
509 $notice->conversation = $conv->id;
514 if (!$notice->update($orig)) {
515 common_log_db_error($notice, 'UPDATE', __FILE__);
516 // TRANS: Server exception thrown when a notice cannot be updated.
517 throw new ServerException(_('Problem saving notice.'));
523 // Clear the cache for subscribed users, so they'll update at next request
524 // XXX: someone clever could prepend instead of clearing the cache
526 $notice->blowOnInsert();
528 // Save per-notice metadata...
530 if (isset($replies)) {
531 $notice->saveKnownReplies($replies);
533 $notice->saveReplies();
537 $notice->saveKnownTags($tags);
542 // Note: groups may save tags, so must be run after tags are saved
543 // to avoid errors on duplicates.
544 // Note: groups should always be set.
546 $notice->saveKnownGroups($groups);
548 if (isset($peopletags)) {
549 $notice->saveProfileTags($peopletags);
551 $notice->saveProfileTags();
555 $notice->saveKnownUrls($urls);
561 // Prepare inbox delivery, may be queued to background.
562 $notice->distribute();
568 function blowOnInsert($conversation = false)
570 self::blow('profile:notice_ids:%d', $this->profile_id);
572 if ($this->isPublic()) {
573 self::blow('public');
576 // XXX: Before we were blowing the casche only if the notice id
577 // was not the root of the conversation. What to do now?
579 self::blow('notice:conversation_ids:%d', $this->conversation);
580 self::blow('conversation::notice_count:%d', $this->conversation);
582 if (!empty($this->repeat_of)) {
583 self::blow('notice:repeats:%d', $this->repeat_of);
586 $original = Notice::staticGet('id', $this->repeat_of);
588 if (!empty($original)) {
589 $originalUser = User::staticGet('id', $original->profile_id);
590 if (!empty($originalUser)) {
591 self::blow('user:repeats_of_me:%d', $originalUser->id);
595 $profile = Profile::staticGet($this->profile_id);
596 if (!empty($profile)) {
597 $profile->blowNoticeCount();
602 * Clear cache entries related to this notice at delete time.
603 * Necessary to avoid breaking paging on public, profile timelines.
605 function blowOnDelete()
607 $this->blowOnInsert();
609 self::blow('profile:notice_ids:%d;last', $this->profile_id);
611 if ($this->isPublic()) {
612 self::blow('public;last');
615 self::blow('fave:by_notice', $this->id);
617 if ($this->conversation) {
618 // In case we're the first, will need to calc a new root.
619 self::blow('notice:conversation_root:%d', $this->conversation);
623 /** save all urls in the notice to the db
625 * follow redirects and save all available file information
626 * (mimetype, date, size, oembed, etc.)
630 function saveUrls() {
631 if (common_config('attachments', 'process_links')) {
632 common_replace_urls_callback($this->content, array($this, 'saveUrl'), $this->id);
637 * Save the given URLs as related links/attachments to the db
639 * follow redirects and save all available file information
640 * (mimetype, date, size, oembed, etc.)
644 function saveKnownUrls($urls)
646 if (common_config('attachments', 'process_links')) {
647 // @fixme validation?
648 foreach (array_unique($urls) as $url) {
649 File::processNew($url, $this->id);
657 function saveUrl($url, $notice_id) {
658 File::processNew($url, $notice_id);
661 static function checkDupes($profile_id, $content) {
662 $profile = Profile::staticGet($profile_id);
663 if (empty($profile)) {
666 $notice = $profile->getNotices(0, CachingNoticeStream::CACHE_WINDOW);
667 if (!empty($notice)) {
669 while ($notice->fetch()) {
670 if (time() - strtotime($notice->created) >= common_config('site', 'dupelimit')) {
672 } else if ($notice->content == $content) {
677 // If we get here, oldest item in cache window is not
678 // old enough for dupe limit; do direct check against DB
679 $notice = new Notice();
680 $notice->profile_id = $profile_id;
681 $notice->content = $content;
682 $threshold = common_sql_date(time() - common_config('site', 'dupelimit'));
683 $notice->whereAdd(sprintf("created > '%s'", $notice->escape($threshold)));
685 $cnt = $notice->count();
689 static function checkEditThrottle($profile_id) {
690 $profile = Profile::staticGet($profile_id);
691 if (empty($profile)) {
694 // Get the Nth notice
695 $notice = $profile->getNotices(common_config('throttle', 'count') - 1, 1);
696 if ($notice && $notice->fetch()) {
697 // If the Nth notice was posted less than timespan seconds ago
698 if (time() - strtotime($notice->created) <= common_config('throttle', 'timespan')) {
703 // Either not N notices in the stream, OR the Nth was not posted within timespan seconds
707 function getUploadedAttachment() {
709 $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"';
710 $post->query($query);
712 if (empty($post->up) || empty($post->i)) {
715 $ret = array($post->up, $post->i);
721 function hasAttachments() {
723 $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);
724 $post->query($query);
726 $n_attachments = intval($post->n_attachments);
728 return $n_attachments;
731 function attachments() {
733 $keypart = sprintf('notice:file_ids:%d', $this->id);
735 $idstr = self::cacheGet($keypart);
737 if ($idstr !== false) {
738 $ids = explode(',', $idstr);
741 $f2p = new File_to_post;
742 $f2p->post_id = $this->id;
744 while ($f2p->fetch()) {
745 $ids[] = $f2p->file_id;
748 self::cacheSet($keypart, implode(',', $ids));
753 foreach ($ids as $id) {
754 $f = File::staticGet('id', $id);
764 function publicStream($offset=0, $limit=20, $since_id=0, $max_id=0)
766 $stream = new PublicNoticeStream();
767 return $stream->getNotices($offset, $limit, $since_id, $max_id);
771 function conversationStream($id, $offset=0, $limit=20, $since_id=0, $max_id=0)
773 $stream = new ConversationNoticeStream($id);
775 return $stream->getNotices($offset, $limit, $since_id, $max_id);
779 * Is this notice part of an active conversation?
781 * @return boolean true if other messages exist in the same
782 * conversation, false if this is the only one
784 function hasConversation()
786 if (!empty($this->conversation)) {
787 $conversation = Notice::conversationStream(
793 if ($conversation->N > 0) {
801 * Grab the earliest notice from this conversation.
803 * @return Notice or null
805 function conversationRoot()
807 if (!empty($this->conversation)) {
808 $c = self::memcache();
810 $key = Cache::key('notice:conversation_root:' . $this->conversation);
811 $notice = $c->get($key);
816 $notice = new Notice();
817 $notice->conversation = $this->conversation;
818 $notice->orderBy('CREATED');
823 $c->set($key, $notice);
830 * Pull up a full list of local recipients who will be getting
831 * this notice in their inbox. Results will be cached, so don't
832 * change the input data wily-nilly!
834 * @param array $groups optional list of Group objects;
835 * if left empty, will be loaded from group_inbox records
836 * @param array $recipient optional list of reply profile ids
837 * if left empty, will be loaded from reply records
838 * @return array associating recipient user IDs with an inbox source constant
840 function whoGets($groups=null, $recipients=null)
842 $c = self::memcache();
845 $ni = $c->get(Cache::key('notice:who_gets:'.$this->id));
851 if (is_null($groups)) {
852 $groups = $this->getGroups();
855 if (is_null($recipients)) {
856 $recipients = $this->getReplies();
859 $users = $this->getSubscribedUsers();
860 $ptags = $this->getProfileTags();
862 // FIXME: kind of ignoring 'transitional'...
863 // we'll probably stop supporting inboxless mode
868 // Give plugins a chance to add folks in at start...
869 if (Event::handle('StartNoticeWhoGets', array($this, &$ni))) {
871 foreach ($users as $id) {
872 $ni[$id] = NOTICE_INBOX_SOURCE_SUB;
875 foreach ($groups as $group) {
876 $users = $group->getUserMembers();
877 foreach ($users as $id) {
878 if (!array_key_exists($id, $ni)) {
879 $ni[$id] = NOTICE_INBOX_SOURCE_GROUP;
884 foreach ($ptags as $ptag) {
885 $users = $ptag->getUserSubscribers();
886 foreach ($users as $id) {
887 if (!array_key_exists($id, $ni)) {
888 $user = User::staticGet('id', $id);
889 if (!$user->hasBlocked($profile)) {
890 $ni[$id] = NOTICE_INBOX_SOURCE_PROFILE_TAG;
896 foreach ($recipients as $recipient) {
897 if (!array_key_exists($recipient, $ni)) {
898 $ni[$recipient] = NOTICE_INBOX_SOURCE_REPLY;
901 // Exclude any deleted, non-local, or blocking recipients.
902 $profile = $this->getProfile();
903 $originalProfile = null;
904 if ($this->repeat_of) {
905 // Check blocks against the original notice's poster as well.
906 $original = Notice::staticGet('id', $this->repeat_of);
908 $originalProfile = $original->getProfile();
911 foreach ($ni as $id => $source) {
912 $user = User::staticGet('id', $id);
913 if (empty($user) || $user->hasBlocked($profile) ||
914 ($originalProfile && $user->hasBlocked($originalProfile))) {
920 // Give plugins a chance to filter out...
921 Event::handle('EndNoticeWhoGets', array($this, &$ni));
925 // XXX: pack this data better
926 $c->set(Cache::key('notice:who_gets:'.$this->id), $ni);
933 * Adds this notice to the inboxes of each local user who should receive
934 * it, based on author subscriptions, group memberships, and @-replies.
936 * Warning: running a second time currently will make items appear
937 * multiple times in users' inboxes.
939 * @fixme make more robust against errors
940 * @fixme break up massive deliveries to smaller background tasks
942 * @param array $groups optional list of Group objects;
943 * if left empty, will be loaded from group_inbox records
944 * @param array $recipient optional list of reply profile ids
945 * if left empty, will be loaded from reply records
947 function addToInboxes($groups=null, $recipients=null)
949 $ni = $this->whoGets($groups, $recipients);
951 $ids = array_keys($ni);
953 // We remove the author (if they're a local user),
954 // since we'll have already done this in distribute()
956 $i = array_search($this->profile_id, $ids);
964 Inbox::bulkInsert($this->id, $ids);
969 function getSubscribedUsers()
973 if(common_config('db','quote_identifiers'))
974 $user_table = '"user"';
975 else $user_table = 'user';
979 'FROM '. $user_table .' JOIN subscription '.
980 'ON '. $user_table .'.id = subscription.subscriber ' .
981 'WHERE subscription.subscribed = %d ';
983 $user->query(sprintf($qry, $this->profile_id));
987 while ($user->fetch()) {
996 function getProfileTags()
998 // Don't save ptags for repeats, for now.
1000 if (!empty($this->repeat_of)) {
1008 $ptagi = new Profile_tag_inbox();
1010 $ptagi->selectAdd();
1011 $ptagi->selectAdd('profile_tag_id');
1013 $ptagi->notice_id = $this->id;
1015 if ($ptagi->find()) {
1016 while ($ptagi->fetch()) {
1017 $profile_list = Profile_list::staticGet('id', $ptagi->profile_tag_id);
1018 if ($profile_list) {
1019 $ptags[] = $profile_list;
1030 * Record this notice to the given group inboxes for delivery.
1031 * Overrides the regular parsing of !group markup.
1033 * @param string $group_ids
1034 * @fixme might prefer URIs as identifiers, as for replies?
1035 * best with generalizations on user_group to support
1036 * remote groups better.
1038 function saveKnownGroups($group_ids)
1040 if (!is_array($group_ids)) {
1041 // TRANS: Server exception thrown when no array is provided to the method saveKnownGroups().
1042 throw new ServerException(_('Bad type provided to saveKnownGroups.'));
1046 foreach (array_unique($group_ids) as $id) {
1047 $group = User_group::staticGet('id', $id);
1049 common_log(LOG_ERR, "Local delivery to group id $id, $group->nickname");
1050 $result = $this->addToGroupInbox($group);
1052 common_log_db_error($gi, 'INSERT', __FILE__);
1055 // we automatically add a tag for every group name, too
1057 $tag = Notice_tag::pkeyGet(array('tag' => common_canonical_tag($group->nickname),
1058 'notice_id' => $this->id));
1060 if (is_null($tag)) {
1061 $this->saveTag($group->nickname);
1064 $groups[] = clone($group);
1066 common_log(LOG_ERR, "Local delivery to group id $id skipped, doesn't exist");
1074 * Parse !group delivery and record targets into group_inbox.
1075 * @return array of Group objects
1077 function saveGroups()
1079 // Don't save groups for repeats
1081 if (!empty($this->repeat_of)) {
1085 $profile = $this->getProfile();
1087 $groups = self::groupsFromText($this->content, $profile);
1089 /* Add them to the database */
1091 foreach ($groups as $group) {
1092 /* XXX: remote groups. */
1094 if (empty($group)) {
1099 if ($profile->isMember($group)) {
1101 $result = $this->addToGroupInbox($group);
1104 common_log_db_error($gi, 'INSERT', __FILE__);
1107 $groups[] = clone($group);
1114 function addToGroupInbox($group)
1116 $gi = Group_inbox::pkeyGet(array('group_id' => $group->id,
1117 'notice_id' => $this->id));
1121 $gi = new Group_inbox();
1123 $gi->group_id = $group->id;
1124 $gi->notice_id = $this->id;
1125 $gi->created = $this->created;
1127 $result = $gi->insert();
1130 common_log_db_error($gi, 'INSERT', __FILE__);
1131 // TRANS: Server exception thrown when an update for a group inbox fails.
1132 throw new ServerException(_('Problem saving group inbox.'));
1135 self::blow('user_group:notice_ids:%d', $gi->group_id);
1142 * record targets into profile_tag_inbox.
1143 * @return array of Profile_list objects
1145 function saveProfileTags($known=array())
1147 // Don't save ptags for repeats, for now
1149 if (!empty($this->repeat_of)) {
1153 if (is_array($known)) {
1159 $ptag = new Profile_tag();
1160 $ptag->tagged = $this->profile_id;
1163 while($ptag->fetch()) {
1164 $plist = Profile_list::getByTaggerAndTag($ptag->tagger, $ptag->tag);
1165 if (!empty($plist)) {
1166 $ptags[] = clone($plist);
1171 foreach ($ptags as $target) {
1172 $this->addToProfileTagInbox($target);
1178 function addToProfileTagInbox($plist)
1180 $ptagi = Profile_tag_inbox::pkeyGet(array('profile_tag_id' => $plist->id,
1181 'notice_id' => $this->id));
1183 if (empty($ptagi)) {
1185 $ptagi = new Profile_tag_inbox();
1187 $ptagi->query('BEGIN');
1188 $ptagi->profile_tag_id = $plist->id;
1189 $ptagi->notice_id = $this->id;
1190 $ptagi->created = $this->created;
1192 $result = $ptagi->insert();
1194 common_log_db_error($ptagi, 'INSERT', __FILE__);
1195 // TRANS: Server exception thrown when saving profile_tag inbox fails.
1196 throw new ServerException(_('Problem saving profile_tag inbox.'));
1199 $ptagi->query('COMMIT');
1201 self::blow('profile_tag:notice_ids:%d', $ptagi->profile_tag_id);
1208 * Save reply records indicating that this notice needs to be
1209 * delivered to the local users with the given URIs.
1211 * Since this is expected to be used when saving foreign-sourced
1212 * messages, we won't deliver to any remote targets as that's the
1213 * source service's responsibility.
1215 * Mail notifications etc will be handled later.
1217 * @param array of unique identifier URIs for recipients
1219 function saveKnownReplies($uris)
1225 $sender = Profile::staticGet($this->profile_id);
1227 foreach (array_unique($uris) as $uri) {
1229 $profile = Profile::fromURI($uri);
1231 if (empty($profile)) {
1232 common_log(LOG_WARNING, "Unable to determine profile for URI '$uri'");
1236 if ($profile->hasBlocked($sender)) {
1237 common_log(LOG_INFO, "Not saving reply to profile {$profile->id} ($uri) from sender {$sender->id} because of a block.");
1241 $reply = new Reply();
1243 $reply->notice_id = $this->id;
1244 $reply->profile_id = $profile->id;
1245 $reply->modified = $this->created;
1247 common_log(LOG_INFO, __METHOD__ . ": saving reply: notice $this->id to profile $profile->id");
1249 $id = $reply->insert();
1256 * Pull @-replies from this message's content in StatusNet markup format
1257 * and save reply records indicating that this message needs to be
1258 * delivered to those users.
1260 * Mail notifications to local profiles will be sent later.
1262 * @return array of integer profile IDs
1265 function saveReplies()
1267 // Don't save reply data for repeats
1269 if (!empty($this->repeat_of)) {
1273 $sender = Profile::staticGet($this->profile_id);
1275 // @todo ideally this parser information would only
1276 // be calculated once.
1278 $mentions = common_find_mentions($this->content, $this);
1282 // store replied only for first @ (what user/notice what the reply directed,
1283 // we assume first @ is it)
1285 foreach ($mentions as $mention) {
1287 foreach ($mention['mentioned'] as $mentioned) {
1289 // skip if they're already covered
1291 if (!empty($replied[$mentioned->id])) {
1295 // Don't save replies from blocked profile to local user
1297 $mentioned_user = User::staticGet('id', $mentioned->id);
1298 if (!empty($mentioned_user) && $mentioned_user->hasBlocked($sender)) {
1302 $reply = new Reply();
1304 $reply->notice_id = $this->id;
1305 $reply->profile_id = $mentioned->id;
1306 $reply->modified = $this->created;
1308 $id = $reply->insert();
1311 common_log_db_error($reply, 'INSERT', __FILE__);
1312 // TRANS: Server exception thrown when a reply cannot be saved.
1313 // TRANS: %1$d is a notice ID, %2$d is the ID of the mentioned user.
1314 throw new ServerException(sprintf(_('Could not save reply for %1$d, %2$d.'), $this->id, $mentioned->id));
1316 $replied[$mentioned->id] = 1;
1317 self::blow('reply:stream:%d', $mentioned->id);
1322 $recipientIds = array_keys($replied);
1324 return $recipientIds;
1328 * Pull the complete list of @-reply targets for this notice.
1330 * @return array of integer profile ids
1332 function getReplies()
1334 $keypart = sprintf('notice:reply_ids:%d', $this->id);
1336 $idstr = self::cacheGet($keypart);
1338 if ($idstr !== false) {
1339 $ids = explode(',', $idstr);
1343 $reply = new Reply();
1344 $reply->selectAdd();
1345 $reply->selectAdd('profile_id');
1346 $reply->notice_id = $this->id;
1348 if ($reply->find()) {
1349 while($reply->fetch()) {
1350 $ids[] = $reply->profile_id;
1353 self::cacheSet($keypart, implode(',', $ids));
1360 * Send e-mail notifications to local @-reply targets.
1362 * Replies must already have been saved; this is expected to be run
1363 * from the distrib queue handler.
1365 function sendReplyNotifications()
1367 // Don't send reply notifications for repeats
1369 if (!empty($this->repeat_of)) {
1373 $recipientIds = $this->getReplies();
1375 foreach ($recipientIds as $recipientId) {
1376 $user = User::staticGet('id', $recipientId);
1377 if (!empty($user)) {
1378 mail_notify_attn($user, $this);
1384 * Pull list of groups this notice needs to be delivered to,
1385 * as previously recorded by saveGroups() or saveKnownGroups().
1387 * @return array of Group objects
1389 function getGroups()
1391 // Don't save groups for repeats
1393 if (!empty($this->repeat_of)) {
1399 $keypart = sprintf('notice:groups:%d', $this->id);
1401 $idstr = self::cacheGet($keypart);
1403 if ($idstr !== false) {
1404 $ids = explode(',', $idstr);
1406 $gi = new Group_inbox();
1409 $gi->selectAdd('group_id');
1411 $gi->notice_id = $this->id;
1414 while ($gi->fetch()) {
1415 $ids[] = $gi->group_id;
1419 self::cacheSet($keypart, implode(',', $ids));
1424 foreach ($ids as $id) {
1425 $group = User_group::staticGet('id', $id);
1435 * Convert a notice into an activity for export.
1437 * @param User $cur Current user
1439 * @return Activity activity object representing this Notice.
1442 function asActivity($cur)
1444 $act = self::cacheGet(Cache::codeKey('notice:as-activity:'.$this->id));
1449 $act = new Activity();
1451 if (Event::handle('StartNoticeAsActivity', array($this, &$act))) {
1453 $profile = $this->getProfile();
1455 $act->actor = ActivityObject::fromProfile($profile);
1456 $act->actor->extra[] = $profile->profileInfo($cur);
1457 $act->verb = ActivityVerb::POST;
1458 $act->objects[] = ActivityObject::fromNotice($this);
1460 // XXX: should this be handled by default processing for object entry?
1462 $act->time = strtotime($this->created);
1463 $act->link = $this->bestUrl();
1465 $act->content = common_xml_safe_str($this->rendered);
1466 $act->id = $this->uri;
1467 $act->title = common_xml_safe_str($this->content);
1471 $tags = $this->getTags();
1473 foreach ($tags as $tag) {
1474 $cat = new AtomCategory();
1477 $act->categories[] = $cat;
1481 // XXX: use Atom Media and/or File activity objects instead
1483 $attachments = $this->attachments();
1485 foreach ($attachments as $attachment) {
1486 $enclosure = $attachment->getEnclosure();
1488 $act->enclosures[] = $enclosure;
1492 $ctx = new ActivityContext();
1494 if (!empty($this->reply_to)) {
1495 $reply = Notice::staticGet('id', $this->reply_to);
1496 if (!empty($reply)) {
1497 $ctx->replyToID = $reply->uri;
1498 $ctx->replyToUrl = $reply->bestUrl();
1502 $ctx->location = $this->getLocation();
1506 if (!empty($this->conversation)) {
1507 $conv = Conversation::staticGet('id', $this->conversation);
1508 if (!empty($conv)) {
1509 $ctx->conversation = $conv->uri;
1513 $reply_ids = $this->getReplies();
1515 foreach ($reply_ids as $id) {
1516 $rprofile = Profile::staticGet('id', $id);
1517 if (!empty($rprofile)) {
1518 $ctx->attention[] = $rprofile->getUri();
1522 $groups = $this->getGroups();
1524 foreach ($groups as $group) {
1525 $ctx->attention[] = $group->getUri();
1528 // XXX: deprecated; use ActivityVerb::SHARE instead
1532 if (!empty($this->repeat_of)) {
1533 $repeat = Notice::staticGet('id', $this->repeat_of);
1534 $ctx->forwardID = $repeat->uri;
1535 $ctx->forwardUrl = $repeat->bestUrl();
1538 $act->context = $ctx;
1542 $atom_feed = $profile->getAtomFeed();
1544 if (!empty($atom_feed)) {
1546 $act->source = new ActivitySource();
1548 // XXX: we should store the actual feed ID
1550 $act->source->id = $atom_feed;
1552 // XXX: we should store the actual feed title
1554 $act->source->title = $profile->getBestName();
1556 $act->source->links['alternate'] = $profile->profileurl;
1557 $act->source->links['self'] = $atom_feed;
1559 $act->source->icon = $profile->avatarUrl(AVATAR_PROFILE_SIZE);
1561 $notice = $profile->getCurrentNotice();
1563 if (!empty($notice)) {
1564 $act->source->updated = self::utcDate($notice->created);
1567 $user = User::staticGet('id', $profile->id);
1569 if (!empty($user)) {
1570 $act->source->links['license'] = common_config('license', 'url');
1574 if ($this->isLocal()) {
1575 $act->selfLink = common_local_url('ApiStatusesShow', array('id' => $this->id,
1576 'format' => 'atom'));
1577 $act->editLink = $act->selfLink;
1580 Event::handle('EndNoticeAsActivity', array($this, &$act));
1583 self::cacheSet(Cache::codeKey('notice:as-activity:'.$this->id), $act);
1588 // This has gotten way too long. Needs to be sliced up into functional bits
1589 // or ideally exported to a utility class.
1591 function asAtomEntry($namespace=false,
1596 $act = $this->asActivity($cur);
1597 $act->extra[] = $this->noticeInfo($cur);
1598 return $act->asString($namespace, $author, $source);
1602 * Extra notice info for atom entries
1604 * Clients use some extra notice info in the atom stream.
1605 * This gives it to them.
1607 * @param User $cur Current user
1609 * @return array representation of <statusnet:notice_info> element
1612 function noticeInfo($cur)
1614 // local notice ID (useful to clients for ordering)
1616 $noticeInfoAttr = array('local_id' => $this->id);
1620 $ns = $this->getSource();
1623 $noticeInfoAttr['source'] = $ns->code;
1624 if (!empty($ns->url)) {
1625 $noticeInfoAttr['source_link'] = $ns->url;
1626 if (!empty($ns->name)) {
1627 $noticeInfoAttr['source'] = '<a href="'
1628 . htmlspecialchars($ns->url)
1629 . '" rel="nofollow">'
1630 . htmlspecialchars($ns->name)
1636 // favorite and repeated
1639 $noticeInfoAttr['favorite'] = ($cur->hasFave($this)) ? "true" : "false";
1640 $cp = $cur->getProfile();
1641 $noticeInfoAttr['repeated'] = ($cp->hasRepeated($this->id)) ? "true" : "false";
1644 if (!empty($this->repeat_of)) {
1645 $noticeInfoAttr['repeat_of'] = $this->repeat_of;
1648 return array('statusnet:notice_info', $noticeInfoAttr, null);
1652 * Returns an XML string fragment with a reference to a notice as an
1653 * Activity Streams noun object with the given element type.
1655 * Assumes that 'activity' namespace has been previously defined.
1657 * @param string $element one of 'subject', 'object', 'target'
1661 function asActivityNoun($element)
1663 $noun = ActivityObject::fromNotice($this);
1664 return $noun->asString('activity:' . $element);
1669 if (!empty($this->url)) {
1671 } else if (!empty($this->uri) && preg_match('/^https?:/', $this->uri)) {
1674 return common_local_url('shownotice',
1675 array('notice' => $this->id));
1681 * Determine which notice, if any, a new notice is in reply to.
1683 * For conversation tracking, we try to see where this notice fits
1684 * in the tree. Rough algorithm is:
1686 * if (reply_to is set and valid) {
1688 * } else if ((source not API or Web) and (content starts with "T NAME" or "@name ")) {
1689 * return ID of last notice by initial @name in content;
1692 * Note that all @nickname instances will still be used to save "reply" records,
1693 * so the notice shows up in the mentioned users' "replies" tab.
1695 * @param integer $reply_to ID passed in by Web or API
1696 * @param integer $profile_id ID of author
1697 * @param string $source Source tag, like 'web' or 'gwibber'
1698 * @param string $content Final notice content
1700 * @return integer ID of replied-to notice, or null for not a reply.
1703 static function getReplyTo($reply_to, $profile_id, $source, $content)
1705 static $lb = array('xmpp', 'mail', 'sms', 'omb');
1707 // If $reply_to is specified, we check that it exists, and then
1708 // return it if it does
1710 if (!empty($reply_to)) {
1711 $reply_notice = Notice::staticGet('id', $reply_to);
1712 if (!empty($reply_notice)) {
1713 return $reply_notice;
1717 // If it's not a "low bandwidth" source (one where you can't set
1718 // a reply_to argument), we return. This is mostly web and API
1721 if (!in_array($source, $lb)) {
1725 // Is there an initial @ or T?
1727 if (preg_match('/^T ([A-Z0-9]{1,64}) /', $content, $match) ||
1728 preg_match('/^@([a-z0-9]{1,64})\s+/', $content, $match)) {
1729 $nickname = common_canonical_nickname($match[1]);
1734 // Figure out who that is.
1736 $sender = Profile::staticGet('id', $profile_id);
1737 if (empty($sender)) {
1741 $recipient = common_relative_profile($sender, $nickname, common_sql_now());
1743 if (empty($recipient)) {
1747 // Get their last notice
1749 $last = $recipient->getCurrentNotice();
1751 if (!empty($last)) {
1758 static function maxContent()
1760 $contentlimit = common_config('notice', 'contentlimit');
1761 // null => use global limit (distinct from 0!)
1762 if (is_null($contentlimit)) {
1763 $contentlimit = common_config('site', 'textlimit');
1765 return $contentlimit;
1768 static function contentTooLong($content)
1770 $contentlimit = self::maxContent();
1771 return ($contentlimit > 0 && !empty($content) && (mb_strlen($content) > $contentlimit));
1774 function getLocation()
1778 if (!empty($this->location_id) && !empty($this->location_ns)) {
1779 $location = Location::fromId($this->location_id, $this->location_ns);
1782 if (is_null($location)) { // no ID, or Location::fromId() failed
1783 if (!empty($this->lat) && !empty($this->lon)) {
1784 $location = Location::fromLatLon($this->lat, $this->lon);
1792 * Convenience function for posting a repeat of an existing message.
1794 * @param int $repeater_id: profile ID of user doing the repeat
1795 * @param string $source: posting source key, eg 'web', 'api', etc
1798 * @throws Exception on failure or permission problems
1800 function repeat($repeater_id, $source)
1802 $author = Profile::staticGet('id', $this->profile_id);
1804 // TRANS: Message used to repeat a notice. RT is the abbreviation of 'retweet'.
1805 // TRANS: %1$s is the repeated user's name, %2$s is the repeated notice.
1806 $content = sprintf(_('RT @%1$s %2$s'),
1810 $maxlen = common_config('site', 'textlimit');
1811 if ($maxlen > 0 && mb_strlen($content) > $maxlen) {
1812 // Web interface and current Twitter API clients will
1813 // pull the original notice's text, but some older
1814 // clients and RSS/Atom feeds will see this trimmed text.
1816 // Unfortunately this is likely to lose tags or URLs
1817 // at the end of long notices.
1818 $content = mb_substr($content, 0, $maxlen - 4) . ' ...';
1821 // Scope is same as this one's
1823 return self::saveNew($repeater_id,
1826 array('repeat_of' => $this->id,
1827 'scope' => $this->scope));
1830 // These are supposed to be in chron order!
1832 function repeatStream($limit=100)
1834 $cache = Cache::instance();
1836 if (empty($cache)) {
1837 $ids = $this->_repeatStreamDirect($limit);
1839 $idstr = $cache->get(Cache::key('notice:repeats:'.$this->id));
1840 if ($idstr !== false) {
1841 $ids = explode(',', $idstr);
1843 $ids = $this->_repeatStreamDirect(100);
1844 $cache->set(Cache::key('notice:repeats:'.$this->id), implode(',', $ids));
1847 // We do a max of 100, so slice down to limit
1848 $ids = array_slice($ids, 0, $limit);
1852 return NoticeStream::getStreamByIds($ids);
1855 function _repeatStreamDirect($limit)
1857 $notice = new Notice();
1859 $notice->selectAdd(); // clears it
1860 $notice->selectAdd('id');
1862 $notice->repeat_of = $this->id;
1864 $notice->orderBy('created, id'); // NB: asc!
1866 if (!is_null($limit)) {
1867 $notice->limit(0, $limit);
1872 if ($notice->find()) {
1873 while ($notice->fetch()) {
1874 $ids[] = $notice->id;
1884 function locationOptions($lat, $lon, $location_id, $location_ns, $profile = null)
1888 if (!empty($location_id) && !empty($location_ns)) {
1889 $options['location_id'] = $location_id;
1890 $options['location_ns'] = $location_ns;
1892 $location = Location::fromId($location_id, $location_ns);
1894 if (!empty($location)) {
1895 $options['lat'] = $location->lat;
1896 $options['lon'] = $location->lon;
1899 } else if (!empty($lat) && !empty($lon)) {
1900 $options['lat'] = $lat;
1901 $options['lon'] = $lon;
1903 $location = Location::fromLatLon($lat, $lon);
1905 if (!empty($location)) {
1906 $options['location_id'] = $location->location_id;
1907 $options['location_ns'] = $location->location_ns;
1909 } else if (!empty($profile)) {
1910 if (isset($profile->lat) && isset($profile->lon)) {
1911 $options['lat'] = $profile->lat;
1912 $options['lon'] = $profile->lon;
1915 if (isset($profile->location_id) && isset($profile->location_ns)) {
1916 $options['location_id'] = $profile->location_id;
1917 $options['location_ns'] = $profile->location_ns;
1924 function clearReplies()
1926 $replyNotice = new Notice();
1927 $replyNotice->reply_to = $this->id;
1929 //Null any notices that are replies to this notice
1931 if ($replyNotice->find()) {
1932 while ($replyNotice->fetch()) {
1933 $orig = clone($replyNotice);
1934 $replyNotice->reply_to = null;
1935 $replyNotice->update($orig);
1941 $reply = new Reply();
1942 $reply->notice_id = $this->id;
1944 if ($reply->find()) {
1945 while($reply->fetch()) {
1946 self::blow('reply:stream:%d', $reply->profile_id);
1954 function clearFiles()
1956 $f2p = new File_to_post();
1958 $f2p->post_id = $this->id;
1961 while ($f2p->fetch()) {
1965 // FIXME: decide whether to delete File objects
1966 // ...and related (actual) files
1969 function clearRepeats()
1971 $repeatNotice = new Notice();
1972 $repeatNotice->repeat_of = $this->id;
1974 //Null any notices that are repeats of this notice
1976 if ($repeatNotice->find()) {
1977 while ($repeatNotice->fetch()) {
1978 $orig = clone($repeatNotice);
1979 $repeatNotice->repeat_of = null;
1980 $repeatNotice->update($orig);
1985 function clearFaves()
1988 $fave->notice_id = $this->id;
1990 if ($fave->find()) {
1991 while ($fave->fetch()) {
1992 self::blow('fave:ids_by_user_own:%d', $fave->user_id);
1993 self::blow('fave:ids_by_user_own:%d;last', $fave->user_id);
1994 self::blow('fave:ids_by_user:%d', $fave->user_id);
1995 self::blow('fave:ids_by_user:%d;last', $fave->user_id);
2003 function clearTags()
2005 $tag = new Notice_tag();
2006 $tag->notice_id = $this->id;
2009 while ($tag->fetch()) {
2010 self::blow('profile:notice_ids_tagged:%d:%s', $this->profile_id, Cache::keyize($tag->tag));
2011 self::blow('profile:notice_ids_tagged:%d:%s;last', $this->profile_id, Cache::keyize($tag->tag));
2012 self::blow('notice_tag:notice_ids:%s', Cache::keyize($tag->tag));
2013 self::blow('notice_tag:notice_ids:%s;last', Cache::keyize($tag->tag));
2021 function clearGroupInboxes()
2023 $gi = new Group_inbox();
2025 $gi->notice_id = $this->id;
2028 while ($gi->fetch()) {
2029 self::blow('user_group:notice_ids:%d', $gi->group_id);
2037 function distribute()
2039 // We always insert for the author so they don't
2041 Event::handle('StartNoticeDistribute', array($this));
2043 $user = User::staticGet('id', $this->profile_id);
2044 if (!empty($user)) {
2045 Inbox::insertNotice($user->id, $this->id);
2048 if (common_config('queue', 'inboxes')) {
2049 // If there's a failure, we want to _force_
2050 // distribution at this point.
2052 $qm = QueueManager::get();
2053 $qm->enqueue($this, 'distrib');
2054 } catch (Exception $e) {
2055 // If the exception isn't transient, this
2056 // may throw more exceptions as DQH does
2057 // its own enqueueing. So, we ignore them!
2059 $handler = new DistribQueueHandler();
2060 $handler->handle($this);
2061 } catch (Exception $e) {
2062 common_log(LOG_ERR, "emergency redistribution resulted in " . $e->getMessage());
2064 // Re-throw so somebody smarter can handle it.
2068 $handler = new DistribQueueHandler();
2069 $handler->handle($this);
2075 $result = parent::insert();
2078 // Profile::hasRepeated() abuses pkeyGet(), so we
2079 // have to clear manually
2080 if (!empty($this->repeat_of)) {
2081 $c = self::memcache();
2083 $ck = self::multicacheKey('Notice',
2084 array('profile_id' => $this->profile_id,
2085 'repeat_of' => $this->repeat_of));
2095 * Get the source of the notice
2097 * @return Notice_source $ns A notice source object. 'code' is the only attribute
2098 * guaranteed to be populated.
2100 function getSource()
2102 $ns = new Notice_source();
2103 if (!empty($this->source)) {
2104 switch ($this->source) {
2111 $ns->code = $this->source;
2114 $ns = Notice_source::staticGet($this->source);
2116 $ns = new Notice_source();
2117 $ns->code = $this->source;
2118 $app = Oauth_application::staticGet('name', $this->source);
2120 $ns->name = $app->name;
2121 $ns->url = $app->source_url;
2131 * Determine whether the notice was locally created
2133 * @return boolean locality
2136 public function isLocal()
2138 return ($this->is_local == Notice::LOCAL_PUBLIC ||
2139 $this->is_local == Notice::LOCAL_NONPUBLIC);
2143 * Get the list of hash tags saved with this notice.
2145 * @return array of strings
2147 public function getTags()
2151 $keypart = sprintf('notice:tags:%d', $this->id);
2153 $tagstr = self::cacheGet($keypart);
2155 if ($tagstr !== false) {
2156 $tags = explode(',', $tagstr);
2158 $tag = new Notice_tag();
2159 $tag->notice_id = $this->id;
2161 while ($tag->fetch()) {
2162 $tags[] = $tag->tag;
2165 self::cacheSet($keypart, implode(',', $tags));
2171 static private function utcDate($dt)
2173 $dateStr = date('d F Y H:i:s', strtotime($dt));
2174 $d = new DateTime($dateStr, new DateTimeZone('UTC'));
2175 return $d->format(DATE_W3C);
2179 * Look up the creation timestamp for a given notice ID, even
2180 * if it's been deleted.
2183 * @return mixed string recorded creation timestamp, or false if can't be found
2185 public static function getAsTimestamp($id)
2191 $notice = Notice::staticGet('id', $id);
2193 return $notice->created;
2196 $deleted = Deleted_notice::staticGet('id', $id);
2198 return $deleted->created;
2205 * Build an SQL 'where' fragment for timestamp-based sorting from a since_id
2206 * parameter, matching notices posted after the given one (exclusive).
2208 * If the referenced notice can't be found, will return false.
2211 * @param string $idField
2212 * @param string $createdField
2213 * @return mixed string or false if no match
2215 public static function whereSinceId($id, $idField='id', $createdField='created')
2217 $since = Notice::getAsTimestamp($id);
2219 return sprintf("($createdField = '%s' and $idField > %d) or ($createdField > '%s')", $since, $id, $since);
2225 * Build an SQL 'where' fragment for timestamp-based sorting from a since_id
2226 * parameter, matching notices posted after the given one (exclusive), and
2227 * if necessary add it to the data object's query.
2229 * @param DB_DataObject $obj
2231 * @param string $idField
2232 * @param string $createdField
2233 * @return mixed string or false if no match
2235 public static function addWhereSinceId(DB_DataObject $obj, $id, $idField='id', $createdField='created')
2237 $since = self::whereSinceId($id, $idField, $createdField);
2239 $obj->whereAdd($since);
2244 * Build an SQL 'where' fragment for timestamp-based sorting from a max_id
2245 * parameter, matching notices posted before the given one (inclusive).
2247 * If the referenced notice can't be found, will return false.
2250 * @param string $idField
2251 * @param string $createdField
2252 * @return mixed string or false if no match
2254 public static function whereMaxId($id, $idField='id', $createdField='created')
2256 $max = Notice::getAsTimestamp($id);
2258 return sprintf("($createdField < '%s') or ($createdField = '%s' and $idField <= %d)", $max, $max, $id);
2264 * Build an SQL 'where' fragment for timestamp-based sorting from a max_id
2265 * parameter, matching notices posted before the given one (inclusive), and
2266 * if necessary add it to the data object's query.
2268 * @param DB_DataObject $obj
2270 * @param string $idField
2271 * @param string $createdField
2272 * @return mixed string or false if no match
2274 public static function addWhereMaxId(DB_DataObject $obj, $id, $idField='id', $createdField='created')
2276 $max = self::whereMaxId($id, $idField, $createdField);
2278 $obj->whereAdd($max);
2284 if (common_config('public', 'localonly')) {
2285 return ($this->is_local == Notice::LOCAL_PUBLIC);
2287 return (($this->is_local != Notice::LOCAL_NONPUBLIC) &&
2288 ($this->is_local != Notice::GATEWAY));
2293 * Check that the given profile is allowed to read, respond to, or otherwise
2294 * act on this notice.
2296 * The $scope member is a bitmask of scopes, representing a logical AND of the
2297 * scope requirement. So, 0x03 (Notice::ADDRESSEE_SCOPE | Notice::SITE_SCOPE) means
2298 * "only visible to people who are mentioned in the notice AND are users on this site."
2299 * Users on the site who are not mentioned in the notice will not be able to see the
2302 * @param Profile $profile The profile to check; pass null to check for public/unauthenticated users.
2304 * @return boolean whether the profile is in the notice's scope
2306 function inScope($profile)
2308 $keypart = sprintf('notice:in-scope-for:%d:%d', $this->id, $profile->id);
2310 $result = self::cacheGet($keypart);
2312 if ($result === false) {
2313 $bResult = $this->_inScope($profile);
2314 $result = ($bResult) ? 1 : 0;
2315 self::cacheSet($keypart, $result, 0, 300);
2318 return ($result == 1) ? true : false;
2321 protected function _inScope($profile)
2323 // If there's no scope, anyone (even anon) is in scope.
2325 if ($this->scope == 0) {
2329 // If there's scope, anon cannot be in scope
2331 if (empty($profile)) {
2335 // Author is always in scope
2337 if ($this->profile_id == $profile->id) {
2341 // Only for users on this site
2343 if ($this->scope & Notice::SITE_SCOPE) {
2344 $user = $profile->getUser();
2350 // Only for users mentioned in the notice
2352 if ($this->scope & Notice::ADDRESSEE_SCOPE) {
2354 // XXX: just query for the single reply
2356 $replies = $this->getReplies();
2358 if (!in_array($profile->id, $replies)) {
2363 // Only for members of the given group
2365 if ($this->scope & Notice::GROUP_SCOPE) {
2367 // XXX: just query for the single membership
2369 $groups = $this->getGroups();
2373 foreach ($groups as $group) {
2374 if ($profile->isMember($group)) {
2385 // Only for followers of the author
2387 if ($this->scope & Notice::FOLLOWER_SCOPE) {
2388 $author = $this->getProfile();
2389 if (!Subscription::exists($profile, $author)) {
2397 static function groupsFromText($text, $profile)
2401 /* extract all !group */
2402 $count = preg_match_all('/(?:^|\s)!(' . Nickname::DISPLAY_FMT . ')/',
2410 foreach (array_unique($match[1]) as $nickname) {
2411 $group = User_group::getForNickname($nickname, $profile);
2412 if (!empty($group) && $profile->isMember($group)) {
2413 $groups[] = $group->id;