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);
549 $notice->saveKnownUrls($urls);
555 // Prepare inbox delivery, may be queued to background.
556 $notice->distribute();
562 function blowOnInsert($conversation = false)
564 self::blow('profile:notice_ids:%d', $this->profile_id);
566 if ($this->isPublic()) {
567 self::blow('public');
570 // XXX: Before we were blowing the casche only if the notice id
571 // was not the root of the conversation. What to do now?
573 self::blow('notice:conversation_ids:%d', $this->conversation);
574 self::blow('conversation::notice_count:%d', $this->conversation);
576 if (!empty($this->repeat_of)) {
577 self::blow('notice:repeats:%d', $this->repeat_of);
580 $original = Notice::staticGet('id', $this->repeat_of);
582 if (!empty($original)) {
583 $originalUser = User::staticGet('id', $original->profile_id);
584 if (!empty($originalUser)) {
585 self::blow('user:repeats_of_me:%d', $originalUser->id);
589 $profile = Profile::staticGet($this->profile_id);
590 if (!empty($profile)) {
591 $profile->blowNoticeCount();
594 $ptags = $this->getProfileTags();
595 foreach ($ptags as $ptag) {
596 $ptag->blowNoticeStreamCache();
601 * Clear cache entries related to this notice at delete time.
602 * Necessary to avoid breaking paging on public, profile timelines.
604 function blowOnDelete()
606 $this->blowOnInsert();
608 self::blow('profile:notice_ids:%d;last', $this->profile_id);
610 if ($this->isPublic()) {
611 self::blow('public;last');
614 self::blow('fave:by_notice', $this->id);
616 if ($this->conversation) {
617 // In case we're the first, will need to calc a new root.
618 self::blow('notice:conversation_root:%d', $this->conversation);
621 $ptags = $this->getProfileTags();
622 foreach ($ptags as $ptag) {
623 $ptag->blowNoticeStreamCache(true);
627 /** save all urls in the notice to the db
629 * follow redirects and save all available file information
630 * (mimetype, date, size, oembed, etc.)
634 function saveUrls() {
635 if (common_config('attachments', 'process_links')) {
636 common_replace_urls_callback($this->content, array($this, 'saveUrl'), $this->id);
641 * Save the given URLs as related links/attachments to the db
643 * follow redirects and save all available file information
644 * (mimetype, date, size, oembed, etc.)
648 function saveKnownUrls($urls)
650 if (common_config('attachments', 'process_links')) {
651 // @fixme validation?
652 foreach (array_unique($urls) as $url) {
653 File::processNew($url, $this->id);
661 function saveUrl($url, $notice_id) {
662 File::processNew($url, $notice_id);
665 static function checkDupes($profile_id, $content) {
666 $profile = Profile::staticGet($profile_id);
667 if (empty($profile)) {
670 $notice = $profile->getNotices(0, CachingNoticeStream::CACHE_WINDOW);
671 if (!empty($notice)) {
673 while ($notice->fetch()) {
674 if (time() - strtotime($notice->created) >= common_config('site', 'dupelimit')) {
676 } else if ($notice->content == $content) {
681 // If we get here, oldest item in cache window is not
682 // old enough for dupe limit; do direct check against DB
683 $notice = new Notice();
684 $notice->profile_id = $profile_id;
685 $notice->content = $content;
686 $threshold = common_sql_date(time() - common_config('site', 'dupelimit'));
687 $notice->whereAdd(sprintf("created > '%s'", $notice->escape($threshold)));
689 $cnt = $notice->count();
693 static function checkEditThrottle($profile_id) {
694 $profile = Profile::staticGet($profile_id);
695 if (empty($profile)) {
698 // Get the Nth notice
699 $notice = $profile->getNotices(common_config('throttle', 'count') - 1, 1);
700 if ($notice && $notice->fetch()) {
701 // If the Nth notice was posted less than timespan seconds ago
702 if (time() - strtotime($notice->created) <= common_config('throttle', 'timespan')) {
707 // Either not N notices in the stream, OR the Nth was not posted within timespan seconds
711 function getUploadedAttachment() {
713 $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"';
714 $post->query($query);
716 if (empty($post->up) || empty($post->i)) {
719 $ret = array($post->up, $post->i);
725 function hasAttachments() {
727 $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);
728 $post->query($query);
730 $n_attachments = intval($post->n_attachments);
732 return $n_attachments;
735 function attachments() {
737 $keypart = sprintf('notice:file_ids:%d', $this->id);
739 $idstr = self::cacheGet($keypart);
741 if ($idstr !== false) {
742 $ids = explode(',', $idstr);
745 $f2p = new File_to_post;
746 $f2p->post_id = $this->id;
748 while ($f2p->fetch()) {
749 $ids[] = $f2p->file_id;
752 self::cacheSet($keypart, implode(',', $ids));
757 foreach ($ids as $id) {
758 $f = File::staticGet('id', $id);
768 function publicStream($offset=0, $limit=20, $since_id=0, $max_id=0)
770 $stream = new PublicNoticeStream();
771 return $stream->getNotices($offset, $limit, $since_id, $max_id);
775 function conversationStream($id, $offset=0, $limit=20, $since_id=0, $max_id=0)
777 $stream = new ConversationNoticeStream($id);
779 return $stream->getNotices($offset, $limit, $since_id, $max_id);
783 * Is this notice part of an active conversation?
785 * @return boolean true if other messages exist in the same
786 * conversation, false if this is the only one
788 function hasConversation()
790 if (!empty($this->conversation)) {
791 $conversation = Notice::conversationStream(
797 if ($conversation->N > 0) {
805 * Grab the earliest notice from this conversation.
807 * @return Notice or null
809 function conversationRoot($profile=-1)
811 // XXX: can this happen?
813 if (empty($this->conversation)) {
817 // Get the current profile if not specified
819 if (is_int($profile) && $profile == -1) {
820 $profile = Profile::current();
823 // If this notice is out of scope, no root for you!
825 if (!$this->inScope($profile)) {
829 // If this isn't a reply to anything, then it's its own
832 if (empty($this->reply_to)) {
836 if (is_null($profile)) {
837 $keypart = sprintf('notice:conversation_root:%d:null', $this->id);
839 $keypart = sprintf('notice:conversation_root:%d:%d',
844 $root = self::cacheGet($keypart);
846 if ($root !== false && $root->inScope($profile)) {
852 $parent = $last->getOriginal();
853 if (!empty($parent) && $parent->inScope($profile)) {
860 } while (!empty($parent));
862 self::cacheSet($keypart, $root);
869 * Pull up a full list of local recipients who will be getting
870 * this notice in their inbox. Results will be cached, so don't
871 * change the input data wily-nilly!
873 * @param array $groups optional list of Group objects;
874 * if left empty, will be loaded from group_inbox records
875 * @param array $recipient optional list of reply profile ids
876 * if left empty, will be loaded from reply records
877 * @return array associating recipient user IDs with an inbox source constant
879 function whoGets($groups=null, $recipients=null)
881 $c = self::memcache();
884 $ni = $c->get(Cache::key('notice:who_gets:'.$this->id));
890 if (is_null($groups)) {
891 $groups = $this->getGroups();
894 if (is_null($recipients)) {
895 $recipients = $this->getReplies();
898 $users = $this->getSubscribedUsers();
899 $ptags = $this->getProfileTags();
901 // FIXME: kind of ignoring 'transitional'...
902 // we'll probably stop supporting inboxless mode
907 // Give plugins a chance to add folks in at start...
908 if (Event::handle('StartNoticeWhoGets', array($this, &$ni))) {
910 foreach ($users as $id) {
911 $ni[$id] = NOTICE_INBOX_SOURCE_SUB;
914 foreach ($groups as $group) {
915 $users = $group->getUserMembers();
916 foreach ($users as $id) {
917 if (!array_key_exists($id, $ni)) {
918 $ni[$id] = NOTICE_INBOX_SOURCE_GROUP;
923 foreach ($ptags as $ptag) {
924 $users = $ptag->getUserSubscribers();
925 foreach ($users as $id) {
926 if (!array_key_exists($id, $ni)) {
927 $user = User::staticGet('id', $id);
928 if (!$user->hasBlocked($profile)) {
929 $ni[$id] = NOTICE_INBOX_SOURCE_PROFILE_TAG;
935 foreach ($recipients as $recipient) {
936 if (!array_key_exists($recipient, $ni)) {
937 $ni[$recipient] = NOTICE_INBOX_SOURCE_REPLY;
940 // Exclude any deleted, non-local, or blocking recipients.
941 $profile = $this->getProfile();
942 $originalProfile = null;
943 if ($this->repeat_of) {
944 // Check blocks against the original notice's poster as well.
945 $original = Notice::staticGet('id', $this->repeat_of);
947 $originalProfile = $original->getProfile();
950 foreach ($ni as $id => $source) {
951 $user = User::staticGet('id', $id);
952 if (empty($user) || $user->hasBlocked($profile) ||
953 ($originalProfile && $user->hasBlocked($originalProfile))) {
959 // Give plugins a chance to filter out...
960 Event::handle('EndNoticeWhoGets', array($this, &$ni));
964 // XXX: pack this data better
965 $c->set(Cache::key('notice:who_gets:'.$this->id), $ni);
972 * Adds this notice to the inboxes of each local user who should receive
973 * it, based on author subscriptions, group memberships, and @-replies.
975 * Warning: running a second time currently will make items appear
976 * multiple times in users' inboxes.
978 * @fixme make more robust against errors
979 * @fixme break up massive deliveries to smaller background tasks
981 * @param array $groups optional list of Group objects;
982 * if left empty, will be loaded from group_inbox records
983 * @param array $recipient optional list of reply profile ids
984 * if left empty, will be loaded from reply records
986 function addToInboxes($groups=null, $recipients=null)
988 $ni = $this->whoGets($groups, $recipients);
990 $ids = array_keys($ni);
992 // We remove the author (if they're a local user),
993 // since we'll have already done this in distribute()
995 $i = array_search($this->profile_id, $ids);
1003 Inbox::bulkInsert($this->id, $ids);
1008 function getSubscribedUsers()
1012 if(common_config('db','quote_identifiers'))
1013 $user_table = '"user"';
1014 else $user_table = 'user';
1018 'FROM '. $user_table .' JOIN subscription '.
1019 'ON '. $user_table .'.id = subscription.subscriber ' .
1020 'WHERE subscription.subscribed = %d ';
1022 $user->query(sprintf($qry, $this->profile_id));
1026 while ($user->fetch()) {
1035 function getProfileTags()
1037 $profile = $this->getProfile();
1038 $list = $profile->getOtherTags($profile);
1041 while($list->fetch()) {
1042 $ptags[] = clone($list);
1049 * Record this notice to the given group inboxes for delivery.
1050 * Overrides the regular parsing of !group markup.
1052 * @param string $group_ids
1053 * @fixme might prefer URIs as identifiers, as for replies?
1054 * best with generalizations on user_group to support
1055 * remote groups better.
1057 function saveKnownGroups($group_ids)
1059 if (!is_array($group_ids)) {
1060 // TRANS: Server exception thrown when no array is provided to the method saveKnownGroups().
1061 throw new ServerException(_('Bad type provided to saveKnownGroups.'));
1065 foreach (array_unique($group_ids) as $id) {
1066 $group = User_group::staticGet('id', $id);
1068 common_log(LOG_ERR, "Local delivery to group id $id, $group->nickname");
1069 $result = $this->addToGroupInbox($group);
1071 common_log_db_error($gi, 'INSERT', __FILE__);
1074 // we automatically add a tag for every group name, too
1076 $tag = Notice_tag::pkeyGet(array('tag' => common_canonical_tag($group->nickname),
1077 'notice_id' => $this->id));
1079 if (is_null($tag)) {
1080 $this->saveTag($group->nickname);
1083 $groups[] = clone($group);
1085 common_log(LOG_ERR, "Local delivery to group id $id skipped, doesn't exist");
1093 * Parse !group delivery and record targets into group_inbox.
1094 * @return array of Group objects
1096 function saveGroups()
1098 // Don't save groups for repeats
1100 if (!empty($this->repeat_of)) {
1104 $profile = $this->getProfile();
1106 $groups = self::groupsFromText($this->content, $profile);
1108 /* Add them to the database */
1110 foreach ($groups as $group) {
1111 /* XXX: remote groups. */
1113 if (empty($group)) {
1118 if ($profile->isMember($group)) {
1120 $result = $this->addToGroupInbox($group);
1123 common_log_db_error($gi, 'INSERT', __FILE__);
1126 $groups[] = clone($group);
1133 function addToGroupInbox($group)
1135 $gi = Group_inbox::pkeyGet(array('group_id' => $group->id,
1136 'notice_id' => $this->id));
1140 $gi = new Group_inbox();
1142 $gi->group_id = $group->id;
1143 $gi->notice_id = $this->id;
1144 $gi->created = $this->created;
1146 $result = $gi->insert();
1149 common_log_db_error($gi, 'INSERT', __FILE__);
1150 // TRANS: Server exception thrown when an update for a group inbox fails.
1151 throw new ServerException(_('Problem saving group inbox.'));
1154 self::blow('user_group:notice_ids:%d', $gi->group_id);
1161 * Save reply records indicating that this notice needs to be
1162 * delivered to the local users with the given URIs.
1164 * Since this is expected to be used when saving foreign-sourced
1165 * messages, we won't deliver to any remote targets as that's the
1166 * source service's responsibility.
1168 * Mail notifications etc will be handled later.
1170 * @param array of unique identifier URIs for recipients
1172 function saveKnownReplies($uris)
1178 $sender = Profile::staticGet($this->profile_id);
1180 foreach (array_unique($uris) as $uri) {
1182 $profile = Profile::fromURI($uri);
1184 if (empty($profile)) {
1185 common_log(LOG_WARNING, "Unable to determine profile for URI '$uri'");
1189 if ($profile->hasBlocked($sender)) {
1190 common_log(LOG_INFO, "Not saving reply to profile {$profile->id} ($uri) from sender {$sender->id} because of a block.");
1194 $reply = new Reply();
1196 $reply->notice_id = $this->id;
1197 $reply->profile_id = $profile->id;
1198 $reply->modified = $this->created;
1200 common_log(LOG_INFO, __METHOD__ . ": saving reply: notice $this->id to profile $profile->id");
1202 $id = $reply->insert();
1209 * Pull @-replies from this message's content in StatusNet markup format
1210 * and save reply records indicating that this message needs to be
1211 * delivered to those users.
1213 * Mail notifications to local profiles will be sent later.
1215 * @return array of integer profile IDs
1218 function saveReplies()
1220 // Don't save reply data for repeats
1222 if (!empty($this->repeat_of)) {
1226 $sender = Profile::staticGet($this->profile_id);
1228 // @todo ideally this parser information would only
1229 // be calculated once.
1231 $mentions = common_find_mentions($this->content, $this);
1235 // store replied only for first @ (what user/notice what the reply directed,
1236 // we assume first @ is it)
1238 foreach ($mentions as $mention) {
1240 foreach ($mention['mentioned'] as $mentioned) {
1242 // skip if they're already covered
1244 if (!empty($replied[$mentioned->id])) {
1248 // Don't save replies from blocked profile to local user
1250 $mentioned_user = User::staticGet('id', $mentioned->id);
1251 if (!empty($mentioned_user) && $mentioned_user->hasBlocked($sender)) {
1255 $reply = new Reply();
1257 $reply->notice_id = $this->id;
1258 $reply->profile_id = $mentioned->id;
1259 $reply->modified = $this->created;
1261 $id = $reply->insert();
1264 common_log_db_error($reply, 'INSERT', __FILE__);
1265 // TRANS: Server exception thrown when a reply cannot be saved.
1266 // TRANS: %1$d is a notice ID, %2$d is the ID of the mentioned user.
1267 throw new ServerException(sprintf(_('Could not save reply for %1$d, %2$d.'), $this->id, $mentioned->id));
1269 $replied[$mentioned->id] = 1;
1270 self::blow('reply:stream:%d', $mentioned->id);
1275 $recipientIds = array_keys($replied);
1277 return $recipientIds;
1281 * Pull the complete list of @-reply targets for this notice.
1283 * @return array of integer profile ids
1285 function getReplies()
1287 $keypart = sprintf('notice:reply_ids:%d', $this->id);
1289 $idstr = self::cacheGet($keypart);
1291 if ($idstr !== false) {
1292 $ids = explode(',', $idstr);
1296 $reply = new Reply();
1297 $reply->selectAdd();
1298 $reply->selectAdd('profile_id');
1299 $reply->notice_id = $this->id;
1301 if ($reply->find()) {
1302 while($reply->fetch()) {
1303 $ids[] = $reply->profile_id;
1306 self::cacheSet($keypart, implode(',', $ids));
1313 * Pull the complete list of @-reply targets for this notice.
1315 * @return array of Profiles
1317 function getReplyProfiles()
1319 $ids = $this->getReplies();
1320 $profiles = array();
1322 foreach ($ids as $id) {
1323 $profile = Profile::staticGet('id', $id);
1324 if (!empty($profile)) {
1325 $profiles[] = $profile;
1333 * Send e-mail notifications to local @-reply targets.
1335 * Replies must already have been saved; this is expected to be run
1336 * from the distrib queue handler.
1338 function sendReplyNotifications()
1340 // Don't send reply notifications for repeats
1342 if (!empty($this->repeat_of)) {
1346 $recipientIds = $this->getReplies();
1348 foreach ($recipientIds as $recipientId) {
1349 $user = User::staticGet('id', $recipientId);
1350 if (!empty($user)) {
1351 mail_notify_attn($user, $this);
1357 * Pull list of groups this notice needs to be delivered to,
1358 * as previously recorded by saveGroups() or saveKnownGroups().
1360 * @return array of Group objects
1362 function getGroups()
1364 // Don't save groups for repeats
1366 if (!empty($this->repeat_of)) {
1372 $keypart = sprintf('notice:groups:%d', $this->id);
1374 $idstr = self::cacheGet($keypart);
1376 if ($idstr !== false) {
1377 $ids = explode(',', $idstr);
1379 $gi = new Group_inbox();
1382 $gi->selectAdd('group_id');
1384 $gi->notice_id = $this->id;
1387 while ($gi->fetch()) {
1388 $ids[] = $gi->group_id;
1392 self::cacheSet($keypart, implode(',', $ids));
1397 foreach ($ids as $id) {
1398 $group = User_group::staticGet('id', $id);
1408 * Convert a notice into an activity for export.
1410 * @param User $cur Current user
1412 * @return Activity activity object representing this Notice.
1415 function asActivity($cur)
1417 $act = self::cacheGet(Cache::codeKey('notice:as-activity:'.$this->id));
1422 $act = new Activity();
1424 if (Event::handle('StartNoticeAsActivity', array($this, &$act))) {
1426 $profile = $this->getProfile();
1428 $act->actor = ActivityObject::fromProfile($profile);
1429 $act->actor->extra[] = $profile->profileInfo($cur);
1430 $act->verb = ActivityVerb::POST;
1431 $act->objects[] = ActivityObject::fromNotice($this);
1433 // XXX: should this be handled by default processing for object entry?
1435 $act->time = strtotime($this->created);
1436 $act->link = $this->bestUrl();
1438 $act->content = common_xml_safe_str($this->rendered);
1439 $act->id = $this->uri;
1440 $act->title = common_xml_safe_str($this->content);
1444 $tags = $this->getTags();
1446 foreach ($tags as $tag) {
1447 $cat = new AtomCategory();
1450 $act->categories[] = $cat;
1454 // XXX: use Atom Media and/or File activity objects instead
1456 $attachments = $this->attachments();
1458 foreach ($attachments as $attachment) {
1459 $enclosure = $attachment->getEnclosure();
1461 $act->enclosures[] = $enclosure;
1465 $ctx = new ActivityContext();
1467 if (!empty($this->reply_to)) {
1468 $reply = Notice::staticGet('id', $this->reply_to);
1469 if (!empty($reply)) {
1470 $ctx->replyToID = $reply->uri;
1471 $ctx->replyToUrl = $reply->bestUrl();
1475 $ctx->location = $this->getLocation();
1479 if (!empty($this->conversation)) {
1480 $conv = Conversation::staticGet('id', $this->conversation);
1481 if (!empty($conv)) {
1482 $ctx->conversation = $conv->uri;
1486 $reply_ids = $this->getReplies();
1488 foreach ($reply_ids as $id) {
1489 $rprofile = Profile::staticGet('id', $id);
1490 if (!empty($rprofile)) {
1491 $ctx->attention[] = $rprofile->getUri();
1495 $groups = $this->getGroups();
1497 foreach ($groups as $group) {
1498 $ctx->attention[] = $group->getUri();
1501 // XXX: deprecated; use ActivityVerb::SHARE instead
1505 if (!empty($this->repeat_of)) {
1506 $repeat = Notice::staticGet('id', $this->repeat_of);
1507 $ctx->forwardID = $repeat->uri;
1508 $ctx->forwardUrl = $repeat->bestUrl();
1511 $act->context = $ctx;
1515 $atom_feed = $profile->getAtomFeed();
1517 if (!empty($atom_feed)) {
1519 $act->source = new ActivitySource();
1521 // XXX: we should store the actual feed ID
1523 $act->source->id = $atom_feed;
1525 // XXX: we should store the actual feed title
1527 $act->source->title = $profile->getBestName();
1529 $act->source->links['alternate'] = $profile->profileurl;
1530 $act->source->links['self'] = $atom_feed;
1532 $act->source->icon = $profile->avatarUrl(AVATAR_PROFILE_SIZE);
1534 $notice = $profile->getCurrentNotice();
1536 if (!empty($notice)) {
1537 $act->source->updated = self::utcDate($notice->created);
1540 $user = User::staticGet('id', $profile->id);
1542 if (!empty($user)) {
1543 $act->source->links['license'] = common_config('license', 'url');
1547 if ($this->isLocal()) {
1548 $act->selfLink = common_local_url('ApiStatusesShow', array('id' => $this->id,
1549 'format' => 'atom'));
1550 $act->editLink = $act->selfLink;
1553 Event::handle('EndNoticeAsActivity', array($this, &$act));
1556 self::cacheSet(Cache::codeKey('notice:as-activity:'.$this->id), $act);
1561 // This has gotten way too long. Needs to be sliced up into functional bits
1562 // or ideally exported to a utility class.
1564 function asAtomEntry($namespace=false,
1569 $act = $this->asActivity($cur);
1570 $act->extra[] = $this->noticeInfo($cur);
1571 return $act->asString($namespace, $author, $source);
1575 * Extra notice info for atom entries
1577 * Clients use some extra notice info in the atom stream.
1578 * This gives it to them.
1580 * @param User $cur Current user
1582 * @return array representation of <statusnet:notice_info> element
1585 function noticeInfo($cur)
1587 // local notice ID (useful to clients for ordering)
1589 $noticeInfoAttr = array('local_id' => $this->id);
1593 $ns = $this->getSource();
1596 $noticeInfoAttr['source'] = $ns->code;
1597 if (!empty($ns->url)) {
1598 $noticeInfoAttr['source_link'] = $ns->url;
1599 if (!empty($ns->name)) {
1600 $noticeInfoAttr['source'] = '<a href="'
1601 . htmlspecialchars($ns->url)
1602 . '" rel="nofollow">'
1603 . htmlspecialchars($ns->name)
1609 // favorite and repeated
1612 $noticeInfoAttr['favorite'] = ($cur->hasFave($this)) ? "true" : "false";
1613 $cp = $cur->getProfile();
1614 $noticeInfoAttr['repeated'] = ($cp->hasRepeated($this->id)) ? "true" : "false";
1617 if (!empty($this->repeat_of)) {
1618 $noticeInfoAttr['repeat_of'] = $this->repeat_of;
1621 return array('statusnet:notice_info', $noticeInfoAttr, null);
1625 * Returns an XML string fragment with a reference to a notice as an
1626 * Activity Streams noun object with the given element type.
1628 * Assumes that 'activity' namespace has been previously defined.
1630 * @param string $element one of 'subject', 'object', 'target'
1634 function asActivityNoun($element)
1636 $noun = ActivityObject::fromNotice($this);
1637 return $noun->asString('activity:' . $element);
1642 if (!empty($this->url)) {
1644 } else if (!empty($this->uri) && preg_match('/^https?:/', $this->uri)) {
1647 return common_local_url('shownotice',
1648 array('notice' => $this->id));
1654 * Determine which notice, if any, a new notice is in reply to.
1656 * For conversation tracking, we try to see where this notice fits
1657 * in the tree. Rough algorithm is:
1659 * if (reply_to is set and valid) {
1661 * } else if ((source not API or Web) and (content starts with "T NAME" or "@name ")) {
1662 * return ID of last notice by initial @name in content;
1665 * Note that all @nickname instances will still be used to save "reply" records,
1666 * so the notice shows up in the mentioned users' "replies" tab.
1668 * @param integer $reply_to ID passed in by Web or API
1669 * @param integer $profile_id ID of author
1670 * @param string $source Source tag, like 'web' or 'gwibber'
1671 * @param string $content Final notice content
1673 * @return integer ID of replied-to notice, or null for not a reply.
1676 static function getReplyTo($reply_to, $profile_id, $source, $content)
1678 static $lb = array('xmpp', 'mail', 'sms', 'omb');
1680 // If $reply_to is specified, we check that it exists, and then
1681 // return it if it does
1683 if (!empty($reply_to)) {
1684 $reply_notice = Notice::staticGet('id', $reply_to);
1685 if (!empty($reply_notice)) {
1686 return $reply_notice;
1690 // If it's not a "low bandwidth" source (one where you can't set
1691 // a reply_to argument), we return. This is mostly web and API
1694 if (!in_array($source, $lb)) {
1698 // Is there an initial @ or T?
1700 if (preg_match('/^T ([A-Z0-9]{1,64}) /', $content, $match) ||
1701 preg_match('/^@([a-z0-9]{1,64})\s+/', $content, $match)) {
1702 $nickname = common_canonical_nickname($match[1]);
1707 // Figure out who that is.
1709 $sender = Profile::staticGet('id', $profile_id);
1710 if (empty($sender)) {
1714 $recipient = common_relative_profile($sender, $nickname, common_sql_now());
1716 if (empty($recipient)) {
1720 // Get their last notice
1722 $last = $recipient->getCurrentNotice();
1724 if (!empty($last)) {
1731 static function maxContent()
1733 $contentlimit = common_config('notice', 'contentlimit');
1734 // null => use global limit (distinct from 0!)
1735 if (is_null($contentlimit)) {
1736 $contentlimit = common_config('site', 'textlimit');
1738 return $contentlimit;
1741 static function contentTooLong($content)
1743 $contentlimit = self::maxContent();
1744 return ($contentlimit > 0 && !empty($content) && (mb_strlen($content) > $contentlimit));
1747 function getLocation()
1751 if (!empty($this->location_id) && !empty($this->location_ns)) {
1752 $location = Location::fromId($this->location_id, $this->location_ns);
1755 if (is_null($location)) { // no ID, or Location::fromId() failed
1756 if (!empty($this->lat) && !empty($this->lon)) {
1757 $location = Location::fromLatLon($this->lat, $this->lon);
1765 * Convenience function for posting a repeat of an existing message.
1767 * @param int $repeater_id: profile ID of user doing the repeat
1768 * @param string $source: posting source key, eg 'web', 'api', etc
1771 * @throws Exception on failure or permission problems
1773 function repeat($repeater_id, $source)
1775 $author = Profile::staticGet('id', $this->profile_id);
1777 // TRANS: Message used to repeat a notice. RT is the abbreviation of 'retweet'.
1778 // TRANS: %1$s is the repeated user's name, %2$s is the repeated notice.
1779 $content = sprintf(_('RT @%1$s %2$s'),
1783 $maxlen = common_config('site', 'textlimit');
1784 if ($maxlen > 0 && mb_strlen($content) > $maxlen) {
1785 // Web interface and current Twitter API clients will
1786 // pull the original notice's text, but some older
1787 // clients and RSS/Atom feeds will see this trimmed text.
1789 // Unfortunately this is likely to lose tags or URLs
1790 // at the end of long notices.
1791 $content = mb_substr($content, 0, $maxlen - 4) . ' ...';
1794 // Scope is same as this one's
1796 return self::saveNew($repeater_id,
1799 array('repeat_of' => $this->id,
1800 'scope' => $this->scope));
1803 // These are supposed to be in chron order!
1805 function repeatStream($limit=100)
1807 $cache = Cache::instance();
1809 if (empty($cache)) {
1810 $ids = $this->_repeatStreamDirect($limit);
1812 $idstr = $cache->get(Cache::key('notice:repeats:'.$this->id));
1813 if ($idstr !== false) {
1814 $ids = explode(',', $idstr);
1816 $ids = $this->_repeatStreamDirect(100);
1817 $cache->set(Cache::key('notice:repeats:'.$this->id), implode(',', $ids));
1820 // We do a max of 100, so slice down to limit
1821 $ids = array_slice($ids, 0, $limit);
1825 return NoticeStream::getStreamByIds($ids);
1828 function _repeatStreamDirect($limit)
1830 $notice = new Notice();
1832 $notice->selectAdd(); // clears it
1833 $notice->selectAdd('id');
1835 $notice->repeat_of = $this->id;
1837 $notice->orderBy('created, id'); // NB: asc!
1839 if (!is_null($limit)) {
1840 $notice->limit(0, $limit);
1845 if ($notice->find()) {
1846 while ($notice->fetch()) {
1847 $ids[] = $notice->id;
1857 function locationOptions($lat, $lon, $location_id, $location_ns, $profile = null)
1861 if (!empty($location_id) && !empty($location_ns)) {
1862 $options['location_id'] = $location_id;
1863 $options['location_ns'] = $location_ns;
1865 $location = Location::fromId($location_id, $location_ns);
1867 if (!empty($location)) {
1868 $options['lat'] = $location->lat;
1869 $options['lon'] = $location->lon;
1872 } else if (!empty($lat) && !empty($lon)) {
1873 $options['lat'] = $lat;
1874 $options['lon'] = $lon;
1876 $location = Location::fromLatLon($lat, $lon);
1878 if (!empty($location)) {
1879 $options['location_id'] = $location->location_id;
1880 $options['location_ns'] = $location->location_ns;
1882 } else if (!empty($profile)) {
1883 if (isset($profile->lat) && isset($profile->lon)) {
1884 $options['lat'] = $profile->lat;
1885 $options['lon'] = $profile->lon;
1888 if (isset($profile->location_id) && isset($profile->location_ns)) {
1889 $options['location_id'] = $profile->location_id;
1890 $options['location_ns'] = $profile->location_ns;
1897 function clearReplies()
1899 $replyNotice = new Notice();
1900 $replyNotice->reply_to = $this->id;
1902 //Null any notices that are replies to this notice
1904 if ($replyNotice->find()) {
1905 while ($replyNotice->fetch()) {
1906 $orig = clone($replyNotice);
1907 $replyNotice->reply_to = null;
1908 $replyNotice->update($orig);
1914 $reply = new Reply();
1915 $reply->notice_id = $this->id;
1917 if ($reply->find()) {
1918 while($reply->fetch()) {
1919 self::blow('reply:stream:%d', $reply->profile_id);
1927 function clearFiles()
1929 $f2p = new File_to_post();
1931 $f2p->post_id = $this->id;
1934 while ($f2p->fetch()) {
1938 // FIXME: decide whether to delete File objects
1939 // ...and related (actual) files
1942 function clearRepeats()
1944 $repeatNotice = new Notice();
1945 $repeatNotice->repeat_of = $this->id;
1947 //Null any notices that are repeats of this notice
1949 if ($repeatNotice->find()) {
1950 while ($repeatNotice->fetch()) {
1951 $orig = clone($repeatNotice);
1952 $repeatNotice->repeat_of = null;
1953 $repeatNotice->update($orig);
1958 function clearFaves()
1961 $fave->notice_id = $this->id;
1963 if ($fave->find()) {
1964 while ($fave->fetch()) {
1965 self::blow('fave:ids_by_user_own:%d', $fave->user_id);
1966 self::blow('fave:ids_by_user_own:%d;last', $fave->user_id);
1967 self::blow('fave:ids_by_user:%d', $fave->user_id);
1968 self::blow('fave:ids_by_user:%d;last', $fave->user_id);
1976 function clearTags()
1978 $tag = new Notice_tag();
1979 $tag->notice_id = $this->id;
1982 while ($tag->fetch()) {
1983 self::blow('profile:notice_ids_tagged:%d:%s', $this->profile_id, Cache::keyize($tag->tag));
1984 self::blow('profile:notice_ids_tagged:%d:%s;last', $this->profile_id, Cache::keyize($tag->tag));
1985 self::blow('notice_tag:notice_ids:%s', Cache::keyize($tag->tag));
1986 self::blow('notice_tag:notice_ids:%s;last', Cache::keyize($tag->tag));
1994 function clearGroupInboxes()
1996 $gi = new Group_inbox();
1998 $gi->notice_id = $this->id;
2001 while ($gi->fetch()) {
2002 self::blow('user_group:notice_ids:%d', $gi->group_id);
2010 function distribute()
2012 // We always insert for the author so they don't
2014 Event::handle('StartNoticeDistribute', array($this));
2016 $user = User::staticGet('id', $this->profile_id);
2017 if (!empty($user)) {
2018 Inbox::insertNotice($user->id, $this->id);
2021 if (common_config('queue', 'inboxes')) {
2022 // If there's a failure, we want to _force_
2023 // distribution at this point.
2025 $qm = QueueManager::get();
2026 $qm->enqueue($this, 'distrib');
2027 } catch (Exception $e) {
2028 // If the exception isn't transient, this
2029 // may throw more exceptions as DQH does
2030 // its own enqueueing. So, we ignore them!
2032 $handler = new DistribQueueHandler();
2033 $handler->handle($this);
2034 } catch (Exception $e) {
2035 common_log(LOG_ERR, "emergency redistribution resulted in " . $e->getMessage());
2037 // Re-throw so somebody smarter can handle it.
2041 $handler = new DistribQueueHandler();
2042 $handler->handle($this);
2048 $result = parent::insert();
2051 // Profile::hasRepeated() abuses pkeyGet(), so we
2052 // have to clear manually
2053 if (!empty($this->repeat_of)) {
2054 $c = self::memcache();
2056 $ck = self::multicacheKey('Notice',
2057 array('profile_id' => $this->profile_id,
2058 'repeat_of' => $this->repeat_of));
2068 * Get the source of the notice
2070 * @return Notice_source $ns A notice source object. 'code' is the only attribute
2071 * guaranteed to be populated.
2073 function getSource()
2075 $ns = new Notice_source();
2076 if (!empty($this->source)) {
2077 switch ($this->source) {
2084 $ns->code = $this->source;
2087 $ns = Notice_source::staticGet($this->source);
2089 $ns = new Notice_source();
2090 $ns->code = $this->source;
2091 $app = Oauth_application::staticGet('name', $this->source);
2093 $ns->name = $app->name;
2094 $ns->url = $app->source_url;
2104 * Determine whether the notice was locally created
2106 * @return boolean locality
2109 public function isLocal()
2111 return ($this->is_local == Notice::LOCAL_PUBLIC ||
2112 $this->is_local == Notice::LOCAL_NONPUBLIC);
2116 * Get the list of hash tags saved with this notice.
2118 * @return array of strings
2120 public function getTags()
2124 $keypart = sprintf('notice:tags:%d', $this->id);
2126 $tagstr = self::cacheGet($keypart);
2128 if ($tagstr !== false) {
2129 $tags = explode(',', $tagstr);
2131 $tag = new Notice_tag();
2132 $tag->notice_id = $this->id;
2134 while ($tag->fetch()) {
2135 $tags[] = $tag->tag;
2138 self::cacheSet($keypart, implode(',', $tags));
2144 static private function utcDate($dt)
2146 $dateStr = date('d F Y H:i:s', strtotime($dt));
2147 $d = new DateTime($dateStr, new DateTimeZone('UTC'));
2148 return $d->format(DATE_W3C);
2152 * Look up the creation timestamp for a given notice ID, even
2153 * if it's been deleted.
2156 * @return mixed string recorded creation timestamp, or false if can't be found
2158 public static function getAsTimestamp($id)
2164 $notice = Notice::staticGet('id', $id);
2166 return $notice->created;
2169 $deleted = Deleted_notice::staticGet('id', $id);
2171 return $deleted->created;
2178 * Build an SQL 'where' fragment for timestamp-based sorting from a since_id
2179 * parameter, matching notices posted after the given one (exclusive).
2181 * If the referenced notice can't be found, will return false.
2184 * @param string $idField
2185 * @param string $createdField
2186 * @return mixed string or false if no match
2188 public static function whereSinceId($id, $idField='id', $createdField='created')
2190 $since = Notice::getAsTimestamp($id);
2192 return sprintf("($createdField = '%s' and $idField > %d) or ($createdField > '%s')", $since, $id, $since);
2198 * Build an SQL 'where' fragment for timestamp-based sorting from a since_id
2199 * parameter, matching notices posted after the given one (exclusive), and
2200 * if necessary add it to the data object's query.
2202 * @param DB_DataObject $obj
2204 * @param string $idField
2205 * @param string $createdField
2206 * @return mixed string or false if no match
2208 public static function addWhereSinceId(DB_DataObject $obj, $id, $idField='id', $createdField='created')
2210 $since = self::whereSinceId($id, $idField, $createdField);
2212 $obj->whereAdd($since);
2217 * Build an SQL 'where' fragment for timestamp-based sorting from a max_id
2218 * parameter, matching notices posted before the given one (inclusive).
2220 * If the referenced notice can't be found, will return false.
2223 * @param string $idField
2224 * @param string $createdField
2225 * @return mixed string or false if no match
2227 public static function whereMaxId($id, $idField='id', $createdField='created')
2229 $max = Notice::getAsTimestamp($id);
2231 return sprintf("($createdField < '%s') or ($createdField = '%s' and $idField <= %d)", $max, $max, $id);
2237 * Build an SQL 'where' fragment for timestamp-based sorting from a max_id
2238 * parameter, matching notices posted before the given one (inclusive), and
2239 * if necessary add it to the data object's query.
2241 * @param DB_DataObject $obj
2243 * @param string $idField
2244 * @param string $createdField
2245 * @return mixed string or false if no match
2247 public static function addWhereMaxId(DB_DataObject $obj, $id, $idField='id', $createdField='created')
2249 $max = self::whereMaxId($id, $idField, $createdField);
2251 $obj->whereAdd($max);
2257 if (common_config('public', 'localonly')) {
2258 return ($this->is_local == Notice::LOCAL_PUBLIC);
2260 return (($this->is_local != Notice::LOCAL_NONPUBLIC) &&
2261 ($this->is_local != Notice::GATEWAY));
2266 * Check that the given profile is allowed to read, respond to, or otherwise
2267 * act on this notice.
2269 * The $scope member is a bitmask of scopes, representing a logical AND of the
2270 * scope requirement. So, 0x03 (Notice::ADDRESSEE_SCOPE | Notice::SITE_SCOPE) means
2271 * "only visible to people who are mentioned in the notice AND are users on this site."
2272 * Users on the site who are not mentioned in the notice will not be able to see the
2275 * @param Profile $profile The profile to check; pass null to check for public/unauthenticated users.
2277 * @return boolean whether the profile is in the notice's scope
2279 function inScope($profile)
2281 if (is_null($profile)) {
2282 $keypart = sprintf('notice:in-scope-for:%d:null', $this->id);
2284 $keypart = sprintf('notice:in-scope-for:%d:%d', $this->id, $profile->id);
2287 $result = self::cacheGet($keypart);
2289 if ($result === false) {
2290 $bResult = $this->_inScope($profile);
2291 $result = ($bResult) ? 1 : 0;
2292 self::cacheSet($keypart, $result, 0, 300);
2295 return ($result == 1) ? true : false;
2298 protected function _inScope($profile)
2300 // If there's no scope, anyone (even anon) is in scope.
2302 if ($this->scope == 0) {
2306 // If there's scope, anon cannot be in scope
2308 if (empty($profile)) {
2312 // Author is always in scope
2314 if ($this->profile_id == $profile->id) {
2318 // Only for users on this site
2320 if ($this->scope & Notice::SITE_SCOPE) {
2321 $user = $profile->getUser();
2327 // Only for users mentioned in the notice
2329 if ($this->scope & Notice::ADDRESSEE_SCOPE) {
2331 // XXX: just query for the single reply
2333 $replies = $this->getReplies();
2335 if (!in_array($profile->id, $replies)) {
2340 // Only for members of the given group
2342 if ($this->scope & Notice::GROUP_SCOPE) {
2344 // XXX: just query for the single membership
2346 $groups = $this->getGroups();
2350 foreach ($groups as $group) {
2351 if ($profile->isMember($group)) {
2362 // Only for followers of the author
2364 if ($this->scope & Notice::FOLLOWER_SCOPE) {
2365 $author = $this->getProfile();
2366 if (!Subscription::exists($profile, $author)) {
2374 static function groupsFromText($text, $profile)
2378 /* extract all !group */
2379 $count = preg_match_all('/(?:^|\s)!(' . Nickname::DISPLAY_FMT . ')/',
2387 foreach (array_unique($match[1]) as $nickname) {
2388 $group = User_group::getForNickname($nickname, $profile);
2389 if (!empty($group) && $profile->isMember($group)) {
2390 $groups[] = $group->id;
2397 protected $_original = -1;
2399 function getOriginal()
2401 if (is_int($this->_original) && $this->_original == -1) {
2402 if (empty($this->reply_to)) {
2403 $this->_original = null;
2405 $this->_original = Notice::staticGet('id', $this->reply_to);
2408 return $this->_original;