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 // Clear related records
126 $this->clearReplies();
127 $this->clearRepeats();
130 $this->clearGroupInboxes();
132 // NOTE: we don't clear inboxes
133 // NOTE: we don't clear queue items
135 $result = parent::delete();
137 $this->blowOnDelete();
142 * Extract #hashtags from this notice's content and save them to the database.
146 /* extract all #hastags */
147 $count = preg_match_all('/(?:^|\s)#([\pL\pN_\-\.]{1,64})/', strtolower($this->content), $match);
152 /* Add them to the database */
153 return $this->saveKnownTags($match[1]);
157 * Record the given set of hash tags in the db for this notice.
158 * Given tag strings will be normalized and checked for dupes.
160 function saveKnownTags($hashtags)
162 //turn each into their canonical tag
163 //this is needed to remove dupes before saving e.g. #hash.tag = #hashtag
164 for($i=0; $i<count($hashtags); $i++) {
165 /* elide characters we don't want in the tag */
166 $hashtags[$i] = common_canonical_tag($hashtags[$i]);
169 foreach(array_unique($hashtags) as $hashtag) {
170 $this->saveTag($hashtag);
171 self::blow('profile:notice_ids_tagged:%d:%s', $this->profile_id, $hashtag);
177 * Record a single hash tag as associated with this notice.
178 * Tag format and uniqueness must be validated by caller.
180 function saveTag($hashtag)
182 $tag = new Notice_tag();
183 $tag->notice_id = $this->id;
184 $tag->tag = $hashtag;
185 $tag->created = $this->created;
186 $id = $tag->insert();
189 // TRANS: Server exception. %s are the error details.
190 throw new ServerException(sprintf(_('Database error inserting hashtag: %s'),
191 $last_error->message));
195 // if it's saved, blow its cache
196 $tag->blowCache(false);
200 * Save a new notice and push it out to subscribers' inboxes.
201 * Poster's permissions are checked before sending.
203 * @param int $profile_id Profile ID of the poster
204 * @param string $content source message text; links may be shortened
205 * per current user's preference
206 * @param string $source source key ('web', 'api', etc)
207 * @param array $options Associative array of optional properties:
208 * string 'created' timestamp of notice; defaults to now
209 * int 'is_local' source/gateway ID, one of:
210 * Notice::LOCAL_PUBLIC - Local, ok to appear in public timeline
211 * Notice::REMOTE_OMB - Sent from a remote OMB service;
212 * hide from public timeline but show in
213 * local "and friends" timelines
214 * Notice::LOCAL_NONPUBLIC - Local, but hide from public timeline
215 * Notice::GATEWAY - From another non-OMB service;
216 * will not appear in public views
217 * float 'lat' decimal latitude for geolocation
218 * float 'lon' decimal longitude for geolocation
219 * int 'location_id' geoname identifier
220 * int 'location_ns' geoname namespace to interpret location_id
221 * int 'reply_to'; notice ID this is a reply to
222 * int 'repeat_of'; notice ID this is a repeat of
223 * string 'uri' unique ID for notice; defaults to local notice URL
224 * string 'url' permalink to notice; defaults to local notice URL
225 * string 'rendered' rendered HTML version of content
226 * array 'replies' list of profile URIs for reply delivery in
227 * place of extracting @-replies from content.
228 * array 'groups' list of group IDs to deliver to, in place of
229 * extracting ! tags from content
230 * array 'tags' list of hashtag strings to save with the notice
231 * in place of extracting # tags from content
232 * array 'urls' list of attached/referred URLs to save with the
233 * notice in place of extracting links from content
234 * @fixme tag override
237 * @throws ClientException
239 static function saveNew($profile_id, $content, $source, $options=null) {
240 $defaults = array('uri' => null,
243 'repeat_of' => null);
245 if (!empty($options)) {
246 $options = $options + $defaults;
252 if (!isset($is_local)) {
253 $is_local = Notice::LOCAL_PUBLIC;
256 $profile = Profile::staticGet($profile_id);
258 $final = common_shorten_links($content);
260 if (Notice::contentTooLong($final)) {
261 // TRANS: Client exception thrown if a notice contains too many characters.
262 throw new ClientException(_('Problem saving notice. Too long.'));
265 if (empty($profile)) {
266 // TRANS: Client exception thrown when trying to save a notice for an unknown user.
267 throw new ClientException(_('Problem saving notice. Unknown user.'));
270 if (common_config('throttle', 'enabled') && !Notice::checkEditThrottle($profile_id)) {
271 common_log(LOG_WARNING, 'Excessive posting by profile #' . $profile_id . '; throttled.');
272 // TRANS: Client exception thrown when a user tries to post too many notices in a given time frame.
273 throw new ClientException(_('Too many notices too fast; take a breather '.
274 'and post again in a few minutes.'));
277 if (common_config('site', 'dupelimit') > 0 && !Notice::checkDupes($profile_id, $final)) {
278 common_log(LOG_WARNING, 'Dupe posting by profile #' . $profile_id . '; throttled.');
279 // TRANS: Client exception thrown when a user tries to post too many duplicate notices in a given time frame.
280 throw new ClientException(_('Too many duplicate messages too quickly;'.
281 ' take a breather and post again in a few minutes.'));
284 if (!$profile->hasRight(Right::NEWNOTICE)) {
285 common_log(LOG_WARNING, "Attempted post from user disallowed to post: " . $profile->nickname);
287 // TRANS: Client exception thrown when a user tries to post while being banned.
288 throw new ClientException(_('You are banned from posting notices on this site.'), 403);
291 $notice = new Notice();
292 $notice->profile_id = $profile_id;
294 $autosource = common_config('public', 'autosource');
296 # Sandboxed are non-false, but not 1, either
298 if (!$profile->hasRight(Right::PUBLICNOTICE) ||
299 ($source && $autosource && in_array($source, $autosource))) {
300 $notice->is_local = Notice::LOCAL_NONPUBLIC;
302 $notice->is_local = $is_local;
305 if (!empty($created)) {
306 $notice->created = $created;
308 $notice->created = common_sql_now();
311 $notice->content = $final;
313 $notice->source = $source;
317 // Handle repeat case
319 if (isset($repeat_of)) {
320 $notice->repeat_of = $repeat_of;
322 $notice->reply_to = self::getReplyTo($reply_to, $profile_id, $source, $final);
325 if (!empty($notice->reply_to)) {
326 $reply = Notice::staticGet('id', $notice->reply_to);
327 $notice->conversation = $reply->conversation;
330 if (!empty($lat) && !empty($lon)) {
335 if (!empty($location_ns) && !empty($location_id)) {
336 $notice->location_id = $location_id;
337 $notice->location_ns = $location_ns;
340 if (!empty($rendered)) {
341 $notice->rendered = $rendered;
343 $notice->rendered = common_render_content($final, $notice);
346 if (Event::handle('StartNoticeSave', array(&$notice))) {
348 // XXX: some of these functions write to the DB
350 $id = $notice->insert();
353 common_log_db_error($notice, 'INSERT', __FILE__);
354 // TRANS: Server exception thrown when a notice cannot be saved.
355 throw new ServerException(_('Problem saving notice.'));
358 // Update ID-dependent columns: URI, conversation
360 $orig = clone($notice);
365 $notice->uri = common_notice_uri($notice);
369 // If it's not part of a conversation, it's
370 // the beginning of a new conversation.
372 if (empty($notice->conversation)) {
373 $conv = Conversation::create();
374 $notice->conversation = $conv->id;
379 if (!$notice->update($orig)) {
380 common_log_db_error($notice, 'UPDATE', __FILE__);
381 // TRANS: Server exception thrown when a notice cannot be updated.
382 throw new ServerException(_('Problem saving notice.'));
388 # Clear the cache for subscribed users, so they'll update at next request
389 # XXX: someone clever could prepend instead of clearing the cache
391 $notice->blowOnInsert();
393 // Save per-notice metadata...
395 if (isset($replies)) {
396 $notice->saveKnownReplies($replies);
398 $notice->saveReplies();
402 $notice->saveKnownTags($tags);
407 // Note: groups may save tags, so must be run after tags are saved
408 // to avoid errors on duplicates.
409 if (isset($groups)) {
410 $notice->saveKnownGroups($groups);
412 $notice->saveGroups();
416 $notice->saveKnownUrls($urls);
421 // Prepare inbox delivery, may be queued to background.
422 $notice->distribute();
427 function blowOnInsert($conversation = false)
429 self::blow('profile:notice_ids:%d', $this->profile_id);
430 self::blow('public');
432 // XXX: Before we were blowing the casche only if the notice id
433 // was not the root of the conversation. What to do now?
435 self::blow('notice:conversation_ids:%d', $this->conversation);
437 if (!empty($this->repeat_of)) {
438 self::blow('notice:repeats:%d', $this->repeat_of);
441 $original = Notice::staticGet('id', $this->repeat_of);
443 if (!empty($original)) {
444 $originalUser = User::staticGet('id', $original->profile_id);
445 if (!empty($originalUser)) {
446 self::blow('user:repeats_of_me:%d', $originalUser->id);
450 $profile = Profile::staticGet($this->profile_id);
451 if (!empty($profile)) {
452 $profile->blowNoticeCount();
457 * Clear cache entries related to this notice at delete time.
458 * Necessary to avoid breaking paging on public, profile timelines.
460 function blowOnDelete()
462 $this->blowOnInsert();
464 self::blow('profile:notice_ids:%d;last', $this->profile_id);
465 self::blow('public;last');
468 /** save all urls in the notice to the db
470 * follow redirects and save all available file information
471 * (mimetype, date, size, oembed, etc.)
475 function saveUrls() {
476 common_replace_urls_callback($this->content, array($this, 'saveUrl'), $this->id);
480 * Save the given URLs as related links/attachments to the db
482 * follow redirects and save all available file information
483 * (mimetype, date, size, oembed, etc.)
487 function saveKnownUrls($urls)
489 // @fixme validation?
490 foreach (array_unique($urls) as $url) {
491 File::processNew($url, $this->id);
498 function saveUrl($data) {
499 list($url, $notice_id) = $data;
500 File::processNew($url, $notice_id);
503 static function checkDupes($profile_id, $content) {
504 $profile = Profile::staticGet($profile_id);
505 if (empty($profile)) {
508 $notice = $profile->getNotices(0, NOTICE_CACHE_WINDOW);
509 if (!empty($notice)) {
511 while ($notice->fetch()) {
512 if (time() - strtotime($notice->created) >= common_config('site', 'dupelimit')) {
514 } else if ($notice->content == $content) {
519 # If we get here, oldest item in cache window is not
520 # old enough for dupe limit; do direct check against DB
521 $notice = new Notice();
522 $notice->profile_id = $profile_id;
523 $notice->content = $content;
524 if (common_config('db','type') == 'pgsql')
525 $notice->whereAdd('extract(epoch from now() - created) < ' . common_config('site', 'dupelimit'));
527 $notice->whereAdd('now() - created < ' . common_config('site', 'dupelimit'));
529 $cnt = $notice->count();
533 static function checkEditThrottle($profile_id) {
534 $profile = Profile::staticGet($profile_id);
535 if (empty($profile)) {
539 $notice = $profile->getNotices(common_config('throttle', 'count') - 1, 1);
540 if ($notice && $notice->fetch()) {
541 # If the Nth notice was posted less than timespan seconds ago
542 if (time() - strtotime($notice->created) <= common_config('throttle', 'timespan')) {
547 # Either not N notices in the stream, OR the Nth was not posted within timespan seconds
551 function getUploadedAttachment() {
553 $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"';
554 $post->query($query);
556 if (empty($post->up) || empty($post->i)) {
559 $ret = array($post->up, $post->i);
565 function hasAttachments() {
567 $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);
568 $post->query($query);
570 $n_attachments = intval($post->n_attachments);
572 return $n_attachments;
575 function attachments() {
578 $f2p = new File_to_post;
579 $f2p->post_id = $this->id;
581 while ($f2p->fetch()) {
582 $f = File::staticGet($f2p->file_id);
589 function getStreamByIds($ids)
591 $cache = common_memcache();
593 if (!empty($cache)) {
595 foreach ($ids as $id) {
596 $n = Notice::staticGet('id', $id);
601 return new ArrayWrapper($notices);
603 $notice = new Notice();
605 //if no IDs requested, just return the notice object
608 $notice->whereAdd('id in (' . implode(', ', $ids) . ')');
614 while ($notice->fetch()) {
615 $temp[$notice->id] = clone($notice);
620 foreach ($ids as $id) {
621 if (array_key_exists($id, $temp)) {
622 $wrapped[] = $temp[$id];
626 return new ArrayWrapper($wrapped);
630 function publicStream($offset=0, $limit=20, $since_id=0, $max_id=0)
632 $ids = Notice::stream(array('Notice', '_publicStreamDirect'),
635 $offset, $limit, $since_id, $max_id);
636 return Notice::getStreamByIds($ids);
639 function _publicStreamDirect($offset=0, $limit=20, $since_id=0, $max_id=0)
641 $notice = new Notice();
643 $notice->selectAdd(); // clears it
644 $notice->selectAdd('id');
646 $notice->orderBy('id DESC');
648 if (!is_null($offset)) {
649 $notice->limit($offset, $limit);
652 if (common_config('public', 'localonly')) {
653 $notice->whereAdd('is_local = ' . Notice::LOCAL_PUBLIC);
655 # -1 == blacklisted, -2 == gateway (i.e. Twitter)
656 $notice->whereAdd('is_local !='. Notice::LOCAL_NONPUBLIC);
657 $notice->whereAdd('is_local !='. Notice::GATEWAY);
660 if ($since_id != 0) {
661 $notice->whereAdd('id > ' . $since_id);
665 $notice->whereAdd('id <= ' . $max_id);
670 if ($notice->find()) {
671 while ($notice->fetch()) {
672 $ids[] = $notice->id;
682 function conversationStream($id, $offset=0, $limit=20, $since_id=0, $max_id=0)
684 $ids = Notice::stream(array('Notice', '_conversationStreamDirect'),
686 'notice:conversation_ids:'.$id,
687 $offset, $limit, $since_id, $max_id);
689 return Notice::getStreamByIds($ids);
692 function _conversationStreamDirect($id, $offset=0, $limit=20, $since_id=0, $max_id=0)
694 $notice = new Notice();
696 $notice->selectAdd(); // clears it
697 $notice->selectAdd('id');
699 $notice->conversation = $id;
701 $notice->orderBy('id DESC');
703 if (!is_null($offset)) {
704 $notice->limit($offset, $limit);
707 if ($since_id != 0) {
708 $notice->whereAdd('id > ' . $since_id);
712 $notice->whereAdd('id <= ' . $max_id);
717 if ($notice->find()) {
718 while ($notice->fetch()) {
719 $ids[] = $notice->id;
730 * Is this notice part of an active conversation?
732 * @return boolean true if other messages exist in the same
733 * conversation, false if this is the only one
735 function hasConversation()
737 if (!empty($this->conversation)) {
738 $conversation = Notice::conversationStream(
743 if ($conversation->N > 0) {
751 * @param $groups array of Group *objects*
752 * @param $recipients array of profile *ids*
754 function whoGets($groups=null, $recipients=null)
756 $c = self::memcache();
759 $ni = $c->get(common_cache_key('notice:who_gets:'.$this->id));
765 if (is_null($groups)) {
766 $groups = $this->getGroups();
769 if (is_null($recipients)) {
770 $recipients = $this->getReplies();
773 $users = $this->getSubscribedUsers();
775 // FIXME: kind of ignoring 'transitional'...
776 // we'll probably stop supporting inboxless mode
781 foreach ($users as $id) {
782 $ni[$id] = NOTICE_INBOX_SOURCE_SUB;
785 $profile = $this->getProfile();
787 foreach ($groups as $group) {
788 $users = $group->getUserMembers();
789 foreach ($users as $id) {
790 if (!array_key_exists($id, $ni)) {
791 $user = User::staticGet('id', $id);
792 if (!$user->hasBlocked($profile)) {
793 $ni[$id] = NOTICE_INBOX_SOURCE_GROUP;
799 foreach ($recipients as $recipient) {
801 if (!array_key_exists($recipient, $ni)) {
802 $recipientUser = User::staticGet('id', $recipient);
803 if (!empty($recipientUser)) {
804 $ni[$recipient] = NOTICE_INBOX_SOURCE_REPLY;
810 // XXX: pack this data better
811 $c->set(common_cache_key('notice:who_gets:'.$this->id), $ni);
818 * Adds this notice to the inboxes of each local user who should receive
819 * it, based on author subscriptions, group memberships, and @-replies.
821 * Warning: running a second time currently will make items appear
822 * multiple times in users' inboxes.
824 * @fixme make more robust against errors
825 * @fixme break up massive deliveries to smaller background tasks
827 * @param array $groups optional list of Group objects;
828 * if left empty, will be loaded from group_inbox records
829 * @param array $recipient optional list of reply profile ids
830 * if left empty, will be loaded from reply records
832 function addToInboxes($groups=null, $recipients=null)
834 $ni = $this->whoGets($groups, $recipients);
836 $ids = array_keys($ni);
838 // We remove the author (if they're a local user),
839 // since we'll have already done this in distribute()
841 $i = array_search($this->profile_id, $ids);
849 Inbox::bulkInsert($this->id, $ids);
854 function getSubscribedUsers()
858 if(common_config('db','quote_identifiers'))
859 $user_table = '"user"';
860 else $user_table = 'user';
864 'FROM '. $user_table .' JOIN subscription '.
865 'ON '. $user_table .'.id = subscription.subscriber ' .
866 'WHERE subscription.subscribed = %d ';
868 $user->query(sprintf($qry, $this->profile_id));
872 while ($user->fetch()) {
882 * Record this notice to the given group inboxes for delivery.
883 * Overrides the regular parsing of !group markup.
885 * @param string $group_ids
886 * @fixme might prefer URIs as identifiers, as for replies?
887 * best with generalizations on user_group to support
888 * remote groups better.
890 function saveKnownGroups($group_ids)
892 if (!is_array($group_ids)) {
893 // TRANS: Server exception thrown when no array is provided to the method saveKnownGroups().
894 throw new ServerException(_("Bad type provided to saveKnownGroups"));
898 foreach (array_unique($group_ids) as $id) {
899 $group = User_group::staticGet('id', $id);
901 common_log(LOG_ERR, "Local delivery to group id $id, $group->nickname");
902 $result = $this->addToGroupInbox($group);
904 common_log_db_error($gi, 'INSERT', __FILE__);
907 // @fixme should we save the tags here or not?
908 $groups[] = clone($group);
910 common_log(LOG_ERR, "Local delivery to group id $id skipped, doesn't exist");
918 * Parse !group delivery and record targets into group_inbox.
919 * @return array of Group objects
921 function saveGroups()
923 // Don't save groups for repeats
925 if (!empty($this->repeat_of)) {
931 /* extract all !group */
932 $count = preg_match_all('/(?:^|\s)!([A-Za-z0-9]{1,64})/',
933 strtolower($this->content),
939 $profile = $this->getProfile();
941 /* Add them to the database */
943 foreach (array_unique($match[1]) as $nickname) {
944 /* XXX: remote groups. */
945 $group = User_group::getForNickname($nickname, $profile);
951 // we automatically add a tag for every group name, too
953 $tag = Notice_tag::pkeyGet(array('tag' => common_canonical_tag($nickname),
954 'notice_id' => $this->id));
957 $this->saveTag($nickname);
960 if ($profile->isMember($group)) {
962 $result = $this->addToGroupInbox($group);
965 common_log_db_error($gi, 'INSERT', __FILE__);
968 $groups[] = clone($group);
975 function addToGroupInbox($group)
977 $gi = Group_inbox::pkeyGet(array('group_id' => $group->id,
978 'notice_id' => $this->id));
982 $gi = new Group_inbox();
984 $gi->group_id = $group->id;
985 $gi->notice_id = $this->id;
986 $gi->created = $this->created;
988 $result = $gi->insert();
991 common_log_db_error($gi, 'INSERT', __FILE__);
992 // TRANS: Server exception thrown when an update for a group inbox fails.
993 throw new ServerException(_('Problem saving group inbox.'));
996 self::blow('user_group:notice_ids:%d', $gi->group_id);
1003 * Save reply records indicating that this notice needs to be
1004 * delivered to the local users with the given URIs.
1006 * Since this is expected to be used when saving foreign-sourced
1007 * messages, we won't deliver to any remote targets as that's the
1008 * source service's responsibility.
1010 * Mail notifications etc will be handled later.
1012 * @param array of unique identifier URIs for recipients
1014 function saveKnownReplies($uris)
1019 $sender = Profile::staticGet($this->profile_id);
1021 foreach (array_unique($uris) as $uri) {
1023 $user = User::staticGet('uri', $uri);
1025 if (!empty($user)) {
1026 if ($user->hasBlocked($sender)) {
1030 $reply = new Reply();
1032 $reply->notice_id = $this->id;
1033 $reply->profile_id = $user->id;
1034 common_log(LOG_INFO, __METHOD__ . ": saving reply: notice $this->id to profile $user->id");
1036 $id = $reply->insert();
1044 * Pull @-replies from this message's content in StatusNet markup format
1045 * and save reply records indicating that this message needs to be
1046 * delivered to those users.
1048 * Mail notifications to local profiles will be sent later.
1050 * @return array of integer profile IDs
1053 function saveReplies()
1055 // Don't save reply data for repeats
1057 if (!empty($this->repeat_of)) {
1061 $sender = Profile::staticGet($this->profile_id);
1063 // @todo ideally this parser information would only
1064 // be calculated once.
1066 $mentions = common_find_mentions($this->content, $this);
1070 // store replied only for first @ (what user/notice what the reply directed,
1071 // we assume first @ is it)
1073 foreach ($mentions as $mention) {
1075 foreach ($mention['mentioned'] as $mentioned) {
1077 // skip if they're already covered
1079 if (!empty($replied[$mentioned->id])) {
1083 // Don't save replies from blocked profile to local user
1085 $mentioned_user = User::staticGet('id', $mentioned->id);
1086 if (!empty($mentioned_user) && $mentioned_user->hasBlocked($sender)) {
1090 $reply = new Reply();
1092 $reply->notice_id = $this->id;
1093 $reply->profile_id = $mentioned->id;
1095 $id = $reply->insert();
1098 common_log_db_error($reply, 'INSERT', __FILE__);
1099 // TRANS: Server exception thrown when a reply cannot be saved.
1100 // TRANS: %1$d is a notice ID, %2$d is the ID of the mentioned user.
1101 throw new ServerException(sprintf(_("Could not save reply for %1$d, %2$d."), $this->id, $mentioned->id));
1103 $replied[$mentioned->id] = 1;
1104 self::blow('reply:stream:%d', $mentioned->id);
1109 $recipientIds = array_keys($replied);
1111 return $recipientIds;
1115 * Pull the complete list of @-reply targets for this notice.
1117 * @return array of integer profile ids
1119 function getReplies()
1125 $reply = new Reply();
1126 $reply->selectAdd();
1127 $reply->selectAdd('profile_id');
1128 $reply->notice_id = $this->id;
1130 if ($reply->find()) {
1131 while($reply->fetch()) {
1132 $ids[] = $reply->profile_id;
1142 * Send e-mail notifications to local @-reply targets.
1144 * Replies must already have been saved; this is expected to be run
1145 * from the distrib queue handler.
1147 function sendReplyNotifications()
1149 // Don't send reply notifications for repeats
1151 if (!empty($this->repeat_of)) {
1155 $recipientIds = $this->getReplies();
1157 foreach ($recipientIds as $recipientId) {
1158 $user = User::staticGet('id', $recipientId);
1159 if (!empty($user)) {
1160 mail_notify_attn($user, $this);
1166 * Pull list of groups this notice needs to be delivered to,
1167 * as previously recorded by saveGroups() or saveKnownGroups().
1169 * @return array of Group objects
1171 function getGroups()
1173 // Don't save groups for repeats
1175 if (!empty($this->repeat_of)) {
1183 $gi = new Group_inbox();
1186 $gi->selectAdd('group_id');
1188 $gi->notice_id = $this->id;
1191 while ($gi->fetch()) {
1192 $group = User_group::staticGet('id', $gi->group_id);
1204 // This has gotten way too long. Needs to be sliced up into functional bits
1205 // or ideally exported to a utility class.
1207 function asAtomEntry($namespace=false, $source=false, $author=true, $cur=null)
1209 $profile = $this->getProfile();
1211 $xs = new XMLStringer(true);
1214 $attrs = array('xmlns' => 'http://www.w3.org/2005/Atom',
1215 'xmlns:thr' => 'http://purl.org/syndication/thread/1.0',
1216 'xmlns:georss' => 'http://www.georss.org/georss',
1217 'xmlns:activity' => 'http://activitystrea.ms/spec/1.0/',
1218 'xmlns:media' => 'http://purl.org/syndication/atommedia',
1219 'xmlns:poco' => 'http://portablecontacts.net/spec/1.0',
1220 'xmlns:ostatus' => 'http://ostatus.org/schema/1.0',
1221 'xmlns:statusnet' => 'http://status.net/schema/api/1/');
1226 if (Event::handle('StartActivityStart', array(&$this, &$xs, &$attrs))) {
1227 $xs->elementStart('entry', $attrs);
1228 Event::handle('EndActivityStart', array(&$this, &$xs, &$attrs));
1231 if (Event::handle('StartActivitySource', array(&$this, &$xs))) {
1235 $atom_feed = $profile->getAtomFeed();
1237 if (!empty($atom_feed)) {
1239 $xs->elementStart('source');
1241 // XXX: we should store the actual feed ID
1243 $xs->element('id', null, $atom_feed);
1245 // XXX: we should store the actual feed title
1247 $xs->element('title', null, $profile->getBestName());
1249 $xs->element('link', array('rel' => 'alternate',
1250 'type' => 'text/html',
1251 'href' => $profile->profileurl));
1253 $xs->element('link', array('rel' => 'self',
1254 'type' => 'application/atom+xml',
1255 'href' => $atom_feed));
1257 $xs->element('icon', null, $profile->avatarUrl(AVATAR_PROFILE_SIZE));
1259 $notice = $profile->getCurrentNotice();
1261 if (!empty($notice)) {
1262 $xs->element('updated', null, self::utcDate($notice->created));
1265 $user = User::staticGet('id', $profile->id);
1267 if (!empty($user)) {
1268 $xs->element('link', array('rel' => 'license',
1269 'href' => common_config('license', 'url')));
1272 $xs->elementEnd('source');
1275 Event::handle('EndActivitySource', array(&$this, &$xs));
1278 $title = common_xml_safe_str($this->content);
1280 if (Event::handle('StartActivityTitle', array(&$this, &$xs, &$title))) {
1281 $xs->element('title', null, $title);
1282 Event::handle('EndActivityTitle', array($this, &$xs, $title));
1288 $atomAuthor = $profile->asAtomAuthor($cur);
1291 if (Event::handle('StartActivityAuthor', array(&$this, &$xs, &$atomAuthor))) {
1292 if (!empty($atomAuthor)) {
1293 $xs->raw($atomAuthor);
1294 Event::handle('EndActivityAuthor', array(&$this, &$xs, &$atomAuthor));
1301 $actor = $profile->asActivityActor();
1304 if (Event::handle('StartActivityActor', array(&$this, &$xs, &$actor))) {
1305 if (!empty($actor)) {
1307 Event::handle('EndActivityActor', array(&$this, &$xs, &$actor));
1311 $url = $this->bestUrl();
1313 if (Event::handle('StartActivityLink', array(&$this, &$xs, &$url))) {
1314 $xs->element('link', array('rel' => 'alternate',
1315 'type' => 'text/html',
1317 Event::handle('EndActivityLink', array(&$this, &$xs, $url));
1322 if (Event::handle('StartActivityId', array(&$this, &$xs, &$id))) {
1323 $xs->element('id', null, $id);
1324 Event::handle('EndActivityId', array(&$this, &$xs, $id));
1327 $published = self::utcDate($this->created);
1329 if (Event::handle('StartActivityPublished', array(&$this, &$xs, &$published))) {
1330 $xs->element('published', null, $published);
1331 Event::handle('EndActivityPublished', array(&$this, &$xs, $published));
1334 $updated = $published; // XXX: notices are usually immutable
1336 if (Event::handle('StartActivityUpdated', array(&$this, &$xs, &$updated))) {
1337 $xs->element('updated', null, $updated);
1338 Event::handle('EndActivityUpdated', array(&$this, &$xs, $updated));
1341 $content = common_xml_safe_str($this->rendered);
1343 if (Event::handle('StartActivityContent', array(&$this, &$xs, &$content))) {
1344 $xs->element('content', array('type' => 'html'), $content);
1345 Event::handle('EndActivityContent', array(&$this, &$xs, $content));
1348 // Most of our notices represent POSTing a NOTE. This is the default verb
1349 // for activity streams, so we normally just leave it out.
1351 $verb = ActivityVerb::POST;
1353 if (Event::handle('StartActivityVerb', array(&$this, &$xs, &$verb))) {
1354 $xs->element('activity:verb', null, $verb);
1355 Event::handle('EndActivityVerb', array(&$this, &$xs, $verb));
1358 // We use the default behavior for activity streams: if there's no activity:object,
1359 // then treat the entry itself as the object. Here, you can set the type of that object,
1360 // which is normally a NOTE.
1362 $type = ActivityObject::NOTE;
1364 if (Event::handle('StartActivityDefaultObjectType', array(&$this, &$xs, &$type))) {
1365 $xs->element('activity:object-type', null, $type);
1366 Event::handle('EndActivityDefaultObjectType', array(&$this, &$xs, $type));
1369 // Since we usually use the entry itself as an object, we don't have an explicit
1370 // object. Some extensions may want to add them (for photo, event, music, etc.).
1374 if (Event::handle('StartActivityObjects', array(&$this, &$xs, &$objects))) {
1375 foreach ($objects as $object) {
1376 $xs->raw($object->asString());
1378 Event::handle('EndActivityObjects', array(&$this, &$xs, $objects));
1381 $noticeInfoAttr = array('local_id' => $this->id); // local notice ID (useful to clients for ordering)
1383 $ns = $this->getSource();
1386 $noticeInfoAttr['source'] = $ns->code;
1387 if (!empty($ns->url)) {
1388 $noticeInfoAttr['source_link'] = $ns->url;
1389 if (!empty($ns->name)) {
1390 $noticeInfoAttr['source'] = '<a href="'
1391 . htmlspecialchars($ns->url)
1392 . '" rel="nofollow">'
1393 . htmlspecialchars($ns->name)
1400 $noticeInfoAttr['favorite'] = ($cur->hasFave($this)) ? "true" : "false";
1401 $profile = $cur->getProfile();
1402 $noticeInfoAttr['repeated'] = ($profile->hasRepeated($this->id)) ? "true" : "false";
1405 if (!empty($this->repeat_of)) {
1406 $noticeInfoAttr['repeat_of'] = $this->repeat_of;
1409 if (Event::handle('StartActivityNoticeInfo', array(&$this, &$xs, &$noticeInfoAttr))) {
1410 $xs->element('statusnet:notice_info', $noticeInfoAttr, null);
1411 Event::handle('EndActivityNoticeInfo', array(&$this, &$xs, $noticeInfoAttr));
1414 $replyNotice = null;
1416 if ($this->reply_to) {
1417 $replyNotice = Notice::staticGet('id', $this->reply_to);
1420 if (Event::handle('StartActivityInReplyTo', array(&$this, &$xs, &$replyNotice))) {
1421 if (!empty($replyNotice)) {
1422 $xs->element('link', array('rel' => 'related',
1423 'href' => $replyNotice->bestUrl()));
1424 $xs->element('thr:in-reply-to',
1425 array('ref' => $replyNotice->uri,
1426 'href' => $replyNotice->bestUrl()));
1427 Event::handle('EndActivityInReplyTo', array(&$this, &$xs, $replyNotice));
1433 if (!empty($this->conversation)) {
1434 $conv = Conversation::staticGet('id', $this->conversation);
1437 if (Event::handle('StartActivityConversation', array(&$this, &$xs, &$conv))) {
1438 if (!empty($conv)) {
1439 $xs->element('link', array('rel' => 'ostatus:conversation',
1440 'href' => $conv->uri));
1442 Event::handle('EndActivityConversation', array(&$this, &$xs, $conv));
1445 $replyProfiles = array();
1447 $reply_ids = $this->getReplies();
1449 foreach ($reply_ids as $id) {
1450 $profile = Profile::staticGet('id', $id);
1451 if (!empty($profile)) {
1452 $replyProfiles[] = $profile;
1456 if (Event::handle('StartActivityAttentionProfiles', array(&$this, &$xs, &$replyProfiles))) {
1457 foreach ($replyProfiles as $profile) {
1458 $xs->element('link', array('rel' => 'ostatus:attention',
1459 'href' => $profile->getUri()));
1460 $xs->element('link', array('rel' => 'mentioned',
1461 'href' => $profile->getUri()));
1463 Event::handle('EndActivityAttentionProfiles', array(&$this, &$xs, $replyProfiles));
1466 $groups = $this->getGroups();
1468 if (Event::handle('StartActivityAttentionGroups', array(&$this, &$xs, &$groups))) {
1469 foreach ($groups as $group) {
1470 $xs->element('link', array('rel' => 'ostatus:attention',
1471 'href' => $group->permalink()));
1472 $xs->element('link', array('rel' => 'mentioned',
1473 'href' => $group->permalink()));
1475 Event::handle('EndActivityAttentionGroups', array(&$this, &$xs, $groups));
1480 if (!empty($this->repeat_of)) {
1481 $repeat = Notice::staticGet('id', $this->repeat_of);
1484 if (Event::handle('StartActivityForward', array(&$this, &$xs, &$repeat))) {
1485 if (!empty($repeat)) {
1486 $xs->element('ostatus:forward',
1487 array('ref' => $repeat->uri,
1488 'href' => $repeat->bestUrl()));
1491 Event::handle('EndActivityForward', array(&$this, &$xs, $repeat));
1494 $tags = $this->getTags();
1496 if (Event::handle('StartActivityCategories', array(&$this, &$xs, &$tags))) {
1497 foreach ($tags as $tag) {
1498 $xs->element('category', array('term' => $tag));
1500 Event::handle('EndActivityCategories', array(&$this, &$xs, $tags));
1505 $enclosures = array();
1507 $attachments = $this->attachments();
1509 foreach ($attachments as $attachment) {
1510 $enclosure = $attachment->getEnclosure();
1512 $enclosures[] = $enclosure;
1516 if (Event::handle('StartActivityEnclosures', array(&$this, &$xs, &$enclosures))) {
1517 foreach ($enclosures as $enclosure) {
1518 $attributes = array('rel' => 'enclosure',
1519 'href' => $enclosure->url,
1520 'type' => $enclosure->mimetype,
1521 'length' => $enclosure->size);
1523 if ($enclosure->title) {
1524 $attributes['title'] = $enclosure->title;
1527 $xs->element('link', $attributes, null);
1529 Event::handle('EndActivityEnclosures', array(&$this, &$xs, $enclosures));
1535 if (Event::handle('StartActivityGeo', array(&$this, &$xs, &$lat, &$lon))) {
1536 if (!empty($lat) && !empty($lon)) {
1537 $xs->element('georss:point', null, $lat . ' ' . $lon);
1539 Event::handle('EndActivityGeo', array(&$this, &$xs, $lat, $lon));
1542 if (Event::handle('StartActivityEnd', array(&$this, &$xs))) {
1543 $xs->elementEnd('entry');
1544 Event::handle('EndActivityEnd', array(&$this, &$xs));
1547 return $xs->getString();
1551 * Returns an XML string fragment with a reference to a notice as an
1552 * Activity Streams noun object with the given element type.
1554 * Assumes that 'activity' namespace has been previously defined.
1556 * @param string $element one of 'subject', 'object', 'target'
1559 function asActivityNoun($element)
1561 $noun = ActivityObject::fromNotice($this);
1562 return $noun->asString('activity:' . $element);
1567 if (!empty($this->url)) {
1569 } else if (!empty($this->uri) && preg_match('/^https?:/', $this->uri)) {
1572 return common_local_url('shownotice',
1573 array('notice' => $this->id));
1577 function stream($fn, $args, $cachekey, $offset=0, $limit=20, $since_id=0, $max_id=0)
1579 $cache = common_memcache();
1581 if (empty($cache) ||
1582 $since_id != 0 || $max_id != 0 ||
1584 ($offset + $limit) > NOTICE_CACHE_WINDOW) {
1585 return call_user_func_array($fn, array_merge($args, array($offset, $limit, $since_id,
1589 $idkey = common_cache_key($cachekey);
1591 $idstr = $cache->get($idkey);
1593 if ($idstr !== false) {
1594 // Cache hit! Woohoo!
1595 $window = explode(',', $idstr);
1596 $ids = array_slice($window, $offset, $limit);
1600 $laststr = $cache->get($idkey.';last');
1602 if ($laststr !== false) {
1603 $window = explode(',', $laststr);
1604 $last_id = $window[0];
1605 $new_ids = call_user_func_array($fn, array_merge($args, array(0, NOTICE_CACHE_WINDOW,
1606 $last_id, 0, null)));
1608 $new_window = array_merge($new_ids, $window);
1610 $new_windowstr = implode(',', $new_window);
1612 $result = $cache->set($idkey, $new_windowstr);
1613 $result = $cache->set($idkey . ';last', $new_windowstr);
1615 $ids = array_slice($new_window, $offset, $limit);
1620 $window = call_user_func_array($fn, array_merge($args, array(0, NOTICE_CACHE_WINDOW,
1623 $windowstr = implode(',', $window);
1625 $result = $cache->set($idkey, $windowstr);
1626 $result = $cache->set($idkey . ';last', $windowstr);
1628 $ids = array_slice($window, $offset, $limit);
1634 * Determine which notice, if any, a new notice is in reply to.
1636 * For conversation tracking, we try to see where this notice fits
1637 * in the tree. Rough algorithm is:
1639 * if (reply_to is set and valid) {
1641 * } else if ((source not API or Web) and (content starts with "T NAME" or "@name ")) {
1642 * return ID of last notice by initial @name in content;
1645 * Note that all @nickname instances will still be used to save "reply" records,
1646 * so the notice shows up in the mentioned users' "replies" tab.
1648 * @param integer $reply_to ID passed in by Web or API
1649 * @param integer $profile_id ID of author
1650 * @param string $source Source tag, like 'web' or 'gwibber'
1651 * @param string $content Final notice content
1653 * @return integer ID of replied-to notice, or null for not a reply.
1656 static function getReplyTo($reply_to, $profile_id, $source, $content)
1658 static $lb = array('xmpp', 'mail', 'sms', 'omb');
1660 // If $reply_to is specified, we check that it exists, and then
1661 // return it if it does
1663 if (!empty($reply_to)) {
1664 $reply_notice = Notice::staticGet('id', $reply_to);
1665 if (!empty($reply_notice)) {
1670 // If it's not a "low bandwidth" source (one where you can't set
1671 // a reply_to argument), we return. This is mostly web and API
1674 if (!in_array($source, $lb)) {
1678 // Is there an initial @ or T?
1680 if (preg_match('/^T ([A-Z0-9]{1,64}) /', $content, $match) ||
1681 preg_match('/^@([a-z0-9]{1,64})\s+/', $content, $match)) {
1682 $nickname = common_canonical_nickname($match[1]);
1687 // Figure out who that is.
1689 $sender = Profile::staticGet('id', $profile_id);
1690 if (empty($sender)) {
1694 $recipient = common_relative_profile($sender, $nickname, common_sql_now());
1696 if (empty($recipient)) {
1700 // Get their last notice
1702 $last = $recipient->getCurrentNotice();
1704 if (!empty($last)) {
1709 static function maxContent()
1711 $contentlimit = common_config('notice', 'contentlimit');
1712 // null => use global limit (distinct from 0!)
1713 if (is_null($contentlimit)) {
1714 $contentlimit = common_config('site', 'textlimit');
1716 return $contentlimit;
1719 static function contentTooLong($content)
1721 $contentlimit = self::maxContent();
1722 return ($contentlimit > 0 && !empty($content) && (mb_strlen($content) > $contentlimit));
1725 function getLocation()
1729 if (!empty($this->location_id) && !empty($this->location_ns)) {
1730 $location = Location::fromId($this->location_id, $this->location_ns);
1733 if (is_null($location)) { // no ID, or Location::fromId() failed
1734 if (!empty($this->lat) && !empty($this->lon)) {
1735 $location = Location::fromLatLon($this->lat, $this->lon);
1742 function repeat($repeater_id, $source)
1744 $author = Profile::staticGet('id', $this->profile_id);
1746 // TRANS: Message used to repeat a notice. RT is the abbreviation of 'retweet'.
1747 // TRANS: %1$s is the repeated user's name, %2$s is the repeated notice.
1748 $content = sprintf(_('RT @%1$s %2$s'),
1752 $maxlen = common_config('site', 'textlimit');
1753 if ($maxlen > 0 && mb_strlen($content) > $maxlen) {
1754 // Web interface and current Twitter API clients will
1755 // pull the original notice's text, but some older
1756 // clients and RSS/Atom feeds will see this trimmed text.
1758 // Unfortunately this is likely to lose tags or URLs
1759 // at the end of long notices.
1760 $content = mb_substr($content, 0, $maxlen - 4) . ' ...';
1763 return self::saveNew($repeater_id, $content, $source,
1764 array('repeat_of' => $this->id));
1767 // These are supposed to be in chron order!
1769 function repeatStream($limit=100)
1771 $cache = common_memcache();
1773 if (empty($cache)) {
1774 $ids = $this->_repeatStreamDirect($limit);
1776 $idstr = $cache->get(common_cache_key('notice:repeats:'.$this->id));
1777 if ($idstr !== false) {
1778 $ids = explode(',', $idstr);
1780 $ids = $this->_repeatStreamDirect(100);
1781 $cache->set(common_cache_key('notice:repeats:'.$this->id), implode(',', $ids));
1784 // We do a max of 100, so slice down to limit
1785 $ids = array_slice($ids, 0, $limit);
1789 return Notice::getStreamByIds($ids);
1792 function _repeatStreamDirect($limit)
1794 $notice = new Notice();
1796 $notice->selectAdd(); // clears it
1797 $notice->selectAdd('id');
1799 $notice->repeat_of = $this->id;
1801 $notice->orderBy('created'); // NB: asc!
1803 if (!is_null($offset)) {
1804 $notice->limit($offset, $limit);
1809 if ($notice->find()) {
1810 while ($notice->fetch()) {
1811 $ids[] = $notice->id;
1821 function locationOptions($lat, $lon, $location_id, $location_ns, $profile = null)
1825 if (!empty($location_id) && !empty($location_ns)) {
1827 $options['location_id'] = $location_id;
1828 $options['location_ns'] = $location_ns;
1830 $location = Location::fromId($location_id, $location_ns);
1832 if (!empty($location)) {
1833 $options['lat'] = $location->lat;
1834 $options['lon'] = $location->lon;
1837 } else if (!empty($lat) && !empty($lon)) {
1839 $options['lat'] = $lat;
1840 $options['lon'] = $lon;
1842 $location = Location::fromLatLon($lat, $lon);
1844 if (!empty($location)) {
1845 $options['location_id'] = $location->location_id;
1846 $options['location_ns'] = $location->location_ns;
1848 } else if (!empty($profile)) {
1850 if (isset($profile->lat) && isset($profile->lon)) {
1851 $options['lat'] = $profile->lat;
1852 $options['lon'] = $profile->lon;
1855 if (isset($profile->location_id) && isset($profile->location_ns)) {
1856 $options['location_id'] = $profile->location_id;
1857 $options['location_ns'] = $profile->location_ns;
1864 function clearReplies()
1866 $replyNotice = new Notice();
1867 $replyNotice->reply_to = $this->id;
1869 //Null any notices that are replies to this notice
1871 if ($replyNotice->find()) {
1872 while ($replyNotice->fetch()) {
1873 $orig = clone($replyNotice);
1874 $replyNotice->reply_to = null;
1875 $replyNotice->update($orig);
1881 $reply = new Reply();
1882 $reply->notice_id = $this->id;
1884 if ($reply->find()) {
1885 while($reply->fetch()) {
1886 self::blow('reply:stream:%d', $reply->profile_id);
1894 function clearRepeats()
1896 $repeatNotice = new Notice();
1897 $repeatNotice->repeat_of = $this->id;
1899 //Null any notices that are repeats of this notice
1901 if ($repeatNotice->find()) {
1902 while ($repeatNotice->fetch()) {
1903 $orig = clone($repeatNotice);
1904 $repeatNotice->repeat_of = null;
1905 $repeatNotice->update($orig);
1910 function clearFaves()
1913 $fave->notice_id = $this->id;
1915 if ($fave->find()) {
1916 while ($fave->fetch()) {
1917 self::blow('fave:ids_by_user_own:%d', $fave->user_id);
1918 self::blow('fave:ids_by_user_own:%d;last', $fave->user_id);
1919 self::blow('fave:ids_by_user:%d', $fave->user_id);
1920 self::blow('fave:ids_by_user:%d;last', $fave->user_id);
1928 function clearTags()
1930 $tag = new Notice_tag();
1931 $tag->notice_id = $this->id;
1934 while ($tag->fetch()) {
1935 self::blow('profile:notice_ids_tagged:%d:%s', $this->profile_id, common_keyize($tag->tag));
1936 self::blow('profile:notice_ids_tagged:%d:%s;last', $this->profile_id, common_keyize($tag->tag));
1937 self::blow('notice_tag:notice_ids:%s', common_keyize($tag->tag));
1938 self::blow('notice_tag:notice_ids:%s;last', common_keyize($tag->tag));
1946 function clearGroupInboxes()
1948 $gi = new Group_inbox();
1950 $gi->notice_id = $this->id;
1953 while ($gi->fetch()) {
1954 self::blow('user_group:notice_ids:%d', $gi->group_id);
1962 function distribute()
1964 // We always insert for the author so they don't
1967 $user = User::staticGet('id', $this->profile_id);
1968 if (!empty($user)) {
1969 Inbox::insertNotice($user->id, $this->id);
1972 if (common_config('queue', 'inboxes')) {
1973 // If there's a failure, we want to _force_
1974 // distribution at this point.
1976 $qm = QueueManager::get();
1977 $qm->enqueue($this, 'distrib');
1978 } catch (Exception $e) {
1979 // If the exception isn't transient, this
1980 // may throw more exceptions as DQH does
1981 // its own enqueueing. So, we ignore them!
1983 $handler = new DistribQueueHandler();
1984 $handler->handle($this);
1985 } catch (Exception $e) {
1986 common_log(LOG_ERR, "emergency redistribution resulted in " . $e->getMessage());
1988 // Re-throw so somebody smarter can handle it.
1992 $handler = new DistribQueueHandler();
1993 $handler->handle($this);
1999 $result = parent::insert();
2002 // Profile::hasRepeated() abuses pkeyGet(), so we
2003 // have to clear manually
2004 if (!empty($this->repeat_of)) {
2005 $c = self::memcache();
2007 $ck = self::multicacheKey('Notice',
2008 array('profile_id' => $this->profile_id,
2009 'repeat_of' => $this->repeat_of));
2019 * Get the source of the notice
2021 * @return Notice_source $ns A notice source object. 'code' is the only attribute
2022 * guaranteed to be populated.
2024 function getSource()
2026 $ns = new Notice_source();
2027 if (!empty($this->source)) {
2028 switch ($this->source) {
2035 $ns->code = $this->source;
2038 $ns = Notice_source::staticGet($this->source);
2040 $ns = new Notice_source();
2041 $ns->code = $this->source;
2042 $app = Oauth_application::staticGet('name', $this->source);
2044 $ns->name = $app->name;
2045 $ns->url = $app->source_url;
2055 * Determine whether the notice was locally created
2057 * @return boolean locality
2060 public function isLocal()
2062 return ($this->is_local == Notice::LOCAL_PUBLIC ||
2063 $this->is_local == Notice::LOCAL_NONPUBLIC);
2066 public function getTags()
2069 $tag = new Notice_tag();
2070 $tag->notice_id = $this->id;
2072 while ($tag->fetch()) {
2073 $tags[] = $tag->tag;
2080 static private function utcDate($dt)
2082 $dateStr = date('d F Y H:i:s', strtotime($dt));
2083 $d = new DateTime($dateStr, new DateTimeZone('UTC'));
2084 return $d->format(DATE_W3C);