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 * @fixme tag override
240 * @throws ClientException
242 static function saveNew($profile_id, $content, $source, $options=null) {
243 $defaults = array('uri' => null,
246 'repeat_of' => null);
248 if (!empty($options)) {
249 $options = $options + $defaults;
255 if (!isset($is_local)) {
256 $is_local = Notice::LOCAL_PUBLIC;
259 $profile = Profile::staticGet('id', $profile_id);
260 $user = User::staticGet('id', $profile_id);
262 // Use the local user's shortening preferences, if applicable.
263 $final = $user->shortenLinks($content);
265 $final = common_shorten_links($content);
268 if (Notice::contentTooLong($final)) {
269 // TRANS: Client exception thrown if a notice contains too many characters.
270 throw new ClientException(_('Problem saving notice. Too long.'));
273 if (empty($profile)) {
274 // TRANS: Client exception thrown when trying to save a notice for an unknown user.
275 throw new ClientException(_('Problem saving notice. Unknown user.'));
278 if (common_config('throttle', 'enabled') && !Notice::checkEditThrottle($profile_id)) {
279 common_log(LOG_WARNING, 'Excessive posting by profile #' . $profile_id . '; throttled.');
280 // TRANS: Client exception thrown when a user tries to post too many notices in a given time frame.
281 throw new ClientException(_('Too many notices too fast; take a breather '.
282 'and post again in a few minutes.'));
285 if (common_config('site', 'dupelimit') > 0 && !Notice::checkDupes($profile_id, $final)) {
286 common_log(LOG_WARNING, 'Dupe posting by profile #' . $profile_id . '; throttled.');
287 // TRANS: Client exception thrown when a user tries to post too many duplicate notices in a given time frame.
288 throw new ClientException(_('Too many duplicate messages too quickly;'.
289 ' take a breather and post again in a few minutes.'));
292 if (!$profile->hasRight(Right::NEWNOTICE)) {
293 common_log(LOG_WARNING, "Attempted post from user disallowed to post: " . $profile->nickname);
295 // TRANS: Client exception thrown when a user tries to post while being banned.
296 throw new ClientException(_('You are banned from posting notices on this site.'), 403);
299 $notice = new Notice();
300 $notice->profile_id = $profile_id;
302 $autosource = common_config('public', 'autosource');
304 # Sandboxed are non-false, but not 1, either
306 if (!$profile->hasRight(Right::PUBLICNOTICE) ||
307 ($source && $autosource && in_array($source, $autosource))) {
308 $notice->is_local = Notice::LOCAL_NONPUBLIC;
310 $notice->is_local = $is_local;
313 if (!empty($created)) {
314 $notice->created = $created;
316 $notice->created = common_sql_now();
319 $notice->content = $final;
321 $notice->source = $source;
325 // Handle repeat case
327 if (isset($repeat_of)) {
328 $notice->repeat_of = $repeat_of;
330 $notice->reply_to = self::getReplyTo($reply_to, $profile_id, $source, $final);
333 if (!empty($notice->reply_to)) {
334 $reply = Notice::staticGet('id', $notice->reply_to);
335 $notice->conversation = $reply->conversation;
338 if (!empty($lat) && !empty($lon)) {
343 if (!empty($location_ns) && !empty($location_id)) {
344 $notice->location_id = $location_id;
345 $notice->location_ns = $location_ns;
348 if (!empty($rendered)) {
349 $notice->rendered = $rendered;
351 $notice->rendered = common_render_content($final, $notice);
354 if (Event::handle('StartNoticeSave', array(&$notice))) {
356 // XXX: some of these functions write to the DB
358 $id = $notice->insert();
361 common_log_db_error($notice, 'INSERT', __FILE__);
362 // TRANS: Server exception thrown when a notice cannot be saved.
363 throw new ServerException(_('Problem saving notice.'));
366 // Update ID-dependent columns: URI, conversation
368 $orig = clone($notice);
373 $notice->uri = common_notice_uri($notice);
377 // If it's not part of a conversation, it's
378 // the beginning of a new conversation.
380 if (empty($notice->conversation)) {
381 $conv = Conversation::create();
382 $notice->conversation = $conv->id;
387 if (!$notice->update($orig)) {
388 common_log_db_error($notice, 'UPDATE', __FILE__);
389 // TRANS: Server exception thrown when a notice cannot be updated.
390 throw new ServerException(_('Problem saving notice.'));
396 # Clear the cache for subscribed users, so they'll update at next request
397 # XXX: someone clever could prepend instead of clearing the cache
399 $notice->blowOnInsert();
401 // Save per-notice metadata...
403 if (isset($replies)) {
404 $notice->saveKnownReplies($replies);
406 $notice->saveReplies();
410 $notice->saveKnownTags($tags);
415 // Note: groups may save tags, so must be run after tags are saved
416 // to avoid errors on duplicates.
417 if (isset($groups)) {
418 $notice->saveKnownGroups($groups);
420 $notice->saveGroups();
424 $notice->saveKnownUrls($urls);
429 // Prepare inbox delivery, may be queued to background.
430 $notice->distribute();
435 function blowOnInsert($conversation = false)
437 self::blow('profile:notice_ids:%d', $this->profile_id);
438 self::blow('public');
440 // XXX: Before we were blowing the casche only if the notice id
441 // was not the root of the conversation. What to do now?
443 self::blow('notice:conversation_ids:%d', $this->conversation);
445 if (!empty($this->repeat_of)) {
446 self::blow('notice:repeats:%d', $this->repeat_of);
449 $original = Notice::staticGet('id', $this->repeat_of);
451 if (!empty($original)) {
452 $originalUser = User::staticGet('id', $original->profile_id);
453 if (!empty($originalUser)) {
454 self::blow('user:repeats_of_me:%d', $originalUser->id);
458 $profile = Profile::staticGet($this->profile_id);
459 if (!empty($profile)) {
460 $profile->blowNoticeCount();
465 * Clear cache entries related to this notice at delete time.
466 * Necessary to avoid breaking paging on public, profile timelines.
468 function blowOnDelete()
470 $this->blowOnInsert();
472 self::blow('profile:notice_ids:%d;last', $this->profile_id);
473 self::blow('public;last');
476 /** save all urls in the notice to the db
478 * follow redirects and save all available file information
479 * (mimetype, date, size, oembed, etc.)
483 function saveUrls() {
484 if (common_config('attachments', 'process_links')) {
485 common_replace_urls_callback($this->content, array($this, 'saveUrl'), $this->id);
490 * Save the given URLs as related links/attachments to the db
492 * follow redirects and save all available file information
493 * (mimetype, date, size, oembed, etc.)
497 function saveKnownUrls($urls)
499 if (common_config('attachments', 'process_links')) {
500 // @fixme validation?
501 foreach (array_unique($urls) as $url) {
502 File::processNew($url, $this->id);
510 function saveUrl($url, $notice_id) {
511 File::processNew($url, $notice_id);
514 static function checkDupes($profile_id, $content) {
515 $profile = Profile::staticGet($profile_id);
516 if (empty($profile)) {
519 $notice = $profile->getNotices(0, NOTICE_CACHE_WINDOW);
520 if (!empty($notice)) {
522 while ($notice->fetch()) {
523 if (time() - strtotime($notice->created) >= common_config('site', 'dupelimit')) {
525 } else if ($notice->content == $content) {
530 # If we get here, oldest item in cache window is not
531 # old enough for dupe limit; do direct check against DB
532 $notice = new Notice();
533 $notice->profile_id = $profile_id;
534 $notice->content = $content;
535 $threshold = common_sql_date(time() - common_config('site', 'dupelimit'));
536 $notice->whereAdd(sprintf("created > '%s'", $notice->escape($threshold)));
538 $cnt = $notice->count();
542 static function checkEditThrottle($profile_id) {
543 $profile = Profile::staticGet($profile_id);
544 if (empty($profile)) {
548 $notice = $profile->getNotices(common_config('throttle', 'count') - 1, 1);
549 if ($notice && $notice->fetch()) {
550 # If the Nth notice was posted less than timespan seconds ago
551 if (time() - strtotime($notice->created) <= common_config('throttle', 'timespan')) {
556 # Either not N notices in the stream, OR the Nth was not posted within timespan seconds
560 function getUploadedAttachment() {
562 $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"';
563 $post->query($query);
565 if (empty($post->up) || empty($post->i)) {
568 $ret = array($post->up, $post->i);
574 function hasAttachments() {
576 $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);
577 $post->query($query);
579 $n_attachments = intval($post->n_attachments);
581 return $n_attachments;
584 function attachments() {
587 $f2p = new File_to_post;
588 $f2p->post_id = $this->id;
590 while ($f2p->fetch()) {
591 $f = File::staticGet($f2p->file_id);
600 function getStreamByIds($ids)
602 $cache = common_memcache();
604 if (!empty($cache)) {
606 foreach ($ids as $id) {
607 $n = Notice::staticGet('id', $id);
612 return new ArrayWrapper($notices);
614 $notice = new Notice();
616 //if no IDs requested, just return the notice object
619 $notice->whereAdd('id in (' . implode(', ', $ids) . ')');
625 while ($notice->fetch()) {
626 $temp[$notice->id] = clone($notice);
631 foreach ($ids as $id) {
632 if (array_key_exists($id, $temp)) {
633 $wrapped[] = $temp[$id];
637 return new ArrayWrapper($wrapped);
641 function publicStream($offset=0, $limit=20, $since_id=0, $max_id=0)
643 $ids = Notice::stream(array('Notice', '_publicStreamDirect'),
646 $offset, $limit, $since_id, $max_id);
647 return Notice::getStreamByIds($ids);
650 function _publicStreamDirect($offset=0, $limit=20, $since_id=0, $max_id=0)
652 $notice = new Notice();
654 $notice->selectAdd(); // clears it
655 $notice->selectAdd('id');
657 $notice->orderBy('id DESC');
659 if (!is_null($offset)) {
660 $notice->limit($offset, $limit);
663 if (common_config('public', 'localonly')) {
664 $notice->whereAdd('is_local = ' . Notice::LOCAL_PUBLIC);
666 # -1 == blacklisted, -2 == gateway (i.e. Twitter)
667 $notice->whereAdd('is_local !='. Notice::LOCAL_NONPUBLIC);
668 $notice->whereAdd('is_local !='. Notice::GATEWAY);
671 if ($since_id != 0) {
672 $notice->whereAdd('id > ' . $since_id);
676 $notice->whereAdd('id <= ' . $max_id);
681 if ($notice->find()) {
682 while ($notice->fetch()) {
683 $ids[] = $notice->id;
693 function conversationStream($id, $offset=0, $limit=20, $since_id=0, $max_id=0)
695 $ids = Notice::stream(array('Notice', '_conversationStreamDirect'),
697 'notice:conversation_ids:'.$id,
698 $offset, $limit, $since_id, $max_id);
700 return Notice::getStreamByIds($ids);
703 function _conversationStreamDirect($id, $offset=0, $limit=20, $since_id=0, $max_id=0)
705 $notice = new Notice();
707 $notice->selectAdd(); // clears it
708 $notice->selectAdd('id');
710 $notice->conversation = $id;
712 $notice->orderBy('id DESC');
714 if (!is_null($offset)) {
715 $notice->limit($offset, $limit);
718 if ($since_id != 0) {
719 $notice->whereAdd('id > ' . $since_id);
723 $notice->whereAdd('id <= ' . $max_id);
728 if ($notice->find()) {
729 while ($notice->fetch()) {
730 $ids[] = $notice->id;
741 * Is this notice part of an active conversation?
743 * @return boolean true if other messages exist in the same
744 * conversation, false if this is the only one
746 function hasConversation()
748 if (!empty($this->conversation)) {
749 $conversation = Notice::conversationStream(
755 if ($conversation->N > 0) {
763 * Pull up a full list of local recipients who will be getting
764 * this notice in their inbox. Results will be cached, so don't
765 * change the input data wily-nilly!
767 * @param array $groups optional list of Group objects;
768 * if left empty, will be loaded from group_inbox records
769 * @param array $recipient optional list of reply profile ids
770 * if left empty, will be loaded from reply records
771 * @return array associating recipient user IDs with an inbox source constant
773 function whoGets($groups=null, $recipients=null)
775 $c = self::memcache();
778 $ni = $c->get(common_cache_key('notice:who_gets:'.$this->id));
784 if (is_null($groups)) {
785 $groups = $this->getGroups();
788 if (is_null($recipients)) {
789 $recipients = $this->getReplies();
792 $users = $this->getSubscribedUsers();
794 // FIXME: kind of ignoring 'transitional'...
795 // we'll probably stop supporting inboxless mode
800 foreach ($users as $id) {
801 $ni[$id] = NOTICE_INBOX_SOURCE_SUB;
804 foreach ($groups as $group) {
805 $users = $group->getUserMembers();
806 foreach ($users as $id) {
807 if (!array_key_exists($id, $ni)) {
808 $ni[$id] = NOTICE_INBOX_SOURCE_GROUP;
813 foreach ($recipients as $recipient) {
814 if (!array_key_exists($recipient, $ni)) {
815 $ni[$recipient] = NOTICE_INBOX_SOURCE_REPLY;
819 // Exclude any deleted, non-local, or blocking recipients.
820 $profile = $this->getProfile();
821 foreach ($ni as $id => $source) {
822 $user = User::staticGet('id', $id);
823 if (empty($user) || $user->hasBlocked($profile)) {
829 // XXX: pack this data better
830 $c->set(common_cache_key('notice:who_gets:'.$this->id), $ni);
837 * Adds this notice to the inboxes of each local user who should receive
838 * it, based on author subscriptions, group memberships, and @-replies.
840 * Warning: running a second time currently will make items appear
841 * multiple times in users' inboxes.
843 * @fixme make more robust against errors
844 * @fixme break up massive deliveries to smaller background tasks
846 * @param array $groups optional list of Group objects;
847 * if left empty, will be loaded from group_inbox records
848 * @param array $recipient optional list of reply profile ids
849 * if left empty, will be loaded from reply records
851 function addToInboxes($groups=null, $recipients=null)
853 $ni = $this->whoGets($groups, $recipients);
855 $ids = array_keys($ni);
857 // We remove the author (if they're a local user),
858 // since we'll have already done this in distribute()
860 $i = array_search($this->profile_id, $ids);
868 Inbox::bulkInsert($this->id, $ids);
873 function getSubscribedUsers()
877 if(common_config('db','quote_identifiers'))
878 $user_table = '"user"';
879 else $user_table = 'user';
883 'FROM '. $user_table .' JOIN subscription '.
884 'ON '. $user_table .'.id = subscription.subscriber ' .
885 'WHERE subscription.subscribed = %d ';
887 $user->query(sprintf($qry, $this->profile_id));
891 while ($user->fetch()) {
901 * Record this notice to the given group inboxes for delivery.
902 * Overrides the regular parsing of !group markup.
904 * @param string $group_ids
905 * @fixme might prefer URIs as identifiers, as for replies?
906 * best with generalizations on user_group to support
907 * remote groups better.
909 function saveKnownGroups($group_ids)
911 if (!is_array($group_ids)) {
912 // TRANS: Server exception thrown when no array is provided to the method saveKnownGroups().
913 throw new ServerException(_('Bad type provided to saveKnownGroups.'));
917 foreach (array_unique($group_ids) as $id) {
918 $group = User_group::staticGet('id', $id);
920 common_log(LOG_ERR, "Local delivery to group id $id, $group->nickname");
921 $result = $this->addToGroupInbox($group);
923 common_log_db_error($gi, 'INSERT', __FILE__);
926 // @fixme should we save the tags here or not?
927 $groups[] = clone($group);
929 common_log(LOG_ERR, "Local delivery to group id $id skipped, doesn't exist");
937 * Parse !group delivery and record targets into group_inbox.
938 * @return array of Group objects
940 function saveGroups()
942 // Don't save groups for repeats
944 if (!empty($this->repeat_of)) {
950 /* extract all !group */
951 $count = preg_match_all('/(?:^|\s)!([A-Za-z0-9]{1,64})/',
952 strtolower($this->content),
958 $profile = $this->getProfile();
960 /* Add them to the database */
962 foreach (array_unique($match[1]) as $nickname) {
963 /* XXX: remote groups. */
964 $group = User_group::getForNickname($nickname, $profile);
970 // we automatically add a tag for every group name, too
972 $tag = Notice_tag::pkeyGet(array('tag' => common_canonical_tag($nickname),
973 'notice_id' => $this->id));
976 $this->saveTag($nickname);
979 if ($profile->isMember($group)) {
981 $result = $this->addToGroupInbox($group);
984 common_log_db_error($gi, 'INSERT', __FILE__);
987 $groups[] = clone($group);
994 function addToGroupInbox($group)
996 $gi = Group_inbox::pkeyGet(array('group_id' => $group->id,
997 'notice_id' => $this->id));
1001 $gi = new Group_inbox();
1003 $gi->group_id = $group->id;
1004 $gi->notice_id = $this->id;
1005 $gi->created = $this->created;
1007 $result = $gi->insert();
1010 common_log_db_error($gi, 'INSERT', __FILE__);
1011 // TRANS: Server exception thrown when an update for a group inbox fails.
1012 throw new ServerException(_('Problem saving group inbox.'));
1015 self::blow('user_group:notice_ids:%d', $gi->group_id);
1022 * Save reply records indicating that this notice needs to be
1023 * delivered to the local users with the given URIs.
1025 * Since this is expected to be used when saving foreign-sourced
1026 * messages, we won't deliver to any remote targets as that's the
1027 * source service's responsibility.
1029 * Mail notifications etc will be handled later.
1031 * @param array of unique identifier URIs for recipients
1033 function saveKnownReplies($uris)
1039 $sender = Profile::staticGet($this->profile_id);
1041 foreach (array_unique($uris) as $uri) {
1043 $profile = Profile::fromURI($uri);
1045 if (empty($profile)) {
1046 common_log(LOG_WARNING, "Unable to determine profile for URI '$uri'");
1050 if ($profile->hasBlocked($sender)) {
1051 common_log(LOG_INFO, "Not saving reply to profile {$profile->id} ($uri) from sender {$sender->id} because of a block.");
1055 $reply = new Reply();
1057 $reply->notice_id = $this->id;
1058 $reply->profile_id = $profile->id;
1060 common_log(LOG_INFO, __METHOD__ . ": saving reply: notice $this->id to profile $profile->id");
1062 $id = $reply->insert();
1069 * Pull @-replies from this message's content in StatusNet markup format
1070 * and save reply records indicating that this message needs to be
1071 * delivered to those users.
1073 * Mail notifications to local profiles will be sent later.
1075 * @return array of integer profile IDs
1078 function saveReplies()
1080 // Don't save reply data for repeats
1082 if (!empty($this->repeat_of)) {
1086 $sender = Profile::staticGet($this->profile_id);
1088 // @todo ideally this parser information would only
1089 // be calculated once.
1091 $mentions = common_find_mentions($this->content, $this);
1095 // store replied only for first @ (what user/notice what the reply directed,
1096 // we assume first @ is it)
1098 foreach ($mentions as $mention) {
1100 foreach ($mention['mentioned'] as $mentioned) {
1102 // skip if they're already covered
1104 if (!empty($replied[$mentioned->id])) {
1108 // Don't save replies from blocked profile to local user
1110 $mentioned_user = User::staticGet('id', $mentioned->id);
1111 if (!empty($mentioned_user) && $mentioned_user->hasBlocked($sender)) {
1115 $reply = new Reply();
1117 $reply->notice_id = $this->id;
1118 $reply->profile_id = $mentioned->id;
1120 $id = $reply->insert();
1123 common_log_db_error($reply, 'INSERT', __FILE__);
1124 // TRANS: Server exception thrown when a reply cannot be saved.
1125 // TRANS: %1$d is a notice ID, %2$d is the ID of the mentioned user.
1126 throw new ServerException(sprintf(_('Could not save reply for %1$d, %2$d.'), $this->id, $mentioned->id));
1128 $replied[$mentioned->id] = 1;
1129 self::blow('reply:stream:%d', $mentioned->id);
1134 $recipientIds = array_keys($replied);
1136 return $recipientIds;
1140 * Pull the complete list of @-reply targets for this notice.
1142 * @return array of integer profile ids
1144 function getReplies()
1150 $reply = new Reply();
1151 $reply->selectAdd();
1152 $reply->selectAdd('profile_id');
1153 $reply->notice_id = $this->id;
1155 if ($reply->find()) {
1156 while($reply->fetch()) {
1157 $ids[] = $reply->profile_id;
1167 * Send e-mail notifications to local @-reply targets.
1169 * Replies must already have been saved; this is expected to be run
1170 * from the distrib queue handler.
1172 function sendReplyNotifications()
1174 // Don't send reply notifications for repeats
1176 if (!empty($this->repeat_of)) {
1180 $recipientIds = $this->getReplies();
1182 foreach ($recipientIds as $recipientId) {
1183 $user = User::staticGet('id', $recipientId);
1184 if (!empty($user)) {
1185 mail_notify_attn($user, $this);
1191 * Pull list of groups this notice needs to be delivered to,
1192 * as previously recorded by saveGroups() or saveKnownGroups().
1194 * @return array of Group objects
1196 function getGroups()
1198 // Don't save groups for repeats
1200 if (!empty($this->repeat_of)) {
1208 $gi = new Group_inbox();
1211 $gi->selectAdd('group_id');
1213 $gi->notice_id = $this->id;
1216 while ($gi->fetch()) {
1217 $group = User_group::staticGet('id', $gi->group_id);
1230 * Convert a notice into an activity for export.
1232 * @param User $cur Current user
1234 * @return Activity activity object representing this Notice.
1237 function asActivity($cur = null, $source = false)
1239 $act = self::cacheGet(Cache::codeKey('notice:as-activity:'.$this->id));
1245 $act = new Activity();
1247 if (Event::handle('StartNoticeAsActivity', array($this, &$act))) {
1249 $profile = $this->getProfile();
1251 $act->actor = ActivityObject::fromProfile($profile);
1252 $act->verb = ActivityVerb::POST;
1253 $act->objects[] = ActivityObject::fromNotice($this);
1255 // XXX: should this be handled by default processing for object entry?
1257 $act->time = strtotime($this->created);
1258 $act->link = $this->bestUrl();
1260 $act->content = common_xml_safe_str($this->rendered);
1261 $act->id = $this->uri;
1262 $act->title = common_xml_safe_str($this->content);
1266 $tags = $this->getTags();
1268 foreach ($tags as $tag) {
1269 $cat = new AtomCategory();
1272 $act->categories[] = $cat;
1276 // XXX: use Atom Media and/or File activity objects instead
1278 $attachments = $this->attachments();
1280 foreach ($attachments as $attachment) {
1281 $enclosure = $attachment->getEnclosure();
1283 $act->enclosures[] = $enclosure;
1287 $ctx = new ActivityContext();
1289 if (!empty($this->reply_to)) {
1290 $reply = Notice::staticGet('id', $this->reply_to);
1291 if (!empty($reply)) {
1292 $ctx->replyToID = $reply->uri;
1293 $ctx->replyToUrl = $reply->bestUrl();
1297 $ctx->location = $this->getLocation();
1301 if (!empty($this->conversation)) {
1302 $conv = Conversation::staticGet('id', $this->conversation);
1303 if (!empty($conv)) {
1304 $ctx->conversation = $conv->uri;
1308 $reply_ids = $this->getReplies();
1310 foreach ($reply_ids as $id) {
1311 $profile = Profile::staticGet('id', $id);
1312 if (!empty($profile)) {
1313 $ctx->attention[] = $profile->getUri();
1317 $groups = $this->getGroups();
1319 foreach ($groups as $group) {
1320 $ctx->attention[] = $group->uri;
1323 // XXX: deprecated; use ActivityVerb::SHARE instead
1327 if (!empty($this->repeat_of)) {
1328 $repeat = Notice::staticGet('id', $this->repeat_of);
1329 $ctx->forwardID = $repeat->uri;
1330 $ctx->forwardUrl = $repeat->bestUrl();
1333 $act->context = $ctx;
1335 $noticeInfoAttr = array('local_id' => $this->id); // local notice ID (useful to clients for ordering)
1337 $ns = $this->getSource();
1340 $noticeInfoAttr['source'] = $ns->code;
1341 if (!empty($ns->url)) {
1342 $noticeInfoAttr['source_link'] = $ns->url;
1343 if (!empty($ns->name)) {
1344 $noticeInfoAttr['source'] = '<a href="'
1345 . htmlspecialchars($ns->url)
1346 . '" rel="nofollow">'
1347 . htmlspecialchars($ns->name)
1354 $noticeInfoAttr['favorite'] = ($cur->hasFave($this)) ? "true" : "false";
1355 $cp = $cur->getProfile();
1356 $noticeInfoAttr['repeated'] = ($cp->hasRepeated($this->id)) ? "true" : "false";
1359 if (!empty($this->repeat_of)) {
1360 $noticeInfoAttr['repeat_of'] = $this->repeat_of;
1363 $act->extra[] = array('statusnet:notice_info', $noticeInfoAttr, null);
1367 $atom_feed = $profile->getAtomFeed();
1369 if (!empty($atom_feed)) {
1371 $act->source = new ActivitySource();
1373 // XXX: we should store the actual feed ID
1375 $act->source->id = $atom_feed;
1377 // XXX: we should store the actual feed title
1379 $act->source->title = $profile->getBestName();
1381 $act->source->links['alternate'] = $profile->profileurl;
1382 $act->source->links['self'] = $atom_feed;
1384 $act->source->icon = $profile->avatarUrl(AVATAR_PROFILE_SIZE);
1386 $notice = $profile->getCurrentNotice();
1388 if (!empty($notice)) {
1389 $act->source->updated = self::utcDate($notice->created);
1392 $user = User::staticGet('id', $profile->id);
1394 if (!empty($user)) {
1395 $act->source->links['license'] = common_config('license', 'url');
1400 if ($this->isLocal()) {
1401 $act->selfLink = common_local_url('ApiStatusesShow', array('id' => $this->id,
1402 'format' => 'atom'));
1403 $act->editLink = $act->selfLink;
1406 Event::handle('EndNoticeAsActivity', array($this, &$act));
1409 self::cacheSet(Cache::codeKey('notice:as-activity:'.$this->id), $act);
1414 // This has gotten way too long. Needs to be sliced up into functional bits
1415 // or ideally exported to a utility class.
1417 function asAtomEntry($namespace=false, $source=false, $author=true, $cur=null)
1419 $act = $this->asActivity($cur, $source);
1420 return $act->asString($namespace, $author);
1425 * Returns an XML string fragment with a reference to a notice as an
1426 * Activity Streams noun object with the given element type.
1428 * Assumes that 'activity' namespace has been previously defined.
1430 * @param string $element one of 'subject', 'object', 'target'
1434 function asActivityNoun($element)
1436 $noun = ActivityObject::fromNotice($this);
1437 return $noun->asString('activity:' . $element);
1442 if (!empty($this->url)) {
1444 } else if (!empty($this->uri) && preg_match('/^https?:/', $this->uri)) {
1447 return common_local_url('shownotice',
1448 array('notice' => $this->id));
1452 function stream($fn, $args, $cachekey, $offset=0, $limit=20, $since_id=0, $max_id=0)
1454 $cache = common_memcache();
1456 if (empty($cache) ||
1457 $since_id != 0 || $max_id != 0 ||
1459 ($offset + $limit) > NOTICE_CACHE_WINDOW) {
1460 return call_user_func_array($fn, array_merge($args, array($offset, $limit, $since_id,
1464 $idkey = common_cache_key($cachekey);
1466 $idstr = $cache->get($idkey);
1468 if ($idstr !== false) {
1469 // Cache hit! Woohoo!
1470 $window = explode(',', $idstr);
1471 $ids = array_slice($window, $offset, $limit);
1475 $laststr = $cache->get($idkey.';last');
1477 if ($laststr !== false) {
1478 $window = explode(',', $laststr);
1479 $last_id = $window[0];
1480 $new_ids = call_user_func_array($fn, array_merge($args, array(0, NOTICE_CACHE_WINDOW,
1481 $last_id, 0, null)));
1483 $new_window = array_merge($new_ids, $window);
1485 $new_windowstr = implode(',', $new_window);
1487 $result = $cache->set($idkey, $new_windowstr);
1488 $result = $cache->set($idkey . ';last', $new_windowstr);
1490 $ids = array_slice($new_window, $offset, $limit);
1495 $window = call_user_func_array($fn, array_merge($args, array(0, NOTICE_CACHE_WINDOW,
1498 $windowstr = implode(',', $window);
1500 $result = $cache->set($idkey, $windowstr);
1501 $result = $cache->set($idkey . ';last', $windowstr);
1503 $ids = array_slice($window, $offset, $limit);
1509 * Determine which notice, if any, a new notice is in reply to.
1511 * For conversation tracking, we try to see where this notice fits
1512 * in the tree. Rough algorithm is:
1514 * if (reply_to is set and valid) {
1516 * } else if ((source not API or Web) and (content starts with "T NAME" or "@name ")) {
1517 * return ID of last notice by initial @name in content;
1520 * Note that all @nickname instances will still be used to save "reply" records,
1521 * so the notice shows up in the mentioned users' "replies" tab.
1523 * @param integer $reply_to ID passed in by Web or API
1524 * @param integer $profile_id ID of author
1525 * @param string $source Source tag, like 'web' or 'gwibber'
1526 * @param string $content Final notice content
1528 * @return integer ID of replied-to notice, or null for not a reply.
1531 static function getReplyTo($reply_to, $profile_id, $source, $content)
1533 static $lb = array('xmpp', 'mail', 'sms', 'omb');
1535 // If $reply_to is specified, we check that it exists, and then
1536 // return it if it does
1538 if (!empty($reply_to)) {
1539 $reply_notice = Notice::staticGet('id', $reply_to);
1540 if (!empty($reply_notice)) {
1545 // If it's not a "low bandwidth" source (one where you can't set
1546 // a reply_to argument), we return. This is mostly web and API
1549 if (!in_array($source, $lb)) {
1553 // Is there an initial @ or T?
1555 if (preg_match('/^T ([A-Z0-9]{1,64}) /', $content, $match) ||
1556 preg_match('/^@([a-z0-9]{1,64})\s+/', $content, $match)) {
1557 $nickname = common_canonical_nickname($match[1]);
1562 // Figure out who that is.
1564 $sender = Profile::staticGet('id', $profile_id);
1565 if (empty($sender)) {
1569 $recipient = common_relative_profile($sender, $nickname, common_sql_now());
1571 if (empty($recipient)) {
1575 // Get their last notice
1577 $last = $recipient->getCurrentNotice();
1579 if (!empty($last)) {
1584 static function maxContent()
1586 $contentlimit = common_config('notice', 'contentlimit');
1587 // null => use global limit (distinct from 0!)
1588 if (is_null($contentlimit)) {
1589 $contentlimit = common_config('site', 'textlimit');
1591 return $contentlimit;
1594 static function contentTooLong($content)
1596 $contentlimit = self::maxContent();
1597 return ($contentlimit > 0 && !empty($content) && (mb_strlen($content) > $contentlimit));
1600 function getLocation()
1604 if (!empty($this->location_id) && !empty($this->location_ns)) {
1605 $location = Location::fromId($this->location_id, $this->location_ns);
1608 if (is_null($location)) { // no ID, or Location::fromId() failed
1609 if (!empty($this->lat) && !empty($this->lon)) {
1610 $location = Location::fromLatLon($this->lat, $this->lon);
1617 function repeat($repeater_id, $source)
1619 $author = Profile::staticGet('id', $this->profile_id);
1621 // TRANS: Message used to repeat a notice. RT is the abbreviation of 'retweet'.
1622 // TRANS: %1$s is the repeated user's name, %2$s is the repeated notice.
1623 $content = sprintf(_('RT @%1$s %2$s'),
1627 $maxlen = common_config('site', 'textlimit');
1628 if ($maxlen > 0 && mb_strlen($content) > $maxlen) {
1629 // Web interface and current Twitter API clients will
1630 // pull the original notice's text, but some older
1631 // clients and RSS/Atom feeds will see this trimmed text.
1633 // Unfortunately this is likely to lose tags or URLs
1634 // at the end of long notices.
1635 $content = mb_substr($content, 0, $maxlen - 4) . ' ...';
1638 return self::saveNew($repeater_id, $content, $source,
1639 array('repeat_of' => $this->id));
1642 // These are supposed to be in chron order!
1644 function repeatStream($limit=100)
1646 $cache = common_memcache();
1648 if (empty($cache)) {
1649 $ids = $this->_repeatStreamDirect($limit);
1651 $idstr = $cache->get(common_cache_key('notice:repeats:'.$this->id));
1652 if ($idstr !== false) {
1653 $ids = explode(',', $idstr);
1655 $ids = $this->_repeatStreamDirect(100);
1656 $cache->set(common_cache_key('notice:repeats:'.$this->id), implode(',', $ids));
1659 // We do a max of 100, so slice down to limit
1660 $ids = array_slice($ids, 0, $limit);
1664 return Notice::getStreamByIds($ids);
1667 function _repeatStreamDirect($limit)
1669 $notice = new Notice();
1671 $notice->selectAdd(); // clears it
1672 $notice->selectAdd('id');
1674 $notice->repeat_of = $this->id;
1676 $notice->orderBy('created'); // NB: asc!
1678 if (!is_null($offset)) {
1679 $notice->limit($offset, $limit);
1684 if ($notice->find()) {
1685 while ($notice->fetch()) {
1686 $ids[] = $notice->id;
1696 function locationOptions($lat, $lon, $location_id, $location_ns, $profile = null)
1700 if (!empty($location_id) && !empty($location_ns)) {
1701 $options['location_id'] = $location_id;
1702 $options['location_ns'] = $location_ns;
1704 $location = Location::fromId($location_id, $location_ns);
1706 if (!empty($location)) {
1707 $options['lat'] = $location->lat;
1708 $options['lon'] = $location->lon;
1711 } else if (!empty($lat) && !empty($lon)) {
1712 $options['lat'] = $lat;
1713 $options['lon'] = $lon;
1715 $location = Location::fromLatLon($lat, $lon);
1717 if (!empty($location)) {
1718 $options['location_id'] = $location->location_id;
1719 $options['location_ns'] = $location->location_ns;
1721 } else if (!empty($profile)) {
1722 if (isset($profile->lat) && isset($profile->lon)) {
1723 $options['lat'] = $profile->lat;
1724 $options['lon'] = $profile->lon;
1727 if (isset($profile->location_id) && isset($profile->location_ns)) {
1728 $options['location_id'] = $profile->location_id;
1729 $options['location_ns'] = $profile->location_ns;
1736 function clearReplies()
1738 $replyNotice = new Notice();
1739 $replyNotice->reply_to = $this->id;
1741 //Null any notices that are replies to this notice
1743 if ($replyNotice->find()) {
1744 while ($replyNotice->fetch()) {
1745 $orig = clone($replyNotice);
1746 $replyNotice->reply_to = null;
1747 $replyNotice->update($orig);
1753 $reply = new Reply();
1754 $reply->notice_id = $this->id;
1756 if ($reply->find()) {
1757 while($reply->fetch()) {
1758 self::blow('reply:stream:%d', $reply->profile_id);
1766 function clearRepeats()
1768 $repeatNotice = new Notice();
1769 $repeatNotice->repeat_of = $this->id;
1771 //Null any notices that are repeats of this notice
1773 if ($repeatNotice->find()) {
1774 while ($repeatNotice->fetch()) {
1775 $orig = clone($repeatNotice);
1776 $repeatNotice->repeat_of = null;
1777 $repeatNotice->update($orig);
1782 function clearFaves()
1785 $fave->notice_id = $this->id;
1787 if ($fave->find()) {
1788 while ($fave->fetch()) {
1789 self::blow('fave:ids_by_user_own:%d', $fave->user_id);
1790 self::blow('fave:ids_by_user_own:%d;last', $fave->user_id);
1791 self::blow('fave:ids_by_user:%d', $fave->user_id);
1792 self::blow('fave:ids_by_user:%d;last', $fave->user_id);
1800 function clearTags()
1802 $tag = new Notice_tag();
1803 $tag->notice_id = $this->id;
1806 while ($tag->fetch()) {
1807 self::blow('profile:notice_ids_tagged:%d:%s', $this->profile_id, common_keyize($tag->tag));
1808 self::blow('profile:notice_ids_tagged:%d:%s;last', $this->profile_id, common_keyize($tag->tag));
1809 self::blow('notice_tag:notice_ids:%s', common_keyize($tag->tag));
1810 self::blow('notice_tag:notice_ids:%s;last', common_keyize($tag->tag));
1818 function clearGroupInboxes()
1820 $gi = new Group_inbox();
1822 $gi->notice_id = $this->id;
1825 while ($gi->fetch()) {
1826 self::blow('user_group:notice_ids:%d', $gi->group_id);
1834 function distribute()
1836 // We always insert for the author so they don't
1838 Event::handle('StartNoticeDistribute', array($this));
1840 $user = User::staticGet('id', $this->profile_id);
1841 if (!empty($user)) {
1842 Inbox::insertNotice($user->id, $this->id);
1845 if (common_config('queue', 'inboxes')) {
1846 // If there's a failure, we want to _force_
1847 // distribution at this point.
1849 $qm = QueueManager::get();
1850 $qm->enqueue($this, 'distrib');
1851 } catch (Exception $e) {
1852 // If the exception isn't transient, this
1853 // may throw more exceptions as DQH does
1854 // its own enqueueing. So, we ignore them!
1856 $handler = new DistribQueueHandler();
1857 $handler->handle($this);
1858 } catch (Exception $e) {
1859 common_log(LOG_ERR, "emergency redistribution resulted in " . $e->getMessage());
1861 // Re-throw so somebody smarter can handle it.
1865 $handler = new DistribQueueHandler();
1866 $handler->handle($this);
1872 $result = parent::insert();
1875 // Profile::hasRepeated() abuses pkeyGet(), so we
1876 // have to clear manually
1877 if (!empty($this->repeat_of)) {
1878 $c = self::memcache();
1880 $ck = self::multicacheKey('Notice',
1881 array('profile_id' => $this->profile_id,
1882 'repeat_of' => $this->repeat_of));
1892 * Get the source of the notice
1894 * @return Notice_source $ns A notice source object. 'code' is the only attribute
1895 * guaranteed to be populated.
1897 function getSource()
1899 $ns = new Notice_source();
1900 if (!empty($this->source)) {
1901 switch ($this->source) {
1908 $ns->code = $this->source;
1911 $ns = Notice_source::staticGet($this->source);
1913 $ns = new Notice_source();
1914 $ns->code = $this->source;
1915 $app = Oauth_application::staticGet('name', $this->source);
1917 $ns->name = $app->name;
1918 $ns->url = $app->source_url;
1928 * Determine whether the notice was locally created
1930 * @return boolean locality
1933 public function isLocal()
1935 return ($this->is_local == Notice::LOCAL_PUBLIC ||
1936 $this->is_local == Notice::LOCAL_NONPUBLIC);
1939 public function getTags()
1942 $tag = new Notice_tag();
1943 $tag->notice_id = $this->id;
1945 while ($tag->fetch()) {
1946 $tags[] = $tag->tag;
1953 static private function utcDate($dt)
1955 $dateStr = date('d F Y H:i:s', strtotime($dt));
1956 $d = new DateTime($dateStr, new DateTimeZone('UTC'));
1957 return $d->format(DATE_W3C);