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;
250 if (!isset($is_local)) {
251 $is_local = Notice::LOCAL_PUBLIC;
254 $profile = Profile::staticGet($profile_id);
256 $final = common_shorten_links($content);
258 if (Notice::contentTooLong($final)) {
259 // TRANS: Client exception thrown if a notice contains too many characters.
260 throw new ClientException(_('Problem saving notice. Too long.'));
263 if (empty($profile)) {
264 // TRANS: Client exception thrown when trying to save a notice for an unknown user.
265 throw new ClientException(_('Problem saving notice. Unknown user.'));
268 if (common_config('throttle', 'enabled') && !Notice::checkEditThrottle($profile_id)) {
269 common_log(LOG_WARNING, 'Excessive posting by profile #' . $profile_id . '; throttled.');
270 // TRANS: Client exception thrown when a user tries to post too many notices in a given time frame.
271 throw new ClientException(_('Too many notices too fast; take a breather '.
272 'and post again in a few minutes.'));
275 if (common_config('site', 'dupelimit') > 0 && !Notice::checkDupes($profile_id, $final)) {
276 common_log(LOG_WARNING, 'Dupe posting by profile #' . $profile_id . '; throttled.');
277 // TRANS: Client exception thrown when a user tries to post too many duplicate notices in a given time frame.
278 throw new ClientException(_('Too many duplicate messages too quickly;'.
279 ' take a breather and post again in a few minutes.'));
282 if (!$profile->hasRight(Right::NEWNOTICE)) {
283 common_log(LOG_WARNING, "Attempted post from user disallowed to post: " . $profile->nickname);
285 // TRANS: Client exception thrown when a user tries to post while being banned.
286 throw new ClientException(_('You are banned from posting notices on this site.'), 403);
289 $notice = new Notice();
290 $notice->profile_id = $profile_id;
292 $autosource = common_config('public', 'autosource');
294 # Sandboxed are non-false, but not 1, either
296 if (!$profile->hasRight(Right::PUBLICNOTICE) ||
297 ($source && $autosource && in_array($source, $autosource))) {
298 $notice->is_local = Notice::LOCAL_NONPUBLIC;
300 $notice->is_local = $is_local;
303 if (!empty($created)) {
304 $notice->created = $created;
306 $notice->created = common_sql_now();
309 $notice->content = $final;
311 $notice->source = $source;
315 // Handle repeat case
317 if (isset($repeat_of)) {
318 $notice->repeat_of = $repeat_of;
320 $notice->reply_to = self::getReplyTo($reply_to, $profile_id, $source, $final);
323 if (!empty($notice->reply_to)) {
324 $reply = Notice::staticGet('id', $notice->reply_to);
325 $notice->conversation = $reply->conversation;
328 if (!empty($lat) && !empty($lon)) {
333 if (!empty($location_ns) && !empty($location_id)) {
334 $notice->location_id = $location_id;
335 $notice->location_ns = $location_ns;
338 if (!empty($rendered)) {
339 $notice->rendered = $rendered;
341 $notice->rendered = common_render_content($final, $notice);
344 if (Event::handle('StartNoticeSave', array(&$notice))) {
346 // XXX: some of these functions write to the DB
348 $id = $notice->insert();
351 common_log_db_error($notice, 'INSERT', __FILE__);
352 // TRANS: Server exception thrown when a notice cannot be saved.
353 throw new ServerException(_('Problem saving notice.'));
356 // Update ID-dependent columns: URI, conversation
358 $orig = clone($notice);
363 $notice->uri = common_notice_uri($notice);
367 // If it's not part of a conversation, it's
368 // the beginning of a new conversation.
370 if (empty($notice->conversation)) {
371 $conv = Conversation::create();
372 $notice->conversation = $conv->id;
377 if (!$notice->update($orig)) {
378 common_log_db_error($notice, 'UPDATE', __FILE__);
379 // TRANS: Server exception thrown when a notice cannot be updated.
380 throw new ServerException(_('Problem saving notice.'));
386 # Clear the cache for subscribed users, so they'll update at next request
387 # XXX: someone clever could prepend instead of clearing the cache
389 $notice->blowOnInsert();
391 // Save per-notice metadata...
393 if (isset($replies)) {
394 $notice->saveKnownReplies($replies);
396 $notice->saveReplies();
400 $notice->saveKnownTags($tags);
405 // Note: groups may save tags, so must be run after tags are saved
406 // to avoid errors on duplicates.
407 if (isset($groups)) {
408 $notice->saveKnownGroups($groups);
410 $notice->saveGroups();
414 $notice->saveKnownUrls($urls);
419 // Prepare inbox delivery, may be queued to background.
420 $notice->distribute();
425 function blowOnInsert($conversation = false)
427 self::blow('profile:notice_ids:%d', $this->profile_id);
428 self::blow('public');
430 // XXX: Before we were blowing the casche only if the notice id
431 // was not the root of the conversation. What to do now?
433 self::blow('notice:conversation_ids:%d', $this->conversation);
435 if (!empty($this->repeat_of)) {
436 self::blow('notice:repeats:%d', $this->repeat_of);
439 $original = Notice::staticGet('id', $this->repeat_of);
441 if (!empty($original)) {
442 $originalUser = User::staticGet('id', $original->profile_id);
443 if (!empty($originalUser)) {
444 self::blow('user:repeats_of_me:%d', $originalUser->id);
448 $profile = Profile::staticGet($this->profile_id);
449 if (!empty($profile)) {
450 $profile->blowNoticeCount();
455 * Clear cache entries related to this notice at delete time.
456 * Necessary to avoid breaking paging on public, profile timelines.
458 function blowOnDelete()
460 $this->blowOnInsert();
462 self::blow('profile:notice_ids:%d;last', $this->profile_id);
463 self::blow('public;last');
466 /** save all urls in the notice to the db
468 * follow redirects and save all available file information
469 * (mimetype, date, size, oembed, etc.)
473 function saveUrls() {
474 common_replace_urls_callback($this->content, array($this, 'saveUrl'), $this->id);
478 * Save the given URLs as related links/attachments to the db
480 * follow redirects and save all available file information
481 * (mimetype, date, size, oembed, etc.)
485 function saveKnownUrls($urls)
487 // @fixme validation?
488 foreach (array_unique($urls) as $url) {
489 File::processNew($url, $this->id);
496 function saveUrl($data) {
497 list($url, $notice_id) = $data;
498 File::processNew($url, $notice_id);
501 static function checkDupes($profile_id, $content) {
502 $profile = Profile::staticGet($profile_id);
503 if (empty($profile)) {
506 $notice = $profile->getNotices(0, NOTICE_CACHE_WINDOW);
507 if (!empty($notice)) {
509 while ($notice->fetch()) {
510 if (time() - strtotime($notice->created) >= common_config('site', 'dupelimit')) {
512 } else if ($notice->content == $content) {
517 # If we get here, oldest item in cache window is not
518 # old enough for dupe limit; do direct check against DB
519 $notice = new Notice();
520 $notice->profile_id = $profile_id;
521 $notice->content = $content;
522 if (common_config('db','type') == 'pgsql')
523 $notice->whereAdd('extract(epoch from now() - created) < ' . common_config('site', 'dupelimit'));
525 $notice->whereAdd('now() - created < ' . common_config('site', 'dupelimit'));
527 $cnt = $notice->count();
531 static function checkEditThrottle($profile_id) {
532 $profile = Profile::staticGet($profile_id);
533 if (empty($profile)) {
537 $notice = $profile->getNotices(common_config('throttle', 'count') - 1, 1);
538 if ($notice && $notice->fetch()) {
539 # If the Nth notice was posted less than timespan seconds ago
540 if (time() - strtotime($notice->created) <= common_config('throttle', 'timespan')) {
545 # Either not N notices in the stream, OR the Nth was not posted within timespan seconds
549 function getUploadedAttachment() {
551 $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"';
552 $post->query($query);
554 if (empty($post->up) || empty($post->i)) {
557 $ret = array($post->up, $post->i);
563 function hasAttachments() {
565 $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);
566 $post->query($query);
568 $n_attachments = intval($post->n_attachments);
570 return $n_attachments;
573 function attachments() {
576 $f2p = new File_to_post;
577 $f2p->post_id = $this->id;
579 while ($f2p->fetch()) {
580 $f = File::staticGet($f2p->file_id);
587 function getStreamByIds($ids)
589 $cache = common_memcache();
591 if (!empty($cache)) {
593 foreach ($ids as $id) {
594 $n = Notice::staticGet('id', $id);
599 return new ArrayWrapper($notices);
601 $notice = new Notice();
603 //if no IDs requested, just return the notice object
606 $notice->whereAdd('id in (' . implode(', ', $ids) . ')');
612 while ($notice->fetch()) {
613 $temp[$notice->id] = clone($notice);
618 foreach ($ids as $id) {
619 if (array_key_exists($id, $temp)) {
620 $wrapped[] = $temp[$id];
624 return new ArrayWrapper($wrapped);
628 function publicStream($offset=0, $limit=20, $since_id=0, $max_id=0)
630 $ids = Notice::stream(array('Notice', '_publicStreamDirect'),
633 $offset, $limit, $since_id, $max_id);
634 return Notice::getStreamByIds($ids);
637 function _publicStreamDirect($offset=0, $limit=20, $since_id=0, $max_id=0)
639 $notice = new Notice();
641 $notice->selectAdd(); // clears it
642 $notice->selectAdd('id');
644 $notice->orderBy('id DESC');
646 if (!is_null($offset)) {
647 $notice->limit($offset, $limit);
650 if (common_config('public', 'localonly')) {
651 $notice->whereAdd('is_local = ' . Notice::LOCAL_PUBLIC);
653 # -1 == blacklisted, -2 == gateway (i.e. Twitter)
654 $notice->whereAdd('is_local !='. Notice::LOCAL_NONPUBLIC);
655 $notice->whereAdd('is_local !='. Notice::GATEWAY);
658 if ($since_id != 0) {
659 $notice->whereAdd('id > ' . $since_id);
663 $notice->whereAdd('id <= ' . $max_id);
668 if ($notice->find()) {
669 while ($notice->fetch()) {
670 $ids[] = $notice->id;
680 function conversationStream($id, $offset=0, $limit=20, $since_id=0, $max_id=0)
682 $ids = Notice::stream(array('Notice', '_conversationStreamDirect'),
684 'notice:conversation_ids:'.$id,
685 $offset, $limit, $since_id, $max_id);
687 return Notice::getStreamByIds($ids);
690 function _conversationStreamDirect($id, $offset=0, $limit=20, $since_id=0, $max_id=0)
692 $notice = new Notice();
694 $notice->selectAdd(); // clears it
695 $notice->selectAdd('id');
697 $notice->conversation = $id;
699 $notice->orderBy('id DESC');
701 if (!is_null($offset)) {
702 $notice->limit($offset, $limit);
705 if ($since_id != 0) {
706 $notice->whereAdd('id > ' . $since_id);
710 $notice->whereAdd('id <= ' . $max_id);
715 if ($notice->find()) {
716 while ($notice->fetch()) {
717 $ids[] = $notice->id;
728 * Is this notice part of an active conversation?
730 * @return boolean true if other messages exist in the same
731 * conversation, false if this is the only one
733 function hasConversation()
735 if (!empty($this->conversation)) {
736 $conversation = Notice::conversationStream(
741 if ($conversation->N > 0) {
749 * @param $groups array of Group *objects*
750 * @param $recipients array of profile *ids*
752 function whoGets($groups=null, $recipients=null)
754 $c = self::memcache();
757 $ni = $c->get(common_cache_key('notice:who_gets:'.$this->id));
763 if (is_null($groups)) {
764 $groups = $this->getGroups();
767 if (is_null($recipients)) {
768 $recipients = $this->getReplies();
771 $users = $this->getSubscribedUsers();
773 // FIXME: kind of ignoring 'transitional'...
774 // we'll probably stop supporting inboxless mode
779 foreach ($users as $id) {
780 $ni[$id] = NOTICE_INBOX_SOURCE_SUB;
783 $profile = $this->getProfile();
785 foreach ($groups as $group) {
786 $users = $group->getUserMembers();
787 foreach ($users as $id) {
788 if (!array_key_exists($id, $ni)) {
789 $user = User::staticGet('id', $id);
790 if (!$user->hasBlocked($profile)) {
791 $ni[$id] = NOTICE_INBOX_SOURCE_GROUP;
797 foreach ($recipients as $recipient) {
799 if (!array_key_exists($recipient, $ni)) {
800 $recipientUser = User::staticGet('id', $recipient);
801 if (!empty($recipientUser)) {
802 $ni[$recipient] = NOTICE_INBOX_SOURCE_REPLY;
808 // XXX: pack this data better
809 $c->set(common_cache_key('notice:who_gets:'.$this->id), $ni);
816 * Adds this notice to the inboxes of each local user who should receive
817 * it, based on author subscriptions, group memberships, and @-replies.
819 * Warning: running a second time currently will make items appear
820 * multiple times in users' inboxes.
822 * @fixme make more robust against errors
823 * @fixme break up massive deliveries to smaller background tasks
825 * @param array $groups optional list of Group objects;
826 * if left empty, will be loaded from group_inbox records
827 * @param array $recipient optional list of reply profile ids
828 * if left empty, will be loaded from reply records
830 function addToInboxes($groups=null, $recipients=null)
832 $ni = $this->whoGets($groups, $recipients);
834 $ids = array_keys($ni);
836 // We remove the author (if they're a local user),
837 // since we'll have already done this in distribute()
839 $i = array_search($this->profile_id, $ids);
847 Inbox::bulkInsert($this->id, $ids);
852 function getSubscribedUsers()
856 if(common_config('db','quote_identifiers'))
857 $user_table = '"user"';
858 else $user_table = 'user';
862 'FROM '. $user_table .' JOIN subscription '.
863 'ON '. $user_table .'.id = subscription.subscriber ' .
864 'WHERE subscription.subscribed = %d ';
866 $user->query(sprintf($qry, $this->profile_id));
870 while ($user->fetch()) {
880 * Record this notice to the given group inboxes for delivery.
881 * Overrides the regular parsing of !group markup.
883 * @param string $group_ids
884 * @fixme might prefer URIs as identifiers, as for replies?
885 * best with generalizations on user_group to support
886 * remote groups better.
888 function saveKnownGroups($group_ids)
890 if (!is_array($group_ids)) {
891 // TRANS: Server exception thrown when no array is provided to the method saveKnownGroups().
892 throw new ServerException(_("Bad type provided to saveKnownGroups"));
896 foreach (array_unique($group_ids) as $id) {
897 $group = User_group::staticGet('id', $id);
899 common_log(LOG_ERR, "Local delivery to group id $id, $group->nickname");
900 $result = $this->addToGroupInbox($group);
902 common_log_db_error($gi, 'INSERT', __FILE__);
905 // @fixme should we save the tags here or not?
906 $groups[] = clone($group);
908 common_log(LOG_ERR, "Local delivery to group id $id skipped, doesn't exist");
916 * Parse !group delivery and record targets into group_inbox.
917 * @return array of Group objects
919 function saveGroups()
921 // Don't save groups for repeats
923 if (!empty($this->repeat_of)) {
929 /* extract all !group */
930 $count = preg_match_all('/(?:^|\s)!([A-Za-z0-9]{1,64})/',
931 strtolower($this->content),
937 $profile = $this->getProfile();
939 /* Add them to the database */
941 foreach (array_unique($match[1]) as $nickname) {
942 /* XXX: remote groups. */
943 $group = User_group::getForNickname($nickname, $profile);
949 // we automatically add a tag for every group name, too
951 $tag = Notice_tag::pkeyGet(array('tag' => common_canonical_tag($nickname),
952 'notice_id' => $this->id));
955 $this->saveTag($nickname);
958 if ($profile->isMember($group)) {
960 $result = $this->addToGroupInbox($group);
963 common_log_db_error($gi, 'INSERT', __FILE__);
966 $groups[] = clone($group);
973 function addToGroupInbox($group)
975 $gi = Group_inbox::pkeyGet(array('group_id' => $group->id,
976 'notice_id' => $this->id));
980 $gi = new Group_inbox();
982 $gi->group_id = $group->id;
983 $gi->notice_id = $this->id;
984 $gi->created = $this->created;
986 $result = $gi->insert();
989 common_log_db_error($gi, 'INSERT', __FILE__);
990 // TRANS: Server exception thrown when an update for a group inbox fails.
991 throw new ServerException(_('Problem saving group inbox.'));
994 self::blow('user_group:notice_ids:%d', $gi->group_id);
1001 * Save reply records indicating that this notice needs to be
1002 * delivered to the local users with the given URIs.
1004 * Since this is expected to be used when saving foreign-sourced
1005 * messages, we won't deliver to any remote targets as that's the
1006 * source service's responsibility.
1008 * Mail notifications etc will be handled later.
1010 * @param array of unique identifier URIs for recipients
1012 function saveKnownReplies($uris)
1017 $sender = Profile::staticGet($this->profile_id);
1019 foreach (array_unique($uris) as $uri) {
1021 $user = User::staticGet('uri', $uri);
1023 if (!empty($user)) {
1024 if ($user->hasBlocked($sender)) {
1028 $reply = new Reply();
1030 $reply->notice_id = $this->id;
1031 $reply->profile_id = $user->id;
1032 common_log(LOG_INFO, __METHOD__ . ": saving reply: notice $this->id to profile $user->id");
1034 $id = $reply->insert();
1042 * Pull @-replies from this message's content in StatusNet markup format
1043 * and save reply records indicating that this message needs to be
1044 * delivered to those users.
1046 * Mail notifications to local profiles will be sent later.
1048 * @return array of integer profile IDs
1051 function saveReplies()
1053 // Don't save reply data for repeats
1055 if (!empty($this->repeat_of)) {
1059 $sender = Profile::staticGet($this->profile_id);
1061 // @todo ideally this parser information would only
1062 // be calculated once.
1064 $mentions = common_find_mentions($this->content, $this);
1068 // store replied only for first @ (what user/notice what the reply directed,
1069 // we assume first @ is it)
1071 foreach ($mentions as $mention) {
1073 foreach ($mention['mentioned'] as $mentioned) {
1075 // skip if they're already covered
1077 if (!empty($replied[$mentioned->id])) {
1081 // Don't save replies from blocked profile to local user
1083 $mentioned_user = User::staticGet('id', $mentioned->id);
1084 if (!empty($mentioned_user) && $mentioned_user->hasBlocked($sender)) {
1088 $reply = new Reply();
1090 $reply->notice_id = $this->id;
1091 $reply->profile_id = $mentioned->id;
1093 $id = $reply->insert();
1096 common_log_db_error($reply, 'INSERT', __FILE__);
1097 // TRANS: Server exception thrown when a reply cannot be saved.
1098 // TRANS: %1$d is a notice ID, %2$d is the ID of the mentioned user.
1099 throw new ServerException(sprintf(_("Could not save reply for %1$d, %2$d."), $this->id, $mentioned->id));
1101 $replied[$mentioned->id] = 1;
1102 self::blow('reply:stream:%d', $mentioned->id);
1107 $recipientIds = array_keys($replied);
1109 return $recipientIds;
1113 * Pull the complete list of @-reply targets for this notice.
1115 * @return array of integer profile ids
1117 function getReplies()
1123 $reply = new Reply();
1124 $reply->selectAdd();
1125 $reply->selectAdd('profile_id');
1126 $reply->notice_id = $this->id;
1128 if ($reply->find()) {
1129 while($reply->fetch()) {
1130 $ids[] = $reply->profile_id;
1140 * Send e-mail notifications to local @-reply targets.
1142 * Replies must already have been saved; this is expected to be run
1143 * from the distrib queue handler.
1145 function sendReplyNotifications()
1147 // Don't send reply notifications for repeats
1149 if (!empty($this->repeat_of)) {
1153 $recipientIds = $this->getReplies();
1155 foreach ($recipientIds as $recipientId) {
1156 $user = User::staticGet('id', $recipientId);
1157 if (!empty($user)) {
1158 mail_notify_attn($user, $this);
1164 * Pull list of groups this notice needs to be delivered to,
1165 * as previously recorded by saveGroups() or saveKnownGroups().
1167 * @return array of Group objects
1169 function getGroups()
1171 // Don't save groups for repeats
1173 if (!empty($this->repeat_of)) {
1181 $gi = new Group_inbox();
1184 $gi->selectAdd('group_id');
1186 $gi->notice_id = $this->id;
1189 while ($gi->fetch()) {
1190 $group = User_group::staticGet('id', $gi->group_id);
1202 // This has gotten way too long. Needs to be sliced up into functional bits
1203 // or ideally exported to a utility class.
1205 function asAtomEntry($namespace=false, $source=false, $author=true, $cur=null)
1207 $profile = $this->getProfile();
1209 $xs = new XMLStringer(true);
1212 $attrs = array('xmlns' => 'http://www.w3.org/2005/Atom',
1213 'xmlns:thr' => 'http://purl.org/syndication/thread/1.0',
1214 'xmlns:georss' => 'http://www.georss.org/georss',
1215 'xmlns:activity' => 'http://activitystrea.ms/spec/1.0/',
1216 'xmlns:media' => 'http://purl.org/syndication/atommedia',
1217 'xmlns:poco' => 'http://portablecontacts.net/spec/1.0',
1218 'xmlns:ostatus' => 'http://ostatus.org/schema/1.0',
1219 'xmlns:statusnet' => 'http://status.net/schema/api/1/');
1224 if (Event::handle('StartActivityStart', array(&$this, &$xs, &$attrs))) {
1225 $xs->elementStart('entry', $attrs);
1226 Event::handle('EndActivityStart', array(&$this, &$xs, &$attrs));
1229 if (Event::handle('StartActivitySource', array(&$this, &$xs))) {
1233 $atom_feed = $profile->getAtomFeed();
1235 if (!empty($atom_feed)) {
1237 $xs->elementStart('source');
1239 // XXX: we should store the actual feed ID
1241 $xs->element('id', null, $atom_feed);
1243 // XXX: we should store the actual feed title
1245 $xs->element('title', null, $profile->getBestName());
1247 $xs->element('link', array('rel' => 'alternate',
1248 'type' => 'text/html',
1249 'href' => $profile->profileurl));
1251 $xs->element('link', array('rel' => 'self',
1252 'type' => 'application/atom+xml',
1253 'href' => $atom_feed));
1255 $xs->element('icon', null, $profile->avatarUrl(AVATAR_PROFILE_SIZE));
1257 $notice = $profile->getCurrentNotice();
1259 if (!empty($notice)) {
1260 $xs->element('updated', null, self::utcDate($notice->created));
1263 $user = User::staticGet('id', $profile->id);
1265 if (!empty($user)) {
1266 $xs->element('link', array('rel' => 'license',
1267 'href' => common_config('license', 'url')));
1270 $xs->elementEnd('source');
1273 Event::handle('EndActivitySource', array(&$this, &$xs));
1276 $title = common_xml_safe_str($this->content);
1278 if (Event::handle('StartActivityTitle', array(&$this, &$xs, &$title))) {
1279 $xs->element('title', null, $title);
1280 Event::handle('EndActivityTitle', array($this, &$xs, $title));
1286 $atomAuthor = $profile->asAtomAuthor($cur);
1289 if (Event::handle('StartActivityAuthor', array(&$this, &$xs, &$atomAuthor))) {
1290 if (!empty($atomAuthor)) {
1291 $xs->raw($atomAuthor);
1292 Event::handle('EndActivityAuthor', array(&$this, &$xs, &$atomAuthor));
1299 $actor = $profile->asActivityActor();
1302 if (Event::handle('StartActivityActor', array(&$this, &$xs, &$actor))) {
1303 if (!empty($actor)) {
1305 Event::handle('EndActivityActor', array(&$this, &$xs, &$actor));
1309 $url = $this->bestUrl();
1311 if (Event::handle('StartActivityLink', array(&$this, &$xs, &$url))) {
1312 $xs->element('link', array('rel' => 'alternate',
1313 'type' => 'text/html',
1315 Event::handle('EndActivityLink', array(&$this, &$xs, $url));
1320 if (Event::handle('StartActivityId', array(&$this, &$xs, &$id))) {
1321 $xs->element('id', null, $id);
1322 Event::handle('EndActivityId', array(&$this, &$xs, $id));
1325 $published = self::utcDate($this->created);
1327 if (Event::handle('StartActivityPublished', array(&$this, &$xs, &$published))) {
1328 $xs->element('published', null, $published);
1329 Event::handle('EndActivityPublished', array(&$this, &$xs, $published));
1332 $updated = $published; // XXX: notices are usually immutable
1334 if (Event::handle('StartActivityUpdated', array(&$this, &$xs, &$updated))) {
1335 $xs->element('updated', null, $updated);
1336 Event::handle('EndActivityUpdated', array(&$this, &$xs, $updated));
1339 $content = common_xml_safe_str($this->rendered);
1341 if (Event::handle('StartActivityContent', array(&$this, &$xs, &$content))) {
1342 $xs->element('content', array('type' => 'html'), $content);
1343 Event::handle('EndActivityContent', array(&$this, &$xs, $content));
1346 // Most of our notices represent POSTing a NOTE. This is the default verb
1347 // for activity streams, so we normally just leave it out.
1349 $verb = ActivityVerb::POST;
1351 if (Event::handle('StartActivityVerb', array(&$this, &$xs, &$verb))) {
1352 $xs->element('activity:verb', null, $verb);
1353 Event::handle('EndActivityVerb', array(&$this, &$xs, $verb));
1356 // We use the default behavior for activity streams: if there's no activity:object,
1357 // then treat the entry itself as the object. Here, you can set the type of that object,
1358 // which is normally a NOTE.
1360 $type = ActivityObject::NOTE;
1362 if (Event::handle('StartActivityDefaultObjectType', array(&$this, &$xs, &$type))) {
1363 $xs->element('activity:object-type', null, $type);
1364 Event::handle('EndActivityDefaultObjectType', array(&$this, &$xs, $type));
1367 // Since we usually use the entry itself as an object, we don't have an explicit
1368 // object. Some extensions may want to add them (for photo, event, music, etc.).
1372 if (Event::handle('StartActivityObjects', array(&$this, &$xs, &$objects))) {
1373 foreach ($objects as $object) {
1374 $xs->raw($object->asString());
1376 Event::handle('EndActivityObjects', array(&$this, &$xs, $objects));
1379 $noticeInfoAttr = array('local_id' => $this->id); // local notice ID (useful to clients for ordering)
1381 $ns = $this->getSource();
1384 $noticeInfoAttr['source'] = $ns->code;
1385 if (!empty($ns->url)) {
1386 $noticeInfoAttr['source_link'] = $ns->url;
1387 if (!empty($ns->name)) {
1388 $noticeInfoAttr['source'] = '<a href="'
1389 . htmlspecialchars($ns->url)
1390 . '" rel="nofollow">'
1391 . htmlspecialchars($ns->name)
1398 $noticeInfoAttr['favorite'] = ($cur->hasFave($this)) ? "true" : "false";
1399 $profile = $cur->getProfile();
1400 $noticeInfoAttr['repeated'] = ($profile->hasRepeated($this->id)) ? "true" : "false";
1403 if (!empty($this->repeat_of)) {
1404 $noticeInfoAttr['repeat_of'] = $this->repeat_of;
1407 if (Event::handle('StartActivityNoticeInfo', array(&$this, &$xs, &$noticeInfoAttr))) {
1408 $xs->element('statusnet:notice_info', $noticeInfoAttr, null);
1409 Event::handle('EndActivityNoticeInfo', array(&$this, &$xs, $noticeInfoAttr));
1412 $replyNotice = null;
1414 if ($this->reply_to) {
1415 $replyNotice = Notice::staticGet('id', $this->reply_to);
1418 if (Event::handle('StartActivityInReplyTo', array(&$this, &$xs, &$replyNotice))) {
1419 if (!empty($replyNotice)) {
1420 $xs->element('link', array('rel' => 'related',
1421 'href' => $replyNotice->bestUrl()));
1422 $xs->element('thr:in-reply-to',
1423 array('ref' => $replyNotice->uri,
1424 'href' => $replyNotice->bestUrl()));
1425 Event::handle('EndActivityInReplyTo', array(&$this, &$xs, $replyNotice));
1431 if (!empty($this->conversation)) {
1432 $conv = Conversation::staticGet('id', $this->conversation);
1435 if (Event::handle('StartActivityConversation', array(&$this, &$xs, &$conv))) {
1436 if (!empty($conv)) {
1437 $xs->element('link', array('rel' => 'ostatus:conversation',
1438 'href' => $conv->uri));
1440 Event::handle('EndActivityConversation', array(&$this, &$xs, $conv));
1443 $replyProfiles = array();
1445 $reply_ids = $this->getReplies();
1447 foreach ($reply_ids as $id) {
1448 $profile = Profile::staticGet('id', $id);
1449 if (!empty($profile)) {
1450 $replyProfiles[] = $profile;
1454 if (Event::handle('StartActivityAttentionProfiles', array(&$this, &$xs, &$replyProfiles))) {
1455 foreach ($replyProfiles as $profile) {
1456 $xs->element('link', array('rel' => 'ostatus:attention',
1457 'href' => $profile->getUri()));
1458 $xs->element('link', array('rel' => 'mentioned',
1459 'href' => $profile->getUri()));
1461 Event::handle('EndActivityAttentionProfiles', array(&$this, &$xs, $replyProfiles));
1464 $groups = $this->getGroups();
1466 if (Event::handle('StartActivityAttentionGroups', array(&$this, &$xs, &$groups))) {
1467 foreach ($groups as $group) {
1468 $xs->element('link', array('rel' => 'ostatus:attention',
1469 'href' => $group->permalink()));
1470 $xs->element('link', array('rel' => 'mentioned',
1471 'href' => $group->permalink()));
1473 Event::handle('EndActivityAttentionGroups', array(&$this, &$xs, $groups));
1478 if (!empty($this->repeat_of)) {
1479 $repeat = Notice::staticGet('id', $this->repeat_of);
1482 if (Event::handle('StartActivityForward', array(&$this, &$xs, &$repeat))) {
1483 if (!empty($repeat)) {
1484 $xs->element('ostatus:forward',
1485 array('ref' => $repeat->uri,
1486 'href' => $repeat->bestUrl()));
1489 Event::handle('EndActivityForward', array(&$this, &$xs, $repeat));
1492 $tags = $this->getTags();
1494 if (Event::handle('StartActivityCategories', array(&$this, &$xs, &$tags))) {
1495 foreach ($tags as $tag) {
1496 $xs->element('category', array('term' => $tag));
1498 Event::handle('EndActivityCategories', array(&$this, &$xs, $tags));
1503 $enclosures = array();
1505 $attachments = $this->attachments();
1507 foreach ($attachments as $attachment) {
1508 $enclosure = $attachment->getEnclosure();
1510 $enclosures[] = $enclosure;
1514 if (Event::handle('StartActivityEnclosures', array(&$this, &$xs, &$enclosures))) {
1515 foreach ($enclosures as $enclosure) {
1516 $attributes = array('rel' => 'enclosure',
1517 'href' => $enclosure->url,
1518 'type' => $enclosure->mimetype,
1519 'length' => $enclosure->size);
1521 if ($enclosure->title) {
1522 $attributes['title'] = $enclosure->title;
1525 $xs->element('link', $attributes, null);
1527 Event::handle('EndActivityEnclosures', array(&$this, &$xs, $enclosures));
1533 if (Event::handle('StartActivityGeo', array(&$this, &$xs, &$lat, &$lon))) {
1534 if (!empty($lat) && !empty($lon)) {
1535 $xs->element('georss:point', null, $lat . ' ' . $lon);
1537 Event::handle('EndActivityGeo', array(&$this, &$xs, $lat, $lon));
1540 if (Event::handle('StartActivityEnd', array(&$this, &$xs))) {
1541 $xs->elementEnd('entry');
1542 Event::handle('EndActivityEnd', array(&$this, &$xs));
1545 return $xs->getString();
1549 * Returns an XML string fragment with a reference to a notice as an
1550 * Activity Streams noun object with the given element type.
1552 * Assumes that 'activity' namespace has been previously defined.
1554 * @param string $element one of 'subject', 'object', 'target'
1557 function asActivityNoun($element)
1559 $noun = ActivityObject::fromNotice($this);
1560 return $noun->asString('activity:' . $element);
1565 if (!empty($this->url)) {
1567 } else if (!empty($this->uri) && preg_match('/^https?:/', $this->uri)) {
1570 return common_local_url('shownotice',
1571 array('notice' => $this->id));
1575 function stream($fn, $args, $cachekey, $offset=0, $limit=20, $since_id=0, $max_id=0)
1577 $cache = common_memcache();
1579 if (empty($cache) ||
1580 $since_id != 0 || $max_id != 0 ||
1582 ($offset + $limit) > NOTICE_CACHE_WINDOW) {
1583 return call_user_func_array($fn, array_merge($args, array($offset, $limit, $since_id,
1587 $idkey = common_cache_key($cachekey);
1589 $idstr = $cache->get($idkey);
1591 if ($idstr !== false) {
1592 // Cache hit! Woohoo!
1593 $window = explode(',', $idstr);
1594 $ids = array_slice($window, $offset, $limit);
1598 $laststr = $cache->get($idkey.';last');
1600 if ($laststr !== false) {
1601 $window = explode(',', $laststr);
1602 $last_id = $window[0];
1603 $new_ids = call_user_func_array($fn, array_merge($args, array(0, NOTICE_CACHE_WINDOW,
1604 $last_id, 0, null)));
1606 $new_window = array_merge($new_ids, $window);
1608 $new_windowstr = implode(',', $new_window);
1610 $result = $cache->set($idkey, $new_windowstr);
1611 $result = $cache->set($idkey . ';last', $new_windowstr);
1613 $ids = array_slice($new_window, $offset, $limit);
1618 $window = call_user_func_array($fn, array_merge($args, array(0, NOTICE_CACHE_WINDOW,
1621 $windowstr = implode(',', $window);
1623 $result = $cache->set($idkey, $windowstr);
1624 $result = $cache->set($idkey . ';last', $windowstr);
1626 $ids = array_slice($window, $offset, $limit);
1632 * Determine which notice, if any, a new notice is in reply to.
1634 * For conversation tracking, we try to see where this notice fits
1635 * in the tree. Rough algorithm is:
1637 * if (reply_to is set and valid) {
1639 * } else if ((source not API or Web) and (content starts with "T NAME" or "@name ")) {
1640 * return ID of last notice by initial @name in content;
1643 * Note that all @nickname instances will still be used to save "reply" records,
1644 * so the notice shows up in the mentioned users' "replies" tab.
1646 * @param integer $reply_to ID passed in by Web or API
1647 * @param integer $profile_id ID of author
1648 * @param string $source Source tag, like 'web' or 'gwibber'
1649 * @param string $content Final notice content
1651 * @return integer ID of replied-to notice, or null for not a reply.
1654 static function getReplyTo($reply_to, $profile_id, $source, $content)
1656 static $lb = array('xmpp', 'mail', 'sms', 'omb');
1658 // If $reply_to is specified, we check that it exists, and then
1659 // return it if it does
1661 if (!empty($reply_to)) {
1662 $reply_notice = Notice::staticGet('id', $reply_to);
1663 if (!empty($reply_notice)) {
1668 // If it's not a "low bandwidth" source (one where you can't set
1669 // a reply_to argument), we return. This is mostly web and API
1672 if (!in_array($source, $lb)) {
1676 // Is there an initial @ or T?
1678 if (preg_match('/^T ([A-Z0-9]{1,64}) /', $content, $match) ||
1679 preg_match('/^@([a-z0-9]{1,64})\s+/', $content, $match)) {
1680 $nickname = common_canonical_nickname($match[1]);
1685 // Figure out who that is.
1687 $sender = Profile::staticGet('id', $profile_id);
1688 if (empty($sender)) {
1692 $recipient = common_relative_profile($sender, $nickname, common_sql_now());
1694 if (empty($recipient)) {
1698 // Get their last notice
1700 $last = $recipient->getCurrentNotice();
1702 if (!empty($last)) {
1707 static function maxContent()
1709 $contentlimit = common_config('notice', 'contentlimit');
1710 // null => use global limit (distinct from 0!)
1711 if (is_null($contentlimit)) {
1712 $contentlimit = common_config('site', 'textlimit');
1714 return $contentlimit;
1717 static function contentTooLong($content)
1719 $contentlimit = self::maxContent();
1720 return ($contentlimit > 0 && !empty($content) && (mb_strlen($content) > $contentlimit));
1723 function getLocation()
1727 if (!empty($this->location_id) && !empty($this->location_ns)) {
1728 $location = Location::fromId($this->location_id, $this->location_ns);
1731 if (is_null($location)) { // no ID, or Location::fromId() failed
1732 if (!empty($this->lat) && !empty($this->lon)) {
1733 $location = Location::fromLatLon($this->lat, $this->lon);
1740 function repeat($repeater_id, $source)
1742 $author = Profile::staticGet('id', $this->profile_id);
1744 // TRANS: Message used to repeat a notice. RT is the abbreviation of 'retweet'.
1745 // TRANS: %1$s is the repeated user's name, %2$s is the repeated notice.
1746 $content = sprintf(_('RT @%1$s %2$s'),
1750 $maxlen = common_config('site', 'textlimit');
1751 if ($maxlen > 0 && mb_strlen($content) > $maxlen) {
1752 // Web interface and current Twitter API clients will
1753 // pull the original notice's text, but some older
1754 // clients and RSS/Atom feeds will see this trimmed text.
1756 // Unfortunately this is likely to lose tags or URLs
1757 // at the end of long notices.
1758 $content = mb_substr($content, 0, $maxlen - 4) . ' ...';
1761 return self::saveNew($repeater_id, $content, $source,
1762 array('repeat_of' => $this->id));
1765 // These are supposed to be in chron order!
1767 function repeatStream($limit=100)
1769 $cache = common_memcache();
1771 if (empty($cache)) {
1772 $ids = $this->_repeatStreamDirect($limit);
1774 $idstr = $cache->get(common_cache_key('notice:repeats:'.$this->id));
1775 if ($idstr !== false) {
1776 $ids = explode(',', $idstr);
1778 $ids = $this->_repeatStreamDirect(100);
1779 $cache->set(common_cache_key('notice:repeats:'.$this->id), implode(',', $ids));
1782 // We do a max of 100, so slice down to limit
1783 $ids = array_slice($ids, 0, $limit);
1787 return Notice::getStreamByIds($ids);
1790 function _repeatStreamDirect($limit)
1792 $notice = new Notice();
1794 $notice->selectAdd(); // clears it
1795 $notice->selectAdd('id');
1797 $notice->repeat_of = $this->id;
1799 $notice->orderBy('created'); // NB: asc!
1801 if (!is_null($offset)) {
1802 $notice->limit($offset, $limit);
1807 if ($notice->find()) {
1808 while ($notice->fetch()) {
1809 $ids[] = $notice->id;
1819 function locationOptions($lat, $lon, $location_id, $location_ns, $profile = null)
1823 if (!empty($location_id) && !empty($location_ns)) {
1825 $options['location_id'] = $location_id;
1826 $options['location_ns'] = $location_ns;
1828 $location = Location::fromId($location_id, $location_ns);
1830 if (!empty($location)) {
1831 $options['lat'] = $location->lat;
1832 $options['lon'] = $location->lon;
1835 } else if (!empty($lat) && !empty($lon)) {
1837 $options['lat'] = $lat;
1838 $options['lon'] = $lon;
1840 $location = Location::fromLatLon($lat, $lon);
1842 if (!empty($location)) {
1843 $options['location_id'] = $location->location_id;
1844 $options['location_ns'] = $location->location_ns;
1846 } else if (!empty($profile)) {
1848 if (isset($profile->lat) && isset($profile->lon)) {
1849 $options['lat'] = $profile->lat;
1850 $options['lon'] = $profile->lon;
1853 if (isset($profile->location_id) && isset($profile->location_ns)) {
1854 $options['location_id'] = $profile->location_id;
1855 $options['location_ns'] = $profile->location_ns;
1862 function clearReplies()
1864 $replyNotice = new Notice();
1865 $replyNotice->reply_to = $this->id;
1867 //Null any notices that are replies to this notice
1869 if ($replyNotice->find()) {
1870 while ($replyNotice->fetch()) {
1871 $orig = clone($replyNotice);
1872 $replyNotice->reply_to = null;
1873 $replyNotice->update($orig);
1879 $reply = new Reply();
1880 $reply->notice_id = $this->id;
1882 if ($reply->find()) {
1883 while($reply->fetch()) {
1884 self::blow('reply:stream:%d', $reply->profile_id);
1892 function clearRepeats()
1894 $repeatNotice = new Notice();
1895 $repeatNotice->repeat_of = $this->id;
1897 //Null any notices that are repeats of this notice
1899 if ($repeatNotice->find()) {
1900 while ($repeatNotice->fetch()) {
1901 $orig = clone($repeatNotice);
1902 $repeatNotice->repeat_of = null;
1903 $repeatNotice->update($orig);
1908 function clearFaves()
1911 $fave->notice_id = $this->id;
1913 if ($fave->find()) {
1914 while ($fave->fetch()) {
1915 self::blow('fave:ids_by_user_own:%d', $fave->user_id);
1916 self::blow('fave:ids_by_user_own:%d;last', $fave->user_id);
1917 self::blow('fave:ids_by_user:%d', $fave->user_id);
1918 self::blow('fave:ids_by_user:%d;last', $fave->user_id);
1926 function clearTags()
1928 $tag = new Notice_tag();
1929 $tag->notice_id = $this->id;
1932 while ($tag->fetch()) {
1933 self::blow('profile:notice_ids_tagged:%d:%s', $this->profile_id, common_keyize($tag->tag));
1934 self::blow('profile:notice_ids_tagged:%d:%s;last', $this->profile_id, common_keyize($tag->tag));
1935 self::blow('notice_tag:notice_ids:%s', common_keyize($tag->tag));
1936 self::blow('notice_tag:notice_ids:%s;last', common_keyize($tag->tag));
1944 function clearGroupInboxes()
1946 $gi = new Group_inbox();
1948 $gi->notice_id = $this->id;
1951 while ($gi->fetch()) {
1952 self::blow('user_group:notice_ids:%d', $gi->group_id);
1960 function distribute()
1962 // We always insert for the author so they don't
1965 $user = User::staticGet('id', $this->profile_id);
1966 if (!empty($user)) {
1967 Inbox::insertNotice($user->id, $this->id);
1970 if (common_config('queue', 'inboxes')) {
1971 // If there's a failure, we want to _force_
1972 // distribution at this point.
1974 $qm = QueueManager::get();
1975 $qm->enqueue($this, 'distrib');
1976 } catch (Exception $e) {
1977 // If the exception isn't transient, this
1978 // may throw more exceptions as DQH does
1979 // its own enqueueing. So, we ignore them!
1981 $handler = new DistribQueueHandler();
1982 $handler->handle($this);
1983 } catch (Exception $e) {
1984 common_log(LOG_ERR, "emergency redistribution resulted in " . $e->getMessage());
1986 // Re-throw so somebody smarter can handle it.
1990 $handler = new DistribQueueHandler();
1991 $handler->handle($this);
1997 $result = parent::insert();
2000 // Profile::hasRepeated() abuses pkeyGet(), so we
2001 // have to clear manually
2002 if (!empty($this->repeat_of)) {
2003 $c = self::memcache();
2005 $ck = self::multicacheKey('Notice',
2006 array('profile_id' => $this->profile_id,
2007 'repeat_of' => $this->repeat_of));
2017 * Get the source of the notice
2019 * @return Notice_source $ns A notice source object. 'code' is the only attribute
2020 * guaranteed to be populated.
2022 function getSource()
2024 $ns = new Notice_source();
2025 if (!empty($this->source)) {
2026 switch ($this->source) {
2033 $ns->code = $this->source;
2036 $ns = Notice_source::staticGet($this->source);
2038 $ns = new Notice_source();
2039 $ns->code = $this->source;
2040 $app = Oauth_application::staticGet('name', $this->source);
2042 $ns->name = $app->name;
2043 $ns->url = $app->source_url;
2053 * Determine whether the notice was locally created
2055 * @return boolean locality
2058 public function isLocal()
2060 return ($this->is_local == Notice::LOCAL_PUBLIC ||
2061 $this->is_local == Notice::LOCAL_NONPUBLIC);
2064 public function getTags()
2067 $tag = new Notice_tag();
2068 $tag->notice_id = $this->id;
2070 while ($tag->fetch()) {
2071 $tags[] = $tag->tag;
2078 static private function utcDate($dt)
2080 $dateStr = date('d F Y H:i:s', strtotime($dt));
2081 $d = new DateTime($dateStr, new DateTimeZone('UTC'));
2082 return $d->format(DATE_W3C);