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 $this->saveReply($profile->id);
1195 self::blow('reply:stream:%d', $profile->id);
1202 * Pull @-replies from this message's content in StatusNet markup format
1203 * and save reply records indicating that this message needs to be
1204 * delivered to those users.
1206 * Mail notifications to local profiles will be sent later.
1208 * @return array of integer profile IDs
1211 function saveReplies()
1213 // Don't save reply data for repeats
1215 if (!empty($this->repeat_of)) {
1219 $sender = Profile::staticGet($this->profile_id);
1223 // If it's a reply, save for the replied-to author
1225 if (!empty($this->reply_to)) {
1226 $original = $this->getOriginal();
1227 if (!empty($original)) { // that'd be weird
1228 $author = $original->getProfile();
1229 if (!empty($author)) {
1230 $this->saveReply($author->id);
1231 $replied[$author->id] = 1;
1232 self::blow('reply:stream:%d', $author->id);
1237 // @todo ideally this parser information would only
1238 // be calculated once.
1240 $mentions = common_find_mentions($this->content, $this);
1242 // store replied only for first @ (what user/notice what the reply directed,
1243 // we assume first @ is it)
1245 foreach ($mentions as $mention) {
1247 foreach ($mention['mentioned'] as $mentioned) {
1249 // skip if they're already covered
1251 if (!empty($replied[$mentioned->id])) {
1255 // Don't save replies from blocked profile to local user
1257 $mentioned_user = User::staticGet('id', $mentioned->id);
1258 if (!empty($mentioned_user) && $mentioned_user->hasBlocked($sender)) {
1262 $this->saveReply($mentioned->id);
1263 $replied[$mentioned->id] = 1;
1264 self::blow('reply:stream:%d', $mentioned->id);
1268 $recipientIds = array_keys($replied);
1270 return $recipientIds;
1273 function saveReply($profileId)
1275 $reply = new Reply();
1277 $reply->notice_id = $this->id;
1278 $reply->profile_id = $profileId;
1279 $reply->modified = $this->created;
1287 * Pull the complete list of @-reply targets for this notice.
1289 * @return array of integer profile ids
1291 function getReplies()
1293 $keypart = sprintf('notice:reply_ids:%d', $this->id);
1295 $idstr = self::cacheGet($keypart);
1297 if ($idstr !== false) {
1298 $ids = explode(',', $idstr);
1302 $reply = new Reply();
1303 $reply->selectAdd();
1304 $reply->selectAdd('profile_id');
1305 $reply->notice_id = $this->id;
1307 if ($reply->find()) {
1308 while($reply->fetch()) {
1309 $ids[] = $reply->profile_id;
1312 self::cacheSet($keypart, implode(',', $ids));
1319 * Pull the complete list of @-reply targets for this notice.
1321 * @return array of Profiles
1323 function getReplyProfiles()
1325 $ids = $this->getReplies();
1326 $profiles = array();
1328 foreach ($ids as $id) {
1329 $profile = Profile::staticGet('id', $id);
1330 if (!empty($profile)) {
1331 $profiles[] = $profile;
1339 * Send e-mail notifications to local @-reply targets.
1341 * Replies must already have been saved; this is expected to be run
1342 * from the distrib queue handler.
1344 function sendReplyNotifications()
1346 // Don't send reply notifications for repeats
1348 if (!empty($this->repeat_of)) {
1352 $recipientIds = $this->getReplies();
1354 foreach ($recipientIds as $recipientId) {
1355 $user = User::staticGet('id', $recipientId);
1356 if (!empty($user)) {
1357 mail_notify_attn($user, $this);
1363 * Pull list of groups this notice needs to be delivered to,
1364 * as previously recorded by saveGroups() or saveKnownGroups().
1366 * @return array of Group objects
1368 function getGroups()
1370 // Don't save groups for repeats
1372 if (!empty($this->repeat_of)) {
1378 $keypart = sprintf('notice:groups:%d', $this->id);
1380 $idstr = self::cacheGet($keypart);
1382 if ($idstr !== false) {
1383 $ids = explode(',', $idstr);
1385 $gi = new Group_inbox();
1388 $gi->selectAdd('group_id');
1390 $gi->notice_id = $this->id;
1393 while ($gi->fetch()) {
1394 $ids[] = $gi->group_id;
1398 self::cacheSet($keypart, implode(',', $ids));
1403 foreach ($ids as $id) {
1404 $group = User_group::staticGet('id', $id);
1414 * Convert a notice into an activity for export.
1416 * @param User $cur Current user
1418 * @return Activity activity object representing this Notice.
1421 function asActivity($cur)
1423 $act = self::cacheGet(Cache::codeKey('notice:as-activity:'.$this->id));
1428 $act = new Activity();
1430 if (Event::handle('StartNoticeAsActivity', array($this, &$act))) {
1432 $profile = $this->getProfile();
1434 $act->actor = ActivityObject::fromProfile($profile);
1435 $act->actor->extra[] = $profile->profileInfo($cur);
1436 $act->verb = ActivityVerb::POST;
1437 $act->objects[] = ActivityObject::fromNotice($this);
1439 // XXX: should this be handled by default processing for object entry?
1441 $act->time = strtotime($this->created);
1442 $act->link = $this->bestUrl();
1444 $act->content = common_xml_safe_str($this->rendered);
1445 $act->id = $this->uri;
1446 $act->title = common_xml_safe_str($this->content);
1450 $tags = $this->getTags();
1452 foreach ($tags as $tag) {
1453 $cat = new AtomCategory();
1456 $act->categories[] = $cat;
1460 // XXX: use Atom Media and/or File activity objects instead
1462 $attachments = $this->attachments();
1464 foreach ($attachments as $attachment) {
1465 $enclosure = $attachment->getEnclosure();
1467 $act->enclosures[] = $enclosure;
1471 $ctx = new ActivityContext();
1473 if (!empty($this->reply_to)) {
1474 $reply = Notice::staticGet('id', $this->reply_to);
1475 if (!empty($reply)) {
1476 $ctx->replyToID = $reply->uri;
1477 $ctx->replyToUrl = $reply->bestUrl();
1481 $ctx->location = $this->getLocation();
1485 if (!empty($this->conversation)) {
1486 $conv = Conversation::staticGet('id', $this->conversation);
1487 if (!empty($conv)) {
1488 $ctx->conversation = $conv->uri;
1492 $reply_ids = $this->getReplies();
1494 foreach ($reply_ids as $id) {
1495 $rprofile = Profile::staticGet('id', $id);
1496 if (!empty($rprofile)) {
1497 $ctx->attention[] = $rprofile->getUri();
1501 $groups = $this->getGroups();
1503 foreach ($groups as $group) {
1504 $ctx->attention[] = $group->getUri();
1507 // XXX: deprecated; use ActivityVerb::SHARE instead
1511 if (!empty($this->repeat_of)) {
1512 $repeat = Notice::staticGet('id', $this->repeat_of);
1513 $ctx->forwardID = $repeat->uri;
1514 $ctx->forwardUrl = $repeat->bestUrl();
1517 $act->context = $ctx;
1521 $atom_feed = $profile->getAtomFeed();
1523 if (!empty($atom_feed)) {
1525 $act->source = new ActivitySource();
1527 // XXX: we should store the actual feed ID
1529 $act->source->id = $atom_feed;
1531 // XXX: we should store the actual feed title
1533 $act->source->title = $profile->getBestName();
1535 $act->source->links['alternate'] = $profile->profileurl;
1536 $act->source->links['self'] = $atom_feed;
1538 $act->source->icon = $profile->avatarUrl(AVATAR_PROFILE_SIZE);
1540 $notice = $profile->getCurrentNotice();
1542 if (!empty($notice)) {
1543 $act->source->updated = self::utcDate($notice->created);
1546 $user = User::staticGet('id', $profile->id);
1548 if (!empty($user)) {
1549 $act->source->links['license'] = common_config('license', 'url');
1553 if ($this->isLocal()) {
1554 $act->selfLink = common_local_url('ApiStatusesShow', array('id' => $this->id,
1555 'format' => 'atom'));
1556 $act->editLink = $act->selfLink;
1559 Event::handle('EndNoticeAsActivity', array($this, &$act));
1562 self::cacheSet(Cache::codeKey('notice:as-activity:'.$this->id), $act);
1567 // This has gotten way too long. Needs to be sliced up into functional bits
1568 // or ideally exported to a utility class.
1570 function asAtomEntry($namespace=false,
1575 $act = $this->asActivity($cur);
1576 $act->extra[] = $this->noticeInfo($cur);
1577 return $act->asString($namespace, $author, $source);
1581 * Extra notice info for atom entries
1583 * Clients use some extra notice info in the atom stream.
1584 * This gives it to them.
1586 * @param User $cur Current user
1588 * @return array representation of <statusnet:notice_info> element
1591 function noticeInfo($cur)
1593 // local notice ID (useful to clients for ordering)
1595 $noticeInfoAttr = array('local_id' => $this->id);
1599 $ns = $this->getSource();
1602 $noticeInfoAttr['source'] = $ns->code;
1603 if (!empty($ns->url)) {
1604 $noticeInfoAttr['source_link'] = $ns->url;
1605 if (!empty($ns->name)) {
1606 $noticeInfoAttr['source'] = '<a href="'
1607 . htmlspecialchars($ns->url)
1608 . '" rel="nofollow">'
1609 . htmlspecialchars($ns->name)
1615 // favorite and repeated
1618 $noticeInfoAttr['favorite'] = ($cur->hasFave($this)) ? "true" : "false";
1619 $cp = $cur->getProfile();
1620 $noticeInfoAttr['repeated'] = ($cp->hasRepeated($this->id)) ? "true" : "false";
1623 if (!empty($this->repeat_of)) {
1624 $noticeInfoAttr['repeat_of'] = $this->repeat_of;
1627 return array('statusnet:notice_info', $noticeInfoAttr, null);
1631 * Returns an XML string fragment with a reference to a notice as an
1632 * Activity Streams noun object with the given element type.
1634 * Assumes that 'activity' namespace has been previously defined.
1636 * @param string $element one of 'subject', 'object', 'target'
1640 function asActivityNoun($element)
1642 $noun = ActivityObject::fromNotice($this);
1643 return $noun->asString('activity:' . $element);
1648 if (!empty($this->url)) {
1650 } else if (!empty($this->uri) && preg_match('/^https?:/', $this->uri)) {
1653 return common_local_url('shownotice',
1654 array('notice' => $this->id));
1660 * Determine which notice, if any, a new notice is in reply to.
1662 * For conversation tracking, we try to see where this notice fits
1663 * in the tree. Rough algorithm is:
1665 * if (reply_to is set and valid) {
1667 * } else if ((source not API or Web) and (content starts with "T NAME" or "@name ")) {
1668 * return ID of last notice by initial @name in content;
1671 * Note that all @nickname instances will still be used to save "reply" records,
1672 * so the notice shows up in the mentioned users' "replies" tab.
1674 * @param integer $reply_to ID passed in by Web or API
1675 * @param integer $profile_id ID of author
1676 * @param string $source Source tag, like 'web' or 'gwibber'
1677 * @param string $content Final notice content
1679 * @return integer ID of replied-to notice, or null for not a reply.
1682 static function getReplyTo($reply_to, $profile_id, $source, $content)
1684 static $lb = array('xmpp', 'mail', 'sms', 'omb');
1686 // If $reply_to is specified, we check that it exists, and then
1687 // return it if it does
1689 if (!empty($reply_to)) {
1690 $reply_notice = Notice::staticGet('id', $reply_to);
1691 if (!empty($reply_notice)) {
1692 return $reply_notice;
1696 // If it's not a "low bandwidth" source (one where you can't set
1697 // a reply_to argument), we return. This is mostly web and API
1700 if (!in_array($source, $lb)) {
1704 // Is there an initial @ or T?
1706 if (preg_match('/^T ([A-Z0-9]{1,64}) /', $content, $match) ||
1707 preg_match('/^@([a-z0-9]{1,64})\s+/', $content, $match)) {
1708 $nickname = common_canonical_nickname($match[1]);
1713 // Figure out who that is.
1715 $sender = Profile::staticGet('id', $profile_id);
1716 if (empty($sender)) {
1720 $recipient = common_relative_profile($sender, $nickname, common_sql_now());
1722 if (empty($recipient)) {
1726 // Get their last notice
1728 $last = $recipient->getCurrentNotice();
1730 if (!empty($last)) {
1737 static function maxContent()
1739 $contentlimit = common_config('notice', 'contentlimit');
1740 // null => use global limit (distinct from 0!)
1741 if (is_null($contentlimit)) {
1742 $contentlimit = common_config('site', 'textlimit');
1744 return $contentlimit;
1747 static function contentTooLong($content)
1749 $contentlimit = self::maxContent();
1750 return ($contentlimit > 0 && !empty($content) && (mb_strlen($content) > $contentlimit));
1753 function getLocation()
1757 if (!empty($this->location_id) && !empty($this->location_ns)) {
1758 $location = Location::fromId($this->location_id, $this->location_ns);
1761 if (is_null($location)) { // no ID, or Location::fromId() failed
1762 if (!empty($this->lat) && !empty($this->lon)) {
1763 $location = Location::fromLatLon($this->lat, $this->lon);
1771 * Convenience function for posting a repeat of an existing message.
1773 * @param int $repeater_id: profile ID of user doing the repeat
1774 * @param string $source: posting source key, eg 'web', 'api', etc
1777 * @throws Exception on failure or permission problems
1779 function repeat($repeater_id, $source)
1781 $author = Profile::staticGet('id', $this->profile_id);
1783 // TRANS: Message used to repeat a notice. RT is the abbreviation of 'retweet'.
1784 // TRANS: %1$s is the repeated user's name, %2$s is the repeated notice.
1785 $content = sprintf(_('RT @%1$s %2$s'),
1789 $maxlen = common_config('site', 'textlimit');
1790 if ($maxlen > 0 && mb_strlen($content) > $maxlen) {
1791 // Web interface and current Twitter API clients will
1792 // pull the original notice's text, but some older
1793 // clients and RSS/Atom feeds will see this trimmed text.
1795 // Unfortunately this is likely to lose tags or URLs
1796 // at the end of long notices.
1797 $content = mb_substr($content, 0, $maxlen - 4) . ' ...';
1800 // Scope is same as this one's
1802 return self::saveNew($repeater_id,
1805 array('repeat_of' => $this->id,
1806 'scope' => $this->scope));
1809 // These are supposed to be in chron order!
1811 function repeatStream($limit=100)
1813 $cache = Cache::instance();
1815 if (empty($cache)) {
1816 $ids = $this->_repeatStreamDirect($limit);
1818 $idstr = $cache->get(Cache::key('notice:repeats:'.$this->id));
1819 if ($idstr !== false) {
1820 $ids = explode(',', $idstr);
1822 $ids = $this->_repeatStreamDirect(100);
1823 $cache->set(Cache::key('notice:repeats:'.$this->id), implode(',', $ids));
1826 // We do a max of 100, so slice down to limit
1827 $ids = array_slice($ids, 0, $limit);
1831 return NoticeStream::getStreamByIds($ids);
1834 function _repeatStreamDirect($limit)
1836 $notice = new Notice();
1838 $notice->selectAdd(); // clears it
1839 $notice->selectAdd('id');
1841 $notice->repeat_of = $this->id;
1843 $notice->orderBy('created, id'); // NB: asc!
1845 if (!is_null($limit)) {
1846 $notice->limit(0, $limit);
1851 if ($notice->find()) {
1852 while ($notice->fetch()) {
1853 $ids[] = $notice->id;
1863 function locationOptions($lat, $lon, $location_id, $location_ns, $profile = null)
1867 if (!empty($location_id) && !empty($location_ns)) {
1868 $options['location_id'] = $location_id;
1869 $options['location_ns'] = $location_ns;
1871 $location = Location::fromId($location_id, $location_ns);
1873 if (!empty($location)) {
1874 $options['lat'] = $location->lat;
1875 $options['lon'] = $location->lon;
1878 } else if (!empty($lat) && !empty($lon)) {
1879 $options['lat'] = $lat;
1880 $options['lon'] = $lon;
1882 $location = Location::fromLatLon($lat, $lon);
1884 if (!empty($location)) {
1885 $options['location_id'] = $location->location_id;
1886 $options['location_ns'] = $location->location_ns;
1888 } else if (!empty($profile)) {
1889 if (isset($profile->lat) && isset($profile->lon)) {
1890 $options['lat'] = $profile->lat;
1891 $options['lon'] = $profile->lon;
1894 if (isset($profile->location_id) && isset($profile->location_ns)) {
1895 $options['location_id'] = $profile->location_id;
1896 $options['location_ns'] = $profile->location_ns;
1903 function clearReplies()
1905 $replyNotice = new Notice();
1906 $replyNotice->reply_to = $this->id;
1908 //Null any notices that are replies to this notice
1910 if ($replyNotice->find()) {
1911 while ($replyNotice->fetch()) {
1912 $orig = clone($replyNotice);
1913 $replyNotice->reply_to = null;
1914 $replyNotice->update($orig);
1920 $reply = new Reply();
1921 $reply->notice_id = $this->id;
1923 if ($reply->find()) {
1924 while($reply->fetch()) {
1925 self::blow('reply:stream:%d', $reply->profile_id);
1933 function clearFiles()
1935 $f2p = new File_to_post();
1937 $f2p->post_id = $this->id;
1940 while ($f2p->fetch()) {
1944 // FIXME: decide whether to delete File objects
1945 // ...and related (actual) files
1948 function clearRepeats()
1950 $repeatNotice = new Notice();
1951 $repeatNotice->repeat_of = $this->id;
1953 //Null any notices that are repeats of this notice
1955 if ($repeatNotice->find()) {
1956 while ($repeatNotice->fetch()) {
1957 $orig = clone($repeatNotice);
1958 $repeatNotice->repeat_of = null;
1959 $repeatNotice->update($orig);
1964 function clearFaves()
1967 $fave->notice_id = $this->id;
1969 if ($fave->find()) {
1970 while ($fave->fetch()) {
1971 self::blow('fave:ids_by_user_own:%d', $fave->user_id);
1972 self::blow('fave:ids_by_user_own:%d;last', $fave->user_id);
1973 self::blow('fave:ids_by_user:%d', $fave->user_id);
1974 self::blow('fave:ids_by_user:%d;last', $fave->user_id);
1982 function clearTags()
1984 $tag = new Notice_tag();
1985 $tag->notice_id = $this->id;
1988 while ($tag->fetch()) {
1989 self::blow('profile:notice_ids_tagged:%d:%s', $this->profile_id, Cache::keyize($tag->tag));
1990 self::blow('profile:notice_ids_tagged:%d:%s;last', $this->profile_id, Cache::keyize($tag->tag));
1991 self::blow('notice_tag:notice_ids:%s', Cache::keyize($tag->tag));
1992 self::blow('notice_tag:notice_ids:%s;last', Cache::keyize($tag->tag));
2000 function clearGroupInboxes()
2002 $gi = new Group_inbox();
2004 $gi->notice_id = $this->id;
2007 while ($gi->fetch()) {
2008 self::blow('user_group:notice_ids:%d', $gi->group_id);
2016 function distribute()
2018 // We always insert for the author so they don't
2020 Event::handle('StartNoticeDistribute', array($this));
2022 $user = User::staticGet('id', $this->profile_id);
2023 if (!empty($user)) {
2024 Inbox::insertNotice($user->id, $this->id);
2027 if (common_config('queue', 'inboxes')) {
2028 // If there's a failure, we want to _force_
2029 // distribution at this point.
2031 $qm = QueueManager::get();
2032 $qm->enqueue($this, 'distrib');
2033 } catch (Exception $e) {
2034 // If the exception isn't transient, this
2035 // may throw more exceptions as DQH does
2036 // its own enqueueing. So, we ignore them!
2038 $handler = new DistribQueueHandler();
2039 $handler->handle($this);
2040 } catch (Exception $e) {
2041 common_log(LOG_ERR, "emergency redistribution resulted in " . $e->getMessage());
2043 // Re-throw so somebody smarter can handle it.
2047 $handler = new DistribQueueHandler();
2048 $handler->handle($this);
2054 $result = parent::insert();
2057 // Profile::hasRepeated() abuses pkeyGet(), so we
2058 // have to clear manually
2059 if (!empty($this->repeat_of)) {
2060 $c = self::memcache();
2062 $ck = self::multicacheKey('Notice',
2063 array('profile_id' => $this->profile_id,
2064 'repeat_of' => $this->repeat_of));
2074 * Get the source of the notice
2076 * @return Notice_source $ns A notice source object. 'code' is the only attribute
2077 * guaranteed to be populated.
2079 function getSource()
2081 $ns = new Notice_source();
2082 if (!empty($this->source)) {
2083 switch ($this->source) {
2090 $ns->code = $this->source;
2093 $ns = Notice_source::staticGet($this->source);
2095 $ns = new Notice_source();
2096 $ns->code = $this->source;
2097 $app = Oauth_application::staticGet('name', $this->source);
2099 $ns->name = $app->name;
2100 $ns->url = $app->source_url;
2110 * Determine whether the notice was locally created
2112 * @return boolean locality
2115 public function isLocal()
2117 return ($this->is_local == Notice::LOCAL_PUBLIC ||
2118 $this->is_local == Notice::LOCAL_NONPUBLIC);
2122 * Get the list of hash tags saved with this notice.
2124 * @return array of strings
2126 public function getTags()
2130 $keypart = sprintf('notice:tags:%d', $this->id);
2132 $tagstr = self::cacheGet($keypart);
2134 if ($tagstr !== false) {
2135 $tags = explode(',', $tagstr);
2137 $tag = new Notice_tag();
2138 $tag->notice_id = $this->id;
2140 while ($tag->fetch()) {
2141 $tags[] = $tag->tag;
2144 self::cacheSet($keypart, implode(',', $tags));
2150 static private function utcDate($dt)
2152 $dateStr = date('d F Y H:i:s', strtotime($dt));
2153 $d = new DateTime($dateStr, new DateTimeZone('UTC'));
2154 return $d->format(DATE_W3C);
2158 * Look up the creation timestamp for a given notice ID, even
2159 * if it's been deleted.
2162 * @return mixed string recorded creation timestamp, or false if can't be found
2164 public static function getAsTimestamp($id)
2170 $notice = Notice::staticGet('id', $id);
2172 return $notice->created;
2175 $deleted = Deleted_notice::staticGet('id', $id);
2177 return $deleted->created;
2184 * Build an SQL 'where' fragment for timestamp-based sorting from a since_id
2185 * parameter, matching notices posted after the given one (exclusive).
2187 * If the referenced notice can't be found, will return false.
2190 * @param string $idField
2191 * @param string $createdField
2192 * @return mixed string or false if no match
2194 public static function whereSinceId($id, $idField='id', $createdField='created')
2196 $since = Notice::getAsTimestamp($id);
2198 return sprintf("($createdField = '%s' and $idField > %d) or ($createdField > '%s')", $since, $id, $since);
2204 * Build an SQL 'where' fragment for timestamp-based sorting from a since_id
2205 * parameter, matching notices posted after the given one (exclusive), and
2206 * if necessary add it to the data object's query.
2208 * @param DB_DataObject $obj
2210 * @param string $idField
2211 * @param string $createdField
2212 * @return mixed string or false if no match
2214 public static function addWhereSinceId(DB_DataObject $obj, $id, $idField='id', $createdField='created')
2216 $since = self::whereSinceId($id, $idField, $createdField);
2218 $obj->whereAdd($since);
2223 * Build an SQL 'where' fragment for timestamp-based sorting from a max_id
2224 * parameter, matching notices posted before the given one (inclusive).
2226 * If the referenced notice can't be found, will return false.
2229 * @param string $idField
2230 * @param string $createdField
2231 * @return mixed string or false if no match
2233 public static function whereMaxId($id, $idField='id', $createdField='created')
2235 $max = Notice::getAsTimestamp($id);
2237 return sprintf("($createdField < '%s') or ($createdField = '%s' and $idField <= %d)", $max, $max, $id);
2243 * Build an SQL 'where' fragment for timestamp-based sorting from a max_id
2244 * parameter, matching notices posted before the given one (inclusive), and
2245 * if necessary add it to the data object's query.
2247 * @param DB_DataObject $obj
2249 * @param string $idField
2250 * @param string $createdField
2251 * @return mixed string or false if no match
2253 public static function addWhereMaxId(DB_DataObject $obj, $id, $idField='id', $createdField='created')
2255 $max = self::whereMaxId($id, $idField, $createdField);
2257 $obj->whereAdd($max);
2263 if (common_config('public', 'localonly')) {
2264 return ($this->is_local == Notice::LOCAL_PUBLIC);
2266 return (($this->is_local != Notice::LOCAL_NONPUBLIC) &&
2267 ($this->is_local != Notice::GATEWAY));
2272 * Check that the given profile is allowed to read, respond to, or otherwise
2273 * act on this notice.
2275 * The $scope member is a bitmask of scopes, representing a logical AND of the
2276 * scope requirement. So, 0x03 (Notice::ADDRESSEE_SCOPE | Notice::SITE_SCOPE) means
2277 * "only visible to people who are mentioned in the notice AND are users on this site."
2278 * Users on the site who are not mentioned in the notice will not be able to see the
2281 * @param Profile $profile The profile to check; pass null to check for public/unauthenticated users.
2283 * @return boolean whether the profile is in the notice's scope
2285 function inScope($profile)
2287 if (is_null($profile)) {
2288 $keypart = sprintf('notice:in-scope-for:%d:null', $this->id);
2290 $keypart = sprintf('notice:in-scope-for:%d:%d', $this->id, $profile->id);
2293 $result = self::cacheGet($keypart);
2295 if ($result === false) {
2296 $bResult = $this->_inScope($profile);
2297 $result = ($bResult) ? 1 : 0;
2298 self::cacheSet($keypart, $result, 0, 300);
2301 return ($result == 1) ? true : false;
2304 protected function _inScope($profile)
2306 // If there's no scope, anyone (even anon) is in scope.
2308 if ($this->scope == 0) {
2312 // If there's scope, anon cannot be in scope
2314 if (empty($profile)) {
2318 // Author is always in scope
2320 if ($this->profile_id == $profile->id) {
2324 // Only for users on this site
2326 if ($this->scope & Notice::SITE_SCOPE) {
2327 $user = $profile->getUser();
2333 // Only for users mentioned in the notice
2335 if ($this->scope & Notice::ADDRESSEE_SCOPE) {
2337 // XXX: just query for the single reply
2339 $replies = $this->getReplies();
2341 if (!in_array($profile->id, $replies)) {
2346 // Only for members of the given group
2348 if ($this->scope & Notice::GROUP_SCOPE) {
2350 // XXX: just query for the single membership
2352 $groups = $this->getGroups();
2356 foreach ($groups as $group) {
2357 if ($profile->isMember($group)) {
2368 // Only for followers of the author
2370 if ($this->scope & Notice::FOLLOWER_SCOPE) {
2371 $author = $this->getProfile();
2372 if (!Subscription::exists($profile, $author)) {
2380 static function groupsFromText($text, $profile)
2384 /* extract all !group */
2385 $count = preg_match_all('/(?:^|\s)!(' . Nickname::DISPLAY_FMT . ')/',
2393 foreach (array_unique($match[1]) as $nickname) {
2394 $group = User_group::getForNickname($nickname, $profile);
2395 if (!empty($group) && $profile->isMember($group)) {
2396 $groups[] = $group->id;
2403 protected $_original = -1;
2405 function getOriginal()
2407 if (is_int($this->_original) && $this->_original == -1) {
2408 if (empty($this->reply_to)) {
2409 $this->_original = null;
2411 $this->_original = Notice::staticGet('id', $this->reply_to);
2414 return $this->_original;
2418 * Magic function called at serialize() time.
2420 * We use this to drop a couple process-specific references
2421 * from DB_DataObject which can cause trouble in future
2424 * @return array of variable names to include in serialization.
2429 $vars = parent::__sleep();
2430 $skip = array('_original', '_profile');
2431 return array_diff($vars, $skip);