3 * StatusNet - the distributed open-source microblogging tool
4 * Copyright (C) 2008-2011 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 * @author Mikael Nordfeldth <mmn@hethane.se>
33 * @copyright 2009 Free Software Foundation, Inc http://www.fsf.org
34 * @license GNU Affero General Public License http://www.gnu.org/licenses/
37 if (!defined('GNUSOCIAL')) { exit(1); }
40 * Table Definition for notice
43 /* We keep 200 notices, the max number of notices available per API request,
44 * in the memcached cache. */
46 define('NOTICE_CACHE_WINDOW', CachingNoticeStream::CACHE_WINDOW);
48 define('MAX_BOXCARS', 128);
50 class Notice extends Managed_DataObject
53 /* the code below is auto generated do not remove the above tag */
55 public $__table = 'notice'; // table name
56 public $id; // int(4) primary_key not_null
57 public $profile_id; // int(4) multiple_key not_null
58 public $uri; // varchar(191) unique_key not 255 because utf8mb4 takes more space
59 public $content; // text
60 public $rendered; // text
61 public $url; // varchar(191) not 255 because utf8mb4 takes more space
62 public $created; // datetime multiple_key not_null default_0000-00-00%2000%3A00%3A00
63 public $modified; // timestamp not_null default_CURRENT_TIMESTAMP
64 public $reply_to; // int(4)
65 public $is_local; // int(4)
66 public $source; // varchar(32)
67 public $conversation; // int(4)
68 public $lat; // decimal(10,7)
69 public $lon; // decimal(10,7)
70 public $location_id; // int(4)
71 public $location_ns; // int(4)
72 public $repeat_of; // int(4)
73 public $verb; // varchar(191) not 255 because utf8mb4 takes more space
74 public $object_type; // varchar(191) not 255 because utf8mb4 takes more space
75 public $scope; // int(4)
77 /* the code above is auto generated do not remove the tag below */
80 public static function schemaDef()
84 'id' => array('type' => 'serial', 'not null' => true, 'description' => 'unique identifier'),
85 'profile_id' => array('type' => 'int', 'not null' => true, 'description' => 'who made the update'),
86 'uri' => array('type' => 'varchar', 'length' => 191, 'description' => 'universally unique identifier, usually a tag URI'),
87 'content' => array('type' => 'text', 'description' => 'update content', 'collate' => 'utf8mb4_general_ci'),
88 'rendered' => array('type' => 'text', 'description' => 'HTML version of the content'),
89 'url' => array('type' => 'varchar', 'length' => 191, 'description' => 'URL of any attachment (image, video, bookmark, whatever)'),
90 'created' => array('type' => 'datetime', 'not null' => true, 'description' => 'date this record was created'),
91 'modified' => array('type' => 'timestamp', 'not null' => true, 'description' => 'date this record was modified'),
92 'reply_to' => array('type' => 'int', 'description' => 'notice replied to (usually a guess)'),
93 'is_local' => array('type' => 'int', 'size' => 'tiny', 'default' => 0, 'description' => 'notice was generated by a user'),
94 'source' => array('type' => 'varchar', 'length' => 32, 'description' => 'source of comment, like "web", "im", or "clientname"'),
95 'conversation' => array('type' => 'int', 'description' => 'id of root notice in this conversation'),
96 'lat' => array('type' => 'numeric', 'precision' => 10, 'scale' => 7, 'description' => 'latitude'),
97 'lon' => array('type' => 'numeric', 'precision' => 10, 'scale' => 7, 'description' => 'longitude'),
98 'location_id' => array('type' => 'int', 'description' => 'location id if possible'),
99 'location_ns' => array('type' => 'int', 'description' => 'namespace for location'),
100 'repeat_of' => array('type' => 'int', 'description' => 'notice this is a repeat of'),
101 'object_type' => array('type' => 'varchar', 'length' => 191, 'description' => 'URI representing activity streams object type', 'default' => 'http://activitystrea.ms/schema/1.0/note'),
102 'verb' => array('type' => 'varchar', 'length' => 191, 'description' => 'URI representing activity streams verb', 'default' => 'http://activitystrea.ms/schema/1.0/post'),
103 'scope' => array('type' => 'int',
104 'description' => 'bit map for distribution scope; 0 = everywhere; 1 = this server only; 2 = addressees; 4 = followers; null = default'),
106 'primary key' => array('id'),
107 'unique keys' => array(
108 'notice_uri_key' => array('uri'),
110 'foreign keys' => array(
111 'notice_profile_id_fkey' => array('profile', array('profile_id' => 'id')),
112 'notice_reply_to_fkey' => array('notice', array('reply_to' => 'id')),
113 'notice_conversation_fkey' => array('conversation', array('conversation' => 'id')), # note... used to refer to notice.id
114 'notice_repeat_of_fkey' => array('notice', array('repeat_of' => 'id')), # @fixme: what about repeats of deleted notices?
117 'notice_created_id_is_local_idx' => array('created', 'id', 'is_local'),
118 'notice_profile_id_idx' => array('profile_id', 'created', 'id'),
119 'notice_repeat_of_created_id_idx' => array('repeat_of', 'created', 'id'),
120 'notice_conversation_created_id_idx' => array('conversation', 'created', 'id'),
121 'notice_replyto_idx' => array('reply_to')
125 if (common_config('search', 'type') == 'fulltext') {
126 $def['fulltext indexes'] = array('content' => array('content'));
133 const LOCAL_PUBLIC = 1;
135 const LOCAL_NONPUBLIC = -1;
138 const PUBLIC_SCOPE = 0; // Useful fake constant
139 const SITE_SCOPE = 1;
140 const ADDRESSEE_SCOPE = 2;
141 const GROUP_SCOPE = 4;
142 const FOLLOWER_SCOPE = 8;
144 protected $_profile = array();
147 * Will always return a profile, if anything fails it will
148 * (through _setProfile) throw a NoProfileException.
150 public function getProfile()
152 if (!isset($this->_profile[$this->profile_id])) {
153 // We could've sent getKV directly to _setProfile, but occasionally we get
154 // a "false" (instead of null), likely because it indicates a cache miss.
155 $profile = Profile::getKV('id', $this->profile_id);
156 $this->_setProfile($profile instanceof Profile ? $profile : null);
158 return $this->_profile[$this->profile_id];
161 public function _setProfile(Profile $profile=null)
163 if (!$profile instanceof Profile) {
164 throw new NoProfileException($this->profile_id);
166 $this->_profile[$this->profile_id] = $profile;
169 function delete($useWhere=false)
171 // For auditing purposes, save a record that the notice
174 // @fixme we have some cases where things get re-run and so the
176 $deleted = Deleted_notice::getKV('id', $this->id);
178 if (!$deleted instanceof Deleted_notice) {
179 $deleted = Deleted_notice::getKV('uri', $this->uri);
182 if (!$deleted instanceof Deleted_notice) {
183 $deleted = new Deleted_notice();
185 $deleted->id = $this->id;
186 $deleted->profile_id = $this->profile_id;
187 $deleted->uri = $this->uri;
188 $deleted->created = $this->created;
189 $deleted->deleted = common_sql_now();
194 if (Event::handle('NoticeDeleteRelated', array($this))) {
196 // Clear related records
198 $this->clearReplies();
199 $this->clearRepeats();
201 $this->clearGroupInboxes();
203 $this->clearAttentions();
205 // NOTE: we don't clear queue items
208 $result = parent::delete($useWhere);
210 $this->blowOnDelete();
214 public function getUri()
220 * Get a Notice object by URI. Will call external plugins for help
221 * using the event StartGetNoticeFromURI.
223 * @param string $uri A unique identifier for a resource (notice in this case)
225 static function fromUri($uri)
229 if (Event::handle('StartGetNoticeFromUri', array($uri, &$notice))) {
230 $notice = Notice::getKV('uri', $uri);
231 Event::handle('EndGetNoticeFromUri', array($uri, $notice));
234 if (!$notice instanceof Notice) {
235 throw new UnknownUriException($uri);
242 * @param $root boolean If true, link to just the conversation root.
244 * @return URL to conversation
246 public function getConversationUrl($anchor=true)
248 return Conversation::getUrlFromNotice($this, $anchor);
252 * Get the local representation URL of this notice.
254 public function getLocalUrl()
256 return common_local_url('shownotice', array('notice' => $this->id), null, null, false);
259 public function getTitle()
262 if (Event::handle('GetNoticeTitle', array($this, &$title))) {
263 // TRANS: Title of a notice posted without a title value.
264 // TRANS: %1$s is a user name, %2$s is the notice creation date/time.
265 $title = sprintf(_('%1$s\'s status on %2$s'),
266 $this->getProfile()->getFancyName(),
267 common_exact_date($this->created));
272 public function getContent()
274 return $this->content;
278 * Get the original representation URL of this notice.
280 * @param boolean $fallback Whether to fall back to generate a local URL or throw InvalidUrlException
282 public function getUrl($fallback=false)
284 // The risk is we start having empty urls and non-http uris...
285 // and we can't really handle any other protocol right now.
287 case common_valid_http_url($this->url): // should we allow non-http/https URLs?
289 case !$this->isLocal() && common_valid_http_url($this->uri): // Sometimes we only have the URI for remote posts.
291 case $this->isLocal() || $fallback:
292 // let's generate a valid link to our locally available notice on demand
293 return common_local_url('shownotice', array('notice' => $this->id), null, null, false);
295 common_debug('No URL available for notice: id='.$this->id);
296 throw new InvalidUrlException($this->url);
300 public function get_object_type($canonical=false) {
302 ? ActivityObject::canonicalType($this->object_type)
303 : $this->object_type;
306 public static function getByUri($uri)
308 $notice = new Notice();
310 if (!$notice->find(true)) {
311 throw new NoResultException($notice);
317 * Extract #hashtags from this notice's content and save them to the database.
321 /* extract all #hastags */
322 $count = preg_match_all('/(?:^|\s)#([\pL\pN_\-\.]{1,64})/u', strtolower($this->content), $match);
327 /* Add them to the database */
328 return $this->saveKnownTags($match[1]);
332 * Record the given set of hash tags in the db for this notice.
333 * Given tag strings will be normalized and checked for dupes.
335 function saveKnownTags(array $hashtags)
337 //turn each into their canonical tag
338 //this is needed to remove dupes before saving e.g. #hash.tag = #hashtag
339 for($i=0; $i<count($hashtags); $i++) {
340 /* elide characters we don't want in the tag */
341 $hashtags[$i] = common_canonical_tag($hashtags[$i]);
344 foreach(array_unique($hashtags) as $hashtag) {
345 $this->saveTag($hashtag);
346 self::blow('profile:notice_ids_tagged:%d:%s', $this->profile_id, $hashtag);
352 * Record a single hash tag as associated with this notice.
353 * Tag format and uniqueness must be validated by caller.
355 function saveTag($hashtag)
357 $tag = new Notice_tag();
358 $tag->notice_id = $this->id;
359 $tag->tag = $hashtag;
360 $tag->created = $this->created;
361 $id = $tag->insert();
364 // TRANS: Server exception. %s are the error details.
365 throw new ServerException(sprintf(_('Database error inserting hashtag: %s.'),
366 $last_error->message));
370 // if it's saved, blow its cache
371 $tag->blowCache(false);
375 * Save a new notice and push it out to subscribers' inboxes.
376 * Poster's permissions are checked before sending.
378 * @param int $profile_id Profile ID of the poster
379 * @param string $content source message text; links may be shortened
380 * per current user's preference
381 * @param string $source source key ('web', 'api', etc)
382 * @param array $options Associative array of optional properties:
383 * string 'created' timestamp of notice; defaults to now
384 * int 'is_local' source/gateway ID, one of:
385 * Notice::LOCAL_PUBLIC - Local, ok to appear in public timeline
386 * Notice::REMOTE - Sent from a remote service;
387 * hide from public timeline but show in
388 * local "and friends" timelines
389 * Notice::LOCAL_NONPUBLIC - Local, but hide from public timeline
390 * Notice::GATEWAY - From another non-OStatus service;
391 * will not appear in public views
392 * float 'lat' decimal latitude for geolocation
393 * float 'lon' decimal longitude for geolocation
394 * int 'location_id' geoname identifier
395 * int 'location_ns' geoname namespace to interpret location_id
396 * int 'reply_to'; notice ID this is a reply to
397 * int 'repeat_of'; notice ID this is a repeat of
398 * string 'uri' unique ID for notice; a unique tag uri (can be url or anything too)
399 * string 'url' permalink to notice; defaults to local notice URL
400 * string 'rendered' rendered HTML version of content
401 * array 'replies' list of profile URIs for reply delivery in
402 * place of extracting @-replies from content.
403 * array 'groups' list of group IDs to deliver to, in place of
404 * extracting ! tags from content
405 * array 'tags' list of hashtag strings to save with the notice
406 * in place of extracting # tags from content
407 * array 'urls' list of attached/referred URLs to save with the
408 * notice in place of extracting links from content
409 * boolean 'distribute' whether to distribute the notice, default true
410 * string 'object_type' URL of the associated object type (default ActivityObject::NOTE)
411 * string 'verb' URL of the associated verb (default ActivityVerb::POST)
412 * int 'scope' Scope bitmask; default to SITE_SCOPE on private sites, 0 otherwise
414 * @fixme tag override
417 * @throws ClientException
419 static function saveNew($profile_id, $content, $source, array $options=array()) {
420 $defaults = array('uri' => null,
422 'conversation' => null, // URI of conversation
423 'reply_to' => null, // This will override convo URI if the parent is known
424 'repeat_of' => null, // This will override convo URI if the repeated notice is known
426 'distribute' => true,
427 'object_type' => null,
431 * Above type-hint is already array, so simply count it, this saves
434 if (count($options) > 0) {
435 $options = array_merge($defaults, $options);
440 if (!isset($is_local)) {
441 $is_local = Notice::LOCAL_PUBLIC;
444 $profile = Profile::getKV('id', $profile_id);
445 if (!$profile instanceof Profile) {
446 // TRANS: Client exception thrown when trying to save a notice for an unknown user.
447 throw new ClientException(_('Problem saving notice. Unknown user.'));
450 $user = User::getKV('id', $profile_id);
451 if ($user instanceof User) {
452 // Use the local user's shortening preferences, if applicable.
453 $final = $user->shortenLinks($content);
455 $final = common_shorten_links($content);
458 if (Notice::contentTooLong($final)) {
459 // TRANS: Client exception thrown if a notice contains too many characters.
460 throw new ClientException(_('Problem saving notice. Too long.'));
463 if (common_config('throttle', 'enabled') && !Notice::checkEditThrottle($profile_id)) {
464 common_log(LOG_WARNING, 'Excessive posting by profile #' . $profile_id . '; throttled.');
465 // TRANS: Client exception thrown when a user tries to post too many notices in a given time frame.
466 throw new ClientException(_('Too many notices too fast; take a breather '.
467 'and post again in a few minutes.'));
470 if (common_config('site', 'dupelimit') > 0 && !Notice::checkDupes($profile_id, $final)) {
471 common_log(LOG_WARNING, 'Dupe posting by profile #' . $profile_id . '; throttled.');
472 // TRANS: Client exception thrown when a user tries to post too many duplicate notices in a given time frame.
473 throw new ClientException(_('Too many duplicate messages too quickly;'.
474 ' take a breather and post again in a few minutes.'));
477 if (!$profile->hasRight(Right::NEWNOTICE)) {
478 common_log(LOG_WARNING, "Attempted post from user disallowed to post: " . $profile->nickname);
480 // TRANS: Client exception thrown when a user tries to post while being banned.
481 throw new ClientException(_('You are banned from posting notices on this site.'), 403);
484 $notice = new Notice();
485 $notice->profile_id = $profile_id;
487 $autosource = common_config('public', 'autosource');
489 // Sandboxed are non-false, but not 1, either
491 if (!$profile->hasRight(Right::PUBLICNOTICE) ||
492 ($source && $autosource && in_array($source, $autosource))) {
493 $notice->is_local = Notice::LOCAL_NONPUBLIC;
495 $notice->is_local = $is_local;
498 if (!empty($created)) {
499 $notice->created = $created;
501 $notice->created = common_sql_now();
504 if (!$notice->isLocal()) {
505 // Only do these checks for non-local notices. Local notices will generate these values later.
506 if (!common_valid_http_url($url)) {
507 common_debug('Bad notice URL: ['.$url.'], URI: ['.$uri.']. Cannot link back to original! This is normal for shared notices etc.');
510 throw new ServerException('No URI for remote notice. Cannot accept that.');
514 $notice->content = $final;
516 $notice->source = $source;
520 // Get the groups here so we can figure out replies and such
521 if (!isset($groups)) {
522 $groups = User_group::idsFromText($notice->content, $profile);
527 // Handle repeat case
529 if (isset($repeat_of)) {
531 // Check for a private one
533 $repeat = Notice::getKV('id', $repeat_of);
535 if (!($repeat instanceof Notice)) {
536 // TRANS: Client exception thrown in notice when trying to repeat a missing or deleted notice.
537 throw new ClientException(_('Cannot repeat; original notice is missing or deleted.'));
540 if ($profile->id == $repeat->profile_id) {
541 // TRANS: Client error displayed when trying to repeat an own notice.
542 throw new ClientException(_('You cannot repeat your own notice.'));
545 if ($repeat->isPrivateScope()) {
546 // TRANS: Client error displayed when trying to repeat a non-public notice.
547 throw new ClientException(_('Cannot repeat a private notice.'), 403);
550 if (!$repeat->inScope($profile)) {
551 // The generic checks above should cover this, but let's be sure!
552 // TRANS: Client error displayed when trying to repeat a notice you cannot access.
553 throw new ClientException(_('Cannot repeat a notice you cannot read.'), 403);
556 if ($profile->hasRepeated($repeat)) {
557 // TRANS: Client error displayed when trying to repeat an already repeated notice.
558 throw new ClientException(_('You already repeated that notice.'));
561 $notice->repeat_of = $repeat->id;
562 $notice->conversation = $repeat->conversation;
566 // If $reply_to is specified, we check that it exists, and then
567 // return it if it does
568 if (!empty($reply_to)) {
569 $reply = Notice::getKV('id', $reply_to);
570 } elseif (in_array($source, array('xmpp', 'mail', 'sms'))) {
571 // If the source lacks capability of sending the "reply_to"
572 // metadata, let's try to find an inline replyto-reference.
573 $reply = self::getInlineReplyTo($profile, $final);
576 if ($reply instanceof Notice) {
577 if (!$reply->inScope($profile)) {
578 // TRANS: Client error displayed when trying to reply to a notice a the target has no access to.
579 // TRANS: %1$s is a user nickname, %2$d is a notice ID (number).
580 throw new ClientException(sprintf(_('%1$s has no access to notice %2$d.'),
581 $profile->nickname, $reply->id), 403);
584 // If it's a repeat, the reply_to should be to the original
585 if ($reply->isRepeat()) {
586 $notice->reply_to = $reply->repeat_of;
588 $notice->reply_to = $reply->id;
590 // But the conversation ought to be the same :)
591 $notice->conversation = $reply->conversation;
593 // If the original is private to a group, and notice has
594 // no group specified, make it to the same group(s)
596 if (empty($groups) && ($reply->scope & Notice::GROUP_SCOPE)) {
598 $replyGroups = $reply->getGroups();
599 foreach ($replyGroups as $group) {
600 if ($profile->isMember($group)) {
601 $groups[] = $group->id;
609 // If we don't know the reply, we might know the conversation!
610 // This will happen if a known remote user replies to an
611 // unknown remote user - within a known conversation.
612 if (empty($notice->conversation) and !empty($options['conversation'])) {
613 $conv = Conversation::getKV('uri', $options['conversation']);
614 if ($conv instanceof Conversation) {
615 common_debug('Conversation stitched together from (probably) reply to unknown remote user. Activity creation time ('.$notice->created.') should maybe be compared to conversation creation time ('.$conv->created.').');
616 $notice->conversation = $conv->id;
618 // Conversation URI was not found, so we must create it. But we can't create it
619 // until we have a Notice ID because of the database layout...
620 $notice->tmp_conv_uri = $options['conversation'];
623 // If we're not using the attached conversation URI let's remove it
624 // so we don't mistake ourselves later, when creating our own Conversation.
625 // This implies that the notice knows which conversation it belongs to.
626 $options['conversation'] = null;
630 if (!empty($lat) && !empty($lon)) {
635 if (!empty($location_ns) && !empty($location_id)) {
636 $notice->location_id = $location_id;
637 $notice->location_ns = $location_ns;
640 if (!empty($rendered)) {
641 $notice->rendered = $rendered;
643 $notice->rendered = common_render_content($final, $notice);
647 if ($notice->isRepeat()) {
648 $notice->verb = ActivityVerb::SHARE;
649 $notice->object_type = ActivityObject::ACTIVITY;
651 $notice->verb = ActivityVerb::POST;
654 $notice->verb = $verb;
657 if (empty($object_type)) {
658 $notice->object_type = (empty($notice->reply_to)) ? ActivityObject::NOTE : ActivityObject::COMMENT;
660 $notice->object_type = $object_type;
663 if (is_null($scope) && $reply instanceof Notice) {
664 $notice->scope = $reply->scope;
666 $notice->scope = $scope;
669 $notice->scope = self::figureOutScope($profile, $groups, $notice->scope);
671 if (Event::handle('StartNoticeSave', array(&$notice))) {
673 // XXX: some of these functions write to the DB
676 $notice->insert(); // throws exception on failure
677 // If it's not part of a conversation, it's
678 // the beginning of a new conversation.
679 if (empty($notice->conversation)) {
680 $orig = clone($notice);
681 // $act->context->conversation will be null if it was not provided
682 $conv = Conversation::create($notice, $options['conversation']);
683 $notice->conversation = $conv->id;
684 $notice->update($orig);
686 } catch (Exception $e) {
687 // Let's test if we managed initial insert, which would imply
688 // failing on some update-part (check 'insert()'). Delete if
689 // something had been stored to the database.
690 if (!empty($notice->id)) {
697 // Clear the cache for subscribed users, so they'll update at next request
698 // XXX: someone clever could prepend instead of clearing the cache
700 // Save per-notice metadata...
702 if (isset($replies)) {
703 $notice->saveKnownReplies($replies);
705 $notice->saveReplies();
709 $notice->saveKnownTags($tags);
714 // Note: groups may save tags, so must be run after tags are saved
715 // to avoid errors on duplicates.
716 // Note: groups should always be set.
718 $notice->saveKnownGroups($groups);
721 $notice->saveKnownUrls($urls);
727 // Prepare inbox delivery, may be queued to background.
728 $notice->distribute();
734 static function saveActivity(Activity $act, Profile $actor, array $options=array())
736 // First check if we're going to let this Activity through from the specific actor
737 if (!$actor->hasRight(Right::NEWNOTICE)) {
738 common_log(LOG_WARNING, "Attempted post from user disallowed to post: " . $actor->getNickname());
740 // TRANS: Client exception thrown when a user tries to post while being banned.
741 throw new ClientException(_m('You are banned from posting notices on this site.'), 403);
743 if (common_config('throttle', 'enabled') && !self::checkEditThrottle($actor->id)) {
744 common_log(LOG_WARNING, 'Excessive posting by profile #' . $actor->id . '; throttled.');
745 // TRANS: Client exception thrown when a user tries to post too many notices in a given time frame.
746 throw new ClientException(_m('Too many notices too fast; take a breather '.
747 'and post again in a few minutes.'));
750 // Get ActivityObject properties
751 if (!empty($act->id)) {
753 $options['uri'] = $act->id;
754 $options['url'] = $act->link;
756 $actobj = count($act->objects)==1 ? $act->objects[0] : null;
757 if (!is_null($actobj) && !empty($actobj->id)) {
758 $options['uri'] = $actobj->id;
760 $options['url'] = $actobj->link;
761 } elseif (preg_match('!^https?://!', $actobj->id)) {
762 $options['url'] = $actobj->id;
769 'is_local' => self::LOCAL_PUBLIC,
770 'mentions' => array(),
774 'source' => 'unknown',
779 'distribute' => true);
781 // options will have default values when nothing has been supplied
782 $options = array_merge($defaults, $options);
783 foreach (array_keys($defaults) as $key) {
784 // Only convert the keynames we specify ourselves from 'defaults' array into variables
785 $$key = $options[$key];
787 extract($options, EXTR_SKIP);
789 $stored = new Notice();
792 if ($stored->find()) {
793 common_debug('cannot create duplicate Notice URI: '.$stored->uri);
794 throw new Exception('Notice URI already exists');
798 $stored->profile_id = $actor->id;
799 $stored->source = $source;
802 $stored->verb = $act->verb;
804 // Use the local user's shortening preferences, if applicable.
805 $stored->rendered = $actor->isLocal()
806 ? $actor->shortenLinks($act->content)
808 $stored->content = common_strip_html($stored->rendered);
810 $autosource = common_config('public', 'autosource');
812 // Sandboxed are non-false, but not 1, either
813 if (!$actor->hasRight(Right::PUBLICNOTICE) ||
814 ($source && $autosource && in_array($source, $autosource))) {
815 $stored->is_local = Notice::LOCAL_NONPUBLIC;
818 // Maybe a missing act-time should be fatal if the actor is not local?
819 if (!empty($act->time)) {
820 $stored->created = common_sql_date($act->time);
822 $stored->created = common_sql_now();
826 if ($act->context instanceof ActivityContext && !empty($act->context->replyToID)) {
827 $reply = self::getKV('uri', $act->context->replyToID);
829 if (!$reply instanceof Notice && $act->target instanceof ActivityObject) {
830 $reply = self::getKV('uri', $act->target->id);
833 if ($reply instanceof Notice) {
834 if (!$reply->inScope($actor)) {
835 // TRANS: Client error displayed when trying to reply to a notice a the target has no access to.
836 // TRANS: %1$s is a user nickname, %2$d is a notice ID (number).
837 throw new ClientException(sprintf(_m('%1$s has no right to reply to notice %2$d.'), $actor->getNickname(), $reply->id), 403);
840 $stored->reply_to = $reply->id;
841 $stored->conversation = $reply->conversation;
843 // If the original is private to a group, and notice has no group specified,
844 // make it to the same group(s)
845 if (empty($groups) && ($reply->scope & Notice::GROUP_SCOPE)) {
847 $replyGroups = $reply->getGroups();
848 foreach ($replyGroups as $group) {
849 if ($actor->isMember($group)) {
850 $groups[] = $group->id;
855 if (is_null($scope)) {
856 $scope = $reply->scope;
860 if ($act->context instanceof ActivityContext) {
861 $location = $act->context->location;
863 $stored->lat = $location->lat;
864 $stored->lon = $location->lon;
865 if ($location->location_id) {
866 $stored->location_ns = $location->location_ns;
867 $stored->location_id = $location->location_id;
871 $act->context = new ActivityContext();
874 $stored->scope = self::figureOutScope($actor, $groups, $scope);
876 foreach ($act->categories as $cat) {
878 $term = common_canonical_tag($cat->term);
885 foreach ($act->enclosures as $href) {
886 // @todo FIXME: Save these locally or....?
890 if (Event::handle('StartNoticeSave', array(&$stored))) {
891 // XXX: some of these functions write to the DB
894 $stored->insert(); // throws exception on error
895 $orig = clone($stored); // for updating later in this try clause
898 Event::handle('StoreActivityObject', array($act, $stored, $options, &$object));
899 if (empty($object)) {
900 throw new ServerException('Unsuccessful call to StoreActivityObject '.$stored->uri . ': '.$act->asString());
903 // If it's not part of a conversation, it's
904 // the beginning of a new conversation.
905 if (empty($stored->conversation)) {
906 // $act->context->conversation will be null if it was not provided
907 $conv = Conversation::create($stored, $act->context->conversation);
908 $stored->conversation = $conv->id;
911 $stored->update($orig);
912 } catch (Exception $e) {
913 if (empty($stored->id)) {
914 common_debug('Failed to save stored object entry in database ('.$e->getMessage().')');
916 common_debug('Failed to store activity object in database ('.$e->getMessage().'), deleting notice id '.$stored->id);
922 if (!$stored instanceof Notice) {
923 throw new ServerException('StartNoticeSave did not give back a Notice');
926 // Save per-notice metadata...
930 // This event lets plugins filter out non-local recipients (attentions we don't care about)
931 // Used primarily for OStatus (and if we don't federate, all attentions would be local anyway)
932 Event::handle('GetLocalAttentions', array($actor, $act->context->attention, &$mentions, &$groups));
934 if (!empty($mentions)) {
935 $stored->saveKnownReplies($mentions);
937 $stored->saveReplies();
941 $stored->saveKnownTags($tags);
946 // Note: groups may save tags, so must be run after tags are saved
947 // to avoid errors on duplicates.
948 // Note: groups should always be set.
950 $stored->saveKnownGroups($groups);
953 $stored->saveKnownUrls($urls);
959 // Prepare inbox delivery, may be queued to background.
960 $stored->distribute();
966 static public function figureOutScope(Profile $actor, array $groups, $scope=null) {
967 if (is_null($scope)) {
968 $scope = self::defaultScope();
971 // For private streams
973 $user = $actor->getUser();
974 // FIXME: We can't do bit comparison with == (Legacy StatusNet thing. Let's keep it for now.)
975 if ($user->private_stream && ($scope == Notice::PUBLIC_SCOPE || $scope == Notice::SITE_SCOPE)) {
976 $scope |= Notice::FOLLOWER_SCOPE;
978 } catch (NoSuchUserException $e) {
979 // TODO: Not a local user, so we don't know about scope preferences... yet!
982 // Force the scope for private groups
983 foreach ($groups as $group_id) {
985 $group = User_group::getByID($group_id);
986 if ($group->force_scope) {
987 $scope |= Notice::GROUP_SCOPE;
990 } catch (Exception $e) {
991 common_log(LOG_ERR, 'Notice figureOutScope threw exception: '.$e->getMessage());
998 function blowOnInsert($conversation = false)
1000 $this->blowStream('profile:notice_ids:%d', $this->profile_id);
1002 if ($this->isPublic()) {
1003 $this->blowStream('public');
1004 $this->blowStream('networkpublic');
1007 self::blow('notice:list-ids:conversation:%s', $this->conversation);
1008 self::blow('conversation:notice_count:%d', $this->conversation);
1010 if ($this->isRepeat()) {
1011 // XXX: we should probably only use one of these
1012 $this->blowStream('notice:repeats:%d', $this->repeat_of);
1013 self::blow('notice:list-ids:repeat_of:%d', $this->repeat_of);
1016 $original = Notice::getKV('id', $this->repeat_of);
1018 if ($original instanceof Notice) {
1019 $originalUser = User::getKV('id', $original->profile_id);
1020 if ($originalUser instanceof User) {
1021 $this->blowStream('user:repeats_of_me:%d', $originalUser->id);
1025 $profile = Profile::getKV($this->profile_id);
1027 if ($profile instanceof Profile) {
1028 $profile->blowNoticeCount();
1031 $ptags = $this->getProfileTags();
1032 foreach ($ptags as $ptag) {
1033 $ptag->blowNoticeStreamCache();
1038 * Clear cache entries related to this notice at delete time.
1039 * Necessary to avoid breaking paging on public, profile timelines.
1041 function blowOnDelete()
1043 $this->blowOnInsert();
1045 self::blow('profile:notice_ids:%d;last', $this->profile_id);
1047 if ($this->isPublic()) {
1048 self::blow('public;last');
1049 self::blow('networkpublic;last');
1052 self::blow('fave:by_notice', $this->id);
1054 if ($this->conversation) {
1055 // In case we're the first, will need to calc a new root.
1056 self::blow('notice:conversation_root:%d', $this->conversation);
1059 $ptags = $this->getProfileTags();
1060 foreach ($ptags as $ptag) {
1061 $ptag->blowNoticeStreamCache(true);
1065 function blowStream()
1067 $c = self::memcache();
1073 $args = func_get_args();
1074 $format = array_shift($args);
1075 $keyPart = vsprintf($format, $args);
1076 $cacheKey = Cache::key($keyPart);
1077 $c->delete($cacheKey);
1079 // delete the "last" stream, too, if this notice is
1080 // older than the top of that stream
1082 $lastKey = $cacheKey.';last';
1084 $lastStr = $c->get($lastKey);
1086 if ($lastStr !== false) {
1087 $window = explode(',', $lastStr);
1088 $lastID = $window[0];
1089 $lastNotice = Notice::getKV('id', $lastID);
1090 if (!$lastNotice instanceof Notice // just weird
1091 || strtotime($lastNotice->created) >= strtotime($this->created)) {
1092 $c->delete($lastKey);
1097 /** save all urls in the notice to the db
1099 * follow redirects and save all available file information
1100 * (mimetype, date, size, oembed, etc.)
1104 function saveUrls() {
1105 if (common_config('attachments', 'process_links')) {
1106 common_replace_urls_callback($this->content, array($this, 'saveUrl'), $this);
1111 * Save the given URLs as related links/attachments to the db
1113 * follow redirects and save all available file information
1114 * (mimetype, date, size, oembed, etc.)
1118 function saveKnownUrls(array $urls)
1120 if (common_config('attachments', 'process_links')) {
1121 // @fixme validation?
1122 foreach (array_unique($urls) as $url) {
1123 $this->saveUrl($url, $this);
1131 function saveUrl($url, Notice $notice) {
1133 File::processNew($url, $notice);
1134 } catch (ServerException $e) {
1135 // Could not save URL. Log it?
1139 static function checkDupes($profile_id, $content) {
1140 $profile = Profile::getKV($profile_id);
1141 if (!$profile instanceof Profile) {
1144 $notice = $profile->getNotices(0, CachingNoticeStream::CACHE_WINDOW);
1145 if (!empty($notice)) {
1147 while ($notice->fetch()) {
1148 if (time() - strtotime($notice->created) >= common_config('site', 'dupelimit')) {
1150 } else if ($notice->content == $content) {
1155 // If we get here, oldest item in cache window is not
1156 // old enough for dupe limit; do direct check against DB
1157 $notice = new Notice();
1158 $notice->profile_id = $profile_id;
1159 $notice->content = $content;
1160 $threshold = common_sql_date(time() - common_config('site', 'dupelimit'));
1161 $notice->whereAdd(sprintf("created > '%s'", $notice->escape($threshold)));
1163 $cnt = $notice->count();
1167 static function checkEditThrottle($profile_id) {
1168 $profile = Profile::getKV($profile_id);
1169 if (!$profile instanceof Profile) {
1172 // Get the Nth notice
1173 $notice = $profile->getNotices(common_config('throttle', 'count') - 1, 1);
1174 if ($notice && $notice->fetch()) {
1175 // If the Nth notice was posted less than timespan seconds ago
1176 if (time() - strtotime($notice->created) <= common_config('throttle', 'timespan')) {
1181 // Either not N notices in the stream, OR the Nth was not posted within timespan seconds
1185 protected $_attachments = array();
1187 function attachments() {
1188 if (isset($this->_attachments[$this->id])) {
1189 return $this->_attachments[$this->id];
1192 $f2ps = File_to_post::listGet('post_id', array($this->id));
1194 foreach ($f2ps[$this->id] as $f2p) {
1195 $ids[] = $f2p->file_id;
1198 $files = File::multiGet('id', $ids);
1199 $this->_attachments[$this->id] = $files->fetchAll();
1200 return $this->_attachments[$this->id];
1203 function _setAttachments($attachments)
1205 $this->_attachments[$this->id] = $attachments;
1208 function publicStream($offset=0, $limit=20, $since_id=0, $max_id=0)
1210 $stream = new PublicNoticeStream();
1211 return $stream->getNotices($offset, $limit, $since_id, $max_id);
1215 function conversationStream($id, $offset=0, $limit=20, $since_id=0, $max_id=0)
1217 $stream = new ConversationNoticeStream($id);
1219 return $stream->getNotices($offset, $limit, $since_id, $max_id);
1223 * Is this notice part of an active conversation?
1225 * @return boolean true if other messages exist in the same
1226 * conversation, false if this is the only one
1228 function hasConversation()
1230 if (!empty($this->conversation)) {
1231 $conversation = Notice::conversationStream(
1232 $this->conversation,
1237 if ($conversation->N > 0) {
1245 * Grab the earliest notice from this conversation.
1247 * @return Notice or null
1249 function conversationRoot($profile=-1)
1251 // XXX: can this happen?
1253 if (empty($this->conversation)) {
1257 // Get the current profile if not specified
1259 if (is_int($profile) && $profile == -1) {
1260 $profile = Profile::current();
1263 // If this notice is out of scope, no root for you!
1265 if (!$this->inScope($profile)) {
1269 // If this isn't a reply to anything, then it's its own
1270 // root if it's the earliest notice in the conversation:
1272 if (empty($this->reply_to)) {
1274 $root->conversation = $this->conversation;
1275 $root->orderBy('notice.created ASC');
1282 if (is_null($profile)) {
1283 $keypart = sprintf('notice:conversation_root:%d:null', $this->id);
1285 $keypart = sprintf('notice:conversation_root:%d:%d',
1290 $root = self::cacheGet($keypart);
1292 if ($root !== false && $root->inScope($profile)) {
1299 $parent = $last->getParent();
1300 if ($parent->inScope($profile)) {
1304 } catch (NoParentNoticeException $e) {
1305 // Latest notice has no parent
1307 // No parent, or parent out of scope
1312 self::cacheSet($keypart, $root);
1318 * Pull up a full list of local recipients who will be getting
1319 * this notice in their inbox. Results will be cached, so don't
1320 * change the input data wily-nilly!
1322 * @param array $groups optional list of Group objects;
1323 * if left empty, will be loaded from group_inbox records
1324 * @param array $recipient optional list of reply profile ids
1325 * if left empty, will be loaded from reply records
1326 * @return array associating recipient user IDs with an inbox source constant
1328 function whoGets(array $groups=null, array $recipients=null)
1330 $c = self::memcache();
1333 $ni = $c->get(Cache::key('notice:who_gets:'.$this->id));
1334 if ($ni !== false) {
1339 if (is_null($recipients)) {
1340 $recipients = $this->getReplies();
1345 // Give plugins a chance to add folks in at start...
1346 if (Event::handle('StartNoticeWhoGets', array($this, &$ni))) {
1348 $users = $this->getSubscribedUsers();
1349 foreach ($users as $id) {
1350 $ni[$id] = NOTICE_INBOX_SOURCE_SUB;
1353 if (is_null($groups)) {
1354 $groups = $this->getGroups();
1356 foreach ($groups as $group) {
1357 $users = $group->getUserMembers();
1358 foreach ($users as $id) {
1359 if (!array_key_exists($id, $ni)) {
1360 $ni[$id] = NOTICE_INBOX_SOURCE_GROUP;
1365 $ptAtts = $this->getAttentionsFromProfileTags();
1366 foreach ($ptAtts as $key=>$val) {
1367 if (!array_key_exists($key, $ni)) {
1372 foreach ($recipients as $recipient) {
1373 if (!array_key_exists($recipient, $ni)) {
1374 $ni[$recipient] = NOTICE_INBOX_SOURCE_REPLY;
1378 // Exclude any deleted, non-local, or blocking recipients.
1379 $profile = $this->getProfile();
1380 $originalProfile = null;
1381 if ($this->isRepeat()) {
1382 // Check blocks against the original notice's poster as well.
1383 $original = Notice::getKV('id', $this->repeat_of);
1384 if ($original instanceof Notice) {
1385 $originalProfile = $original->getProfile();
1389 foreach ($ni as $id => $source) {
1391 $user = User::getKV('id', $id);
1392 if (!$user instanceof User ||
1393 $user->hasBlocked($profile) ||
1394 ($originalProfile && $user->hasBlocked($originalProfile))) {
1397 } catch (UserNoProfileException $e) {
1398 // User doesn't have a profile; invalid; skip them.
1403 // Give plugins a chance to filter out...
1404 Event::handle('EndNoticeWhoGets', array($this, &$ni));
1408 // XXX: pack this data better
1409 $c->set(Cache::key('notice:who_gets:'.$this->id), $ni);
1415 function getSubscribedUsers()
1419 if(common_config('db','quote_identifiers'))
1420 $user_table = '"user"';
1421 else $user_table = 'user';
1425 'FROM '. $user_table .' JOIN subscription '.
1426 'ON '. $user_table .'.id = subscription.subscriber ' .
1427 'WHERE subscription.subscribed = %d ';
1429 $user->query(sprintf($qry, $this->profile_id));
1433 while ($user->fetch()) {
1442 function getProfileTags()
1444 $profile = $this->getProfile();
1445 $list = $profile->getOtherTags($profile);
1448 while($list->fetch()) {
1449 $ptags[] = clone($list);
1455 public function getAttentionsFromProfileTags()
1458 $ptags = $this->getProfileTags();
1459 foreach ($ptags as $ptag) {
1460 $users = $ptag->getUserSubscribers();
1461 foreach ($users as $id) {
1462 $ni[$id] = NOTICE_INBOX_SOURCE_PROFILE_TAG;
1469 * Record this notice to the given group inboxes for delivery.
1470 * Overrides the regular parsing of !group markup.
1472 * @param string $group_ids
1473 * @fixme might prefer URIs as identifiers, as for replies?
1474 * best with generalizations on user_group to support
1475 * remote groups better.
1477 function saveKnownGroups($group_ids)
1479 if (!is_array($group_ids)) {
1480 // TRANS: Server exception thrown when no array is provided to the method saveKnownGroups().
1481 throw new ServerException(_('Bad type provided to saveKnownGroups.'));
1485 foreach (array_unique($group_ids) as $id) {
1486 $group = User_group::getKV('id', $id);
1487 if ($group instanceof User_group) {
1488 common_log(LOG_DEBUG, "Local delivery to group id $id, $group->nickname");
1489 $result = $this->addToGroupInbox($group);
1491 common_log_db_error($gi, 'INSERT', __FILE__);
1494 if (common_config('group', 'addtag')) {
1495 // we automatically add a tag for every group name, too
1497 $tag = Notice_tag::pkeyGet(array('tag' => common_canonical_tag($group->nickname),
1498 'notice_id' => $this->id));
1500 if (is_null($tag)) {
1501 $this->saveTag($group->nickname);
1505 $groups[] = clone($group);
1507 common_log(LOG_ERR, "Local delivery to group id $id skipped, doesn't exist");
1514 function addToGroupInbox(User_group $group)
1516 $gi = Group_inbox::pkeyGet(array('group_id' => $group->id,
1517 'notice_id' => $this->id));
1519 if (!$gi instanceof Group_inbox) {
1521 $gi = new Group_inbox();
1523 $gi->group_id = $group->id;
1524 $gi->notice_id = $this->id;
1525 $gi->created = $this->created;
1527 $result = $gi->insert();
1530 common_log_db_error($gi, 'INSERT', __FILE__);
1531 // TRANS: Server exception thrown when an update for a group inbox fails.
1532 throw new ServerException(_('Problem saving group inbox.'));
1535 self::blow('user_group:notice_ids:%d', $gi->group_id);
1542 * Save reply records indicating that this notice needs to be
1543 * delivered to the local users with the given URIs.
1545 * Since this is expected to be used when saving foreign-sourced
1546 * messages, we won't deliver to any remote targets as that's the
1547 * source service's responsibility.
1549 * Mail notifications etc will be handled later.
1551 * @param array $uris Array of unique identifier URIs for recipients
1553 function saveKnownReplies(array $uris)
1559 $sender = Profile::getKV($this->profile_id);
1561 foreach (array_unique($uris) as $uri) {
1563 $profile = Profile::fromUri($uri);
1564 } catch (UnknownUriException $e) {
1565 common_log(LOG_WARNING, "Unable to determine profile for URI '$uri'");
1569 if ($profile->hasBlocked($sender)) {
1570 common_log(LOG_INFO, "Not saving reply to profile {$profile->id} ($uri) from sender {$sender->id} because of a block.");
1574 $this->saveReply($profile->id);
1575 self::blow('reply:stream:%d', $profile->id);
1582 * Pull @-replies from this message's content in StatusNet markup format
1583 * and save reply records indicating that this message needs to be
1584 * delivered to those users.
1586 * Mail notifications to local profiles will be sent later.
1588 * @return array of integer profile IDs
1591 function saveReplies()
1593 // Don't save reply data for repeats
1595 if ($this->isRepeat()) {
1599 $sender = $this->getProfile();
1603 // If it's a reply, save for the replied-to author
1605 $parent = $this->getParent();
1606 $parentauthor = $parent->getProfile();
1607 $this->saveReply($parentauthor->id);
1608 $replied[$parentauthor->id] = 1;
1609 self::blow('reply:stream:%d', $parentauthor->id);
1610 } catch (NoParentNoticeException $e) {
1611 // Not a reply, since it has no parent!
1614 // @todo ideally this parser information would only
1615 // be calculated once.
1617 $mentions = common_find_mentions($this->content, $this);
1619 // store replied only for first @ (what user/notice what the reply directed,
1620 // we assume first @ is it)
1622 foreach ($mentions as $mention) {
1624 foreach ($mention['mentioned'] as $mentioned) {
1626 // skip if they're already covered
1627 if (array_key_exists($mentioned->id, $replied)) {
1631 // Don't save replies from blocked profile to local user
1633 $mentioned_user = User::getKV('id', $mentioned->id);
1634 if ($mentioned_user instanceof User && $mentioned_user->hasBlocked($sender)) {
1638 $this->saveReply($mentioned->id);
1639 $replied[$mentioned->id] = 1;
1640 self::blow('reply:stream:%d', $mentioned->id);
1644 $recipientIds = array_keys($replied);
1646 return $recipientIds;
1649 function saveReply($profileId)
1651 $reply = new Reply();
1653 $reply->notice_id = $this->id;
1654 $reply->profile_id = $profileId;
1655 $reply->modified = $this->created;
1662 protected $_replies = array();
1665 * Pull the complete list of @-reply targets for this notice.
1667 * @return array of integer profile ids
1669 function getReplies()
1671 if (isset($this->_replies[$this->id])) {
1672 return $this->_replies[$this->id];
1675 $replyMap = Reply::listGet('notice_id', array($this->id));
1679 foreach ($replyMap[$this->id] as $reply) {
1680 $ids[] = $reply->profile_id;
1683 $this->_setReplies($ids);
1688 function _setReplies(array $replies)
1690 $this->_replies[$this->id] = $replies;
1694 * Pull the complete list of @-reply targets for this notice.
1696 * @return array of Profiles
1698 function getReplyProfiles()
1700 $ids = $this->getReplies();
1702 $profiles = Profile::multiGet('id', $ids);
1704 return $profiles->fetchAll();
1708 * Send e-mail notifications to local @-reply targets.
1710 * Replies must already have been saved; this is expected to be run
1711 * from the distrib queue handler.
1713 function sendReplyNotifications()
1715 // Don't send reply notifications for repeats
1717 if ($this->isRepeat()) {
1721 $recipientIds = $this->getReplies();
1722 if (Event::handle('StartNotifyMentioned', array($this, &$recipientIds))) {
1723 require_once INSTALLDIR.'/lib/mail.php';
1725 foreach ($recipientIds as $recipientId) {
1726 $user = User::getKV('id', $recipientId);
1727 if ($user instanceof User) {
1728 mail_notify_attn($user, $this);
1731 Event::handle('EndNotifyMentioned', array($this, $recipientIds));
1736 * Pull list of groups this notice needs to be delivered to,
1737 * as previously recorded by saveKnownGroups().
1739 * @return array of Group objects
1742 protected $_groups = array();
1744 function getGroups()
1746 // Don't save groups for repeats
1748 if (!empty($this->repeat_of)) {
1752 if (isset($this->_groups[$this->id])) {
1753 return $this->_groups[$this->id];
1756 $gis = Group_inbox::listGet('notice_id', array($this->id));
1760 foreach ($gis[$this->id] as $gi) {
1761 $ids[] = $gi->group_id;
1764 $groups = User_group::multiGet('id', $ids);
1765 $this->_setGroups($groups->fetchAll());
1766 return $this->_groups[$this->id];
1769 function _setGroups(array $groups)
1771 $this->_groups[$this->id] = $groups;
1775 * Convert a notice into an activity for export.
1777 * @param Profile $scoped The currently logged in/scoped profile
1779 * @return Activity activity object representing this Notice.
1782 function asActivity(Profile $scoped=null)
1784 $act = self::cacheGet(Cache::codeKey('notice:as-activity:'.$this->id));
1786 if ($act instanceof Activity) {
1789 $act = new Activity();
1791 if (Event::handle('StartNoticeAsActivity', array($this, $act, $scoped))) {
1793 $act->id = $this->uri;
1794 $act->time = strtotime($this->created);
1796 $act->link = $this->getUrl();
1797 } catch (InvalidUrlException $e) {
1798 // The notice is probably a share or similar, which don't
1799 // have a representational URL of their own.
1801 $act->content = common_xml_safe_str($this->rendered);
1803 $profile = $this->getProfile();
1805 $act->actor = $profile->asActivityObject();
1806 $act->actor->extra[] = $profile->profileInfo($scoped);
1808 $act->verb = $this->verb;
1810 if (!$this->repeat_of) {
1811 $act->objects[] = $this->asActivityObject();
1814 // XXX: should this be handled by default processing for object entry?
1818 $tags = $this->getTags();
1820 foreach ($tags as $tag) {
1821 $cat = new AtomCategory();
1824 $act->categories[] = $cat;
1828 // XXX: use Atom Media and/or File activity objects instead
1830 $attachments = $this->attachments();
1832 foreach ($attachments as $attachment) {
1833 // Include local attachments in Activity
1834 if (!empty($attachment->filename)) {
1835 $act->enclosures[] = $attachment->getEnclosure();
1839 $ctx = new ActivityContext();
1842 $reply = $this->getParent();
1843 $ctx->replyToID = $reply->getUri();
1844 $ctx->replyToUrl = $reply->getUrl(true); // true for fallback to local URL, less messy
1845 } catch (NoParentNoticeException $e) {
1846 // This is not a reply to something
1849 $ctx->location = $this->getLocation();
1853 if (!empty($this->conversation)) {
1854 $conv = Conversation::getKV('id', $this->conversation);
1855 if ($conv instanceof Conversation) {
1856 $ctx->conversation = $conv->uri;
1860 $reply_ids = $this->getReplies();
1862 foreach ($reply_ids as $id) {
1863 $rprofile = Profile::getKV('id', $id);
1864 if ($rprofile instanceof Profile) {
1865 $ctx->attention[$rprofile->getUri()] = ActivityObject::PERSON;
1869 $groups = $this->getGroups();
1871 foreach ($groups as $group) {
1872 $ctx->attention[$group->getUri()] = ActivityObject::GROUP;
1875 switch ($this->scope) {
1876 case Notice::PUBLIC_SCOPE:
1877 $ctx->attention[ActivityContext::ATTN_PUBLIC] = ActivityObject::COLLECTION;
1879 case Notice::FOLLOWER_SCOPE:
1880 $surl = common_local_url("subscribers", array('nickname' => $profile->nickname));
1881 $ctx->attention[$surl] = ActivityObject::COLLECTION;
1885 $act->context = $ctx;
1887 $source = $this->getSource();
1889 if ($source instanceof Notice_source) {
1890 $act->generator = ActivityObject::fromNoticeSource($source);
1895 $atom_feed = $profile->getAtomFeed();
1897 if (!empty($atom_feed)) {
1899 $act->source = new ActivitySource();
1901 // XXX: we should store the actual feed ID
1903 $act->source->id = $atom_feed;
1905 // XXX: we should store the actual feed title
1907 $act->source->title = $profile->getBestName();
1909 $act->source->links['alternate'] = $profile->profileurl;
1910 $act->source->links['self'] = $atom_feed;
1912 $act->source->icon = $profile->avatarUrl(AVATAR_PROFILE_SIZE);
1914 $notice = $profile->getCurrentNotice();
1916 if ($notice instanceof Notice) {
1917 $act->source->updated = self::utcDate($notice->created);
1920 $user = User::getKV('id', $profile->id);
1922 if ($user instanceof User) {
1923 $act->source->links['license'] = common_config('license', 'url');
1927 if ($this->isLocal()) {
1928 $act->selfLink = common_local_url('ApiStatusesShow', array('id' => $this->id,
1929 'format' => 'atom'));
1930 $act->editLink = $act->selfLink;
1933 Event::handle('EndNoticeAsActivity', array($this, $act, $scoped));
1936 self::cacheSet(Cache::codeKey('notice:as-activity:'.$this->id), $act);
1941 // This has gotten way too long. Needs to be sliced up into functional bits
1942 // or ideally exported to a utility class.
1944 function asAtomEntry($namespace=false,
1947 Profile $scoped=null)
1949 $act = $this->asActivity($scoped);
1950 $act->extra[] = $this->noticeInfo($scoped);
1951 return $act->asString($namespace, $author, $source);
1955 * Extra notice info for atom entries
1957 * Clients use some extra notice info in the atom stream.
1958 * This gives it to them.
1960 * @param Profile $scoped The currently logged in/scoped profile
1962 * @return array representation of <statusnet:notice_info> element
1965 function noticeInfo(Profile $scoped=null)
1967 // local notice ID (useful to clients for ordering)
1969 $noticeInfoAttr = array('local_id' => $this->id);
1973 $ns = $this->getSource();
1975 if ($ns instanceof Notice_source) {
1976 $noticeInfoAttr['source'] = $ns->code;
1977 if (!empty($ns->url)) {
1978 $noticeInfoAttr['source_link'] = $ns->url;
1979 if (!empty($ns->name)) {
1980 $noticeInfoAttr['source'] = '<a href="'
1981 . htmlspecialchars($ns->url)
1982 . '" rel="nofollow">'
1983 . htmlspecialchars($ns->name)
1989 // favorite and repeated
1991 if ($scoped instanceof Profile) {
1992 $noticeInfoAttr['repeated'] = ($scoped->hasRepeated($this)) ? "true" : "false";
1995 if (!empty($this->repeat_of)) {
1996 $noticeInfoAttr['repeat_of'] = $this->repeat_of;
1999 Event::handle('StatusNetApiNoticeInfo', array($this, &$noticeInfoAttr, $scoped));
2001 return array('statusnet:notice_info', $noticeInfoAttr, null);
2005 * Returns an XML string fragment with a reference to a notice as an
2006 * Activity Streams noun object with the given element type.
2008 * Assumes that 'activity' namespace has been previously defined.
2010 * @param string $element one of 'subject', 'object', 'target'
2014 function asActivityNoun($element)
2016 $noun = $this->asActivityObject();
2017 return $noun->asString('activity:' . $element);
2020 public function asActivityObject()
2022 $object = new ActivityObject();
2024 if (Event::handle('StartActivityObjectFromNotice', array($this, &$object))) {
2025 $object->type = $this->object_type ?: ActivityObject::NOTE;
2026 $object->id = $this->getUri();
2027 $object->title = sprintf('New %1$s by %2$s', ActivityObject::canonicalType($object->type), $this->getProfile()->getNickname());
2028 $object->content = $this->rendered;
2029 $object->link = $this->getUrl();
2031 $object->extra[] = array('status_net', array('notice_id' => $this->id));
2033 Event::handle('EndActivityObjectFromNotice', array($this, &$object));
2040 * Determine which notice, if any, a new notice is in reply to.
2042 * For conversation tracking, we try to see where this notice fits
2043 * in the tree. Beware that this may very well give false positives
2044 * and add replies to wrong threads (if there have been newer posts
2045 * by the same user as we're replying to).
2047 * @param Profile $sender Author profile
2048 * @param string $content Final notice content
2050 * @return integer ID of replied-to notice, or null for not a reply.
2053 static function getInlineReplyTo(Profile $sender, $content)
2055 // Is there an initial @ or T?
2056 if (preg_match('/^T ([A-Z0-9]{1,64}) /', $content, $match)
2057 || preg_match('/^@([a-z0-9]{1,64})\s+/', $content, $match)) {
2058 $nickname = common_canonical_nickname($match[1]);
2063 // Figure out who that is.
2064 $recipient = common_relative_profile($sender, $nickname, common_sql_now());
2066 if ($recipient instanceof Profile) {
2067 // Get their last notice
2068 $last = $recipient->getCurrentNotice();
2069 if ($last instanceof Notice) {
2072 // Maybe in the future we want to handle something else below
2073 // so don't return getCurrentNotice() immediately.
2079 static function maxContent()
2081 $contentlimit = common_config('notice', 'contentlimit');
2082 // null => use global limit (distinct from 0!)
2083 if (is_null($contentlimit)) {
2084 $contentlimit = common_config('site', 'textlimit');
2086 return $contentlimit;
2089 static function contentTooLong($content)
2091 $contentlimit = self::maxContent();
2092 return ($contentlimit > 0 && !empty($content) && (mb_strlen($content) > $contentlimit));
2095 function getLocation()
2099 if (!empty($this->location_id) && !empty($this->location_ns)) {
2100 $location = Location::fromId($this->location_id, $this->location_ns);
2103 if (is_null($location)) { // no ID, or Location::fromId() failed
2104 if (!empty($this->lat) && !empty($this->lon)) {
2105 $location = Location::fromLatLon($this->lat, $this->lon);
2113 * Convenience function for posting a repeat of an existing message.
2115 * @param Profile $repeater Profile which is doing the repeat
2116 * @param string $source: posting source key, eg 'web', 'api', etc
2119 * @throws Exception on failure or permission problems
2121 function repeat(Profile $repeater, $source)
2123 $author = $this->getProfile();
2125 // TRANS: Message used to repeat a notice. RT is the abbreviation of 'retweet'.
2126 // TRANS: %1$s is the repeated user's name, %2$s is the repeated notice.
2127 $content = sprintf(_('RT @%1$s %2$s'),
2128 $author->getNickname(),
2131 $maxlen = self::maxContent();
2132 if ($maxlen > 0 && mb_strlen($content) > $maxlen) {
2133 // Web interface and current Twitter API clients will
2134 // pull the original notice's text, but some older
2135 // clients and RSS/Atom feeds will see this trimmed text.
2137 // Unfortunately this is likely to lose tags or URLs
2138 // at the end of long notices.
2139 $content = mb_substr($content, 0, $maxlen - 4) . ' ...';
2143 // Scope is same as this one's
2144 return self::saveNew($repeater->id,
2147 array('repeat_of' => $this->id,
2148 'scope' => $this->scope));
2151 // These are supposed to be in chron order!
2153 function repeatStream($limit=100)
2155 $cache = Cache::instance();
2157 if (empty($cache)) {
2158 $ids = $this->_repeatStreamDirect($limit);
2160 $idstr = $cache->get(Cache::key('notice:repeats:'.$this->id));
2161 if ($idstr !== false) {
2162 if (empty($idstr)) {
2165 $ids = explode(',', $idstr);
2168 $ids = $this->_repeatStreamDirect(100);
2169 $cache->set(Cache::key('notice:repeats:'.$this->id), implode(',', $ids));
2172 // We do a max of 100, so slice down to limit
2173 $ids = array_slice($ids, 0, $limit);
2177 return NoticeStream::getStreamByIds($ids);
2180 function _repeatStreamDirect($limit)
2182 $notice = new Notice();
2184 $notice->selectAdd(); // clears it
2185 $notice->selectAdd('id');
2187 $notice->repeat_of = $this->id;
2189 $notice->orderBy('created, id'); // NB: asc!
2191 if (!is_null($limit)) {
2192 $notice->limit(0, $limit);
2195 return $notice->fetchAll('id');
2198 function locationOptions($lat, $lon, $location_id, $location_ns, $profile = null)
2202 if (!empty($location_id) && !empty($location_ns)) {
2203 $options['location_id'] = $location_id;
2204 $options['location_ns'] = $location_ns;
2206 $location = Location::fromId($location_id, $location_ns);
2208 if ($location instanceof Location) {
2209 $options['lat'] = $location->lat;
2210 $options['lon'] = $location->lon;
2213 } else if (!empty($lat) && !empty($lon)) {
2214 $options['lat'] = $lat;
2215 $options['lon'] = $lon;
2217 $location = Location::fromLatLon($lat, $lon);
2219 if ($location instanceof Location) {
2220 $options['location_id'] = $location->location_id;
2221 $options['location_ns'] = $location->location_ns;
2223 } else if (!empty($profile)) {
2224 if (isset($profile->lat) && isset($profile->lon)) {
2225 $options['lat'] = $profile->lat;
2226 $options['lon'] = $profile->lon;
2229 if (isset($profile->location_id) && isset($profile->location_ns)) {
2230 $options['location_id'] = $profile->location_id;
2231 $options['location_ns'] = $profile->location_ns;
2238 function clearAttentions()
2240 $att = new Attention();
2241 $att->notice_id = $this->getID();
2244 while ($att->fetch()) {
2245 // Can't do delete() on the object directly since it won't remove all of it
2246 $other = clone($att);
2252 function clearReplies()
2254 $replyNotice = new Notice();
2255 $replyNotice->reply_to = $this->id;
2257 //Null any notices that are replies to this notice
2259 if ($replyNotice->find()) {
2260 while ($replyNotice->fetch()) {
2261 $orig = clone($replyNotice);
2262 $replyNotice->reply_to = null;
2263 $replyNotice->update($orig);
2269 $reply = new Reply();
2270 $reply->notice_id = $this->id;
2272 if ($reply->find()) {
2273 while($reply->fetch()) {
2274 self::blow('reply:stream:%d', $reply->profile_id);
2282 function clearFiles()
2284 $f2p = new File_to_post();
2286 $f2p->post_id = $this->id;
2289 while ($f2p->fetch()) {
2293 // FIXME: decide whether to delete File objects
2294 // ...and related (actual) files
2297 function clearRepeats()
2299 $repeatNotice = new Notice();
2300 $repeatNotice->repeat_of = $this->id;
2302 //Null any notices that are repeats of this notice
2304 if ($repeatNotice->find()) {
2305 while ($repeatNotice->fetch()) {
2306 $orig = clone($repeatNotice);
2307 $repeatNotice->repeat_of = null;
2308 $repeatNotice->update($orig);
2313 function clearTags()
2315 $tag = new Notice_tag();
2316 $tag->notice_id = $this->id;
2319 while ($tag->fetch()) {
2320 self::blow('profile:notice_ids_tagged:%d:%s', $this->profile_id, Cache::keyize($tag->tag));
2321 self::blow('profile:notice_ids_tagged:%d:%s;last', $this->profile_id, Cache::keyize($tag->tag));
2322 self::blow('notice_tag:notice_ids:%s', Cache::keyize($tag->tag));
2323 self::blow('notice_tag:notice_ids:%s;last', Cache::keyize($tag->tag));
2331 function clearGroupInboxes()
2333 $gi = new Group_inbox();
2335 $gi->notice_id = $this->id;
2338 while ($gi->fetch()) {
2339 self::blow('user_group:notice_ids:%d', $gi->group_id);
2347 function distribute()
2349 // We always insert for the author so they don't
2351 Event::handle('StartNoticeDistribute', array($this));
2353 // If there's a failure, we want to _force_
2354 // distribution at this point.
2356 $qm = QueueManager::get();
2357 $qm->enqueue($this, 'distrib');
2358 } catch (Exception $e) {
2359 // If the exception isn't transient, this
2360 // may throw more exceptions as DQH does
2361 // its own enqueueing. So, we ignore them!
2363 $handler = new DistribQueueHandler();
2364 $handler->handle($this);
2365 } catch (Exception $e) {
2366 common_log(LOG_ERR, "emergency redistribution resulted in " . $e->getMessage());
2368 // Re-throw so somebody smarter can handle it.
2375 $result = parent::insert();
2377 if ($result === false) {
2378 common_log_db_error($this, 'INSERT', __FILE__);
2379 // TRANS: Server exception thrown when a stored object entry cannot be saved.
2380 throw new ServerException('Could not save Notice');
2383 // Profile::hasRepeated() abuses pkeyGet(), so we
2384 // have to clear manually
2385 if (!empty($this->repeat_of)) {
2386 $c = self::memcache();
2388 $ck = self::multicacheKey('Notice',
2389 array('profile_id' => $this->profile_id,
2390 'repeat_of' => $this->repeat_of));
2395 // Update possibly ID-dependent columns: URI, conversation
2396 // (now that INSERT has added the notice's local id)
2397 $orig = clone($this);
2400 // We can only get here if it's a local notice, since remote notices
2401 // should've bailed out earlier due to lacking a URI.
2402 if (empty($this->uri)) {
2403 $this->uri = sprintf('%s%s=%d:%s=%s',
2405 'noticeId', $this->id,
2406 'objectType', $this->get_object_type(true));
2410 if ($changed && $this->update($orig) === false) {
2411 common_log_db_error($notice, 'UPDATE', __FILE__);
2412 // TRANS: Server exception thrown when a notice cannot be updated.
2413 throw new ServerException(_('Problem saving notice.'));
2416 $this->blowOnInsert();
2422 * Get the source of the notice
2424 * @return Notice_source $ns A notice source object. 'code' is the only attribute
2425 * guaranteed to be populated.
2427 function getSource()
2429 if (empty($this->source)) {
2433 $ns = new Notice_source();
2434 switch ($this->source) {
2441 $ns->code = $this->source;
2444 $ns = Notice_source::getKV($this->source);
2446 $ns = new Notice_source();
2447 $ns->code = $this->source;
2448 $app = Oauth_application::getKV('name', $this->source);
2450 $ns->name = $app->name;
2451 $ns->url = $app->source_url;
2461 * Determine whether the notice was locally created
2463 * @return boolean locality
2466 public function isLocal()
2468 return ($this->is_local == Notice::LOCAL_PUBLIC ||
2469 $this->is_local == Notice::LOCAL_NONPUBLIC);
2472 public function isRepeat()
2474 return !empty($this->repeat_of);
2478 * Get the list of hash tags saved with this notice.
2480 * @return array of strings
2482 public function getTags()
2484 // Check default scope (non-private notices)
2485 $inScope = (!$this->isPrivateScope());
2487 // Get current profile
2488 $profile = Profile::current();
2490 // Is the general scope check okay and the user in logged in?
2491 //* NOISY-DEBUG: */ common_debug('[' . __METHOD__ . ':' . __LINE__ . ']: inScope=' . intval($inScope) . ',profile[]=' . gettype($profile));
2492 if (($inScope === TRUE) && ($profile instanceof Profile)) {
2494 * Check scope, else a privacy leaks happens this way:
2496 * 1) Bob and Alice follow each other and write private notices
2497 * (this->scope=2) to each other.
2498 * 2) Bob uses tags in his private notice to alice (which she can
2500 * 3) Alice adds that notice (with tags) to her favorites
2502 * 4) The tags from Bob's private notice becomes visible in Alice's
2505 * This has the simple background that the scope is not being
2506 * re-checked. This has to be done here at this point because given
2507 * above scenario is a privacy leak as the tags may be *really*
2508 * private (nobody else shall see them) such as initmate words or
2509 * very political words.
2511 $inScope = $this->inScope($profile);
2512 //* NOISY-DEBUG: */ common_debug('[' . __METHOD__ . ':' . __LINE__ . ']: inScope=' . intval($inScope) . ' - After inScope() has been called.');
2517 $keypart = sprintf('notice:tags:%d', $this->id);
2519 $tagstr = self::cacheGet($keypart);
2521 if ($tagstr !== false) {
2522 $tags = explode(',', $tagstr);
2524 $tag = new Notice_tag();
2525 $tag->notice_id = $this->id;
2527 // Check scope for privacy-leak protection (see some lines above why)
2528 if (($inScope === TRUE) && ($tag->find())) {
2529 while ($tag->fetch()) {
2530 $tags[] = $tag->tag;
2533 self::cacheSet($keypart, implode(',', $tags));
2539 static private function utcDate($dt)
2541 $dateStr = date('d F Y H:i:s', strtotime($dt));
2542 $d = new DateTime($dateStr, new DateTimeZone('UTC'));
2543 return $d->format(DATE_W3C);
2547 * Look up the creation timestamp for a given notice ID, even
2548 * if it's been deleted.
2551 * @return mixed string recorded creation timestamp, or false if can't be found
2553 public static function getAsTimestamp($id)
2559 $notice = Notice::getKV('id', $id);
2561 return $notice->created;
2564 $deleted = Deleted_notice::getKV('id', $id);
2566 return $deleted->created;
2573 * Build an SQL 'where' fragment for timestamp-based sorting from a since_id
2574 * parameter, matching notices posted after the given one (exclusive).
2576 * If the referenced notice can't be found, will return false.
2579 * @param string $idField
2580 * @param string $createdField
2581 * @return mixed string or false if no match
2583 public static function whereSinceId($id, $idField='id', $createdField='created')
2585 $since = Notice::getAsTimestamp($id);
2587 return sprintf("($createdField = '%s' and $idField > %d) or ($createdField > '%s')", $since, $id, $since);
2593 * Build an SQL 'where' fragment for timestamp-based sorting from a since_id
2594 * parameter, matching notices posted after the given one (exclusive), and
2595 * if necessary add it to the data object's query.
2597 * @param DB_DataObject $obj
2599 * @param string $idField
2600 * @param string $createdField
2601 * @return mixed string or false if no match
2603 public static function addWhereSinceId(DB_DataObject $obj, $id, $idField='id', $createdField='created')
2605 $since = self::whereSinceId($id, $idField, $createdField);
2607 $obj->whereAdd($since);
2612 * Build an SQL 'where' fragment for timestamp-based sorting from a max_id
2613 * parameter, matching notices posted before the given one (inclusive).
2615 * If the referenced notice can't be found, will return false.
2618 * @param string $idField
2619 * @param string $createdField
2620 * @return mixed string or false if no match
2622 public static function whereMaxId($id, $idField='id', $createdField='created')
2624 $max = Notice::getAsTimestamp($id);
2626 return sprintf("($createdField < '%s') or ($createdField = '%s' and $idField <= %d)", $max, $max, $id);
2632 * Build an SQL 'where' fragment for timestamp-based sorting from a max_id
2633 * parameter, matching notices posted before the given one (inclusive), and
2634 * if necessary add it to the data object's query.
2636 * @param DB_DataObject $obj
2638 * @param string $idField
2639 * @param string $createdField
2640 * @return mixed string or false if no match
2642 public static function addWhereMaxId(DB_DataObject $obj, $id, $idField='id', $createdField='created')
2644 $max = self::whereMaxId($id, $idField, $createdField);
2646 $obj->whereAdd($max);
2652 return (($this->is_local != Notice::LOCAL_NONPUBLIC) &&
2653 ($this->is_local != Notice::GATEWAY));
2656 public function isPrivateScope () {
2657 return ($this->scope != Notice::SITE_SCOPE &&
2658 $this->scope != Notice::PUBLIC_SCOPE);
2662 * Check that the given profile is allowed to read, respond to, or otherwise
2663 * act on this notice.
2665 * The $scope member is a bitmask of scopes, representing a logical AND of the
2666 * scope requirement. So, 0x03 (Notice::ADDRESSEE_SCOPE | Notice::SITE_SCOPE) means
2667 * "only visible to people who are mentioned in the notice AND are users on this site."
2668 * Users on the site who are not mentioned in the notice will not be able to see the
2671 * @param Profile $profile The profile to check; pass null to check for public/unauthenticated users.
2673 * @return boolean whether the profile is in the notice's scope
2675 function inScope(Profile $profile=null)
2677 if (is_null($profile)) {
2678 $keypart = sprintf('notice:in-scope-for:%d:null', $this->id);
2680 $keypart = sprintf('notice:in-scope-for:%d:%d', $this->id, $profile->id);
2683 $result = self::cacheGet($keypart);
2685 if ($result === false) {
2687 if (Event::handle('StartNoticeInScope', array($this, $profile, &$bResult))) {
2688 $bResult = $this->_inScope($profile);
2689 Event::handle('EndNoticeInScope', array($this, $profile, &$bResult));
2691 $result = ($bResult) ? 1 : 0;
2692 self::cacheSet($keypart, $result, 0, 300);
2695 return ($result == 1) ? true : false;
2698 protected function _inScope(Profile $profile=null)
2700 if (!is_null($this->scope)) {
2701 $scope = $this->scope;
2703 $scope = self::defaultScope();
2706 if ($scope == 0 && !$this->getProfile()->isPrivateStream()) { // Not scoping, so it is public.
2707 return !$this->isHiddenSpam($profile);
2710 // If there's scope, anon cannot be in scope
2711 if (empty($profile)) {
2715 // Author is always in scope
2716 if ($this->profile_id == $profile->id) {
2720 // Only for users on this site
2721 if (($scope & Notice::SITE_SCOPE) && !$profile->isLocal()) {
2725 // Only for users mentioned in the notice
2726 if ($scope & Notice::ADDRESSEE_SCOPE) {
2728 $reply = Reply::pkeyGet(array('notice_id' => $this->id,
2729 'profile_id' => $profile->id));
2731 if (!$reply instanceof Reply) {
2736 // Only for members of the given group
2737 if ($scope & Notice::GROUP_SCOPE) {
2739 // XXX: just query for the single membership
2741 $groups = $this->getGroups();
2745 foreach ($groups as $group) {
2746 if ($profile->isMember($group)) {
2757 if ($scope & Notice::FOLLOWER_SCOPE || $this->getProfile()->isPrivateStream()) {
2759 if (!Subscription::exists($profile, $this->getProfile())) {
2764 return !$this->isHiddenSpam($profile);
2767 function isHiddenSpam(Profile $profile=null) {
2769 // Hide posts by silenced users from everyone but moderators.
2771 if (common_config('notice', 'hidespam')) {
2774 $author = $this->getProfile();
2775 } catch(Exception $e) {
2776 // If we can't get an author, keep it hidden.
2777 // XXX: technically not spam, but, whatever.
2781 if ($author->hasRole(Profile_role::SILENCED)) {
2782 if (!$profile instanceof Profile || (($profile->id !== $author->id) && (!$profile->hasRight(Right::REVIEWSPAM)))) {
2791 public function getParent()
2793 if (empty($this->reply_to)) {
2794 throw new NoParentNoticeException($this);
2796 return self::getByID($this->reply_to);
2800 * Magic function called at serialize() time.
2802 * We use this to drop a couple process-specific references
2803 * from DB_DataObject which can cause trouble in future
2806 * @return array of variable names to include in serialization.
2811 $vars = parent::__sleep();
2812 $skip = array('_profile', '_groups', '_attachments', '_faves', '_replies', '_repeats');
2813 return array_diff($vars, $skip);
2816 static function defaultScope()
2818 $scope = common_config('notice', 'defaultscope');
2819 if (is_null($scope)) {
2820 if (common_config('site', 'private')) {
2829 static function fillProfiles(array $notices)
2831 $map = self::getProfiles($notices);
2832 foreach ($notices as $entry=>$notice) {
2834 if (array_key_exists($notice->profile_id, $map)) {
2835 $notice->_setProfile($map[$notice->profile_id]);
2837 } catch (NoProfileException $e) {
2838 common_log(LOG_WARNING, "Failed to fill profile in Notice with non-existing entry for profile_id: {$e->profile_id}");
2839 unset($notices[$entry]);
2843 return array_values($map);
2846 static function getProfiles(array &$notices)
2849 foreach ($notices as $notice) {
2850 $ids[] = $notice->profile_id;
2852 $ids = array_unique($ids);
2853 return Profile::pivotGet('id', $ids);
2856 static function fillGroups(array &$notices)
2858 $ids = self::_idsOf($notices);
2859 $gis = Group_inbox::listGet('notice_id', $ids);
2862 foreach ($gis as $id => $gi) {
2865 $gids[] = $g->group_id;
2869 $gids = array_unique($gids);
2870 $group = User_group::pivotGet('id', $gids);
2871 foreach ($notices as $notice)
2874 $gi = $gis[$notice->id];
2875 foreach ($gi as $g) {
2876 $grps[] = $group[$g->group_id];
2878 $notice->_setGroups($grps);
2882 static function _idsOf(array &$notices)
2885 foreach ($notices as $notice) {
2886 $ids[$notice->id] = true;
2888 return array_keys($ids);
2891 static function fillAttachments(array &$notices)
2893 $ids = self::_idsOf($notices);
2894 $f2pMap = File_to_post::listGet('post_id', $ids);
2896 foreach ($f2pMap as $noticeId => $f2ps) {
2897 foreach ($f2ps as $f2p) {
2898 $fileIds[] = $f2p->file_id;
2902 $fileIds = array_unique($fileIds);
2903 $fileMap = File::pivotGet('id', $fileIds);
2904 foreach ($notices as $notice)
2907 $f2ps = $f2pMap[$notice->id];
2908 foreach ($f2ps as $f2p) {
2909 $files[] = $fileMap[$f2p->file_id];
2911 $notice->_setAttachments($files);
2915 static function fillReplies(array &$notices)
2917 $ids = self::_idsOf($notices);
2918 $replyMap = Reply::listGet('notice_id', $ids);
2919 foreach ($notices as $notice) {
2920 $replies = $replyMap[$notice->id];
2922 foreach ($replies as $reply) {
2923 $ids[] = $reply->profile_id;
2925 $notice->_setReplies($ids);
2930 * Checks whether the current profile is allowed (in scope) to see this notice.
2932 * @return $inScope Whether the current profile is allowed to see this notice
2934 function isCurrentProfileInScope () {
2935 // Check scope, default is allowed
2938 //* NOISY-DEBUG: */ common_debug('[' . __METHOD__ . ':' . __LINE__ . '] this->tag=' . $this->tag . ',this->id=' . $this->id . ',this->scope=' . $this->scope);
2940 // Is it private scope?
2941 if ($this->isPrivateScope()) {
2942 // 2) Get current profile
2943 $profile = Profile::current();
2945 // Is the profile not set?
2946 if (!$profile instanceof Profile) {
2947 // Public viewer shall not see a tag from a private dent (privacy leak)
2948 //* NOISY-DEBUG: */ common_debug('[' . __METHOD__ . ':' . __LINE__ . '] Not logged in (public view).');
2950 } elseif (!$this->inScope($profile)) {
2951 // Current profile is not in scope (not allowed to see) of notice
2952 //* NOISY-DEBUG: */ common_debug('[' . __METHOD__ . ':' . __LINE__ . '] profile->id=' . $profile->id . ' is not allowed to see this notice.');
2958 //* NOISY-DEBUG: */ common_debug('[' . __METHOD__ . ':' . __LINE__ . '] this->tag=' . $this->tag . ',this->weight=' . $this->weight . ',inScope=' . intval($inScope) . ' - EXIT!');