3 * StatusNet - the distributed open-source microblogging tool
4 * Copyright (C) 2008, 2009, StatusNet, Inc.
6 * This program is free software: you can redistribute it and/or modify
7 * it under the terms of the GNU Affero General Public License as published by
8 * the Free Software Foundation, either version 3 of the License, or
9 * (at your option) any later version.
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU Affero General Public License for more details.
16 * You should have received a copy of the GNU Affero General Public License
17 * along with this program. If not, see <http://www.gnu.org/licenses/>.
21 * @author Brenda Wallace <shiny@cpan.org>
22 * @author Christopher Vollick <psycotica0@gmail.com>
23 * @author CiaranG <ciaran@ciarang.com>
24 * @author Craig Andrews <candrews@integralblue.com>
25 * @author Evan Prodromou <evan@controlezvous.ca>
26 * @author Gina Haeussge <osd@foosel.net>
27 * @author Jeffery To <jeffery.to@gmail.com>
28 * @author Mike Cochrane <mikec@mikenz.geek.nz>
29 * @author Robin Millette <millette@controlyourself.ca>
30 * @author Sarven Capadisli <csarven@controlyourself.ca>
31 * @author Tom Adams <tom@holizz.com>
32 * @copyright 2009 Free Software Foundation, Inc http://www.fsf.org
33 * @license GNU Affero General Public License http://www.gnu.org/licenses/
36 if (!defined('STATUSNET') && !defined('LACONICA')) {
41 * Table Definition for notice
43 require_once INSTALLDIR.'/classes/Memcached_DataObject.php';
45 /* We keep 200 notices, the max number of notices available per API request,
46 * in the memcached cache. */
48 define('NOTICE_CACHE_WINDOW', CachingNoticeStream::CACHE_WINDOW);
50 define('MAX_BOXCARS', 128);
52 class Notice extends Memcached_DataObject
55 /* the code below is auto generated do not remove the above tag */
57 public $__table = 'notice'; // table name
58 public $id; // int(4) primary_key not_null
59 public $profile_id; // int(4) multiple_key not_null
60 public $uri; // varchar(255) unique_key
61 public $content; // text
62 public $rendered; // text
63 public $url; // varchar(255)
64 public $created; // datetime multiple_key not_null default_0000-00-00%2000%3A00%3A00
65 public $modified; // timestamp not_null default_CURRENT_TIMESTAMP
66 public $reply_to; // int(4)
67 public $is_local; // int(4)
68 public $source; // varchar(32)
69 public $conversation; // int(4)
70 public $lat; // decimal(10,7)
71 public $lon; // decimal(10,7)
72 public $location_id; // int(4)
73 public $location_ns; // int(4)
74 public $repeat_of; // int(4)
75 public $object_type; // varchar(255)
76 public $scope; // int(4)
79 function staticGet($k,$v=NULL)
81 return Memcached_DataObject::staticGet('Notice',$k,$v);
84 /* the code above is auto generated do not remove the tag below */
88 const LOCAL_PUBLIC = 1;
90 const LOCAL_NONPUBLIC = -1;
93 const PUBLIC_SCOPE = 0; // Useful fake constant
95 const ADDRESSEE_SCOPE = 2;
96 const GROUP_SCOPE = 4;
97 const FOLLOWER_SCOPE = 8;
101 $profile = Profile::staticGet('id', $this->profile_id);
103 if (empty($profile)) {
104 // TRANS: Server exception thrown when a user profile for a notice cannot be found.
105 // TRANS: %1$d is a profile ID (number), %2$d is a notice ID (number).
106 throw new ServerException(sprintf(_('No such profile (%1$d) for notice (%2$d).'), $this->profile_id, $this->id));
114 // For auditing purposes, save a record that the notice
117 // @fixme we have some cases where things get re-run and so the
119 $deleted = Deleted_notice::staticGet('id', $this->id);
122 $deleted = Deleted_notice::staticGet('uri', $this->uri);
126 $deleted = new Deleted_notice();
128 $deleted->id = $this->id;
129 $deleted->profile_id = $this->profile_id;
130 $deleted->uri = $this->uri;
131 $deleted->created = $this->created;
132 $deleted->deleted = common_sql_now();
137 if (Event::handle('NoticeDeleteRelated', array($this))) {
139 // Clear related records
141 $this->clearReplies();
142 $this->clearRepeats();
145 $this->clearGroupInboxes();
148 // NOTE: we don't clear inboxes
149 // NOTE: we don't clear queue items
152 $result = parent::delete();
154 $this->blowOnDelete();
159 * Extract #hashtags from this notice's content and save them to the database.
163 /* extract all #hastags */
164 $count = preg_match_all('/(?:^|\s)#([\pL\pN_\-\.]{1,64})/u', strtolower($this->content), $match);
169 /* Add them to the database */
170 return $this->saveKnownTags($match[1]);
174 * Record the given set of hash tags in the db for this notice.
175 * Given tag strings will be normalized and checked for dupes.
177 function saveKnownTags($hashtags)
179 //turn each into their canonical tag
180 //this is needed to remove dupes before saving e.g. #hash.tag = #hashtag
181 for($i=0; $i<count($hashtags); $i++) {
182 /* elide characters we don't want in the tag */
183 $hashtags[$i] = common_canonical_tag($hashtags[$i]);
186 foreach(array_unique($hashtags) as $hashtag) {
187 $this->saveTag($hashtag);
188 self::blow('profile:notice_ids_tagged:%d:%s', $this->profile_id, $hashtag);
194 * Record a single hash tag as associated with this notice.
195 * Tag format and uniqueness must be validated by caller.
197 function saveTag($hashtag)
199 $tag = new Notice_tag();
200 $tag->notice_id = $this->id;
201 $tag->tag = $hashtag;
202 $tag->created = $this->created;
203 $id = $tag->insert();
206 // TRANS: Server exception. %s are the error details.
207 throw new ServerException(sprintf(_('Database error inserting hashtag: %s'),
208 $last_error->message));
212 // if it's saved, blow its cache
213 $tag->blowCache(false);
217 * Save a new notice and push it out to subscribers' inboxes.
218 * Poster's permissions are checked before sending.
220 * @param int $profile_id Profile ID of the poster
221 * @param string $content source message text; links may be shortened
222 * per current user's preference
223 * @param string $source source key ('web', 'api', etc)
224 * @param array $options Associative array of optional properties:
225 * string 'created' timestamp of notice; defaults to now
226 * int 'is_local' source/gateway ID, one of:
227 * Notice::LOCAL_PUBLIC - Local, ok to appear in public timeline
228 * Notice::REMOTE_OMB - Sent from a remote OMB service;
229 * hide from public timeline but show in
230 * local "and friends" timelines
231 * Notice::LOCAL_NONPUBLIC - Local, but hide from public timeline
232 * Notice::GATEWAY - From another non-OMB service;
233 * will not appear in public views
234 * float 'lat' decimal latitude for geolocation
235 * float 'lon' decimal longitude for geolocation
236 * int 'location_id' geoname identifier
237 * int 'location_ns' geoname namespace to interpret location_id
238 * int 'reply_to'; notice ID this is a reply to
239 * int 'repeat_of'; notice ID this is a repeat of
240 * string 'uri' unique ID for notice; defaults to local notice URL
241 * string 'url' permalink to notice; defaults to local notice URL
242 * string 'rendered' rendered HTML version of content
243 * array 'replies' list of profile URIs for reply delivery in
244 * place of extracting @-replies from content.
245 * array 'groups' list of group IDs to deliver to, in place of
246 * extracting ! tags from content
247 * array 'tags' list of hashtag strings to save with the notice
248 * in place of extracting # tags from content
249 * array 'urls' list of attached/referred URLs to save with the
250 * notice in place of extracting links from content
251 * boolean 'distribute' whether to distribute the notice, default true
252 * string 'object_type' URL of the associated object type (default ActivityObject::NOTE)
253 * int 'scope' Scope bitmask; default to SITE_SCOPE on private sites, 0 otherwise
255 * @fixme tag override
258 * @throws ClientException
260 static function saveNew($profile_id, $content, $source, $options=null) {
261 $defaults = array('uri' => null,
266 'distribute' => true);
268 if (!empty($options)) {
269 $options = $options + $defaults;
275 if (!isset($is_local)) {
276 $is_local = Notice::LOCAL_PUBLIC;
279 $profile = Profile::staticGet('id', $profile_id);
280 $user = User::staticGet('id', $profile_id);
282 // Use the local user's shortening preferences, if applicable.
283 $final = $user->shortenLinks($content);
285 $final = common_shorten_links($content);
288 if (Notice::contentTooLong($final)) {
289 // TRANS: Client exception thrown if a notice contains too many characters.
290 throw new ClientException(_('Problem saving notice. Too long.'));
293 if (empty($profile)) {
294 // TRANS: Client exception thrown when trying to save a notice for an unknown user.
295 throw new ClientException(_('Problem saving notice. Unknown user.'));
298 if (common_config('throttle', 'enabled') && !Notice::checkEditThrottle($profile_id)) {
299 common_log(LOG_WARNING, 'Excessive posting by profile #' . $profile_id . '; throttled.');
300 // TRANS: Client exception thrown when a user tries to post too many notices in a given time frame.
301 throw new ClientException(_('Too many notices too fast; take a breather '.
302 'and post again in a few minutes.'));
305 if (common_config('site', 'dupelimit') > 0 && !Notice::checkDupes($profile_id, $final)) {
306 common_log(LOG_WARNING, 'Dupe posting by profile #' . $profile_id . '; throttled.');
307 // TRANS: Client exception thrown when a user tries to post too many duplicate notices in a given time frame.
308 throw new ClientException(_('Too many duplicate messages too quickly;'.
309 ' take a breather and post again in a few minutes.'));
312 if (!$profile->hasRight(Right::NEWNOTICE)) {
313 common_log(LOG_WARNING, "Attempted post from user disallowed to post: " . $profile->nickname);
315 // TRANS: Client exception thrown when a user tries to post while being banned.
316 throw new ClientException(_('You are banned from posting notices on this site.'), 403);
319 $notice = new Notice();
320 $notice->profile_id = $profile_id;
322 $autosource = common_config('public', 'autosource');
324 // Sandboxed are non-false, but not 1, either
326 if (!$profile->hasRight(Right::PUBLICNOTICE) ||
327 ($source && $autosource && in_array($source, $autosource))) {
328 $notice->is_local = Notice::LOCAL_NONPUBLIC;
330 $notice->is_local = $is_local;
333 if (!empty($created)) {
334 $notice->created = $created;
336 $notice->created = common_sql_now();
339 $notice->content = $final;
341 $notice->source = $source;
345 // Handle repeat case
347 if (isset($repeat_of)) {
349 // Check for a private one
351 $repeat = Notice::staticGet('id', $repeat_of);
353 if (empty($repeat)) {
354 throw new ClientException(_('Cannot repeat; original notice is missing or deleted.'));
357 if ($profile->id == $repeat->profile_id) {
358 // TRANS: Client error displayed when trying to repeat an own notice.
359 throw new ClientException(_('You cannot repeat your own notice.'));
362 if ($repeat->scope != Notice::SITE_SCOPE &&
363 $repeat->scope != Notice::PUBLIC_SCOPE) {
364 // TRANS: Client error displayed when trying to repeat a non-public notice.
365 throw new ClientException(_('Cannot repeat a private notice.'), 403);
368 if (!$repeat->inScope($profile)) {
369 // The generic checks above should cover this, but let's be sure!
370 // TRANS: Client error displayed when trying to repeat a notice you cannot access.
371 throw new ClientException(_('Cannot repeat a notice you cannot read.'), 403);
374 if ($profile->hasRepeated($repeat->id)) {
375 // TRANS: Client error displayed when trying to repeat an already repeated notice.
376 throw new ClientException(_('You already repeated that notice.'));
379 $notice->repeat_of = $repeat_of;
381 $notice->reply_to = self::getReplyTo($reply_to, $profile_id, $source, $final);
384 if (!empty($notice->reply_to)) {
385 $reply = Notice::staticGet('id', $notice->reply_to);
386 if (!$reply->inScope($profile)) {
387 throw new ClientException(sprintf(_("%s has no access to notice %d"),
388 $profile->nickname, $reply->id), 403);
390 $notice->conversation = $reply->conversation;
393 if (!empty($lat) && !empty($lon)) {
398 if (!empty($location_ns) && !empty($location_id)) {
399 $notice->location_id = $location_id;
400 $notice->location_ns = $location_ns;
403 if (!empty($rendered)) {
404 $notice->rendered = $rendered;
406 $notice->rendered = common_render_content($final, $notice);
409 if (empty($object_type)) {
410 $notice->object_type = (empty($notice->reply_to)) ? ActivityObject::NOTE : ActivityObject::COMMENT;
412 $notice->object_type = $object_type;
415 if (is_null($scope)) { // 0 is a valid value
416 $notice->scope = common_config('notice', 'defaultscope');
418 $notice->scope = $scope;
421 if (Event::handle('StartNoticeSave', array(&$notice))) {
423 // XXX: some of these functions write to the DB
425 $id = $notice->insert();
428 common_log_db_error($notice, 'INSERT', __FILE__);
429 // TRANS: Server exception thrown when a notice cannot be saved.
430 throw new ServerException(_('Problem saving notice.'));
433 // Update ID-dependent columns: URI, conversation
435 $orig = clone($notice);
440 $notice->uri = common_notice_uri($notice);
444 // If it's not part of a conversation, it's
445 // the beginning of a new conversation.
447 if (empty($notice->conversation)) {
448 $conv = Conversation::create();
449 $notice->conversation = $conv->id;
454 if (!$notice->update($orig)) {
455 common_log_db_error($notice, 'UPDATE', __FILE__);
456 // TRANS: Server exception thrown when a notice cannot be updated.
457 throw new ServerException(_('Problem saving notice.'));
463 // Clear the cache for subscribed users, so they'll update at next request
464 // XXX: someone clever could prepend instead of clearing the cache
466 $notice->blowOnInsert();
468 // Save per-notice metadata...
470 if (isset($replies)) {
471 $notice->saveKnownReplies($replies);
473 $notice->saveReplies();
477 $notice->saveKnownTags($tags);
482 // Note: groups may save tags, so must be run after tags are saved
483 // to avoid errors on duplicates.
484 if (isset($groups)) {
485 $notice->saveKnownGroups($groups);
487 $notice->saveGroups();
491 $notice->saveKnownUrls($urls);
497 // Prepare inbox delivery, may be queued to background.
498 $notice->distribute();
504 function blowOnInsert($conversation = false)
506 self::blow('profile:notice_ids:%d', $this->profile_id);
508 if ($this->isPublic()) {
509 self::blow('public');
512 // XXX: Before we were blowing the casche only if the notice id
513 // was not the root of the conversation. What to do now?
515 self::blow('notice:conversation_ids:%d', $this->conversation);
517 if (!empty($this->repeat_of)) {
518 self::blow('notice:repeats:%d', $this->repeat_of);
521 $original = Notice::staticGet('id', $this->repeat_of);
523 if (!empty($original)) {
524 $originalUser = User::staticGet('id', $original->profile_id);
525 if (!empty($originalUser)) {
526 self::blow('user:repeats_of_me:%d', $originalUser->id);
530 $profile = Profile::staticGet($this->profile_id);
531 if (!empty($profile)) {
532 $profile->blowNoticeCount();
537 * Clear cache entries related to this notice at delete time.
538 * Necessary to avoid breaking paging on public, profile timelines.
540 function blowOnDelete()
542 $this->blowOnInsert();
544 self::blow('profile:notice_ids:%d;last', $this->profile_id);
546 if ($this->isPublic()) {
547 self::blow('public;last');
550 self::blow('fave:by_notice', $this->id);
552 if ($this->conversation) {
553 // In case we're the first, will need to calc a new root.
554 self::blow('notice:conversation_root:%d', $this->conversation);
558 /** save all urls in the notice to the db
560 * follow redirects and save all available file information
561 * (mimetype, date, size, oembed, etc.)
565 function saveUrls() {
566 if (common_config('attachments', 'process_links')) {
567 common_replace_urls_callback($this->content, array($this, 'saveUrl'), $this->id);
572 * Save the given URLs as related links/attachments to the db
574 * follow redirects and save all available file information
575 * (mimetype, date, size, oembed, etc.)
579 function saveKnownUrls($urls)
581 if (common_config('attachments', 'process_links')) {
582 // @fixme validation?
583 foreach (array_unique($urls) as $url) {
584 File::processNew($url, $this->id);
592 function saveUrl($url, $notice_id) {
593 File::processNew($url, $notice_id);
596 static function checkDupes($profile_id, $content) {
597 $profile = Profile::staticGet($profile_id);
598 if (empty($profile)) {
601 $notice = $profile->getNotices(0, CachingNoticeStream::CACHE_WINDOW);
602 if (!empty($notice)) {
604 while ($notice->fetch()) {
605 if (time() - strtotime($notice->created) >= common_config('site', 'dupelimit')) {
607 } else if ($notice->content == $content) {
612 // If we get here, oldest item in cache window is not
613 // old enough for dupe limit; do direct check against DB
614 $notice = new Notice();
615 $notice->profile_id = $profile_id;
616 $notice->content = $content;
617 $threshold = common_sql_date(time() - common_config('site', 'dupelimit'));
618 $notice->whereAdd(sprintf("created > '%s'", $notice->escape($threshold)));
620 $cnt = $notice->count();
624 static function checkEditThrottle($profile_id) {
625 $profile = Profile::staticGet($profile_id);
626 if (empty($profile)) {
629 // Get the Nth notice
630 $notice = $profile->getNotices(common_config('throttle', 'count') - 1, 1);
631 if ($notice && $notice->fetch()) {
632 // If the Nth notice was posted less than timespan seconds ago
633 if (time() - strtotime($notice->created) <= common_config('throttle', 'timespan')) {
638 // Either not N notices in the stream, OR the Nth was not posted within timespan seconds
642 function getUploadedAttachment() {
644 $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"';
645 $post->query($query);
647 if (empty($post->up) || empty($post->i)) {
650 $ret = array($post->up, $post->i);
656 function hasAttachments() {
658 $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);
659 $post->query($query);
661 $n_attachments = intval($post->n_attachments);
663 return $n_attachments;
666 function attachments() {
669 $f2p = new File_to_post;
670 $f2p->post_id = $this->id;
672 while ($f2p->fetch()) {
673 $f = File::staticGet($f2p->file_id);
683 function publicStream($offset=0, $limit=20, $since_id=0, $max_id=0)
685 $stream = new PublicNoticeStream();
686 return $stream->getNotices($offset, $limit, $since_id, $max_id);
690 function conversationStream($id, $offset=0, $limit=20, $since_id=0, $max_id=0)
692 $stream = new ConversationNoticeStream($id);
694 return $stream->getNotices($offset, $limit, $since_id, $max_id);
698 * Is this notice part of an active conversation?
700 * @return boolean true if other messages exist in the same
701 * conversation, false if this is the only one
703 function hasConversation()
705 if (!empty($this->conversation)) {
706 $conversation = Notice::conversationStream(
712 if ($conversation->N > 0) {
720 * Grab the earliest notice from this conversation.
722 * @return Notice or null
724 function conversationRoot()
726 if (!empty($this->conversation)) {
727 $c = self::memcache();
729 $key = Cache::key('notice:conversation_root:' . $this->conversation);
730 $notice = $c->get($key);
735 $notice = new Notice();
736 $notice->conversation = $this->conversation;
737 $notice->orderBy('CREATED');
742 $c->set($key, $notice);
749 * Pull up a full list of local recipients who will be getting
750 * this notice in their inbox. Results will be cached, so don't
751 * change the input data wily-nilly!
753 * @param array $groups optional list of Group objects;
754 * if left empty, will be loaded from group_inbox records
755 * @param array $recipient optional list of reply profile ids
756 * if left empty, will be loaded from reply records
757 * @return array associating recipient user IDs with an inbox source constant
759 function whoGets($groups=null, $recipients=null)
761 $c = self::memcache();
764 $ni = $c->get(Cache::key('notice:who_gets:'.$this->id));
770 if (is_null($groups)) {
771 $groups = $this->getGroups();
774 if (is_null($recipients)) {
775 $recipients = $this->getReplies();
778 $users = $this->getSubscribedUsers();
780 // FIXME: kind of ignoring 'transitional'...
781 // we'll probably stop supporting inboxless mode
786 // Give plugins a chance to add folks in at start...
787 if (Event::handle('StartNoticeWhoGets', array($this, &$ni))) {
789 foreach ($users as $id) {
790 $ni[$id] = NOTICE_INBOX_SOURCE_SUB;
793 foreach ($groups as $group) {
794 $users = $group->getUserMembers();
795 foreach ($users as $id) {
796 if (!array_key_exists($id, $ni)) {
797 $ni[$id] = NOTICE_INBOX_SOURCE_GROUP;
802 foreach ($recipients as $recipient) {
803 if (!array_key_exists($recipient, $ni)) {
804 $ni[$recipient] = NOTICE_INBOX_SOURCE_REPLY;
808 // Exclude any deleted, non-local, or blocking recipients.
809 $profile = $this->getProfile();
810 $originalProfile = null;
811 if ($this->repeat_of) {
812 // Check blocks against the original notice's poster as well.
813 $original = Notice::staticGet('id', $this->repeat_of);
815 $originalProfile = $original->getProfile();
818 foreach ($ni as $id => $source) {
819 $user = User::staticGet('id', $id);
820 if (empty($user) || $user->hasBlocked($profile) ||
821 ($originalProfile && $user->hasBlocked($originalProfile))) {
826 // Give plugins a chance to filter out...
827 Event::handle('EndNoticeWhoGets', array($this, &$ni));
831 // XXX: pack this data better
832 $c->set(Cache::key('notice:who_gets:'.$this->id), $ni);
839 * Adds this notice to the inboxes of each local user who should receive
840 * it, based on author subscriptions, group memberships, and @-replies.
842 * Warning: running a second time currently will make items appear
843 * multiple times in users' inboxes.
845 * @fixme make more robust against errors
846 * @fixme break up massive deliveries to smaller background tasks
848 * @param array $groups optional list of Group objects;
849 * if left empty, will be loaded from group_inbox records
850 * @param array $recipient optional list of reply profile ids
851 * if left empty, will be loaded from reply records
853 function addToInboxes($groups=null, $recipients=null)
855 $ni = $this->whoGets($groups, $recipients);
857 $ids = array_keys($ni);
859 // We remove the author (if they're a local user),
860 // since we'll have already done this in distribute()
862 $i = array_search($this->profile_id, $ids);
870 Inbox::bulkInsert($this->id, $ids);
875 function getSubscribedUsers()
879 if(common_config('db','quote_identifiers'))
880 $user_table = '"user"';
881 else $user_table = 'user';
885 'FROM '. $user_table .' JOIN subscription '.
886 'ON '. $user_table .'.id = subscription.subscriber ' .
887 'WHERE subscription.subscribed = %d ';
889 $user->query(sprintf($qry, $this->profile_id));
893 while ($user->fetch()) {
903 * Record this notice to the given group inboxes for delivery.
904 * Overrides the regular parsing of !group markup.
906 * @param string $group_ids
907 * @fixme might prefer URIs as identifiers, as for replies?
908 * best with generalizations on user_group to support
909 * remote groups better.
911 function saveKnownGroups($group_ids)
913 if (!is_array($group_ids)) {
914 // TRANS: Server exception thrown when no array is provided to the method saveKnownGroups().
915 throw new ServerException(_('Bad type provided to saveKnownGroups.'));
919 foreach (array_unique($group_ids) as $id) {
920 $group = User_group::staticGet('id', $id);
922 common_log(LOG_ERR, "Local delivery to group id $id, $group->nickname");
923 $result = $this->addToGroupInbox($group);
925 common_log_db_error($gi, 'INSERT', __FILE__);
928 // @fixme should we save the tags here or not?
929 $groups[] = clone($group);
931 common_log(LOG_ERR, "Local delivery to group id $id skipped, doesn't exist");
939 * Parse !group delivery and record targets into group_inbox.
940 * @return array of Group objects
942 function saveGroups()
944 // Don't save groups for repeats
946 if (!empty($this->repeat_of)) {
952 /* extract all !group */
953 $count = preg_match_all('/(?:^|\s)!(' . Nickname::DISPLAY_FMT . ')/',
954 strtolower($this->content),
960 $profile = $this->getProfile();
962 /* Add them to the database */
964 foreach (array_unique($match[1]) as $nickname) {
965 /* XXX: remote groups. */
966 $group = User_group::getForNickname($nickname, $profile);
972 // we automatically add a tag for every group name, too
974 $tag = Notice_tag::pkeyGet(array('tag' => common_canonical_tag($nickname),
975 'notice_id' => $this->id));
978 $this->saveTag($nickname);
981 if ($profile->isMember($group)) {
983 $result = $this->addToGroupInbox($group);
986 common_log_db_error($gi, 'INSERT', __FILE__);
989 $groups[] = clone($group);
996 function addToGroupInbox($group)
998 $gi = Group_inbox::pkeyGet(array('group_id' => $group->id,
999 'notice_id' => $this->id));
1003 $gi = new Group_inbox();
1005 $gi->group_id = $group->id;
1006 $gi->notice_id = $this->id;
1007 $gi->created = $this->created;
1009 $result = $gi->insert();
1012 common_log_db_error($gi, 'INSERT', __FILE__);
1013 // TRANS: Server exception thrown when an update for a group inbox fails.
1014 throw new ServerException(_('Problem saving group inbox.'));
1017 self::blow('user_group:notice_ids:%d', $gi->group_id);
1024 * Save reply records indicating that this notice needs to be
1025 * delivered to the local users with the given URIs.
1027 * Since this is expected to be used when saving foreign-sourced
1028 * messages, we won't deliver to any remote targets as that's the
1029 * source service's responsibility.
1031 * Mail notifications etc will be handled later.
1033 * @param array of unique identifier URIs for recipients
1035 function saveKnownReplies($uris)
1041 $sender = Profile::staticGet($this->profile_id);
1043 foreach (array_unique($uris) as $uri) {
1045 $profile = Profile::fromURI($uri);
1047 if (empty($profile)) {
1048 common_log(LOG_WARNING, "Unable to determine profile for URI '$uri'");
1052 if ($profile->hasBlocked($sender)) {
1053 common_log(LOG_INFO, "Not saving reply to profile {$profile->id} ($uri) from sender {$sender->id} because of a block.");
1057 $reply = new Reply();
1059 $reply->notice_id = $this->id;
1060 $reply->profile_id = $profile->id;
1061 $reply->modified = $this->created;
1063 common_log(LOG_INFO, __METHOD__ . ": saving reply: notice $this->id to profile $profile->id");
1065 $id = $reply->insert();
1072 * Pull @-replies from this message's content in StatusNet markup format
1073 * and save reply records indicating that this message needs to be
1074 * delivered to those users.
1076 * Mail notifications to local profiles will be sent later.
1078 * @return array of integer profile IDs
1081 function saveReplies()
1083 // Don't save reply data for repeats
1085 if (!empty($this->repeat_of)) {
1089 $sender = Profile::staticGet($this->profile_id);
1091 // @todo ideally this parser information would only
1092 // be calculated once.
1094 $mentions = common_find_mentions($this->content, $this);
1098 // store replied only for first @ (what user/notice what the reply directed,
1099 // we assume first @ is it)
1101 foreach ($mentions as $mention) {
1103 foreach ($mention['mentioned'] as $mentioned) {
1105 // skip if they're already covered
1107 if (!empty($replied[$mentioned->id])) {
1111 // Don't save replies from blocked profile to local user
1113 $mentioned_user = User::staticGet('id', $mentioned->id);
1114 if (!empty($mentioned_user) && $mentioned_user->hasBlocked($sender)) {
1118 $reply = new Reply();
1120 $reply->notice_id = $this->id;
1121 $reply->profile_id = $mentioned->id;
1122 $reply->modified = $this->created;
1124 $id = $reply->insert();
1127 common_log_db_error($reply, 'INSERT', __FILE__);
1128 // TRANS: Server exception thrown when a reply cannot be saved.
1129 // TRANS: %1$d is a notice ID, %2$d is the ID of the mentioned user.
1130 throw new ServerException(sprintf(_('Could not save reply for %1$d, %2$d.'), $this->id, $mentioned->id));
1132 $replied[$mentioned->id] = 1;
1133 self::blow('reply:stream:%d', $mentioned->id);
1138 $recipientIds = array_keys($replied);
1140 return $recipientIds;
1144 * Pull the complete list of @-reply targets for this notice.
1146 * @return array of integer profile ids
1148 function getReplies()
1154 $reply = new Reply();
1155 $reply->selectAdd();
1156 $reply->selectAdd('profile_id');
1157 $reply->notice_id = $this->id;
1159 if ($reply->find()) {
1160 while($reply->fetch()) {
1161 $ids[] = $reply->profile_id;
1171 * Send e-mail notifications to local @-reply targets.
1173 * Replies must already have been saved; this is expected to be run
1174 * from the distrib queue handler.
1176 function sendReplyNotifications()
1178 // Don't send reply notifications for repeats
1180 if (!empty($this->repeat_of)) {
1184 $recipientIds = $this->getReplies();
1186 foreach ($recipientIds as $recipientId) {
1187 $user = User::staticGet('id', $recipientId);
1188 if (!empty($user)) {
1189 mail_notify_attn($user, $this);
1195 * Pull list of groups this notice needs to be delivered to,
1196 * as previously recorded by saveGroups() or saveKnownGroups().
1198 * @return array of Group objects
1200 function getGroups()
1202 // Don't save groups for repeats
1204 if (!empty($this->repeat_of)) {
1212 $gi = new Group_inbox();
1215 $gi->selectAdd('group_id');
1217 $gi->notice_id = $this->id;
1220 while ($gi->fetch()) {
1221 $group = User_group::staticGet('id', $gi->group_id);
1234 * Convert a notice into an activity for export.
1236 * @param User $cur Current user
1238 * @return Activity activity object representing this Notice.
1241 function asActivity($cur)
1243 $act = self::cacheGet(Cache::codeKey('notice:as-activity:'.$this->id));
1248 $act = new Activity();
1250 if (Event::handle('StartNoticeAsActivity', array($this, &$act))) {
1252 $profile = $this->getProfile();
1254 $act->actor = ActivityObject::fromProfile($profile);
1255 $act->actor->extra[] = $profile->profileInfo($cur);
1256 $act->verb = ActivityVerb::POST;
1257 $act->objects[] = ActivityObject::fromNotice($this);
1259 // XXX: should this be handled by default processing for object entry?
1261 $act->time = strtotime($this->created);
1262 $act->link = $this->bestUrl();
1264 $act->content = common_xml_safe_str($this->rendered);
1265 $act->id = $this->uri;
1266 $act->title = common_xml_safe_str($this->content);
1270 $tags = $this->getTags();
1272 foreach ($tags as $tag) {
1273 $cat = new AtomCategory();
1276 $act->categories[] = $cat;
1280 // XXX: use Atom Media and/or File activity objects instead
1282 $attachments = $this->attachments();
1284 foreach ($attachments as $attachment) {
1285 $enclosure = $attachment->getEnclosure();
1287 $act->enclosures[] = $enclosure;
1291 $ctx = new ActivityContext();
1293 if (!empty($this->reply_to)) {
1294 $reply = Notice::staticGet('id', $this->reply_to);
1295 if (!empty($reply)) {
1296 $ctx->replyToID = $reply->uri;
1297 $ctx->replyToUrl = $reply->bestUrl();
1301 $ctx->location = $this->getLocation();
1305 if (!empty($this->conversation)) {
1306 $conv = Conversation::staticGet('id', $this->conversation);
1307 if (!empty($conv)) {
1308 $ctx->conversation = $conv->uri;
1312 $reply_ids = $this->getReplies();
1314 foreach ($reply_ids as $id) {
1315 $profile = Profile::staticGet('id', $id);
1316 if (!empty($profile)) {
1317 $ctx->attention[] = $profile->getUri();
1321 $groups = $this->getGroups();
1323 foreach ($groups as $group) {
1324 $ctx->attention[] = $group->getUri();
1327 // XXX: deprecated; use ActivityVerb::SHARE instead
1331 if (!empty($this->repeat_of)) {
1332 $repeat = Notice::staticGet('id', $this->repeat_of);
1333 $ctx->forwardID = $repeat->uri;
1334 $ctx->forwardUrl = $repeat->bestUrl();
1337 $act->context = $ctx;
1341 $atom_feed = $profile->getAtomFeed();
1343 if (!empty($atom_feed)) {
1345 $act->source = new ActivitySource();
1347 // XXX: we should store the actual feed ID
1349 $act->source->id = $atom_feed;
1351 // XXX: we should store the actual feed title
1353 $act->source->title = $profile->getBestName();
1355 $act->source->links['alternate'] = $profile->profileurl;
1356 $act->source->links['self'] = $atom_feed;
1358 $act->source->icon = $profile->avatarUrl(AVATAR_PROFILE_SIZE);
1360 $notice = $profile->getCurrentNotice();
1362 if (!empty($notice)) {
1363 $act->source->updated = self::utcDate($notice->created);
1366 $user = User::staticGet('id', $profile->id);
1368 if (!empty($user)) {
1369 $act->source->links['license'] = common_config('license', 'url');
1373 if ($this->isLocal()) {
1374 $act->selfLink = common_local_url('ApiStatusesShow', array('id' => $this->id,
1375 'format' => 'atom'));
1376 $act->editLink = $act->selfLink;
1379 Event::handle('EndNoticeAsActivity', array($this, &$act));
1382 self::cacheSet(Cache::codeKey('notice:as-activity:'.$this->id), $act);
1387 // This has gotten way too long. Needs to be sliced up into functional bits
1388 // or ideally exported to a utility class.
1390 function asAtomEntry($namespace=false,
1395 $act = $this->asActivity($cur);
1396 $act->extra[] = $this->noticeInfo($cur);
1397 return $act->asString($namespace, $author, $source);
1401 * Extra notice info for atom entries
1403 * Clients use some extra notice info in the atom stream.
1404 * This gives it to them.
1406 * @param User $cur Current user
1408 * @return array representation of <statusnet:notice_info> element
1411 function noticeInfo($cur)
1413 // local notice ID (useful to clients for ordering)
1415 $noticeInfoAttr = array('local_id' => $this->id);
1419 $ns = $this->getSource();
1422 $noticeInfoAttr['source'] = $ns->code;
1423 if (!empty($ns->url)) {
1424 $noticeInfoAttr['source_link'] = $ns->url;
1425 if (!empty($ns->name)) {
1426 $noticeInfoAttr['source'] = '<a href="'
1427 . htmlspecialchars($ns->url)
1428 . '" rel="nofollow">'
1429 . htmlspecialchars($ns->name)
1435 // favorite and repeated
1438 $noticeInfoAttr['favorite'] = ($cur->hasFave($this)) ? "true" : "false";
1439 $cp = $cur->getProfile();
1440 $noticeInfoAttr['repeated'] = ($cp->hasRepeated($this->id)) ? "true" : "false";
1443 if (!empty($this->repeat_of)) {
1444 $noticeInfoAttr['repeat_of'] = $this->repeat_of;
1447 return array('statusnet:notice_info', $noticeInfoAttr, null);
1451 * Returns an XML string fragment with a reference to a notice as an
1452 * Activity Streams noun object with the given element type.
1454 * Assumes that 'activity' namespace has been previously defined.
1456 * @param string $element one of 'subject', 'object', 'target'
1460 function asActivityNoun($element)
1462 $noun = ActivityObject::fromNotice($this);
1463 return $noun->asString('activity:' . $element);
1468 if (!empty($this->url)) {
1470 } else if (!empty($this->uri) && preg_match('/^https?:/', $this->uri)) {
1473 return common_local_url('shownotice',
1474 array('notice' => $this->id));
1480 * Determine which notice, if any, a new notice is in reply to.
1482 * For conversation tracking, we try to see where this notice fits
1483 * in the tree. Rough algorithm is:
1485 * if (reply_to is set and valid) {
1487 * } else if ((source not API or Web) and (content starts with "T NAME" or "@name ")) {
1488 * return ID of last notice by initial @name in content;
1491 * Note that all @nickname instances will still be used to save "reply" records,
1492 * so the notice shows up in the mentioned users' "replies" tab.
1494 * @param integer $reply_to ID passed in by Web or API
1495 * @param integer $profile_id ID of author
1496 * @param string $source Source tag, like 'web' or 'gwibber'
1497 * @param string $content Final notice content
1499 * @return integer ID of replied-to notice, or null for not a reply.
1502 static function getReplyTo($reply_to, $profile_id, $source, $content)
1504 static $lb = array('xmpp', 'mail', 'sms', 'omb');
1506 // If $reply_to is specified, we check that it exists, and then
1507 // return it if it does
1509 if (!empty($reply_to)) {
1510 $reply_notice = Notice::staticGet('id', $reply_to);
1511 if (!empty($reply_notice)) {
1516 // If it's not a "low bandwidth" source (one where you can't set
1517 // a reply_to argument), we return. This is mostly web and API
1520 if (!in_array($source, $lb)) {
1524 // Is there an initial @ or T?
1526 if (preg_match('/^T ([A-Z0-9]{1,64}) /', $content, $match) ||
1527 preg_match('/^@([a-z0-9]{1,64})\s+/', $content, $match)) {
1528 $nickname = common_canonical_nickname($match[1]);
1533 // Figure out who that is.
1535 $sender = Profile::staticGet('id', $profile_id);
1536 if (empty($sender)) {
1540 $recipient = common_relative_profile($sender, $nickname, common_sql_now());
1542 if (empty($recipient)) {
1546 // Get their last notice
1548 $last = $recipient->getCurrentNotice();
1550 if (!empty($last)) {
1555 static function maxContent()
1557 $contentlimit = common_config('notice', 'contentlimit');
1558 // null => use global limit (distinct from 0!)
1559 if (is_null($contentlimit)) {
1560 $contentlimit = common_config('site', 'textlimit');
1562 return $contentlimit;
1565 static function contentTooLong($content)
1567 $contentlimit = self::maxContent();
1568 return ($contentlimit > 0 && !empty($content) && (mb_strlen($content) > $contentlimit));
1571 function getLocation()
1575 if (!empty($this->location_id) && !empty($this->location_ns)) {
1576 $location = Location::fromId($this->location_id, $this->location_ns);
1579 if (is_null($location)) { // no ID, or Location::fromId() failed
1580 if (!empty($this->lat) && !empty($this->lon)) {
1581 $location = Location::fromLatLon($this->lat, $this->lon);
1589 * Convenience function for posting a repeat of an existing message.
1591 * @param int $repeater_id: profile ID of user doing the repeat
1592 * @param string $source: posting source key, eg 'web', 'api', etc
1595 * @throws Exception on failure or permission problems
1597 function repeat($repeater_id, $source)
1599 $author = Profile::staticGet('id', $this->profile_id);
1601 // TRANS: Message used to repeat a notice. RT is the abbreviation of 'retweet'.
1602 // TRANS: %1$s is the repeated user's name, %2$s is the repeated notice.
1603 $content = sprintf(_('RT @%1$s %2$s'),
1607 $maxlen = common_config('site', 'textlimit');
1608 if ($maxlen > 0 && mb_strlen($content) > $maxlen) {
1609 // Web interface and current Twitter API clients will
1610 // pull the original notice's text, but some older
1611 // clients and RSS/Atom feeds will see this trimmed text.
1613 // Unfortunately this is likely to lose tags or URLs
1614 // at the end of long notices.
1615 $content = mb_substr($content, 0, $maxlen - 4) . ' ...';
1618 // Scope is same as this one's
1620 return self::saveNew($repeater_id,
1623 array('repeat_of' => $this->id,
1624 'scope' => $this->scope));
1627 // These are supposed to be in chron order!
1629 function repeatStream($limit=100)
1631 $cache = Cache::instance();
1633 if (empty($cache)) {
1634 $ids = $this->_repeatStreamDirect($limit);
1636 $idstr = $cache->get(Cache::key('notice:repeats:'.$this->id));
1637 if ($idstr !== false) {
1638 $ids = explode(',', $idstr);
1640 $ids = $this->_repeatStreamDirect(100);
1641 $cache->set(Cache::key('notice:repeats:'.$this->id), implode(',', $ids));
1644 // We do a max of 100, so slice down to limit
1645 $ids = array_slice($ids, 0, $limit);
1649 return NoticeStream::getStreamByIds($ids);
1652 function _repeatStreamDirect($limit)
1654 $notice = new Notice();
1656 $notice->selectAdd(); // clears it
1657 $notice->selectAdd('id');
1659 $notice->repeat_of = $this->id;
1661 $notice->orderBy('created, id'); // NB: asc!
1663 if (!is_null($limit)) {
1664 $notice->limit(0, $limit);
1669 if ($notice->find()) {
1670 while ($notice->fetch()) {
1671 $ids[] = $notice->id;
1681 function locationOptions($lat, $lon, $location_id, $location_ns, $profile = null)
1685 if (!empty($location_id) && !empty($location_ns)) {
1686 $options['location_id'] = $location_id;
1687 $options['location_ns'] = $location_ns;
1689 $location = Location::fromId($location_id, $location_ns);
1691 if (!empty($location)) {
1692 $options['lat'] = $location->lat;
1693 $options['lon'] = $location->lon;
1696 } else if (!empty($lat) && !empty($lon)) {
1697 $options['lat'] = $lat;
1698 $options['lon'] = $lon;
1700 $location = Location::fromLatLon($lat, $lon);
1702 if (!empty($location)) {
1703 $options['location_id'] = $location->location_id;
1704 $options['location_ns'] = $location->location_ns;
1706 } else if (!empty($profile)) {
1707 if (isset($profile->lat) && isset($profile->lon)) {
1708 $options['lat'] = $profile->lat;
1709 $options['lon'] = $profile->lon;
1712 if (isset($profile->location_id) && isset($profile->location_ns)) {
1713 $options['location_id'] = $profile->location_id;
1714 $options['location_ns'] = $profile->location_ns;
1721 function clearReplies()
1723 $replyNotice = new Notice();
1724 $replyNotice->reply_to = $this->id;
1726 //Null any notices that are replies to this notice
1728 if ($replyNotice->find()) {
1729 while ($replyNotice->fetch()) {
1730 $orig = clone($replyNotice);
1731 $replyNotice->reply_to = null;
1732 $replyNotice->update($orig);
1738 $reply = new Reply();
1739 $reply->notice_id = $this->id;
1741 if ($reply->find()) {
1742 while($reply->fetch()) {
1743 self::blow('reply:stream:%d', $reply->profile_id);
1751 function clearFiles()
1753 $f2p = new File_to_post();
1755 $f2p->post_id = $this->id;
1758 while ($f2p->fetch()) {
1762 // FIXME: decide whether to delete File objects
1763 // ...and related (actual) files
1766 function clearRepeats()
1768 $repeatNotice = new Notice();
1769 $repeatNotice->repeat_of = $this->id;
1771 //Null any notices that are repeats of this notice
1773 if ($repeatNotice->find()) {
1774 while ($repeatNotice->fetch()) {
1775 $orig = clone($repeatNotice);
1776 $repeatNotice->repeat_of = null;
1777 $repeatNotice->update($orig);
1782 function clearFaves()
1785 $fave->notice_id = $this->id;
1787 if ($fave->find()) {
1788 while ($fave->fetch()) {
1789 self::blow('fave:ids_by_user_own:%d', $fave->user_id);
1790 self::blow('fave:ids_by_user_own:%d;last', $fave->user_id);
1791 self::blow('fave:ids_by_user:%d', $fave->user_id);
1792 self::blow('fave:ids_by_user:%d;last', $fave->user_id);
1800 function clearTags()
1802 $tag = new Notice_tag();
1803 $tag->notice_id = $this->id;
1806 while ($tag->fetch()) {
1807 self::blow('profile:notice_ids_tagged:%d:%s', $this->profile_id, Cache::keyize($tag->tag));
1808 self::blow('profile:notice_ids_tagged:%d:%s;last', $this->profile_id, Cache::keyize($tag->tag));
1809 self::blow('notice_tag:notice_ids:%s', Cache::keyize($tag->tag));
1810 self::blow('notice_tag:notice_ids:%s;last', Cache::keyize($tag->tag));
1818 function clearGroupInboxes()
1820 $gi = new Group_inbox();
1822 $gi->notice_id = $this->id;
1825 while ($gi->fetch()) {
1826 self::blow('user_group:notice_ids:%d', $gi->group_id);
1834 function distribute()
1836 // We always insert for the author so they don't
1838 Event::handle('StartNoticeDistribute', array($this));
1840 $user = User::staticGet('id', $this->profile_id);
1841 if (!empty($user)) {
1842 Inbox::insertNotice($user->id, $this->id);
1845 if (common_config('queue', 'inboxes')) {
1846 // If there's a failure, we want to _force_
1847 // distribution at this point.
1849 $qm = QueueManager::get();
1850 $qm->enqueue($this, 'distrib');
1851 } catch (Exception $e) {
1852 // If the exception isn't transient, this
1853 // may throw more exceptions as DQH does
1854 // its own enqueueing. So, we ignore them!
1856 $handler = new DistribQueueHandler();
1857 $handler->handle($this);
1858 } catch (Exception $e) {
1859 common_log(LOG_ERR, "emergency redistribution resulted in " . $e->getMessage());
1861 // Re-throw so somebody smarter can handle it.
1865 $handler = new DistribQueueHandler();
1866 $handler->handle($this);
1872 $result = parent::insert();
1875 // Profile::hasRepeated() abuses pkeyGet(), so we
1876 // have to clear manually
1877 if (!empty($this->repeat_of)) {
1878 $c = self::memcache();
1880 $ck = self::multicacheKey('Notice',
1881 array('profile_id' => $this->profile_id,
1882 'repeat_of' => $this->repeat_of));
1892 * Get the source of the notice
1894 * @return Notice_source $ns A notice source object. 'code' is the only attribute
1895 * guaranteed to be populated.
1897 function getSource()
1899 $ns = new Notice_source();
1900 if (!empty($this->source)) {
1901 switch ($this->source) {
1908 $ns->code = $this->source;
1911 $ns = Notice_source::staticGet($this->source);
1913 $ns = new Notice_source();
1914 $ns->code = $this->source;
1915 $app = Oauth_application::staticGet('name', $this->source);
1917 $ns->name = $app->name;
1918 $ns->url = $app->source_url;
1928 * Determine whether the notice was locally created
1930 * @return boolean locality
1933 public function isLocal()
1935 return ($this->is_local == Notice::LOCAL_PUBLIC ||
1936 $this->is_local == Notice::LOCAL_NONPUBLIC);
1940 * Get the list of hash tags saved with this notice.
1942 * @return array of strings
1944 public function getTags()
1947 $tag = new Notice_tag();
1948 $tag->notice_id = $this->id;
1950 while ($tag->fetch()) {
1951 $tags[] = $tag->tag;
1958 static private function utcDate($dt)
1960 $dateStr = date('d F Y H:i:s', strtotime($dt));
1961 $d = new DateTime($dateStr, new DateTimeZone('UTC'));
1962 return $d->format(DATE_W3C);
1966 * Look up the creation timestamp for a given notice ID, even
1967 * if it's been deleted.
1970 * @return mixed string recorded creation timestamp, or false if can't be found
1972 public static function getAsTimestamp($id)
1978 $notice = Notice::staticGet('id', $id);
1980 return $notice->created;
1983 $deleted = Deleted_notice::staticGet('id', $id);
1985 return $deleted->created;
1992 * Build an SQL 'where' fragment for timestamp-based sorting from a since_id
1993 * parameter, matching notices posted after the given one (exclusive).
1995 * If the referenced notice can't be found, will return false.
1998 * @param string $idField
1999 * @param string $createdField
2000 * @return mixed string or false if no match
2002 public static function whereSinceId($id, $idField='id', $createdField='created')
2004 $since = Notice::getAsTimestamp($id);
2006 return sprintf("($createdField = '%s' and $idField > %d) or ($createdField > '%s')", $since, $id, $since);
2012 * Build an SQL 'where' fragment for timestamp-based sorting from a since_id
2013 * parameter, matching notices posted after the given one (exclusive), and
2014 * if necessary add it to the data object's query.
2016 * @param DB_DataObject $obj
2018 * @param string $idField
2019 * @param string $createdField
2020 * @return mixed string or false if no match
2022 public static function addWhereSinceId(DB_DataObject $obj, $id, $idField='id', $createdField='created')
2024 $since = self::whereSinceId($id, $idField, $createdField);
2026 $obj->whereAdd($since);
2031 * Build an SQL 'where' fragment for timestamp-based sorting from a max_id
2032 * parameter, matching notices posted before the given one (inclusive).
2034 * If the referenced notice can't be found, will return false.
2037 * @param string $idField
2038 * @param string $createdField
2039 * @return mixed string or false if no match
2041 public static function whereMaxId($id, $idField='id', $createdField='created')
2043 $max = Notice::getAsTimestamp($id);
2045 return sprintf("($createdField < '%s') or ($createdField = '%s' and $idField <= %d)", $max, $max, $id);
2051 * Build an SQL 'where' fragment for timestamp-based sorting from a max_id
2052 * parameter, matching notices posted before the given one (inclusive), and
2053 * if necessary add it to the data object's query.
2055 * @param DB_DataObject $obj
2057 * @param string $idField
2058 * @param string $createdField
2059 * @return mixed string or false if no match
2061 public static function addWhereMaxId(DB_DataObject $obj, $id, $idField='id', $createdField='created')
2063 $max = self::whereMaxId($id, $idField, $createdField);
2065 $obj->whereAdd($max);
2071 if (common_config('public', 'localonly')) {
2072 return ($this->is_local == Notice::LOCAL_PUBLIC);
2074 return (($this->is_local != Notice::LOCAL_NONPUBLIC) &&
2075 ($this->is_local != Notice::GATEWAY));
2080 * Check that the given profile is allowed to read, respond to, or otherwise
2081 * act on this notice.
2083 * The $scope member is a bitmask of scopes, representing a logical AND of the
2084 * scope requirement. So, 0x03 (Notice::ADDRESSEE_SCOPE | Notice::SITE_SCOPE) means
2085 * "only visible to people who are mentioned in the notice AND are users on this site."
2086 * Users on the site who are not mentioned in the notice will not be able to see the
2089 * @param Profile $profile The profile to check
2091 * @return boolean whether the profile is in the notice's scope
2094 function inScope($profile)
2096 // If there's no scope, anyone (even anon) is in scope.
2098 if ($this->scope == 0) {
2102 // If there's scope, anon cannot be in scope
2104 if (empty($profile)) {
2108 // Author is always in scope
2110 if ($this->profile_id == $profile->id) {
2114 // Only for users on this site
2116 if ($this->scope & Notice::SITE_SCOPE) {
2117 $user = $profile->getUser();
2123 // Only for users mentioned in the notice
2125 if ($this->scope & Notice::ADDRESSEE_SCOPE) {
2127 // XXX: just query for the single reply
2129 $replies = $this->getReplies();
2131 if (!in_array($profile->id, $replies)) {
2136 // Only for members of the given group
2138 if ($this->scope & Notice::GROUP_SCOPE) {
2140 // XXX: just query for the single membership
2142 $groups = $this->getGroups();
2146 foreach ($groups as $group) {
2147 if ($profile->isMember($group)) {
2158 // Only for followers of the author
2160 if ($this->scope & Notice::FOLLOWER_SCOPE) {
2161 $author = $this->getProfile();
2162 if (!Subscription::exists($profile, $author)) {