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', 200);
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)
77 function staticGet($k,$v=NULL)
79 return Memcached_DataObject::staticGet('Notice',$k,$v);
82 /* the code above is auto generated do not remove the tag below */
86 const LOCAL_PUBLIC = 1;
88 const LOCAL_NONPUBLIC = -1;
93 $profile = Profile::staticGet('id', $this->profile_id);
95 if (empty($profile)) {
96 // TRANS: Server exception thrown when a user profile for a notice cannot be found.
97 // TRANS: %1$d is a profile ID (number), %2$d is a notice ID (number).
98 throw new ServerException(sprintf(_('No such profile (%1$d) for notice (%2$d).'), $this->profile_id, $this->id));
106 // For auditing purposes, save a record that the notice
109 // @fixme we have some cases where things get re-run and so the
111 $deleted = Deleted_notice::staticGet('id', $this->id);
113 $deleted = new Deleted_notice();
115 $deleted->id = $this->id;
116 $deleted->profile_id = $this->profile_id;
117 $deleted->uri = $this->uri;
118 $deleted->created = $this->created;
119 $deleted->deleted = common_sql_now();
124 if (Event::handle('NoticeDeleteRelated', array($this))) {
126 // Clear related records
128 $this->clearReplies();
129 $this->clearRepeats();
132 $this->clearGroupInboxes();
134 // NOTE: we don't clear inboxes
135 // NOTE: we don't clear queue items
138 $result = parent::delete();
140 $this->blowOnDelete();
145 * Extract #hashtags from this notice's content and save them to the database.
149 /* extract all #hastags */
150 $count = preg_match_all('/(?:^|\s)#([\pL\pN_\-\.]{1,64})/', strtolower($this->content), $match);
155 /* Add them to the database */
156 return $this->saveKnownTags($match[1]);
160 * Record the given set of hash tags in the db for this notice.
161 * Given tag strings will be normalized and checked for dupes.
163 function saveKnownTags($hashtags)
165 //turn each into their canonical tag
166 //this is needed to remove dupes before saving e.g. #hash.tag = #hashtag
167 for($i=0; $i<count($hashtags); $i++) {
168 /* elide characters we don't want in the tag */
169 $hashtags[$i] = common_canonical_tag($hashtags[$i]);
172 foreach(array_unique($hashtags) as $hashtag) {
173 $this->saveTag($hashtag);
174 self::blow('profile:notice_ids_tagged:%d:%s', $this->profile_id, $hashtag);
180 * Record a single hash tag as associated with this notice.
181 * Tag format and uniqueness must be validated by caller.
183 function saveTag($hashtag)
185 $tag = new Notice_tag();
186 $tag->notice_id = $this->id;
187 $tag->tag = $hashtag;
188 $tag->created = $this->created;
189 $id = $tag->insert();
192 // TRANS: Server exception. %s are the error details.
193 throw new ServerException(sprintf(_('Database error inserting hashtag: %s'),
194 $last_error->message));
198 // if it's saved, blow its cache
199 $tag->blowCache(false);
203 * Save a new notice and push it out to subscribers' inboxes.
204 * Poster's permissions are checked before sending.
206 * @param int $profile_id Profile ID of the poster
207 * @param string $content source message text; links may be shortened
208 * per current user's preference
209 * @param string $source source key ('web', 'api', etc)
210 * @param array $options Associative array of optional properties:
211 * string 'created' timestamp of notice; defaults to now
212 * int 'is_local' source/gateway ID, one of:
213 * Notice::LOCAL_PUBLIC - Local, ok to appear in public timeline
214 * Notice::REMOTE_OMB - Sent from a remote OMB service;
215 * hide from public timeline but show in
216 * local "and friends" timelines
217 * Notice::LOCAL_NONPUBLIC - Local, but hide from public timeline
218 * Notice::GATEWAY - From another non-OMB service;
219 * will not appear in public views
220 * float 'lat' decimal latitude for geolocation
221 * float 'lon' decimal longitude for geolocation
222 * int 'location_id' geoname identifier
223 * int 'location_ns' geoname namespace to interpret location_id
224 * int 'reply_to'; notice ID this is a reply to
225 * int 'repeat_of'; notice ID this is a repeat of
226 * string 'uri' unique ID for notice; defaults to local notice URL
227 * string 'url' permalink to notice; defaults to local notice URL
228 * string 'rendered' rendered HTML version of content
229 * array 'replies' list of profile URIs for reply delivery in
230 * place of extracting @-replies from content.
231 * array 'groups' list of group IDs to deliver to, in place of
232 * extracting ! tags from content
233 * array 'tags' list of hashtag strings to save with the notice
234 * in place of extracting # tags from content
235 * array 'urls' list of attached/referred URLs to save with the
236 * notice in place of extracting links from content
237 * boolean 'distribute' whether to distribute the notice, default true
239 * @fixme tag override
242 * @throws ClientException
244 static function saveNew($profile_id, $content, $source, $options=null) {
245 $defaults = array('uri' => null,
249 'distribute' => true);
251 if (!empty($options)) {
252 $options = $options + $defaults;
258 if (!isset($is_local)) {
259 $is_local = Notice::LOCAL_PUBLIC;
262 $profile = Profile::staticGet('id', $profile_id);
263 $user = User::staticGet('id', $profile_id);
265 // Use the local user's shortening preferences, if applicable.
266 $final = $user->shortenLinks($content);
268 $final = common_shorten_links($content);
271 if (Notice::contentTooLong($final)) {
272 // TRANS: Client exception thrown if a notice contains too many characters.
273 throw new ClientException(_('Problem saving notice. Too long.'));
276 if (empty($profile)) {
277 // TRANS: Client exception thrown when trying to save a notice for an unknown user.
278 throw new ClientException(_('Problem saving notice. Unknown user.'));
281 if (common_config('throttle', 'enabled') && !Notice::checkEditThrottle($profile_id)) {
282 common_log(LOG_WARNING, 'Excessive posting by profile #' . $profile_id . '; throttled.');
283 // TRANS: Client exception thrown when a user tries to post too many notices in a given time frame.
284 throw new ClientException(_('Too many notices too fast; take a breather '.
285 'and post again in a few minutes.'));
288 if (common_config('site', 'dupelimit') > 0 && !Notice::checkDupes($profile_id, $final)) {
289 common_log(LOG_WARNING, 'Dupe posting by profile #' . $profile_id . '; throttled.');
290 // TRANS: Client exception thrown when a user tries to post too many duplicate notices in a given time frame.
291 throw new ClientException(_('Too many duplicate messages too quickly;'.
292 ' take a breather and post again in a few minutes.'));
295 if (!$profile->hasRight(Right::NEWNOTICE)) {
296 common_log(LOG_WARNING, "Attempted post from user disallowed to post: " . $profile->nickname);
298 // TRANS: Client exception thrown when a user tries to post while being banned.
299 throw new ClientException(_('You are banned from posting notices on this site.'), 403);
302 $notice = new Notice();
303 $notice->profile_id = $profile_id;
305 $autosource = common_config('public', 'autosource');
307 # Sandboxed are non-false, but not 1, either
309 if (!$profile->hasRight(Right::PUBLICNOTICE) ||
310 ($source && $autosource && in_array($source, $autosource))) {
311 $notice->is_local = Notice::LOCAL_NONPUBLIC;
313 $notice->is_local = $is_local;
316 if (!empty($created)) {
317 $notice->created = $created;
319 $notice->created = common_sql_now();
322 $notice->content = $final;
324 $notice->source = $source;
328 // Handle repeat case
330 if (isset($repeat_of)) {
331 $notice->repeat_of = $repeat_of;
333 $notice->reply_to = self::getReplyTo($reply_to, $profile_id, $source, $final);
336 if (!empty($notice->reply_to)) {
337 $reply = Notice::staticGet('id', $notice->reply_to);
338 $notice->conversation = $reply->conversation;
341 if (!empty($lat) && !empty($lon)) {
346 if (!empty($location_ns) && !empty($location_id)) {
347 $notice->location_id = $location_id;
348 $notice->location_ns = $location_ns;
351 if (!empty($rendered)) {
352 $notice->rendered = $rendered;
354 $notice->rendered = common_render_content($final, $notice);
357 if (Event::handle('StartNoticeSave', array(&$notice))) {
359 // XXX: some of these functions write to the DB
361 $id = $notice->insert();
364 common_log_db_error($notice, 'INSERT', __FILE__);
365 // TRANS: Server exception thrown when a notice cannot be saved.
366 throw new ServerException(_('Problem saving notice.'));
369 // Update ID-dependent columns: URI, conversation
371 $orig = clone($notice);
376 $notice->uri = common_notice_uri($notice);
380 // If it's not part of a conversation, it's
381 // the beginning of a new conversation.
383 if (empty($notice->conversation)) {
384 $conv = Conversation::create();
385 $notice->conversation = $conv->id;
390 if (!$notice->update($orig)) {
391 common_log_db_error($notice, 'UPDATE', __FILE__);
392 // TRANS: Server exception thrown when a notice cannot be updated.
393 throw new ServerException(_('Problem saving notice.'));
399 # Clear the cache for subscribed users, so they'll update at next request
400 # XXX: someone clever could prepend instead of clearing the cache
402 $notice->blowOnInsert();
404 // Save per-notice metadata...
406 if (isset($replies)) {
407 $notice->saveKnownReplies($replies);
409 $notice->saveReplies();
413 $notice->saveKnownTags($tags);
418 // Note: groups may save tags, so must be run after tags are saved
419 // to avoid errors on duplicates.
420 if (isset($groups)) {
421 $notice->saveKnownGroups($groups);
423 $notice->saveGroups();
427 $notice->saveKnownUrls($urls);
433 // Prepare inbox delivery, may be queued to background.
434 $notice->distribute();
440 function blowOnInsert($conversation = false)
442 self::blow('profile:notice_ids:%d', $this->profile_id);
443 self::blow('public');
445 // XXX: Before we were blowing the casche only if the notice id
446 // was not the root of the conversation. What to do now?
448 self::blow('notice:conversation_ids:%d', $this->conversation);
450 if (!empty($this->repeat_of)) {
451 self::blow('notice:repeats:%d', $this->repeat_of);
454 $original = Notice::staticGet('id', $this->repeat_of);
456 if (!empty($original)) {
457 $originalUser = User::staticGet('id', $original->profile_id);
458 if (!empty($originalUser)) {
459 self::blow('user:repeats_of_me:%d', $originalUser->id);
463 $profile = Profile::staticGet($this->profile_id);
464 if (!empty($profile)) {
465 $profile->blowNoticeCount();
470 * Clear cache entries related to this notice at delete time.
471 * Necessary to avoid breaking paging on public, profile timelines.
473 function blowOnDelete()
475 $this->blowOnInsert();
477 self::blow('profile:notice_ids:%d;last', $this->profile_id);
478 self::blow('public;last');
481 /** save all urls in the notice to the db
483 * follow redirects and save all available file information
484 * (mimetype, date, size, oembed, etc.)
488 function saveUrls() {
489 if (common_config('attachments', 'process_links')) {
490 common_replace_urls_callback($this->content, array($this, 'saveUrl'), $this->id);
495 * Save the given URLs as related links/attachments to the db
497 * follow redirects and save all available file information
498 * (mimetype, date, size, oembed, etc.)
502 function saveKnownUrls($urls)
504 if (common_config('attachments', 'process_links')) {
505 // @fixme validation?
506 foreach (array_unique($urls) as $url) {
507 File::processNew($url, $this->id);
515 function saveUrl($url, $notice_id) {
516 File::processNew($url, $notice_id);
519 static function checkDupes($profile_id, $content) {
520 $profile = Profile::staticGet($profile_id);
521 if (empty($profile)) {
524 $notice = $profile->getNotices(0, NOTICE_CACHE_WINDOW);
525 if (!empty($notice)) {
527 while ($notice->fetch()) {
528 if (time() - strtotime($notice->created) >= common_config('site', 'dupelimit')) {
530 } else if ($notice->content == $content) {
535 # If we get here, oldest item in cache window is not
536 # old enough for dupe limit; do direct check against DB
537 $notice = new Notice();
538 $notice->profile_id = $profile_id;
539 $notice->content = $content;
540 $threshold = common_sql_date(time() - common_config('site', 'dupelimit'));
541 $notice->whereAdd(sprintf("created > '%s'", $notice->escape($threshold)));
543 $cnt = $notice->count();
547 static function checkEditThrottle($profile_id) {
548 $profile = Profile::staticGet($profile_id);
549 if (empty($profile)) {
553 $notice = $profile->getNotices(common_config('throttle', 'count') - 1, 1);
554 if ($notice && $notice->fetch()) {
555 # If the Nth notice was posted less than timespan seconds ago
556 if (time() - strtotime($notice->created) <= common_config('throttle', 'timespan')) {
561 # Either not N notices in the stream, OR the Nth was not posted within timespan seconds
565 function getUploadedAttachment() {
567 $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"';
568 $post->query($query);
570 if (empty($post->up) || empty($post->i)) {
573 $ret = array($post->up, $post->i);
579 function hasAttachments() {
581 $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);
582 $post->query($query);
584 $n_attachments = intval($post->n_attachments);
586 return $n_attachments;
589 function attachments() {
592 $f2p = new File_to_post;
593 $f2p->post_id = $this->id;
595 while ($f2p->fetch()) {
596 $f = File::staticGet($f2p->file_id);
605 function getStreamByIds($ids)
607 $cache = common_memcache();
609 if (!empty($cache)) {
611 foreach ($ids as $id) {
612 $n = Notice::staticGet('id', $id);
617 return new ArrayWrapper($notices);
619 $notice = new Notice();
621 //if no IDs requested, just return the notice object
624 $notice->whereAdd('id in (' . implode(', ', $ids) . ')');
630 while ($notice->fetch()) {
631 $temp[$notice->id] = clone($notice);
636 foreach ($ids as $id) {
637 if (array_key_exists($id, $temp)) {
638 $wrapped[] = $temp[$id];
642 return new ArrayWrapper($wrapped);
646 function publicStream($offset=0, $limit=20, $since_id=0, $max_id=0)
648 $ids = Notice::stream(array('Notice', '_publicStreamDirect'),
651 $offset, $limit, $since_id, $max_id);
652 return Notice::getStreamByIds($ids);
655 function _publicStreamDirect($offset=0, $limit=20, $since_id=0, $max_id=0)
657 $notice = new Notice();
659 $notice->selectAdd(); // clears it
660 $notice->selectAdd('id');
662 $notice->orderBy('id DESC');
664 if (!is_null($offset)) {
665 $notice->limit($offset, $limit);
668 if (common_config('public', 'localonly')) {
669 $notice->whereAdd('is_local = ' . Notice::LOCAL_PUBLIC);
671 # -1 == blacklisted, -2 == gateway (i.e. Twitter)
672 $notice->whereAdd('is_local !='. Notice::LOCAL_NONPUBLIC);
673 $notice->whereAdd('is_local !='. Notice::GATEWAY);
676 if ($since_id != 0) {
677 $notice->whereAdd('id > ' . $since_id);
681 $notice->whereAdd('id <= ' . $max_id);
686 if ($notice->find()) {
687 while ($notice->fetch()) {
688 $ids[] = $notice->id;
698 function conversationStream($id, $offset=0, $limit=20, $since_id=0, $max_id=0)
700 $ids = Notice::stream(array('Notice', '_conversationStreamDirect'),
702 'notice:conversation_ids:'.$id,
703 $offset, $limit, $since_id, $max_id);
705 return Notice::getStreamByIds($ids);
708 function _conversationStreamDirect($id, $offset=0, $limit=20, $since_id=0, $max_id=0)
710 $notice = new Notice();
712 $notice->selectAdd(); // clears it
713 $notice->selectAdd('id');
715 $notice->conversation = $id;
717 $notice->orderBy('id DESC');
719 if (!is_null($offset)) {
720 $notice->limit($offset, $limit);
723 if ($since_id != 0) {
724 $notice->whereAdd('id > ' . $since_id);
728 $notice->whereAdd('id <= ' . $max_id);
733 if ($notice->find()) {
734 while ($notice->fetch()) {
735 $ids[] = $notice->id;
746 * Is this notice part of an active conversation?
748 * @return boolean true if other messages exist in the same
749 * conversation, false if this is the only one
751 function hasConversation()
753 if (!empty($this->conversation)) {
754 $conversation = Notice::conversationStream(
760 if ($conversation->N > 0) {
768 * Pull up a full list of local recipients who will be getting
769 * this notice in their inbox. Results will be cached, so don't
770 * change the input data wily-nilly!
772 * @param array $groups optional list of Group objects;
773 * if left empty, will be loaded from group_inbox records
774 * @param array $recipient optional list of reply profile ids
775 * if left empty, will be loaded from reply records
776 * @return array associating recipient user IDs with an inbox source constant
778 function whoGets($groups=null, $recipients=null)
780 $c = self::memcache();
783 $ni = $c->get(common_cache_key('notice:who_gets:'.$this->id));
789 if (is_null($groups)) {
790 $groups = $this->getGroups();
793 if (is_null($recipients)) {
794 $recipients = $this->getReplies();
797 $users = $this->getSubscribedUsers();
799 // FIXME: kind of ignoring 'transitional'...
800 // we'll probably stop supporting inboxless mode
805 foreach ($users as $id) {
806 $ni[$id] = NOTICE_INBOX_SOURCE_SUB;
809 foreach ($groups as $group) {
810 $users = $group->getUserMembers();
811 foreach ($users as $id) {
812 if (!array_key_exists($id, $ni)) {
813 $ni[$id] = NOTICE_INBOX_SOURCE_GROUP;
818 foreach ($recipients as $recipient) {
819 if (!array_key_exists($recipient, $ni)) {
820 $ni[$recipient] = NOTICE_INBOX_SOURCE_REPLY;
824 // Exclude any deleted, non-local, or blocking recipients.
825 $profile = $this->getProfile();
826 foreach ($ni as $id => $source) {
827 $user = User::staticGet('id', $id);
828 if (empty($user) || $user->hasBlocked($profile)) {
834 // XXX: pack this data better
835 $c->set(common_cache_key('notice:who_gets:'.$this->id), $ni);
842 * Adds this notice to the inboxes of each local user who should receive
843 * it, based on author subscriptions, group memberships, and @-replies.
845 * Warning: running a second time currently will make items appear
846 * multiple times in users' inboxes.
848 * @fixme make more robust against errors
849 * @fixme break up massive deliveries to smaller background tasks
851 * @param array $groups optional list of Group objects;
852 * if left empty, will be loaded from group_inbox records
853 * @param array $recipient optional list of reply profile ids
854 * if left empty, will be loaded from reply records
856 function addToInboxes($groups=null, $recipients=null)
858 $ni = $this->whoGets($groups, $recipients);
860 $ids = array_keys($ni);
862 // We remove the author (if they're a local user),
863 // since we'll have already done this in distribute()
865 $i = array_search($this->profile_id, $ids);
873 Inbox::bulkInsert($this->id, $ids);
878 function getSubscribedUsers()
882 if(common_config('db','quote_identifiers'))
883 $user_table = '"user"';
884 else $user_table = 'user';
888 'FROM '. $user_table .' JOIN subscription '.
889 'ON '. $user_table .'.id = subscription.subscriber ' .
890 'WHERE subscription.subscribed = %d ';
892 $user->query(sprintf($qry, $this->profile_id));
896 while ($user->fetch()) {
906 * Record this notice to the given group inboxes for delivery.
907 * Overrides the regular parsing of !group markup.
909 * @param string $group_ids
910 * @fixme might prefer URIs as identifiers, as for replies?
911 * best with generalizations on user_group to support
912 * remote groups better.
914 function saveKnownGroups($group_ids)
916 if (!is_array($group_ids)) {
917 // TRANS: Server exception thrown when no array is provided to the method saveKnownGroups().
918 throw new ServerException(_('Bad type provided to saveKnownGroups.'));
922 foreach (array_unique($group_ids) as $id) {
923 $group = User_group::staticGet('id', $id);
925 common_log(LOG_ERR, "Local delivery to group id $id, $group->nickname");
926 $result = $this->addToGroupInbox($group);
928 common_log_db_error($gi, 'INSERT', __FILE__);
931 // @fixme should we save the tags here or not?
932 $groups[] = clone($group);
934 common_log(LOG_ERR, "Local delivery to group id $id skipped, doesn't exist");
942 * Parse !group delivery and record targets into group_inbox.
943 * @return array of Group objects
945 function saveGroups()
947 // Don't save groups for repeats
949 if (!empty($this->repeat_of)) {
955 /* extract all !group */
956 $count = preg_match_all('/(?:^|\s)!([A-Za-z0-9]{1,64})/',
957 strtolower($this->content),
963 $profile = $this->getProfile();
965 /* Add them to the database */
967 foreach (array_unique($match[1]) as $nickname) {
968 /* XXX: remote groups. */
969 $group = User_group::getForNickname($nickname, $profile);
975 // we automatically add a tag for every group name, too
977 $tag = Notice_tag::pkeyGet(array('tag' => common_canonical_tag($nickname),
978 'notice_id' => $this->id));
981 $this->saveTag($nickname);
984 if ($profile->isMember($group)) {
986 $result = $this->addToGroupInbox($group);
989 common_log_db_error($gi, 'INSERT', __FILE__);
992 $groups[] = clone($group);
999 function addToGroupInbox($group)
1001 $gi = Group_inbox::pkeyGet(array('group_id' => $group->id,
1002 'notice_id' => $this->id));
1006 $gi = new Group_inbox();
1008 $gi->group_id = $group->id;
1009 $gi->notice_id = $this->id;
1010 $gi->created = $this->created;
1012 $result = $gi->insert();
1015 common_log_db_error($gi, 'INSERT', __FILE__);
1016 // TRANS: Server exception thrown when an update for a group inbox fails.
1017 throw new ServerException(_('Problem saving group inbox.'));
1020 self::blow('user_group:notice_ids:%d', $gi->group_id);
1027 * Save reply records indicating that this notice needs to be
1028 * delivered to the local users with the given URIs.
1030 * Since this is expected to be used when saving foreign-sourced
1031 * messages, we won't deliver to any remote targets as that's the
1032 * source service's responsibility.
1034 * Mail notifications etc will be handled later.
1036 * @param array of unique identifier URIs for recipients
1038 function saveKnownReplies($uris)
1044 $sender = Profile::staticGet($this->profile_id);
1046 foreach (array_unique($uris) as $uri) {
1048 $profile = Profile::fromURI($uri);
1050 if (empty($profile)) {
1051 common_log(LOG_WARNING, "Unable to determine profile for URI '$uri'");
1055 if ($profile->hasBlocked($sender)) {
1056 common_log(LOG_INFO, "Not saving reply to profile {$profile->id} ($uri) from sender {$sender->id} because of a block.");
1060 $reply = new Reply();
1062 $reply->notice_id = $this->id;
1063 $reply->profile_id = $profile->id;
1065 common_log(LOG_INFO, __METHOD__ . ": saving reply: notice $this->id to profile $profile->id");
1067 $id = $reply->insert();
1074 * Pull @-replies from this message's content in StatusNet markup format
1075 * and save reply records indicating that this message needs to be
1076 * delivered to those users.
1078 * Mail notifications to local profiles will be sent later.
1080 * @return array of integer profile IDs
1083 function saveReplies()
1085 // Don't save reply data for repeats
1087 if (!empty($this->repeat_of)) {
1091 $sender = Profile::staticGet($this->profile_id);
1093 // @todo ideally this parser information would only
1094 // be calculated once.
1096 $mentions = common_find_mentions($this->content, $this);
1100 // store replied only for first @ (what user/notice what the reply directed,
1101 // we assume first @ is it)
1103 foreach ($mentions as $mention) {
1105 foreach ($mention['mentioned'] as $mentioned) {
1107 // skip if they're already covered
1109 if (!empty($replied[$mentioned->id])) {
1113 // Don't save replies from blocked profile to local user
1115 $mentioned_user = User::staticGet('id', $mentioned->id);
1116 if (!empty($mentioned_user) && $mentioned_user->hasBlocked($sender)) {
1120 $reply = new Reply();
1122 $reply->notice_id = $this->id;
1123 $reply->profile_id = $mentioned->id;
1125 $id = $reply->insert();
1128 common_log_db_error($reply, 'INSERT', __FILE__);
1129 // TRANS: Server exception thrown when a reply cannot be saved.
1130 // TRANS: %1$d is a notice ID, %2$d is the ID of the mentioned user.
1131 throw new ServerException(sprintf(_('Could not save reply for %1$d, %2$d.'), $this->id, $mentioned->id));
1133 $replied[$mentioned->id] = 1;
1134 self::blow('reply:stream:%d', $mentioned->id);
1139 $recipientIds = array_keys($replied);
1141 return $recipientIds;
1145 * Pull the complete list of @-reply targets for this notice.
1147 * @return array of integer profile ids
1149 function getReplies()
1155 $reply = new Reply();
1156 $reply->selectAdd();
1157 $reply->selectAdd('profile_id');
1158 $reply->notice_id = $this->id;
1160 if ($reply->find()) {
1161 while($reply->fetch()) {
1162 $ids[] = $reply->profile_id;
1172 * Send e-mail notifications to local @-reply targets.
1174 * Replies must already have been saved; this is expected to be run
1175 * from the distrib queue handler.
1177 function sendReplyNotifications()
1179 // Don't send reply notifications for repeats
1181 if (!empty($this->repeat_of)) {
1185 $recipientIds = $this->getReplies();
1187 foreach ($recipientIds as $recipientId) {
1188 $user = User::staticGet('id', $recipientId);
1189 if (!empty($user)) {
1190 mail_notify_attn($user, $this);
1196 * Pull list of groups this notice needs to be delivered to,
1197 * as previously recorded by saveGroups() or saveKnownGroups().
1199 * @return array of Group objects
1201 function getGroups()
1203 // Don't save groups for repeats
1205 if (!empty($this->repeat_of)) {
1213 $gi = new Group_inbox();
1216 $gi->selectAdd('group_id');
1218 $gi->notice_id = $this->id;
1221 while ($gi->fetch()) {
1222 $group = User_group::staticGet('id', $gi->group_id);
1235 * Convert a notice into an activity for export.
1237 * @param User $cur Current user
1239 * @return Activity activity object representing this Notice.
1242 function asActivity()
1244 $act = self::cacheGet(Cache::codeKey('notice:as-activity:'.$this->id));
1250 $act = new Activity();
1252 if (Event::handle('StartNoticeAsActivity', array($this, &$act))) {
1254 $profile = $this->getProfile();
1256 $act->actor = ActivityObject::fromProfile($profile);
1257 $act->verb = ActivityVerb::POST;
1258 $act->objects[] = ActivityObject::fromNotice($this);
1260 // XXX: should this be handled by default processing for object entry?
1262 $act->time = strtotime($this->created);
1263 $act->link = $this->bestUrl();
1265 $act->content = common_xml_safe_str($this->rendered);
1266 $act->id = $this->uri;
1267 $act->title = common_xml_safe_str($this->content);
1271 $tags = $this->getTags();
1273 foreach ($tags as $tag) {
1274 $cat = new AtomCategory();
1277 $act->categories[] = $cat;
1281 // XXX: use Atom Media and/or File activity objects instead
1283 $attachments = $this->attachments();
1285 foreach ($attachments as $attachment) {
1286 $enclosure = $attachment->getEnclosure();
1288 $act->enclosures[] = $enclosure;
1292 $ctx = new ActivityContext();
1294 if (!empty($this->reply_to)) {
1295 $reply = Notice::staticGet('id', $this->reply_to);
1296 if (!empty($reply)) {
1297 $ctx->replyToID = $reply->uri;
1298 $ctx->replyToUrl = $reply->bestUrl();
1302 $ctx->location = $this->getLocation();
1306 if (!empty($this->conversation)) {
1307 $conv = Conversation::staticGet('id', $this->conversation);
1308 if (!empty($conv)) {
1309 $ctx->conversation = $conv->uri;
1313 $reply_ids = $this->getReplies();
1315 foreach ($reply_ids as $id) {
1316 $profile = Profile::staticGet('id', $id);
1317 if (!empty($profile)) {
1318 $ctx->attention[] = $profile->getUri();
1322 $groups = $this->getGroups();
1324 foreach ($groups as $group) {
1325 $ctx->attention[] = $group->uri;
1328 // XXX: deprecated; use ActivityVerb::SHARE instead
1332 if (!empty($this->repeat_of)) {
1333 $repeat = Notice::staticGet('id', $this->repeat_of);
1334 $ctx->forwardID = $repeat->uri;
1335 $ctx->forwardUrl = $repeat->bestUrl();
1338 $act->context = $ctx;
1342 $atom_feed = $profile->getAtomFeed();
1344 if (!empty($atom_feed)) {
1346 $act->source = new ActivitySource();
1348 // XXX: we should store the actual feed ID
1350 $act->source->id = $atom_feed;
1352 // XXX: we should store the actual feed title
1354 $act->source->title = $profile->getBestName();
1356 $act->source->links['alternate'] = $profile->profileurl;
1357 $act->source->links['self'] = $atom_feed;
1359 $act->source->icon = $profile->avatarUrl(AVATAR_PROFILE_SIZE);
1361 $notice = $profile->getCurrentNotice();
1363 if (!empty($notice)) {
1364 $act->source->updated = self::utcDate($notice->created);
1367 $user = User::staticGet('id', $profile->id);
1369 if (!empty($user)) {
1370 $act->source->links['license'] = common_config('license', 'url');
1374 if ($this->isLocal()) {
1375 $act->selfLink = common_local_url('ApiStatusesShow', array('id' => $this->id,
1376 'format' => 'atom'));
1377 $act->editLink = $act->selfLink;
1380 Event::handle('EndNoticeAsActivity', array($this, &$act));
1383 self::cacheSet(Cache::codeKey('notice:as-activity:'.$this->id), $act);
1388 // This has gotten way too long. Needs to be sliced up into functional bits
1389 // or ideally exported to a utility class.
1391 function asAtomEntry($namespace=false,
1396 $act = $this->asActivity();
1397 $act->extra[] = $this->noticeInfo($cur);
1398 return $act->asString($namespace, $author, $source);
1402 * Extra notice info for atom entries
1404 * Clients use some extra notice info in the atom stream.
1405 * This gives it to them.
1407 * @param User $cur Current user
1409 * @return array representation of <statusnet:notice_info> element
1412 function noticeInfo($cur)
1414 // local notice ID (useful to clients for ordering)
1416 $noticeInfoAttr = array('local_id' => $this->id);
1420 $ns = $this->getSource();
1423 $noticeInfoAttr['source'] = $ns->code;
1424 if (!empty($ns->url)) {
1425 $noticeInfoAttr['source_link'] = $ns->url;
1426 if (!empty($ns->name)) {
1427 $noticeInfoAttr['source'] = '<a href="'
1428 . htmlspecialchars($ns->url)
1429 . '" rel="nofollow">'
1430 . htmlspecialchars($ns->name)
1436 // favorite and repeated
1439 $noticeInfoAttr['favorite'] = ($cur->hasFave($this)) ? "true" : "false";
1440 $cp = $cur->getProfile();
1441 $noticeInfoAttr['repeated'] = ($cp->hasRepeated($this->id)) ? "true" : "false";
1444 if (!empty($this->repeat_of)) {
1445 $noticeInfoAttr['repeat_of'] = $this->repeat_of;
1448 return array('statusnet:notice_info', $noticeInfoAttr, null);
1452 * Returns an XML string fragment with a reference to a notice as an
1453 * Activity Streams noun object with the given element type.
1455 * Assumes that 'activity' namespace has been previously defined.
1457 * @param string $element one of 'subject', 'object', 'target'
1461 function asActivityNoun($element)
1463 $noun = ActivityObject::fromNotice($this);
1464 return $noun->asString('activity:' . $element);
1469 if (!empty($this->url)) {
1471 } else if (!empty($this->uri) && preg_match('/^https?:/', $this->uri)) {
1474 return common_local_url('shownotice',
1475 array('notice' => $this->id));
1479 function stream($fn, $args, $cachekey, $offset=0, $limit=20, $since_id=0, $max_id=0)
1481 $cache = common_memcache();
1483 if (empty($cache) ||
1484 $since_id != 0 || $max_id != 0 ||
1486 ($offset + $limit) > NOTICE_CACHE_WINDOW) {
1487 return call_user_func_array($fn, array_merge($args, array($offset, $limit, $since_id,
1491 $idkey = common_cache_key($cachekey);
1493 $idstr = $cache->get($idkey);
1495 if ($idstr !== false) {
1496 // Cache hit! Woohoo!
1497 $window = explode(',', $idstr);
1498 $ids = array_slice($window, $offset, $limit);
1502 $laststr = $cache->get($idkey.';last');
1504 if ($laststr !== false) {
1505 $window = explode(',', $laststr);
1506 $last_id = $window[0];
1507 $new_ids = call_user_func_array($fn, array_merge($args, array(0, NOTICE_CACHE_WINDOW,
1508 $last_id, 0, null)));
1510 $new_window = array_merge($new_ids, $window);
1512 $new_windowstr = implode(',', $new_window);
1514 $result = $cache->set($idkey, $new_windowstr);
1515 $result = $cache->set($idkey . ';last', $new_windowstr);
1517 $ids = array_slice($new_window, $offset, $limit);
1522 $window = call_user_func_array($fn, array_merge($args, array(0, NOTICE_CACHE_WINDOW,
1525 $windowstr = implode(',', $window);
1527 $result = $cache->set($idkey, $windowstr);
1528 $result = $cache->set($idkey . ';last', $windowstr);
1530 $ids = array_slice($window, $offset, $limit);
1536 * Determine which notice, if any, a new notice is in reply to.
1538 * For conversation tracking, we try to see where this notice fits
1539 * in the tree. Rough algorithm is:
1541 * if (reply_to is set and valid) {
1543 * } else if ((source not API or Web) and (content starts with "T NAME" or "@name ")) {
1544 * return ID of last notice by initial @name in content;
1547 * Note that all @nickname instances will still be used to save "reply" records,
1548 * so the notice shows up in the mentioned users' "replies" tab.
1550 * @param integer $reply_to ID passed in by Web or API
1551 * @param integer $profile_id ID of author
1552 * @param string $source Source tag, like 'web' or 'gwibber'
1553 * @param string $content Final notice content
1555 * @return integer ID of replied-to notice, or null for not a reply.
1558 static function getReplyTo($reply_to, $profile_id, $source, $content)
1560 static $lb = array('xmpp', 'mail', 'sms', 'omb');
1562 // If $reply_to is specified, we check that it exists, and then
1563 // return it if it does
1565 if (!empty($reply_to)) {
1566 $reply_notice = Notice::staticGet('id', $reply_to);
1567 if (!empty($reply_notice)) {
1572 // If it's not a "low bandwidth" source (one where you can't set
1573 // a reply_to argument), we return. This is mostly web and API
1576 if (!in_array($source, $lb)) {
1580 // Is there an initial @ or T?
1582 if (preg_match('/^T ([A-Z0-9]{1,64}) /', $content, $match) ||
1583 preg_match('/^@([a-z0-9]{1,64})\s+/', $content, $match)) {
1584 $nickname = common_canonical_nickname($match[1]);
1589 // Figure out who that is.
1591 $sender = Profile::staticGet('id', $profile_id);
1592 if (empty($sender)) {
1596 $recipient = common_relative_profile($sender, $nickname, common_sql_now());
1598 if (empty($recipient)) {
1602 // Get their last notice
1604 $last = $recipient->getCurrentNotice();
1606 if (!empty($last)) {
1611 static function maxContent()
1613 $contentlimit = common_config('notice', 'contentlimit');
1614 // null => use global limit (distinct from 0!)
1615 if (is_null($contentlimit)) {
1616 $contentlimit = common_config('site', 'textlimit');
1618 return $contentlimit;
1621 static function contentTooLong($content)
1623 $contentlimit = self::maxContent();
1624 return ($contentlimit > 0 && !empty($content) && (mb_strlen($content) > $contentlimit));
1627 function getLocation()
1631 if (!empty($this->location_id) && !empty($this->location_ns)) {
1632 $location = Location::fromId($this->location_id, $this->location_ns);
1635 if (is_null($location)) { // no ID, or Location::fromId() failed
1636 if (!empty($this->lat) && !empty($this->lon)) {
1637 $location = Location::fromLatLon($this->lat, $this->lon);
1644 function repeat($repeater_id, $source)
1646 $author = Profile::staticGet('id', $this->profile_id);
1648 // TRANS: Message used to repeat a notice. RT is the abbreviation of 'retweet'.
1649 // TRANS: %1$s is the repeated user's name, %2$s is the repeated notice.
1650 $content = sprintf(_('RT @%1$s %2$s'),
1654 $maxlen = common_config('site', 'textlimit');
1655 if ($maxlen > 0 && mb_strlen($content) > $maxlen) {
1656 // Web interface and current Twitter API clients will
1657 // pull the original notice's text, but some older
1658 // clients and RSS/Atom feeds will see this trimmed text.
1660 // Unfortunately this is likely to lose tags or URLs
1661 // at the end of long notices.
1662 $content = mb_substr($content, 0, $maxlen - 4) . ' ...';
1665 return self::saveNew($repeater_id, $content, $source,
1666 array('repeat_of' => $this->id));
1669 // These are supposed to be in chron order!
1671 function repeatStream($limit=100)
1673 $cache = common_memcache();
1675 if (empty($cache)) {
1676 $ids = $this->_repeatStreamDirect($limit);
1678 $idstr = $cache->get(common_cache_key('notice:repeats:'.$this->id));
1679 if ($idstr !== false) {
1680 $ids = explode(',', $idstr);
1682 $ids = $this->_repeatStreamDirect(100);
1683 $cache->set(common_cache_key('notice:repeats:'.$this->id), implode(',', $ids));
1686 // We do a max of 100, so slice down to limit
1687 $ids = array_slice($ids, 0, $limit);
1691 return Notice::getStreamByIds($ids);
1694 function _repeatStreamDirect($limit)
1696 $notice = new Notice();
1698 $notice->selectAdd(); // clears it
1699 $notice->selectAdd('id');
1701 $notice->repeat_of = $this->id;
1703 $notice->orderBy('created'); // NB: asc!
1705 if (!is_null($offset)) {
1706 $notice->limit($offset, $limit);
1711 if ($notice->find()) {
1712 while ($notice->fetch()) {
1713 $ids[] = $notice->id;
1723 function locationOptions($lat, $lon, $location_id, $location_ns, $profile = null)
1727 if (!empty($location_id) && !empty($location_ns)) {
1728 $options['location_id'] = $location_id;
1729 $options['location_ns'] = $location_ns;
1731 $location = Location::fromId($location_id, $location_ns);
1733 if (!empty($location)) {
1734 $options['lat'] = $location->lat;
1735 $options['lon'] = $location->lon;
1738 } else if (!empty($lat) && !empty($lon)) {
1739 $options['lat'] = $lat;
1740 $options['lon'] = $lon;
1742 $location = Location::fromLatLon($lat, $lon);
1744 if (!empty($location)) {
1745 $options['location_id'] = $location->location_id;
1746 $options['location_ns'] = $location->location_ns;
1748 } else if (!empty($profile)) {
1749 if (isset($profile->lat) && isset($profile->lon)) {
1750 $options['lat'] = $profile->lat;
1751 $options['lon'] = $profile->lon;
1754 if (isset($profile->location_id) && isset($profile->location_ns)) {
1755 $options['location_id'] = $profile->location_id;
1756 $options['location_ns'] = $profile->location_ns;
1763 function clearReplies()
1765 $replyNotice = new Notice();
1766 $replyNotice->reply_to = $this->id;
1768 //Null any notices that are replies to this notice
1770 if ($replyNotice->find()) {
1771 while ($replyNotice->fetch()) {
1772 $orig = clone($replyNotice);
1773 $replyNotice->reply_to = null;
1774 $replyNotice->update($orig);
1780 $reply = new Reply();
1781 $reply->notice_id = $this->id;
1783 if ($reply->find()) {
1784 while($reply->fetch()) {
1785 self::blow('reply:stream:%d', $reply->profile_id);
1793 function clearRepeats()
1795 $repeatNotice = new Notice();
1796 $repeatNotice->repeat_of = $this->id;
1798 //Null any notices that are repeats of this notice
1800 if ($repeatNotice->find()) {
1801 while ($repeatNotice->fetch()) {
1802 $orig = clone($repeatNotice);
1803 $repeatNotice->repeat_of = null;
1804 $repeatNotice->update($orig);
1809 function clearFaves()
1812 $fave->notice_id = $this->id;
1814 if ($fave->find()) {
1815 while ($fave->fetch()) {
1816 self::blow('fave:ids_by_user_own:%d', $fave->user_id);
1817 self::blow('fave:ids_by_user_own:%d;last', $fave->user_id);
1818 self::blow('fave:ids_by_user:%d', $fave->user_id);
1819 self::blow('fave:ids_by_user:%d;last', $fave->user_id);
1827 function clearTags()
1829 $tag = new Notice_tag();
1830 $tag->notice_id = $this->id;
1833 while ($tag->fetch()) {
1834 self::blow('profile:notice_ids_tagged:%d:%s', $this->profile_id, common_keyize($tag->tag));
1835 self::blow('profile:notice_ids_tagged:%d:%s;last', $this->profile_id, common_keyize($tag->tag));
1836 self::blow('notice_tag:notice_ids:%s', common_keyize($tag->tag));
1837 self::blow('notice_tag:notice_ids:%s;last', common_keyize($tag->tag));
1845 function clearGroupInboxes()
1847 $gi = new Group_inbox();
1849 $gi->notice_id = $this->id;
1852 while ($gi->fetch()) {
1853 self::blow('user_group:notice_ids:%d', $gi->group_id);
1861 function distribute()
1863 // We always insert for the author so they don't
1865 Event::handle('StartNoticeDistribute', array($this));
1867 $user = User::staticGet('id', $this->profile_id);
1868 if (!empty($user)) {
1869 Inbox::insertNotice($user->id, $this->id);
1872 if (common_config('queue', 'inboxes')) {
1873 // If there's a failure, we want to _force_
1874 // distribution at this point.
1876 $qm = QueueManager::get();
1877 $qm->enqueue($this, 'distrib');
1878 } catch (Exception $e) {
1879 // If the exception isn't transient, this
1880 // may throw more exceptions as DQH does
1881 // its own enqueueing. So, we ignore them!
1883 $handler = new DistribQueueHandler();
1884 $handler->handle($this);
1885 } catch (Exception $e) {
1886 common_log(LOG_ERR, "emergency redistribution resulted in " . $e->getMessage());
1888 // Re-throw so somebody smarter can handle it.
1892 $handler = new DistribQueueHandler();
1893 $handler->handle($this);
1899 $result = parent::insert();
1902 // Profile::hasRepeated() abuses pkeyGet(), so we
1903 // have to clear manually
1904 if (!empty($this->repeat_of)) {
1905 $c = self::memcache();
1907 $ck = self::multicacheKey('Notice',
1908 array('profile_id' => $this->profile_id,
1909 'repeat_of' => $this->repeat_of));
1919 * Get the source of the notice
1921 * @return Notice_source $ns A notice source object. 'code' is the only attribute
1922 * guaranteed to be populated.
1924 function getSource()
1926 $ns = new Notice_source();
1927 if (!empty($this->source)) {
1928 switch ($this->source) {
1935 $ns->code = $this->source;
1938 $ns = Notice_source::staticGet($this->source);
1940 $ns = new Notice_source();
1941 $ns->code = $this->source;
1942 $app = Oauth_application::staticGet('name', $this->source);
1944 $ns->name = $app->name;
1945 $ns->url = $app->source_url;
1955 * Determine whether the notice was locally created
1957 * @return boolean locality
1960 public function isLocal()
1962 return ($this->is_local == Notice::LOCAL_PUBLIC ||
1963 $this->is_local == Notice::LOCAL_NONPUBLIC);
1966 public function getTags()
1969 $tag = new Notice_tag();
1970 $tag->notice_id = $this->id;
1972 while ($tag->fetch()) {
1973 $tags[] = $tag->tag;
1980 static private function utcDate($dt)
1982 $dateStr = date('d F Y H:i:s', strtotime($dt));
1983 $d = new DateTime($dateStr, new DateTimeZone('UTC'));
1984 return $d->format(DATE_W3C);