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 */
87 function multiGet($kc, $kvs)
89 return Memcached_DataObject::multiGet('Notice', $kc, $kvs);
93 const LOCAL_PUBLIC = 1;
95 const LOCAL_NONPUBLIC = -1;
98 const PUBLIC_SCOPE = 0; // Useful fake constant
100 const ADDRESSEE_SCOPE = 2;
101 const GROUP_SCOPE = 4;
102 const FOLLOWER_SCOPE = 8;
104 protected $_profile = -1;
106 function getProfile()
108 if (is_int($this->_profile) && $this->_profile == -1) {
109 $this->_profile = Profile::staticGet('id', $this->profile_id);
111 if (empty($this->_profile)) {
112 // TRANS: Server exception thrown when a user profile for a notice cannot be found.
113 // TRANS: %1$d is a profile ID (number), %2$d is a notice ID (number).
114 throw new ServerException(sprintf(_('No such profile (%1$d) for notice (%2$d).'), $this->profile_id, $this->id));
118 return $this->_profile;
123 // For auditing purposes, save a record that the notice
126 // @fixme we have some cases where things get re-run and so the
128 $deleted = Deleted_notice::staticGet('id', $this->id);
131 $deleted = Deleted_notice::staticGet('uri', $this->uri);
135 $deleted = new Deleted_notice();
137 $deleted->id = $this->id;
138 $deleted->profile_id = $this->profile_id;
139 $deleted->uri = $this->uri;
140 $deleted->created = $this->created;
141 $deleted->deleted = common_sql_now();
146 if (Event::handle('NoticeDeleteRelated', array($this))) {
148 // Clear related records
150 $this->clearReplies();
151 $this->clearRepeats();
154 $this->clearGroupInboxes();
157 // NOTE: we don't clear inboxes
158 // NOTE: we don't clear queue items
161 $result = parent::delete();
163 $this->blowOnDelete();
168 * Extract #hashtags from this notice's content and save them to the database.
172 /* extract all #hastags */
173 $count = preg_match_all('/(?:^|\s)#([\pL\pN_\-\.]{1,64})/u', strtolower($this->content), $match);
178 /* Add them to the database */
179 return $this->saveKnownTags($match[1]);
183 * Record the given set of hash tags in the db for this notice.
184 * Given tag strings will be normalized and checked for dupes.
186 function saveKnownTags($hashtags)
188 //turn each into their canonical tag
189 //this is needed to remove dupes before saving e.g. #hash.tag = #hashtag
190 for($i=0; $i<count($hashtags); $i++) {
191 /* elide characters we don't want in the tag */
192 $hashtags[$i] = common_canonical_tag($hashtags[$i]);
195 foreach(array_unique($hashtags) as $hashtag) {
196 $this->saveTag($hashtag);
197 self::blow('profile:notice_ids_tagged:%d:%s', $this->profile_id, $hashtag);
203 * Record a single hash tag as associated with this notice.
204 * Tag format and uniqueness must be validated by caller.
206 function saveTag($hashtag)
208 $tag = new Notice_tag();
209 $tag->notice_id = $this->id;
210 $tag->tag = $hashtag;
211 $tag->created = $this->created;
212 $id = $tag->insert();
215 // TRANS: Server exception. %s are the error details.
216 throw new ServerException(sprintf(_('Database error inserting hashtag: %s.'),
217 $last_error->message));
221 // if it's saved, blow its cache
222 $tag->blowCache(false);
226 * Save a new notice and push it out to subscribers' inboxes.
227 * Poster's permissions are checked before sending.
229 * @param int $profile_id Profile ID of the poster
230 * @param string $content source message text; links may be shortened
231 * per current user's preference
232 * @param string $source source key ('web', 'api', etc)
233 * @param array $options Associative array of optional properties:
234 * string 'created' timestamp of notice; defaults to now
235 * int 'is_local' source/gateway ID, one of:
236 * Notice::LOCAL_PUBLIC - Local, ok to appear in public timeline
237 * Notice::REMOTE_OMB - Sent from a remote OMB service;
238 * hide from public timeline but show in
239 * local "and friends" timelines
240 * Notice::LOCAL_NONPUBLIC - Local, but hide from public timeline
241 * Notice::GATEWAY - From another non-OMB service;
242 * will not appear in public views
243 * float 'lat' decimal latitude for geolocation
244 * float 'lon' decimal longitude for geolocation
245 * int 'location_id' geoname identifier
246 * int 'location_ns' geoname namespace to interpret location_id
247 * int 'reply_to'; notice ID this is a reply to
248 * int 'repeat_of'; notice ID this is a repeat of
249 * string 'uri' unique ID for notice; defaults to local notice URL
250 * string 'url' permalink to notice; defaults to local notice URL
251 * string 'rendered' rendered HTML version of content
252 * array 'replies' list of profile URIs for reply delivery in
253 * place of extracting @-replies from content.
254 * array 'groups' list of group IDs to deliver to, in place of
255 * extracting ! tags from content
256 * array 'tags' list of hashtag strings to save with the notice
257 * in place of extracting # tags from content
258 * array 'urls' list of attached/referred URLs to save with the
259 * notice in place of extracting links from content
260 * boolean 'distribute' whether to distribute the notice, default true
261 * string 'object_type' URL of the associated object type (default ActivityObject::NOTE)
262 * int 'scope' Scope bitmask; default to SITE_SCOPE on private sites, 0 otherwise
264 * @fixme tag override
267 * @throws ClientException
269 static function saveNew($profile_id, $content, $source, $options=null) {
270 $defaults = array('uri' => null,
275 'distribute' => true);
277 if (!empty($options)) {
278 $options = $options + $defaults;
284 if (!isset($is_local)) {
285 $is_local = Notice::LOCAL_PUBLIC;
288 $profile = Profile::staticGet('id', $profile_id);
289 $user = User::staticGet('id', $profile_id);
291 // Use the local user's shortening preferences, if applicable.
292 $final = $user->shortenLinks($content);
294 $final = common_shorten_links($content);
297 if (Notice::contentTooLong($final)) {
298 // TRANS: Client exception thrown if a notice contains too many characters.
299 throw new ClientException(_('Problem saving notice. Too long.'));
302 if (empty($profile)) {
303 // TRANS: Client exception thrown when trying to save a notice for an unknown user.
304 throw new ClientException(_('Problem saving notice. Unknown user.'));
307 if (common_config('throttle', 'enabled') && !Notice::checkEditThrottle($profile_id)) {
308 common_log(LOG_WARNING, 'Excessive posting by profile #' . $profile_id . '; throttled.');
309 // TRANS: Client exception thrown when a user tries to post too many notices in a given time frame.
310 throw new ClientException(_('Too many notices too fast; take a breather '.
311 'and post again in a few minutes.'));
314 if (common_config('site', 'dupelimit') > 0 && !Notice::checkDupes($profile_id, $final)) {
315 common_log(LOG_WARNING, 'Dupe posting by profile #' . $profile_id . '; throttled.');
316 // TRANS: Client exception thrown when a user tries to post too many duplicate notices in a given time frame.
317 throw new ClientException(_('Too many duplicate messages too quickly;'.
318 ' take a breather and post again in a few minutes.'));
321 if (!$profile->hasRight(Right::NEWNOTICE)) {
322 common_log(LOG_WARNING, "Attempted post from user disallowed to post: " . $profile->nickname);
324 // TRANS: Client exception thrown when a user tries to post while being banned.
325 throw new ClientException(_('You are banned from posting notices on this site.'), 403);
328 $notice = new Notice();
329 $notice->profile_id = $profile_id;
331 $autosource = common_config('public', 'autosource');
333 // Sandboxed are non-false, but not 1, either
335 if (!$profile->hasRight(Right::PUBLICNOTICE) ||
336 ($source && $autosource && in_array($source, $autosource))) {
337 $notice->is_local = Notice::LOCAL_NONPUBLIC;
339 $notice->is_local = $is_local;
342 if (!empty($created)) {
343 $notice->created = $created;
345 $notice->created = common_sql_now();
348 $notice->content = $final;
350 $notice->source = $source;
354 // Get the groups here so we can figure out replies and such
356 if (!isset($groups)) {
357 $groups = self::groupsFromText($notice->content, $profile);
362 // Handle repeat case
364 if (isset($repeat_of)) {
366 // Check for a private one
368 $repeat = Notice::staticGet('id', $repeat_of);
370 if (empty($repeat)) {
371 // TRANS: Client exception thrown in notice when trying to repeat a missing or deleted notice.
372 throw new ClientException(_('Cannot repeat; original notice is missing or deleted.'));
375 if ($profile->id == $repeat->profile_id) {
376 // TRANS: Client error displayed when trying to repeat an own notice.
377 throw new ClientException(_('You cannot repeat your own notice.'));
380 if ($repeat->scope != Notice::SITE_SCOPE &&
381 $repeat->scope != Notice::PUBLIC_SCOPE) {
382 // TRANS: Client error displayed when trying to repeat a non-public notice.
383 throw new ClientException(_('Cannot repeat a private notice.'), 403);
386 if (!$repeat->inScope($profile)) {
387 // The generic checks above should cover this, but let's be sure!
388 // TRANS: Client error displayed when trying to repeat a notice you cannot access.
389 throw new ClientException(_('Cannot repeat a notice you cannot read.'), 403);
392 if ($profile->hasRepeated($repeat->id)) {
393 // TRANS: Client error displayed when trying to repeat an already repeated notice.
394 throw new ClientException(_('You already repeated that notice.'));
397 $notice->repeat_of = $repeat_of;
399 $reply = self::getReplyTo($reply_to, $profile_id, $source, $final);
401 if (!empty($reply)) {
403 if (!$reply->inScope($profile)) {
404 // TRANS: Client error displayed when trying to reply to a notice a the target has no access to.
405 // TRANS: %1$s is a user nickname, %2$d is a notice ID (number).
406 throw new ClientException(sprintf(_('%1$s has no access to notice %2$d.'),
407 $profile->nickname, $reply->id), 403);
410 $notice->reply_to = $reply->id;
411 $notice->conversation = $reply->conversation;
413 // If the original is private to a group, and notice has no group specified,
414 // make it to the same group(s)
416 if (empty($groups) && ($reply->scope | Notice::GROUP_SCOPE)) {
418 $replyGroups = $reply->getGroups();
419 foreach ($replyGroups as $group) {
420 if ($profile->isMember($group)) {
421 $groups[] = $group->id;
430 if (!empty($lat) && !empty($lon)) {
435 if (!empty($location_ns) && !empty($location_id)) {
436 $notice->location_id = $location_id;
437 $notice->location_ns = $location_ns;
440 if (!empty($rendered)) {
441 $notice->rendered = $rendered;
443 $notice->rendered = common_render_content($final, $notice);
446 if (empty($object_type)) {
447 $notice->object_type = (empty($notice->reply_to)) ? ActivityObject::NOTE : ActivityObject::COMMENT;
449 $notice->object_type = $object_type;
452 if (is_null($scope)) { // 0 is a valid value
453 if (!empty($reply)) {
454 $notice->scope = $reply->scope;
456 $notice->scope = self::defaultScope();
459 $notice->scope = $scope;
462 // For private streams
464 $user = $profile->getUser();
467 if ($user->private_stream &&
468 ($notice->scope == Notice::PUBLIC_SCOPE ||
469 $notice->scope == Notice::SITE_SCOPE)) {
470 $notice->scope |= Notice::FOLLOWER_SCOPE;
474 // Force the scope for private groups
476 foreach ($groups as $groupId) {
477 $group = User_group::staticGet('id', $groupId);
478 if (!empty($group)) {
479 if ($group->force_scope) {
480 $notice->scope |= Notice::GROUP_SCOPE;
486 if (Event::handle('StartNoticeSave', array(&$notice))) {
488 // XXX: some of these functions write to the DB
490 $id = $notice->insert();
493 common_log_db_error($notice, 'INSERT', __FILE__);
494 // TRANS: Server exception thrown when a notice cannot be saved.
495 throw new ServerException(_('Problem saving notice.'));
498 // Update ID-dependent columns: URI, conversation
500 $orig = clone($notice);
505 $notice->uri = common_notice_uri($notice);
509 // If it's not part of a conversation, it's
510 // the beginning of a new conversation.
512 if (empty($notice->conversation)) {
513 $conv = Conversation::create();
514 $notice->conversation = $conv->id;
519 if (!$notice->update($orig)) {
520 common_log_db_error($notice, 'UPDATE', __FILE__);
521 // TRANS: Server exception thrown when a notice cannot be updated.
522 throw new ServerException(_('Problem saving notice.'));
528 // Clear the cache for subscribed users, so they'll update at next request
529 // XXX: someone clever could prepend instead of clearing the cache
531 $notice->blowOnInsert();
533 // Save per-notice metadata...
535 if (isset($replies)) {
536 $notice->saveKnownReplies($replies);
538 $notice->saveReplies();
542 $notice->saveKnownTags($tags);
547 // Note: groups may save tags, so must be run after tags are saved
548 // to avoid errors on duplicates.
549 // Note: groups should always be set.
551 $notice->saveKnownGroups($groups);
554 $notice->saveKnownUrls($urls);
560 // Prepare inbox delivery, may be queued to background.
561 $notice->distribute();
567 function blowOnInsert($conversation = false)
569 $this->blowStream('profile:notice_ids:%d', $this->profile_id);
571 if ($this->isPublic()) {
572 $this->blowStream('public');
575 // XXX: Before we were blowing the casche only if the notice id
576 // was not the root of the conversation. What to do now?
578 self::blow('notice:conversation_ids:%d', $this->conversation);
579 self::blow('conversation::notice_count:%d', $this->conversation);
581 if (!empty($this->repeat_of)) {
582 $this->blowStream('notice:repeats:%d', $this->repeat_of);
585 $original = Notice::staticGet('id', $this->repeat_of);
587 if (!empty($original)) {
588 $originalUser = User::staticGet('id', $original->profile_id);
589 if (!empty($originalUser)) {
590 $this->blowStream('user:repeats_of_me:%d', $originalUser->id);
594 $profile = Profile::staticGet($this->profile_id);
596 if (!empty($profile)) {
597 $profile->blowNoticeCount();
600 $ptags = $this->getProfileTags();
601 foreach ($ptags as $ptag) {
602 $ptag->blowNoticeStreamCache();
607 * Clear cache entries related to this notice at delete time.
608 * Necessary to avoid breaking paging on public, profile timelines.
610 function blowOnDelete()
612 $this->blowOnInsert();
614 self::blow('profile:notice_ids:%d;last', $this->profile_id);
616 if ($this->isPublic()) {
617 self::blow('public;last');
620 self::blow('fave:by_notice', $this->id);
622 if ($this->conversation) {
623 // In case we're the first, will need to calc a new root.
624 self::blow('notice:conversation_root:%d', $this->conversation);
627 $ptags = $this->getProfileTags();
628 foreach ($ptags as $ptag) {
629 $ptag->blowNoticeStreamCache(true);
633 function blowStream()
635 $c = self::memcache();
641 $args = func_get_args();
643 $format = array_shift($args);
645 $keyPart = vsprintf($format, $args);
647 $cacheKey = Cache::key($keyPart);
649 $c->delete($cacheKey);
651 // delete the "last" stream, too, if this notice is
652 // older than the top of that stream
654 $lastKey = $cacheKey.';last';
656 $lastStr = $c->get($lastKey);
658 if ($lastStr !== false) {
659 $window = explode(',', $lastStr);
660 $lastID = $window[0];
661 $lastNotice = Notice::staticGet('id', $lastID);
662 if (empty($lastNotice) // just weird
663 || strtotime($lastNotice->created) >= strtotime($this->created)) {
664 $c->delete($lastKey);
669 /** save all urls in the notice to the db
671 * follow redirects and save all available file information
672 * (mimetype, date, size, oembed, etc.)
676 function saveUrls() {
677 if (common_config('attachments', 'process_links')) {
678 common_replace_urls_callback($this->content, array($this, 'saveUrl'), $this->id);
683 * Save the given URLs as related links/attachments to the db
685 * follow redirects and save all available file information
686 * (mimetype, date, size, oembed, etc.)
690 function saveKnownUrls($urls)
692 if (common_config('attachments', 'process_links')) {
693 // @fixme validation?
694 foreach (array_unique($urls) as $url) {
695 File::processNew($url, $this->id);
703 function saveUrl($url, $notice_id) {
704 File::processNew($url, $notice_id);
707 static function checkDupes($profile_id, $content) {
708 $profile = Profile::staticGet($profile_id);
709 if (empty($profile)) {
712 $notice = $profile->getNotices(0, CachingNoticeStream::CACHE_WINDOW);
713 if (!empty($notice)) {
715 while ($notice->fetch()) {
716 if (time() - strtotime($notice->created) >= common_config('site', 'dupelimit')) {
718 } else if ($notice->content == $content) {
723 // If we get here, oldest item in cache window is not
724 // old enough for dupe limit; do direct check against DB
725 $notice = new Notice();
726 $notice->profile_id = $profile_id;
727 $notice->content = $content;
728 $threshold = common_sql_date(time() - common_config('site', 'dupelimit'));
729 $notice->whereAdd(sprintf("created > '%s'", $notice->escape($threshold)));
731 $cnt = $notice->count();
735 static function checkEditThrottle($profile_id) {
736 $profile = Profile::staticGet($profile_id);
737 if (empty($profile)) {
740 // Get the Nth notice
741 $notice = $profile->getNotices(common_config('throttle', 'count') - 1, 1);
742 if ($notice && $notice->fetch()) {
743 // If the Nth notice was posted less than timespan seconds ago
744 if (time() - strtotime($notice->created) <= common_config('throttle', 'timespan')) {
749 // Either not N notices in the stream, OR the Nth was not posted within timespan seconds
753 function getUploadedAttachment() {
755 $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"';
756 $post->query($query);
758 if (empty($post->up) || empty($post->i)) {
761 $ret = array($post->up, $post->i);
767 function hasAttachments() {
769 $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);
770 $post->query($query);
772 $n_attachments = intval($post->n_attachments);
774 return $n_attachments;
777 function attachments() {
779 $keypart = sprintf('notice:file_ids:%d', $this->id);
781 $idstr = self::cacheGet($keypart);
783 if ($idstr !== false) {
784 $ids = explode(',', $idstr);
787 $f2p = new File_to_post;
788 $f2p->post_id = $this->id;
790 while ($f2p->fetch()) {
791 $ids[] = $f2p->file_id;
794 self::cacheSet($keypart, implode(',', $ids));
799 foreach ($ids as $id) {
800 $f = File::staticGet('id', $id);
810 function publicStream($offset=0, $limit=20, $since_id=0, $max_id=0)
812 $stream = new PublicNoticeStream();
813 return $stream->getNotices($offset, $limit, $since_id, $max_id);
817 function conversationStream($id, $offset=0, $limit=20, $since_id=0, $max_id=0)
819 $stream = new ConversationNoticeStream($id);
821 return $stream->getNotices($offset, $limit, $since_id, $max_id);
825 * Is this notice part of an active conversation?
827 * @return boolean true if other messages exist in the same
828 * conversation, false if this is the only one
830 function hasConversation()
832 if (!empty($this->conversation)) {
833 $conversation = Notice::conversationStream(
839 if ($conversation->N > 0) {
847 * Grab the earliest notice from this conversation.
849 * @return Notice or null
851 function conversationRoot($profile=-1)
853 // XXX: can this happen?
855 if (empty($this->conversation)) {
859 // Get the current profile if not specified
861 if (is_int($profile) && $profile == -1) {
862 $profile = Profile::current();
865 // If this notice is out of scope, no root for you!
867 if (!$this->inScope($profile)) {
871 // If this isn't a reply to anything, then it's its own
874 if (empty($this->reply_to)) {
878 if (is_null($profile)) {
879 $keypart = sprintf('notice:conversation_root:%d:null', $this->id);
881 $keypart = sprintf('notice:conversation_root:%d:%d',
886 $root = self::cacheGet($keypart);
888 if ($root !== false && $root->inScope($profile)) {
894 $parent = $last->getOriginal();
895 if (!empty($parent) && $parent->inScope($profile)) {
902 } while (!empty($parent));
904 self::cacheSet($keypart, $root);
911 * Pull up a full list of local recipients who will be getting
912 * this notice in their inbox. Results will be cached, so don't
913 * change the input data wily-nilly!
915 * @param array $groups optional list of Group objects;
916 * if left empty, will be loaded from group_inbox records
917 * @param array $recipient optional list of reply profile ids
918 * if left empty, will be loaded from reply records
919 * @return array associating recipient user IDs with an inbox source constant
921 function whoGets($groups=null, $recipients=null)
923 $c = self::memcache();
926 $ni = $c->get(Cache::key('notice:who_gets:'.$this->id));
932 if (is_null($groups)) {
933 $groups = $this->getGroups();
936 if (is_null($recipients)) {
937 $recipients = $this->getReplies();
940 $users = $this->getSubscribedUsers();
941 $ptags = $this->getProfileTags();
943 // FIXME: kind of ignoring 'transitional'...
944 // we'll probably stop supporting inboxless mode
949 // Give plugins a chance to add folks in at start...
950 if (Event::handle('StartNoticeWhoGets', array($this, &$ni))) {
952 foreach ($users as $id) {
953 $ni[$id] = NOTICE_INBOX_SOURCE_SUB;
956 foreach ($groups as $group) {
957 $users = $group->getUserMembers();
958 foreach ($users as $id) {
959 if (!array_key_exists($id, $ni)) {
960 $ni[$id] = NOTICE_INBOX_SOURCE_GROUP;
965 foreach ($ptags as $ptag) {
966 $users = $ptag->getUserSubscribers();
967 foreach ($users as $id) {
968 if (!array_key_exists($id, $ni)) {
969 $user = User::staticGet('id', $id);
970 if (!$user->hasBlocked($profile)) {
971 $ni[$id] = NOTICE_INBOX_SOURCE_PROFILE_TAG;
977 foreach ($recipients as $recipient) {
978 if (!array_key_exists($recipient, $ni)) {
979 $ni[$recipient] = NOTICE_INBOX_SOURCE_REPLY;
982 // Exclude any deleted, non-local, or blocking recipients.
983 $profile = $this->getProfile();
984 $originalProfile = null;
985 if ($this->repeat_of) {
986 // Check blocks against the original notice's poster as well.
987 $original = Notice::staticGet('id', $this->repeat_of);
989 $originalProfile = $original->getProfile();
992 foreach ($ni as $id => $source) {
993 $user = User::staticGet('id', $id);
994 if (empty($user) || $user->hasBlocked($profile) ||
995 ($originalProfile && $user->hasBlocked($originalProfile))) {
1001 // Give plugins a chance to filter out...
1002 Event::handle('EndNoticeWhoGets', array($this, &$ni));
1006 // XXX: pack this data better
1007 $c->set(Cache::key('notice:who_gets:'.$this->id), $ni);
1014 * Adds this notice to the inboxes of each local user who should receive
1015 * it, based on author subscriptions, group memberships, and @-replies.
1017 * Warning: running a second time currently will make items appear
1018 * multiple times in users' inboxes.
1020 * @fixme make more robust against errors
1021 * @fixme break up massive deliveries to smaller background tasks
1023 * @param array $groups optional list of Group objects;
1024 * if left empty, will be loaded from group_inbox records
1025 * @param array $recipient optional list of reply profile ids
1026 * if left empty, will be loaded from reply records
1028 function addToInboxes($groups=null, $recipients=null)
1030 $ni = $this->whoGets($groups, $recipients);
1032 $ids = array_keys($ni);
1034 // We remove the author (if they're a local user),
1035 // since we'll have already done this in distribute()
1037 $i = array_search($this->profile_id, $ids);
1045 Inbox::bulkInsert($this->id, $ids);
1050 function getSubscribedUsers()
1054 if(common_config('db','quote_identifiers'))
1055 $user_table = '"user"';
1056 else $user_table = 'user';
1060 'FROM '. $user_table .' JOIN subscription '.
1061 'ON '. $user_table .'.id = subscription.subscriber ' .
1062 'WHERE subscription.subscribed = %d ';
1064 $user->query(sprintf($qry, $this->profile_id));
1068 while ($user->fetch()) {
1077 function getProfileTags()
1079 $profile = $this->getProfile();
1080 $list = $profile->getOtherTags($profile);
1083 while($list->fetch()) {
1084 $ptags[] = clone($list);
1091 * Record this notice to the given group inboxes for delivery.
1092 * Overrides the regular parsing of !group markup.
1094 * @param string $group_ids
1095 * @fixme might prefer URIs as identifiers, as for replies?
1096 * best with generalizations on user_group to support
1097 * remote groups better.
1099 function saveKnownGroups($group_ids)
1101 if (!is_array($group_ids)) {
1102 // TRANS: Server exception thrown when no array is provided to the method saveKnownGroups().
1103 throw new ServerException(_('Bad type provided to saveKnownGroups.'));
1107 foreach (array_unique($group_ids) as $id) {
1108 $group = User_group::staticGet('id', $id);
1110 common_log(LOG_ERR, "Local delivery to group id $id, $group->nickname");
1111 $result = $this->addToGroupInbox($group);
1113 common_log_db_error($gi, 'INSERT', __FILE__);
1116 if (common_config('group', 'addtag')) {
1117 // we automatically add a tag for every group name, too
1119 $tag = Notice_tag::pkeyGet(array('tag' => common_canonical_tag($group->nickname),
1120 'notice_id' => $this->id));
1122 if (is_null($tag)) {
1123 $this->saveTag($group->nickname);
1127 $groups[] = clone($group);
1129 common_log(LOG_ERR, "Local delivery to group id $id skipped, doesn't exist");
1137 * Parse !group delivery and record targets into group_inbox.
1138 * @return array of Group objects
1140 function saveGroups()
1142 // Don't save groups for repeats
1144 if (!empty($this->repeat_of)) {
1148 $profile = $this->getProfile();
1150 $groups = self::groupsFromText($this->content, $profile);
1152 /* Add them to the database */
1154 foreach ($groups as $group) {
1155 /* XXX: remote groups. */
1157 if (empty($group)) {
1162 if ($profile->isMember($group)) {
1164 $result = $this->addToGroupInbox($group);
1167 common_log_db_error($gi, 'INSERT', __FILE__);
1170 $groups[] = clone($group);
1177 function addToGroupInbox($group)
1179 $gi = Group_inbox::pkeyGet(array('group_id' => $group->id,
1180 'notice_id' => $this->id));
1184 $gi = new Group_inbox();
1186 $gi->group_id = $group->id;
1187 $gi->notice_id = $this->id;
1188 $gi->created = $this->created;
1190 $result = $gi->insert();
1193 common_log_db_error($gi, 'INSERT', __FILE__);
1194 // TRANS: Server exception thrown when an update for a group inbox fails.
1195 throw new ServerException(_('Problem saving group inbox.'));
1198 self::blow('user_group:notice_ids:%d', $gi->group_id);
1205 * Save reply records indicating that this notice needs to be
1206 * delivered to the local users with the given URIs.
1208 * Since this is expected to be used when saving foreign-sourced
1209 * messages, we won't deliver to any remote targets as that's the
1210 * source service's responsibility.
1212 * Mail notifications etc will be handled later.
1214 * @param array of unique identifier URIs for recipients
1216 function saveKnownReplies($uris)
1222 $sender = Profile::staticGet($this->profile_id);
1224 foreach (array_unique($uris) as $uri) {
1226 $profile = Profile::fromURI($uri);
1228 if (empty($profile)) {
1229 common_log(LOG_WARNING, "Unable to determine profile for URI '$uri'");
1233 if ($profile->hasBlocked($sender)) {
1234 common_log(LOG_INFO, "Not saving reply to profile {$profile->id} ($uri) from sender {$sender->id} because of a block.");
1238 $this->saveReply($profile->id);
1239 self::blow('reply:stream:%d', $profile->id);
1246 * Pull @-replies from this message's content in StatusNet markup format
1247 * and save reply records indicating that this message needs to be
1248 * delivered to those users.
1250 * Mail notifications to local profiles will be sent later.
1252 * @return array of integer profile IDs
1255 function saveReplies()
1257 // Don't save reply data for repeats
1259 if (!empty($this->repeat_of)) {
1263 $sender = Profile::staticGet($this->profile_id);
1267 // If it's a reply, save for the replied-to author
1269 if (!empty($this->reply_to)) {
1270 $original = $this->getOriginal();
1271 if (!empty($original)) { // that'd be weird
1272 $author = $original->getProfile();
1273 if (!empty($author)) {
1274 $this->saveReply($author->id);
1275 $replied[$author->id] = 1;
1276 self::blow('reply:stream:%d', $author->id);
1281 // @todo ideally this parser information would only
1282 // be calculated once.
1284 $mentions = common_find_mentions($this->content, $this);
1286 // store replied only for first @ (what user/notice what the reply directed,
1287 // we assume first @ is it)
1289 foreach ($mentions as $mention) {
1291 foreach ($mention['mentioned'] as $mentioned) {
1293 // skip if they're already covered
1295 if (!empty($replied[$mentioned->id])) {
1299 // Don't save replies from blocked profile to local user
1301 $mentioned_user = User::staticGet('id', $mentioned->id);
1302 if (!empty($mentioned_user) && $mentioned_user->hasBlocked($sender)) {
1306 $this->saveReply($mentioned->id);
1307 $replied[$mentioned->id] = 1;
1308 self::blow('reply:stream:%d', $mentioned->id);
1312 $recipientIds = array_keys($replied);
1314 return $recipientIds;
1317 function saveReply($profileId)
1319 $reply = new Reply();
1321 $reply->notice_id = $this->id;
1322 $reply->profile_id = $profileId;
1323 $reply->modified = $this->created;
1331 * Pull the complete list of @-reply targets for this notice.
1333 * @return array of integer profile ids
1335 function getReplies()
1337 $keypart = sprintf('notice:reply_ids:%d', $this->id);
1339 $idstr = self::cacheGet($keypart);
1341 if ($idstr !== false) {
1342 $ids = explode(',', $idstr);
1346 $reply = new Reply();
1347 $reply->selectAdd();
1348 $reply->selectAdd('profile_id');
1349 $reply->notice_id = $this->id;
1351 if ($reply->find()) {
1352 while($reply->fetch()) {
1353 $ids[] = $reply->profile_id;
1356 self::cacheSet($keypart, implode(',', $ids));
1363 * Pull the complete list of @-reply targets for this notice.
1365 * @return array of Profiles
1367 function getReplyProfiles()
1369 $ids = $this->getReplies();
1370 $profiles = array();
1372 foreach ($ids as $id) {
1373 $profile = Profile::staticGet('id', $id);
1374 if (!empty($profile)) {
1375 $profiles[] = $profile;
1383 * Send e-mail notifications to local @-reply targets.
1385 * Replies must already have been saved; this is expected to be run
1386 * from the distrib queue handler.
1388 function sendReplyNotifications()
1390 // Don't send reply notifications for repeats
1392 if (!empty($this->repeat_of)) {
1396 $recipientIds = $this->getReplies();
1398 foreach ($recipientIds as $recipientId) {
1399 $user = User::staticGet('id', $recipientId);
1400 if (!empty($user)) {
1401 mail_notify_attn($user, $this);
1407 * Pull list of groups this notice needs to be delivered to,
1408 * as previously recorded by saveGroups() or saveKnownGroups().
1410 * @return array of Group objects
1412 function getGroups()
1414 // Don't save groups for repeats
1416 if (!empty($this->repeat_of)) {
1422 $keypart = sprintf('notice:groups:%d', $this->id);
1424 $idstr = self::cacheGet($keypart);
1426 if ($idstr !== false) {
1427 $ids = explode(',', $idstr);
1429 $gi = new Group_inbox();
1432 $gi->selectAdd('group_id');
1434 $gi->notice_id = $this->id;
1437 while ($gi->fetch()) {
1438 $ids[] = $gi->group_id;
1442 self::cacheSet($keypart, implode(',', $ids));
1447 foreach ($ids as $id) {
1448 $group = User_group::staticGet('id', $id);
1458 * Convert a notice into an activity for export.
1460 * @param User $cur Current user
1462 * @return Activity activity object representing this Notice.
1465 function asActivity($cur)
1467 $act = self::cacheGet(Cache::codeKey('notice:as-activity:'.$this->id));
1472 $act = new Activity();
1474 if (Event::handle('StartNoticeAsActivity', array($this, &$act))) {
1476 $profile = $this->getProfile();
1478 $act->actor = ActivityObject::fromProfile($profile);
1479 $act->actor->extra[] = $profile->profileInfo($cur);
1480 $act->verb = ActivityVerb::POST;
1481 $act->objects[] = ActivityObject::fromNotice($this);
1483 // XXX: should this be handled by default processing for object entry?
1485 $act->time = strtotime($this->created);
1486 $act->link = $this->bestUrl();
1488 $act->content = common_xml_safe_str($this->rendered);
1489 $act->id = $this->uri;
1490 $act->title = common_xml_safe_str($this->content);
1494 $tags = $this->getTags();
1496 foreach ($tags as $tag) {
1497 $cat = new AtomCategory();
1500 $act->categories[] = $cat;
1504 // XXX: use Atom Media and/or File activity objects instead
1506 $attachments = $this->attachments();
1508 foreach ($attachments as $attachment) {
1509 $enclosure = $attachment->getEnclosure();
1511 $act->enclosures[] = $enclosure;
1515 $ctx = new ActivityContext();
1517 if (!empty($this->reply_to)) {
1518 $reply = Notice::staticGet('id', $this->reply_to);
1519 if (!empty($reply)) {
1520 $ctx->replyToID = $reply->uri;
1521 $ctx->replyToUrl = $reply->bestUrl();
1525 $ctx->location = $this->getLocation();
1529 if (!empty($this->conversation)) {
1530 $conv = Conversation::staticGet('id', $this->conversation);
1531 if (!empty($conv)) {
1532 $ctx->conversation = $conv->uri;
1536 $reply_ids = $this->getReplies();
1538 foreach ($reply_ids as $id) {
1539 $rprofile = Profile::staticGet('id', $id);
1540 if (!empty($rprofile)) {
1541 $ctx->attention[] = $rprofile->getUri();
1545 $groups = $this->getGroups();
1547 foreach ($groups as $group) {
1548 $ctx->attention[] = $group->getUri();
1551 // XXX: deprecated; use ActivityVerb::SHARE instead
1555 if (!empty($this->repeat_of)) {
1556 $repeat = Notice::staticGet('id', $this->repeat_of);
1557 $ctx->forwardID = $repeat->uri;
1558 $ctx->forwardUrl = $repeat->bestUrl();
1561 $act->context = $ctx;
1565 $atom_feed = $profile->getAtomFeed();
1567 if (!empty($atom_feed)) {
1569 $act->source = new ActivitySource();
1571 // XXX: we should store the actual feed ID
1573 $act->source->id = $atom_feed;
1575 // XXX: we should store the actual feed title
1577 $act->source->title = $profile->getBestName();
1579 $act->source->links['alternate'] = $profile->profileurl;
1580 $act->source->links['self'] = $atom_feed;
1582 $act->source->icon = $profile->avatarUrl(AVATAR_PROFILE_SIZE);
1584 $notice = $profile->getCurrentNotice();
1586 if (!empty($notice)) {
1587 $act->source->updated = self::utcDate($notice->created);
1590 $user = User::staticGet('id', $profile->id);
1592 if (!empty($user)) {
1593 $act->source->links['license'] = common_config('license', 'url');
1597 if ($this->isLocal()) {
1598 $act->selfLink = common_local_url('ApiStatusesShow', array('id' => $this->id,
1599 'format' => 'atom'));
1600 $act->editLink = $act->selfLink;
1603 Event::handle('EndNoticeAsActivity', array($this, &$act));
1606 self::cacheSet(Cache::codeKey('notice:as-activity:'.$this->id), $act);
1611 // This has gotten way too long. Needs to be sliced up into functional bits
1612 // or ideally exported to a utility class.
1614 function asAtomEntry($namespace=false,
1619 $act = $this->asActivity($cur);
1620 $act->extra[] = $this->noticeInfo($cur);
1621 return $act->asString($namespace, $author, $source);
1625 * Extra notice info for atom entries
1627 * Clients use some extra notice info in the atom stream.
1628 * This gives it to them.
1630 * @param User $cur Current user
1632 * @return array representation of <statusnet:notice_info> element
1635 function noticeInfo($cur)
1637 // local notice ID (useful to clients for ordering)
1639 $noticeInfoAttr = array('local_id' => $this->id);
1643 $ns = $this->getSource();
1646 $noticeInfoAttr['source'] = $ns->code;
1647 if (!empty($ns->url)) {
1648 $noticeInfoAttr['source_link'] = $ns->url;
1649 if (!empty($ns->name)) {
1650 $noticeInfoAttr['source'] = '<a href="'
1651 . htmlspecialchars($ns->url)
1652 . '" rel="nofollow">'
1653 . htmlspecialchars($ns->name)
1659 // favorite and repeated
1662 $noticeInfoAttr['favorite'] = ($cur->hasFave($this)) ? "true" : "false";
1663 $cp = $cur->getProfile();
1664 $noticeInfoAttr['repeated'] = ($cp->hasRepeated($this->id)) ? "true" : "false";
1667 if (!empty($this->repeat_of)) {
1668 $noticeInfoAttr['repeat_of'] = $this->repeat_of;
1671 return array('statusnet:notice_info', $noticeInfoAttr, null);
1675 * Returns an XML string fragment with a reference to a notice as an
1676 * Activity Streams noun object with the given element type.
1678 * Assumes that 'activity' namespace has been previously defined.
1680 * @param string $element one of 'subject', 'object', 'target'
1684 function asActivityNoun($element)
1686 $noun = ActivityObject::fromNotice($this);
1687 return $noun->asString('activity:' . $element);
1692 if (!empty($this->url)) {
1694 } else if (!empty($this->uri) && preg_match('/^https?:/', $this->uri)) {
1697 return common_local_url('shownotice',
1698 array('notice' => $this->id));
1704 * Determine which notice, if any, a new notice is in reply to.
1706 * For conversation tracking, we try to see where this notice fits
1707 * in the tree. Rough algorithm is:
1709 * if (reply_to is set and valid) {
1711 * } else if ((source not API or Web) and (content starts with "T NAME" or "@name ")) {
1712 * return ID of last notice by initial @name in content;
1715 * Note that all @nickname instances will still be used to save "reply" records,
1716 * so the notice shows up in the mentioned users' "replies" tab.
1718 * @param integer $reply_to ID passed in by Web or API
1719 * @param integer $profile_id ID of author
1720 * @param string $source Source tag, like 'web' or 'gwibber'
1721 * @param string $content Final notice content
1723 * @return integer ID of replied-to notice, or null for not a reply.
1726 static function getReplyTo($reply_to, $profile_id, $source, $content)
1728 static $lb = array('xmpp', 'mail', 'sms', 'omb');
1730 // If $reply_to is specified, we check that it exists, and then
1731 // return it if it does
1733 if (!empty($reply_to)) {
1734 $reply_notice = Notice::staticGet('id', $reply_to);
1735 if (!empty($reply_notice)) {
1736 return $reply_notice;
1740 // If it's not a "low bandwidth" source (one where you can't set
1741 // a reply_to argument), we return. This is mostly web and API
1744 if (!in_array($source, $lb)) {
1748 // Is there an initial @ or T?
1750 if (preg_match('/^T ([A-Z0-9]{1,64}) /', $content, $match) ||
1751 preg_match('/^@([a-z0-9]{1,64})\s+/', $content, $match)) {
1752 $nickname = common_canonical_nickname($match[1]);
1757 // Figure out who that is.
1759 $sender = Profile::staticGet('id', $profile_id);
1760 if (empty($sender)) {
1764 $recipient = common_relative_profile($sender, $nickname, common_sql_now());
1766 if (empty($recipient)) {
1770 // Get their last notice
1772 $last = $recipient->getCurrentNotice();
1774 if (!empty($last)) {
1781 static function maxContent()
1783 $contentlimit = common_config('notice', 'contentlimit');
1784 // null => use global limit (distinct from 0!)
1785 if (is_null($contentlimit)) {
1786 $contentlimit = common_config('site', 'textlimit');
1788 return $contentlimit;
1791 static function contentTooLong($content)
1793 $contentlimit = self::maxContent();
1794 return ($contentlimit > 0 && !empty($content) && (mb_strlen($content) > $contentlimit));
1797 function getLocation()
1801 if (!empty($this->location_id) && !empty($this->location_ns)) {
1802 $location = Location::fromId($this->location_id, $this->location_ns);
1805 if (is_null($location)) { // no ID, or Location::fromId() failed
1806 if (!empty($this->lat) && !empty($this->lon)) {
1807 $location = Location::fromLatLon($this->lat, $this->lon);
1815 * Convenience function for posting a repeat of an existing message.
1817 * @param int $repeater_id: profile ID of user doing the repeat
1818 * @param string $source: posting source key, eg 'web', 'api', etc
1821 * @throws Exception on failure or permission problems
1823 function repeat($repeater_id, $source)
1825 $author = Profile::staticGet('id', $this->profile_id);
1827 // TRANS: Message used to repeat a notice. RT is the abbreviation of 'retweet'.
1828 // TRANS: %1$s is the repeated user's name, %2$s is the repeated notice.
1829 $content = sprintf(_('RT @%1$s %2$s'),
1833 $maxlen = common_config('site', 'textlimit');
1834 if ($maxlen > 0 && mb_strlen($content) > $maxlen) {
1835 // Web interface and current Twitter API clients will
1836 // pull the original notice's text, but some older
1837 // clients and RSS/Atom feeds will see this trimmed text.
1839 // Unfortunately this is likely to lose tags or URLs
1840 // at the end of long notices.
1841 $content = mb_substr($content, 0, $maxlen - 4) . ' ...';
1844 // Scope is same as this one's
1846 return self::saveNew($repeater_id,
1849 array('repeat_of' => $this->id,
1850 'scope' => $this->scope));
1853 // These are supposed to be in chron order!
1855 function repeatStream($limit=100)
1857 $cache = Cache::instance();
1859 if (empty($cache)) {
1860 $ids = $this->_repeatStreamDirect($limit);
1862 $idstr = $cache->get(Cache::key('notice:repeats:'.$this->id));
1863 if ($idstr !== false) {
1864 if (empty($idstr)) {
1867 $ids = explode(',', $idstr);
1870 $ids = $this->_repeatStreamDirect(100);
1871 $cache->set(Cache::key('notice:repeats:'.$this->id), implode(',', $ids));
1874 // We do a max of 100, so slice down to limit
1875 $ids = array_slice($ids, 0, $limit);
1879 return NoticeStream::getStreamByIds($ids);
1882 function _repeatStreamDirect($limit)
1884 $notice = new Notice();
1886 $notice->selectAdd(); // clears it
1887 $notice->selectAdd('id');
1889 $notice->repeat_of = $this->id;
1891 $notice->orderBy('created, id'); // NB: asc!
1893 if (!is_null($limit)) {
1894 $notice->limit(0, $limit);
1897 return $notice->fetchAll('id');
1900 function locationOptions($lat, $lon, $location_id, $location_ns, $profile = null)
1904 if (!empty($location_id) && !empty($location_ns)) {
1905 $options['location_id'] = $location_id;
1906 $options['location_ns'] = $location_ns;
1908 $location = Location::fromId($location_id, $location_ns);
1910 if (!empty($location)) {
1911 $options['lat'] = $location->lat;
1912 $options['lon'] = $location->lon;
1915 } else if (!empty($lat) && !empty($lon)) {
1916 $options['lat'] = $lat;
1917 $options['lon'] = $lon;
1919 $location = Location::fromLatLon($lat, $lon);
1921 if (!empty($location)) {
1922 $options['location_id'] = $location->location_id;
1923 $options['location_ns'] = $location->location_ns;
1925 } else if (!empty($profile)) {
1926 if (isset($profile->lat) && isset($profile->lon)) {
1927 $options['lat'] = $profile->lat;
1928 $options['lon'] = $profile->lon;
1931 if (isset($profile->location_id) && isset($profile->location_ns)) {
1932 $options['location_id'] = $profile->location_id;
1933 $options['location_ns'] = $profile->location_ns;
1940 function clearReplies()
1942 $replyNotice = new Notice();
1943 $replyNotice->reply_to = $this->id;
1945 //Null any notices that are replies to this notice
1947 if ($replyNotice->find()) {
1948 while ($replyNotice->fetch()) {
1949 $orig = clone($replyNotice);
1950 $replyNotice->reply_to = null;
1951 $replyNotice->update($orig);
1957 $reply = new Reply();
1958 $reply->notice_id = $this->id;
1960 if ($reply->find()) {
1961 while($reply->fetch()) {
1962 self::blow('reply:stream:%d', $reply->profile_id);
1970 function clearFiles()
1972 $f2p = new File_to_post();
1974 $f2p->post_id = $this->id;
1977 while ($f2p->fetch()) {
1981 // FIXME: decide whether to delete File objects
1982 // ...and related (actual) files
1985 function clearRepeats()
1987 $repeatNotice = new Notice();
1988 $repeatNotice->repeat_of = $this->id;
1990 //Null any notices that are repeats of this notice
1992 if ($repeatNotice->find()) {
1993 while ($repeatNotice->fetch()) {
1994 $orig = clone($repeatNotice);
1995 $repeatNotice->repeat_of = null;
1996 $repeatNotice->update($orig);
2001 function clearFaves()
2004 $fave->notice_id = $this->id;
2006 if ($fave->find()) {
2007 while ($fave->fetch()) {
2008 self::blow('fave:ids_by_user_own:%d', $fave->user_id);
2009 self::blow('fave:ids_by_user_own:%d;last', $fave->user_id);
2010 self::blow('fave:ids_by_user:%d', $fave->user_id);
2011 self::blow('fave:ids_by_user:%d;last', $fave->user_id);
2019 function clearTags()
2021 $tag = new Notice_tag();
2022 $tag->notice_id = $this->id;
2025 while ($tag->fetch()) {
2026 self::blow('profile:notice_ids_tagged:%d:%s', $this->profile_id, Cache::keyize($tag->tag));
2027 self::blow('profile:notice_ids_tagged:%d:%s;last', $this->profile_id, Cache::keyize($tag->tag));
2028 self::blow('notice_tag:notice_ids:%s', Cache::keyize($tag->tag));
2029 self::blow('notice_tag:notice_ids:%s;last', Cache::keyize($tag->tag));
2037 function clearGroupInboxes()
2039 $gi = new Group_inbox();
2041 $gi->notice_id = $this->id;
2044 while ($gi->fetch()) {
2045 self::blow('user_group:notice_ids:%d', $gi->group_id);
2053 function distribute()
2055 // We always insert for the author so they don't
2057 Event::handle('StartNoticeDistribute', array($this));
2059 $user = User::staticGet('id', $this->profile_id);
2060 if (!empty($user)) {
2061 Inbox::insertNotice($user->id, $this->id);
2064 if (common_config('queue', 'inboxes')) {
2065 // If there's a failure, we want to _force_
2066 // distribution at this point.
2068 $qm = QueueManager::get();
2069 $qm->enqueue($this, 'distrib');
2070 } catch (Exception $e) {
2071 // If the exception isn't transient, this
2072 // may throw more exceptions as DQH does
2073 // its own enqueueing. So, we ignore them!
2075 $handler = new DistribQueueHandler();
2076 $handler->handle($this);
2077 } catch (Exception $e) {
2078 common_log(LOG_ERR, "emergency redistribution resulted in " . $e->getMessage());
2080 // Re-throw so somebody smarter can handle it.
2084 $handler = new DistribQueueHandler();
2085 $handler->handle($this);
2091 $result = parent::insert();
2094 // Profile::hasRepeated() abuses pkeyGet(), so we
2095 // have to clear manually
2096 if (!empty($this->repeat_of)) {
2097 $c = self::memcache();
2099 $ck = self::multicacheKey('Notice',
2100 array('profile_id' => $this->profile_id,
2101 'repeat_of' => $this->repeat_of));
2111 * Get the source of the notice
2113 * @return Notice_source $ns A notice source object. 'code' is the only attribute
2114 * guaranteed to be populated.
2116 function getSource()
2118 $ns = new Notice_source();
2119 if (!empty($this->source)) {
2120 switch ($this->source) {
2127 $ns->code = $this->source;
2130 $ns = Notice_source::staticGet($this->source);
2132 $ns = new Notice_source();
2133 $ns->code = $this->source;
2134 $app = Oauth_application::staticGet('name', $this->source);
2136 $ns->name = $app->name;
2137 $ns->url = $app->source_url;
2147 * Determine whether the notice was locally created
2149 * @return boolean locality
2152 public function isLocal()
2154 return ($this->is_local == Notice::LOCAL_PUBLIC ||
2155 $this->is_local == Notice::LOCAL_NONPUBLIC);
2159 * Get the list of hash tags saved with this notice.
2161 * @return array of strings
2163 public function getTags()
2167 $keypart = sprintf('notice:tags:%d', $this->id);
2169 $tagstr = self::cacheGet($keypart);
2171 if ($tagstr !== false) {
2172 $tags = explode(',', $tagstr);
2174 $tag = new Notice_tag();
2175 $tag->notice_id = $this->id;
2177 while ($tag->fetch()) {
2178 $tags[] = $tag->tag;
2181 self::cacheSet($keypart, implode(',', $tags));
2187 static private function utcDate($dt)
2189 $dateStr = date('d F Y H:i:s', strtotime($dt));
2190 $d = new DateTime($dateStr, new DateTimeZone('UTC'));
2191 return $d->format(DATE_W3C);
2195 * Look up the creation timestamp for a given notice ID, even
2196 * if it's been deleted.
2199 * @return mixed string recorded creation timestamp, or false if can't be found
2201 public static function getAsTimestamp($id)
2207 $notice = Notice::staticGet('id', $id);
2209 return $notice->created;
2212 $deleted = Deleted_notice::staticGet('id', $id);
2214 return $deleted->created;
2221 * Build an SQL 'where' fragment for timestamp-based sorting from a since_id
2222 * parameter, matching notices posted after the given one (exclusive).
2224 * If the referenced notice can't be found, will return false.
2227 * @param string $idField
2228 * @param string $createdField
2229 * @return mixed string or false if no match
2231 public static function whereSinceId($id, $idField='id', $createdField='created')
2233 $since = Notice::getAsTimestamp($id);
2235 return sprintf("($createdField = '%s' and $idField > %d) or ($createdField > '%s')", $since, $id, $since);
2241 * Build an SQL 'where' fragment for timestamp-based sorting from a since_id
2242 * parameter, matching notices posted after the given one (exclusive), and
2243 * if necessary add it to the data object's query.
2245 * @param DB_DataObject $obj
2247 * @param string $idField
2248 * @param string $createdField
2249 * @return mixed string or false if no match
2251 public static function addWhereSinceId(DB_DataObject $obj, $id, $idField='id', $createdField='created')
2253 $since = self::whereSinceId($id, $idField, $createdField);
2255 $obj->whereAdd($since);
2260 * Build an SQL 'where' fragment for timestamp-based sorting from a max_id
2261 * parameter, matching notices posted before the given one (inclusive).
2263 * If the referenced notice can't be found, will return false.
2266 * @param string $idField
2267 * @param string $createdField
2268 * @return mixed string or false if no match
2270 public static function whereMaxId($id, $idField='id', $createdField='created')
2272 $max = Notice::getAsTimestamp($id);
2274 return sprintf("($createdField < '%s') or ($createdField = '%s' and $idField <= %d)", $max, $max, $id);
2280 * Build an SQL 'where' fragment for timestamp-based sorting from a max_id
2281 * parameter, matching notices posted before the given one (inclusive), and
2282 * if necessary add it to the data object's query.
2284 * @param DB_DataObject $obj
2286 * @param string $idField
2287 * @param string $createdField
2288 * @return mixed string or false if no match
2290 public static function addWhereMaxId(DB_DataObject $obj, $id, $idField='id', $createdField='created')
2292 $max = self::whereMaxId($id, $idField, $createdField);
2294 $obj->whereAdd($max);
2300 if (common_config('public', 'localonly')) {
2301 return ($this->is_local == Notice::LOCAL_PUBLIC);
2303 return (($this->is_local != Notice::LOCAL_NONPUBLIC) &&
2304 ($this->is_local != Notice::GATEWAY));
2309 * Check that the given profile is allowed to read, respond to, or otherwise
2310 * act on this notice.
2312 * The $scope member is a bitmask of scopes, representing a logical AND of the
2313 * scope requirement. So, 0x03 (Notice::ADDRESSEE_SCOPE | Notice::SITE_SCOPE) means
2314 * "only visible to people who are mentioned in the notice AND are users on this site."
2315 * Users on the site who are not mentioned in the notice will not be able to see the
2318 * @param Profile $profile The profile to check; pass null to check for public/unauthenticated users.
2320 * @return boolean whether the profile is in the notice's scope
2322 function inScope($profile)
2324 if (is_null($profile)) {
2325 $keypart = sprintf('notice:in-scope-for:%d:null', $this->id);
2327 $keypart = sprintf('notice:in-scope-for:%d:%d', $this->id, $profile->id);
2330 $result = self::cacheGet($keypart);
2332 if ($result === false) {
2333 $bResult = $this->_inScope($profile);
2334 $result = ($bResult) ? 1 : 0;
2335 self::cacheSet($keypart, $result, 0, 300);
2338 return ($result == 1) ? true : false;
2341 protected function _inScope($profile)
2343 // If there's no scope, anyone (even anon) is in scope.
2345 if ($this->scope == 0) {
2349 // If there's scope, anon cannot be in scope
2351 if (empty($profile)) {
2355 // Author is always in scope
2357 if ($this->profile_id == $profile->id) {
2361 // Only for users on this site
2363 if ($this->scope & Notice::SITE_SCOPE) {
2364 $user = $profile->getUser();
2370 // Only for users mentioned in the notice
2372 if ($this->scope & Notice::ADDRESSEE_SCOPE) {
2374 // XXX: just query for the single reply
2376 $replies = $this->getReplies();
2378 if (!in_array($profile->id, $replies)) {
2383 // Only for members of the given group
2385 if ($this->scope & Notice::GROUP_SCOPE) {
2387 // XXX: just query for the single membership
2389 $groups = $this->getGroups();
2393 foreach ($groups as $group) {
2394 if ($profile->isMember($group)) {
2405 // Only for followers of the author
2407 if ($this->scope & Notice::FOLLOWER_SCOPE) {
2408 $author = $this->getProfile();
2409 if (!Subscription::exists($profile, $author)) {
2417 static function groupsFromText($text, $profile)
2421 /* extract all !group */
2422 $count = preg_match_all('/(?:^|\s)!(' . Nickname::DISPLAY_FMT . ')/',
2430 foreach (array_unique($match[1]) as $nickname) {
2431 $group = User_group::getForNickname($nickname, $profile);
2432 if (!empty($group) && $profile->isMember($group)) {
2433 $groups[] = $group->id;
2440 protected $_original = -1;
2442 function getOriginal()
2444 if (is_int($this->_original) && $this->_original == -1) {
2445 if (empty($this->reply_to)) {
2446 $this->_original = null;
2448 $this->_original = Notice::staticGet('id', $this->reply_to);
2451 return $this->_original;
2455 * Magic function called at serialize() time.
2457 * We use this to drop a couple process-specific references
2458 * from DB_DataObject which can cause trouble in future
2461 * @return array of variable names to include in serialization.
2466 $vars = parent::__sleep();
2467 $skip = array('_original', '_profile');
2468 return array_diff($vars, $skip);
2471 static function defaultScope()
2473 $scope = common_config('notice', 'defaultscope');
2474 if (is_null($scope)) {
2475 if (common_config('site', 'private')) {