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 * @license GNU Affero General Public License http://www.gnu.org/licenses/
35 if (!defined('STATUSNET') && !defined('LACONICA')) {
40 * Table Definition for notice
42 require_once INSTALLDIR.'/classes/Memcached_DataObject.php';
44 /* We keep the first three 20-notice pages, plus one for pagination check,
45 * in the memcached cache. */
47 define('NOTICE_CACHE_WINDOW', 61);
49 define('MAX_BOXCARS', 128);
51 class Notice extends Memcached_DataObject
54 /* the code below is auto generated do not remove the above tag */
56 public $__table = 'notice'; // table name
57 public $id; // int(4) primary_key not_null
58 public $profile_id; // int(4) multiple_key not_null
59 public $uri; // varchar(255) unique_key
60 public $content; // text
61 public $rendered; // text
62 public $url; // varchar(255)
63 public $created; // datetime multiple_key not_null default_0000-00-00%2000%3A00%3A00
64 public $modified; // timestamp not_null default_CURRENT_TIMESTAMP
65 public $reply_to; // int(4)
66 public $is_local; // int(4)
67 public $source; // varchar(32)
68 public $conversation; // int(4)
69 public $lat; // decimal(10,7)
70 public $lon; // decimal(10,7)
71 public $location_id; // int(4)
72 public $location_ns; // int(4)
73 public $repeat_of; // int(4)
76 function staticGet($k,$v=NULL)
78 return Memcached_DataObject::staticGet('Notice',$k,$v);
81 /* the code above is auto generated do not remove the tag below */
85 const LOCAL_PUBLIC = 1;
87 const LOCAL_NONPUBLIC = -1;
92 return Profile::staticGet('id', $this->profile_id);
97 // For auditing purposes, save a record that the notice
100 $deleted = new Deleted_notice();
102 $deleted->id = $this->id;
103 $deleted->profile_id = $this->profile_id;
104 $deleted->uri = $this->uri;
105 $deleted->created = $this->created;
106 $deleted->deleted = common_sql_now();
110 // Clear related records
112 $this->clearReplies();
113 $this->clearRepeats();
116 $this->clearGroupInboxes();
118 // NOTE: we don't clear inboxes
119 // NOTE: we don't clear queue items
121 $result = parent::delete();
123 $this->blowOnDelete();
128 * Extract #hashtags from this notice's content and save them to the database.
132 /* extract all #hastags */
133 $count = preg_match_all('/(?:^|\s)#([\pL\pN_\-\.]{1,64})/', strtolower($this->content), $match);
138 /* Add them to the database */
139 return $this->saveKnownTags($match[1]);
143 * Record the given set of hash tags in the db for this notice.
144 * Given tag strings will be normalized and checked for dupes.
146 function saveKnownTags($hashtags)
148 //turn each into their canonical tag
149 //this is needed to remove dupes before saving e.g. #hash.tag = #hashtag
150 for($i=0; $i<count($hashtags); $i++) {
151 /* elide characters we don't want in the tag */
152 $hashtags[$i] = common_canonical_tag($hashtags[$i]);
155 foreach(array_unique($hashtags) as $hashtag) {
156 $this->saveTag($hashtag);
157 self::blow('profile:notice_ids_tagged:%d:%s', $this->profile_id, $hashtag);
163 * Record a single hash tag as associated with this notice.
164 * Tag format and uniqueness must be validated by caller.
166 function saveTag($hashtag)
168 $tag = new Notice_tag();
169 $tag->notice_id = $this->id;
170 $tag->tag = $hashtag;
171 $tag->created = $this->created;
172 $id = $tag->insert();
175 // TRANS: Server exception. %s are the error details.
176 throw new ServerException(sprintf(_('Database error inserting hashtag: %s'),
177 $last_error->message));
181 // if it's saved, blow its cache
182 $tag->blowCache(false);
186 * Save a new notice and push it out to subscribers' inboxes.
187 * Poster's permissions are checked before sending.
189 * @param int $profile_id Profile ID of the poster
190 * @param string $content source message text; links may be shortened
191 * per current user's preference
192 * @param string $source source key ('web', 'api', etc)
193 * @param array $options Associative array of optional properties:
194 * string 'created' timestamp of notice; defaults to now
195 * int 'is_local' source/gateway ID, one of:
196 * Notice::LOCAL_PUBLIC - Local, ok to appear in public timeline
197 * Notice::REMOTE_OMB - Sent from a remote OMB service;
198 * hide from public timeline but show in
199 * local "and friends" timelines
200 * Notice::LOCAL_NONPUBLIC - Local, but hide from public timeline
201 * Notice::GATEWAY - From another non-OMB service;
202 * will not appear in public views
203 * float 'lat' decimal latitude for geolocation
204 * float 'lon' decimal longitude for geolocation
205 * int 'location_id' geoname identifier
206 * int 'location_ns' geoname namespace to interpret location_id
207 * int 'reply_to'; notice ID this is a reply to
208 * int 'repeat_of'; notice ID this is a repeat of
209 * string 'uri' unique ID for notice; defaults to local notice URL
210 * string 'url' permalink to notice; defaults to local notice URL
211 * string 'rendered' rendered HTML version of content
212 * array 'replies' list of profile URIs for reply delivery in
213 * place of extracting @-replies from content.
214 * array 'groups' list of group IDs to deliver to, in place of
215 * extracting ! tags from content
216 * array 'tags' list of hashtag strings to save with the notice
217 * in place of extracting # tags from content
218 * array 'urls' list of attached/referred URLs to save with the
219 * notice in place of extracting links from content
220 * @fixme tag override
223 * @throws ClientException
225 static function saveNew($profile_id, $content, $source, $options=null) {
226 $defaults = array('uri' => null,
229 'repeat_of' => null);
231 if (!empty($options)) {
232 $options = $options + $defaults;
236 if (!isset($is_local)) {
237 $is_local = Notice::LOCAL_PUBLIC;
240 $profile = Profile::staticGet($profile_id);
242 $final = common_shorten_links($content);
244 if (Notice::contentTooLong($final)) {
245 throw new ClientException(_('Problem saving notice. Too long.'));
248 if (empty($profile)) {
249 throw new ClientException(_('Problem saving notice. Unknown user.'));
252 if (common_config('throttle', 'enabled') && !Notice::checkEditThrottle($profile_id)) {
253 common_log(LOG_WARNING, 'Excessive posting by profile #' . $profile_id . '; throttled.');
254 throw new ClientException(_('Too many notices too fast; take a breather '.
255 'and post again in a few minutes.'));
258 if (common_config('site', 'dupelimit') > 0 && !Notice::checkDupes($profile_id, $final)) {
259 common_log(LOG_WARNING, 'Dupe posting by profile #' . $profile_id . '; throttled.');
260 throw new ClientException(_('Too many duplicate messages too quickly;'.
261 ' take a breather and post again in a few minutes.'));
264 if (!$profile->hasRight(Right::NEWNOTICE)) {
265 common_log(LOG_WARNING, "Attempted post from user disallowed to post: " . $profile->nickname);
266 throw new ClientException(_('You are banned from posting notices on this site.'));
269 $notice = new Notice();
270 $notice->profile_id = $profile_id;
272 $autosource = common_config('public', 'autosource');
274 # Sandboxed are non-false, but not 1, either
276 if (!$profile->hasRight(Right::PUBLICNOTICE) ||
277 ($source && $autosource && in_array($source, $autosource))) {
278 $notice->is_local = Notice::LOCAL_NONPUBLIC;
280 $notice->is_local = $is_local;
283 if (!empty($created)) {
284 $notice->created = $created;
286 $notice->created = common_sql_now();
289 $notice->content = $final;
291 $notice->source = $source;
295 // Handle repeat case
297 if (isset($repeat_of)) {
298 $notice->repeat_of = $repeat_of;
300 $notice->reply_to = self::getReplyTo($reply_to, $profile_id, $source, $final);
303 if (!empty($notice->reply_to)) {
304 $reply = Notice::staticGet('id', $notice->reply_to);
305 $notice->conversation = $reply->conversation;
308 if (!empty($lat) && !empty($lon)) {
313 if (!empty($location_ns) && !empty($location_id)) {
314 $notice->location_id = $location_id;
315 $notice->location_ns = $location_ns;
318 if (!empty($rendered)) {
319 $notice->rendered = $rendered;
321 $notice->rendered = common_render_content($final, $notice);
324 if (Event::handle('StartNoticeSave', array(&$notice))) {
326 // XXX: some of these functions write to the DB
328 $id = $notice->insert();
331 common_log_db_error($notice, 'INSERT', __FILE__);
332 throw new ServerException(_('Problem saving notice.'));
335 // Update ID-dependent columns: URI, conversation
337 $orig = clone($notice);
342 $notice->uri = common_notice_uri($notice);
346 // If it's not part of a conversation, it's
347 // the beginning of a new conversation.
349 if (empty($notice->conversation)) {
350 $conv = Conversation::create();
351 $notice->conversation = $conv->id;
356 if (!$notice->update($orig)) {
357 common_log_db_error($notice, 'UPDATE', __FILE__);
358 throw new ServerException(_('Problem saving notice.'));
364 # Clear the cache for subscribed users, so they'll update at next request
365 # XXX: someone clever could prepend instead of clearing the cache
367 $notice->blowOnInsert();
369 // Save per-notice metadata...
371 if (isset($replies)) {
372 $notice->saveKnownReplies($replies);
374 $notice->saveReplies();
378 $notice->saveKnownTags($tags);
383 // Note: groups may save tags, so must be run after tags are saved
384 // to avoid errors on duplicates.
385 if (isset($groups)) {
386 $notice->saveKnownGroups($groups);
388 $notice->saveGroups();
392 $notice->saveKnownUrls($urls);
397 // Prepare inbox delivery, may be queued to background.
398 $notice->distribute();
403 function blowOnInsert($conversation = false)
405 self::blow('profile:notice_ids:%d', $this->profile_id);
406 self::blow('public');
408 // XXX: Before we were blowing the casche only if the notice id
409 // was not the root of the conversation. What to do now?
411 self::blow('notice:conversation_ids:%d', $this->conversation);
413 if (!empty($this->repeat_of)) {
414 self::blow('notice:repeats:%d', $this->repeat_of);
417 $original = Notice::staticGet('id', $this->repeat_of);
419 if (!empty($original)) {
420 $originalUser = User::staticGet('id', $original->profile_id);
421 if (!empty($originalUser)) {
422 self::blow('user:repeats_of_me:%d', $originalUser->id);
426 $profile = Profile::staticGet($this->profile_id);
427 if (!empty($profile)) {
428 $profile->blowNoticeCount();
433 * Clear cache entries related to this notice at delete time.
434 * Necessary to avoid breaking paging on public, profile timelines.
436 function blowOnDelete()
438 $this->blowOnInsert();
440 self::blow('profile:notice_ids:%d;last', $this->profile_id);
441 self::blow('public;last');
444 /** save all urls in the notice to the db
446 * follow redirects and save all available file information
447 * (mimetype, date, size, oembed, etc.)
451 function saveUrls() {
452 common_replace_urls_callback($this->content, array($this, 'saveUrl'), $this->id);
456 * Save the given URLs as related links/attachments to the db
458 * follow redirects and save all available file information
459 * (mimetype, date, size, oembed, etc.)
463 function saveKnownUrls($urls)
465 // @fixme validation?
466 foreach ($urls as $url) {
467 File::processNew($url, $this->id);
474 function saveUrl($data) {
475 list($url, $notice_id) = $data;
476 File::processNew($url, $notice_id);
479 static function checkDupes($profile_id, $content) {
480 $profile = Profile::staticGet($profile_id);
481 if (empty($profile)) {
484 $notice = $profile->getNotices(0, NOTICE_CACHE_WINDOW);
485 if (!empty($notice)) {
487 while ($notice->fetch()) {
488 if (time() - strtotime($notice->created) >= common_config('site', 'dupelimit')) {
490 } else if ($notice->content == $content) {
495 # If we get here, oldest item in cache window is not
496 # old enough for dupe limit; do direct check against DB
497 $notice = new Notice();
498 $notice->profile_id = $profile_id;
499 $notice->content = $content;
500 if (common_config('db','type') == 'pgsql')
501 $notice->whereAdd('extract(epoch from now() - created) < ' . common_config('site', 'dupelimit'));
503 $notice->whereAdd('now() - created < ' . common_config('site', 'dupelimit'));
505 $cnt = $notice->count();
509 static function checkEditThrottle($profile_id) {
510 $profile = Profile::staticGet($profile_id);
511 if (empty($profile)) {
515 $notice = $profile->getNotices(common_config('throttle', 'count') - 1, 1);
516 if ($notice && $notice->fetch()) {
517 # If the Nth notice was posted less than timespan seconds ago
518 if (time() - strtotime($notice->created) <= common_config('throttle', 'timespan')) {
523 # Either not N notices in the stream, OR the Nth was not posted within timespan seconds
527 function getUploadedAttachment() {
529 $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"';
530 $post->query($query);
532 if (empty($post->up) || empty($post->i)) {
535 $ret = array($post->up, $post->i);
541 function hasAttachments() {
543 $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);
544 $post->query($query);
546 $n_attachments = intval($post->n_attachments);
548 return $n_attachments;
551 function attachments() {
554 $f2p = new File_to_post;
555 $f2p->post_id = $this->id;
557 while ($f2p->fetch()) {
558 $f = File::staticGet($f2p->file_id);
565 function getStreamByIds($ids)
567 $cache = common_memcache();
569 if (!empty($cache)) {
571 foreach ($ids as $id) {
572 $n = Notice::staticGet('id', $id);
577 return new ArrayWrapper($notices);
579 $notice = new Notice();
581 //if no IDs requested, just return the notice object
584 $notice->whereAdd('id in (' . implode(', ', $ids) . ')');
590 while ($notice->fetch()) {
591 $temp[$notice->id] = clone($notice);
596 foreach ($ids as $id) {
597 if (array_key_exists($id, $temp)) {
598 $wrapped[] = $temp[$id];
602 return new ArrayWrapper($wrapped);
606 function publicStream($offset=0, $limit=20, $since_id=0, $max_id=0)
608 $ids = Notice::stream(array('Notice', '_publicStreamDirect'),
611 $offset, $limit, $since_id, $max_id);
612 return Notice::getStreamByIds($ids);
615 function _publicStreamDirect($offset=0, $limit=20, $since_id=0, $max_id=0)
617 $notice = new Notice();
619 $notice->selectAdd(); // clears it
620 $notice->selectAdd('id');
622 $notice->orderBy('id DESC');
624 if (!is_null($offset)) {
625 $notice->limit($offset, $limit);
628 if (common_config('public', 'localonly')) {
629 $notice->whereAdd('is_local = ' . Notice::LOCAL_PUBLIC);
631 # -1 == blacklisted, -2 == gateway (i.e. Twitter)
632 $notice->whereAdd('is_local !='. Notice::LOCAL_NONPUBLIC);
633 $notice->whereAdd('is_local !='. Notice::GATEWAY);
636 if ($since_id != 0) {
637 $notice->whereAdd('id > ' . $since_id);
641 $notice->whereAdd('id <= ' . $max_id);
646 if ($notice->find()) {
647 while ($notice->fetch()) {
648 $ids[] = $notice->id;
658 function conversationStream($id, $offset=0, $limit=20, $since_id=0, $max_id=0)
660 $ids = Notice::stream(array('Notice', '_conversationStreamDirect'),
662 'notice:conversation_ids:'.$id,
663 $offset, $limit, $since_id, $max_id);
665 return Notice::getStreamByIds($ids);
668 function _conversationStreamDirect($id, $offset=0, $limit=20, $since_id=0, $max_id=0)
670 $notice = new Notice();
672 $notice->selectAdd(); // clears it
673 $notice->selectAdd('id');
675 $notice->conversation = $id;
677 $notice->orderBy('id DESC');
679 if (!is_null($offset)) {
680 $notice->limit($offset, $limit);
683 if ($since_id != 0) {
684 $notice->whereAdd('id > ' . $since_id);
688 $notice->whereAdd('id <= ' . $max_id);
693 if ($notice->find()) {
694 while ($notice->fetch()) {
695 $ids[] = $notice->id;
706 * Is this notice part of an active conversation?
708 * @return boolean true if other messages exist in the same
709 * conversation, false if this is the only one
711 function hasConversation()
713 if (!empty($this->conversation)) {
714 $conversation = Notice::conversationStream(
719 if ($conversation->N > 0) {
727 * @param $groups array of Group *objects*
728 * @param $recipients array of profile *ids*
730 function whoGets($groups=null, $recipients=null)
732 $c = self::memcache();
735 $ni = $c->get(common_cache_key('notice:who_gets:'.$this->id));
741 if (is_null($groups)) {
742 $groups = $this->getGroups();
745 if (is_null($recipients)) {
746 $recipients = $this->getReplies();
749 $users = $this->getSubscribedUsers();
751 // FIXME: kind of ignoring 'transitional'...
752 // we'll probably stop supporting inboxless mode
757 foreach ($users as $id) {
758 $ni[$id] = NOTICE_INBOX_SOURCE_SUB;
761 $profile = $this->getProfile();
763 foreach ($groups as $group) {
764 $users = $group->getUserMembers();
765 foreach ($users as $id) {
766 if (!array_key_exists($id, $ni)) {
767 $user = User::staticGet('id', $id);
768 if (!$user->hasBlocked($profile)) {
769 $ni[$id] = NOTICE_INBOX_SOURCE_GROUP;
775 foreach ($recipients as $recipient) {
777 if (!array_key_exists($recipient, $ni)) {
778 $recipientUser = User::staticGet('id', $recipient);
779 if (!empty($recipientUser)) {
780 $ni[$recipient] = NOTICE_INBOX_SOURCE_REPLY;
786 // XXX: pack this data better
787 $c->set(common_cache_key('notice:who_gets:'.$this->id), $ni);
794 * Adds this notice to the inboxes of each local user who should receive
795 * it, based on author subscriptions, group memberships, and @-replies.
797 * Warning: running a second time currently will make items appear
798 * multiple times in users' inboxes.
800 * @fixme make more robust against errors
801 * @fixme break up massive deliveries to smaller background tasks
803 * @param array $groups optional list of Group objects;
804 * if left empty, will be loaded from group_inbox records
805 * @param array $recipient optional list of reply profile ids
806 * if left empty, will be loaded from reply records
808 function addToInboxes($groups=null, $recipients=null)
810 $ni = $this->whoGets($groups, $recipients);
812 $ids = array_keys($ni);
814 // We remove the author (if they're a local user),
815 // since we'll have already done this in distribute()
817 $i = array_search($this->profile_id, $ids);
825 Inbox::bulkInsert($this->id, $ids);
830 function getSubscribedUsers()
834 if(common_config('db','quote_identifiers'))
835 $user_table = '"user"';
836 else $user_table = 'user';
840 'FROM '. $user_table .' JOIN subscription '.
841 'ON '. $user_table .'.id = subscription.subscriber ' .
842 'WHERE subscription.subscribed = %d ';
844 $user->query(sprintf($qry, $this->profile_id));
848 while ($user->fetch()) {
858 * Record this notice to the given group inboxes for delivery.
859 * Overrides the regular parsing of !group markup.
861 * @param string $group_ids
862 * @fixme might prefer URIs as identifiers, as for replies?
863 * best with generalizations on user_group to support
864 * remote groups better.
866 function saveKnownGroups($group_ids)
868 if (!is_array($group_ids)) {
869 throw new ServerException("Bad type provided to saveKnownGroups");
873 foreach ($group_ids as $id) {
874 $group = User_group::staticGet('id', $id);
876 common_log(LOG_ERR, "Local delivery to group id $id, $group->nickname");
877 $result = $this->addToGroupInbox($group);
879 common_log_db_error($gi, 'INSERT', __FILE__);
882 // @fixme should we save the tags here or not?
883 $groups[] = clone($group);
885 common_log(LOG_ERR, "Local delivery to group id $id skipped, doesn't exist");
893 * Parse !group delivery and record targets into group_inbox.
894 * @return array of Group objects
896 function saveGroups()
898 // Don't save groups for repeats
900 if (!empty($this->repeat_of)) {
906 /* extract all !group */
907 $count = preg_match_all('/(?:^|\s)!([A-Za-z0-9]{1,64})/',
908 strtolower($this->content),
914 $profile = $this->getProfile();
916 /* Add them to the database */
918 foreach (array_unique($match[1]) as $nickname) {
919 /* XXX: remote groups. */
920 $group = User_group::getForNickname($nickname, $profile);
926 // we automatically add a tag for every group name, too
928 $tag = Notice_tag::pkeyGet(array('tag' => common_canonical_tag($nickname),
929 'notice_id' => $this->id));
932 $this->saveTag($nickname);
935 if ($profile->isMember($group)) {
937 $result = $this->addToGroupInbox($group);
940 common_log_db_error($gi, 'INSERT', __FILE__);
943 $groups[] = clone($group);
950 function addToGroupInbox($group)
952 $gi = Group_inbox::pkeyGet(array('group_id' => $group->id,
953 'notice_id' => $this->id));
957 $gi = new Group_inbox();
959 $gi->group_id = $group->id;
960 $gi->notice_id = $this->id;
961 $gi->created = $this->created;
963 $result = $gi->insert();
966 common_log_db_error($gi, 'INSERT', __FILE__);
967 throw new ServerException(_('Problem saving group inbox.'));
970 self::blow('user_group:notice_ids:%d', $gi->group_id);
977 * Save reply records indicating that this notice needs to be
978 * delivered to the local users with the given URIs.
980 * Since this is expected to be used when saving foreign-sourced
981 * messages, we won't deliver to any remote targets as that's the
982 * source service's responsibility.
984 * @fixme Unlike saveReplies() there's no mail notification here.
985 * Move that to distrib queue handler?
987 * @param array of unique identifier URIs for recipients
989 function saveKnownReplies($uris)
994 $sender = Profile::staticGet($this->profile_id);
996 foreach ($uris as $uri) {
998 $user = User::staticGet('uri', $uri);
1000 if (!empty($user)) {
1001 if ($user->hasBlocked($sender)) {
1005 $reply = new Reply();
1007 $reply->notice_id = $this->id;
1008 $reply->profile_id = $user->id;
1010 $id = $reply->insert();
1012 self::blow('reply:stream:%d', $user->id);
1020 * Pull @-replies from this message's content in StatusNet markup format
1021 * and save reply records indicating that this message needs to be
1022 * delivered to those users.
1024 * Side effect: local recipients get e-mail notifications here.
1025 * @fixme move mail notifications to distrib?
1027 * @return array of integer profile IDs
1030 function saveReplies()
1032 // Don't save reply data for repeats
1034 if (!empty($this->repeat_of)) {
1038 $sender = Profile::staticGet($this->profile_id);
1040 // @todo ideally this parser information would only
1041 // be calculated once.
1043 $mentions = common_find_mentions($this->content, $this);
1047 // store replied only for first @ (what user/notice what the reply directed,
1048 // we assume first @ is it)
1050 foreach ($mentions as $mention) {
1052 foreach ($mention['mentioned'] as $mentioned) {
1054 // skip if they're already covered
1056 if (!empty($replied[$mentioned->id])) {
1060 // Don't save replies from blocked profile to local user
1062 $mentioned_user = User::staticGet('id', $mentioned->id);
1063 if (!empty($mentioned_user) && $mentioned_user->hasBlocked($sender)) {
1067 $reply = new Reply();
1069 $reply->notice_id = $this->id;
1070 $reply->profile_id = $mentioned->id;
1072 $id = $reply->insert();
1075 common_log_db_error($reply, 'INSERT', __FILE__);
1076 throw new ServerException("Couldn't save reply for {$this->id}, {$mentioned->id}");
1078 $replied[$mentioned->id] = 1;
1083 $recipientIds = array_keys($replied);
1085 foreach ($recipientIds as $recipientId) {
1086 $user = User::staticGet('id', $recipientId);
1087 if (!empty($user)) {
1088 self::blow('reply:stream:%d', $reply->profile_id);
1089 mail_notify_attn($user, $this);
1093 return $recipientIds;
1096 function getReplies()
1102 $reply = new Reply();
1103 $reply->selectAdd();
1104 $reply->selectAdd('profile_id');
1105 $reply->notice_id = $this->id;
1107 if ($reply->find()) {
1108 while($reply->fetch()) {
1109 $ids[] = $reply->profile_id;
1119 * Pull list of groups this notice needs to be delivered to,
1120 * as previously recorded by saveGroups() or saveKnownGroups().
1122 * @return array of Group objects
1124 function getGroups()
1126 // Don't save groups for repeats
1128 if (!empty($this->repeat_of)) {
1136 $gi = new Group_inbox();
1139 $gi->selectAdd('group_id');
1141 $gi->notice_id = $this->id;
1144 while ($gi->fetch()) {
1145 $group = User_group::staticGet('id', $gi->group_id);
1157 function asAtomEntry($namespace=false, $source=false, $author=true)
1159 $profile = $this->getProfile();
1161 $xs = new XMLStringer(true);
1164 $attrs = array('xmlns' => 'http://www.w3.org/2005/Atom',
1165 'xmlns:thr' => 'http://purl.org/syndication/thread/1.0',
1166 'xmlns:georss' => 'http://www.georss.org/georss',
1167 'xmlns:activity' => 'http://activitystrea.ms/spec/1.0/',
1168 'xmlns:media' => 'http://purl.org/syndication/atommedia',
1169 'xmlns:poco' => 'http://portablecontacts.net/spec/1.0',
1170 'xmlns:ostatus' => 'http://ostatus.org/schema/1.0');
1175 $xs->elementStart('entry', $attrs);
1178 $xs->elementStart('source');
1179 $xs->element('id', null, $profile->profileurl);
1180 $xs->element('title', null, $profile->nickname . " - " . common_config('site', 'name'));
1181 $xs->element('link', array('href' => $profile->profileurl));
1182 $user = User::staticGet('id', $profile->id);
1183 if (!empty($user)) {
1184 $atom_feed = common_local_url('ApiTimelineUser',
1185 array('format' => 'atom',
1186 'id' => $profile->nickname));
1187 $xs->element('link', array('rel' => 'self',
1188 'type' => 'application/atom+xml',
1189 'href' => $profile->profileurl));
1190 $xs->element('link', array('rel' => 'license',
1191 'href' => common_config('license', 'url')));
1194 $xs->element('icon', null, $profile->avatarUrl(AVATAR_PROFILE_SIZE));
1195 $xs->element('updated', null, common_date_w3dtf($this->created));
1199 $xs->elementEnd('source');
1202 $xs->element('title', null, common_xml_safe_str($this->content));
1205 $xs->raw($profile->asAtomAuthor());
1206 $xs->raw($profile->asActivityActor());
1209 $xs->element('link', array('rel' => 'alternate',
1210 'type' => 'text/html',
1211 'href' => $this->bestUrl()));
1213 $xs->element('id', null, $this->uri);
1215 $xs->element('published', null, common_date_w3dtf($this->created));
1216 $xs->element('updated', null, common_date_w3dtf($this->created));
1218 if ($this->reply_to) {
1219 $reply_notice = Notice::staticGet('id', $this->reply_to);
1220 if (!empty($reply_notice)) {
1221 $xs->element('link', array('rel' => 'related',
1222 'href' => $reply_notice->bestUrl()));
1223 $xs->element('thr:in-reply-to',
1224 array('ref' => $reply_notice->uri,
1225 'href' => $reply_notice->bestUrl()));
1229 if (!empty($this->conversation)) {
1231 $conv = Conversation::staticGet('id', $this->conversation);
1233 if (!empty($conv)) {
1236 'rel' => 'ostatus:conversation',
1237 'href' => $conv->uri
1243 $reply_ids = $this->getReplies();
1245 foreach ($reply_ids as $id) {
1246 $profile = Profile::staticGet('id', $id);
1247 if (!empty($profile)) {
1250 'rel' => 'ostatus:attention',
1251 'href' => $profile->getUri()
1257 $groups = $this->getGroups();
1259 foreach ($groups as $group) {
1262 'rel' => 'ostatus:attention',
1263 'href' => $group->permalink()
1268 if (!empty($this->repeat_of)) {
1269 $repeat = Notice::staticGet('id', $this->repeat_of);
1270 if (!empty($repeat)) {
1273 array('ref' => $repeat->uri, 'href' => $repeat->bestUrl())
1280 array('type' => 'html'),
1281 common_xml_safe_str($this->rendered)
1284 $tag = new Notice_tag();
1285 $tag->notice_id = $this->id;
1287 while ($tag->fetch()) {
1288 $xs->element('category', array('term' => $tag->tag));
1294 $attachments = $this->attachments();
1296 foreach($attachments as $attachment){
1297 $enclosure=$attachment->getEnclosure();
1299 $attributes = array('rel'=>'enclosure','href'=>$enclosure->url,'type'=>$enclosure->mimetype,'length'=>$enclosure->size);
1300 if($enclosure->title){
1301 $attributes['title']=$enclosure->title;
1303 $xs->element('link', $attributes, null);
1308 if (!empty($this->lat) && !empty($this->lon)) {
1309 $xs->element('georss:point', null, $this->lat . ' ' . $this->lon);
1312 $xs->elementEnd('entry');
1314 return $xs->getString();
1318 * Returns an XML string fragment with a reference to a notice as an
1319 * Activity Streams noun object with the given element type.
1321 * Assumes that 'activity' namespace has been previously defined.
1323 * @param string $element one of 'subject', 'object', 'target'
1326 function asActivityNoun($element)
1328 $noun = ActivityObject::fromNotice($this);
1329 return $noun->asString('activity:' . $element);
1334 if (!empty($this->url)) {
1336 } else if (!empty($this->uri) && preg_match('/^https?:/', $this->uri)) {
1339 return common_local_url('shownotice',
1340 array('notice' => $this->id));
1344 function stream($fn, $args, $cachekey, $offset=0, $limit=20, $since_id=0, $max_id=0)
1346 $cache = common_memcache();
1348 if (empty($cache) ||
1349 $since_id != 0 || $max_id != 0 ||
1351 ($offset + $limit) > NOTICE_CACHE_WINDOW) {
1352 return call_user_func_array($fn, array_merge($args, array($offset, $limit, $since_id,
1356 $idkey = common_cache_key($cachekey);
1358 $idstr = $cache->get($idkey);
1360 if ($idstr !== false) {
1361 // Cache hit! Woohoo!
1362 $window = explode(',', $idstr);
1363 $ids = array_slice($window, $offset, $limit);
1367 $laststr = $cache->get($idkey.';last');
1369 if ($laststr !== false) {
1370 $window = explode(',', $laststr);
1371 $last_id = $window[0];
1372 $new_ids = call_user_func_array($fn, array_merge($args, array(0, NOTICE_CACHE_WINDOW,
1373 $last_id, 0, null)));
1375 $new_window = array_merge($new_ids, $window);
1377 $new_windowstr = implode(',', $new_window);
1379 $result = $cache->set($idkey, $new_windowstr);
1380 $result = $cache->set($idkey . ';last', $new_windowstr);
1382 $ids = array_slice($new_window, $offset, $limit);
1387 $window = call_user_func_array($fn, array_merge($args, array(0, NOTICE_CACHE_WINDOW,
1390 $windowstr = implode(',', $window);
1392 $result = $cache->set($idkey, $windowstr);
1393 $result = $cache->set($idkey . ';last', $windowstr);
1395 $ids = array_slice($window, $offset, $limit);
1401 * Determine which notice, if any, a new notice is in reply to.
1403 * For conversation tracking, we try to see where this notice fits
1404 * in the tree. Rough algorithm is:
1406 * if (reply_to is set and valid) {
1408 * } else if ((source not API or Web) and (content starts with "T NAME" or "@name ")) {
1409 * return ID of last notice by initial @name in content;
1412 * Note that all @nickname instances will still be used to save "reply" records,
1413 * so the notice shows up in the mentioned users' "replies" tab.
1415 * @param integer $reply_to ID passed in by Web or API
1416 * @param integer $profile_id ID of author
1417 * @param string $source Source tag, like 'web' or 'gwibber'
1418 * @param string $content Final notice content
1420 * @return integer ID of replied-to notice, or null for not a reply.
1423 static function getReplyTo($reply_to, $profile_id, $source, $content)
1425 static $lb = array('xmpp', 'mail', 'sms', 'omb');
1427 // If $reply_to is specified, we check that it exists, and then
1428 // return it if it does
1430 if (!empty($reply_to)) {
1431 $reply_notice = Notice::staticGet('id', $reply_to);
1432 if (!empty($reply_notice)) {
1437 // If it's not a "low bandwidth" source (one where you can't set
1438 // a reply_to argument), we return. This is mostly web and API
1441 if (!in_array($source, $lb)) {
1445 // Is there an initial @ or T?
1447 if (preg_match('/^T ([A-Z0-9]{1,64}) /', $content, $match) ||
1448 preg_match('/^@([a-z0-9]{1,64})\s+/', $content, $match)) {
1449 $nickname = common_canonical_nickname($match[1]);
1454 // Figure out who that is.
1456 $sender = Profile::staticGet('id', $profile_id);
1457 if (empty($sender)) {
1461 $recipient = common_relative_profile($sender, $nickname, common_sql_now());
1463 if (empty($recipient)) {
1467 // Get their last notice
1469 $last = $recipient->getCurrentNotice();
1471 if (!empty($last)) {
1476 static function maxContent()
1478 $contentlimit = common_config('notice', 'contentlimit');
1479 // null => use global limit (distinct from 0!)
1480 if (is_null($contentlimit)) {
1481 $contentlimit = common_config('site', 'textlimit');
1483 return $contentlimit;
1486 static function contentTooLong($content)
1488 $contentlimit = self::maxContent();
1489 return ($contentlimit > 0 && !empty($content) && (mb_strlen($content) > $contentlimit));
1492 function getLocation()
1496 if (!empty($this->location_id) && !empty($this->location_ns)) {
1497 $location = Location::fromId($this->location_id, $this->location_ns);
1500 if (is_null($location)) { // no ID, or Location::fromId() failed
1501 if (!empty($this->lat) && !empty($this->lon)) {
1502 $location = Location::fromLatLon($this->lat, $this->lon);
1509 function repeat($repeater_id, $source)
1511 $author = Profile::staticGet('id', $this->profile_id);
1513 // TRANS: Message used to repeat a notice. RT is the abbreviation of 'retweet'.
1514 // TRANS: %1$s is the repeated user's name, %2$s is the repeated notice.
1515 $content = sprintf(_('RT @%1$s %2$s'),
1519 $maxlen = common_config('site', 'textlimit');
1520 if ($maxlen > 0 && mb_strlen($content) > $maxlen) {
1521 // Web interface and current Twitter API clients will
1522 // pull the original notice's text, but some older
1523 // clients and RSS/Atom feeds will see this trimmed text.
1525 // Unfortunately this is likely to lose tags or URLs
1526 // at the end of long notices.
1527 $content = mb_substr($content, 0, $maxlen - 4) . ' ...';
1530 return self::saveNew($repeater_id, $content, $source,
1531 array('repeat_of' => $this->id));
1534 // These are supposed to be in chron order!
1536 function repeatStream($limit=100)
1538 $cache = common_memcache();
1540 if (empty($cache)) {
1541 $ids = $this->_repeatStreamDirect($limit);
1543 $idstr = $cache->get(common_cache_key('notice:repeats:'.$this->id));
1544 if ($idstr !== false) {
1545 $ids = explode(',', $idstr);
1547 $ids = $this->_repeatStreamDirect(100);
1548 $cache->set(common_cache_key('notice:repeats:'.$this->id), implode(',', $ids));
1551 // We do a max of 100, so slice down to limit
1552 $ids = array_slice($ids, 0, $limit);
1556 return Notice::getStreamByIds($ids);
1559 function _repeatStreamDirect($limit)
1561 $notice = new Notice();
1563 $notice->selectAdd(); // clears it
1564 $notice->selectAdd('id');
1566 $notice->repeat_of = $this->id;
1568 $notice->orderBy('created'); // NB: asc!
1570 if (!is_null($offset)) {
1571 $notice->limit($offset, $limit);
1576 if ($notice->find()) {
1577 while ($notice->fetch()) {
1578 $ids[] = $notice->id;
1588 function locationOptions($lat, $lon, $location_id, $location_ns, $profile = null)
1592 if (!empty($location_id) && !empty($location_ns)) {
1594 $options['location_id'] = $location_id;
1595 $options['location_ns'] = $location_ns;
1597 $location = Location::fromId($location_id, $location_ns);
1599 if (!empty($location)) {
1600 $options['lat'] = $location->lat;
1601 $options['lon'] = $location->lon;
1604 } else if (!empty($lat) && !empty($lon)) {
1606 $options['lat'] = $lat;
1607 $options['lon'] = $lon;
1609 $location = Location::fromLatLon($lat, $lon);
1611 if (!empty($location)) {
1612 $options['location_id'] = $location->location_id;
1613 $options['location_ns'] = $location->location_ns;
1615 } else if (!empty($profile)) {
1617 if (isset($profile->lat) && isset($profile->lon)) {
1618 $options['lat'] = $profile->lat;
1619 $options['lon'] = $profile->lon;
1622 if (isset($profile->location_id) && isset($profile->location_ns)) {
1623 $options['location_id'] = $profile->location_id;
1624 $options['location_ns'] = $profile->location_ns;
1631 function clearReplies()
1633 $replyNotice = new Notice();
1634 $replyNotice->reply_to = $this->id;
1636 //Null any notices that are replies to this notice
1638 if ($replyNotice->find()) {
1639 while ($replyNotice->fetch()) {
1640 $orig = clone($replyNotice);
1641 $replyNotice->reply_to = null;
1642 $replyNotice->update($orig);
1648 $reply = new Reply();
1649 $reply->notice_id = $this->id;
1651 if ($reply->find()) {
1652 while($reply->fetch()) {
1653 self::blow('reply:stream:%d', $reply->profile_id);
1661 function clearRepeats()
1663 $repeatNotice = new Notice();
1664 $repeatNotice->repeat_of = $this->id;
1666 //Null any notices that are repeats of this notice
1668 if ($repeatNotice->find()) {
1669 while ($repeatNotice->fetch()) {
1670 $orig = clone($repeatNotice);
1671 $repeatNotice->repeat_of = null;
1672 $repeatNotice->update($orig);
1677 function clearFaves()
1680 $fave->notice_id = $this->id;
1682 if ($fave->find()) {
1683 while ($fave->fetch()) {
1684 self::blow('fave:ids_by_user_own:%d', $fave->user_id);
1685 self::blow('fave:ids_by_user_own:%d;last', $fave->user_id);
1686 self::blow('fave:ids_by_user:%d', $fave->user_id);
1687 self::blow('fave:ids_by_user:%d;last', $fave->user_id);
1695 function clearTags()
1697 $tag = new Notice_tag();
1698 $tag->notice_id = $this->id;
1701 while ($tag->fetch()) {
1702 self::blow('profile:notice_ids_tagged:%d:%s', $this->profile_id, common_keyize($tag->tag));
1703 self::blow('profile:notice_ids_tagged:%d:%s;last', $this->profile_id, common_keyize($tag->tag));
1704 self::blow('notice_tag:notice_ids:%s', common_keyize($tag->tag));
1705 self::blow('notice_tag:notice_ids:%s;last', common_keyize($tag->tag));
1713 function clearGroupInboxes()
1715 $gi = new Group_inbox();
1717 $gi->notice_id = $this->id;
1720 while ($gi->fetch()) {
1721 self::blow('user_group:notice_ids:%d', $gi->group_id);
1729 function distribute()
1731 // We always insert for the author so they don't
1734 $user = User::staticGet('id', $this->profile_id);
1735 if (!empty($user)) {
1736 Inbox::insertNotice($user->id, $this->id);
1739 if (common_config('queue', 'inboxes')) {
1740 // If there's a failure, we want to _force_
1741 // distribution at this point.
1743 $qm = QueueManager::get();
1744 $qm->enqueue($this, 'distrib');
1745 } catch (Exception $e) {
1746 // If the exception isn't transient, this
1747 // may throw more exceptions as DQH does
1748 // its own enqueueing. So, we ignore them!
1750 $handler = new DistribQueueHandler();
1751 $handler->handle($this);
1752 } catch (Exception $e) {
1753 common_log(LOG_ERR, "emergency redistribution resulted in " . $e->getMessage());
1755 // Re-throw so somebody smarter can handle it.
1759 $handler = new DistribQueueHandler();
1760 $handler->handle($this);
1766 $result = parent::insert();
1769 // Profile::hasRepeated() abuses pkeyGet(), so we
1770 // have to clear manually
1771 if (!empty($this->repeat_of)) {
1772 $c = self::memcache();
1774 $ck = self::multicacheKey('Notice',
1775 array('profile_id' => $this->profile_id,
1776 'repeat_of' => $this->repeat_of));