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 // Get the groups here so we can figure out replies and such
347 if (!isset($groups)) {
348 $groups = self::groupsFromText($notice->content, $profile);
353 // Handle repeat case
355 if (isset($repeat_of)) {
357 // Check for a private one
359 $repeat = Notice::staticGet('id', $repeat_of);
361 if (empty($repeat)) {
362 // TRANS: Client exception thrown in notice when trying to repeat a missing or deleted notice.
363 throw new ClientException(_('Cannot repeat; original notice is missing or deleted.'));
366 if ($profile->id == $repeat->profile_id) {
367 // TRANS: Client error displayed when trying to repeat an own notice.
368 throw new ClientException(_('You cannot repeat your own notice.'));
371 if ($repeat->scope != Notice::SITE_SCOPE &&
372 $repeat->scope != Notice::PUBLIC_SCOPE) {
373 // TRANS: Client error displayed when trying to repeat a non-public notice.
374 throw new ClientException(_('Cannot repeat a private notice.'), 403);
377 if (!$repeat->inScope($profile)) {
378 // The generic checks above should cover this, but let's be sure!
379 // TRANS: Client error displayed when trying to repeat a notice you cannot access.
380 throw new ClientException(_('Cannot repeat a notice you cannot read.'), 403);
383 if ($profile->hasRepeated($repeat->id)) {
384 // TRANS: Client error displayed when trying to repeat an already repeated notice.
385 throw new ClientException(_('You already repeated that notice.'));
388 $notice->repeat_of = $repeat_of;
390 $reply = self::getReplyTo($reply_to, $profile_id, $source, $final);
392 if (!empty($reply)) {
394 if (!$reply->inScope($profile)) {
395 // TRANS: Client error displayed when trying to reply to a notice a the target has no access to.
396 // TRANS: %1$s is a user nickname, %2$d is a notice ID (number).
397 throw new ClientException(sprintf(_('%1$s has no access to notice %2$d.'),
398 $profile->nickname, $reply->id), 403);
401 $notice->reply_to = $reply->id;
402 $notice->conversation = $reply->conversation;
404 // If the original is private to a group, and notice has no group specified,
405 // make it to the same group(s)
407 if (empty($groups) && ($reply->scope | Notice::GROUP_SCOPE)) {
409 $replyGroups = $reply->getGroups();
410 foreach ($replyGroups as $group) {
411 if ($profile->isMember($group)) {
412 $groups[] = $group->id;
421 if (!empty($lat) && !empty($lon)) {
426 if (!empty($location_ns) && !empty($location_id)) {
427 $notice->location_id = $location_id;
428 $notice->location_ns = $location_ns;
431 if (!empty($rendered)) {
432 $notice->rendered = $rendered;
434 $notice->rendered = common_render_content($final, $notice);
437 if (empty($object_type)) {
438 $notice->object_type = (empty($notice->reply_to)) ? ActivityObject::NOTE : ActivityObject::COMMENT;
440 $notice->object_type = $object_type;
443 if (is_null($scope)) { // 0 is a valid value
444 if (!empty($reply)) {
445 $notice->scope = $reply->scope;
447 $notice->scope = common_config('notice', 'defaultscope');
450 $notice->scope = $scope;
453 // For private streams
455 $user = $profile->getUser();
458 if ($user->private_stream &&
459 ($notice->scope == Notice::PUBLIC_SCOPE ||
460 $notice->scope == Notice::SITE_SCOPE)) {
461 $notice->scope |= Notice::FOLLOWER_SCOPE;
465 // Force the scope for private groups
467 foreach ($groups as $groupId) {
468 $group = User_group::staticGet('id', $groupId);
469 if (!empty($group)) {
470 if ($group->force_scope) {
471 $notice->scope |= Notice::GROUP_SCOPE;
477 if (Event::handle('StartNoticeSave', array(&$notice))) {
479 // XXX: some of these functions write to the DB
481 $id = $notice->insert();
484 common_log_db_error($notice, 'INSERT', __FILE__);
485 // TRANS: Server exception thrown when a notice cannot be saved.
486 throw new ServerException(_('Problem saving notice.'));
489 // Update ID-dependent columns: URI, conversation
491 $orig = clone($notice);
496 $notice->uri = common_notice_uri($notice);
500 // If it's not part of a conversation, it's
501 // the beginning of a new conversation.
503 if (empty($notice->conversation)) {
504 $conv = Conversation::create();
505 $notice->conversation = $conv->id;
510 if (!$notice->update($orig)) {
511 common_log_db_error($notice, 'UPDATE', __FILE__);
512 // TRANS: Server exception thrown when a notice cannot be updated.
513 throw new ServerException(_('Problem saving notice.'));
519 // Clear the cache for subscribed users, so they'll update at next request
520 // XXX: someone clever could prepend instead of clearing the cache
522 $notice->blowOnInsert();
524 // Save per-notice metadata...
526 if (isset($replies)) {
527 $notice->saveKnownReplies($replies);
529 $notice->saveReplies();
533 $notice->saveKnownTags($tags);
538 // Note: groups may save tags, so must be run after tags are saved
539 // to avoid errors on duplicates.
540 // Note: groups should always be set.
542 $notice->saveKnownGroups($groups);
545 $notice->saveKnownUrls($urls);
551 // Prepare inbox delivery, may be queued to background.
552 $notice->distribute();
558 function blowOnInsert($conversation = false)
560 self::blow('profile:notice_ids:%d', $this->profile_id);
562 if ($this->isPublic()) {
563 self::blow('public');
566 // XXX: Before we were blowing the casche only if the notice id
567 // was not the root of the conversation. What to do now?
569 self::blow('notice:conversation_ids:%d', $this->conversation);
570 self::blow('conversation::notice_count:%d', $this->conversation);
572 if (!empty($this->repeat_of)) {
573 self::blow('notice:repeats:%d', $this->repeat_of);
576 $original = Notice::staticGet('id', $this->repeat_of);
578 if (!empty($original)) {
579 $originalUser = User::staticGet('id', $original->profile_id);
580 if (!empty($originalUser)) {
581 self::blow('user:repeats_of_me:%d', $originalUser->id);
585 $profile = Profile::staticGet($this->profile_id);
586 if (!empty($profile)) {
587 $profile->blowNoticeCount();
592 * Clear cache entries related to this notice at delete time.
593 * Necessary to avoid breaking paging on public, profile timelines.
595 function blowOnDelete()
597 $this->blowOnInsert();
599 self::blow('profile:notice_ids:%d;last', $this->profile_id);
601 if ($this->isPublic()) {
602 self::blow('public;last');
605 self::blow('fave:by_notice', $this->id);
607 if ($this->conversation) {
608 // In case we're the first, will need to calc a new root.
609 self::blow('notice:conversation_root:%d', $this->conversation);
613 /** save all urls in the notice to the db
615 * follow redirects and save all available file information
616 * (mimetype, date, size, oembed, etc.)
620 function saveUrls() {
621 if (common_config('attachments', 'process_links')) {
622 common_replace_urls_callback($this->content, array($this, 'saveUrl'), $this->id);
627 * Save the given URLs as related links/attachments to the db
629 * follow redirects and save all available file information
630 * (mimetype, date, size, oembed, etc.)
634 function saveKnownUrls($urls)
636 if (common_config('attachments', 'process_links')) {
637 // @fixme validation?
638 foreach (array_unique($urls) as $url) {
639 File::processNew($url, $this->id);
647 function saveUrl($url, $notice_id) {
648 File::processNew($url, $notice_id);
651 static function checkDupes($profile_id, $content) {
652 $profile = Profile::staticGet($profile_id);
653 if (empty($profile)) {
656 $notice = $profile->getNotices(0, CachingNoticeStream::CACHE_WINDOW);
657 if (!empty($notice)) {
659 while ($notice->fetch()) {
660 if (time() - strtotime($notice->created) >= common_config('site', 'dupelimit')) {
662 } else if ($notice->content == $content) {
667 // If we get here, oldest item in cache window is not
668 // old enough for dupe limit; do direct check against DB
669 $notice = new Notice();
670 $notice->profile_id = $profile_id;
671 $notice->content = $content;
672 $threshold = common_sql_date(time() - common_config('site', 'dupelimit'));
673 $notice->whereAdd(sprintf("created > '%s'", $notice->escape($threshold)));
675 $cnt = $notice->count();
679 static function checkEditThrottle($profile_id) {
680 $profile = Profile::staticGet($profile_id);
681 if (empty($profile)) {
684 // Get the Nth notice
685 $notice = $profile->getNotices(common_config('throttle', 'count') - 1, 1);
686 if ($notice && $notice->fetch()) {
687 // If the Nth notice was posted less than timespan seconds ago
688 if (time() - strtotime($notice->created) <= common_config('throttle', 'timespan')) {
693 // Either not N notices in the stream, OR the Nth was not posted within timespan seconds
697 function getUploadedAttachment() {
699 $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"';
700 $post->query($query);
702 if (empty($post->up) || empty($post->i)) {
705 $ret = array($post->up, $post->i);
711 function hasAttachments() {
713 $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);
714 $post->query($query);
716 $n_attachments = intval($post->n_attachments);
718 return $n_attachments;
721 function attachments() {
723 $keypart = sprintf('notice:file_ids:%d', $this->id);
725 $idstr = self::cacheGet($keypart);
727 if ($idstr !== false) {
728 $ids = explode(',', $idstr);
731 $f2p = new File_to_post;
732 $f2p->post_id = $this->id;
734 while ($f2p->fetch()) {
735 $ids[] = $f2p->file_id;
738 self::cacheSet($keypart, implode(',', $ids));
743 foreach ($ids as $id) {
744 $f = File::staticGet('id', $id);
754 function publicStream($offset=0, $limit=20, $since_id=0, $max_id=0)
756 $stream = new PublicNoticeStream();
757 return $stream->getNotices($offset, $limit, $since_id, $max_id);
761 function conversationStream($id, $offset=0, $limit=20, $since_id=0, $max_id=0)
763 $stream = new ConversationNoticeStream($id);
765 return $stream->getNotices($offset, $limit, $since_id, $max_id);
769 * Is this notice part of an active conversation?
771 * @return boolean true if other messages exist in the same
772 * conversation, false if this is the only one
774 function hasConversation()
776 if (!empty($this->conversation)) {
777 $conversation = Notice::conversationStream(
783 if ($conversation->N > 0) {
791 * Grab the earliest notice from this conversation.
793 * @return Notice or null
795 function conversationRoot()
797 if (!empty($this->conversation)) {
798 $c = self::memcache();
800 $key = Cache::key('notice:conversation_root:' . $this->conversation);
801 $notice = $c->get($key);
806 $notice = new Notice();
807 $notice->conversation = $this->conversation;
808 $notice->orderBy('CREATED');
813 $c->set($key, $notice);
820 * Pull up a full list of local recipients who will be getting
821 * this notice in their inbox. Results will be cached, so don't
822 * change the input data wily-nilly!
824 * @param array $groups optional list of Group objects;
825 * if left empty, will be loaded from group_inbox records
826 * @param array $recipient optional list of reply profile ids
827 * if left empty, will be loaded from reply records
828 * @return array associating recipient user IDs with an inbox source constant
830 function whoGets($groups=null, $recipients=null)
832 $c = self::memcache();
835 $ni = $c->get(Cache::key('notice:who_gets:'.$this->id));
841 if (is_null($groups)) {
842 $groups = $this->getGroups();
845 if (is_null($recipients)) {
846 $recipients = $this->getReplies();
849 $users = $this->getSubscribedUsers();
851 // FIXME: kind of ignoring 'transitional'...
852 // we'll probably stop supporting inboxless mode
857 // Give plugins a chance to add folks in at start...
858 if (Event::handle('StartNoticeWhoGets', array($this, &$ni))) {
860 foreach ($users as $id) {
861 $ni[$id] = NOTICE_INBOX_SOURCE_SUB;
864 foreach ($groups as $group) {
865 $users = $group->getUserMembers();
866 foreach ($users as $id) {
867 if (!array_key_exists($id, $ni)) {
868 $ni[$id] = NOTICE_INBOX_SOURCE_GROUP;
873 foreach ($recipients as $recipient) {
874 if (!array_key_exists($recipient, $ni)) {
875 $ni[$recipient] = NOTICE_INBOX_SOURCE_REPLY;
879 // Exclude any deleted, non-local, or blocking recipients.
880 $profile = $this->getProfile();
881 $originalProfile = null;
882 if ($this->repeat_of) {
883 // Check blocks against the original notice's poster as well.
884 $original = Notice::staticGet('id', $this->repeat_of);
886 $originalProfile = $original->getProfile();
889 foreach ($ni as $id => $source) {
890 $user = User::staticGet('id', $id);
891 if (empty($user) || $user->hasBlocked($profile) ||
892 ($originalProfile && $user->hasBlocked($originalProfile))) {
897 // Give plugins a chance to filter out...
898 Event::handle('EndNoticeWhoGets', array($this, &$ni));
902 // XXX: pack this data better
903 $c->set(Cache::key('notice:who_gets:'.$this->id), $ni);
910 * Adds this notice to the inboxes of each local user who should receive
911 * it, based on author subscriptions, group memberships, and @-replies.
913 * Warning: running a second time currently will make items appear
914 * multiple times in users' inboxes.
916 * @fixme make more robust against errors
917 * @fixme break up massive deliveries to smaller background tasks
919 * @param array $groups optional list of Group objects;
920 * if left empty, will be loaded from group_inbox records
921 * @param array $recipient optional list of reply profile ids
922 * if left empty, will be loaded from reply records
924 function addToInboxes($groups=null, $recipients=null)
926 $ni = $this->whoGets($groups, $recipients);
928 $ids = array_keys($ni);
930 // We remove the author (if they're a local user),
931 // since we'll have already done this in distribute()
933 $i = array_search($this->profile_id, $ids);
941 Inbox::bulkInsert($this->id, $ids);
946 function getSubscribedUsers()
950 if(common_config('db','quote_identifiers'))
951 $user_table = '"user"';
952 else $user_table = 'user';
956 'FROM '. $user_table .' JOIN subscription '.
957 'ON '. $user_table .'.id = subscription.subscriber ' .
958 'WHERE subscription.subscribed = %d ';
960 $user->query(sprintf($qry, $this->profile_id));
964 while ($user->fetch()) {
974 * Record this notice to the given group inboxes for delivery.
975 * Overrides the regular parsing of !group markup.
977 * @param string $group_ids
978 * @fixme might prefer URIs as identifiers, as for replies?
979 * best with generalizations on user_group to support
980 * remote groups better.
982 function saveKnownGroups($group_ids)
984 if (!is_array($group_ids)) {
985 // TRANS: Server exception thrown when no array is provided to the method saveKnownGroups().
986 throw new ServerException(_('Bad type provided to saveKnownGroups.'));
990 foreach (array_unique($group_ids) as $id) {
991 $group = User_group::staticGet('id', $id);
993 common_log(LOG_ERR, "Local delivery to group id $id, $group->nickname");
994 $result = $this->addToGroupInbox($group);
996 common_log_db_error($gi, 'INSERT', __FILE__);
999 // we automatically add a tag for every group name, too
1001 $tag = Notice_tag::pkeyGet(array('tag' => common_canonical_tag($group->nickname),
1002 'notice_id' => $this->id));
1004 if (is_null($tag)) {
1005 $this->saveTag($group->nickname);
1008 $groups[] = clone($group);
1010 common_log(LOG_ERR, "Local delivery to group id $id skipped, doesn't exist");
1018 * Parse !group delivery and record targets into group_inbox.
1019 * @return array of Group objects
1021 function saveGroups()
1023 // Don't save groups for repeats
1025 if (!empty($this->repeat_of)) {
1029 $profile = $this->getProfile();
1031 $groups = self::groupsFromText($this->content, $profile);
1033 /* Add them to the database */
1035 foreach ($groups as $group) {
1036 /* XXX: remote groups. */
1038 if (empty($group)) {
1043 if ($profile->isMember($group)) {
1045 $result = $this->addToGroupInbox($group);
1048 common_log_db_error($gi, 'INSERT', __FILE__);
1051 $groups[] = clone($group);
1058 function addToGroupInbox($group)
1060 $gi = Group_inbox::pkeyGet(array('group_id' => $group->id,
1061 'notice_id' => $this->id));
1065 $gi = new Group_inbox();
1067 $gi->group_id = $group->id;
1068 $gi->notice_id = $this->id;
1069 $gi->created = $this->created;
1071 $result = $gi->insert();
1074 common_log_db_error($gi, 'INSERT', __FILE__);
1075 // TRANS: Server exception thrown when an update for a group inbox fails.
1076 throw new ServerException(_('Problem saving group inbox.'));
1079 self::blow('user_group:notice_ids:%d', $gi->group_id);
1086 * Save reply records indicating that this notice needs to be
1087 * delivered to the local users with the given URIs.
1089 * Since this is expected to be used when saving foreign-sourced
1090 * messages, we won't deliver to any remote targets as that's the
1091 * source service's responsibility.
1093 * Mail notifications etc will be handled later.
1095 * @param array of unique identifier URIs for recipients
1097 function saveKnownReplies($uris)
1103 $sender = Profile::staticGet($this->profile_id);
1105 foreach (array_unique($uris) as $uri) {
1107 $profile = Profile::fromURI($uri);
1109 if (empty($profile)) {
1110 common_log(LOG_WARNING, "Unable to determine profile for URI '$uri'");
1114 if ($profile->hasBlocked($sender)) {
1115 common_log(LOG_INFO, "Not saving reply to profile {$profile->id} ($uri) from sender {$sender->id} because of a block.");
1119 $reply = new Reply();
1121 $reply->notice_id = $this->id;
1122 $reply->profile_id = $profile->id;
1123 $reply->modified = $this->created;
1125 common_log(LOG_INFO, __METHOD__ . ": saving reply: notice $this->id to profile $profile->id");
1127 $id = $reply->insert();
1134 * Pull @-replies from this message's content in StatusNet markup format
1135 * and save reply records indicating that this message needs to be
1136 * delivered to those users.
1138 * Mail notifications to local profiles will be sent later.
1140 * @return array of integer profile IDs
1143 function saveReplies()
1145 // Don't save reply data for repeats
1147 if (!empty($this->repeat_of)) {
1151 $sender = Profile::staticGet($this->profile_id);
1153 // @todo ideally this parser information would only
1154 // be calculated once.
1156 $mentions = common_find_mentions($this->content, $this);
1160 // store replied only for first @ (what user/notice what the reply directed,
1161 // we assume first @ is it)
1163 foreach ($mentions as $mention) {
1165 foreach ($mention['mentioned'] as $mentioned) {
1167 // skip if they're already covered
1169 if (!empty($replied[$mentioned->id])) {
1173 // Don't save replies from blocked profile to local user
1175 $mentioned_user = User::staticGet('id', $mentioned->id);
1176 if (!empty($mentioned_user) && $mentioned_user->hasBlocked($sender)) {
1180 $reply = new Reply();
1182 $reply->notice_id = $this->id;
1183 $reply->profile_id = $mentioned->id;
1184 $reply->modified = $this->created;
1186 $id = $reply->insert();
1189 common_log_db_error($reply, 'INSERT', __FILE__);
1190 // TRANS: Server exception thrown when a reply cannot be saved.
1191 // TRANS: %1$d is a notice ID, %2$d is the ID of the mentioned user.
1192 throw new ServerException(sprintf(_('Could not save reply for %1$d, %2$d.'), $this->id, $mentioned->id));
1194 $replied[$mentioned->id] = 1;
1195 self::blow('reply:stream:%d', $mentioned->id);
1200 $recipientIds = array_keys($replied);
1202 return $recipientIds;
1206 * Pull the complete list of @-reply targets for this notice.
1208 * @return array of integer profile ids
1210 function getReplies()
1212 $keypart = sprintf('notice:reply_ids:%d', $this->id);
1214 $idstr = self::cacheGet($keypart);
1216 if ($idstr !== false) {
1217 $ids = explode(',', $idstr);
1221 $reply = new Reply();
1222 $reply->selectAdd();
1223 $reply->selectAdd('profile_id');
1224 $reply->notice_id = $this->id;
1226 if ($reply->find()) {
1227 while($reply->fetch()) {
1228 $ids[] = $reply->profile_id;
1231 self::cacheSet($keypart, implode(',', $ids));
1238 * Send e-mail notifications to local @-reply targets.
1240 * Replies must already have been saved; this is expected to be run
1241 * from the distrib queue handler.
1243 function sendReplyNotifications()
1245 // Don't send reply notifications for repeats
1247 if (!empty($this->repeat_of)) {
1251 $recipientIds = $this->getReplies();
1253 foreach ($recipientIds as $recipientId) {
1254 $user = User::staticGet('id', $recipientId);
1255 if (!empty($user)) {
1256 mail_notify_attn($user, $this);
1262 * Pull list of groups this notice needs to be delivered to,
1263 * as previously recorded by saveGroups() or saveKnownGroups().
1265 * @return array of Group objects
1267 function getGroups()
1269 // Don't save groups for repeats
1271 if (!empty($this->repeat_of)) {
1277 $keypart = sprintf('notice:groups:%d', $this->id);
1279 $idstr = self::cacheGet($keypart);
1281 if ($idstr !== false) {
1282 $ids = explode(',', $idstr);
1284 $gi = new Group_inbox();
1287 $gi->selectAdd('group_id');
1289 $gi->notice_id = $this->id;
1292 while ($gi->fetch()) {
1293 $ids[] = $gi->group_id;
1297 self::cacheSet($keypart, implode(',', $ids));
1302 foreach ($ids as $id) {
1303 $group = User_group::staticGet('id', $id);
1313 * Convert a notice into an activity for export.
1315 * @param User $cur Current user
1317 * @return Activity activity object representing this Notice.
1320 function asActivity($cur)
1322 $act = self::cacheGet(Cache::codeKey('notice:as-activity:'.$this->id));
1327 $act = new Activity();
1329 if (Event::handle('StartNoticeAsActivity', array($this, &$act))) {
1331 $profile = $this->getProfile();
1333 $act->actor = ActivityObject::fromProfile($profile);
1334 $act->actor->extra[] = $profile->profileInfo($cur);
1335 $act->verb = ActivityVerb::POST;
1336 $act->objects[] = ActivityObject::fromNotice($this);
1338 // XXX: should this be handled by default processing for object entry?
1340 $act->time = strtotime($this->created);
1341 $act->link = $this->bestUrl();
1343 $act->content = common_xml_safe_str($this->rendered);
1344 $act->id = $this->uri;
1345 $act->title = common_xml_safe_str($this->content);
1349 $tags = $this->getTags();
1351 foreach ($tags as $tag) {
1352 $cat = new AtomCategory();
1355 $act->categories[] = $cat;
1359 // XXX: use Atom Media and/or File activity objects instead
1361 $attachments = $this->attachments();
1363 foreach ($attachments as $attachment) {
1364 $enclosure = $attachment->getEnclosure();
1366 $act->enclosures[] = $enclosure;
1370 $ctx = new ActivityContext();
1372 if (!empty($this->reply_to)) {
1373 $reply = Notice::staticGet('id', $this->reply_to);
1374 if (!empty($reply)) {
1375 $ctx->replyToID = $reply->uri;
1376 $ctx->replyToUrl = $reply->bestUrl();
1380 $ctx->location = $this->getLocation();
1384 if (!empty($this->conversation)) {
1385 $conv = Conversation::staticGet('id', $this->conversation);
1386 if (!empty($conv)) {
1387 $ctx->conversation = $conv->uri;
1391 $reply_ids = $this->getReplies();
1393 foreach ($reply_ids as $id) {
1394 $rprofile = Profile::staticGet('id', $id);
1395 if (!empty($rprofile)) {
1396 $ctx->attention[] = $rprofile->getUri();
1400 $groups = $this->getGroups();
1402 foreach ($groups as $group) {
1403 $ctx->attention[] = $group->getUri();
1406 // XXX: deprecated; use ActivityVerb::SHARE instead
1410 if (!empty($this->repeat_of)) {
1411 $repeat = Notice::staticGet('id', $this->repeat_of);
1412 $ctx->forwardID = $repeat->uri;
1413 $ctx->forwardUrl = $repeat->bestUrl();
1416 $act->context = $ctx;
1420 $atom_feed = $profile->getAtomFeed();
1422 if (!empty($atom_feed)) {
1424 $act->source = new ActivitySource();
1426 // XXX: we should store the actual feed ID
1428 $act->source->id = $atom_feed;
1430 // XXX: we should store the actual feed title
1432 $act->source->title = $profile->getBestName();
1434 $act->source->links['alternate'] = $profile->profileurl;
1435 $act->source->links['self'] = $atom_feed;
1437 $act->source->icon = $profile->avatarUrl(AVATAR_PROFILE_SIZE);
1439 $notice = $profile->getCurrentNotice();
1441 if (!empty($notice)) {
1442 $act->source->updated = self::utcDate($notice->created);
1445 $user = User::staticGet('id', $profile->id);
1447 if (!empty($user)) {
1448 $act->source->links['license'] = common_config('license', 'url');
1452 if ($this->isLocal()) {
1453 $act->selfLink = common_local_url('ApiStatusesShow', array('id' => $this->id,
1454 'format' => 'atom'));
1455 $act->editLink = $act->selfLink;
1458 Event::handle('EndNoticeAsActivity', array($this, &$act));
1461 self::cacheSet(Cache::codeKey('notice:as-activity:'.$this->id), $act);
1466 // This has gotten way too long. Needs to be sliced up into functional bits
1467 // or ideally exported to a utility class.
1469 function asAtomEntry($namespace=false,
1474 $act = $this->asActivity($cur);
1475 $act->extra[] = $this->noticeInfo($cur);
1476 return $act->asString($namespace, $author, $source);
1480 * Extra notice info for atom entries
1482 * Clients use some extra notice info in the atom stream.
1483 * This gives it to them.
1485 * @param User $cur Current user
1487 * @return array representation of <statusnet:notice_info> element
1490 function noticeInfo($cur)
1492 // local notice ID (useful to clients for ordering)
1494 $noticeInfoAttr = array('local_id' => $this->id);
1498 $ns = $this->getSource();
1501 $noticeInfoAttr['source'] = $ns->code;
1502 if (!empty($ns->url)) {
1503 $noticeInfoAttr['source_link'] = $ns->url;
1504 if (!empty($ns->name)) {
1505 $noticeInfoAttr['source'] = '<a href="'
1506 . htmlspecialchars($ns->url)
1507 . '" rel="nofollow">'
1508 . htmlspecialchars($ns->name)
1514 // favorite and repeated
1517 $noticeInfoAttr['favorite'] = ($cur->hasFave($this)) ? "true" : "false";
1518 $cp = $cur->getProfile();
1519 $noticeInfoAttr['repeated'] = ($cp->hasRepeated($this->id)) ? "true" : "false";
1522 if (!empty($this->repeat_of)) {
1523 $noticeInfoAttr['repeat_of'] = $this->repeat_of;
1526 return array('statusnet:notice_info', $noticeInfoAttr, null);
1530 * Returns an XML string fragment with a reference to a notice as an
1531 * Activity Streams noun object with the given element type.
1533 * Assumes that 'activity' namespace has been previously defined.
1535 * @param string $element one of 'subject', 'object', 'target'
1539 function asActivityNoun($element)
1541 $noun = ActivityObject::fromNotice($this);
1542 return $noun->asString('activity:' . $element);
1547 if (!empty($this->url)) {
1549 } else if (!empty($this->uri) && preg_match('/^https?:/', $this->uri)) {
1552 return common_local_url('shownotice',
1553 array('notice' => $this->id));
1559 * Determine which notice, if any, a new notice is in reply to.
1561 * For conversation tracking, we try to see where this notice fits
1562 * in the tree. Rough algorithm is:
1564 * if (reply_to is set and valid) {
1566 * } else if ((source not API or Web) and (content starts with "T NAME" or "@name ")) {
1567 * return ID of last notice by initial @name in content;
1570 * Note that all @nickname instances will still be used to save "reply" records,
1571 * so the notice shows up in the mentioned users' "replies" tab.
1573 * @param integer $reply_to ID passed in by Web or API
1574 * @param integer $profile_id ID of author
1575 * @param string $source Source tag, like 'web' or 'gwibber'
1576 * @param string $content Final notice content
1578 * @return integer ID of replied-to notice, or null for not a reply.
1581 static function getReplyTo($reply_to, $profile_id, $source, $content)
1583 static $lb = array('xmpp', 'mail', 'sms', 'omb');
1585 // If $reply_to is specified, we check that it exists, and then
1586 // return it if it does
1588 if (!empty($reply_to)) {
1589 $reply_notice = Notice::staticGet('id', $reply_to);
1590 if (!empty($reply_notice)) {
1591 return $reply_notice;
1595 // If it's not a "low bandwidth" source (one where you can't set
1596 // a reply_to argument), we return. This is mostly web and API
1599 if (!in_array($source, $lb)) {
1603 // Is there an initial @ or T?
1605 if (preg_match('/^T ([A-Z0-9]{1,64}) /', $content, $match) ||
1606 preg_match('/^@([a-z0-9]{1,64})\s+/', $content, $match)) {
1607 $nickname = common_canonical_nickname($match[1]);
1612 // Figure out who that is.
1614 $sender = Profile::staticGet('id', $profile_id);
1615 if (empty($sender)) {
1619 $recipient = common_relative_profile($sender, $nickname, common_sql_now());
1621 if (empty($recipient)) {
1625 // Get their last notice
1627 $last = $recipient->getCurrentNotice();
1629 if (!empty($last)) {
1636 static function maxContent()
1638 $contentlimit = common_config('notice', 'contentlimit');
1639 // null => use global limit (distinct from 0!)
1640 if (is_null($contentlimit)) {
1641 $contentlimit = common_config('site', 'textlimit');
1643 return $contentlimit;
1646 static function contentTooLong($content)
1648 $contentlimit = self::maxContent();
1649 return ($contentlimit > 0 && !empty($content) && (mb_strlen($content) > $contentlimit));
1652 function getLocation()
1656 if (!empty($this->location_id) && !empty($this->location_ns)) {
1657 $location = Location::fromId($this->location_id, $this->location_ns);
1660 if (is_null($location)) { // no ID, or Location::fromId() failed
1661 if (!empty($this->lat) && !empty($this->lon)) {
1662 $location = Location::fromLatLon($this->lat, $this->lon);
1670 * Convenience function for posting a repeat of an existing message.
1672 * @param int $repeater_id: profile ID of user doing the repeat
1673 * @param string $source: posting source key, eg 'web', 'api', etc
1676 * @throws Exception on failure or permission problems
1678 function repeat($repeater_id, $source)
1680 $author = Profile::staticGet('id', $this->profile_id);
1682 // TRANS: Message used to repeat a notice. RT is the abbreviation of 'retweet'.
1683 // TRANS: %1$s is the repeated user's name, %2$s is the repeated notice.
1684 $content = sprintf(_('RT @%1$s %2$s'),
1688 $maxlen = common_config('site', 'textlimit');
1689 if ($maxlen > 0 && mb_strlen($content) > $maxlen) {
1690 // Web interface and current Twitter API clients will
1691 // pull the original notice's text, but some older
1692 // clients and RSS/Atom feeds will see this trimmed text.
1694 // Unfortunately this is likely to lose tags or URLs
1695 // at the end of long notices.
1696 $content = mb_substr($content, 0, $maxlen - 4) . ' ...';
1699 // Scope is same as this one's
1701 return self::saveNew($repeater_id,
1704 array('repeat_of' => $this->id,
1705 'scope' => $this->scope));
1708 // These are supposed to be in chron order!
1710 function repeatStream($limit=100)
1712 $cache = Cache::instance();
1714 if (empty($cache)) {
1715 $ids = $this->_repeatStreamDirect($limit);
1717 $idstr = $cache->get(Cache::key('notice:repeats:'.$this->id));
1718 if ($idstr !== false) {
1719 $ids = explode(',', $idstr);
1721 $ids = $this->_repeatStreamDirect(100);
1722 $cache->set(Cache::key('notice:repeats:'.$this->id), implode(',', $ids));
1725 // We do a max of 100, so slice down to limit
1726 $ids = array_slice($ids, 0, $limit);
1730 return NoticeStream::getStreamByIds($ids);
1733 function _repeatStreamDirect($limit)
1735 $notice = new Notice();
1737 $notice->selectAdd(); // clears it
1738 $notice->selectAdd('id');
1740 $notice->repeat_of = $this->id;
1742 $notice->orderBy('created, id'); // NB: asc!
1744 if (!is_null($limit)) {
1745 $notice->limit(0, $limit);
1750 if ($notice->find()) {
1751 while ($notice->fetch()) {
1752 $ids[] = $notice->id;
1762 function locationOptions($lat, $lon, $location_id, $location_ns, $profile = null)
1766 if (!empty($location_id) && !empty($location_ns)) {
1767 $options['location_id'] = $location_id;
1768 $options['location_ns'] = $location_ns;
1770 $location = Location::fromId($location_id, $location_ns);
1772 if (!empty($location)) {
1773 $options['lat'] = $location->lat;
1774 $options['lon'] = $location->lon;
1777 } else if (!empty($lat) && !empty($lon)) {
1778 $options['lat'] = $lat;
1779 $options['lon'] = $lon;
1781 $location = Location::fromLatLon($lat, $lon);
1783 if (!empty($location)) {
1784 $options['location_id'] = $location->location_id;
1785 $options['location_ns'] = $location->location_ns;
1787 } else if (!empty($profile)) {
1788 if (isset($profile->lat) && isset($profile->lon)) {
1789 $options['lat'] = $profile->lat;
1790 $options['lon'] = $profile->lon;
1793 if (isset($profile->location_id) && isset($profile->location_ns)) {
1794 $options['location_id'] = $profile->location_id;
1795 $options['location_ns'] = $profile->location_ns;
1802 function clearReplies()
1804 $replyNotice = new Notice();
1805 $replyNotice->reply_to = $this->id;
1807 //Null any notices that are replies to this notice
1809 if ($replyNotice->find()) {
1810 while ($replyNotice->fetch()) {
1811 $orig = clone($replyNotice);
1812 $replyNotice->reply_to = null;
1813 $replyNotice->update($orig);
1819 $reply = new Reply();
1820 $reply->notice_id = $this->id;
1822 if ($reply->find()) {
1823 while($reply->fetch()) {
1824 self::blow('reply:stream:%d', $reply->profile_id);
1832 function clearFiles()
1834 $f2p = new File_to_post();
1836 $f2p->post_id = $this->id;
1839 while ($f2p->fetch()) {
1843 // FIXME: decide whether to delete File objects
1844 // ...and related (actual) files
1847 function clearRepeats()
1849 $repeatNotice = new Notice();
1850 $repeatNotice->repeat_of = $this->id;
1852 //Null any notices that are repeats of this notice
1854 if ($repeatNotice->find()) {
1855 while ($repeatNotice->fetch()) {
1856 $orig = clone($repeatNotice);
1857 $repeatNotice->repeat_of = null;
1858 $repeatNotice->update($orig);
1863 function clearFaves()
1866 $fave->notice_id = $this->id;
1868 if ($fave->find()) {
1869 while ($fave->fetch()) {
1870 self::blow('fave:ids_by_user_own:%d', $fave->user_id);
1871 self::blow('fave:ids_by_user_own:%d;last', $fave->user_id);
1872 self::blow('fave:ids_by_user:%d', $fave->user_id);
1873 self::blow('fave:ids_by_user:%d;last', $fave->user_id);
1881 function clearTags()
1883 $tag = new Notice_tag();
1884 $tag->notice_id = $this->id;
1887 while ($tag->fetch()) {
1888 self::blow('profile:notice_ids_tagged:%d:%s', $this->profile_id, Cache::keyize($tag->tag));
1889 self::blow('profile:notice_ids_tagged:%d:%s;last', $this->profile_id, Cache::keyize($tag->tag));
1890 self::blow('notice_tag:notice_ids:%s', Cache::keyize($tag->tag));
1891 self::blow('notice_tag:notice_ids:%s;last', Cache::keyize($tag->tag));
1899 function clearGroupInboxes()
1901 $gi = new Group_inbox();
1903 $gi->notice_id = $this->id;
1906 while ($gi->fetch()) {
1907 self::blow('user_group:notice_ids:%d', $gi->group_id);
1915 function distribute()
1917 // We always insert for the author so they don't
1919 Event::handle('StartNoticeDistribute', array($this));
1921 $user = User::staticGet('id', $this->profile_id);
1922 if (!empty($user)) {
1923 Inbox::insertNotice($user->id, $this->id);
1926 if (common_config('queue', 'inboxes')) {
1927 // If there's a failure, we want to _force_
1928 // distribution at this point.
1930 $qm = QueueManager::get();
1931 $qm->enqueue($this, 'distrib');
1932 } catch (Exception $e) {
1933 // If the exception isn't transient, this
1934 // may throw more exceptions as DQH does
1935 // its own enqueueing. So, we ignore them!
1937 $handler = new DistribQueueHandler();
1938 $handler->handle($this);
1939 } catch (Exception $e) {
1940 common_log(LOG_ERR, "emergency redistribution resulted in " . $e->getMessage());
1942 // Re-throw so somebody smarter can handle it.
1946 $handler = new DistribQueueHandler();
1947 $handler->handle($this);
1953 $result = parent::insert();
1956 // Profile::hasRepeated() abuses pkeyGet(), so we
1957 // have to clear manually
1958 if (!empty($this->repeat_of)) {
1959 $c = self::memcache();
1961 $ck = self::multicacheKey('Notice',
1962 array('profile_id' => $this->profile_id,
1963 'repeat_of' => $this->repeat_of));
1973 * Get the source of the notice
1975 * @return Notice_source $ns A notice source object. 'code' is the only attribute
1976 * guaranteed to be populated.
1978 function getSource()
1980 $ns = new Notice_source();
1981 if (!empty($this->source)) {
1982 switch ($this->source) {
1989 $ns->code = $this->source;
1992 $ns = Notice_source::staticGet($this->source);
1994 $ns = new Notice_source();
1995 $ns->code = $this->source;
1996 $app = Oauth_application::staticGet('name', $this->source);
1998 $ns->name = $app->name;
1999 $ns->url = $app->source_url;
2009 * Determine whether the notice was locally created
2011 * @return boolean locality
2014 public function isLocal()
2016 return ($this->is_local == Notice::LOCAL_PUBLIC ||
2017 $this->is_local == Notice::LOCAL_NONPUBLIC);
2021 * Get the list of hash tags saved with this notice.
2023 * @return array of strings
2025 public function getTags()
2029 $keypart = sprintf('notice:tags:%d', $this->id);
2031 $tagstr = self::cacheGet($keypart);
2033 if ($tagstr !== false) {
2034 $tags = explode(',', $tagstr);
2036 $tag = new Notice_tag();
2037 $tag->notice_id = $this->id;
2039 while ($tag->fetch()) {
2040 $tags[] = $tag->tag;
2043 self::cacheSet($keypart, implode(',', $tags));
2049 static private function utcDate($dt)
2051 $dateStr = date('d F Y H:i:s', strtotime($dt));
2052 $d = new DateTime($dateStr, new DateTimeZone('UTC'));
2053 return $d->format(DATE_W3C);
2057 * Look up the creation timestamp for a given notice ID, even
2058 * if it's been deleted.
2061 * @return mixed string recorded creation timestamp, or false if can't be found
2063 public static function getAsTimestamp($id)
2069 $notice = Notice::staticGet('id', $id);
2071 return $notice->created;
2074 $deleted = Deleted_notice::staticGet('id', $id);
2076 return $deleted->created;
2083 * Build an SQL 'where' fragment for timestamp-based sorting from a since_id
2084 * parameter, matching notices posted after the given one (exclusive).
2086 * If the referenced notice can't be found, will return false.
2089 * @param string $idField
2090 * @param string $createdField
2091 * @return mixed string or false if no match
2093 public static function whereSinceId($id, $idField='id', $createdField='created')
2095 $since = Notice::getAsTimestamp($id);
2097 return sprintf("($createdField = '%s' and $idField > %d) or ($createdField > '%s')", $since, $id, $since);
2103 * Build an SQL 'where' fragment for timestamp-based sorting from a since_id
2104 * parameter, matching notices posted after the given one (exclusive), and
2105 * if necessary add it to the data object's query.
2107 * @param DB_DataObject $obj
2109 * @param string $idField
2110 * @param string $createdField
2111 * @return mixed string or false if no match
2113 public static function addWhereSinceId(DB_DataObject $obj, $id, $idField='id', $createdField='created')
2115 $since = self::whereSinceId($id, $idField, $createdField);
2117 $obj->whereAdd($since);
2122 * Build an SQL 'where' fragment for timestamp-based sorting from a max_id
2123 * parameter, matching notices posted before the given one (inclusive).
2125 * If the referenced notice can't be found, will return false.
2128 * @param string $idField
2129 * @param string $createdField
2130 * @return mixed string or false if no match
2132 public static function whereMaxId($id, $idField='id', $createdField='created')
2134 $max = Notice::getAsTimestamp($id);
2136 return sprintf("($createdField < '%s') or ($createdField = '%s' and $idField <= %d)", $max, $max, $id);
2142 * Build an SQL 'where' fragment for timestamp-based sorting from a max_id
2143 * parameter, matching notices posted before the given one (inclusive), and
2144 * if necessary add it to the data object's query.
2146 * @param DB_DataObject $obj
2148 * @param string $idField
2149 * @param string $createdField
2150 * @return mixed string or false if no match
2152 public static function addWhereMaxId(DB_DataObject $obj, $id, $idField='id', $createdField='created')
2154 $max = self::whereMaxId($id, $idField, $createdField);
2156 $obj->whereAdd($max);
2162 if (common_config('public', 'localonly')) {
2163 return ($this->is_local == Notice::LOCAL_PUBLIC);
2165 return (($this->is_local != Notice::LOCAL_NONPUBLIC) &&
2166 ($this->is_local != Notice::GATEWAY));
2171 * Check that the given profile is allowed to read, respond to, or otherwise
2172 * act on this notice.
2174 * The $scope member is a bitmask of scopes, representing a logical AND of the
2175 * scope requirement. So, 0x03 (Notice::ADDRESSEE_SCOPE | Notice::SITE_SCOPE) means
2176 * "only visible to people who are mentioned in the notice AND are users on this site."
2177 * Users on the site who are not mentioned in the notice will not be able to see the
2180 * @param Profile $profile The profile to check; pass null to check for public/unauthenticated users.
2182 * @return boolean whether the profile is in the notice's scope
2184 function inScope($profile)
2186 $keypart = sprintf('notice:in-scope-for:%d:%d', $this->id, $profile->id);
2188 $result = self::cacheGet($keypart);
2190 if ($result === false) {
2191 $bResult = $this->_inScope($profile);
2192 $result = ($bResult) ? 1 : 0;
2193 self::cacheSet($keypart, $result, 0, 300);
2196 return ($result == 1) ? true : false;
2199 protected function _inScope($profile)
2201 // If there's no scope, anyone (even anon) is in scope.
2203 if ($this->scope == 0) {
2207 // If there's scope, anon cannot be in scope
2209 if (empty($profile)) {
2213 // Author is always in scope
2215 if ($this->profile_id == $profile->id) {
2219 // Only for users on this site
2221 if ($this->scope & Notice::SITE_SCOPE) {
2222 $user = $profile->getUser();
2228 // Only for users mentioned in the notice
2230 if ($this->scope & Notice::ADDRESSEE_SCOPE) {
2232 // XXX: just query for the single reply
2234 $replies = $this->getReplies();
2236 if (!in_array($profile->id, $replies)) {
2241 // Only for members of the given group
2243 if ($this->scope & Notice::GROUP_SCOPE) {
2245 // XXX: just query for the single membership
2247 $groups = $this->getGroups();
2251 foreach ($groups as $group) {
2252 if ($profile->isMember($group)) {
2263 // Only for followers of the author
2265 if ($this->scope & Notice::FOLLOWER_SCOPE) {
2266 $author = $this->getProfile();
2267 if (!Subscription::exists($profile, $author)) {
2275 static function groupsFromText($text, $profile)
2279 /* extract all !group */
2280 $count = preg_match_all('/(?:^|\s)!(' . Nickname::DISPLAY_FMT . ')/',
2288 foreach (array_unique($match[1]) as $nickname) {
2289 $group = User_group::getForNickname($nickname, $profile);
2290 if (!empty($group) && $profile->isMember($group)) {
2291 $groups[] = $group->id;