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 * @copyright 2009 Free Software Foundation, Inc http://www.fsf.org
33 * @license GNU Affero General Public License http://www.gnu.org/licenses/
36 if (!defined('STATUSNET') && !defined('LACONICA')) {
41 * Table Definition for notice
43 require_once INSTALLDIR.'/classes/Memcached_DataObject.php';
45 /* We keep 200 notices, the max number of notices available per API request,
46 * in the memcached cache. */
48 define('NOTICE_CACHE_WINDOW', 200);
50 define('MAX_BOXCARS', 128);
52 class Notice extends Memcached_DataObject
55 /* the code below is auto generated do not remove the above tag */
57 public $__table = 'notice'; // table name
58 public $id; // int(4) primary_key not_null
59 public $profile_id; // int(4) multiple_key not_null
60 public $uri; // varchar(255) unique_key
61 public $content; // text
62 public $rendered; // text
63 public $url; // varchar(255)
64 public $created; // datetime multiple_key not_null default_0000-00-00%2000%3A00%3A00
65 public $modified; // timestamp not_null default_CURRENT_TIMESTAMP
66 public $reply_to; // int(4)
67 public $is_local; // int(4)
68 public $source; // varchar(32)
69 public $conversation; // int(4)
70 public $lat; // decimal(10,7)
71 public $lon; // decimal(10,7)
72 public $location_id; // int(4)
73 public $location_ns; // int(4)
74 public $repeat_of; // int(4)
77 function staticGet($k,$v=NULL)
79 return Memcached_DataObject::staticGet('Notice',$k,$v);
82 /* the code above is auto generated do not remove the tag below */
86 const LOCAL_PUBLIC = 1;
88 const LOCAL_NONPUBLIC = -1;
93 $profile = Profile::staticGet('id', $this->profile_id);
95 if (empty($profile)) {
96 // TRANS: Server exception thrown when a user profile for a notice cannot be found.
97 // TRANS: %1$d is a profile ID (number), %2$d is a notice ID (number).
98 throw new ServerException(sprintf(_('No such profile (%1$d) for notice (%2$d).'), $this->profile_id, $this->id));
106 // For auditing purposes, save a record that the notice
109 // @fixme we have some cases where things get re-run and so the
111 $deleted = Deleted_notice::staticGet('id', $this->id);
113 $deleted = new Deleted_notice();
115 $deleted->id = $this->id;
116 $deleted->profile_id = $this->profile_id;
117 $deleted->uri = $this->uri;
118 $deleted->created = $this->created;
119 $deleted->deleted = common_sql_now();
124 if (Event::handle('NoticeDeleteRelated', array($this))) {
126 // Clear related records
128 $this->clearReplies();
129 $this->clearRepeats();
132 $this->clearGroupInboxes();
134 // NOTE: we don't clear inboxes
135 // NOTE: we don't clear queue items
138 $result = parent::delete();
140 $this->blowOnDelete();
145 * Extract #hashtags from this notice's content and save them to the database.
149 /* extract all #hastags */
150 $count = preg_match_all('/(?:^|\s)#([\pL\pN_\-\.]{1,64})/', strtolower($this->content), $match);
155 /* Add them to the database */
156 return $this->saveKnownTags($match[1]);
160 * Record the given set of hash tags in the db for this notice.
161 * Given tag strings will be normalized and checked for dupes.
163 function saveKnownTags($hashtags)
165 //turn each into their canonical tag
166 //this is needed to remove dupes before saving e.g. #hash.tag = #hashtag
167 for($i=0; $i<count($hashtags); $i++) {
168 /* elide characters we don't want in the tag */
169 $hashtags[$i] = common_canonical_tag($hashtags[$i]);
172 foreach(array_unique($hashtags) as $hashtag) {
173 $this->saveTag($hashtag);
174 self::blow('profile:notice_ids_tagged:%d:%s', $this->profile_id, $hashtag);
180 * Record a single hash tag as associated with this notice.
181 * Tag format and uniqueness must be validated by caller.
183 function saveTag($hashtag)
185 $tag = new Notice_tag();
186 $tag->notice_id = $this->id;
187 $tag->tag = $hashtag;
188 $tag->created = $this->created;
189 $id = $tag->insert();
192 // TRANS: Server exception. %s are the error details.
193 throw new ServerException(sprintf(_('Database error inserting hashtag: %s'),
194 $last_error->message));
198 // if it's saved, blow its cache
199 $tag->blowCache(false);
203 * Save a new notice and push it out to subscribers' inboxes.
204 * Poster's permissions are checked before sending.
206 * @param int $profile_id Profile ID of the poster
207 * @param string $content source message text; links may be shortened
208 * per current user's preference
209 * @param string $source source key ('web', 'api', etc)
210 * @param array $options Associative array of optional properties:
211 * string 'created' timestamp of notice; defaults to now
212 * int 'is_local' source/gateway ID, one of:
213 * Notice::LOCAL_PUBLIC - Local, ok to appear in public timeline
214 * Notice::REMOTE_OMB - Sent from a remote OMB service;
215 * hide from public timeline but show in
216 * local "and friends" timelines
217 * Notice::LOCAL_NONPUBLIC - Local, but hide from public timeline
218 * Notice::GATEWAY - From another non-OMB service;
219 * will not appear in public views
220 * float 'lat' decimal latitude for geolocation
221 * float 'lon' decimal longitude for geolocation
222 * int 'location_id' geoname identifier
223 * int 'location_ns' geoname namespace to interpret location_id
224 * int 'reply_to'; notice ID this is a reply to
225 * int 'repeat_of'; notice ID this is a repeat of
226 * string 'uri' unique ID for notice; defaults to local notice URL
227 * string 'url' permalink to notice; defaults to local notice URL
228 * string 'rendered' rendered HTML version of content
229 * array 'replies' list of profile URIs for reply delivery in
230 * place of extracting @-replies from content.
231 * array 'groups' list of group IDs to deliver to, in place of
232 * extracting ! tags from content
233 * array 'tags' list of hashtag strings to save with the notice
234 * in place of extracting # tags from content
235 * array 'urls' list of attached/referred URLs to save with the
236 * notice in place of extracting links from content
237 * @fixme tag override
240 * @throws ClientException
242 static function saveNew($profile_id, $content, $source, $options=null) {
243 $defaults = array('uri' => null,
246 'repeat_of' => null);
248 if (!empty($options)) {
249 $options = $options + $defaults;
255 if (!isset($is_local)) {
256 $is_local = Notice::LOCAL_PUBLIC;
259 $profile = Profile::staticGet($profile_id);
261 $final = common_shorten_links($content);
263 if (Notice::contentTooLong($final)) {
264 // TRANS: Client exception thrown if a notice contains too many characters.
265 throw new ClientException(_('Problem saving notice. Too long.'));
268 if (empty($profile)) {
269 // TRANS: Client exception thrown when trying to save a notice for an unknown user.
270 throw new ClientException(_('Problem saving notice. Unknown user.'));
273 if (common_config('throttle', 'enabled') && !Notice::checkEditThrottle($profile_id)) {
274 common_log(LOG_WARNING, 'Excessive posting by profile #' . $profile_id . '; throttled.');
275 // TRANS: Client exception thrown when a user tries to post too many notices in a given time frame.
276 throw new ClientException(_('Too many notices too fast; take a breather '.
277 'and post again in a few minutes.'));
280 if (common_config('site', 'dupelimit') > 0 && !Notice::checkDupes($profile_id, $final)) {
281 common_log(LOG_WARNING, 'Dupe posting by profile #' . $profile_id . '; throttled.');
282 // TRANS: Client exception thrown when a user tries to post too many duplicate notices in a given time frame.
283 throw new ClientException(_('Too many duplicate messages too quickly;'.
284 ' take a breather and post again in a few minutes.'));
287 if (!$profile->hasRight(Right::NEWNOTICE)) {
288 common_log(LOG_WARNING, "Attempted post from user disallowed to post: " . $profile->nickname);
290 // TRANS: Client exception thrown when a user tries to post while being banned.
291 throw new ClientException(_('You are banned from posting notices on this site.'), 403);
294 $notice = new Notice();
295 $notice->profile_id = $profile_id;
297 $autosource = common_config('public', 'autosource');
299 # Sandboxed are non-false, but not 1, either
301 if (!$profile->hasRight(Right::PUBLICNOTICE) ||
302 ($source && $autosource && in_array($source, $autosource))) {
303 $notice->is_local = Notice::LOCAL_NONPUBLIC;
305 $notice->is_local = $is_local;
308 if (!empty($created)) {
309 $notice->created = $created;
311 $notice->created = common_sql_now();
314 $notice->content = $final;
316 $notice->source = $source;
320 // Handle repeat case
322 if (isset($repeat_of)) {
323 $notice->repeat_of = $repeat_of;
325 $notice->reply_to = self::getReplyTo($reply_to, $profile_id, $source, $final);
328 if (!empty($notice->reply_to)) {
329 $reply = Notice::staticGet('id', $notice->reply_to);
330 $notice->conversation = $reply->conversation;
333 if (!empty($lat) && !empty($lon)) {
338 if (!empty($location_ns) && !empty($location_id)) {
339 $notice->location_id = $location_id;
340 $notice->location_ns = $location_ns;
343 if (!empty($rendered)) {
344 $notice->rendered = $rendered;
346 $notice->rendered = common_render_content($final, $notice);
349 if (Event::handle('StartNoticeSave', array(&$notice))) {
351 // XXX: some of these functions write to the DB
353 $id = $notice->insert();
356 common_log_db_error($notice, 'INSERT', __FILE__);
357 // TRANS: Server exception thrown when a notice cannot be saved.
358 throw new ServerException(_('Problem saving notice.'));
361 // Update ID-dependent columns: URI, conversation
363 $orig = clone($notice);
368 $notice->uri = common_notice_uri($notice);
372 // If it's not part of a conversation, it's
373 // the beginning of a new conversation.
375 if (empty($notice->conversation)) {
376 $conv = Conversation::create();
377 $notice->conversation = $conv->id;
382 if (!$notice->update($orig)) {
383 common_log_db_error($notice, 'UPDATE', __FILE__);
384 // TRANS: Server exception thrown when a notice cannot be updated.
385 throw new ServerException(_('Problem saving notice.'));
391 # Clear the cache for subscribed users, so they'll update at next request
392 # XXX: someone clever could prepend instead of clearing the cache
394 $notice->blowOnInsert();
396 // Save per-notice metadata...
398 if (isset($replies)) {
399 $notice->saveKnownReplies($replies);
401 $notice->saveReplies();
405 $notice->saveKnownTags($tags);
410 // Note: groups may save tags, so must be run after tags are saved
411 // to avoid errors on duplicates.
412 if (isset($groups)) {
413 $notice->saveKnownGroups($groups);
415 $notice->saveGroups();
419 $notice->saveKnownUrls($urls);
424 // Prepare inbox delivery, may be queued to background.
425 $notice->distribute();
430 function blowOnInsert($conversation = false)
432 self::blow('profile:notice_ids:%d', $this->profile_id);
433 self::blow('public');
435 // XXX: Before we were blowing the casche only if the notice id
436 // was not the root of the conversation. What to do now?
438 self::blow('notice:conversation_ids:%d', $this->conversation);
440 if (!empty($this->repeat_of)) {
441 self::blow('notice:repeats:%d', $this->repeat_of);
444 $original = Notice::staticGet('id', $this->repeat_of);
446 if (!empty($original)) {
447 $originalUser = User::staticGet('id', $original->profile_id);
448 if (!empty($originalUser)) {
449 self::blow('user:repeats_of_me:%d', $originalUser->id);
453 $profile = Profile::staticGet($this->profile_id);
454 if (!empty($profile)) {
455 $profile->blowNoticeCount();
460 * Clear cache entries related to this notice at delete time.
461 * Necessary to avoid breaking paging on public, profile timelines.
463 function blowOnDelete()
465 $this->blowOnInsert();
467 self::blow('profile:notice_ids:%d;last', $this->profile_id);
468 self::blow('public;last');
471 /** save all urls in the notice to the db
473 * follow redirects and save all available file information
474 * (mimetype, date, size, oembed, etc.)
478 function saveUrls() {
479 common_replace_urls_callback($this->content, array($this, 'saveUrl'), $this->id);
483 * Save the given URLs as related links/attachments to the db
485 * follow redirects and save all available file information
486 * (mimetype, date, size, oembed, etc.)
490 function saveKnownUrls($urls)
492 // @fixme validation?
493 foreach (array_unique($urls) as $url) {
494 File::processNew($url, $this->id);
501 function saveUrl($data) {
502 list($url, $notice_id) = $data;
503 File::processNew($url, $notice_id);
506 static function checkDupes($profile_id, $content) {
507 $profile = Profile::staticGet($profile_id);
508 if (empty($profile)) {
511 $notice = $profile->getNotices(0, NOTICE_CACHE_WINDOW);
512 if (!empty($notice)) {
514 while ($notice->fetch()) {
515 if (time() - strtotime($notice->created) >= common_config('site', 'dupelimit')) {
517 } else if ($notice->content == $content) {
522 # If we get here, oldest item in cache window is not
523 # old enough for dupe limit; do direct check against DB
524 $notice = new Notice();
525 $notice->profile_id = $profile_id;
526 $notice->content = $content;
527 $threshold = common_sql_date(time() - common_config('site', 'dupelimit'));
528 $notice->whereAdd(sprintf("created > '%s'", $notice->escape($threshold)));
530 $cnt = $notice->count();
534 static function checkEditThrottle($profile_id) {
535 $profile = Profile::staticGet($profile_id);
536 if (empty($profile)) {
540 $notice = $profile->getNotices(common_config('throttle', 'count') - 1, 1);
541 if ($notice && $notice->fetch()) {
542 # If the Nth notice was posted less than timespan seconds ago
543 if (time() - strtotime($notice->created) <= common_config('throttle', 'timespan')) {
548 # Either not N notices in the stream, OR the Nth was not posted within timespan seconds
552 function getUploadedAttachment() {
554 $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"';
555 $post->query($query);
557 if (empty($post->up) || empty($post->i)) {
560 $ret = array($post->up, $post->i);
566 function hasAttachments() {
568 $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);
569 $post->query($query);
571 $n_attachments = intval($post->n_attachments);
573 return $n_attachments;
576 function attachments() {
579 $f2p = new File_to_post;
580 $f2p->post_id = $this->id;
582 while ($f2p->fetch()) {
583 $f = File::staticGet($f2p->file_id);
592 function getStreamByIds($ids)
594 $cache = common_memcache();
596 if (!empty($cache)) {
598 foreach ($ids as $id) {
599 $n = Notice::staticGet('id', $id);
604 return new ArrayWrapper($notices);
606 $notice = new Notice();
608 //if no IDs requested, just return the notice object
611 $notice->whereAdd('id in (' . implode(', ', $ids) . ')');
617 while ($notice->fetch()) {
618 $temp[$notice->id] = clone($notice);
623 foreach ($ids as $id) {
624 if (array_key_exists($id, $temp)) {
625 $wrapped[] = $temp[$id];
629 return new ArrayWrapper($wrapped);
633 function publicStream($offset=0, $limit=20, $since_id=0, $max_id=0)
635 $ids = Notice::stream(array('Notice', '_publicStreamDirect'),
638 $offset, $limit, $since_id, $max_id);
639 return Notice::getStreamByIds($ids);
642 function _publicStreamDirect($offset=0, $limit=20, $since_id=0, $max_id=0)
644 $notice = new Notice();
646 $notice->selectAdd(); // clears it
647 $notice->selectAdd('id');
649 $notice->orderBy('id DESC');
651 if (!is_null($offset)) {
652 $notice->limit($offset, $limit);
655 if (common_config('public', 'localonly')) {
656 $notice->whereAdd('is_local = ' . Notice::LOCAL_PUBLIC);
658 # -1 == blacklisted, -2 == gateway (i.e. Twitter)
659 $notice->whereAdd('is_local !='. Notice::LOCAL_NONPUBLIC);
660 $notice->whereAdd('is_local !='. Notice::GATEWAY);
663 if ($since_id != 0) {
664 $notice->whereAdd('id > ' . $since_id);
668 $notice->whereAdd('id <= ' . $max_id);
673 if ($notice->find()) {
674 while ($notice->fetch()) {
675 $ids[] = $notice->id;
685 function conversationStream($id, $offset=0, $limit=20, $since_id=0, $max_id=0)
687 $ids = Notice::stream(array('Notice', '_conversationStreamDirect'),
689 'notice:conversation_ids:'.$id,
690 $offset, $limit, $since_id, $max_id);
692 return Notice::getStreamByIds($ids);
695 function _conversationStreamDirect($id, $offset=0, $limit=20, $since_id=0, $max_id=0)
697 $notice = new Notice();
699 $notice->selectAdd(); // clears it
700 $notice->selectAdd('id');
702 $notice->conversation = $id;
704 $notice->orderBy('id DESC');
706 if (!is_null($offset)) {
707 $notice->limit($offset, $limit);
710 if ($since_id != 0) {
711 $notice->whereAdd('id > ' . $since_id);
715 $notice->whereAdd('id <= ' . $max_id);
720 if ($notice->find()) {
721 while ($notice->fetch()) {
722 $ids[] = $notice->id;
733 * Is this notice part of an active conversation?
735 * @return boolean true if other messages exist in the same
736 * conversation, false if this is the only one
738 function hasConversation()
740 if (!empty($this->conversation)) {
741 $conversation = Notice::conversationStream(
747 if ($conversation->N > 0) {
755 * Pull up a full list of local recipients who will be getting
756 * this notice in their inbox. Results will be cached, so don't
757 * change the input data wily-nilly!
759 * @param array $groups optional list of Group objects;
760 * if left empty, will be loaded from group_inbox records
761 * @param array $recipient optional list of reply profile ids
762 * if left empty, will be loaded from reply records
763 * @return array associating recipient user IDs with an inbox source constant
765 function whoGets($groups=null, $recipients=null)
767 $c = self::memcache();
770 $ni = $c->get(common_cache_key('notice:who_gets:'.$this->id));
776 if (is_null($groups)) {
777 $groups = $this->getGroups();
780 if (is_null($recipients)) {
781 $recipients = $this->getReplies();
784 $users = $this->getSubscribedUsers();
786 // FIXME: kind of ignoring 'transitional'...
787 // we'll probably stop supporting inboxless mode
792 foreach ($users as $id) {
793 $ni[$id] = NOTICE_INBOX_SOURCE_SUB;
796 foreach ($groups as $group) {
797 $users = $group->getUserMembers();
798 foreach ($users as $id) {
799 if (!array_key_exists($id, $ni)) {
800 $ni[$id] = NOTICE_INBOX_SOURCE_GROUP;
805 foreach ($recipients as $recipient) {
806 if (!array_key_exists($recipient, $ni)) {
807 $ni[$recipient] = NOTICE_INBOX_SOURCE_REPLY;
811 // Exclude any deleted, non-local, or blocking recipients.
812 $profile = $this->getProfile();
813 foreach ($ni as $id => $source) {
814 $user = User::staticGet('id', $id);
815 if (empty($user) || $user->hasBlocked($profile)) {
821 // XXX: pack this data better
822 $c->set(common_cache_key('notice:who_gets:'.$this->id), $ni);
829 * Adds this notice to the inboxes of each local user who should receive
830 * it, based on author subscriptions, group memberships, and @-replies.
832 * Warning: running a second time currently will make items appear
833 * multiple times in users' inboxes.
835 * @fixme make more robust against errors
836 * @fixme break up massive deliveries to smaller background tasks
838 * @param array $groups optional list of Group objects;
839 * if left empty, will be loaded from group_inbox records
840 * @param array $recipient optional list of reply profile ids
841 * if left empty, will be loaded from reply records
843 function addToInboxes($groups=null, $recipients=null)
845 $ni = $this->whoGets($groups, $recipients);
847 $ids = array_keys($ni);
849 // We remove the author (if they're a local user),
850 // since we'll have already done this in distribute()
852 $i = array_search($this->profile_id, $ids);
860 Inbox::bulkInsert($this->id, $ids);
865 function getSubscribedUsers()
869 if(common_config('db','quote_identifiers'))
870 $user_table = '"user"';
871 else $user_table = 'user';
875 'FROM '. $user_table .' JOIN subscription '.
876 'ON '. $user_table .'.id = subscription.subscriber ' .
877 'WHERE subscription.subscribed = %d ';
879 $user->query(sprintf($qry, $this->profile_id));
883 while ($user->fetch()) {
893 * Record this notice to the given group inboxes for delivery.
894 * Overrides the regular parsing of !group markup.
896 * @param string $group_ids
897 * @fixme might prefer URIs as identifiers, as for replies?
898 * best with generalizations on user_group to support
899 * remote groups better.
901 function saveKnownGroups($group_ids)
903 if (!is_array($group_ids)) {
904 // TRANS: Server exception thrown when no array is provided to the method saveKnownGroups().
905 throw new ServerException(_('Bad type provided to saveKnownGroups.'));
909 foreach (array_unique($group_ids) as $id) {
910 $group = User_group::staticGet('id', $id);
912 common_log(LOG_ERR, "Local delivery to group id $id, $group->nickname");
913 $result = $this->addToGroupInbox($group);
915 common_log_db_error($gi, 'INSERT', __FILE__);
918 // @fixme should we save the tags here or not?
919 $groups[] = clone($group);
921 common_log(LOG_ERR, "Local delivery to group id $id skipped, doesn't exist");
929 * Parse !group delivery and record targets into group_inbox.
930 * @return array of Group objects
932 function saveGroups()
934 // Don't save groups for repeats
936 if (!empty($this->repeat_of)) {
942 /* extract all !group */
943 $count = preg_match_all('/(?:^|\s)!([A-Za-z0-9]{1,64})/',
944 strtolower($this->content),
950 $profile = $this->getProfile();
952 /* Add them to the database */
954 foreach (array_unique($match[1]) as $nickname) {
955 /* XXX: remote groups. */
956 $group = User_group::getForNickname($nickname, $profile);
962 // we automatically add a tag for every group name, too
964 $tag = Notice_tag::pkeyGet(array('tag' => common_canonical_tag($nickname),
965 'notice_id' => $this->id));
968 $this->saveTag($nickname);
971 if ($profile->isMember($group)) {
973 $result = $this->addToGroupInbox($group);
976 common_log_db_error($gi, 'INSERT', __FILE__);
979 $groups[] = clone($group);
986 function addToGroupInbox($group)
988 $gi = Group_inbox::pkeyGet(array('group_id' => $group->id,
989 'notice_id' => $this->id));
993 $gi = new Group_inbox();
995 $gi->group_id = $group->id;
996 $gi->notice_id = $this->id;
997 $gi->created = $this->created;
999 $result = $gi->insert();
1002 common_log_db_error($gi, 'INSERT', __FILE__);
1003 // TRANS: Server exception thrown when an update for a group inbox fails.
1004 throw new ServerException(_('Problem saving group inbox.'));
1007 self::blow('user_group:notice_ids:%d', $gi->group_id);
1014 * Save reply records indicating that this notice needs to be
1015 * delivered to the local users with the given URIs.
1017 * Since this is expected to be used when saving foreign-sourced
1018 * messages, we won't deliver to any remote targets as that's the
1019 * source service's responsibility.
1021 * Mail notifications etc will be handled later.
1023 * @param array of unique identifier URIs for recipients
1025 function saveKnownReplies($uris)
1031 $sender = Profile::staticGet($this->profile_id);
1033 foreach (array_unique($uris) as $uri) {
1035 $profile = Profile::fromURI($uri);
1037 if (empty($profile)) {
1038 common_log(LOG_WARNING, "Unable to determine profile for URI '$uri'");
1042 if ($profile->hasBlocked($sender)) {
1043 common_log(LOG_INFO, "Not saving reply to profile {$profile->id} ($uri) from sender {$sender->id} because of a block.");
1047 $reply = new Reply();
1049 $reply->notice_id = $this->id;
1050 $reply->profile_id = $profile->id;
1052 common_log(LOG_INFO, __METHOD__ . ": saving reply: notice $this->id to profile $profile->id");
1054 $id = $reply->insert();
1061 * Pull @-replies from this message's content in StatusNet markup format
1062 * and save reply records indicating that this message needs to be
1063 * delivered to those users.
1065 * Mail notifications to local profiles will be sent later.
1067 * @return array of integer profile IDs
1070 function saveReplies()
1072 // Don't save reply data for repeats
1074 if (!empty($this->repeat_of)) {
1078 $sender = Profile::staticGet($this->profile_id);
1080 // @todo ideally this parser information would only
1081 // be calculated once.
1083 $mentions = common_find_mentions($this->content, $this);
1087 // store replied only for first @ (what user/notice what the reply directed,
1088 // we assume first @ is it)
1090 foreach ($mentions as $mention) {
1092 foreach ($mention['mentioned'] as $mentioned) {
1094 // skip if they're already covered
1096 if (!empty($replied[$mentioned->id])) {
1100 // Don't save replies from blocked profile to local user
1102 $mentioned_user = User::staticGet('id', $mentioned->id);
1103 if (!empty($mentioned_user) && $mentioned_user->hasBlocked($sender)) {
1107 $reply = new Reply();
1109 $reply->notice_id = $this->id;
1110 $reply->profile_id = $mentioned->id;
1112 $id = $reply->insert();
1115 common_log_db_error($reply, 'INSERT', __FILE__);
1116 // TRANS: Server exception thrown when a reply cannot be saved.
1117 // TRANS: %1$d is a notice ID, %2$d is the ID of the mentioned user.
1118 throw new ServerException(sprintf(_('Could not save reply for %1$d, %2$d.'), $this->id, $mentioned->id));
1120 $replied[$mentioned->id] = 1;
1121 self::blow('reply:stream:%d', $mentioned->id);
1126 $recipientIds = array_keys($replied);
1128 return $recipientIds;
1132 * Pull the complete list of @-reply targets for this notice.
1134 * @return array of integer profile ids
1136 function getReplies()
1142 $reply = new Reply();
1143 $reply->selectAdd();
1144 $reply->selectAdd('profile_id');
1145 $reply->notice_id = $this->id;
1147 if ($reply->find()) {
1148 while($reply->fetch()) {
1149 $ids[] = $reply->profile_id;
1159 * Send e-mail notifications to local @-reply targets.
1161 * Replies must already have been saved; this is expected to be run
1162 * from the distrib queue handler.
1164 function sendReplyNotifications()
1166 // Don't send reply notifications for repeats
1168 if (!empty($this->repeat_of)) {
1172 $recipientIds = $this->getReplies();
1174 foreach ($recipientIds as $recipientId) {
1175 $user = User::staticGet('id', $recipientId);
1176 if (!empty($user)) {
1177 mail_notify_attn($user, $this);
1183 * Pull list of groups this notice needs to be delivered to,
1184 * as previously recorded by saveGroups() or saveKnownGroups().
1186 * @return array of Group objects
1188 function getGroups()
1190 // Don't save groups for repeats
1192 if (!empty($this->repeat_of)) {
1200 $gi = new Group_inbox();
1203 $gi->selectAdd('group_id');
1205 $gi->notice_id = $this->id;
1208 while ($gi->fetch()) {
1209 $group = User_group::staticGet('id', $gi->group_id);
1221 function asActivity()
1223 $profile = $this->getProfile();
1225 $act = new Activity();
1227 $act->actor = ActivityObject::fromProfile($profile);
1228 $act->verb = ActivityVerb::POST;
1229 $act->objects[] = ActivityObject::fromNotice($this);
1231 $act->time = strtotime($this->created);
1232 $act->link = $this->bestUrl();
1234 $act->content = common_xml_safe_str($this->rendered);
1235 $act->id = $this->uri;
1236 $act->title = common_xml_safe_str($this->content);
1238 $ctx = new ActivityContext();
1240 if (!empty($this->reply_to)) {
1241 $reply = Notice::staticGet('id', $this->reply_to);
1242 if (!empty($reply)) {
1243 $ctx->replyToID = $reply->uri;
1244 $ctx->replyToUrl = $reply->bestUrl();
1248 $ctx->location = $this->getLocation();
1252 if (!empty($this->conversation)) {
1253 $conv = Conversation::staticGet('id', $this->conversation);
1254 if (!empty($conv)) {
1255 $ctx->conversation = $conv->uri;
1259 $reply_ids = $this->getReplies();
1261 foreach ($reply_ids as $id) {
1262 $profile = Profile::staticGet('id', $id);
1263 if (!empty($profile)) {
1264 $ctx->attention[] = $profile->getUri();
1268 $groups = $this->getGroups();
1270 foreach ($groups as $group) {
1271 $ctx->attention[] = $group->uri;
1274 $act->context = $ctx;
1279 // This has gotten way too long. Needs to be sliced up into functional bits
1280 // or ideally exported to a utility class.
1282 function asAtomEntry($namespace=false, $source=false, $author=true, $cur=null)
1284 $profile = $this->getProfile();
1286 $xs = new XMLStringer(true);
1289 $attrs = array('xmlns' => 'http://www.w3.org/2005/Atom',
1290 'xmlns:thr' => 'http://purl.org/syndication/thread/1.0',
1291 'xmlns:georss' => 'http://www.georss.org/georss',
1292 'xmlns:activity' => 'http://activitystrea.ms/spec/1.0/',
1293 'xmlns:media' => 'http://purl.org/syndication/atommedia',
1294 'xmlns:poco' => 'http://portablecontacts.net/spec/1.0',
1295 'xmlns:ostatus' => 'http://ostatus.org/schema/1.0',
1296 'xmlns:statusnet' => 'http://status.net/schema/api/1/');
1301 if (Event::handle('StartActivityStart', array(&$this, &$xs, &$attrs))) {
1302 $xs->elementStart('entry', $attrs);
1303 Event::handle('EndActivityStart', array(&$this, &$xs, &$attrs));
1306 if (Event::handle('StartActivitySource', array(&$this, &$xs))) {
1308 $atom_feed = $profile->getAtomFeed();
1310 if (!empty($atom_feed)) {
1311 $xs->elementStart('source');
1313 // XXX: we should store the actual feed ID
1315 $xs->element('id', null, $atom_feed);
1317 // XXX: we should store the actual feed title
1319 $xs->element('title', null, $profile->getBestName());
1321 $xs->element('link', array('rel' => 'alternate',
1322 'type' => 'text/html',
1323 'href' => $profile->profileurl));
1325 $xs->element('link', array('rel' => 'self',
1326 'type' => 'application/atom+xml',
1327 'href' => $atom_feed));
1329 $xs->element('icon', null, $profile->avatarUrl(AVATAR_PROFILE_SIZE));
1331 $notice = $profile->getCurrentNotice();
1333 if (!empty($notice)) {
1334 $xs->element('updated', null, self::utcDate($notice->created));
1337 $user = User::staticGet('id', $profile->id);
1339 if (!empty($user)) {
1340 $xs->element('link', array('rel' => 'license',
1341 'href' => common_config('license', 'url')));
1344 $xs->elementEnd('source');
1347 Event::handle('EndActivitySource', array(&$this, &$xs));
1350 $title = common_xml_safe_str($this->content);
1352 if (Event::handle('StartActivityTitle', array(&$this, &$xs, &$title))) {
1353 $xs->element('title', null, $title);
1354 Event::handle('EndActivityTitle', array($this, &$xs, $title));
1360 $atomAuthor = $profile->asAtomAuthor($cur);
1363 if (Event::handle('StartActivityAuthor', array(&$this, &$xs, &$atomAuthor))) {
1364 if (!empty($atomAuthor)) {
1365 $xs->raw($atomAuthor);
1366 Event::handle('EndActivityAuthor', array(&$this, &$xs, &$atomAuthor));
1373 $actor = $profile->asActivityActor();
1376 if (Event::handle('StartActivityActor', array(&$this, &$xs, &$actor))) {
1377 if (!empty($actor)) {
1379 Event::handle('EndActivityActor', array(&$this, &$xs, &$actor));
1383 $url = $this->bestUrl();
1385 if (Event::handle('StartActivityLink', array(&$this, &$xs, &$url))) {
1386 $xs->element('link', array('rel' => 'alternate',
1387 'type' => 'text/html',
1389 Event::handle('EndActivityLink', array(&$this, &$xs, $url));
1394 if (Event::handle('StartActivityId', array(&$this, &$xs, &$id))) {
1395 $xs->element('id', null, $id);
1396 Event::handle('EndActivityId', array(&$this, &$xs, $id));
1399 $published = self::utcDate($this->created);
1401 if (Event::handle('StartActivityPublished', array(&$this, &$xs, &$published))) {
1402 $xs->element('published', null, $published);
1403 Event::handle('EndActivityPublished', array(&$this, &$xs, $published));
1406 $updated = $published; // XXX: notices are usually immutable
1408 if (Event::handle('StartActivityUpdated', array(&$this, &$xs, &$updated))) {
1409 $xs->element('updated', null, $updated);
1410 Event::handle('EndActivityUpdated', array(&$this, &$xs, $updated));
1413 $content = common_xml_safe_str($this->rendered);
1415 if (Event::handle('StartActivityContent', array(&$this, &$xs, &$content))) {
1416 $xs->element('content', array('type' => 'html'), $content);
1417 Event::handle('EndActivityContent', array(&$this, &$xs, $content));
1420 // Most of our notices represent POSTing a NOTE. This is the default verb
1421 // for activity streams, so we normally just leave it out.
1423 $verb = ActivityVerb::POST;
1425 if (Event::handle('StartActivityVerb', array(&$this, &$xs, &$verb))) {
1426 $xs->element('activity:verb', null, $verb);
1427 Event::handle('EndActivityVerb', array(&$this, &$xs, $verb));
1430 // We use the default behavior for activity streams: if there's no activity:object,
1431 // then treat the entry itself as the object. Here, you can set the type of that object,
1432 // which is normally a NOTE.
1434 $type = ActivityObject::NOTE;
1436 if (Event::handle('StartActivityDefaultObjectType', array(&$this, &$xs, &$type))) {
1437 $xs->element('activity:object-type', null, $type);
1438 Event::handle('EndActivityDefaultObjectType', array(&$this, &$xs, $type));
1441 // Since we usually use the entry itself as an object, we don't have an explicit
1442 // object. Some extensions may want to add them (for photo, event, music, etc.).
1446 if (Event::handle('StartActivityObjects', array(&$this, &$xs, &$objects))) {
1447 foreach ($objects as $object) {
1448 $xs->raw($object->asString());
1450 Event::handle('EndActivityObjects', array(&$this, &$xs, $objects));
1453 $noticeInfoAttr = array('local_id' => $this->id); // local notice ID (useful to clients for ordering)
1455 $ns = $this->getSource();
1458 $noticeInfoAttr['source'] = $ns->code;
1459 if (!empty($ns->url)) {
1460 $noticeInfoAttr['source_link'] = $ns->url;
1461 if (!empty($ns->name)) {
1462 $noticeInfoAttr['source'] = '<a href="'
1463 . htmlspecialchars($ns->url)
1464 . '" rel="nofollow">'
1465 . htmlspecialchars($ns->name)
1472 $noticeInfoAttr['favorite'] = ($cur->hasFave($this)) ? "true" : "false";
1473 $profile = $cur->getProfile();
1474 $noticeInfoAttr['repeated'] = ($profile->hasRepeated($this->id)) ? "true" : "false";
1477 if (!empty($this->repeat_of)) {
1478 $noticeInfoAttr['repeat_of'] = $this->repeat_of;
1481 if (Event::handle('StartActivityNoticeInfo', array(&$this, &$xs, &$noticeInfoAttr))) {
1482 $xs->element('statusnet:notice_info', $noticeInfoAttr, null);
1483 Event::handle('EndActivityNoticeInfo', array(&$this, &$xs, $noticeInfoAttr));
1486 $replyNotice = null;
1488 if ($this->reply_to) {
1489 $replyNotice = Notice::staticGet('id', $this->reply_to);
1492 if (Event::handle('StartActivityInReplyTo', array(&$this, &$xs, &$replyNotice))) {
1493 if (!empty($replyNotice)) {
1494 $xs->element('link', array('rel' => 'related',
1495 'href' => $replyNotice->bestUrl()));
1496 $xs->element('thr:in-reply-to',
1497 array('ref' => $replyNotice->uri,
1498 'href' => $replyNotice->bestUrl()));
1499 Event::handle('EndActivityInReplyTo', array(&$this, &$xs, $replyNotice));
1505 if (!empty($this->conversation)) {
1506 $conv = Conversation::staticGet('id', $this->conversation);
1509 if (Event::handle('StartActivityConversation', array(&$this, &$xs, &$conv))) {
1510 if (!empty($conv)) {
1511 $xs->element('link', array('rel' => 'ostatus:conversation',
1512 'href' => $conv->uri));
1514 Event::handle('EndActivityConversation', array(&$this, &$xs, $conv));
1517 $replyProfiles = array();
1519 $reply_ids = $this->getReplies();
1521 foreach ($reply_ids as $id) {
1522 $profile = Profile::staticGet('id', $id);
1523 if (!empty($profile)) {
1524 $replyProfiles[] = $profile;
1528 if (Event::handle('StartActivityAttentionProfiles', array(&$this, &$xs, &$replyProfiles))) {
1529 foreach ($replyProfiles as $profile) {
1530 $xs->element('link', array('rel' => 'ostatus:attention',
1531 'href' => $profile->getUri()));
1532 $xs->element('link', array('rel' => 'mentioned',
1533 'href' => $profile->getUri()));
1535 Event::handle('EndActivityAttentionProfiles', array(&$this, &$xs, $replyProfiles));
1538 $groups = $this->getGroups();
1540 if (Event::handle('StartActivityAttentionGroups', array(&$this, &$xs, &$groups))) {
1541 foreach ($groups as $group) {
1542 $xs->element('link', array('rel' => 'ostatus:attention',
1543 'href' => $group->permalink()));
1544 $xs->element('link', array('rel' => 'mentioned',
1545 'href' => $group->permalink()));
1547 Event::handle('EndActivityAttentionGroups', array(&$this, &$xs, $groups));
1552 if (!empty($this->repeat_of)) {
1553 $repeat = Notice::staticGet('id', $this->repeat_of);
1556 if (Event::handle('StartActivityForward', array(&$this, &$xs, &$repeat))) {
1557 if (!empty($repeat)) {
1558 $xs->element('ostatus:forward',
1559 array('ref' => $repeat->uri,
1560 'href' => $repeat->bestUrl()));
1563 Event::handle('EndActivityForward', array(&$this, &$xs, $repeat));
1566 $tags = $this->getTags();
1568 if (Event::handle('StartActivityCategories', array(&$this, &$xs, &$tags))) {
1569 foreach ($tags as $tag) {
1570 $xs->element('category', array('term' => $tag));
1572 Event::handle('EndActivityCategories', array(&$this, &$xs, $tags));
1577 $enclosures = array();
1579 $attachments = $this->attachments();
1581 foreach ($attachments as $attachment) {
1582 $enclosure = $attachment->getEnclosure();
1584 $enclosures[] = $enclosure;
1588 if (Event::handle('StartActivityEnclosures', array(&$this, &$xs, &$enclosures))) {
1589 foreach ($enclosures as $enclosure) {
1590 $attributes = array('rel' => 'enclosure',
1591 'href' => $enclosure->url,
1592 'type' => $enclosure->mimetype,
1593 'length' => $enclosure->size);
1595 if ($enclosure->title) {
1596 $attributes['title'] = $enclosure->title;
1599 $xs->element('link', $attributes, null);
1601 Event::handle('EndActivityEnclosures', array(&$this, &$xs, $enclosures));
1607 if (Event::handle('StartActivityGeo', array(&$this, &$xs, &$lat, &$lon))) {
1608 if (!empty($lat) && !empty($lon)) {
1609 $xs->element('georss:point', null, $lat . ' ' . $lon);
1611 Event::handle('EndActivityGeo', array(&$this, &$xs, $lat, $lon));
1614 // @fixme check this logic
1616 if ($this->isLocal()) {
1618 $selfUrl = common_local_url('ApiStatusesShow', array('id' => $this->id,
1619 'format' => 'atom'));
1621 if (Event::handle('StartActivityRelSelf', array(&$this, &$xs, &$selfUrl))) {
1622 $xs->element('link', array('rel' => 'self',
1623 'type' => 'application/atom+xml',
1624 'href' => $selfUrl));
1625 Event::handle('EndActivityRelSelf', array(&$this, &$xs, $selfUrl));
1628 if (!empty($cur) && $cur->id == $this->profile_id) {
1630 // note: $selfUrl may have been changed by a plugin
1631 $relEditUrl = common_local_url('ApiStatusesShow', array('id' => $this->id,
1632 'format' => 'atom'));
1634 if (Event::handle('StartActivityRelEdit', array(&$this, &$xs, &$relEditUrl))) {
1635 $xs->element('link', array('rel' => 'edit',
1636 'type' => 'application/atom+xml',
1637 'href' => $relEditUrl));
1638 Event::handle('EndActivityRelEdit', array(&$this, &$xs, $relEditUrl));
1643 if (Event::handle('StartActivityEnd', array(&$this, &$xs))) {
1644 $xs->elementEnd('entry');
1645 Event::handle('EndActivityEnd', array(&$this, &$xs));
1648 return $xs->getString();
1652 * Returns an XML string fragment with a reference to a notice as an
1653 * Activity Streams noun object with the given element type.
1655 * Assumes that 'activity' namespace has been previously defined.
1657 * @param string $element one of 'subject', 'object', 'target'
1660 function asActivityNoun($element)
1662 $noun = ActivityObject::fromNotice($this);
1663 return $noun->asString('activity:' . $element);
1668 if (!empty($this->url)) {
1670 } else if (!empty($this->uri) && preg_match('/^https?:/', $this->uri)) {
1673 return common_local_url('shownotice',
1674 array('notice' => $this->id));
1678 function stream($fn, $args, $cachekey, $offset=0, $limit=20, $since_id=0, $max_id=0)
1680 $cache = common_memcache();
1682 if (empty($cache) ||
1683 $since_id != 0 || $max_id != 0 ||
1685 ($offset + $limit) > NOTICE_CACHE_WINDOW) {
1686 return call_user_func_array($fn, array_merge($args, array($offset, $limit, $since_id,
1690 $idkey = common_cache_key($cachekey);
1692 $idstr = $cache->get($idkey);
1694 if ($idstr !== false) {
1695 // Cache hit! Woohoo!
1696 $window = explode(',', $idstr);
1697 $ids = array_slice($window, $offset, $limit);
1701 $laststr = $cache->get($idkey.';last');
1703 if ($laststr !== false) {
1704 $window = explode(',', $laststr);
1705 $last_id = $window[0];
1706 $new_ids = call_user_func_array($fn, array_merge($args, array(0, NOTICE_CACHE_WINDOW,
1707 $last_id, 0, null)));
1709 $new_window = array_merge($new_ids, $window);
1711 $new_windowstr = implode(',', $new_window);
1713 $result = $cache->set($idkey, $new_windowstr);
1714 $result = $cache->set($idkey . ';last', $new_windowstr);
1716 $ids = array_slice($new_window, $offset, $limit);
1721 $window = call_user_func_array($fn, array_merge($args, array(0, NOTICE_CACHE_WINDOW,
1724 $windowstr = implode(',', $window);
1726 $result = $cache->set($idkey, $windowstr);
1727 $result = $cache->set($idkey . ';last', $windowstr);
1729 $ids = array_slice($window, $offset, $limit);
1735 * Determine which notice, if any, a new notice is in reply to.
1737 * For conversation tracking, we try to see where this notice fits
1738 * in the tree. Rough algorithm is:
1740 * if (reply_to is set and valid) {
1742 * } else if ((source not API or Web) and (content starts with "T NAME" or "@name ")) {
1743 * return ID of last notice by initial @name in content;
1746 * Note that all @nickname instances will still be used to save "reply" records,
1747 * so the notice shows up in the mentioned users' "replies" tab.
1749 * @param integer $reply_to ID passed in by Web or API
1750 * @param integer $profile_id ID of author
1751 * @param string $source Source tag, like 'web' or 'gwibber'
1752 * @param string $content Final notice content
1754 * @return integer ID of replied-to notice, or null for not a reply.
1757 static function getReplyTo($reply_to, $profile_id, $source, $content)
1759 static $lb = array('xmpp', 'mail', 'sms', 'omb');
1761 // If $reply_to is specified, we check that it exists, and then
1762 // return it if it does
1764 if (!empty($reply_to)) {
1765 $reply_notice = Notice::staticGet('id', $reply_to);
1766 if (!empty($reply_notice)) {
1771 // If it's not a "low bandwidth" source (one where you can't set
1772 // a reply_to argument), we return. This is mostly web and API
1775 if (!in_array($source, $lb)) {
1779 // Is there an initial @ or T?
1781 if (preg_match('/^T ([A-Z0-9]{1,64}) /', $content, $match) ||
1782 preg_match('/^@([a-z0-9]{1,64})\s+/', $content, $match)) {
1783 $nickname = common_canonical_nickname($match[1]);
1788 // Figure out who that is.
1790 $sender = Profile::staticGet('id', $profile_id);
1791 if (empty($sender)) {
1795 $recipient = common_relative_profile($sender, $nickname, common_sql_now());
1797 if (empty($recipient)) {
1801 // Get their last notice
1803 $last = $recipient->getCurrentNotice();
1805 if (!empty($last)) {
1810 static function maxContent()
1812 $contentlimit = common_config('notice', 'contentlimit');
1813 // null => use global limit (distinct from 0!)
1814 if (is_null($contentlimit)) {
1815 $contentlimit = common_config('site', 'textlimit');
1817 return $contentlimit;
1820 static function contentTooLong($content)
1822 $contentlimit = self::maxContent();
1823 return ($contentlimit > 0 && !empty($content) && (mb_strlen($content) > $contentlimit));
1826 function getLocation()
1830 if (!empty($this->location_id) && !empty($this->location_ns)) {
1831 $location = Location::fromId($this->location_id, $this->location_ns);
1834 if (is_null($location)) { // no ID, or Location::fromId() failed
1835 if (!empty($this->lat) && !empty($this->lon)) {
1836 $location = Location::fromLatLon($this->lat, $this->lon);
1843 function repeat($repeater_id, $source)
1845 $author = Profile::staticGet('id', $this->profile_id);
1847 // TRANS: Message used to repeat a notice. RT is the abbreviation of 'retweet'.
1848 // TRANS: %1$s is the repeated user's name, %2$s is the repeated notice.
1849 $content = sprintf(_('RT @%1$s %2$s'),
1853 $maxlen = common_config('site', 'textlimit');
1854 if ($maxlen > 0 && mb_strlen($content) > $maxlen) {
1855 // Web interface and current Twitter API clients will
1856 // pull the original notice's text, but some older
1857 // clients and RSS/Atom feeds will see this trimmed text.
1859 // Unfortunately this is likely to lose tags or URLs
1860 // at the end of long notices.
1861 $content = mb_substr($content, 0, $maxlen - 4) . ' ...';
1864 return self::saveNew($repeater_id, $content, $source,
1865 array('repeat_of' => $this->id));
1868 // These are supposed to be in chron order!
1870 function repeatStream($limit=100)
1872 $cache = common_memcache();
1874 if (empty($cache)) {
1875 $ids = $this->_repeatStreamDirect($limit);
1877 $idstr = $cache->get(common_cache_key('notice:repeats:'.$this->id));
1878 if ($idstr !== false) {
1879 $ids = explode(',', $idstr);
1881 $ids = $this->_repeatStreamDirect(100);
1882 $cache->set(common_cache_key('notice:repeats:'.$this->id), implode(',', $ids));
1885 // We do a max of 100, so slice down to limit
1886 $ids = array_slice($ids, 0, $limit);
1890 return Notice::getStreamByIds($ids);
1893 function _repeatStreamDirect($limit)
1895 $notice = new Notice();
1897 $notice->selectAdd(); // clears it
1898 $notice->selectAdd('id');
1900 $notice->repeat_of = $this->id;
1902 $notice->orderBy('created'); // NB: asc!
1904 if (!is_null($offset)) {
1905 $notice->limit($offset, $limit);
1910 if ($notice->find()) {
1911 while ($notice->fetch()) {
1912 $ids[] = $notice->id;
1922 function locationOptions($lat, $lon, $location_id, $location_ns, $profile = null)
1926 if (!empty($location_id) && !empty($location_ns)) {
1927 $options['location_id'] = $location_id;
1928 $options['location_ns'] = $location_ns;
1930 $location = Location::fromId($location_id, $location_ns);
1932 if (!empty($location)) {
1933 $options['lat'] = $location->lat;
1934 $options['lon'] = $location->lon;
1937 } else if (!empty($lat) && !empty($lon)) {
1938 $options['lat'] = $lat;
1939 $options['lon'] = $lon;
1941 $location = Location::fromLatLon($lat, $lon);
1943 if (!empty($location)) {
1944 $options['location_id'] = $location->location_id;
1945 $options['location_ns'] = $location->location_ns;
1947 } else if (!empty($profile)) {
1948 if (isset($profile->lat) && isset($profile->lon)) {
1949 $options['lat'] = $profile->lat;
1950 $options['lon'] = $profile->lon;
1953 if (isset($profile->location_id) && isset($profile->location_ns)) {
1954 $options['location_id'] = $profile->location_id;
1955 $options['location_ns'] = $profile->location_ns;
1962 function clearReplies()
1964 $replyNotice = new Notice();
1965 $replyNotice->reply_to = $this->id;
1967 //Null any notices that are replies to this notice
1969 if ($replyNotice->find()) {
1970 while ($replyNotice->fetch()) {
1971 $orig = clone($replyNotice);
1972 $replyNotice->reply_to = null;
1973 $replyNotice->update($orig);
1979 $reply = new Reply();
1980 $reply->notice_id = $this->id;
1982 if ($reply->find()) {
1983 while($reply->fetch()) {
1984 self::blow('reply:stream:%d', $reply->profile_id);
1992 function clearRepeats()
1994 $repeatNotice = new Notice();
1995 $repeatNotice->repeat_of = $this->id;
1997 //Null any notices that are repeats of this notice
1999 if ($repeatNotice->find()) {
2000 while ($repeatNotice->fetch()) {
2001 $orig = clone($repeatNotice);
2002 $repeatNotice->repeat_of = null;
2003 $repeatNotice->update($orig);
2008 function clearFaves()
2011 $fave->notice_id = $this->id;
2013 if ($fave->find()) {
2014 while ($fave->fetch()) {
2015 self::blow('fave:ids_by_user_own:%d', $fave->user_id);
2016 self::blow('fave:ids_by_user_own:%d;last', $fave->user_id);
2017 self::blow('fave:ids_by_user:%d', $fave->user_id);
2018 self::blow('fave:ids_by_user:%d;last', $fave->user_id);
2026 function clearTags()
2028 $tag = new Notice_tag();
2029 $tag->notice_id = $this->id;
2032 while ($tag->fetch()) {
2033 self::blow('profile:notice_ids_tagged:%d:%s', $this->profile_id, common_keyize($tag->tag));
2034 self::blow('profile:notice_ids_tagged:%d:%s;last', $this->profile_id, common_keyize($tag->tag));
2035 self::blow('notice_tag:notice_ids:%s', common_keyize($tag->tag));
2036 self::blow('notice_tag:notice_ids:%s;last', common_keyize($tag->tag));
2044 function clearGroupInboxes()
2046 $gi = new Group_inbox();
2048 $gi->notice_id = $this->id;
2051 while ($gi->fetch()) {
2052 self::blow('user_group:notice_ids:%d', $gi->group_id);
2060 function distribute()
2062 // We always insert for the author so they don't
2064 Event::handle('StartNoticeDistribute', array($this));
2066 $user = User::staticGet('id', $this->profile_id);
2067 if (!empty($user)) {
2068 Inbox::insertNotice($user->id, $this->id);
2071 if (common_config('queue', 'inboxes')) {
2072 // If there's a failure, we want to _force_
2073 // distribution at this point.
2075 $qm = QueueManager::get();
2076 $qm->enqueue($this, 'distrib');
2077 } catch (Exception $e) {
2078 // If the exception isn't transient, this
2079 // may throw more exceptions as DQH does
2080 // its own enqueueing. So, we ignore them!
2082 $handler = new DistribQueueHandler();
2083 $handler->handle($this);
2084 } catch (Exception $e) {
2085 common_log(LOG_ERR, "emergency redistribution resulted in " . $e->getMessage());
2087 // Re-throw so somebody smarter can handle it.
2091 $handler = new DistribQueueHandler();
2092 $handler->handle($this);
2098 $result = parent::insert();
2101 // Profile::hasRepeated() abuses pkeyGet(), so we
2102 // have to clear manually
2103 if (!empty($this->repeat_of)) {
2104 $c = self::memcache();
2106 $ck = self::multicacheKey('Notice',
2107 array('profile_id' => $this->profile_id,
2108 'repeat_of' => $this->repeat_of));
2118 * Get the source of the notice
2120 * @return Notice_source $ns A notice source object. 'code' is the only attribute
2121 * guaranteed to be populated.
2123 function getSource()
2125 $ns = new Notice_source();
2126 if (!empty($this->source)) {
2127 switch ($this->source) {
2134 $ns->code = $this->source;
2137 $ns = Notice_source::staticGet($this->source);
2139 $ns = new Notice_source();
2140 $ns->code = $this->source;
2141 $app = Oauth_application::staticGet('name', $this->source);
2143 $ns->name = $app->name;
2144 $ns->url = $app->source_url;
2154 * Determine whether the notice was locally created
2156 * @return boolean locality
2159 public function isLocal()
2161 return ($this->is_local == Notice::LOCAL_PUBLIC ||
2162 $this->is_local == Notice::LOCAL_NONPUBLIC);
2165 public function getTags()
2168 $tag = new Notice_tag();
2169 $tag->notice_id = $this->id;
2171 while ($tag->fetch()) {
2172 $tags[] = $tag->tag;
2179 static private function utcDate($dt)
2181 $dateStr = date('d F Y H:i:s', strtotime($dt));
2182 $d = new DateTime($dateStr, new DateTimeZone('UTC'));
2183 return $d->format(DATE_W3C);