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 // @fixme we have some cases where things get re-run and so the
102 $deleted = Deleted_notice::staticGet('id', $this->id);
104 $deleted = new Deleted_notice();
106 $deleted->id = $this->id;
107 $deleted->profile_id = $this->profile_id;
108 $deleted->uri = $this->uri;
109 $deleted->created = $this->created;
110 $deleted->deleted = common_sql_now();
115 // Clear related records
117 $this->clearReplies();
118 $this->clearRepeats();
121 $this->clearGroupInboxes();
123 // NOTE: we don't clear inboxes
124 // NOTE: we don't clear queue items
126 $result = parent::delete();
128 $this->blowOnDelete();
133 * Extract #hashtags from this notice's content and save them to the database.
137 /* extract all #hastags */
138 $count = preg_match_all('/(?:^|\s)#([\pL\pN_\-\.]{1,64})/', strtolower($this->content), $match);
143 /* Add them to the database */
144 return $this->saveKnownTags($match[1]);
148 * Record the given set of hash tags in the db for this notice.
149 * Given tag strings will be normalized and checked for dupes.
151 function saveKnownTags($hashtags)
153 //turn each into their canonical tag
154 //this is needed to remove dupes before saving e.g. #hash.tag = #hashtag
155 for($i=0; $i<count($hashtags); $i++) {
156 /* elide characters we don't want in the tag */
157 $hashtags[$i] = common_canonical_tag($hashtags[$i]);
160 foreach(array_unique($hashtags) as $hashtag) {
161 $this->saveTag($hashtag);
162 self::blow('profile:notice_ids_tagged:%d:%s', $this->profile_id, $hashtag);
168 * Record a single hash tag as associated with this notice.
169 * Tag format and uniqueness must be validated by caller.
171 function saveTag($hashtag)
173 $tag = new Notice_tag();
174 $tag->notice_id = $this->id;
175 $tag->tag = $hashtag;
176 $tag->created = $this->created;
177 $id = $tag->insert();
180 throw new ServerException(sprintf(_('DB error inserting hashtag: %s'),
181 $last_error->message));
185 // if it's saved, blow its cache
186 $tag->blowCache(false);
190 * Save a new notice and push it out to subscribers' inboxes.
191 * Poster's permissions are checked before sending.
193 * @param int $profile_id Profile ID of the poster
194 * @param string $content source message text; links may be shortened
195 * per current user's preference
196 * @param string $source source key ('web', 'api', etc)
197 * @param array $options Associative array of optional properties:
198 * string 'created' timestamp of notice; defaults to now
199 * int 'is_local' source/gateway ID, one of:
200 * Notice::LOCAL_PUBLIC - Local, ok to appear in public timeline
201 * Notice::REMOTE_OMB - Sent from a remote OMB service;
202 * hide from public timeline but show in
203 * local "and friends" timelines
204 * Notice::LOCAL_NONPUBLIC - Local, but hide from public timeline
205 * Notice::GATEWAY - From another non-OMB service;
206 * will not appear in public views
207 * float 'lat' decimal latitude for geolocation
208 * float 'lon' decimal longitude for geolocation
209 * int 'location_id' geoname identifier
210 * int 'location_ns' geoname namespace to interpret location_id
211 * int 'reply_to'; notice ID this is a reply to
212 * int 'repeat_of'; notice ID this is a repeat of
213 * string 'uri' unique ID for notice; defaults to local notice URL
214 * string 'url' permalink to notice; defaults to local notice URL
215 * string 'rendered' rendered HTML version of content
216 * array 'replies' list of profile URIs for reply delivery in
217 * place of extracting @-replies from content.
218 * array 'groups' list of group IDs to deliver to, in place of
219 * extracting ! tags from content
220 * array 'tags' list of hashtag strings to save with the notice
221 * in place of extracting # tags from content
222 * array 'urls' list of attached/referred URLs to save with the
223 * notice in place of extracting links from content
224 * @fixme tag override
227 * @throws ClientException
229 static function saveNew($profile_id, $content, $source, $options=null) {
230 $defaults = array('uri' => null,
233 'repeat_of' => null);
235 if (!empty($options)) {
236 $options = $options + $defaults;
240 if (!isset($is_local)) {
241 $is_local = Notice::LOCAL_PUBLIC;
244 $profile = Profile::staticGet($profile_id);
246 $final = common_shorten_links($content);
248 if (Notice::contentTooLong($final)) {
249 throw new ClientException(_('Problem saving notice. Too long.'));
252 if (empty($profile)) {
253 throw new ClientException(_('Problem saving notice. Unknown user.'));
256 if (common_config('throttle', 'enabled') && !Notice::checkEditThrottle($profile_id)) {
257 common_log(LOG_WARNING, 'Excessive posting by profile #' . $profile_id . '; throttled.');
258 throw new ClientException(_('Too many notices too fast; take a breather '.
259 'and post again in a few minutes.'));
262 if (common_config('site', 'dupelimit') > 0 && !Notice::checkDupes($profile_id, $final)) {
263 common_log(LOG_WARNING, 'Dupe posting by profile #' . $profile_id . '; throttled.');
264 throw new ClientException(_('Too many duplicate messages too quickly;'.
265 ' take a breather and post again in a few minutes.'));
268 if (!$profile->hasRight(Right::NEWNOTICE)) {
269 common_log(LOG_WARNING, "Attempted post from user disallowed to post: " . $profile->nickname);
270 throw new ClientException(_('You are banned from posting notices on this site.'));
273 $notice = new Notice();
274 $notice->profile_id = $profile_id;
276 $autosource = common_config('public', 'autosource');
278 # Sandboxed are non-false, but not 1, either
280 if (!$profile->hasRight(Right::PUBLICNOTICE) ||
281 ($source && $autosource && in_array($source, $autosource))) {
282 $notice->is_local = Notice::LOCAL_NONPUBLIC;
284 $notice->is_local = $is_local;
287 if (!empty($created)) {
288 $notice->created = $created;
290 $notice->created = common_sql_now();
293 $notice->content = $final;
295 $notice->source = $source;
299 // Handle repeat case
301 if (isset($repeat_of)) {
302 $notice->repeat_of = $repeat_of;
304 $notice->reply_to = self::getReplyTo($reply_to, $profile_id, $source, $final);
307 if (!empty($notice->reply_to)) {
308 $reply = Notice::staticGet('id', $notice->reply_to);
309 $notice->conversation = $reply->conversation;
312 if (!empty($lat) && !empty($lon)) {
317 if (!empty($location_ns) && !empty($location_id)) {
318 $notice->location_id = $location_id;
319 $notice->location_ns = $location_ns;
322 if (!empty($rendered)) {
323 $notice->rendered = $rendered;
325 $notice->rendered = common_render_content($final, $notice);
328 if (Event::handle('StartNoticeSave', array(&$notice))) {
330 // XXX: some of these functions write to the DB
332 $id = $notice->insert();
335 common_log_db_error($notice, 'INSERT', __FILE__);
336 throw new ServerException(_('Problem saving notice.'));
339 // Update ID-dependent columns: URI, conversation
341 $orig = clone($notice);
346 $notice->uri = common_notice_uri($notice);
350 // If it's not part of a conversation, it's
351 // the beginning of a new conversation.
353 if (empty($notice->conversation)) {
354 $conv = Conversation::create();
355 $notice->conversation = $conv->id;
360 if (!$notice->update($orig)) {
361 common_log_db_error($notice, 'UPDATE', __FILE__);
362 throw new ServerException(_('Problem saving notice.'));
368 # Clear the cache for subscribed users, so they'll update at next request
369 # XXX: someone clever could prepend instead of clearing the cache
371 $notice->blowOnInsert();
373 // Save per-notice metadata...
375 if (isset($replies)) {
376 $notice->saveKnownReplies($replies);
378 $notice->saveReplies();
382 $notice->saveKnownTags($tags);
387 // Note: groups may save tags, so must be run after tags are saved
388 // to avoid errors on duplicates.
389 if (isset($groups)) {
390 $notice->saveKnownGroups($groups);
392 $notice->saveGroups();
396 $notice->saveKnownUrls($urls);
401 // Prepare inbox delivery, may be queued to background.
402 $notice->distribute();
407 function blowOnInsert($conversation = false)
409 self::blow('profile:notice_ids:%d', $this->profile_id);
410 self::blow('public');
412 // XXX: Before we were blowing the casche only if the notice id
413 // was not the root of the conversation. What to do now?
415 self::blow('notice:conversation_ids:%d', $this->conversation);
417 if (!empty($this->repeat_of)) {
418 self::blow('notice:repeats:%d', $this->repeat_of);
421 $original = Notice::staticGet('id', $this->repeat_of);
423 if (!empty($original)) {
424 $originalUser = User::staticGet('id', $original->profile_id);
425 if (!empty($originalUser)) {
426 self::blow('user:repeats_of_me:%d', $originalUser->id);
430 $profile = Profile::staticGet($this->profile_id);
431 if (!empty($profile)) {
432 $profile->blowNoticeCount();
437 * Clear cache entries related to this notice at delete time.
438 * Necessary to avoid breaking paging on public, profile timelines.
440 function blowOnDelete()
442 $this->blowOnInsert();
444 self::blow('profile:notice_ids:%d;last', $this->profile_id);
445 self::blow('public;last');
448 /** save all urls in the notice to the db
450 * follow redirects and save all available file information
451 * (mimetype, date, size, oembed, etc.)
455 function saveUrls() {
456 common_replace_urls_callback($this->content, array($this, 'saveUrl'), $this->id);
460 * Save the given URLs as related links/attachments to the db
462 * follow redirects and save all available file information
463 * (mimetype, date, size, oembed, etc.)
467 function saveKnownUrls($urls)
469 // @fixme validation?
470 foreach ($urls as $url) {
471 File::processNew($url, $this->id);
478 function saveUrl($data) {
479 list($url, $notice_id) = $data;
480 File::processNew($url, $notice_id);
483 static function checkDupes($profile_id, $content) {
484 $profile = Profile::staticGet($profile_id);
485 if (empty($profile)) {
488 $notice = $profile->getNotices(0, NOTICE_CACHE_WINDOW);
489 if (!empty($notice)) {
491 while ($notice->fetch()) {
492 if (time() - strtotime($notice->created) >= common_config('site', 'dupelimit')) {
494 } else if ($notice->content == $content) {
499 # If we get here, oldest item in cache window is not
500 # old enough for dupe limit; do direct check against DB
501 $notice = new Notice();
502 $notice->profile_id = $profile_id;
503 $notice->content = $content;
504 if (common_config('db','type') == 'pgsql')
505 $notice->whereAdd('extract(epoch from now() - created) < ' . common_config('site', 'dupelimit'));
507 $notice->whereAdd('now() - created < ' . common_config('site', 'dupelimit'));
509 $cnt = $notice->count();
513 static function checkEditThrottle($profile_id) {
514 $profile = Profile::staticGet($profile_id);
515 if (empty($profile)) {
519 $notice = $profile->getNotices(common_config('throttle', 'count') - 1, 1);
520 if ($notice && $notice->fetch()) {
521 # If the Nth notice was posted less than timespan seconds ago
522 if (time() - strtotime($notice->created) <= common_config('throttle', 'timespan')) {
527 # Either not N notices in the stream, OR the Nth was not posted within timespan seconds
531 function getUploadedAttachment() {
533 $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"';
534 $post->query($query);
536 if (empty($post->up) || empty($post->i)) {
539 $ret = array($post->up, $post->i);
545 function hasAttachments() {
547 $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);
548 $post->query($query);
550 $n_attachments = intval($post->n_attachments);
552 return $n_attachments;
555 function attachments() {
558 $f2p = new File_to_post;
559 $f2p->post_id = $this->id;
561 while ($f2p->fetch()) {
562 $f = File::staticGet($f2p->file_id);
569 function getStreamByIds($ids)
571 $cache = common_memcache();
573 if (!empty($cache)) {
575 foreach ($ids as $id) {
576 $n = Notice::staticGet('id', $id);
581 return new ArrayWrapper($notices);
583 $notice = new Notice();
585 //if no IDs requested, just return the notice object
588 $notice->whereAdd('id in (' . implode(', ', $ids) . ')');
594 while ($notice->fetch()) {
595 $temp[$notice->id] = clone($notice);
600 foreach ($ids as $id) {
601 if (array_key_exists($id, $temp)) {
602 $wrapped[] = $temp[$id];
606 return new ArrayWrapper($wrapped);
610 function publicStream($offset=0, $limit=20, $since_id=0, $max_id=0)
612 $ids = Notice::stream(array('Notice', '_publicStreamDirect'),
615 $offset, $limit, $since_id, $max_id);
616 return Notice::getStreamByIds($ids);
619 function _publicStreamDirect($offset=0, $limit=20, $since_id=0, $max_id=0)
621 $notice = new Notice();
623 $notice->selectAdd(); // clears it
624 $notice->selectAdd('id');
626 $notice->orderBy('id DESC');
628 if (!is_null($offset)) {
629 $notice->limit($offset, $limit);
632 if (common_config('public', 'localonly')) {
633 $notice->whereAdd('is_local = ' . Notice::LOCAL_PUBLIC);
635 # -1 == blacklisted, -2 == gateway (i.e. Twitter)
636 $notice->whereAdd('is_local !='. Notice::LOCAL_NONPUBLIC);
637 $notice->whereAdd('is_local !='. Notice::GATEWAY);
640 if ($since_id != 0) {
641 $notice->whereAdd('id > ' . $since_id);
645 $notice->whereAdd('id <= ' . $max_id);
650 if ($notice->find()) {
651 while ($notice->fetch()) {
652 $ids[] = $notice->id;
662 function conversationStream($id, $offset=0, $limit=20, $since_id=0, $max_id=0)
664 $ids = Notice::stream(array('Notice', '_conversationStreamDirect'),
666 'notice:conversation_ids:'.$id,
667 $offset, $limit, $since_id, $max_id);
669 return Notice::getStreamByIds($ids);
672 function _conversationStreamDirect($id, $offset=0, $limit=20, $since_id=0, $max_id=0)
674 $notice = new Notice();
676 $notice->selectAdd(); // clears it
677 $notice->selectAdd('id');
679 $notice->conversation = $id;
681 $notice->orderBy('id DESC');
683 if (!is_null($offset)) {
684 $notice->limit($offset, $limit);
687 if ($since_id != 0) {
688 $notice->whereAdd('id > ' . $since_id);
692 $notice->whereAdd('id <= ' . $max_id);
697 if ($notice->find()) {
698 while ($notice->fetch()) {
699 $ids[] = $notice->id;
710 * Is this notice part of an active conversation?
712 * @return boolean true if other messages exist in the same
713 * conversation, false if this is the only one
715 function hasConversation()
717 if (!empty($this->conversation)) {
718 $conversation = Notice::conversationStream(
723 if ($conversation->N > 0) {
731 * @param $groups array of Group *objects*
732 * @param $recipients array of profile *ids*
734 function whoGets($groups=null, $recipients=null)
736 $c = self::memcache();
739 $ni = $c->get(common_cache_key('notice:who_gets:'.$this->id));
745 if (is_null($groups)) {
746 $groups = $this->getGroups();
749 if (is_null($recipients)) {
750 $recipients = $this->getReplies();
753 $users = $this->getSubscribedUsers();
755 // FIXME: kind of ignoring 'transitional'...
756 // we'll probably stop supporting inboxless mode
761 foreach ($users as $id) {
762 $ni[$id] = NOTICE_INBOX_SOURCE_SUB;
765 $profile = $this->getProfile();
767 foreach ($groups as $group) {
768 $users = $group->getUserMembers();
769 foreach ($users as $id) {
770 if (!array_key_exists($id, $ni)) {
771 $user = User::staticGet('id', $id);
772 if (!$user->hasBlocked($profile)) {
773 $ni[$id] = NOTICE_INBOX_SOURCE_GROUP;
779 foreach ($recipients as $recipient) {
781 if (!array_key_exists($recipient, $ni)) {
782 $recipientUser = User::staticGet('id', $recipient);
783 if (!empty($recipientUser)) {
784 $ni[$recipient] = NOTICE_INBOX_SOURCE_REPLY;
790 // XXX: pack this data better
791 $c->set(common_cache_key('notice:who_gets:'.$this->id), $ni);
798 * Adds this notice to the inboxes of each local user who should receive
799 * it, based on author subscriptions, group memberships, and @-replies.
801 * Warning: running a second time currently will make items appear
802 * multiple times in users' inboxes.
804 * @fixme make more robust against errors
805 * @fixme break up massive deliveries to smaller background tasks
807 * @param array $groups optional list of Group objects;
808 * if left empty, will be loaded from group_inbox records
809 * @param array $recipient optional list of reply profile ids
810 * if left empty, will be loaded from reply records
812 function addToInboxes($groups=null, $recipients=null)
814 $ni = $this->whoGets($groups, $recipients);
816 $ids = array_keys($ni);
818 // We remove the author (if they're a local user),
819 // since we'll have already done this in distribute()
821 $i = array_search($this->profile_id, $ids);
829 Inbox::bulkInsert($this->id, $ids);
834 function getSubscribedUsers()
838 if(common_config('db','quote_identifiers'))
839 $user_table = '"user"';
840 else $user_table = 'user';
844 'FROM '. $user_table .' JOIN subscription '.
845 'ON '. $user_table .'.id = subscription.subscriber ' .
846 'WHERE subscription.subscribed = %d ';
848 $user->query(sprintf($qry, $this->profile_id));
852 while ($user->fetch()) {
862 * Record this notice to the given group inboxes for delivery.
863 * Overrides the regular parsing of !group markup.
865 * @param string $group_ids
866 * @fixme might prefer URIs as identifiers, as for replies?
867 * best with generalizations on user_group to support
868 * remote groups better.
870 function saveKnownGroups($group_ids)
872 if (!is_array($group_ids)) {
873 throw new ServerException("Bad type provided to saveKnownGroups");
877 foreach ($group_ids as $id) {
878 $group = User_group::staticGet('id', $id);
880 common_log(LOG_ERR, "Local delivery to group id $id, $group->nickname");
881 $result = $this->addToGroupInbox($group);
883 common_log_db_error($gi, 'INSERT', __FILE__);
886 // @fixme should we save the tags here or not?
887 $groups[] = clone($group);
889 common_log(LOG_ERR, "Local delivery to group id $id skipped, doesn't exist");
897 * Parse !group delivery and record targets into group_inbox.
898 * @return array of Group objects
900 function saveGroups()
902 // Don't save groups for repeats
904 if (!empty($this->repeat_of)) {
910 /* extract all !group */
911 $count = preg_match_all('/(?:^|\s)!([A-Za-z0-9]{1,64})/',
912 strtolower($this->content),
918 $profile = $this->getProfile();
920 /* Add them to the database */
922 foreach (array_unique($match[1]) as $nickname) {
923 /* XXX: remote groups. */
924 $group = User_group::getForNickname($nickname, $profile);
930 // we automatically add a tag for every group name, too
932 $tag = Notice_tag::pkeyGet(array('tag' => common_canonical_tag($nickname),
933 'notice_id' => $this->id));
936 $this->saveTag($nickname);
939 if ($profile->isMember($group)) {
941 $result = $this->addToGroupInbox($group);
944 common_log_db_error($gi, 'INSERT', __FILE__);
947 $groups[] = clone($group);
954 function addToGroupInbox($group)
956 $gi = Group_inbox::pkeyGet(array('group_id' => $group->id,
957 'notice_id' => $this->id));
961 $gi = new Group_inbox();
963 $gi->group_id = $group->id;
964 $gi->notice_id = $this->id;
965 $gi->created = $this->created;
967 $result = $gi->insert();
970 common_log_db_error($gi, 'INSERT', __FILE__);
971 throw new ServerException(_('Problem saving group inbox.'));
974 self::blow('user_group:notice_ids:%d', $gi->group_id);
981 * Save reply records indicating that this notice needs to be
982 * delivered to the local users with the given URIs.
984 * Since this is expected to be used when saving foreign-sourced
985 * messages, we won't deliver to any remote targets as that's the
986 * source service's responsibility.
988 * Mail notifications etc will be handled later.
990 * @param array of unique identifier URIs for recipients
992 function saveKnownReplies($uris)
997 $sender = Profile::staticGet($this->profile_id);
999 foreach ($uris as $uri) {
1001 $user = User::staticGet('uri', $uri);
1003 if (!empty($user)) {
1004 if ($user->hasBlocked($sender)) {
1008 $reply = new Reply();
1010 $reply->notice_id = $this->id;
1011 $reply->profile_id = $user->id;
1013 $id = $reply->insert();
1021 * Pull @-replies from this message's content in StatusNet markup format
1022 * and save reply records indicating that this message needs to be
1023 * delivered to those users.
1025 * Mail notifications to local profiles will be sent later.
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;
1079 self::blow('reply:stream:%d', $mentioned->id);
1084 $recipientIds = array_keys($replied);
1086 return $recipientIds;
1090 * Pull the complete list of @-reply targets for this notice.
1092 * @return array of integer profile ids
1094 function getReplies()
1100 $reply = new Reply();
1101 $reply->selectAdd();
1102 $reply->selectAdd('profile_id');
1103 $reply->notice_id = $this->id;
1105 if ($reply->find()) {
1106 while($reply->fetch()) {
1107 $ids[] = $reply->profile_id;
1117 * Send e-mail notifications to local @-reply targets.
1119 * Replies must already have been saved; this is expected to be run
1120 * from the distrib queue handler.
1122 function sendReplyNotifications()
1124 // Don't send reply notifications for repeats
1126 if (!empty($this->repeat_of)) {
1130 $recipientIds = $this->getReplies();
1132 foreach ($recipientIds as $recipientId) {
1133 $user = User::staticGet('id', $recipientId);
1134 if (!empty($user)) {
1135 mail_notify_attn($user, $this);
1141 * Pull list of groups this notice needs to be delivered to,
1142 * as previously recorded by saveGroups() or saveKnownGroups().
1144 * @return array of Group objects
1146 function getGroups()
1148 // Don't save groups for repeats
1150 if (!empty($this->repeat_of)) {
1158 $gi = new Group_inbox();
1161 $gi->selectAdd('group_id');
1163 $gi->notice_id = $this->id;
1166 while ($gi->fetch()) {
1167 $group = User_group::staticGet('id', $gi->group_id);
1179 function asAtomEntry($namespace=false, $source=false, $author=true, $cur=null)
1181 $profile = $this->getProfile();
1183 $xs = new XMLStringer(true);
1186 $attrs = array('xmlns' => 'http://www.w3.org/2005/Atom',
1187 'xmlns:thr' => 'http://purl.org/syndication/thread/1.0',
1188 'xmlns:georss' => 'http://www.georss.org/georss',
1189 'xmlns:activity' => 'http://activitystrea.ms/spec/1.0/',
1190 'xmlns:media' => 'http://purl.org/syndication/atommedia',
1191 'xmlns:poco' => 'http://portablecontacts.net/spec/1.0',
1192 'xmlns:ostatus' => 'http://ostatus.org/schema/1.0',
1193 'xmlns:statusnet' => 'http://status.net/ont/');
1198 $xs->elementStart('entry', $attrs);
1201 $xs->elementStart('source');
1202 $xs->element('id', null, $profile->profileurl);
1203 $xs->element('title', null, $profile->nickname . " - " . common_config('site', 'name'));
1204 $xs->element('link', array('href' => $profile->profileurl));
1205 $user = User::staticGet('id', $profile->id);
1206 if (!empty($user)) {
1207 $atom_feed = common_local_url('ApiTimelineUser',
1208 array('format' => 'atom',
1209 'id' => $profile->nickname));
1210 $xs->element('link', array('rel' => 'self',
1211 'type' => 'application/atom+xml',
1212 'href' => $profile->profileurl));
1213 $xs->element('link', array('rel' => 'license',
1214 'href' => common_config('license', 'url')));
1217 $xs->element('icon', null, $profile->avatarUrl(AVATAR_PROFILE_SIZE));
1218 $xs->element('updated', null, common_date_w3dtf($this->created));
1222 $xs->elementEnd('source');
1225 $xs->element('title', null, common_xml_safe_str($this->content));
1228 $xs->raw($profile->asAtomAuthor());
1229 $xs->raw($profile->asActivityActor());
1232 $xs->element('link', array('rel' => 'alternate',
1233 'type' => 'text/html',
1234 'href' => $this->bestUrl()));
1236 $xs->element('id', null, $this->uri);
1238 $xs->element('published', null, common_date_w3dtf($this->created));
1239 $xs->element('updated', null, common_date_w3dtf($this->created));
1241 $noticeInfoAttr = array(
1242 'local_id' => $this->id, // local notice ID (useful to clients for ordering)
1243 'source' => $this->source, // the client name (source attribution)
1246 $ns = $this->getSource();
1248 if (!empty($ns->url)) {
1249 $noticeInfoAttr['source_link'] = $ns->url;
1254 $noticeInfoAttr['favorite'] = ($cur->hasFave($this)) ? "true" : "false";
1257 if (!empty($this->repeat_of)) {
1258 $noticeInfoAttr['repeat_of'] = $this->repeat_of;
1261 $xs->element('statusnet:notice_info', $noticeInfoAttr, null);
1263 if ($this->reply_to) {
1264 $reply_notice = Notice::staticGet('id', $this->reply_to);
1265 if (!empty($reply_notice)) {
1266 $xs->element('link', array('rel' => 'related',
1267 'href' => $reply_notice->bestUrl()));
1268 $xs->element('thr:in-reply-to',
1269 array('ref' => $reply_notice->uri,
1270 'href' => $reply_notice->bestUrl()));
1274 if (!empty($this->conversation)) {
1276 $conv = Conversation::staticGet('id', $this->conversation);
1278 if (!empty($conv)) {
1281 'rel' => 'ostatus:conversation',
1282 'href' => $conv->uri
1288 $reply_ids = $this->getReplies();
1290 foreach ($reply_ids as $id) {
1291 $profile = Profile::staticGet('id', $id);
1292 if (!empty($profile)) {
1295 'rel' => 'ostatus:attention',
1296 'href' => $profile->getUri()
1302 $groups = $this->getGroups();
1304 foreach ($groups as $group) {
1307 'rel' => 'ostatus:attention',
1308 'href' => $group->permalink()
1313 if (!empty($this->repeat_of)) {
1314 $repeat = Notice::staticGet('id', $this->repeat_of);
1315 if (!empty($repeat)) {
1318 array('ref' => $repeat->uri, 'href' => $repeat->bestUrl())
1325 array('type' => 'html'),
1326 common_xml_safe_str($this->rendered)
1329 $tag = new Notice_tag();
1330 $tag->notice_id = $this->id;
1332 while ($tag->fetch()) {
1333 $xs->element('category', array('term' => $tag->tag));
1339 $attachments = $this->attachments();
1341 foreach($attachments as $attachment){
1342 $enclosure=$attachment->getEnclosure();
1344 $attributes = array('rel'=>'enclosure','href'=>$enclosure->url,'type'=>$enclosure->mimetype,'length'=>$enclosure->size);
1345 if($enclosure->title){
1346 $attributes['title']=$enclosure->title;
1348 $xs->element('link', $attributes, null);
1353 if (!empty($this->lat) && !empty($this->lon)) {
1354 $xs->element('georss:point', null, $this->lat . ' ' . $this->lon);
1357 $xs->elementEnd('entry');
1359 return $xs->getString();
1363 * Returns an XML string fragment with a reference to a notice as an
1364 * Activity Streams noun object with the given element type.
1366 * Assumes that 'activity' namespace has been previously defined.
1368 * @param string $element one of 'subject', 'object', 'target'
1371 function asActivityNoun($element)
1373 $noun = ActivityObject::fromNotice($this);
1374 return $noun->asString('activity:' . $element);
1379 if (!empty($this->url)) {
1381 } else if (!empty($this->uri) && preg_match('/^https?:/', $this->uri)) {
1384 return common_local_url('shownotice',
1385 array('notice' => $this->id));
1389 function stream($fn, $args, $cachekey, $offset=0, $limit=20, $since_id=0, $max_id=0)
1391 $cache = common_memcache();
1393 if (empty($cache) ||
1394 $since_id != 0 || $max_id != 0 ||
1396 ($offset + $limit) > NOTICE_CACHE_WINDOW) {
1397 return call_user_func_array($fn, array_merge($args, array($offset, $limit, $since_id,
1401 $idkey = common_cache_key($cachekey);
1403 $idstr = $cache->get($idkey);
1405 if ($idstr !== false) {
1406 // Cache hit! Woohoo!
1407 $window = explode(',', $idstr);
1408 $ids = array_slice($window, $offset, $limit);
1412 $laststr = $cache->get($idkey.';last');
1414 if ($laststr !== false) {
1415 $window = explode(',', $laststr);
1416 $last_id = $window[0];
1417 $new_ids = call_user_func_array($fn, array_merge($args, array(0, NOTICE_CACHE_WINDOW,
1418 $last_id, 0, null)));
1420 $new_window = array_merge($new_ids, $window);
1422 $new_windowstr = implode(',', $new_window);
1424 $result = $cache->set($idkey, $new_windowstr);
1425 $result = $cache->set($idkey . ';last', $new_windowstr);
1427 $ids = array_slice($new_window, $offset, $limit);
1432 $window = call_user_func_array($fn, array_merge($args, array(0, NOTICE_CACHE_WINDOW,
1435 $windowstr = implode(',', $window);
1437 $result = $cache->set($idkey, $windowstr);
1438 $result = $cache->set($idkey . ';last', $windowstr);
1440 $ids = array_slice($window, $offset, $limit);
1446 * Determine which notice, if any, a new notice is in reply to.
1448 * For conversation tracking, we try to see where this notice fits
1449 * in the tree. Rough algorithm is:
1451 * if (reply_to is set and valid) {
1453 * } else if ((source not API or Web) and (content starts with "T NAME" or "@name ")) {
1454 * return ID of last notice by initial @name in content;
1457 * Note that all @nickname instances will still be used to save "reply" records,
1458 * so the notice shows up in the mentioned users' "replies" tab.
1460 * @param integer $reply_to ID passed in by Web or API
1461 * @param integer $profile_id ID of author
1462 * @param string $source Source tag, like 'web' or 'gwibber'
1463 * @param string $content Final notice content
1465 * @return integer ID of replied-to notice, or null for not a reply.
1468 static function getReplyTo($reply_to, $profile_id, $source, $content)
1470 static $lb = array('xmpp', 'mail', 'sms', 'omb');
1472 // If $reply_to is specified, we check that it exists, and then
1473 // return it if it does
1475 if (!empty($reply_to)) {
1476 $reply_notice = Notice::staticGet('id', $reply_to);
1477 if (!empty($reply_notice)) {
1482 // If it's not a "low bandwidth" source (one where you can't set
1483 // a reply_to argument), we return. This is mostly web and API
1486 if (!in_array($source, $lb)) {
1490 // Is there an initial @ or T?
1492 if (preg_match('/^T ([A-Z0-9]{1,64}) /', $content, $match) ||
1493 preg_match('/^@([a-z0-9]{1,64})\s+/', $content, $match)) {
1494 $nickname = common_canonical_nickname($match[1]);
1499 // Figure out who that is.
1501 $sender = Profile::staticGet('id', $profile_id);
1502 if (empty($sender)) {
1506 $recipient = common_relative_profile($sender, $nickname, common_sql_now());
1508 if (empty($recipient)) {
1512 // Get their last notice
1514 $last = $recipient->getCurrentNotice();
1516 if (!empty($last)) {
1521 static function maxContent()
1523 $contentlimit = common_config('notice', 'contentlimit');
1524 // null => use global limit (distinct from 0!)
1525 if (is_null($contentlimit)) {
1526 $contentlimit = common_config('site', 'textlimit');
1528 return $contentlimit;
1531 static function contentTooLong($content)
1533 $contentlimit = self::maxContent();
1534 return ($contentlimit > 0 && !empty($content) && (mb_strlen($content) > $contentlimit));
1537 function getLocation()
1541 if (!empty($this->location_id) && !empty($this->location_ns)) {
1542 $location = Location::fromId($this->location_id, $this->location_ns);
1545 if (is_null($location)) { // no ID, or Location::fromId() failed
1546 if (!empty($this->lat) && !empty($this->lon)) {
1547 $location = Location::fromLatLon($this->lat, $this->lon);
1554 function repeat($repeater_id, $source)
1556 $author = Profile::staticGet('id', $this->profile_id);
1558 $content = sprintf(_('RT @%1$s %2$s'),
1562 $maxlen = common_config('site', 'textlimit');
1563 if ($maxlen > 0 && mb_strlen($content) > $maxlen) {
1564 // Web interface and current Twitter API clients will
1565 // pull the original notice's text, but some older
1566 // clients and RSS/Atom feeds will see this trimmed text.
1568 // Unfortunately this is likely to lose tags or URLs
1569 // at the end of long notices.
1570 $content = mb_substr($content, 0, $maxlen - 4) . ' ...';
1573 return self::saveNew($repeater_id, $content, $source,
1574 array('repeat_of' => $this->id));
1577 // These are supposed to be in chron order!
1579 function repeatStream($limit=100)
1581 $cache = common_memcache();
1583 if (empty($cache)) {
1584 $ids = $this->_repeatStreamDirect($limit);
1586 $idstr = $cache->get(common_cache_key('notice:repeats:'.$this->id));
1587 if ($idstr !== false) {
1588 $ids = explode(',', $idstr);
1590 $ids = $this->_repeatStreamDirect(100);
1591 $cache->set(common_cache_key('notice:repeats:'.$this->id), implode(',', $ids));
1594 // We do a max of 100, so slice down to limit
1595 $ids = array_slice($ids, 0, $limit);
1599 return Notice::getStreamByIds($ids);
1602 function _repeatStreamDirect($limit)
1604 $notice = new Notice();
1606 $notice->selectAdd(); // clears it
1607 $notice->selectAdd('id');
1609 $notice->repeat_of = $this->id;
1611 $notice->orderBy('created'); // NB: asc!
1613 if (!is_null($offset)) {
1614 $notice->limit($offset, $limit);
1619 if ($notice->find()) {
1620 while ($notice->fetch()) {
1621 $ids[] = $notice->id;
1631 function locationOptions($lat, $lon, $location_id, $location_ns, $profile = null)
1635 if (!empty($location_id) && !empty($location_ns)) {
1637 $options['location_id'] = $location_id;
1638 $options['location_ns'] = $location_ns;
1640 $location = Location::fromId($location_id, $location_ns);
1642 if (!empty($location)) {
1643 $options['lat'] = $location->lat;
1644 $options['lon'] = $location->lon;
1647 } else if (!empty($lat) && !empty($lon)) {
1649 $options['lat'] = $lat;
1650 $options['lon'] = $lon;
1652 $location = Location::fromLatLon($lat, $lon);
1654 if (!empty($location)) {
1655 $options['location_id'] = $location->location_id;
1656 $options['location_ns'] = $location->location_ns;
1658 } else if (!empty($profile)) {
1660 if (isset($profile->lat) && isset($profile->lon)) {
1661 $options['lat'] = $profile->lat;
1662 $options['lon'] = $profile->lon;
1665 if (isset($profile->location_id) && isset($profile->location_ns)) {
1666 $options['location_id'] = $profile->location_id;
1667 $options['location_ns'] = $profile->location_ns;
1674 function clearReplies()
1676 $replyNotice = new Notice();
1677 $replyNotice->reply_to = $this->id;
1679 //Null any notices that are replies to this notice
1681 if ($replyNotice->find()) {
1682 while ($replyNotice->fetch()) {
1683 $orig = clone($replyNotice);
1684 $replyNotice->reply_to = null;
1685 $replyNotice->update($orig);
1691 $reply = new Reply();
1692 $reply->notice_id = $this->id;
1694 if ($reply->find()) {
1695 while($reply->fetch()) {
1696 self::blow('reply:stream:%d', $reply->profile_id);
1704 function clearRepeats()
1706 $repeatNotice = new Notice();
1707 $repeatNotice->repeat_of = $this->id;
1709 //Null any notices that are repeats of this notice
1711 if ($repeatNotice->find()) {
1712 while ($repeatNotice->fetch()) {
1713 $orig = clone($repeatNotice);
1714 $repeatNotice->repeat_of = null;
1715 $repeatNotice->update($orig);
1720 function clearFaves()
1723 $fave->notice_id = $this->id;
1725 if ($fave->find()) {
1726 while ($fave->fetch()) {
1727 self::blow('fave:ids_by_user_own:%d', $fave->user_id);
1728 self::blow('fave:ids_by_user_own:%d;last', $fave->user_id);
1729 self::blow('fave:ids_by_user:%d', $fave->user_id);
1730 self::blow('fave:ids_by_user:%d;last', $fave->user_id);
1738 function clearTags()
1740 $tag = new Notice_tag();
1741 $tag->notice_id = $this->id;
1744 while ($tag->fetch()) {
1745 self::blow('profile:notice_ids_tagged:%d:%s', $this->profile_id, common_keyize($tag->tag));
1746 self::blow('profile:notice_ids_tagged:%d:%s;last', $this->profile_id, common_keyize($tag->tag));
1747 self::blow('notice_tag:notice_ids:%s', common_keyize($tag->tag));
1748 self::blow('notice_tag:notice_ids:%s;last', common_keyize($tag->tag));
1756 function clearGroupInboxes()
1758 $gi = new Group_inbox();
1760 $gi->notice_id = $this->id;
1763 while ($gi->fetch()) {
1764 self::blow('user_group:notice_ids:%d', $gi->group_id);
1772 function distribute()
1774 // We always insert for the author so they don't
1777 $user = User::staticGet('id', $this->profile_id);
1778 if (!empty($user)) {
1779 Inbox::insertNotice($user->id, $this->id);
1782 if (common_config('queue', 'inboxes')) {
1783 // If there's a failure, we want to _force_
1784 // distribution at this point.
1786 $qm = QueueManager::get();
1787 $qm->enqueue($this, 'distrib');
1788 } catch (Exception $e) {
1789 // If the exception isn't transient, this
1790 // may throw more exceptions as DQH does
1791 // its own enqueueing. So, we ignore them!
1793 $handler = new DistribQueueHandler();
1794 $handler->handle($this);
1795 } catch (Exception $e) {
1796 common_log(LOG_ERR, "emergency redistribution resulted in " . $e->getMessage());
1798 // Re-throw so somebody smarter can handle it.
1802 $handler = new DistribQueueHandler();
1803 $handler->handle($this);
1809 $result = parent::insert();
1812 // Profile::hasRepeated() abuses pkeyGet(), so we
1813 // have to clear manually
1814 if (!empty($this->repeat_of)) {
1815 $c = self::memcache();
1817 $ck = self::multicacheKey('Notice',
1818 array('profile_id' => $this->profile_id,
1819 'repeat_of' => $this->repeat_of));
1829 * Get the source of the notice
1831 * @return Notice_source $ns A notice source object. 'code' is the only attribute
1832 * guaranteed to be populated.
1834 function getSource()
1836 $ns = new Notice_source();
1837 if (!empty($this->source)) {
1838 switch ($this->source) {
1845 $ns->code = $this->source;
1848 $ns = Notice_source::staticGet($this->source);
1850 $ns = new Notice_source();
1851 $ns->code = $this->source;
1852 $app = Oauth_application::staticGet('name', $this->source);
1854 $ns->name = $app->name;
1855 $ns->url = $app->source_url;
1865 * Determine whether the notice was locally created
1867 * @return boolean locality
1870 public function isLocal()
1872 return ($this->is_local == Notice::LOCAL_PUBLIC ||
1873 $this->is_local == Notice::LOCAL_NONPUBLIC);