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,
199 'repeat_of' => null);
201 if (!empty($options)) {
202 $options = $options + $defaults;
206 if (!isset($is_local)) {
207 $is_local = Notice::LOCAL_PUBLIC;
210 $profile = Profile::staticGet($profile_id);
212 $final = common_shorten_links($content);
214 if (Notice::contentTooLong($final)) {
215 throw new ClientException(_('Problem saving notice. Too long.'));
218 if (empty($profile)) {
219 throw new ClientException(_('Problem saving notice. Unknown user.'));
222 if (common_config('throttle', 'enabled') && !Notice::checkEditThrottle($profile_id)) {
223 common_log(LOG_WARNING, 'Excessive posting by profile #' . $profile_id . '; throttled.');
224 throw new ClientException(_('Too many notices too fast; take a breather '.
225 'and post again in a few minutes.'));
228 if (common_config('site', 'dupelimit') > 0 && !Notice::checkDupes($profile_id, $final)) {
229 common_log(LOG_WARNING, 'Dupe posting by profile #' . $profile_id . '; throttled.');
230 throw new ClientException(_('Too many duplicate messages too quickly;'.
231 ' take a breather and post again in a few minutes.'));
234 if (!$profile->hasRight(Right::NEWNOTICE)) {
235 common_log(LOG_WARNING, "Attempted post from user disallowed to post: " . $profile->nickname);
236 throw new ClientException(_('You are banned from posting notices on this site.'));
239 $notice = new Notice();
240 $notice->profile_id = $profile_id;
242 $autosource = common_config('public', 'autosource');
244 # Sandboxed are non-false, but not 1, either
246 if (!$profile->hasRight(Right::PUBLICNOTICE) ||
247 ($source && $autosource && in_array($source, $autosource))) {
248 $notice->is_local = Notice::LOCAL_NONPUBLIC;
250 $notice->is_local = $is_local;
253 if (!empty($created)) {
254 $notice->created = $created;
256 $notice->created = common_sql_now();
259 $notice->content = $final;
261 if (!empty($rendered)) {
262 $notice->rendered = $rendered;
264 $notice->rendered = common_render_content($final, $notice);
267 $notice->source = $source;
271 // Handle repeat case
273 if (isset($repeat_of)) {
274 $notice->repeat_of = $repeat_of;
276 $notice->reply_to = self::getReplyTo($reply_to, $profile_id, $source, $final);
279 if (!empty($notice->reply_to)) {
280 $reply = Notice::staticGet('id', $notice->reply_to);
281 $notice->conversation = $reply->conversation;
284 if (!empty($lat) && !empty($lon)) {
289 if (!empty($location_ns) && !empty($location_id)) {
290 $notice->location_id = $location_id;
291 $notice->location_ns = $location_ns;
294 if (Event::handle('StartNoticeSave', array(&$notice))) {
296 // XXX: some of these functions write to the DB
298 $id = $notice->insert();
301 common_log_db_error($notice, 'INSERT', __FILE__);
302 throw new ServerException(_('Problem saving notice.'));
305 // Update ID-dependent columns: URI, conversation
307 $orig = clone($notice);
312 $notice->uri = common_notice_uri($notice);
316 // If it's not part of a conversation, it's
317 // the beginning of a new conversation.
319 if (empty($notice->conversation)) {
320 $conv = Conversation::create();
321 $notice->conversation = $conv->id;
326 if (!$notice->update($orig)) {
327 common_log_db_error($notice, 'UPDATE', __FILE__);
328 throw new ServerException(_('Problem saving notice.'));
334 # Clear the cache for subscribed users, so they'll update at next request
335 # XXX: someone clever could prepend instead of clearing the cache
337 $notice->blowOnInsert();
339 if (isset($replies)) {
340 $notice->saveKnownReplies($replies);
342 $notice->saveReplies();
345 $notice->distribute();
350 function blowOnInsert($conversation = false)
352 self::blow('profile:notice_ids:%d', $this->profile_id);
353 self::blow('public');
355 // XXX: Before we were blowing the casche only if the notice id
356 // was not the root of the conversation. What to do now?
358 self::blow('notice:conversation_ids:%d', $this->conversation);
360 if (!empty($this->repeat_of)) {
361 self::blow('notice:repeats:%d', $this->repeat_of);
364 $original = Notice::staticGet('id', $this->repeat_of);
366 if (!empty($original)) {
367 $originalUser = User::staticGet('id', $original->profile_id);
368 if (!empty($originalUser)) {
369 self::blow('user:repeats_of_me:%d', $originalUser->id);
373 $profile = Profile::staticGet($this->profile_id);
374 $profile->blowNoticeCount();
377 /** save all urls in the notice to the db
379 * follow redirects and save all available file information
380 * (mimetype, date, size, oembed, etc.)
384 function saveUrls() {
385 common_replace_urls_callback($this->content, array($this, 'saveUrl'), $this->id);
388 function saveUrl($data) {
389 list($url, $notice_id) = $data;
390 File::processNew($url, $notice_id);
393 static function checkDupes($profile_id, $content) {
394 $profile = Profile::staticGet($profile_id);
395 if (empty($profile)) {
398 $notice = $profile->getNotices(0, NOTICE_CACHE_WINDOW);
399 if (!empty($notice)) {
401 while ($notice->fetch()) {
402 if (time() - strtotime($notice->created) >= common_config('site', 'dupelimit')) {
404 } else if ($notice->content == $content) {
409 # If we get here, oldest item in cache window is not
410 # old enough for dupe limit; do direct check against DB
411 $notice = new Notice();
412 $notice->profile_id = $profile_id;
413 $notice->content = $content;
414 if (common_config('db','type') == 'pgsql')
415 $notice->whereAdd('extract(epoch from now() - created) < ' . common_config('site', 'dupelimit'));
417 $notice->whereAdd('now() - created < ' . common_config('site', 'dupelimit'));
419 $cnt = $notice->count();
423 static function checkEditThrottle($profile_id) {
424 $profile = Profile::staticGet($profile_id);
425 if (empty($profile)) {
429 $notice = $profile->getNotices(common_config('throttle', 'count') - 1, 1);
430 if ($notice && $notice->fetch()) {
431 # If the Nth notice was posted less than timespan seconds ago
432 if (time() - strtotime($notice->created) <= common_config('throttle', 'timespan')) {
437 # Either not N notices in the stream, OR the Nth was not posted within timespan seconds
441 function getUploadedAttachment() {
443 $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"';
444 $post->query($query);
446 if (empty($post->up) || empty($post->i)) {
449 $ret = array($post->up, $post->i);
455 function hasAttachments() {
457 $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);
458 $post->query($query);
460 $n_attachments = intval($post->n_attachments);
462 return $n_attachments;
465 function attachments() {
468 $f2p = new File_to_post;
469 $f2p->post_id = $this->id;
471 while ($f2p->fetch()) {
472 $f = File::staticGet($f2p->file_id);
479 function getStreamByIds($ids)
481 $cache = common_memcache();
483 if (!empty($cache)) {
485 foreach ($ids as $id) {
486 $n = Notice::staticGet('id', $id);
491 return new ArrayWrapper($notices);
493 $notice = new Notice();
495 //if no IDs requested, just return the notice object
498 $notice->whereAdd('id in (' . implode(', ', $ids) . ')');
504 while ($notice->fetch()) {
505 $temp[$notice->id] = clone($notice);
510 foreach ($ids as $id) {
511 if (array_key_exists($id, $temp)) {
512 $wrapped[] = $temp[$id];
516 return new ArrayWrapper($wrapped);
520 function publicStream($offset=0, $limit=20, $since_id=0, $max_id=0, $since=null)
522 $ids = Notice::stream(array('Notice', '_publicStreamDirect'),
525 $offset, $limit, $since_id, $max_id, $since);
527 return Notice::getStreamByIds($ids);
530 function _publicStreamDirect($offset=0, $limit=20, $since_id=0, $max_id=0, $since=null)
532 $notice = new Notice();
534 $notice->selectAdd(); // clears it
535 $notice->selectAdd('id');
537 $notice->orderBy('id DESC');
539 if (!is_null($offset)) {
540 $notice->limit($offset, $limit);
543 if (common_config('public', 'localonly')) {
544 $notice->whereAdd('is_local = ' . Notice::LOCAL_PUBLIC);
546 # -1 == blacklisted, -2 == gateway (i.e. Twitter)
547 $notice->whereAdd('is_local !='. Notice::LOCAL_NONPUBLIC);
548 $notice->whereAdd('is_local !='. Notice::GATEWAY);
551 if ($since_id != 0) {
552 $notice->whereAdd('id > ' . $since_id);
556 $notice->whereAdd('id <= ' . $max_id);
559 if (!is_null($since)) {
560 $notice->whereAdd('created > \'' . date('Y-m-d H:i:s', $since) . '\'');
565 if ($notice->find()) {
566 while ($notice->fetch()) {
567 $ids[] = $notice->id;
577 function conversationStream($id, $offset=0, $limit=20, $since_id=0, $max_id=0, $since=null)
579 $ids = Notice::stream(array('Notice', '_conversationStreamDirect'),
581 'notice:conversation_ids:'.$id,
582 $offset, $limit, $since_id, $max_id, $since);
584 return Notice::getStreamByIds($ids);
587 function _conversationStreamDirect($id, $offset=0, $limit=20, $since_id=0, $max_id=0, $since=null)
589 $notice = new Notice();
591 $notice->selectAdd(); // clears it
592 $notice->selectAdd('id');
594 $notice->conversation = $id;
596 $notice->orderBy('id DESC');
598 if (!is_null($offset)) {
599 $notice->limit($offset, $limit);
602 if ($since_id != 0) {
603 $notice->whereAdd('id > ' . $since_id);
607 $notice->whereAdd('id <= ' . $max_id);
610 if (!is_null($since)) {
611 $notice->whereAdd('created > \'' . date('Y-m-d H:i:s', $since) . '\'');
616 if ($notice->find()) {
617 while ($notice->fetch()) {
618 $ids[] = $notice->id;
629 * @param $groups array of Group *objects*
630 * @param $recipients array of profile *ids*
632 function whoGets($groups=null, $recipients=null)
634 $c = self::memcache();
637 $ni = $c->get(common_cache_key('notice:who_gets:'.$this->id));
643 if (is_null($groups)) {
644 $groups = $this->getGroups();
647 if (is_null($recipients)) {
648 $recipients = $this->getReplies();
651 $users = $this->getSubscribedUsers();
653 // FIXME: kind of ignoring 'transitional'...
654 // we'll probably stop supporting inboxless mode
659 foreach ($users as $id) {
660 $ni[$id] = NOTICE_INBOX_SOURCE_SUB;
663 $profile = $this->getProfile();
665 foreach ($groups as $group) {
666 $users = $group->getUserMembers();
667 foreach ($users as $id) {
668 if (!array_key_exists($id, $ni)) {
669 $user = User::staticGet('id', $id);
670 if (!$user->hasBlocked($profile)) {
671 $ni[$id] = NOTICE_INBOX_SOURCE_GROUP;
677 foreach ($recipients as $recipient) {
679 if (!array_key_exists($recipient, $ni)) {
680 $recipientUser = User::staticGet('id', $recipient);
681 if (!empty($recipientUser)) {
682 $ni[$recipient] = NOTICE_INBOX_SOURCE_REPLY;
688 // XXX: pack this data better
689 $c->set(common_cache_key('notice:who_gets:'.$this->id), $ni);
695 function addToInboxes($groups, $recipients)
697 $ni = $this->whoGets($groups, $recipients);
699 $ids = array_keys($ni);
701 // We remove the author (if they're a local user),
702 // since we'll have already done this in distribute()
704 $i = array_search($this->profile_id, $ids);
712 Inbox::bulkInsert($this->id, $ids);
717 function getSubscribedUsers()
721 if(common_config('db','quote_identifiers'))
722 $user_table = '"user"';
723 else $user_table = 'user';
727 'FROM '. $user_table .' JOIN subscription '.
728 'ON '. $user_table .'.id = subscription.subscriber ' .
729 'WHERE subscription.subscribed = %d ';
731 $user->query(sprintf($qry, $this->profile_id));
735 while ($user->fetch()) {
745 * @return array of Group objects
747 function saveGroups()
749 // Don't save groups for repeats
751 if (!empty($this->repeat_of)) {
757 /* extract all !group */
758 $count = preg_match_all('/(?:^|\s)!([A-Za-z0-9]{1,64})/',
759 strtolower($this->content),
765 $profile = $this->getProfile();
767 /* Add them to the database */
769 foreach (array_unique($match[1]) as $nickname) {
770 /* XXX: remote groups. */
771 $group = User_group::getForNickname($nickname);
777 // we automatically add a tag for every group name, too
779 $tag = Notice_tag::pkeyGet(array('tag' => common_canonical_tag($nickname),
780 'notice_id' => $this->id));
783 $this->saveTag($nickname);
786 if ($profile->isMember($group)) {
788 $result = $this->addToGroupInbox($group);
791 common_log_db_error($gi, 'INSERT', __FILE__);
794 $groups[] = clone($group);
801 function addToGroupInbox($group)
803 $gi = Group_inbox::pkeyGet(array('group_id' => $group->id,
804 'notice_id' => $this->id));
808 $gi = new Group_inbox();
810 $gi->group_id = $group->id;
811 $gi->notice_id = $this->id;
812 $gi->created = $this->created;
814 $result = $gi->insert();
817 common_log_db_error($gi, 'INSERT', __FILE__);
818 throw new ServerException(_('Problem saving group inbox.'));
821 self::blow('user_group:notice_ids:%d', $gi->group_id);
827 function saveKnownReplies($uris)
829 foreach ($uris as $uri) {
831 $user = User::staticGet('uri', $uri);
835 $reply = new Reply();
837 $reply->notice_id = $this->id;
838 $reply->profile_id = $user->id;
840 $id = $reply->insert();
848 * @return array of integer profile IDs
851 function saveReplies()
853 // Don't save reply data for repeats
855 if (!empty($this->repeat_of)) {
859 $sender = Profile::staticGet($this->profile_id);
861 $mentions = common_find_mentions($this->profile_id, $this->content);
865 // store replied only for first @ (what user/notice what the reply directed,
866 // we assume first @ is it)
868 foreach ($mentions as $mention) {
870 foreach ($mention['mentioned'] as $mentioned) {
872 // skip if they're already covered
874 if (!empty($replied[$mentioned->id])) {
878 // Don't save replies from blocked profile to local user
880 $mentioned_user = User::staticGet('id', $mentioned->id);
881 if (!empty($mentioned_user) && $mentioned_user->hasBlocked($sender)) {
885 $reply = new Reply();
887 $reply->notice_id = $this->id;
888 $reply->profile_id = $mentioned->id;
890 $id = $reply->insert();
893 common_log_db_error($reply, 'INSERT', __FILE__);
894 throw new ServerException("Couldn't save reply for {$this->id}, {$mentioned->id}");
896 $replied[$mentioned->id] = 1;
901 $recipientIds = array_keys($replied);
903 foreach ($recipientIds as $recipientId) {
904 $user = User::staticGet('id', $recipientId);
906 self::blow('reply:stream:%d', $reply->profile_id);
907 mail_notify_attn($user, $this);
911 return $recipientIds;
914 function getReplies()
920 $reply = new Reply();
922 $reply->selectAdd('profile_id');
923 $reply->notice_id = $this->id;
925 if ($reply->find()) {
926 while($reply->fetch()) {
927 $ids[] = $reply->profile_id;
937 * Same calculation as saveGroups but without the saving
938 * @fixme merge the functions
939 * @return array of Group_inbox objects
943 // Don't save groups for repeats
945 if (!empty($this->repeat_of)) {
953 $gi = new Group_inbox();
956 $gi->selectAdd('group_id');
958 $gi->notice_id = $this->id;
961 while ($gi->fetch()) {
962 $groups[] = clone($gi);
971 function asAtomEntry($namespace=false, $source=false)
973 $profile = $this->getProfile();
975 $xs = new XMLStringer(true);
978 $attrs = array('xmlns' => 'http://www.w3.org/2005/Atom',
979 'xmlns:thr' => 'http://purl.org/syndication/thread/1.0',
980 'xmlns:georss' => 'http://www.georss.org/georss',
981 'xmlns:activity' => 'http://activitystrea.ms/spec/1.0/',
982 'xmlns:ostatus' => 'http://ostatus.org/schema/1.0');
987 $xs->elementStart('entry', $attrs);
990 $xs->elementStart('source');
991 $xs->element('title', null, $profile->nickname . " - " . common_config('site', 'name'));
992 $xs->element('link', array('href' => $profile->profileurl));
993 $user = User::staticGet('id', $profile->id);
995 $atom_feed = common_local_url('ApiTimelineUser',
996 array('format' => 'atom',
997 'id' => $profile->nickname));
998 $xs->element('link', array('rel' => 'self',
999 'type' => 'application/atom+xml',
1000 'href' => $profile->profileurl));
1001 $xs->element('link', array('rel' => 'license',
1002 'href' => common_config('license', 'url')));
1005 $xs->element('icon', null, $profile->avatarUrl(AVATAR_PROFILE_SIZE));
1009 $xs->elementEnd('source');
1012 $xs->element('title', null, $this->content);
1013 $xs->element('summary', null, $this->content);
1015 $xs->raw($profile->asAtomAuthor());
1016 $xs->raw($profile->asActivityActor());
1018 $xs->element('link', array('rel' => 'alternate',
1019 'type' => 'text/html',
1020 'href' => $this->bestUrl()));
1022 $xs->element('id', null, $this->uri);
1024 $xs->element('published', null, common_date_w3dtf($this->created));
1025 $xs->element('updated', null, common_date_w3dtf($this->created));
1027 if ($this->reply_to) {
1028 $reply_notice = Notice::staticGet('id', $this->reply_to);
1029 if (!empty($reply_notice)) {
1030 $xs->element('link', array('rel' => 'related',
1031 'href' => $reply_notice->bestUrl()));
1032 $xs->element('thr:in-reply-to',
1033 array('ref' => $reply_notice->uri,
1034 'href' => $reply_notice->bestUrl()));
1038 if (!empty($this->conversation)) {
1040 $conv = Conversation::staticGet('id', $this->conversation);
1042 if (!empty($conv)) {
1045 'rel' => 'ostatus:conversation',
1046 'href' => $conv->uri
1052 $reply_ids = $this->getReplies();
1054 foreach ($reply_ids as $id) {
1055 $profile = Profile::staticGet('id', $id);
1056 if (!empty($profile)) {
1059 'rel' => 'ostatus:attention',
1060 'href' => $profile->getUri()
1066 if (!empty($this->repeat_of)) {
1067 $repeat = Notice::staticGet('id', $this->repeat_of);
1068 if (!empty($repeat)) {
1071 array('ref' => $repeat->uri, 'href' => $repeat->bestUrl())
1076 $xs->element('content', array('type' => 'html'), $this->rendered);
1078 $tag = new Notice_tag();
1079 $tag->notice_id = $this->id;
1081 while ($tag->fetch()) {
1082 $xs->element('category', array('term' => $tag->tag));
1088 $attachments = $this->attachments();
1090 foreach($attachments as $attachment){
1091 $enclosure=$attachment->getEnclosure();
1093 $attributes = array('rel'=>'enclosure','href'=>$enclosure->url,'type'=>$enclosure->mimetype,'length'=>$enclosure->size);
1094 if($enclosure->title){
1095 $attributes['title']=$enclosure->title;
1097 $xs->element('link', $attributes, null);
1102 if (!empty($this->lat) && !empty($this->lon)) {
1103 $xs->element('georss:point', null, $this->lat . ' ' . $this->lon);
1106 $xs->elementEnd('entry');
1108 return $xs->getString();
1112 * Returns an XML string fragment with a reference to a notice as an
1113 * Activity Streams noun object with the given element type.
1115 * Assumes that 'activity' namespace has been previously defined.
1117 * @param string $element one of 'subject', 'object', 'target'
1120 function asActivityNoun($element)
1122 $xs = new XMLStringer(true);
1124 $xs->elementStart('activity:' . $element);
1125 $xs->element('activity:object-type',
1127 'http://activitystrea.ms/schema/1.0/note');
1131 $xs->element('content',
1132 array('type' => 'text/html'),
1134 $xs->element('link',
1135 array('type' => 'text/html',
1136 'rel' => 'alternate',
1137 'href' => $this->bestUrl()));
1138 $xs->elementEnd('activity:' . $element);
1140 return $xs->getString();
1145 if (!empty($this->url)) {
1147 } else if (!empty($this->uri) && preg_match('/^https?:/', $this->uri)) {
1150 return common_local_url('shownotice',
1151 array('notice' => $this->id));
1155 function stream($fn, $args, $cachekey, $offset=0, $limit=20, $since_id=0, $max_id=0, $since=null)
1157 $cache = common_memcache();
1159 if (empty($cache) ||
1160 $since_id != 0 || $max_id != 0 || (!is_null($since) && $since > 0) ||
1162 ($offset + $limit) > NOTICE_CACHE_WINDOW) {
1163 return call_user_func_array($fn, array_merge($args, array($offset, $limit, $since_id,
1167 $idkey = common_cache_key($cachekey);
1169 $idstr = $cache->get($idkey);
1171 if ($idstr !== false) {
1172 // Cache hit! Woohoo!
1173 $window = explode(',', $idstr);
1174 $ids = array_slice($window, $offset, $limit);
1178 $laststr = $cache->get($idkey.';last');
1180 if ($laststr !== false) {
1181 $window = explode(',', $laststr);
1182 $last_id = $window[0];
1183 $new_ids = call_user_func_array($fn, array_merge($args, array(0, NOTICE_CACHE_WINDOW,
1184 $last_id, 0, null)));
1186 $new_window = array_merge($new_ids, $window);
1188 $new_windowstr = implode(',', $new_window);
1190 $result = $cache->set($idkey, $new_windowstr);
1191 $result = $cache->set($idkey . ';last', $new_windowstr);
1193 $ids = array_slice($new_window, $offset, $limit);
1198 $window = call_user_func_array($fn, array_merge($args, array(0, NOTICE_CACHE_WINDOW,
1201 $windowstr = implode(',', $window);
1203 $result = $cache->set($idkey, $windowstr);
1204 $result = $cache->set($idkey . ';last', $windowstr);
1206 $ids = array_slice($window, $offset, $limit);
1212 * Determine which notice, if any, a new notice is in reply to.
1214 * For conversation tracking, we try to see where this notice fits
1215 * in the tree. Rough algorithm is:
1217 * if (reply_to is set and valid) {
1219 * } else if ((source not API or Web) and (content starts with "T NAME" or "@name ")) {
1220 * return ID of last notice by initial @name in content;
1223 * Note that all @nickname instances will still be used to save "reply" records,
1224 * so the notice shows up in the mentioned users' "replies" tab.
1226 * @param integer $reply_to ID passed in by Web or API
1227 * @param integer $profile_id ID of author
1228 * @param string $source Source tag, like 'web' or 'gwibber'
1229 * @param string $content Final notice content
1231 * @return integer ID of replied-to notice, or null for not a reply.
1234 static function getReplyTo($reply_to, $profile_id, $source, $content)
1236 static $lb = array('xmpp', 'mail', 'sms', 'omb');
1238 // If $reply_to is specified, we check that it exists, and then
1239 // return it if it does
1241 if (!empty($reply_to)) {
1242 $reply_notice = Notice::staticGet('id', $reply_to);
1243 if (!empty($reply_notice)) {
1248 // If it's not a "low bandwidth" source (one where you can't set
1249 // a reply_to argument), we return. This is mostly web and API
1252 if (!in_array($source, $lb)) {
1256 // Is there an initial @ or T?
1258 if (preg_match('/^T ([A-Z0-9]{1,64}) /', $content, $match) ||
1259 preg_match('/^@([a-z0-9]{1,64})\s+/', $content, $match)) {
1260 $nickname = common_canonical_nickname($match[1]);
1265 // Figure out who that is.
1267 $sender = Profile::staticGet('id', $profile_id);
1268 if (empty($sender)) {
1272 $recipient = common_relative_profile($sender, $nickname, common_sql_now());
1274 if (empty($recipient)) {
1278 // Get their last notice
1280 $last = $recipient->getCurrentNotice();
1282 if (!empty($last)) {
1287 static function maxContent()
1289 $contentlimit = common_config('notice', 'contentlimit');
1290 // null => use global limit (distinct from 0!)
1291 if (is_null($contentlimit)) {
1292 $contentlimit = common_config('site', 'textlimit');
1294 return $contentlimit;
1297 static function contentTooLong($content)
1299 $contentlimit = self::maxContent();
1300 return ($contentlimit > 0 && !empty($content) && (mb_strlen($content) > $contentlimit));
1303 function getLocation()
1307 if (!empty($this->location_id) && !empty($this->location_ns)) {
1308 $location = Location::fromId($this->location_id, $this->location_ns);
1311 if (is_null($location)) { // no ID, or Location::fromId() failed
1312 if (!empty($this->lat) && !empty($this->lon)) {
1313 $location = Location::fromLatLon($this->lat, $this->lon);
1320 function repeat($repeater_id, $source)
1322 $author = Profile::staticGet('id', $this->profile_id);
1324 $content = sprintf(_('RT @%1$s %2$s'),
1328 $maxlen = common_config('site', 'textlimit');
1329 if ($maxlen > 0 && mb_strlen($content) > $maxlen) {
1330 // Web interface and current Twitter API clients will
1331 // pull the original notice's text, but some older
1332 // clients and RSS/Atom feeds will see this trimmed text.
1334 // Unfortunately this is likely to lose tags or URLs
1335 // at the end of long notices.
1336 $content = mb_substr($content, 0, $maxlen - 4) . ' ...';
1339 return self::saveNew($repeater_id, $content, $source,
1340 array('repeat_of' => $this->id));
1343 // These are supposed to be in chron order!
1345 function repeatStream($limit=100)
1347 $cache = common_memcache();
1349 if (empty($cache)) {
1350 $ids = $this->_repeatStreamDirect($limit);
1352 $idstr = $cache->get(common_cache_key('notice:repeats:'.$this->id));
1353 if ($idstr !== false) {
1354 $ids = explode(',', $idstr);
1356 $ids = $this->_repeatStreamDirect(100);
1357 $cache->set(common_cache_key('notice:repeats:'.$this->id), implode(',', $ids));
1360 // We do a max of 100, so slice down to limit
1361 $ids = array_slice($ids, 0, $limit);
1365 return Notice::getStreamByIds($ids);
1368 function _repeatStreamDirect($limit)
1370 $notice = new Notice();
1372 $notice->selectAdd(); // clears it
1373 $notice->selectAdd('id');
1375 $notice->repeat_of = $this->id;
1377 $notice->orderBy('created'); // NB: asc!
1379 if (!is_null($offset)) {
1380 $notice->limit($offset, $limit);
1385 if ($notice->find()) {
1386 while ($notice->fetch()) {
1387 $ids[] = $notice->id;
1397 function locationOptions($lat, $lon, $location_id, $location_ns, $profile = null)
1401 if (!empty($location_id) && !empty($location_ns)) {
1403 $options['location_id'] = $location_id;
1404 $options['location_ns'] = $location_ns;
1406 $location = Location::fromId($location_id, $location_ns);
1408 if (!empty($location)) {
1409 $options['lat'] = $location->lat;
1410 $options['lon'] = $location->lon;
1413 } else if (!empty($lat) && !empty($lon)) {
1415 $options['lat'] = $lat;
1416 $options['lon'] = $lon;
1418 $location = Location::fromLatLon($lat, $lon);
1420 if (!empty($location)) {
1421 $options['location_id'] = $location->location_id;
1422 $options['location_ns'] = $location->location_ns;
1424 } else if (!empty($profile)) {
1426 if (isset($profile->lat) && isset($profile->lon)) {
1427 $options['lat'] = $profile->lat;
1428 $options['lon'] = $profile->lon;
1431 if (isset($profile->location_id) && isset($profile->location_ns)) {
1432 $options['location_id'] = $profile->location_id;
1433 $options['location_ns'] = $profile->location_ns;
1440 function clearReplies()
1442 $replyNotice = new Notice();
1443 $replyNotice->reply_to = $this->id;
1445 //Null any notices that are replies to this notice
1447 if ($replyNotice->find()) {
1448 while ($replyNotice->fetch()) {
1449 $orig = clone($replyNotice);
1450 $replyNotice->reply_to = null;
1451 $replyNotice->update($orig);
1457 $reply = new Reply();
1458 $reply->notice_id = $this->id;
1460 if ($reply->find()) {
1461 while($reply->fetch()) {
1462 self::blow('reply:stream:%d', $reply->profile_id);
1470 function clearRepeats()
1472 $repeatNotice = new Notice();
1473 $repeatNotice->repeat_of = $this->id;
1475 //Null any notices that are repeats of this notice
1477 if ($repeatNotice->find()) {
1478 while ($repeatNotice->fetch()) {
1479 $orig = clone($repeatNotice);
1480 $repeatNotice->repeat_of = null;
1481 $repeatNotice->update($orig);
1486 function clearFaves()
1489 $fave->notice_id = $this->id;
1491 if ($fave->find()) {
1492 while ($fave->fetch()) {
1493 self::blow('fave:ids_by_user_own:%d', $fave->user_id);
1494 self::blow('fave:ids_by_user_own:%d;last', $fave->user_id);
1495 self::blow('fave:ids_by_user:%d', $fave->user_id);
1496 self::blow('fave:ids_by_user:%d;last', $fave->user_id);
1504 function clearTags()
1506 $tag = new Notice_tag();
1507 $tag->notice_id = $this->id;
1510 while ($tag->fetch()) {
1511 self::blow('profile:notice_ids_tagged:%d:%s', $this->profile_id, common_keyize($tag->tag));
1512 self::blow('profile:notice_ids_tagged:%d:%s;last', $this->profile_id, common_keyize($tag->tag));
1513 self::blow('notice_tag:notice_ids:%s', common_keyize($tag->tag));
1514 self::blow('notice_tag:notice_ids:%s;last', common_keyize($tag->tag));
1522 function clearGroupInboxes()
1524 $gi = new Group_inbox();
1526 $gi->notice_id = $this->id;
1529 while ($gi->fetch()) {
1530 self::blow('user_group:notice_ids:%d', $gi->group_id);
1538 function distribute()
1540 // We always insert for the author so they don't
1543 $user = User::staticGet('id', $this->profile_id);
1544 if (!empty($user)) {
1545 Inbox::insertNotice($user->id, $this->id);
1548 if (common_config('queue', 'inboxes')) {
1549 // If there's a failure, we want to _force_
1550 // distribution at this point.
1552 $qm = QueueManager::get();
1553 $qm->enqueue($this, 'distrib');
1554 } catch (Exception $e) {
1555 // If the exception isn't transient, this
1556 // may throw more exceptions as DQH does
1557 // its own enqueueing. So, we ignore them!
1559 $handler = new DistribQueueHandler();
1560 $handler->handle($this);
1561 } catch (Exception $e) {
1562 common_log(LOG_ERR, "emergency redistribution resulted in " . $e->getMessage());
1564 // Re-throw so somebody smarter can handle it.
1568 $handler = new DistribQueueHandler();
1569 $handler->handle($this);
1575 $result = parent::insert();
1578 // Profile::hasRepeated() abuses pkeyGet(), so we
1579 // have to clear manually
1580 if (!empty($this->repeat_of)) {
1581 $c = self::memcache();
1583 $ck = self::multicacheKey('Notice',
1584 array('profile_id' => $this->profile_id,
1585 'repeat_of' => $this->repeat_of));