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 throw new ServerException(sprintf(_('DB error inserting hashtag: %s'),
176 $last_error->message));
180 // if it's saved, blow its cache
181 $tag->blowCache(false);
185 * Save a new notice and push it out to subscribers' inboxes.
186 * Poster's permissions are checked before sending.
188 * @param int $profile_id Profile ID of the poster
189 * @param string $content source message text; links may be shortened
190 * per current user's preference
191 * @param string $source source key ('web', 'api', etc)
192 * @param array $options Associative array of optional properties:
193 * string 'created' timestamp of notice; defaults to now
194 * int 'is_local' source/gateway ID, one of:
195 * Notice::LOCAL_PUBLIC - Local, ok to appear in public timeline
196 * Notice::REMOTE_OMB - Sent from a remote OMB service;
197 * hide from public timeline but show in
198 * local "and friends" timelines
199 * Notice::LOCAL_NONPUBLIC - Local, but hide from public timeline
200 * Notice::GATEWAY - From another non-OMB service;
201 * will not appear in public views
202 * float 'lat' decimal latitude for geolocation
203 * float 'lon' decimal longitude for geolocation
204 * int 'location_id' geoname identifier
205 * int 'location_ns' geoname namespace to interpret location_id
206 * int 'reply_to'; notice ID this is a reply to
207 * int 'repeat_of'; notice ID this is a repeat of
208 * string 'uri' unique ID for notice; defaults to local notice URL
209 * string 'url' permalink to notice; defaults to local notice URL
210 * string 'rendered' rendered HTML version of content
211 * array 'replies' list of profile URIs for reply delivery in
212 * place of extracting @-replies from content.
213 * array 'groups' list of group IDs to deliver to, in place of
214 * extracting ! tags from content
215 * array 'tags' list of hashtag strings to save with the notice
216 * in place of extracting # tags from content
217 * array 'urls' list of attached/referred URLs to save with the
218 * notice in place of extracting links from content
219 * @fixme tag override
222 * @throws ClientException
224 static function saveNew($profile_id, $content, $source, $options=null) {
225 $defaults = array('uri' => null,
228 'repeat_of' => null);
230 if (!empty($options)) {
231 $options = $options + $defaults;
235 if (!isset($is_local)) {
236 $is_local = Notice::LOCAL_PUBLIC;
239 $profile = Profile::staticGet($profile_id);
241 $final = common_shorten_links($content);
243 if (Notice::contentTooLong($final)) {
244 throw new ClientException(_('Problem saving notice. Too long.'));
247 if (empty($profile)) {
248 throw new ClientException(_('Problem saving notice. Unknown user.'));
251 if (common_config('throttle', 'enabled') && !Notice::checkEditThrottle($profile_id)) {
252 common_log(LOG_WARNING, 'Excessive posting by profile #' . $profile_id . '; throttled.');
253 throw new ClientException(_('Too many notices too fast; take a breather '.
254 'and post again in a few minutes.'));
257 if (common_config('site', 'dupelimit') > 0 && !Notice::checkDupes($profile_id, $final)) {
258 common_log(LOG_WARNING, 'Dupe posting by profile #' . $profile_id . '; throttled.');
259 throw new ClientException(_('Too many duplicate messages too quickly;'.
260 ' take a breather and post again in a few minutes.'));
263 if (!$profile->hasRight(Right::NEWNOTICE)) {
264 common_log(LOG_WARNING, "Attempted post from user disallowed to post: " . $profile->nickname);
265 throw new ClientException(_('You are banned from posting notices on this site.'));
268 $notice = new Notice();
269 $notice->profile_id = $profile_id;
271 $autosource = common_config('public', 'autosource');
273 # Sandboxed are non-false, but not 1, either
275 if (!$profile->hasRight(Right::PUBLICNOTICE) ||
276 ($source && $autosource && in_array($source, $autosource))) {
277 $notice->is_local = Notice::LOCAL_NONPUBLIC;
279 $notice->is_local = $is_local;
282 if (!empty($created)) {
283 $notice->created = $created;
285 $notice->created = common_sql_now();
288 $notice->content = $final;
290 $notice->source = $source;
294 // Handle repeat case
296 if (isset($repeat_of)) {
297 $notice->repeat_of = $repeat_of;
299 $notice->reply_to = self::getReplyTo($reply_to, $profile_id, $source, $final);
302 if (!empty($notice->reply_to)) {
303 $reply = Notice::staticGet('id', $notice->reply_to);
304 $notice->conversation = $reply->conversation;
307 if (!empty($lat) && !empty($lon)) {
312 if (!empty($location_ns) && !empty($location_id)) {
313 $notice->location_id = $location_id;
314 $notice->location_ns = $location_ns;
317 if (!empty($rendered)) {
318 $notice->rendered = $rendered;
320 $notice->rendered = common_render_content($final, $notice);
323 if (Event::handle('StartNoticeSave', array(&$notice))) {
325 // XXX: some of these functions write to the DB
327 $id = $notice->insert();
330 common_log_db_error($notice, 'INSERT', __FILE__);
331 throw new ServerException(_('Problem saving notice.'));
334 // Update ID-dependent columns: URI, conversation
336 $orig = clone($notice);
341 $notice->uri = common_notice_uri($notice);
345 // If it's not part of a conversation, it's
346 // the beginning of a new conversation.
348 if (empty($notice->conversation)) {
349 $conv = Conversation::create();
350 $notice->conversation = $conv->id;
355 if (!$notice->update($orig)) {
356 common_log_db_error($notice, 'UPDATE', __FILE__);
357 throw new ServerException(_('Problem saving notice.'));
363 # Clear the cache for subscribed users, so they'll update at next request
364 # XXX: someone clever could prepend instead of clearing the cache
366 $notice->blowOnInsert();
368 // Save per-notice metadata...
370 if (isset($replies)) {
371 $notice->saveKnownReplies($replies);
373 $notice->saveReplies();
377 $notice->saveKnownTags($tags);
382 // Note: groups may save tags, so must be run after tags are saved
383 // to avoid errors on duplicates.
384 if (isset($groups)) {
385 $notice->saveKnownGroups($groups);
387 $notice->saveGroups();
391 $notice->saveKnownUrls($urls);
396 // Prepare inbox delivery, may be queued to background.
397 $notice->distribute();
402 function blowOnInsert($conversation = false)
404 self::blow('profile:notice_ids:%d', $this->profile_id);
405 self::blow('public');
407 // XXX: Before we were blowing the casche only if the notice id
408 // was not the root of the conversation. What to do now?
410 self::blow('notice:conversation_ids:%d', $this->conversation);
412 if (!empty($this->repeat_of)) {
413 self::blow('notice:repeats:%d', $this->repeat_of);
416 $original = Notice::staticGet('id', $this->repeat_of);
418 if (!empty($original)) {
419 $originalUser = User::staticGet('id', $original->profile_id);
420 if (!empty($originalUser)) {
421 self::blow('user:repeats_of_me:%d', $originalUser->id);
425 $profile = Profile::staticGet($this->profile_id);
426 if (!empty($profile)) {
427 $profile->blowNoticeCount();
432 * Clear cache entries related to this notice at delete time.
433 * Necessary to avoid breaking paging on public, profile timelines.
435 function blowOnDelete()
437 $this->blowOnInsert();
439 self::blow('profile:notice_ids:%d;last', $this->profile_id);
440 self::blow('public;last');
443 /** save all urls in the notice to the db
445 * follow redirects and save all available file information
446 * (mimetype, date, size, oembed, etc.)
450 function saveUrls() {
451 common_replace_urls_callback($this->content, array($this, 'saveUrl'), $this->id);
455 * Save the given URLs as related links/attachments to the db
457 * follow redirects and save all available file information
458 * (mimetype, date, size, oembed, etc.)
462 function saveKnownUrls($urls)
464 // @fixme validation?
465 foreach ($urls as $url) {
466 File::processNew($url, $this->id);
473 function saveUrl($data) {
474 list($url, $notice_id) = $data;
475 File::processNew($url, $notice_id);
478 static function checkDupes($profile_id, $content) {
479 $profile = Profile::staticGet($profile_id);
480 if (empty($profile)) {
483 $notice = $profile->getNotices(0, NOTICE_CACHE_WINDOW);
484 if (!empty($notice)) {
486 while ($notice->fetch()) {
487 if (time() - strtotime($notice->created) >= common_config('site', 'dupelimit')) {
489 } else if ($notice->content == $content) {
494 # If we get here, oldest item in cache window is not
495 # old enough for dupe limit; do direct check against DB
496 $notice = new Notice();
497 $notice->profile_id = $profile_id;
498 $notice->content = $content;
499 if (common_config('db','type') == 'pgsql')
500 $notice->whereAdd('extract(epoch from now() - created) < ' . common_config('site', 'dupelimit'));
502 $notice->whereAdd('now() - created < ' . common_config('site', 'dupelimit'));
504 $cnt = $notice->count();
508 static function checkEditThrottle($profile_id) {
509 $profile = Profile::staticGet($profile_id);
510 if (empty($profile)) {
514 $notice = $profile->getNotices(common_config('throttle', 'count') - 1, 1);
515 if ($notice && $notice->fetch()) {
516 # If the Nth notice was posted less than timespan seconds ago
517 if (time() - strtotime($notice->created) <= common_config('throttle', 'timespan')) {
522 # Either not N notices in the stream, OR the Nth was not posted within timespan seconds
526 function getUploadedAttachment() {
528 $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"';
529 $post->query($query);
531 if (empty($post->up) || empty($post->i)) {
534 $ret = array($post->up, $post->i);
540 function hasAttachments() {
542 $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);
543 $post->query($query);
545 $n_attachments = intval($post->n_attachments);
547 return $n_attachments;
550 function attachments() {
553 $f2p = new File_to_post;
554 $f2p->post_id = $this->id;
556 while ($f2p->fetch()) {
557 $f = File::staticGet($f2p->file_id);
564 function getStreamByIds($ids)
566 $cache = common_memcache();
568 if (!empty($cache)) {
570 foreach ($ids as $id) {
571 $n = Notice::staticGet('id', $id);
576 return new ArrayWrapper($notices);
578 $notice = new Notice();
580 //if no IDs requested, just return the notice object
583 $notice->whereAdd('id in (' . implode(', ', $ids) . ')');
589 while ($notice->fetch()) {
590 $temp[$notice->id] = clone($notice);
595 foreach ($ids as $id) {
596 if (array_key_exists($id, $temp)) {
597 $wrapped[] = $temp[$id];
601 return new ArrayWrapper($wrapped);
605 function publicStream($offset=0, $limit=20, $since_id=0, $max_id=0)
607 $ids = Notice::stream(array('Notice', '_publicStreamDirect'),
610 $offset, $limit, $since_id, $max_id);
611 return Notice::getStreamByIds($ids);
614 function _publicStreamDirect($offset=0, $limit=20, $since_id=0, $max_id=0)
616 $notice = new Notice();
618 $notice->selectAdd(); // clears it
619 $notice->selectAdd('id');
621 $notice->orderBy('id DESC');
623 if (!is_null($offset)) {
624 $notice->limit($offset, $limit);
627 if (common_config('public', 'localonly')) {
628 $notice->whereAdd('is_local = ' . Notice::LOCAL_PUBLIC);
630 # -1 == blacklisted, -2 == gateway (i.e. Twitter)
631 $notice->whereAdd('is_local !='. Notice::LOCAL_NONPUBLIC);
632 $notice->whereAdd('is_local !='. Notice::GATEWAY);
635 if ($since_id != 0) {
636 $notice->whereAdd('id > ' . $since_id);
640 $notice->whereAdd('id <= ' . $max_id);
645 if ($notice->find()) {
646 while ($notice->fetch()) {
647 $ids[] = $notice->id;
657 function conversationStream($id, $offset=0, $limit=20, $since_id=0, $max_id=0)
659 $ids = Notice::stream(array('Notice', '_conversationStreamDirect'),
661 'notice:conversation_ids:'.$id,
662 $offset, $limit, $since_id, $max_id);
664 return Notice::getStreamByIds($ids);
667 function _conversationStreamDirect($id, $offset=0, $limit=20, $since_id=0, $max_id=0)
669 $notice = new Notice();
671 $notice->selectAdd(); // clears it
672 $notice->selectAdd('id');
674 $notice->conversation = $id;
676 $notice->orderBy('id DESC');
678 if (!is_null($offset)) {
679 $notice->limit($offset, $limit);
682 if ($since_id != 0) {
683 $notice->whereAdd('id > ' . $since_id);
687 $notice->whereAdd('id <= ' . $max_id);
692 if ($notice->find()) {
693 while ($notice->fetch()) {
694 $ids[] = $notice->id;
705 * Is this notice part of an active conversation?
707 * @return boolean true if other messages exist in the same
708 * conversation, false if this is the only one
710 function hasConversation()
712 if (!empty($this->conversation)) {
713 $conversation = Notice::conversationStream(
718 if ($conversation->N > 0) {
726 * @param $groups array of Group *objects*
727 * @param $recipients array of profile *ids*
729 function whoGets($groups=null, $recipients=null)
731 $c = self::memcache();
734 $ni = $c->get(common_cache_key('notice:who_gets:'.$this->id));
740 if (is_null($groups)) {
741 $groups = $this->getGroups();
744 if (is_null($recipients)) {
745 $recipients = $this->getReplies();
748 $users = $this->getSubscribedUsers();
750 // FIXME: kind of ignoring 'transitional'...
751 // we'll probably stop supporting inboxless mode
756 foreach ($users as $id) {
757 $ni[$id] = NOTICE_INBOX_SOURCE_SUB;
760 $profile = $this->getProfile();
762 foreach ($groups as $group) {
763 $users = $group->getUserMembers();
764 foreach ($users as $id) {
765 if (!array_key_exists($id, $ni)) {
766 $user = User::staticGet('id', $id);
767 if (!$user->hasBlocked($profile)) {
768 $ni[$id] = NOTICE_INBOX_SOURCE_GROUP;
774 foreach ($recipients as $recipient) {
776 if (!array_key_exists($recipient, $ni)) {
777 $recipientUser = User::staticGet('id', $recipient);
778 if (!empty($recipientUser)) {
779 $ni[$recipient] = NOTICE_INBOX_SOURCE_REPLY;
785 // XXX: pack this data better
786 $c->set(common_cache_key('notice:who_gets:'.$this->id), $ni);
793 * Adds this notice to the inboxes of each local user who should receive
794 * it, based on author subscriptions, group memberships, and @-replies.
796 * Warning: running a second time currently will make items appear
797 * multiple times in users' inboxes.
799 * @fixme make more robust against errors
800 * @fixme break up massive deliveries to smaller background tasks
802 * @param array $groups optional list of Group objects;
803 * if left empty, will be loaded from group_inbox records
804 * @param array $recipient optional list of reply profile ids
805 * if left empty, will be loaded from reply records
807 function addToInboxes($groups=null, $recipients=null)
809 $ni = $this->whoGets($groups, $recipients);
811 $ids = array_keys($ni);
813 // We remove the author (if they're a local user),
814 // since we'll have already done this in distribute()
816 $i = array_search($this->profile_id, $ids);
824 Inbox::bulkInsert($this->id, $ids);
829 function getSubscribedUsers()
833 if(common_config('db','quote_identifiers'))
834 $user_table = '"user"';
835 else $user_table = 'user';
839 'FROM '. $user_table .' JOIN subscription '.
840 'ON '. $user_table .'.id = subscription.subscriber ' .
841 'WHERE subscription.subscribed = %d ';
843 $user->query(sprintf($qry, $this->profile_id));
847 while ($user->fetch()) {
857 * Record this notice to the given group inboxes for delivery.
858 * Overrides the regular parsing of !group markup.
860 * @param string $group_ids
861 * @fixme might prefer URIs as identifiers, as for replies?
862 * best with generalizations on user_group to support
863 * remote groups better.
865 function saveKnownGroups($group_ids)
867 if (!is_array($group_ids)) {
868 throw new ServerException("Bad type provided to saveKnownGroups");
872 foreach ($group_ids as $id) {
873 $group = User_group::staticGet('id', $id);
875 common_log(LOG_ERR, "Local delivery to group id $id, $group->nickname");
876 $result = $this->addToGroupInbox($group);
878 common_log_db_error($gi, 'INSERT', __FILE__);
881 // @fixme should we save the tags here or not?
882 $groups[] = clone($group);
884 common_log(LOG_ERR, "Local delivery to group id $id skipped, doesn't exist");
892 * Parse !group delivery and record targets into group_inbox.
893 * @return array of Group objects
895 function saveGroups()
897 // Don't save groups for repeats
899 if (!empty($this->repeat_of)) {
905 /* extract all !group */
906 $count = preg_match_all('/(?:^|\s)!([A-Za-z0-9]{1,64})/',
907 strtolower($this->content),
913 $profile = $this->getProfile();
915 /* Add them to the database */
917 foreach (array_unique($match[1]) as $nickname) {
918 /* XXX: remote groups. */
919 $group = User_group::getForNickname($nickname, $profile);
925 // we automatically add a tag for every group name, too
927 $tag = Notice_tag::pkeyGet(array('tag' => common_canonical_tag($nickname),
928 'notice_id' => $this->id));
931 $this->saveTag($nickname);
934 if ($profile->isMember($group)) {
936 $result = $this->addToGroupInbox($group);
939 common_log_db_error($gi, 'INSERT', __FILE__);
942 $groups[] = clone($group);
949 function addToGroupInbox($group)
951 $gi = Group_inbox::pkeyGet(array('group_id' => $group->id,
952 'notice_id' => $this->id));
956 $gi = new Group_inbox();
958 $gi->group_id = $group->id;
959 $gi->notice_id = $this->id;
960 $gi->created = $this->created;
962 $result = $gi->insert();
965 common_log_db_error($gi, 'INSERT', __FILE__);
966 throw new ServerException(_('Problem saving group inbox.'));
969 self::blow('user_group:notice_ids:%d', $gi->group_id);
976 * Save reply records indicating that this notice needs to be
977 * delivered to the local users with the given URIs.
979 * Since this is expected to be used when saving foreign-sourced
980 * messages, we won't deliver to any remote targets as that's the
981 * source service's responsibility.
983 * @fixme Unlike saveReplies() there's no mail notification here.
984 * Move that to distrib queue handler?
986 * @param array of unique identifier URIs for recipients
988 function saveKnownReplies($uris)
993 $sender = Profile::staticGet($this->profile_id);
995 foreach ($uris as $uri) {
997 $user = User::staticGet('uri', $uri);
1000 if ($user->hasBlocked($sender)) {
1004 $reply = new Reply();
1006 $reply->notice_id = $this->id;
1007 $reply->profile_id = $user->id;
1009 $id = $reply->insert();
1011 self::blow('reply:stream:%d', $user->id);
1019 * Pull @-replies from this message's content in StatusNet markup format
1020 * and save reply records indicating that this message needs to be
1021 * delivered to those users.
1023 * Side effect: local recipients get e-mail notifications here.
1024 * @fixme move mail notifications to distrib?
1026 * @return array of integer profile IDs
1029 function saveReplies()
1031 // Don't save reply data for repeats
1033 if (!empty($this->repeat_of)) {
1037 $sender = Profile::staticGet($this->profile_id);
1039 // @todo ideally this parser information would only
1040 // be calculated once.
1042 $mentions = common_find_mentions($this->content, $this);
1046 // store replied only for first @ (what user/notice what the reply directed,
1047 // we assume first @ is it)
1049 foreach ($mentions as $mention) {
1051 foreach ($mention['mentioned'] as $mentioned) {
1053 // skip if they're already covered
1055 if (!empty($replied[$mentioned->id])) {
1059 // Don't save replies from blocked profile to local user
1061 $mentioned_user = User::staticGet('id', $mentioned->id);
1062 if (!empty($mentioned_user) && $mentioned_user->hasBlocked($sender)) {
1066 $reply = new Reply();
1068 $reply->notice_id = $this->id;
1069 $reply->profile_id = $mentioned->id;
1071 $id = $reply->insert();
1074 common_log_db_error($reply, 'INSERT', __FILE__);
1075 throw new ServerException("Couldn't save reply for {$this->id}, {$mentioned->id}");
1077 $replied[$mentioned->id] = 1;
1082 $recipientIds = array_keys($replied);
1084 foreach ($recipientIds as $recipientId) {
1085 $user = User::staticGet('id', $recipientId);
1086 if (!empty($user)) {
1087 self::blow('reply:stream:%d', $reply->profile_id);
1088 mail_notify_attn($user, $this);
1092 return $recipientIds;
1095 function getReplies()
1101 $reply = new Reply();
1102 $reply->selectAdd();
1103 $reply->selectAdd('profile_id');
1104 $reply->notice_id = $this->id;
1106 if ($reply->find()) {
1107 while($reply->fetch()) {
1108 $ids[] = $reply->profile_id;
1118 * Pull list of groups this notice needs to be delivered to,
1119 * as previously recorded by saveGroups() or saveKnownGroups().
1121 * @return array of Group objects
1123 function getGroups()
1125 // Don't save groups for repeats
1127 if (!empty($this->repeat_of)) {
1135 $gi = new Group_inbox();
1138 $gi->selectAdd('group_id');
1140 $gi->notice_id = $this->id;
1143 while ($gi->fetch()) {
1144 $group = User_group::staticGet('id', $gi->group_id);
1156 function asAtomEntry($namespace=false, $source=false, $author=true)
1158 $profile = $this->getProfile();
1160 $xs = new XMLStringer(true);
1163 $attrs = array('xmlns' => 'http://www.w3.org/2005/Atom',
1164 'xmlns:thr' => 'http://purl.org/syndication/thread/1.0',
1165 'xmlns:georss' => 'http://www.georss.org/georss',
1166 'xmlns:activity' => 'http://activitystrea.ms/spec/1.0/',
1167 'xmlns:media' => 'http://purl.org/syndication/atommedia',
1168 'xmlns:poco' => 'http://portablecontacts.net/spec/1.0',
1169 'xmlns:ostatus' => 'http://ostatus.org/schema/1.0');
1174 $xs->elementStart('entry', $attrs);
1177 $xs->elementStart('source');
1178 $xs->element('id', null, $profile->profileurl);
1179 $xs->element('title', null, $profile->nickname . " - " . common_config('site', 'name'));
1180 $xs->element('link', array('href' => $profile->profileurl));
1181 $user = User::staticGet('id', $profile->id);
1182 if (!empty($user)) {
1183 $atom_feed = common_local_url('ApiTimelineUser',
1184 array('format' => 'atom',
1185 'id' => $profile->nickname));
1186 $xs->element('link', array('rel' => 'self',
1187 'type' => 'application/atom+xml',
1188 'href' => $profile->profileurl));
1189 $xs->element('link', array('rel' => 'license',
1190 'href' => common_config('license', 'url')));
1193 $xs->element('icon', null, $profile->avatarUrl(AVATAR_PROFILE_SIZE));
1194 $xs->element('updated', null, common_date_w3dtf($this->created));
1198 $xs->elementEnd('source');
1201 $xs->element('title', null, common_xml_safe_str($this->content));
1204 $xs->raw($profile->asAtomAuthor());
1205 $xs->raw($profile->asActivityActor());
1208 $xs->element('link', array('rel' => 'alternate',
1209 'type' => 'text/html',
1210 'href' => $this->bestUrl()));
1212 $xs->element('id', null, $this->uri);
1214 $xs->element('published', null, common_date_w3dtf($this->created));
1215 $xs->element('updated', null, common_date_w3dtf($this->created));
1217 if ($this->reply_to) {
1218 $reply_notice = Notice::staticGet('id', $this->reply_to);
1219 if (!empty($reply_notice)) {
1220 $xs->element('link', array('rel' => 'related',
1221 'href' => $reply_notice->bestUrl()));
1222 $xs->element('thr:in-reply-to',
1223 array('ref' => $reply_notice->uri,
1224 'href' => $reply_notice->bestUrl()));
1228 if (!empty($this->conversation)) {
1230 $conv = Conversation::staticGet('id', $this->conversation);
1232 if (!empty($conv)) {
1235 'rel' => 'ostatus:conversation',
1236 'href' => $conv->uri
1242 $reply_ids = $this->getReplies();
1244 foreach ($reply_ids as $id) {
1245 $profile = Profile::staticGet('id', $id);
1246 if (!empty($profile)) {
1249 'rel' => 'ostatus:attention',
1250 'href' => $profile->getUri()
1256 $groups = $this->getGroups();
1258 foreach ($groups as $group) {
1261 'rel' => 'ostatus:attention',
1262 'href' => $group->permalink()
1267 if (!empty($this->repeat_of)) {
1268 $repeat = Notice::staticGet('id', $this->repeat_of);
1269 if (!empty($repeat)) {
1272 array('ref' => $repeat->uri, 'href' => $repeat->bestUrl())
1279 array('type' => 'html'),
1280 common_xml_safe_str($this->rendered)
1283 $tag = new Notice_tag();
1284 $tag->notice_id = $this->id;
1286 while ($tag->fetch()) {
1287 $xs->element('category', array('term' => $tag->tag));
1293 $attachments = $this->attachments();
1295 foreach($attachments as $attachment){
1296 $enclosure=$attachment->getEnclosure();
1298 $attributes = array('rel'=>'enclosure','href'=>$enclosure->url,'type'=>$enclosure->mimetype,'length'=>$enclosure->size);
1299 if($enclosure->title){
1300 $attributes['title']=$enclosure->title;
1302 $xs->element('link', $attributes, null);
1307 if (!empty($this->lat) && !empty($this->lon)) {
1308 $xs->element('georss:point', null, $this->lat . ' ' . $this->lon);
1311 $xs->elementEnd('entry');
1313 return $xs->getString();
1317 * Returns an XML string fragment with a reference to a notice as an
1318 * Activity Streams noun object with the given element type.
1320 * Assumes that 'activity' namespace has been previously defined.
1322 * @param string $element one of 'subject', 'object', 'target'
1325 function asActivityNoun($element)
1327 $noun = ActivityObject::fromNotice($this);
1328 return $noun->asString('activity:' . $element);
1333 if (!empty($this->url)) {
1335 } else if (!empty($this->uri) && preg_match('/^https?:/', $this->uri)) {
1338 return common_local_url('shownotice',
1339 array('notice' => $this->id));
1343 function stream($fn, $args, $cachekey, $offset=0, $limit=20, $since_id=0, $max_id=0)
1345 $cache = common_memcache();
1347 if (empty($cache) ||
1348 $since_id != 0 || $max_id != 0 ||
1350 ($offset + $limit) > NOTICE_CACHE_WINDOW) {
1351 return call_user_func_array($fn, array_merge($args, array($offset, $limit, $since_id,
1355 $idkey = common_cache_key($cachekey);
1357 $idstr = $cache->get($idkey);
1359 if ($idstr !== false) {
1360 // Cache hit! Woohoo!
1361 $window = explode(',', $idstr);
1362 $ids = array_slice($window, $offset, $limit);
1366 $laststr = $cache->get($idkey.';last');
1368 if ($laststr !== false) {
1369 $window = explode(',', $laststr);
1370 $last_id = $window[0];
1371 $new_ids = call_user_func_array($fn, array_merge($args, array(0, NOTICE_CACHE_WINDOW,
1372 $last_id, 0, null)));
1374 $new_window = array_merge($new_ids, $window);
1376 $new_windowstr = implode(',', $new_window);
1378 $result = $cache->set($idkey, $new_windowstr);
1379 $result = $cache->set($idkey . ';last', $new_windowstr);
1381 $ids = array_slice($new_window, $offset, $limit);
1386 $window = call_user_func_array($fn, array_merge($args, array(0, NOTICE_CACHE_WINDOW,
1389 $windowstr = implode(',', $window);
1391 $result = $cache->set($idkey, $windowstr);
1392 $result = $cache->set($idkey . ';last', $windowstr);
1394 $ids = array_slice($window, $offset, $limit);
1400 * Determine which notice, if any, a new notice is in reply to.
1402 * For conversation tracking, we try to see where this notice fits
1403 * in the tree. Rough algorithm is:
1405 * if (reply_to is set and valid) {
1407 * } else if ((source not API or Web) and (content starts with "T NAME" or "@name ")) {
1408 * return ID of last notice by initial @name in content;
1411 * Note that all @nickname instances will still be used to save "reply" records,
1412 * so the notice shows up in the mentioned users' "replies" tab.
1414 * @param integer $reply_to ID passed in by Web or API
1415 * @param integer $profile_id ID of author
1416 * @param string $source Source tag, like 'web' or 'gwibber'
1417 * @param string $content Final notice content
1419 * @return integer ID of replied-to notice, or null for not a reply.
1422 static function getReplyTo($reply_to, $profile_id, $source, $content)
1424 static $lb = array('xmpp', 'mail', 'sms', 'omb');
1426 // If $reply_to is specified, we check that it exists, and then
1427 // return it if it does
1429 if (!empty($reply_to)) {
1430 $reply_notice = Notice::staticGet('id', $reply_to);
1431 if (!empty($reply_notice)) {
1436 // If it's not a "low bandwidth" source (one where you can't set
1437 // a reply_to argument), we return. This is mostly web and API
1440 if (!in_array($source, $lb)) {
1444 // Is there an initial @ or T?
1446 if (preg_match('/^T ([A-Z0-9]{1,64}) /', $content, $match) ||
1447 preg_match('/^@([a-z0-9]{1,64})\s+/', $content, $match)) {
1448 $nickname = common_canonical_nickname($match[1]);
1453 // Figure out who that is.
1455 $sender = Profile::staticGet('id', $profile_id);
1456 if (empty($sender)) {
1460 $recipient = common_relative_profile($sender, $nickname, common_sql_now());
1462 if (empty($recipient)) {
1466 // Get their last notice
1468 $last = $recipient->getCurrentNotice();
1470 if (!empty($last)) {
1475 static function maxContent()
1477 $contentlimit = common_config('notice', 'contentlimit');
1478 // null => use global limit (distinct from 0!)
1479 if (is_null($contentlimit)) {
1480 $contentlimit = common_config('site', 'textlimit');
1482 return $contentlimit;
1485 static function contentTooLong($content)
1487 $contentlimit = self::maxContent();
1488 return ($contentlimit > 0 && !empty($content) && (mb_strlen($content) > $contentlimit));
1491 function getLocation()
1495 if (!empty($this->location_id) && !empty($this->location_ns)) {
1496 $location = Location::fromId($this->location_id, $this->location_ns);
1499 if (is_null($location)) { // no ID, or Location::fromId() failed
1500 if (!empty($this->lat) && !empty($this->lon)) {
1501 $location = Location::fromLatLon($this->lat, $this->lon);
1508 function repeat($repeater_id, $source)
1510 $author = Profile::staticGet('id', $this->profile_id);
1512 $content = sprintf(_('RT @%1$s %2$s'),
1516 $maxlen = common_config('site', 'textlimit');
1517 if ($maxlen > 0 && mb_strlen($content) > $maxlen) {
1518 // Web interface and current Twitter API clients will
1519 // pull the original notice's text, but some older
1520 // clients and RSS/Atom feeds will see this trimmed text.
1522 // Unfortunately this is likely to lose tags or URLs
1523 // at the end of long notices.
1524 $content = mb_substr($content, 0, $maxlen - 4) . ' ...';
1527 return self::saveNew($repeater_id, $content, $source,
1528 array('repeat_of' => $this->id));
1531 // These are supposed to be in chron order!
1533 function repeatStream($limit=100)
1535 $cache = common_memcache();
1537 if (empty($cache)) {
1538 $ids = $this->_repeatStreamDirect($limit);
1540 $idstr = $cache->get(common_cache_key('notice:repeats:'.$this->id));
1541 if ($idstr !== false) {
1542 $ids = explode(',', $idstr);
1544 $ids = $this->_repeatStreamDirect(100);
1545 $cache->set(common_cache_key('notice:repeats:'.$this->id), implode(',', $ids));
1548 // We do a max of 100, so slice down to limit
1549 $ids = array_slice($ids, 0, $limit);
1553 return Notice::getStreamByIds($ids);
1556 function _repeatStreamDirect($limit)
1558 $notice = new Notice();
1560 $notice->selectAdd(); // clears it
1561 $notice->selectAdd('id');
1563 $notice->repeat_of = $this->id;
1565 $notice->orderBy('created'); // NB: asc!
1567 if (!is_null($offset)) {
1568 $notice->limit($offset, $limit);
1573 if ($notice->find()) {
1574 while ($notice->fetch()) {
1575 $ids[] = $notice->id;
1585 function locationOptions($lat, $lon, $location_id, $location_ns, $profile = null)
1589 if (!empty($location_id) && !empty($location_ns)) {
1591 $options['location_id'] = $location_id;
1592 $options['location_ns'] = $location_ns;
1594 $location = Location::fromId($location_id, $location_ns);
1596 if (!empty($location)) {
1597 $options['lat'] = $location->lat;
1598 $options['lon'] = $location->lon;
1601 } else if (!empty($lat) && !empty($lon)) {
1603 $options['lat'] = $lat;
1604 $options['lon'] = $lon;
1606 $location = Location::fromLatLon($lat, $lon);
1608 if (!empty($location)) {
1609 $options['location_id'] = $location->location_id;
1610 $options['location_ns'] = $location->location_ns;
1612 } else if (!empty($profile)) {
1614 if (isset($profile->lat) && isset($profile->lon)) {
1615 $options['lat'] = $profile->lat;
1616 $options['lon'] = $profile->lon;
1619 if (isset($profile->location_id) && isset($profile->location_ns)) {
1620 $options['location_id'] = $profile->location_id;
1621 $options['location_ns'] = $profile->location_ns;
1628 function clearReplies()
1630 $replyNotice = new Notice();
1631 $replyNotice->reply_to = $this->id;
1633 //Null any notices that are replies to this notice
1635 if ($replyNotice->find()) {
1636 while ($replyNotice->fetch()) {
1637 $orig = clone($replyNotice);
1638 $replyNotice->reply_to = null;
1639 $replyNotice->update($orig);
1645 $reply = new Reply();
1646 $reply->notice_id = $this->id;
1648 if ($reply->find()) {
1649 while($reply->fetch()) {
1650 self::blow('reply:stream:%d', $reply->profile_id);
1658 function clearRepeats()
1660 $repeatNotice = new Notice();
1661 $repeatNotice->repeat_of = $this->id;
1663 //Null any notices that are repeats of this notice
1665 if ($repeatNotice->find()) {
1666 while ($repeatNotice->fetch()) {
1667 $orig = clone($repeatNotice);
1668 $repeatNotice->repeat_of = null;
1669 $repeatNotice->update($orig);
1674 function clearFaves()
1677 $fave->notice_id = $this->id;
1679 if ($fave->find()) {
1680 while ($fave->fetch()) {
1681 self::blow('fave:ids_by_user_own:%d', $fave->user_id);
1682 self::blow('fave:ids_by_user_own:%d;last', $fave->user_id);
1683 self::blow('fave:ids_by_user:%d', $fave->user_id);
1684 self::blow('fave:ids_by_user:%d;last', $fave->user_id);
1692 function clearTags()
1694 $tag = new Notice_tag();
1695 $tag->notice_id = $this->id;
1698 while ($tag->fetch()) {
1699 self::blow('profile:notice_ids_tagged:%d:%s', $this->profile_id, common_keyize($tag->tag));
1700 self::blow('profile:notice_ids_tagged:%d:%s;last', $this->profile_id, common_keyize($tag->tag));
1701 self::blow('notice_tag:notice_ids:%s', common_keyize($tag->tag));
1702 self::blow('notice_tag:notice_ids:%s;last', common_keyize($tag->tag));
1710 function clearGroupInboxes()
1712 $gi = new Group_inbox();
1714 $gi->notice_id = $this->id;
1717 while ($gi->fetch()) {
1718 self::blow('user_group:notice_ids:%d', $gi->group_id);
1726 function distribute()
1728 // We always insert for the author so they don't
1731 $user = User::staticGet('id', $this->profile_id);
1732 if (!empty($user)) {
1733 Inbox::insertNotice($user->id, $this->id);
1736 if (common_config('queue', 'inboxes')) {
1737 // If there's a failure, we want to _force_
1738 // distribution at this point.
1740 $qm = QueueManager::get();
1741 $qm->enqueue($this, 'distrib');
1742 } catch (Exception $e) {
1743 // If the exception isn't transient, this
1744 // may throw more exceptions as DQH does
1745 // its own enqueueing. So, we ignore them!
1747 $handler = new DistribQueueHandler();
1748 $handler->handle($this);
1749 } catch (Exception $e) {
1750 common_log(LOG_ERR, "emergency redistribution resulted in " . $e->getMessage());
1752 // Re-throw so somebody smarter can handle it.
1756 $handler = new DistribQueueHandler();
1757 $handler->handle($this);
1763 $result = parent::insert();
1766 // Profile::hasRepeated() abuses pkeyGet(), so we
1767 // have to clear manually
1768 if (!empty($this->repeat_of)) {
1769 $c = self::memcache();
1771 $ck = self::multicacheKey('Notice',
1772 array('profile_id' => $this->profile_id,
1773 'repeat_of' => $this->repeat_of));