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();
126 /* extract all #hastags */
127 $count = preg_match_all('/(?:^|\s)#([\pL\pN_\-\.]{1,64})/', strtolower($this->content), $match);
132 //turn each into their canonical tag
133 //this is needed to remove dupes before saving e.g. #hash.tag = #hashtag
135 for($i=0; $i<count($match[1]); $i++) {
136 $hashtags[] = common_canonical_tag($match[1][$i]);
139 /* Add them to the database */
140 foreach(array_unique($hashtags) as $hashtag) {
141 /* elide characters we don't want in the tag */
142 $this->saveTag($hashtag);
143 self::blow('profile:notice_ids_tagged:%d:%s', $this->profile_id, $hashtag);
148 function saveTag($hashtag)
150 $tag = new Notice_tag();
151 $tag->notice_id = $this->id;
152 $tag->tag = $hashtag;
153 $tag->created = $this->created;
154 $id = $tag->insert();
157 throw new ServerException(sprintf(_('DB error inserting hashtag: %s'),
158 $last_error->message));
162 // if it's saved, blow its cache
163 $tag->blowCache(false);
167 * Save a new notice and push it out to subscribers' inboxes.
168 * Poster's permissions are checked before sending.
170 * @param int $profile_id Profile ID of the poster
171 * @param string $content source message text; links may be shortened
172 * per current user's preference
173 * @param string $source source key ('web', 'api', etc)
174 * @param array $options Associative array of optional properties:
175 * string 'created' timestamp of notice; defaults to now
176 * int 'is_local' source/gateway ID, one of:
177 * Notice::LOCAL_PUBLIC - Local, ok to appear in public timeline
178 * Notice::REMOTE_OMB - Sent from a remote OMB service;
179 * hide from public timeline but show in
180 * local "and friends" timelines
181 * Notice::LOCAL_NONPUBLIC - Local, but hide from public timeline
182 * Notice::GATEWAY - From another non-OMB service;
183 * will not appear in public views
184 * float 'lat' decimal latitude for geolocation
185 * float 'lon' decimal longitude for geolocation
186 * int 'location_id' geoname identifier
187 * int 'location_ns' geoname namespace to interpret location_id
188 * int 'reply_to'; notice ID this is a reply to
189 * int 'repeat_of'; notice ID this is a repeat of
190 * string 'uri' permalink to notice; defaults to local notice URL
193 * @throws ClientException
195 static function saveNew($profile_id, $content, $source, $options=null) {
196 $defaults = array('uri' => null,
198 'repeat_of' => null);
200 if (!empty($options)) {
201 $options = $options + $defaults;
205 if (!isset($is_local)) {
206 $is_local = Notice::LOCAL_PUBLIC;
209 $profile = Profile::staticGet($profile_id);
211 $final = common_shorten_links($content);
213 if (Notice::contentTooLong($final)) {
214 throw new ClientException(_('Problem saving notice. Too long.'));
217 if (empty($profile)) {
218 throw new ClientException(_('Problem saving notice. Unknown user.'));
221 if (common_config('throttle', 'enabled') && !Notice::checkEditThrottle($profile_id)) {
222 common_log(LOG_WARNING, 'Excessive posting by profile #' . $profile_id . '; throttled.');
223 throw new ClientException(_('Too many notices too fast; take a breather '.
224 'and post again in a few minutes.'));
227 if (common_config('site', 'dupelimit') > 0 && !Notice::checkDupes($profile_id, $final)) {
228 common_log(LOG_WARNING, 'Dupe posting by profile #' . $profile_id . '; throttled.');
229 throw new ClientException(_('Too many duplicate messages too quickly;'.
230 ' take a breather and post again in a few minutes.'));
233 if (!$profile->hasRight(Right::NEWNOTICE)) {
234 common_log(LOG_WARNING, "Attempted post from user disallowed to post: " . $profile->nickname);
235 throw new ClientException(_('You are banned from posting notices on this site.'));
238 $notice = new Notice();
239 $notice->profile_id = $profile_id;
241 $autosource = common_config('public', 'autosource');
243 # Sandboxed are non-false, but not 1, either
245 if (!$profile->hasRight(Right::PUBLICNOTICE) ||
246 ($source && $autosource && in_array($source, $autosource))) {
247 $notice->is_local = Notice::LOCAL_NONPUBLIC;
249 $notice->is_local = $is_local;
252 if (!empty($created)) {
253 $notice->created = $created;
255 $notice->created = common_sql_now();
258 $notice->content = $final;
259 $notice->rendered = common_render_content($final, $notice);
260 $notice->source = $source;
263 // Handle repeat case
265 if (isset($repeat_of)) {
266 $notice->repeat_of = $repeat_of;
268 $notice->reply_to = self::getReplyTo($reply_to, $profile_id, $source, $final);
271 if (!empty($notice->reply_to)) {
272 $reply = Notice::staticGet('id', $notice->reply_to);
273 $notice->conversation = $reply->conversation;
276 if (!empty($lat) && !empty($lon)) {
281 if (!empty($location_ns) && !empty($location_id)) {
282 $notice->location_id = $location_id;
283 $notice->location_ns = $location_ns;
286 if (Event::handle('StartNoticeSave', array(&$notice))) {
288 // XXX: some of these functions write to the DB
290 $id = $notice->insert();
293 common_log_db_error($notice, 'INSERT', __FILE__);
294 throw new ServerException(_('Problem saving notice.'));
297 // Update ID-dependent columns: URI, conversation
299 $orig = clone($notice);
304 $notice->uri = common_notice_uri($notice);
308 // If it's not part of a conversation, it's
309 // the beginning of a new conversation.
311 if (empty($notice->conversation)) {
312 $conv = Conversation::create();
313 $notice->conversation = $conv->id;
318 if (!$notice->update($orig)) {
319 common_log_db_error($notice, 'UPDATE', __FILE__);
320 throw new ServerException(_('Problem saving notice.'));
326 # Clear the cache for subscribed users, so they'll update at next request
327 # XXX: someone clever could prepend instead of clearing the cache
328 $notice->blowOnInsert();
330 $notice->distribute();
335 function blowOnInsert($conversation = false)
337 self::blow('profile:notice_ids:%d', $this->profile_id);
338 self::blow('public');
340 // XXX: Before we were blowing the casche only if the notice id
341 // was not the root of the conversation. What to do now?
343 self::blow('notice:conversation_ids:%d', $this->conversation);
345 if (!empty($this->repeat_of)) {
346 self::blow('notice:repeats:%d', $this->repeat_of);
349 $original = Notice::staticGet('id', $this->repeat_of);
351 if (!empty($original)) {
352 $originalUser = User::staticGet('id', $original->profile_id);
353 if (!empty($originalUser)) {
354 self::blow('user:repeats_of_me:%d', $originalUser->id);
358 $profile = Profile::staticGet($this->profile_id);
359 $profile->blowNoticeCount();
362 /** save all urls in the notice to the db
364 * follow redirects and save all available file information
365 * (mimetype, date, size, oembed, etc.)
369 function saveUrls() {
370 common_replace_urls_callback($this->content, array($this, 'saveUrl'), $this->id);
373 function saveUrl($data) {
374 list($url, $notice_id) = $data;
375 File::processNew($url, $notice_id);
378 static function checkDupes($profile_id, $content) {
379 $profile = Profile::staticGet($profile_id);
380 if (empty($profile)) {
383 $notice = $profile->getNotices(0, NOTICE_CACHE_WINDOW);
384 if (!empty($notice)) {
386 while ($notice->fetch()) {
387 if (time() - strtotime($notice->created) >= common_config('site', 'dupelimit')) {
389 } else if ($notice->content == $content) {
394 # If we get here, oldest item in cache window is not
395 # old enough for dupe limit; do direct check against DB
396 $notice = new Notice();
397 $notice->profile_id = $profile_id;
398 $notice->content = $content;
399 if (common_config('db','type') == 'pgsql')
400 $notice->whereAdd('extract(epoch from now() - created) < ' . common_config('site', 'dupelimit'));
402 $notice->whereAdd('now() - created < ' . common_config('site', 'dupelimit'));
404 $cnt = $notice->count();
408 static function checkEditThrottle($profile_id) {
409 $profile = Profile::staticGet($profile_id);
410 if (empty($profile)) {
414 $notice = $profile->getNotices(common_config('throttle', 'count') - 1, 1);
415 if ($notice && $notice->fetch()) {
416 # If the Nth notice was posted less than timespan seconds ago
417 if (time() - strtotime($notice->created) <= common_config('throttle', 'timespan')) {
422 # Either not N notices in the stream, OR the Nth was not posted within timespan seconds
426 function getUploadedAttachment() {
428 $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"';
429 $post->query($query);
431 if (empty($post->up) || empty($post->i)) {
434 $ret = array($post->up, $post->i);
440 function hasAttachments() {
442 $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);
443 $post->query($query);
445 $n_attachments = intval($post->n_attachments);
447 return $n_attachments;
450 function attachments() {
453 $f2p = new File_to_post;
454 $f2p->post_id = $this->id;
456 while ($f2p->fetch()) {
457 $f = File::staticGet($f2p->file_id);
464 function getStreamByIds($ids)
466 $cache = common_memcache();
468 if (!empty($cache)) {
470 foreach ($ids as $id) {
471 $n = Notice::staticGet('id', $id);
476 return new ArrayWrapper($notices);
478 $notice = new Notice();
480 //if no IDs requested, just return the notice object
483 $notice->whereAdd('id in (' . implode(', ', $ids) . ')');
489 while ($notice->fetch()) {
490 $temp[$notice->id] = clone($notice);
495 foreach ($ids as $id) {
496 if (array_key_exists($id, $temp)) {
497 $wrapped[] = $temp[$id];
501 return new ArrayWrapper($wrapped);
505 function publicStream($offset=0, $limit=20, $since_id=0, $max_id=0, $since=null)
507 $ids = Notice::stream(array('Notice', '_publicStreamDirect'),
510 $offset, $limit, $since_id, $max_id, $since);
512 return Notice::getStreamByIds($ids);
515 function _publicStreamDirect($offset=0, $limit=20, $since_id=0, $max_id=0, $since=null)
517 $notice = new Notice();
519 $notice->selectAdd(); // clears it
520 $notice->selectAdd('id');
522 $notice->orderBy('id DESC');
524 if (!is_null($offset)) {
525 $notice->limit($offset, $limit);
528 if (common_config('public', 'localonly')) {
529 $notice->whereAdd('is_local = ' . Notice::LOCAL_PUBLIC);
531 # -1 == blacklisted, -2 == gateway (i.e. Twitter)
532 $notice->whereAdd('is_local !='. Notice::LOCAL_NONPUBLIC);
533 $notice->whereAdd('is_local !='. Notice::GATEWAY);
536 if ($since_id != 0) {
537 $notice->whereAdd('id > ' . $since_id);
541 $notice->whereAdd('id <= ' . $max_id);
544 if (!is_null($since)) {
545 $notice->whereAdd('created > \'' . date('Y-m-d H:i:s', $since) . '\'');
550 if ($notice->find()) {
551 while ($notice->fetch()) {
552 $ids[] = $notice->id;
562 function conversationStream($id, $offset=0, $limit=20, $since_id=0, $max_id=0, $since=null)
564 $ids = Notice::stream(array('Notice', '_conversationStreamDirect'),
566 'notice:conversation_ids:'.$id,
567 $offset, $limit, $since_id, $max_id, $since);
569 return Notice::getStreamByIds($ids);
572 function _conversationStreamDirect($id, $offset=0, $limit=20, $since_id=0, $max_id=0, $since=null)
574 $notice = new Notice();
576 $notice->selectAdd(); // clears it
577 $notice->selectAdd('id');
579 $notice->conversation = $id;
581 $notice->orderBy('id DESC');
583 if (!is_null($offset)) {
584 $notice->limit($offset, $limit);
587 if ($since_id != 0) {
588 $notice->whereAdd('id > ' . $since_id);
592 $notice->whereAdd('id <= ' . $max_id);
595 if (!is_null($since)) {
596 $notice->whereAdd('created > \'' . date('Y-m-d H:i:s', $since) . '\'');
601 if ($notice->find()) {
602 while ($notice->fetch()) {
603 $ids[] = $notice->id;
614 * @param $groups array of Group *objects*
615 * @param $recipients array of profile *ids*
617 function whoGets($groups=null, $recipients=null)
619 $c = self::memcache();
622 $ni = $c->get(common_cache_key('notice:who_gets:'.$this->id));
628 if (is_null($groups)) {
629 $groups = $this->getGroups();
632 if (is_null($recipients)) {
633 $recipients = $this->getReplies();
636 $users = $this->getSubscribedUsers();
638 // FIXME: kind of ignoring 'transitional'...
639 // we'll probably stop supporting inboxless mode
644 foreach ($users as $id) {
645 $ni[$id] = NOTICE_INBOX_SOURCE_SUB;
648 $profile = $this->getProfile();
650 foreach ($groups as $group) {
651 $users = $group->getUserMembers();
652 foreach ($users as $id) {
653 if (!array_key_exists($id, $ni)) {
654 $user = User::staticGet('id', $id);
655 if (!$user->hasBlocked($profile)) {
656 $ni[$id] = NOTICE_INBOX_SOURCE_GROUP;
662 foreach ($recipients as $recipient) {
664 if (!array_key_exists($recipient, $ni)) {
665 $recipientUser = User::staticGet('id', $recipient);
666 if (!empty($recipientUser)) {
667 $ni[$recipient] = NOTICE_INBOX_SOURCE_REPLY;
673 // XXX: pack this data better
674 $c->set(common_cache_key('notice:who_gets:'.$this->id), $ni);
680 function addToInboxes($groups, $recipients)
682 $ni = $this->whoGets($groups, $recipients);
684 $ids = array_keys($ni);
686 // We remove the author (if they're a local user),
687 // since we'll have already done this in distribute()
689 $i = array_search($this->profile_id, $ids);
697 Inbox::bulkInsert($this->id, $ids);
702 function getSubscribedUsers()
706 if(common_config('db','quote_identifiers'))
707 $user_table = '"user"';
708 else $user_table = 'user';
712 'FROM '. $user_table .' JOIN subscription '.
713 'ON '. $user_table .'.id = subscription.subscriber ' .
714 'WHERE subscription.subscribed = %d ';
716 $user->query(sprintf($qry, $this->profile_id));
720 while ($user->fetch()) {
730 * @return array of Group objects
732 function saveGroups()
734 // Don't save groups for repeats
736 if (!empty($this->repeat_of)) {
742 /* extract all !group */
743 $count = preg_match_all('/(?:^|\s)!([A-Za-z0-9]{1,64})/',
744 strtolower($this->content),
750 $profile = $this->getProfile();
752 /* Add them to the database */
754 foreach (array_unique($match[1]) as $nickname) {
755 /* XXX: remote groups. */
756 $group = User_group::getForNickname($nickname);
762 // we automatically add a tag for every group name, too
764 $tag = Notice_tag::pkeyGet(array('tag' => common_canonical_tag($nickname),
765 'notice_id' => $this->id));
768 $this->saveTag($nickname);
771 if ($profile->isMember($group)) {
773 $result = $this->addToGroupInbox($group);
776 common_log_db_error($gi, 'INSERT', __FILE__);
779 $groups[] = clone($group);
786 function addToGroupInbox($group)
788 $gi = Group_inbox::pkeyGet(array('group_id' => $group->id,
789 'notice_id' => $this->id));
793 $gi = new Group_inbox();
795 $gi->group_id = $group->id;
796 $gi->notice_id = $this->id;
797 $gi->created = $this->created;
799 $result = $gi->insert();
802 common_log_db_error($gi, 'INSERT', __FILE__);
803 throw new ServerException(_('Problem saving group inbox.'));
806 self::blow('user_group:notice_ids:%d', $gi->group_id);
813 * @return array of integer profile IDs
815 function saveReplies()
817 // Don't save reply data for repeats
819 if (!empty($this->repeat_of)) {
823 // Alternative reply format
825 if (preg_match('/^T ([A-Z0-9]{1,64}) /', $this->content, $match)) {
828 // extract all @messages
829 $cnt = preg_match_all('/(?:^|\s)@([a-z0-9]{1,64})/', $this->content, $match);
833 if ($cnt || $tname) {
834 // XXX: is there another way to make an array copy?
835 $names = ($tname) ? array_unique(array_merge(array(strtolower($tname)), $match[1])) : array_unique($match[1]);
838 $sender = Profile::staticGet($this->profile_id);
842 // store replied only for first @ (what user/notice what the reply directed,
843 // we assume first @ is it)
845 for ($i=0; $i<count($names); $i++) {
846 $nickname = $names[$i];
847 $recipient = common_relative_profile($sender, $nickname, $this->created);
848 if (empty($recipient)) {
851 // Don't save replies from blocked profile to local user
852 $recipient_user = User::staticGet('id', $recipient->id);
853 if (!empty($recipient_user) && $recipient_user->hasBlocked($sender)) {
856 $reply = new Reply();
857 $reply->notice_id = $this->id;
858 $reply->profile_id = $recipient->id;
859 $id = $reply->insert();
861 $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError');
862 common_log(LOG_ERR, 'DB error inserting reply: ' . $last_error->message);
863 common_server_error(sprintf(_('DB error inserting reply: %s'), $last_error->message));
866 $replied[$recipient->id] = 1;
870 // Hash format replies, too
871 $cnt = preg_match_all('/(?:^|\s)@#([a-z0-9]{1,64})/', $this->content, $match);
873 foreach ($match[1] as $tag) {
874 $tagged = Profile_tag::getTagged($sender->id, $tag);
875 foreach ($tagged as $t) {
876 if (!$replied[$t->id]) {
877 // Don't save replies from blocked profile to local user
878 $t_user = User::staticGet('id', $t->id);
879 if ($t_user && $t_user->hasBlocked($sender)) {
882 $reply = new Reply();
883 $reply->notice_id = $this->id;
884 $reply->profile_id = $t->id;
885 $id = $reply->insert();
887 common_log_db_error($reply, 'INSERT', __FILE__);
890 $replied[$recipient->id] = 1;
897 $recipientIds = array_keys($replied);
899 foreach ($recipientIds as $recipientId) {
900 $user = User::staticGet('id', $recipientId);
902 self::blow('reply:stream:%d', $reply->profile_id);
903 mail_notify_attn($user, $this);
907 return $recipientIds;
910 function getReplies()
916 $reply = new Reply();
918 $reply->selectAdd('profile_id');
919 $reply->notice_id = $this->id;
921 if ($reply->find()) {
922 while($reply->fetch()) {
923 $ids[] = $reply->profile_id;
933 * Same calculation as saveGroups but without the saving
934 * @fixme merge the functions
935 * @return array of Group_inbox objects
939 // Don't save groups for repeats
941 if (!empty($this->repeat_of)) {
949 $gi = new Group_inbox();
952 $gi->selectAdd('group_id');
954 $gi->notice_id = $this->id;
957 while ($gi->fetch()) {
958 $groups[] = clone($gi);
967 function asAtomEntry($namespace=false, $source=false)
969 $profile = $this->getProfile();
971 $xs = new XMLStringer(true);
974 $attrs = array('xmlns' => 'http://www.w3.org/2005/Atom',
975 'xmlns:thr' => 'http://purl.org/syndication/thread/1.0',
976 'xmlns:georss' => 'http://www.georss.org/georss',
977 'xmlns:activity' => 'http://activitystrea.ms/spec/1.0/',
978 'xmlns:ostatus' => 'http://ostatus.org/schema/1.0');
983 $xs->elementStart('entry', $attrs);
986 $xs->elementStart('source');
987 $xs->element('title', null, $profile->nickname . " - " . common_config('site', 'name'));
988 $xs->element('link', array('href' => $profile->profileurl));
989 $user = User::staticGet('id', $profile->id);
991 $atom_feed = common_local_url('ApiTimelineUser',
992 array('format' => 'atom',
993 'id' => $profile->nickname));
994 $xs->element('link', array('rel' => 'self',
995 'type' => 'application/atom+xml',
996 'href' => $profile->profileurl));
997 $xs->element('link', array('rel' => 'license',
998 'href' => common_config('license', 'url')));
1001 $xs->element('icon', null, $profile->avatarUrl(AVATAR_PROFILE_SIZE));
1005 $xs->elementEnd('source');
1008 $xs->element('title', null, $this->content);
1009 $xs->element('summary', null, $this->content);
1011 $xs->raw($profile->asAtomAuthor());
1012 $xs->raw($profile->asActivityActor());
1014 $xs->element('link', array('rel' => 'alternate',
1015 'href' => $this->bestUrl()));
1017 $xs->element('id', null, $this->uri);
1019 $xs->element('published', null, common_date_w3dtf($this->created));
1020 $xs->element('updated', null, common_date_w3dtf($this->created));
1022 if ($this->reply_to) {
1023 $reply_notice = Notice::staticGet('id', $this->reply_to);
1024 if (!empty($reply_notice)) {
1025 $xs->element('link', array('rel' => 'related',
1026 'href' => $reply_notice->bestUrl()));
1027 $xs->element('thr:in-reply-to',
1028 array('ref' => $reply_notice->uri,
1029 'href' => $reply_notice->bestUrl()));
1033 if (!empty($this->conversation)) {
1035 $conv = Conversation::staticGet('id', $this->conversation);
1037 if (!empty($conv)) {
1040 'rel' => 'ostatus:conversation',
1041 'href' => $conv->uri
1047 $reply_ids = $this->getReplies();
1049 foreach ($reply_ids as $id) {
1050 $profile = Profile::staticGet('id', $id);
1051 if (!empty($profile)) {
1054 'rel' => 'ostatus:attention',
1055 'href' => $profile->getUri()
1061 if (!empty($this->repeat_of)) {
1062 $repeat = Notice::staticGet('id', $this->repeat_of);
1063 if (!empty($repeat)) {
1066 array('ref' => $repeat->uri, 'href' => $repeat->bestUrl())
1071 $xs->element('content', array('type' => 'html'), $this->rendered);
1073 $tag = new Notice_tag();
1074 $tag->notice_id = $this->id;
1076 while ($tag->fetch()) {
1077 $xs->element('category', array('term' => $tag->tag));
1083 $attachments = $this->attachments();
1085 foreach($attachments as $attachment){
1086 $enclosure=$attachment->getEnclosure();
1088 $attributes = array('rel'=>'enclosure','href'=>$enclosure->url,'type'=>$enclosure->mimetype,'length'=>$enclosure->size);
1089 if($enclosure->title){
1090 $attributes['title']=$enclosure->title;
1092 $xs->element('link', $attributes, null);
1097 if (!empty($this->lat) && !empty($this->lon)) {
1098 $xs->element('georss:point', null, $this->lat . ' ' . $this->lon);
1101 $xs->elementEnd('entry');
1103 return $xs->getString();
1108 if (!empty($this->url)) {
1110 } else if (!empty($this->uri) && preg_match('/^https?:/', $this->uri)) {
1113 return common_local_url('shownotice',
1114 array('notice' => $this->id));
1118 function stream($fn, $args, $cachekey, $offset=0, $limit=20, $since_id=0, $max_id=0, $since=null)
1120 $cache = common_memcache();
1122 if (empty($cache) ||
1123 $since_id != 0 || $max_id != 0 || (!is_null($since) && $since > 0) ||
1125 ($offset + $limit) > NOTICE_CACHE_WINDOW) {
1126 return call_user_func_array($fn, array_merge($args, array($offset, $limit, $since_id,
1130 $idkey = common_cache_key($cachekey);
1132 $idstr = $cache->get($idkey);
1134 if ($idstr !== false) {
1135 // Cache hit! Woohoo!
1136 $window = explode(',', $idstr);
1137 $ids = array_slice($window, $offset, $limit);
1141 $laststr = $cache->get($idkey.';last');
1143 if ($laststr !== false) {
1144 $window = explode(',', $laststr);
1145 $last_id = $window[0];
1146 $new_ids = call_user_func_array($fn, array_merge($args, array(0, NOTICE_CACHE_WINDOW,
1147 $last_id, 0, null)));
1149 $new_window = array_merge($new_ids, $window);
1151 $new_windowstr = implode(',', $new_window);
1153 $result = $cache->set($idkey, $new_windowstr);
1154 $result = $cache->set($idkey . ';last', $new_windowstr);
1156 $ids = array_slice($new_window, $offset, $limit);
1161 $window = call_user_func_array($fn, array_merge($args, array(0, NOTICE_CACHE_WINDOW,
1164 $windowstr = implode(',', $window);
1166 $result = $cache->set($idkey, $windowstr);
1167 $result = $cache->set($idkey . ';last', $windowstr);
1169 $ids = array_slice($window, $offset, $limit);
1175 * Determine which notice, if any, a new notice is in reply to.
1177 * For conversation tracking, we try to see where this notice fits
1178 * in the tree. Rough algorithm is:
1180 * if (reply_to is set and valid) {
1182 * } else if ((source not API or Web) and (content starts with "T NAME" or "@name ")) {
1183 * return ID of last notice by initial @name in content;
1186 * Note that all @nickname instances will still be used to save "reply" records,
1187 * so the notice shows up in the mentioned users' "replies" tab.
1189 * @param integer $reply_to ID passed in by Web or API
1190 * @param integer $profile_id ID of author
1191 * @param string $source Source tag, like 'web' or 'gwibber'
1192 * @param string $content Final notice content
1194 * @return integer ID of replied-to notice, or null for not a reply.
1197 static function getReplyTo($reply_to, $profile_id, $source, $content)
1199 static $lb = array('xmpp', 'mail', 'sms', 'omb');
1201 // If $reply_to is specified, we check that it exists, and then
1202 // return it if it does
1204 if (!empty($reply_to)) {
1205 $reply_notice = Notice::staticGet('id', $reply_to);
1206 if (!empty($reply_notice)) {
1211 // If it's not a "low bandwidth" source (one where you can't set
1212 // a reply_to argument), we return. This is mostly web and API
1215 if (!in_array($source, $lb)) {
1219 // Is there an initial @ or T?
1221 if (preg_match('/^T ([A-Z0-9]{1,64}) /', $content, $match) ||
1222 preg_match('/^@([a-z0-9]{1,64})\s+/', $content, $match)) {
1223 $nickname = common_canonical_nickname($match[1]);
1228 // Figure out who that is.
1230 $sender = Profile::staticGet('id', $profile_id);
1231 if (empty($sender)) {
1235 $recipient = common_relative_profile($sender, $nickname, common_sql_now());
1237 if (empty($recipient)) {
1241 // Get their last notice
1243 $last = $recipient->getCurrentNotice();
1245 if (!empty($last)) {
1250 static function maxContent()
1252 $contentlimit = common_config('notice', 'contentlimit');
1253 // null => use global limit (distinct from 0!)
1254 if (is_null($contentlimit)) {
1255 $contentlimit = common_config('site', 'textlimit');
1257 return $contentlimit;
1260 static function contentTooLong($content)
1262 $contentlimit = self::maxContent();
1263 return ($contentlimit > 0 && !empty($content) && (mb_strlen($content) > $contentlimit));
1266 function getLocation()
1270 if (!empty($this->location_id) && !empty($this->location_ns)) {
1271 $location = Location::fromId($this->location_id, $this->location_ns);
1274 if (is_null($location)) { // no ID, or Location::fromId() failed
1275 if (!empty($this->lat) && !empty($this->lon)) {
1276 $location = Location::fromLatLon($this->lat, $this->lon);
1283 function repeat($repeater_id, $source)
1285 $author = Profile::staticGet('id', $this->profile_id);
1287 $content = sprintf(_('RT @%1$s %2$s'),
1291 $maxlen = common_config('site', 'textlimit');
1292 if ($maxlen > 0 && mb_strlen($content) > $maxlen) {
1293 // Web interface and current Twitter API clients will
1294 // pull the original notice's text, but some older
1295 // clients and RSS/Atom feeds will see this trimmed text.
1297 // Unfortunately this is likely to lose tags or URLs
1298 // at the end of long notices.
1299 $content = mb_substr($content, 0, $maxlen - 4) . ' ...';
1302 return self::saveNew($repeater_id, $content, $source,
1303 array('repeat_of' => $this->id));
1306 // These are supposed to be in chron order!
1308 function repeatStream($limit=100)
1310 $cache = common_memcache();
1312 if (empty($cache)) {
1313 $ids = $this->_repeatStreamDirect($limit);
1315 $idstr = $cache->get(common_cache_key('notice:repeats:'.$this->id));
1316 if ($idstr !== false) {
1317 $ids = explode(',', $idstr);
1319 $ids = $this->_repeatStreamDirect(100);
1320 $cache->set(common_cache_key('notice:repeats:'.$this->id), implode(',', $ids));
1323 // We do a max of 100, so slice down to limit
1324 $ids = array_slice($ids, 0, $limit);
1328 return Notice::getStreamByIds($ids);
1331 function _repeatStreamDirect($limit)
1333 $notice = new Notice();
1335 $notice->selectAdd(); // clears it
1336 $notice->selectAdd('id');
1338 $notice->repeat_of = $this->id;
1340 $notice->orderBy('created'); // NB: asc!
1342 if (!is_null($offset)) {
1343 $notice->limit($offset, $limit);
1348 if ($notice->find()) {
1349 while ($notice->fetch()) {
1350 $ids[] = $notice->id;
1360 function locationOptions($lat, $lon, $location_id, $location_ns, $profile = null)
1364 if (!empty($location_id) && !empty($location_ns)) {
1366 $options['location_id'] = $location_id;
1367 $options['location_ns'] = $location_ns;
1369 $location = Location::fromId($location_id, $location_ns);
1371 if (!empty($location)) {
1372 $options['lat'] = $location->lat;
1373 $options['lon'] = $location->lon;
1376 } else if (!empty($lat) && !empty($lon)) {
1378 $options['lat'] = $lat;
1379 $options['lon'] = $lon;
1381 $location = Location::fromLatLon($lat, $lon);
1383 if (!empty($location)) {
1384 $options['location_id'] = $location->location_id;
1385 $options['location_ns'] = $location->location_ns;
1387 } else if (!empty($profile)) {
1389 if (isset($profile->lat) && isset($profile->lon)) {
1390 $options['lat'] = $profile->lat;
1391 $options['lon'] = $profile->lon;
1394 if (isset($profile->location_id) && isset($profile->location_ns)) {
1395 $options['location_id'] = $profile->location_id;
1396 $options['location_ns'] = $profile->location_ns;
1403 function clearReplies()
1405 $replyNotice = new Notice();
1406 $replyNotice->reply_to = $this->id;
1408 //Null any notices that are replies to this notice
1410 if ($replyNotice->find()) {
1411 while ($replyNotice->fetch()) {
1412 $orig = clone($replyNotice);
1413 $replyNotice->reply_to = null;
1414 $replyNotice->update($orig);
1420 $reply = new Reply();
1421 $reply->notice_id = $this->id;
1423 if ($reply->find()) {
1424 while($reply->fetch()) {
1425 self::blow('reply:stream:%d', $reply->profile_id);
1433 function clearRepeats()
1435 $repeatNotice = new Notice();
1436 $repeatNotice->repeat_of = $this->id;
1438 //Null any notices that are repeats of this notice
1440 if ($repeatNotice->find()) {
1441 while ($repeatNotice->fetch()) {
1442 $orig = clone($repeatNotice);
1443 $repeatNotice->repeat_of = null;
1444 $repeatNotice->update($orig);
1449 function clearFaves()
1452 $fave->notice_id = $this->id;
1454 if ($fave->find()) {
1455 while ($fave->fetch()) {
1456 self::blow('fave:ids_by_user_own:%d', $fave->user_id);
1457 self::blow('fave:ids_by_user_own:%d;last', $fave->user_id);
1458 self::blow('fave:ids_by_user:%d', $fave->user_id);
1459 self::blow('fave:ids_by_user:%d;last', $fave->user_id);
1467 function clearTags()
1469 $tag = new Notice_tag();
1470 $tag->notice_id = $this->id;
1473 while ($tag->fetch()) {
1474 self::blow('profile:notice_ids_tagged:%d:%s', $this->profile_id, common_keyize($tag->tag));
1475 self::blow('profile:notice_ids_tagged:%d:%s;last', $this->profile_id, common_keyize($tag->tag));
1476 self::blow('notice_tag:notice_ids:%s', common_keyize($tag->tag));
1477 self::blow('notice_tag:notice_ids:%s;last', common_keyize($tag->tag));
1485 function clearGroupInboxes()
1487 $gi = new Group_inbox();
1489 $gi->notice_id = $this->id;
1492 while ($gi->fetch()) {
1493 self::blow('user_group:notice_ids:%d', $gi->group_id);
1501 function distribute()
1503 // We always insert for the author so they don't
1506 $user = User::staticGet('id', $this->profile_id);
1507 if (!empty($user)) {
1508 Inbox::insertNotice($user->id, $this->id);
1511 if (common_config('queue', 'inboxes')) {
1512 // If there's a failure, we want to _force_
1513 // distribution at this point.
1515 $qm = QueueManager::get();
1516 $qm->enqueue($this, 'distrib');
1517 } catch (Exception $e) {
1518 // If the exception isn't transient, this
1519 // may throw more exceptions as DQH does
1520 // its own enqueueing. So, we ignore them!
1522 $handler = new DistribQueueHandler();
1523 $handler->handle($this);
1524 } catch (Exception $e) {
1525 common_log(LOG_ERR, "emergency redistribution resulted in " . $e->getMessage());
1527 // Re-throw so somebody smarter can handle it.
1531 $handler = new DistribQueueHandler();
1532 $handler->handle($this);
1538 $result = parent::insert();
1541 // Profile::hasRepeated() abuses pkeyGet(), so we
1542 // have to clear manually
1543 if (!empty($this->repeat_of)) {
1544 $c = self::memcache();
1546 $ck = self::multicacheKey('Notice',
1547 array('profile_id' => $this->profile_id,
1548 'repeat_of' => $this->repeat_of));