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 if (common_config('db','type') == 'pgsql')
528 $notice->whereAdd('extract(epoch from now() - created) < ' . common_config('site', 'dupelimit'));
530 $notice->whereAdd('now() - created < ' . common_config('site', 'dupelimit'));
532 $cnt = $notice->count();
536 static function checkEditThrottle($profile_id) {
537 $profile = Profile::staticGet($profile_id);
538 if (empty($profile)) {
542 $notice = $profile->getNotices(common_config('throttle', 'count') - 1, 1);
543 if ($notice && $notice->fetch()) {
544 # If the Nth notice was posted less than timespan seconds ago
545 if (time() - strtotime($notice->created) <= common_config('throttle', 'timespan')) {
550 # Either not N notices in the stream, OR the Nth was not posted within timespan seconds
554 function getUploadedAttachment() {
556 $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"';
557 $post->query($query);
559 if (empty($post->up) || empty($post->i)) {
562 $ret = array($post->up, $post->i);
568 function hasAttachments() {
570 $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);
571 $post->query($query);
573 $n_attachments = intval($post->n_attachments);
575 return $n_attachments;
578 function attachments() {
581 $f2p = new File_to_post;
582 $f2p->post_id = $this->id;
584 while ($f2p->fetch()) {
585 $f = File::staticGet($f2p->file_id);
594 function getStreamByIds($ids)
596 $cache = common_memcache();
598 if (!empty($cache)) {
600 foreach ($ids as $id) {
601 $n = Notice::staticGet('id', $id);
606 return new ArrayWrapper($notices);
608 $notice = new Notice();
610 //if no IDs requested, just return the notice object
613 $notice->whereAdd('id in (' . implode(', ', $ids) . ')');
619 while ($notice->fetch()) {
620 $temp[$notice->id] = clone($notice);
625 foreach ($ids as $id) {
626 if (array_key_exists($id, $temp)) {
627 $wrapped[] = $temp[$id];
631 return new ArrayWrapper($wrapped);
635 function publicStream($offset=0, $limit=20, $since_id=0, $max_id=0)
637 $ids = Notice::stream(array('Notice', '_publicStreamDirect'),
640 $offset, $limit, $since_id, $max_id);
641 return Notice::getStreamByIds($ids);
644 function _publicStreamDirect($offset=0, $limit=20, $since_id=0, $max_id=0)
646 $notice = new Notice();
648 $notice->selectAdd(); // clears it
649 $notice->selectAdd('id');
651 $notice->orderBy('id DESC');
653 if (!is_null($offset)) {
654 $notice->limit($offset, $limit);
657 if (common_config('public', 'localonly')) {
658 $notice->whereAdd('is_local = ' . Notice::LOCAL_PUBLIC);
660 # -1 == blacklisted, -2 == gateway (i.e. Twitter)
661 $notice->whereAdd('is_local !='. Notice::LOCAL_NONPUBLIC);
662 $notice->whereAdd('is_local !='. Notice::GATEWAY);
665 if ($since_id != 0) {
666 $notice->whereAdd('id > ' . $since_id);
670 $notice->whereAdd('id <= ' . $max_id);
675 if ($notice->find()) {
676 while ($notice->fetch()) {
677 $ids[] = $notice->id;
687 function conversationStream($id, $offset=0, $limit=20, $since_id=0, $max_id=0)
689 $ids = Notice::stream(array('Notice', '_conversationStreamDirect'),
691 'notice:conversation_ids:'.$id,
692 $offset, $limit, $since_id, $max_id);
694 return Notice::getStreamByIds($ids);
697 function _conversationStreamDirect($id, $offset=0, $limit=20, $since_id=0, $max_id=0)
699 $notice = new Notice();
701 $notice->selectAdd(); // clears it
702 $notice->selectAdd('id');
704 $notice->conversation = $id;
706 $notice->orderBy('id DESC');
708 if (!is_null($offset)) {
709 $notice->limit($offset, $limit);
712 if ($since_id != 0) {
713 $notice->whereAdd('id > ' . $since_id);
717 $notice->whereAdd('id <= ' . $max_id);
722 if ($notice->find()) {
723 while ($notice->fetch()) {
724 $ids[] = $notice->id;
735 * Is this notice part of an active conversation?
737 * @return boolean true if other messages exist in the same
738 * conversation, false if this is the only one
740 function hasConversation()
742 if (!empty($this->conversation)) {
743 $conversation = Notice::conversationStream(
748 if ($conversation->N > 0) {
756 * Pull up a full list of local recipients who will be getting
757 * this notice in their inbox. Results will be cached, so don't
758 * change the input data wily-nilly!
760 * @param array $groups optional list of Group objects;
761 * if left empty, will be loaded from group_inbox records
762 * @param array $recipient optional list of reply profile ids
763 * if left empty, will be loaded from reply records
764 * @return array associating recipient user IDs with an inbox source constant
766 function whoGets($groups=null, $recipients=null)
768 $c = self::memcache();
771 $ni = $c->get(common_cache_key('notice:who_gets:'.$this->id));
777 if (is_null($groups)) {
778 $groups = $this->getGroups();
781 if (is_null($recipients)) {
782 $recipients = $this->getReplies();
785 $users = $this->getSubscribedUsers();
787 // FIXME: kind of ignoring 'transitional'...
788 // we'll probably stop supporting inboxless mode
793 foreach ($users as $id) {
794 $ni[$id] = NOTICE_INBOX_SOURCE_SUB;
797 foreach ($groups as $group) {
798 $users = $group->getUserMembers();
799 foreach ($users as $id) {
800 if (!array_key_exists($id, $ni)) {
801 $ni[$id] = NOTICE_INBOX_SOURCE_GROUP;
806 foreach ($recipients as $recipient) {
807 if (!array_key_exists($recipient, $ni)) {
808 $ni[$recipient] = NOTICE_INBOX_SOURCE_REPLY;
812 // Exclude any deleted, non-local, or blocking recipients.
813 $profile = $this->getProfile();
814 foreach ($ni as $id => $source) {
815 $user = User::staticGet('id', $id);
816 if (empty($user) || $user->hasBlocked($profile)) {
822 // XXX: pack this data better
823 $c->set(common_cache_key('notice:who_gets:'.$this->id), $ni);
830 * Adds this notice to the inboxes of each local user who should receive
831 * it, based on author subscriptions, group memberships, and @-replies.
833 * Warning: running a second time currently will make items appear
834 * multiple times in users' inboxes.
836 * @fixme make more robust against errors
837 * @fixme break up massive deliveries to smaller background tasks
839 * @param array $groups optional list of Group objects;
840 * if left empty, will be loaded from group_inbox records
841 * @param array $recipient optional list of reply profile ids
842 * if left empty, will be loaded from reply records
844 function addToInboxes($groups=null, $recipients=null)
846 $ni = $this->whoGets($groups, $recipients);
848 $ids = array_keys($ni);
850 // We remove the author (if they're a local user),
851 // since we'll have already done this in distribute()
853 $i = array_search($this->profile_id, $ids);
861 Inbox::bulkInsert($this->id, $ids);
866 function getSubscribedUsers()
870 if(common_config('db','quote_identifiers'))
871 $user_table = '"user"';
872 else $user_table = 'user';
876 'FROM '. $user_table .' JOIN subscription '.
877 'ON '. $user_table .'.id = subscription.subscriber ' .
878 'WHERE subscription.subscribed = %d ';
880 $user->query(sprintf($qry, $this->profile_id));
884 while ($user->fetch()) {
894 * Record this notice to the given group inboxes for delivery.
895 * Overrides the regular parsing of !group markup.
897 * @param string $group_ids
898 * @fixme might prefer URIs as identifiers, as for replies?
899 * best with generalizations on user_group to support
900 * remote groups better.
902 function saveKnownGroups($group_ids)
904 if (!is_array($group_ids)) {
905 // TRANS: Server exception thrown when no array is provided to the method saveKnownGroups().
906 throw new ServerException(_("Bad type provided to saveKnownGroups"));
910 foreach (array_unique($group_ids) as $id) {
911 $group = User_group::staticGet('id', $id);
913 common_log(LOG_ERR, "Local delivery to group id $id, $group->nickname");
914 $result = $this->addToGroupInbox($group);
916 common_log_db_error($gi, 'INSERT', __FILE__);
919 // @fixme should we save the tags here or not?
920 $groups[] = clone($group);
922 common_log(LOG_ERR, "Local delivery to group id $id skipped, doesn't exist");
930 * Parse !group delivery and record targets into group_inbox.
931 * @return array of Group objects
933 function saveGroups()
935 // Don't save groups for repeats
937 if (!empty($this->repeat_of)) {
943 /* extract all !group */
944 $count = preg_match_all('/(?:^|\s)!([A-Za-z0-9]{1,64})/',
945 strtolower($this->content),
951 $profile = $this->getProfile();
953 /* Add them to the database */
955 foreach (array_unique($match[1]) as $nickname) {
956 /* XXX: remote groups. */
957 $group = User_group::getForNickname($nickname, $profile);
963 // we automatically add a tag for every group name, too
965 $tag = Notice_tag::pkeyGet(array('tag' => common_canonical_tag($nickname),
966 'notice_id' => $this->id));
969 $this->saveTag($nickname);
972 if ($profile->isMember($group)) {
974 $result = $this->addToGroupInbox($group);
977 common_log_db_error($gi, 'INSERT', __FILE__);
980 $groups[] = clone($group);
987 function addToGroupInbox($group)
989 $gi = Group_inbox::pkeyGet(array('group_id' => $group->id,
990 'notice_id' => $this->id));
994 $gi = new Group_inbox();
996 $gi->group_id = $group->id;
997 $gi->notice_id = $this->id;
998 $gi->created = $this->created;
1000 $result = $gi->insert();
1003 common_log_db_error($gi, 'INSERT', __FILE__);
1004 // TRANS: Server exception thrown when an update for a group inbox fails.
1005 throw new ServerException(_('Problem saving group inbox.'));
1008 self::blow('user_group:notice_ids:%d', $gi->group_id);
1015 * Save reply records indicating that this notice needs to be
1016 * delivered to the local users with the given URIs.
1018 * Since this is expected to be used when saving foreign-sourced
1019 * messages, we won't deliver to any remote targets as that's the
1020 * source service's responsibility.
1022 * Mail notifications etc will be handled later.
1024 * @param array of unique identifier URIs for recipients
1026 function saveKnownReplies($uris)
1032 $sender = Profile::staticGet($this->profile_id);
1034 foreach (array_unique($uris) as $uri) {
1036 $profile = Profile::fromURI($uri);
1038 if (empty($profile)) {
1039 common_log(LOG_WARNING, "Unable to determine profile for URI '$uri'");
1043 if ($profile->hasBlocked($sender)) {
1044 common_log(LOG_INFO, "Not saving reply to profile {$profile->id} ($uri) from sender {$sender->id} because of a block.");
1048 $reply = new Reply();
1050 $reply->notice_id = $this->id;
1051 $reply->profile_id = $profile->id;
1053 common_log(LOG_INFO, __METHOD__ . ": saving reply: notice $this->id to profile $profile->id");
1055 $id = $reply->insert();
1062 * Pull @-replies from this message's content in StatusNet markup format
1063 * and save reply records indicating that this message needs to be
1064 * delivered to those users.
1066 * Mail notifications to local profiles will be sent later.
1068 * @return array of integer profile IDs
1071 function saveReplies()
1073 // Don't save reply data for repeats
1075 if (!empty($this->repeat_of)) {
1079 $sender = Profile::staticGet($this->profile_id);
1081 // @todo ideally this parser information would only
1082 // be calculated once.
1084 $mentions = common_find_mentions($this->content, $this);
1088 // store replied only for first @ (what user/notice what the reply directed,
1089 // we assume first @ is it)
1091 foreach ($mentions as $mention) {
1093 foreach ($mention['mentioned'] as $mentioned) {
1095 // skip if they're already covered
1097 if (!empty($replied[$mentioned->id])) {
1101 // Don't save replies from blocked profile to local user
1103 $mentioned_user = User::staticGet('id', $mentioned->id);
1104 if (!empty($mentioned_user) && $mentioned_user->hasBlocked($sender)) {
1108 $reply = new Reply();
1110 $reply->notice_id = $this->id;
1111 $reply->profile_id = $mentioned->id;
1113 $id = $reply->insert();
1116 common_log_db_error($reply, 'INSERT', __FILE__);
1117 // TRANS: Server exception thrown when a reply cannot be saved.
1118 // TRANS: %1$d is a notice ID, %2$d is the ID of the mentioned user.
1119 throw new ServerException(sprintf(_("Could not save reply for %1$d, %2$d."), $this->id, $mentioned->id));
1121 $replied[$mentioned->id] = 1;
1122 self::blow('reply:stream:%d', $mentioned->id);
1127 $recipientIds = array_keys($replied);
1129 return $recipientIds;
1133 * Pull the complete list of @-reply targets for this notice.
1135 * @return array of integer profile ids
1137 function getReplies()
1143 $reply = new Reply();
1144 $reply->selectAdd();
1145 $reply->selectAdd('profile_id');
1146 $reply->notice_id = $this->id;
1148 if ($reply->find()) {
1149 while($reply->fetch()) {
1150 $ids[] = $reply->profile_id;
1160 * Send e-mail notifications to local @-reply targets.
1162 * Replies must already have been saved; this is expected to be run
1163 * from the distrib queue handler.
1165 function sendReplyNotifications()
1167 // Don't send reply notifications for repeats
1169 if (!empty($this->repeat_of)) {
1173 $recipientIds = $this->getReplies();
1175 foreach ($recipientIds as $recipientId) {
1176 $user = User::staticGet('id', $recipientId);
1177 if (!empty($user)) {
1178 mail_notify_attn($user, $this);
1184 * Pull list of groups this notice needs to be delivered to,
1185 * as previously recorded by saveGroups() or saveKnownGroups().
1187 * @return array of Group objects
1189 function getGroups()
1191 // Don't save groups for repeats
1193 if (!empty($this->repeat_of)) {
1201 $gi = new Group_inbox();
1204 $gi->selectAdd('group_id');
1206 $gi->notice_id = $this->id;
1209 while ($gi->fetch()) {
1210 $group = User_group::staticGet('id', $gi->group_id);
1222 // This has gotten way too long. Needs to be sliced up into functional bits
1223 // or ideally exported to a utility class.
1225 function asAtomEntry($namespace=false, $source=false, $author=true, $cur=null)
1227 $profile = $this->getProfile();
1229 $xs = new XMLStringer(true);
1232 $attrs = array('xmlns' => 'http://www.w3.org/2005/Atom',
1233 'xmlns:thr' => 'http://purl.org/syndication/thread/1.0',
1234 'xmlns:georss' => 'http://www.georss.org/georss',
1235 'xmlns:activity' => 'http://activitystrea.ms/spec/1.0/',
1236 'xmlns:media' => 'http://purl.org/syndication/atommedia',
1237 'xmlns:poco' => 'http://portablecontacts.net/spec/1.0',
1238 'xmlns:ostatus' => 'http://ostatus.org/schema/1.0',
1239 'xmlns:statusnet' => 'http://status.net/schema/api/1/');
1244 if (Event::handle('StartActivityStart', array(&$this, &$xs, &$attrs))) {
1245 $xs->elementStart('entry', $attrs);
1246 Event::handle('EndActivityStart', array(&$this, &$xs, &$attrs));
1249 if (Event::handle('StartActivitySource', array(&$this, &$xs))) {
1253 $atom_feed = $profile->getAtomFeed();
1255 if (!empty($atom_feed)) {
1257 $xs->elementStart('source');
1259 // XXX: we should store the actual feed ID
1261 $xs->element('id', null, $atom_feed);
1263 // XXX: we should store the actual feed title
1265 $xs->element('title', null, $profile->getBestName());
1267 $xs->element('link', array('rel' => 'alternate',
1268 'type' => 'text/html',
1269 'href' => $profile->profileurl));
1271 $xs->element('link', array('rel' => 'self',
1272 'type' => 'application/atom+xml',
1273 'href' => $atom_feed));
1275 $xs->element('icon', null, $profile->avatarUrl(AVATAR_PROFILE_SIZE));
1277 $notice = $profile->getCurrentNotice();
1279 if (!empty($notice)) {
1280 $xs->element('updated', null, self::utcDate($notice->created));
1283 $user = User::staticGet('id', $profile->id);
1285 if (!empty($user)) {
1286 $xs->element('link', array('rel' => 'license',
1287 'href' => common_config('license', 'url')));
1290 $xs->elementEnd('source');
1293 Event::handle('EndActivitySource', array(&$this, &$xs));
1296 $title = common_xml_safe_str($this->content);
1298 if (Event::handle('StartActivityTitle', array(&$this, &$xs, &$title))) {
1299 $xs->element('title', null, $title);
1300 Event::handle('EndActivityTitle', array($this, &$xs, $title));
1306 $atomAuthor = $profile->asAtomAuthor($cur);
1309 if (Event::handle('StartActivityAuthor', array(&$this, &$xs, &$atomAuthor))) {
1310 if (!empty($atomAuthor)) {
1311 $xs->raw($atomAuthor);
1312 Event::handle('EndActivityAuthor', array(&$this, &$xs, &$atomAuthor));
1319 $actor = $profile->asActivityActor();
1322 if (Event::handle('StartActivityActor', array(&$this, &$xs, &$actor))) {
1323 if (!empty($actor)) {
1325 Event::handle('EndActivityActor', array(&$this, &$xs, &$actor));
1329 $url = $this->bestUrl();
1331 if (Event::handle('StartActivityLink', array(&$this, &$xs, &$url))) {
1332 $xs->element('link', array('rel' => 'alternate',
1333 'type' => 'text/html',
1335 Event::handle('EndActivityLink', array(&$this, &$xs, $url));
1340 if (Event::handle('StartActivityId', array(&$this, &$xs, &$id))) {
1341 $xs->element('id', null, $id);
1342 Event::handle('EndActivityId', array(&$this, &$xs, $id));
1345 $published = self::utcDate($this->created);
1347 if (Event::handle('StartActivityPublished', array(&$this, &$xs, &$published))) {
1348 $xs->element('published', null, $published);
1349 Event::handle('EndActivityPublished', array(&$this, &$xs, $published));
1352 $updated = $published; // XXX: notices are usually immutable
1354 if (Event::handle('StartActivityUpdated', array(&$this, &$xs, &$updated))) {
1355 $xs->element('updated', null, $updated);
1356 Event::handle('EndActivityUpdated', array(&$this, &$xs, $updated));
1359 $content = common_xml_safe_str($this->rendered);
1361 if (Event::handle('StartActivityContent', array(&$this, &$xs, &$content))) {
1362 $xs->element('content', array('type' => 'html'), $content);
1363 Event::handle('EndActivityContent', array(&$this, &$xs, $content));
1366 // Most of our notices represent POSTing a NOTE. This is the default verb
1367 // for activity streams, so we normally just leave it out.
1369 $verb = ActivityVerb::POST;
1371 if (Event::handle('StartActivityVerb', array(&$this, &$xs, &$verb))) {
1372 $xs->element('activity:verb', null, $verb);
1373 Event::handle('EndActivityVerb', array(&$this, &$xs, $verb));
1376 // We use the default behavior for activity streams: if there's no activity:object,
1377 // then treat the entry itself as the object. Here, you can set the type of that object,
1378 // which is normally a NOTE.
1380 $type = ActivityObject::NOTE;
1382 if (Event::handle('StartActivityDefaultObjectType', array(&$this, &$xs, &$type))) {
1383 $xs->element('activity:object-type', null, $type);
1384 Event::handle('EndActivityDefaultObjectType', array(&$this, &$xs, $type));
1387 // Since we usually use the entry itself as an object, we don't have an explicit
1388 // object. Some extensions may want to add them (for photo, event, music, etc.).
1392 if (Event::handle('StartActivityObjects', array(&$this, &$xs, &$objects))) {
1393 foreach ($objects as $object) {
1394 $xs->raw($object->asString());
1396 Event::handle('EndActivityObjects', array(&$this, &$xs, $objects));
1399 $noticeInfoAttr = array('local_id' => $this->id); // local notice ID (useful to clients for ordering)
1401 $ns = $this->getSource();
1404 $noticeInfoAttr['source'] = $ns->code;
1405 if (!empty($ns->url)) {
1406 $noticeInfoAttr['source_link'] = $ns->url;
1407 if (!empty($ns->name)) {
1408 $noticeInfoAttr['source'] = '<a href="'
1409 . htmlspecialchars($ns->url)
1410 . '" rel="nofollow">'
1411 . htmlspecialchars($ns->name)
1418 $noticeInfoAttr['favorite'] = ($cur->hasFave($this)) ? "true" : "false";
1419 $profile = $cur->getProfile();
1420 $noticeInfoAttr['repeated'] = ($profile->hasRepeated($this->id)) ? "true" : "false";
1423 if (!empty($this->repeat_of)) {
1424 $noticeInfoAttr['repeat_of'] = $this->repeat_of;
1427 if (Event::handle('StartActivityNoticeInfo', array(&$this, &$xs, &$noticeInfoAttr))) {
1428 $xs->element('statusnet:notice_info', $noticeInfoAttr, null);
1429 Event::handle('EndActivityNoticeInfo', array(&$this, &$xs, $noticeInfoAttr));
1432 $replyNotice = null;
1434 if ($this->reply_to) {
1435 $replyNotice = Notice::staticGet('id', $this->reply_to);
1438 if (Event::handle('StartActivityInReplyTo', array(&$this, &$xs, &$replyNotice))) {
1439 if (!empty($replyNotice)) {
1440 $xs->element('link', array('rel' => 'related',
1441 'href' => $replyNotice->bestUrl()));
1442 $xs->element('thr:in-reply-to',
1443 array('ref' => $replyNotice->uri,
1444 'href' => $replyNotice->bestUrl()));
1445 Event::handle('EndActivityInReplyTo', array(&$this, &$xs, $replyNotice));
1451 if (!empty($this->conversation)) {
1452 $conv = Conversation::staticGet('id', $this->conversation);
1455 if (Event::handle('StartActivityConversation', array(&$this, &$xs, &$conv))) {
1456 if (!empty($conv)) {
1457 $xs->element('link', array('rel' => 'ostatus:conversation',
1458 'href' => $conv->uri));
1460 Event::handle('EndActivityConversation', array(&$this, &$xs, $conv));
1463 $replyProfiles = array();
1465 $reply_ids = $this->getReplies();
1467 foreach ($reply_ids as $id) {
1468 $profile = Profile::staticGet('id', $id);
1469 if (!empty($profile)) {
1470 $replyProfiles[] = $profile;
1474 if (Event::handle('StartActivityAttentionProfiles', array(&$this, &$xs, &$replyProfiles))) {
1475 foreach ($replyProfiles as $profile) {
1476 $xs->element('link', array('rel' => 'ostatus:attention',
1477 'href' => $profile->getUri()));
1478 $xs->element('link', array('rel' => 'mentioned',
1479 'href' => $profile->getUri()));
1481 Event::handle('EndActivityAttentionProfiles', array(&$this, &$xs, $replyProfiles));
1484 $groups = $this->getGroups();
1486 if (Event::handle('StartActivityAttentionGroups', array(&$this, &$xs, &$groups))) {
1487 foreach ($groups as $group) {
1488 $xs->element('link', array('rel' => 'ostatus:attention',
1489 'href' => $group->permalink()));
1490 $xs->element('link', array('rel' => 'mentioned',
1491 'href' => $group->permalink()));
1493 Event::handle('EndActivityAttentionGroups', array(&$this, &$xs, $groups));
1498 if (!empty($this->repeat_of)) {
1499 $repeat = Notice::staticGet('id', $this->repeat_of);
1502 if (Event::handle('StartActivityForward', array(&$this, &$xs, &$repeat))) {
1503 if (!empty($repeat)) {
1504 $xs->element('ostatus:forward',
1505 array('ref' => $repeat->uri,
1506 'href' => $repeat->bestUrl()));
1509 Event::handle('EndActivityForward', array(&$this, &$xs, $repeat));
1512 $tags = $this->getTags();
1514 if (Event::handle('StartActivityCategories', array(&$this, &$xs, &$tags))) {
1515 foreach ($tags as $tag) {
1516 $xs->element('category', array('term' => $tag));
1518 Event::handle('EndActivityCategories', array(&$this, &$xs, $tags));
1523 $enclosures = array();
1525 $attachments = $this->attachments();
1527 foreach ($attachments as $attachment) {
1528 $enclosure = $attachment->getEnclosure();
1530 $enclosures[] = $enclosure;
1534 if (Event::handle('StartActivityEnclosures', array(&$this, &$xs, &$enclosures))) {
1535 foreach ($enclosures as $enclosure) {
1536 $attributes = array('rel' => 'enclosure',
1537 'href' => $enclosure->url,
1538 'type' => $enclosure->mimetype,
1539 'length' => $enclosure->size);
1541 if ($enclosure->title) {
1542 $attributes['title'] = $enclosure->title;
1545 $xs->element('link', $attributes, null);
1547 Event::handle('EndActivityEnclosures', array(&$this, &$xs, $enclosures));
1553 if (Event::handle('StartActivityGeo', array(&$this, &$xs, &$lat, &$lon))) {
1554 if (!empty($lat) && !empty($lon)) {
1555 $xs->element('georss:point', null, $lat . ' ' . $lon);
1557 Event::handle('EndActivityGeo', array(&$this, &$xs, $lat, $lon));
1560 if (Event::handle('StartActivityEnd', array(&$this, &$xs))) {
1561 $xs->elementEnd('entry');
1562 Event::handle('EndActivityEnd', array(&$this, &$xs));
1565 return $xs->getString();
1569 * Returns an XML string fragment with a reference to a notice as an
1570 * Activity Streams noun object with the given element type.
1572 * Assumes that 'activity' namespace has been previously defined.
1574 * @param string $element one of 'subject', 'object', 'target'
1577 function asActivityNoun($element)
1579 $noun = ActivityObject::fromNotice($this);
1580 return $noun->asString('activity:' . $element);
1585 if (!empty($this->url)) {
1587 } else if (!empty($this->uri) && preg_match('/^https?:/', $this->uri)) {
1590 return common_local_url('shownotice',
1591 array('notice' => $this->id));
1595 function stream($fn, $args, $cachekey, $offset=0, $limit=20, $since_id=0, $max_id=0)
1597 $cache = common_memcache();
1599 if (empty($cache) ||
1600 $since_id != 0 || $max_id != 0 ||
1602 ($offset + $limit) > NOTICE_CACHE_WINDOW) {
1603 return call_user_func_array($fn, array_merge($args, array($offset, $limit, $since_id,
1607 $idkey = common_cache_key($cachekey);
1609 $idstr = $cache->get($idkey);
1611 if ($idstr !== false) {
1612 // Cache hit! Woohoo!
1613 $window = explode(',', $idstr);
1614 $ids = array_slice($window, $offset, $limit);
1618 $laststr = $cache->get($idkey.';last');
1620 if ($laststr !== false) {
1621 $window = explode(',', $laststr);
1622 $last_id = $window[0];
1623 $new_ids = call_user_func_array($fn, array_merge($args, array(0, NOTICE_CACHE_WINDOW,
1624 $last_id, 0, null)));
1626 $new_window = array_merge($new_ids, $window);
1628 $new_windowstr = implode(',', $new_window);
1630 $result = $cache->set($idkey, $new_windowstr);
1631 $result = $cache->set($idkey . ';last', $new_windowstr);
1633 $ids = array_slice($new_window, $offset, $limit);
1638 $window = call_user_func_array($fn, array_merge($args, array(0, NOTICE_CACHE_WINDOW,
1641 $windowstr = implode(',', $window);
1643 $result = $cache->set($idkey, $windowstr);
1644 $result = $cache->set($idkey . ';last', $windowstr);
1646 $ids = array_slice($window, $offset, $limit);
1652 * Determine which notice, if any, a new notice is in reply to.
1654 * For conversation tracking, we try to see where this notice fits
1655 * in the tree. Rough algorithm is:
1657 * if (reply_to is set and valid) {
1659 * } else if ((source not API or Web) and (content starts with "T NAME" or "@name ")) {
1660 * return ID of last notice by initial @name in content;
1663 * Note that all @nickname instances will still be used to save "reply" records,
1664 * so the notice shows up in the mentioned users' "replies" tab.
1666 * @param integer $reply_to ID passed in by Web or API
1667 * @param integer $profile_id ID of author
1668 * @param string $source Source tag, like 'web' or 'gwibber'
1669 * @param string $content Final notice content
1671 * @return integer ID of replied-to notice, or null for not a reply.
1674 static function getReplyTo($reply_to, $profile_id, $source, $content)
1676 static $lb = array('xmpp', 'mail', 'sms', 'omb');
1678 // If $reply_to is specified, we check that it exists, and then
1679 // return it if it does
1681 if (!empty($reply_to)) {
1682 $reply_notice = Notice::staticGet('id', $reply_to);
1683 if (!empty($reply_notice)) {
1688 // If it's not a "low bandwidth" source (one where you can't set
1689 // a reply_to argument), we return. This is mostly web and API
1692 if (!in_array($source, $lb)) {
1696 // Is there an initial @ or T?
1698 if (preg_match('/^T ([A-Z0-9]{1,64}) /', $content, $match) ||
1699 preg_match('/^@([a-z0-9]{1,64})\s+/', $content, $match)) {
1700 $nickname = common_canonical_nickname($match[1]);
1705 // Figure out who that is.
1707 $sender = Profile::staticGet('id', $profile_id);
1708 if (empty($sender)) {
1712 $recipient = common_relative_profile($sender, $nickname, common_sql_now());
1714 if (empty($recipient)) {
1718 // Get their last notice
1720 $last = $recipient->getCurrentNotice();
1722 if (!empty($last)) {
1727 static function maxContent()
1729 $contentlimit = common_config('notice', 'contentlimit');
1730 // null => use global limit (distinct from 0!)
1731 if (is_null($contentlimit)) {
1732 $contentlimit = common_config('site', 'textlimit');
1734 return $contentlimit;
1737 static function contentTooLong($content)
1739 $contentlimit = self::maxContent();
1740 return ($contentlimit > 0 && !empty($content) && (mb_strlen($content) > $contentlimit));
1743 function getLocation()
1747 if (!empty($this->location_id) && !empty($this->location_ns)) {
1748 $location = Location::fromId($this->location_id, $this->location_ns);
1751 if (is_null($location)) { // no ID, or Location::fromId() failed
1752 if (!empty($this->lat) && !empty($this->lon)) {
1753 $location = Location::fromLatLon($this->lat, $this->lon);
1760 function repeat($repeater_id, $source)
1762 $author = Profile::staticGet('id', $this->profile_id);
1764 // TRANS: Message used to repeat a notice. RT is the abbreviation of 'retweet'.
1765 // TRANS: %1$s is the repeated user's name, %2$s is the repeated notice.
1766 $content = sprintf(_('RT @%1$s %2$s'),
1770 $maxlen = common_config('site', 'textlimit');
1771 if ($maxlen > 0 && mb_strlen($content) > $maxlen) {
1772 // Web interface and current Twitter API clients will
1773 // pull the original notice's text, but some older
1774 // clients and RSS/Atom feeds will see this trimmed text.
1776 // Unfortunately this is likely to lose tags or URLs
1777 // at the end of long notices.
1778 $content = mb_substr($content, 0, $maxlen - 4) . ' ...';
1781 return self::saveNew($repeater_id, $content, $source,
1782 array('repeat_of' => $this->id));
1785 // These are supposed to be in chron order!
1787 function repeatStream($limit=100)
1789 $cache = common_memcache();
1791 if (empty($cache)) {
1792 $ids = $this->_repeatStreamDirect($limit);
1794 $idstr = $cache->get(common_cache_key('notice:repeats:'.$this->id));
1795 if ($idstr !== false) {
1796 $ids = explode(',', $idstr);
1798 $ids = $this->_repeatStreamDirect(100);
1799 $cache->set(common_cache_key('notice:repeats:'.$this->id), implode(',', $ids));
1802 // We do a max of 100, so slice down to limit
1803 $ids = array_slice($ids, 0, $limit);
1807 return Notice::getStreamByIds($ids);
1810 function _repeatStreamDirect($limit)
1812 $notice = new Notice();
1814 $notice->selectAdd(); // clears it
1815 $notice->selectAdd('id');
1817 $notice->repeat_of = $this->id;
1819 $notice->orderBy('created'); // NB: asc!
1821 if (!is_null($offset)) {
1822 $notice->limit($offset, $limit);
1827 if ($notice->find()) {
1828 while ($notice->fetch()) {
1829 $ids[] = $notice->id;
1839 function locationOptions($lat, $lon, $location_id, $location_ns, $profile = null)
1843 if (!empty($location_id) && !empty($location_ns)) {
1845 $options['location_id'] = $location_id;
1846 $options['location_ns'] = $location_ns;
1848 $location = Location::fromId($location_id, $location_ns);
1850 if (!empty($location)) {
1851 $options['lat'] = $location->lat;
1852 $options['lon'] = $location->lon;
1855 } else if (!empty($lat) && !empty($lon)) {
1857 $options['lat'] = $lat;
1858 $options['lon'] = $lon;
1860 $location = Location::fromLatLon($lat, $lon);
1862 if (!empty($location)) {
1863 $options['location_id'] = $location->location_id;
1864 $options['location_ns'] = $location->location_ns;
1866 } else if (!empty($profile)) {
1868 if (isset($profile->lat) && isset($profile->lon)) {
1869 $options['lat'] = $profile->lat;
1870 $options['lon'] = $profile->lon;
1873 if (isset($profile->location_id) && isset($profile->location_ns)) {
1874 $options['location_id'] = $profile->location_id;
1875 $options['location_ns'] = $profile->location_ns;
1882 function clearReplies()
1884 $replyNotice = new Notice();
1885 $replyNotice->reply_to = $this->id;
1887 //Null any notices that are replies to this notice
1889 if ($replyNotice->find()) {
1890 while ($replyNotice->fetch()) {
1891 $orig = clone($replyNotice);
1892 $replyNotice->reply_to = null;
1893 $replyNotice->update($orig);
1899 $reply = new Reply();
1900 $reply->notice_id = $this->id;
1902 if ($reply->find()) {
1903 while($reply->fetch()) {
1904 self::blow('reply:stream:%d', $reply->profile_id);
1912 function clearRepeats()
1914 $repeatNotice = new Notice();
1915 $repeatNotice->repeat_of = $this->id;
1917 //Null any notices that are repeats of this notice
1919 if ($repeatNotice->find()) {
1920 while ($repeatNotice->fetch()) {
1921 $orig = clone($repeatNotice);
1922 $repeatNotice->repeat_of = null;
1923 $repeatNotice->update($orig);
1928 function clearFaves()
1931 $fave->notice_id = $this->id;
1933 if ($fave->find()) {
1934 while ($fave->fetch()) {
1935 self::blow('fave:ids_by_user_own:%d', $fave->user_id);
1936 self::blow('fave:ids_by_user_own:%d;last', $fave->user_id);
1937 self::blow('fave:ids_by_user:%d', $fave->user_id);
1938 self::blow('fave:ids_by_user:%d;last', $fave->user_id);
1946 function clearTags()
1948 $tag = new Notice_tag();
1949 $tag->notice_id = $this->id;
1952 while ($tag->fetch()) {
1953 self::blow('profile:notice_ids_tagged:%d:%s', $this->profile_id, common_keyize($tag->tag));
1954 self::blow('profile:notice_ids_tagged:%d:%s;last', $this->profile_id, common_keyize($tag->tag));
1955 self::blow('notice_tag:notice_ids:%s', common_keyize($tag->tag));
1956 self::blow('notice_tag:notice_ids:%s;last', common_keyize($tag->tag));
1964 function clearGroupInboxes()
1966 $gi = new Group_inbox();
1968 $gi->notice_id = $this->id;
1971 while ($gi->fetch()) {
1972 self::blow('user_group:notice_ids:%d', $gi->group_id);
1980 function distribute()
1982 // We always insert for the author so they don't
1985 $user = User::staticGet('id', $this->profile_id);
1986 if (!empty($user)) {
1987 Inbox::insertNotice($user->id, $this->id);
1990 if (common_config('queue', 'inboxes')) {
1991 // If there's a failure, we want to _force_
1992 // distribution at this point.
1994 $qm = QueueManager::get();
1995 $qm->enqueue($this, 'distrib');
1996 } catch (Exception $e) {
1997 // If the exception isn't transient, this
1998 // may throw more exceptions as DQH does
1999 // its own enqueueing. So, we ignore them!
2001 $handler = new DistribQueueHandler();
2002 $handler->handle($this);
2003 } catch (Exception $e) {
2004 common_log(LOG_ERR, "emergency redistribution resulted in " . $e->getMessage());
2006 // Re-throw so somebody smarter can handle it.
2010 $handler = new DistribQueueHandler();
2011 $handler->handle($this);
2017 $result = parent::insert();
2020 // Profile::hasRepeated() abuses pkeyGet(), so we
2021 // have to clear manually
2022 if (!empty($this->repeat_of)) {
2023 $c = self::memcache();
2025 $ck = self::multicacheKey('Notice',
2026 array('profile_id' => $this->profile_id,
2027 'repeat_of' => $this->repeat_of));
2037 * Get the source of the notice
2039 * @return Notice_source $ns A notice source object. 'code' is the only attribute
2040 * guaranteed to be populated.
2042 function getSource()
2044 $ns = new Notice_source();
2045 if (!empty($this->source)) {
2046 switch ($this->source) {
2053 $ns->code = $this->source;
2056 $ns = Notice_source::staticGet($this->source);
2058 $ns = new Notice_source();
2059 $ns->code = $this->source;
2060 $app = Oauth_application::staticGet('name', $this->source);
2062 $ns->name = $app->name;
2063 $ns->url = $app->source_url;
2073 * Determine whether the notice was locally created
2075 * @return boolean locality
2078 public function isLocal()
2080 return ($this->is_local == Notice::LOCAL_PUBLIC ||
2081 $this->is_local == Notice::LOCAL_NONPUBLIC);
2084 public function getTags()
2087 $tag = new Notice_tag();
2088 $tag->notice_id = $this->id;
2090 while ($tag->fetch()) {
2091 $tags[] = $tag->tag;
2098 static private function utcDate($dt)
2100 $dateStr = date('d F Y H:i:s', strtotime($dt));
2101 $d = new DateTime($dateStr, new DateTimeZone('UTC'));
2102 return $d->format(DATE_W3C);