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 $notice->conversation = $notice->id;
317 if (!$notice->update($orig)) {
318 common_log_db_error($notice, 'UPDATE', __FILE__);
319 throw new ServerException(_('Problem saving notice.'));
325 # Clear the cache for subscribed users, so they'll update at next request
326 # XXX: someone clever could prepend instead of clearing the cache
327 $notice->blowOnInsert();
329 $notice->distribute();
334 function blowOnInsert()
336 self::blow('profile:notice_ids:%d', $this->profile_id);
337 self::blow('public');
339 if ($this->conversation != $this->id) {
340 self::blow('notice:conversation_ids:%d', $this->conversation);
343 if (!empty($this->repeat_of)) {
344 self::blow('notice:repeats:%d', $this->repeat_of);
347 $original = Notice::staticGet('id', $this->repeat_of);
349 if (!empty($original)) {
350 $originalUser = User::staticGet('id', $original->profile_id);
351 if (!empty($originalUser)) {
352 self::blow('user:repeats_of_me:%d', $originalUser->id);
356 $profile = Profile::staticGet($this->profile_id);
357 $profile->blowNoticeCount();
360 /** save all urls in the notice to the db
362 * follow redirects and save all available file information
363 * (mimetype, date, size, oembed, etc.)
367 function saveUrls() {
368 common_replace_urls_callback($this->content, array($this, 'saveUrl'), $this->id);
371 function saveUrl($data) {
372 list($url, $notice_id) = $data;
373 File::processNew($url, $notice_id);
376 static function checkDupes($profile_id, $content) {
377 $profile = Profile::staticGet($profile_id);
378 if (empty($profile)) {
381 $notice = $profile->getNotices(0, NOTICE_CACHE_WINDOW);
382 if (!empty($notice)) {
384 while ($notice->fetch()) {
385 if (time() - strtotime($notice->created) >= common_config('site', 'dupelimit')) {
387 } else if ($notice->content == $content) {
392 # If we get here, oldest item in cache window is not
393 # old enough for dupe limit; do direct check against DB
394 $notice = new Notice();
395 $notice->profile_id = $profile_id;
396 $notice->content = $content;
397 if (common_config('db','type') == 'pgsql')
398 $notice->whereAdd('extract(epoch from now() - created) < ' . common_config('site', 'dupelimit'));
400 $notice->whereAdd('now() - created < ' . common_config('site', 'dupelimit'));
402 $cnt = $notice->count();
406 static function checkEditThrottle($profile_id) {
407 $profile = Profile::staticGet($profile_id);
408 if (empty($profile)) {
412 $notice = $profile->getNotices(common_config('throttle', 'count') - 1, 1);
413 if ($notice && $notice->fetch()) {
414 # If the Nth notice was posted less than timespan seconds ago
415 if (time() - strtotime($notice->created) <= common_config('throttle', 'timespan')) {
420 # Either not N notices in the stream, OR the Nth was not posted within timespan seconds
424 function getUploadedAttachment() {
426 $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"';
427 $post->query($query);
429 if (empty($post->up) || empty($post->i)) {
432 $ret = array($post->up, $post->i);
438 function hasAttachments() {
440 $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);
441 $post->query($query);
443 $n_attachments = intval($post->n_attachments);
445 return $n_attachments;
448 function attachments() {
451 $f2p = new File_to_post;
452 $f2p->post_id = $this->id;
454 while ($f2p->fetch()) {
455 $f = File::staticGet($f2p->file_id);
462 function getStreamByIds($ids)
464 $cache = common_memcache();
466 if (!empty($cache)) {
468 foreach ($ids as $id) {
469 $n = Notice::staticGet('id', $id);
474 return new ArrayWrapper($notices);
476 $notice = new Notice();
478 //if no IDs requested, just return the notice object
481 $notice->whereAdd('id in (' . implode(', ', $ids) . ')');
487 while ($notice->fetch()) {
488 $temp[$notice->id] = clone($notice);
493 foreach ($ids as $id) {
494 if (array_key_exists($id, $temp)) {
495 $wrapped[] = $temp[$id];
499 return new ArrayWrapper($wrapped);
503 function publicStream($offset=0, $limit=20, $since_id=0, $max_id=0, $since=null)
505 $ids = Notice::stream(array('Notice', '_publicStreamDirect'),
508 $offset, $limit, $since_id, $max_id, $since);
510 return Notice::getStreamByIds($ids);
513 function _publicStreamDirect($offset=0, $limit=20, $since_id=0, $max_id=0, $since=null)
515 $notice = new Notice();
517 $notice->selectAdd(); // clears it
518 $notice->selectAdd('id');
520 $notice->orderBy('id DESC');
522 if (!is_null($offset)) {
523 $notice->limit($offset, $limit);
526 if (common_config('public', 'localonly')) {
527 $notice->whereAdd('is_local = ' . Notice::LOCAL_PUBLIC);
529 # -1 == blacklisted, -2 == gateway (i.e. Twitter)
530 $notice->whereAdd('is_local !='. Notice::LOCAL_NONPUBLIC);
531 $notice->whereAdd('is_local !='. Notice::GATEWAY);
534 if ($since_id != 0) {
535 $notice->whereAdd('id > ' . $since_id);
539 $notice->whereAdd('id <= ' . $max_id);
542 if (!is_null($since)) {
543 $notice->whereAdd('created > \'' . date('Y-m-d H:i:s', $since) . '\'');
548 if ($notice->find()) {
549 while ($notice->fetch()) {
550 $ids[] = $notice->id;
560 function conversationStream($id, $offset=0, $limit=20, $since_id=0, $max_id=0, $since=null)
562 $ids = Notice::stream(array('Notice', '_conversationStreamDirect'),
564 'notice:conversation_ids:'.$id,
565 $offset, $limit, $since_id, $max_id, $since);
567 return Notice::getStreamByIds($ids);
570 function _conversationStreamDirect($id, $offset=0, $limit=20, $since_id=0, $max_id=0, $since=null)
572 $notice = new Notice();
574 $notice->selectAdd(); // clears it
575 $notice->selectAdd('id');
577 $notice->conversation = $id;
579 $notice->orderBy('id DESC');
581 if (!is_null($offset)) {
582 $notice->limit($offset, $limit);
585 if ($since_id != 0) {
586 $notice->whereAdd('id > ' . $since_id);
590 $notice->whereAdd('id <= ' . $max_id);
593 if (!is_null($since)) {
594 $notice->whereAdd('created > \'' . date('Y-m-d H:i:s', $since) . '\'');
599 if ($notice->find()) {
600 while ($notice->fetch()) {
601 $ids[] = $notice->id;
612 * @param $groups array of Group *objects*
613 * @param $recipients array of profile *ids*
615 function whoGets($groups=null, $recipients=null)
617 $c = self::memcache();
620 $ni = $c->get(common_cache_key('notice:who_gets:'.$this->id));
626 if (is_null($groups)) {
627 $groups = $this->getGroups();
630 if (is_null($recipients)) {
631 $recipients = $this->getReplies();
634 $users = $this->getSubscribedUsers();
636 // FIXME: kind of ignoring 'transitional'...
637 // we'll probably stop supporting inboxless mode
642 foreach ($users as $id) {
643 $ni[$id] = NOTICE_INBOX_SOURCE_SUB;
646 $profile = $this->getProfile();
648 foreach ($groups as $group) {
649 $users = $group->getUserMembers();
650 foreach ($users as $id) {
651 if (!array_key_exists($id, $ni)) {
652 $user = User::staticGet('id', $id);
653 if (!$user->hasBlocked($profile)) {
654 $ni[$id] = NOTICE_INBOX_SOURCE_GROUP;
660 foreach ($recipients as $recipient) {
662 if (!array_key_exists($recipient, $ni)) {
663 $recipientUser = User::staticGet('id', $recipient);
664 if (!empty($recipientUser)) {
665 $ni[$recipient] = NOTICE_INBOX_SOURCE_REPLY;
671 // XXX: pack this data better
672 $c->set(common_cache_key('notice:who_gets:'.$this->id), $ni);
678 function addToInboxes($groups, $recipients)
680 $ni = $this->whoGets($groups, $recipients);
682 Inbox::bulkInsert($this->id, array_keys($ni));
687 function getSubscribedUsers()
691 if(common_config('db','quote_identifiers'))
692 $user_table = '"user"';
693 else $user_table = 'user';
697 'FROM '. $user_table .' JOIN subscription '.
698 'ON '. $user_table .'.id = subscription.subscriber ' .
699 'WHERE subscription.subscribed = %d ';
701 $user->query(sprintf($qry, $this->profile_id));
705 while ($user->fetch()) {
715 * @return array of Group objects
717 function saveGroups()
719 // Don't save groups for repeats
721 if (!empty($this->repeat_of)) {
727 /* extract all !group */
728 $count = preg_match_all('/(?:^|\s)!([A-Za-z0-9]{1,64})/',
729 strtolower($this->content),
735 $profile = $this->getProfile();
737 /* Add them to the database */
739 foreach (array_unique($match[1]) as $nickname) {
740 /* XXX: remote groups. */
741 $group = User_group::getForNickname($nickname);
747 // we automatically add a tag for every group name, too
749 $tag = Notice_tag::pkeyGet(array('tag' => common_canonical_tag($nickname),
750 'notice_id' => $this->id));
753 $this->saveTag($nickname);
756 if ($profile->isMember($group)) {
758 $result = $this->addToGroupInbox($group);
761 common_log_db_error($gi, 'INSERT', __FILE__);
764 $groups[] = clone($group);
771 function addToGroupInbox($group)
773 $gi = Group_inbox::pkeyGet(array('group_id' => $group->id,
774 'notice_id' => $this->id));
778 $gi = new Group_inbox();
780 $gi->group_id = $group->id;
781 $gi->notice_id = $this->id;
782 $gi->created = $this->created;
784 $result = $gi->insert();
787 common_log_db_error($gi, 'INSERT', __FILE__);
788 throw new ServerException(_('Problem saving group inbox.'));
791 self::blow('user_group:notice_ids:%d', $gi->group_id);
798 * @return array of integer profile IDs
800 function saveReplies()
802 // Don't save reply data for repeats
804 if (!empty($this->repeat_of)) {
808 // Alternative reply format
810 if (preg_match('/^T ([A-Z0-9]{1,64}) /', $this->content, $match)) {
813 // extract all @messages
814 $cnt = preg_match_all('/(?:^|\s)@([a-z0-9]{1,64})/', $this->content, $match);
818 if ($cnt || $tname) {
819 // XXX: is there another way to make an array copy?
820 $names = ($tname) ? array_unique(array_merge(array(strtolower($tname)), $match[1])) : array_unique($match[1]);
823 $sender = Profile::staticGet($this->profile_id);
827 // store replied only for first @ (what user/notice what the reply directed,
828 // we assume first @ is it)
830 for ($i=0; $i<count($names); $i++) {
831 $nickname = $names[$i];
832 $recipient = common_relative_profile($sender, $nickname, $this->created);
833 if (empty($recipient)) {
836 // Don't save replies from blocked profile to local user
837 $recipient_user = User::staticGet('id', $recipient->id);
838 if (!empty($recipient_user) && $recipient_user->hasBlocked($sender)) {
841 $reply = new Reply();
842 $reply->notice_id = $this->id;
843 $reply->profile_id = $recipient->id;
844 $id = $reply->insert();
846 $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError');
847 common_log(LOG_ERR, 'DB error inserting reply: ' . $last_error->message);
848 common_server_error(sprintf(_('DB error inserting reply: %s'), $last_error->message));
851 $replied[$recipient->id] = 1;
855 // Hash format replies, too
856 $cnt = preg_match_all('/(?:^|\s)@#([a-z0-9]{1,64})/', $this->content, $match);
858 foreach ($match[1] as $tag) {
859 $tagged = Profile_tag::getTagged($sender->id, $tag);
860 foreach ($tagged as $t) {
861 if (!$replied[$t->id]) {
862 // Don't save replies from blocked profile to local user
863 $t_user = User::staticGet('id', $t->id);
864 if ($t_user && $t_user->hasBlocked($sender)) {
867 $reply = new Reply();
868 $reply->notice_id = $this->id;
869 $reply->profile_id = $t->id;
870 $id = $reply->insert();
872 common_log_db_error($reply, 'INSERT', __FILE__);
875 $replied[$recipient->id] = 1;
882 $recipientIds = array_keys($replied);
884 foreach ($recipientIds as $recipientId) {
885 $user = User::staticGet('id', $recipientId);
887 self::blow('reply:stream:%d', $reply->profile_id);
888 mail_notify_attn($user, $this);
892 return $recipientIds;
895 function getReplies()
901 $reply = new Reply();
903 $reply->selectAdd('profile_id');
904 $reply->notice_id = $this->id;
906 if ($reply->find()) {
907 while($reply->fetch()) {
908 $ids[] = $reply->profile_id;
918 * Same calculation as saveGroups but without the saving
919 * @fixme merge the functions
920 * @return array of Group objects
924 // Don't save groups for repeats
926 if (!empty($this->repeat_of)) {
934 $gi = new Group_inbox();
937 $gi->selectAdd('group_id');
939 $gi->notice_id = $this->id;
942 while ($gi->fetch()) {
943 $groups[] = clone($gi);
952 function asAtomEntry($namespace=false, $source=false)
954 $profile = $this->getProfile();
956 $xs = new XMLStringer(true);
959 $attrs = array('xmlns' => 'http://www.w3.org/2005/Atom',
960 'xmlns:thr' => 'http://purl.org/syndication/thread/1.0');
965 $xs->elementStart('entry', $attrs);
968 $xs->elementStart('source');
969 $xs->element('title', null, $profile->nickname . " - " . common_config('site', 'name'));
970 $xs->element('link', array('href' => $profile->profileurl));
971 $user = User::staticGet('id', $profile->id);
973 $atom_feed = common_local_url('ApiTimelineUser',
974 array('format' => 'atom',
975 'id' => $profile->nickname));
976 $xs->element('link', array('rel' => 'self',
977 'type' => 'application/atom+xml',
978 'href' => $profile->profileurl));
979 $xs->element('link', array('rel' => 'license',
980 'href' => common_config('license', 'url')));
983 $xs->element('icon', null, $profile->avatarUrl(AVATAR_PROFILE_SIZE));
986 $xs->elementStart('author');
987 $xs->element('name', null, $profile->nickname);
988 $xs->element('uri', null, $profile->profileurl);
989 $xs->elementEnd('author');
992 $xs->elementEnd('source');
995 $xs->element('title', null, $this->content);
996 $xs->element('summary', null, $this->content);
998 $xs->element('link', array('rel' => 'alternate',
999 'href' => $this->bestUrl()));
1001 $xs->element('id', null, $this->uri);
1003 $xs->element('published', null, common_date_w3dtf($this->created));
1004 $xs->element('updated', null, common_date_w3dtf($this->created));
1006 if ($this->reply_to) {
1007 $reply_notice = Notice::staticGet('id', $this->reply_to);
1008 if (!empty($reply_notice)) {
1009 $xs->element('link', array('rel' => 'related',
1010 'href' => $reply_notice->bestUrl()));
1011 $xs->element('thr:in-reply-to',
1012 array('ref' => $reply_notice->uri,
1013 'href' => $reply_notice->bestUrl()));
1017 $xs->element('content', array('type' => 'html'), $this->rendered);
1019 $tag = new Notice_tag();
1020 $tag->notice_id = $this->id;
1022 while ($tag->fetch()) {
1023 $xs->element('category', array('term' => $tag->tag));
1029 $attachments = $this->attachments();
1031 foreach($attachments as $attachment){
1032 $enclosure=$attachment->getEnclosure();
1034 $attributes = array('rel'=>'enclosure','href'=>$enclosure->url,'type'=>$enclosure->mimetype,'length'=>$enclosure->size);
1035 if($enclosure->title){
1036 $attributes['title']=$enclosure->title;
1038 $xs->element('link', $attributes, null);
1043 if (!empty($this->lat) && !empty($this->lon)) {
1044 $xs->elementStart('geo', array('xmlns:georss' => 'http://www.georss.org/georss'));
1045 $xs->element('georss:point', null, $this->lat . ' ' . $this->lon);
1046 $xs->elementEnd('geo');
1049 $xs->elementEnd('entry');
1051 return $xs->getString();
1056 if (!empty($this->url)) {
1058 } else if (!empty($this->uri) && preg_match('/^https?:/', $this->uri)) {
1061 return common_local_url('shownotice',
1062 array('notice' => $this->id));
1066 function stream($fn, $args, $cachekey, $offset=0, $limit=20, $since_id=0, $max_id=0, $since=null)
1068 $cache = common_memcache();
1070 if (empty($cache) ||
1071 $since_id != 0 || $max_id != 0 || (!is_null($since) && $since > 0) ||
1073 ($offset + $limit) > NOTICE_CACHE_WINDOW) {
1074 return call_user_func_array($fn, array_merge($args, array($offset, $limit, $since_id,
1078 $idkey = common_cache_key($cachekey);
1080 $idstr = $cache->get($idkey);
1082 if ($idstr !== false) {
1083 // Cache hit! Woohoo!
1084 $window = explode(',', $idstr);
1085 $ids = array_slice($window, $offset, $limit);
1089 $laststr = $cache->get($idkey.';last');
1091 if ($laststr !== false) {
1092 $window = explode(',', $laststr);
1093 $last_id = $window[0];
1094 $new_ids = call_user_func_array($fn, array_merge($args, array(0, NOTICE_CACHE_WINDOW,
1095 $last_id, 0, null)));
1097 $new_window = array_merge($new_ids, $window);
1099 $new_windowstr = implode(',', $new_window);
1101 $result = $cache->set($idkey, $new_windowstr);
1102 $result = $cache->set($idkey . ';last', $new_windowstr);
1104 $ids = array_slice($new_window, $offset, $limit);
1109 $window = call_user_func_array($fn, array_merge($args, array(0, NOTICE_CACHE_WINDOW,
1112 $windowstr = implode(',', $window);
1114 $result = $cache->set($idkey, $windowstr);
1115 $result = $cache->set($idkey . ';last', $windowstr);
1117 $ids = array_slice($window, $offset, $limit);
1123 * Determine which notice, if any, a new notice is in reply to.
1125 * For conversation tracking, we try to see where this notice fits
1126 * in the tree. Rough algorithm is:
1128 * if (reply_to is set and valid) {
1130 * } else if ((source not API or Web) and (content starts with "T NAME" or "@name ")) {
1131 * return ID of last notice by initial @name in content;
1134 * Note that all @nickname instances will still be used to save "reply" records,
1135 * so the notice shows up in the mentioned users' "replies" tab.
1137 * @param integer $reply_to ID passed in by Web or API
1138 * @param integer $profile_id ID of author
1139 * @param string $source Source tag, like 'web' or 'gwibber'
1140 * @param string $content Final notice content
1142 * @return integer ID of replied-to notice, or null for not a reply.
1145 static function getReplyTo($reply_to, $profile_id, $source, $content)
1147 static $lb = array('xmpp', 'mail', 'sms', 'omb');
1149 // If $reply_to is specified, we check that it exists, and then
1150 // return it if it does
1152 if (!empty($reply_to)) {
1153 $reply_notice = Notice::staticGet('id', $reply_to);
1154 if (!empty($reply_notice)) {
1159 // If it's not a "low bandwidth" source (one where you can't set
1160 // a reply_to argument), we return. This is mostly web and API
1163 if (!in_array($source, $lb)) {
1167 // Is there an initial @ or T?
1169 if (preg_match('/^T ([A-Z0-9]{1,64}) /', $content, $match) ||
1170 preg_match('/^@([a-z0-9]{1,64})\s+/', $content, $match)) {
1171 $nickname = common_canonical_nickname($match[1]);
1176 // Figure out who that is.
1178 $sender = Profile::staticGet('id', $profile_id);
1179 $recipient = common_relative_profile($sender, $nickname, common_sql_now());
1181 if (empty($recipient)) {
1185 // Get their last notice
1187 $last = $recipient->getCurrentNotice();
1189 if (!empty($last)) {
1194 static function maxContent()
1196 $contentlimit = common_config('notice', 'contentlimit');
1197 // null => use global limit (distinct from 0!)
1198 if (is_null($contentlimit)) {
1199 $contentlimit = common_config('site', 'textlimit');
1201 return $contentlimit;
1204 static function contentTooLong($content)
1206 $contentlimit = self::maxContent();
1207 return ($contentlimit > 0 && !empty($content) && (mb_strlen($content) > $contentlimit));
1210 function getLocation()
1214 if (!empty($this->location_id) && !empty($this->location_ns)) {
1215 $location = Location::fromId($this->location_id, $this->location_ns);
1218 if (is_null($location)) { // no ID, or Location::fromId() failed
1219 if (!empty($this->lat) && !empty($this->lon)) {
1220 $location = Location::fromLatLon($this->lat, $this->lon);
1227 function repeat($repeater_id, $source)
1229 $author = Profile::staticGet('id', $this->profile_id);
1231 $content = sprintf(_('RT @%1$s %2$s'),
1235 $maxlen = common_config('site', 'textlimit');
1236 if ($maxlen > 0 && mb_strlen($content) > $maxlen) {
1237 // Web interface and current Twitter API clients will
1238 // pull the original notice's text, but some older
1239 // clients and RSS/Atom feeds will see this trimmed text.
1241 // Unfortunately this is likely to lose tags or URLs
1242 // at the end of long notices.
1243 $content = mb_substr($content, 0, $maxlen - 4) . ' ...';
1246 return self::saveNew($repeater_id, $content, $source,
1247 array('repeat_of' => $this->id));
1250 // These are supposed to be in chron order!
1252 function repeatStream($limit=100)
1254 $cache = common_memcache();
1256 if (empty($cache)) {
1257 $ids = $this->_repeatStreamDirect($limit);
1259 $idstr = $cache->get(common_cache_key('notice:repeats:'.$this->id));
1260 if ($idstr !== false) {
1261 $ids = explode(',', $idstr);
1263 $ids = $this->_repeatStreamDirect(100);
1264 $cache->set(common_cache_key('notice:repeats:'.$this->id), implode(',', $ids));
1267 // We do a max of 100, so slice down to limit
1268 $ids = array_slice($ids, 0, $limit);
1272 return Notice::getStreamByIds($ids);
1275 function _repeatStreamDirect($limit)
1277 $notice = new Notice();
1279 $notice->selectAdd(); // clears it
1280 $notice->selectAdd('id');
1282 $notice->repeat_of = $this->id;
1284 $notice->orderBy('created'); // NB: asc!
1286 if (!is_null($offset)) {
1287 $notice->limit($offset, $limit);
1292 if ($notice->find()) {
1293 while ($notice->fetch()) {
1294 $ids[] = $notice->id;
1304 function locationOptions($lat, $lon, $location_id, $location_ns, $profile = null)
1308 if (!empty($location_id) && !empty($location_ns)) {
1310 $options['location_id'] = $location_id;
1311 $options['location_ns'] = $location_ns;
1313 $location = Location::fromId($location_id, $location_ns);
1315 if (!empty($location)) {
1316 $options['lat'] = $location->lat;
1317 $options['lon'] = $location->lon;
1320 } else if (!empty($lat) && !empty($lon)) {
1322 $options['lat'] = $lat;
1323 $options['lon'] = $lon;
1325 $location = Location::fromLatLon($lat, $lon);
1327 if (!empty($location)) {
1328 $options['location_id'] = $location->location_id;
1329 $options['location_ns'] = $location->location_ns;
1331 } else if (!empty($profile)) {
1333 if (isset($profile->lat) && isset($profile->lon)) {
1334 $options['lat'] = $profile->lat;
1335 $options['lon'] = $profile->lon;
1338 if (isset($profile->location_id) && isset($profile->location_ns)) {
1339 $options['location_id'] = $profile->location_id;
1340 $options['location_ns'] = $profile->location_ns;
1347 function clearReplies()
1349 $replyNotice = new Notice();
1350 $replyNotice->reply_to = $this->id;
1352 //Null any notices that are replies to this notice
1354 if ($replyNotice->find()) {
1355 while ($replyNotice->fetch()) {
1356 $orig = clone($replyNotice);
1357 $replyNotice->reply_to = null;
1358 $replyNotice->update($orig);
1364 $reply = new Reply();
1365 $reply->notice_id = $this->id;
1367 if ($reply->find()) {
1368 while($reply->fetch()) {
1369 self::blow('reply:stream:%d', $reply->profile_id);
1377 function clearRepeats()
1379 $repeatNotice = new Notice();
1380 $repeatNotice->repeat_of = $this->id;
1382 //Null any notices that are repeats of this notice
1384 if ($repeatNotice->find()) {
1385 while ($repeatNotice->fetch()) {
1386 $orig = clone($repeatNotice);
1387 $repeatNotice->repeat_of = null;
1388 $repeatNotice->update($orig);
1393 function clearFaves()
1396 $fave->notice_id = $this->id;
1398 if ($fave->find()) {
1399 while ($fave->fetch()) {
1400 self::blow('fave:ids_by_user_own:%d', $fave->user_id);
1401 self::blow('fave:ids_by_user_own:%d;last', $fave->user_id);
1402 self::blow('fave:ids_by_user:%d', $fave->user_id);
1403 self::blow('fave:ids_by_user:%d;last', $fave->user_id);
1411 function clearTags()
1413 $tag = new Notice_tag();
1414 $tag->notice_id = $this->id;
1417 while ($tag->fetch()) {
1418 self::blow('profile:notice_ids_tagged:%d:%s', $this->profile_id, common_keyize($tag->tag));
1419 self::blow('profile:notice_ids_tagged:%d:%s;last', $this->profile_id, common_keyize($tag->tag));
1420 self::blow('notice_tag:notice_ids:%s', common_keyize($tag->tag));
1421 self::blow('notice_tag:notice_ids:%s;last', common_keyize($tag->tag));
1429 function clearGroupInboxes()
1431 $gi = new Group_inbox();
1433 $gi->notice_id = $this->id;
1436 while ($gi->fetch()) {
1437 self::blow('user_group:notice_ids:%d', $gi->group_id);
1445 function distribute()
1447 if (common_config('queue', 'inboxes')) {
1448 // If there's a failure, we want to _force_
1449 // distribution at this point.
1451 $qm = QueueManager::get();
1452 $qm->enqueue($this, 'distrib');
1453 } catch (Exception $e) {
1454 // If the exception isn't transient, this
1455 // may throw more exceptions as DQH does
1456 // its own enqueueing. So, we ignore them!
1458 $handler = new DistribQueueHandler();
1459 $handler->handle($this);
1460 } catch (Exception $e) {
1461 common_log(LOG_ERR, "emergency redistribution resulted in " . $e->getMessage());
1463 // Re-throw so somebody smarter can handle it.
1467 $handler = new DistribQueueHandler();
1468 $handler->handle($this);
1474 $result = parent::insert();
1477 // Profile::hasRepeated() abuses pkeyGet(), so we
1478 // have to clear manually
1479 if (!empty($this->repeat_of)) {
1480 $c = self::memcache();
1482 $ck = self::multicacheKey('Notice',
1483 array('profile_id' => $this->profile_id,
1484 'repeat_of' => $this->repeat_of));