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 $repeat_of; // int(4)
69 public $verb; // varchar(191) not 255 because utf8mb4 takes more space
70 public $object_type; // varchar(191) not 255 because utf8mb4 takes more space
71 public $scope; // int(4)
73 /* the code above is auto generated do not remove the tag below */
76 public static function schemaDef()
80 'id' => array('type' => 'serial', 'not null' => true, 'description' => 'unique identifier'),
81 'profile_id' => array('type' => 'int', 'not null' => true, 'description' => 'who made the update'),
82 'uri' => array('type' => 'varchar', 'length' => 191, 'description' => 'universally unique identifier, usually a tag URI'),
83 'content' => array('type' => 'text', 'description' => 'update content', 'collate' => 'utf8mb4_general_ci'),
84 'rendered' => array('type' => 'text', 'description' => 'HTML version of the content'),
85 'url' => array('type' => 'varchar', 'length' => 191, 'description' => 'URL of any attachment (image, video, bookmark, whatever)'),
86 'created' => array('type' => 'datetime', 'not null' => true, 'description' => 'date this record was created'),
87 'modified' => array('type' => 'timestamp', 'not null' => true, 'description' => 'date this record was modified'),
88 'reply_to' => array('type' => 'int', 'description' => 'notice replied to (usually a guess)'),
89 'is_local' => array('type' => 'int', 'size' => 'tiny', 'default' => 0, 'description' => 'notice was generated by a user'),
90 'source' => array('type' => 'varchar', 'length' => 32, 'description' => 'source of comment, like "web", "im", or "clientname"'),
91 'conversation' => array('type' => 'int', 'description' => 'id of root notice in this conversation'),
92 'repeat_of' => array('type' => 'int', 'description' => 'notice this is a repeat of'),
93 'object_type' => array('type' => 'varchar', 'length' => 191, 'description' => 'URI representing activity streams object type', 'default' => 'http://activitystrea.ms/schema/1.0/note'),
94 'verb' => array('type' => 'varchar', 'length' => 191, 'description' => 'URI representing activity streams verb', 'default' => 'http://activitystrea.ms/schema/1.0/post'),
95 'scope' => array('type' => 'int',
96 'description' => 'bit map for distribution scope; 0 = everywhere; 1 = this server only; 2 = addressees; 4 = followers; null = default'),
98 'primary key' => array('id'),
99 'unique keys' => array(
100 'notice_uri_key' => array('uri'),
102 'foreign keys' => array(
103 'notice_profile_id_fkey' => array('profile', array('profile_id' => 'id')),
104 'notice_reply_to_fkey' => array('notice', array('reply_to' => 'id')),
105 'notice_conversation_fkey' => array('conversation', array('conversation' => 'id')), # note... used to refer to notice.id
106 'notice_repeat_of_fkey' => array('notice', array('repeat_of' => 'id')), # @fixme: what about repeats of deleted notices?
109 'notice_created_id_is_local_idx' => array('created', 'id', 'is_local'),
110 'notice_profile_id_idx' => array('profile_id', 'created', 'id'),
111 'notice_repeat_of_created_id_idx' => array('repeat_of', 'created', 'id'),
112 'notice_conversation_created_id_idx' => array('conversation', 'created', 'id'),
113 'notice_replyto_idx' => array('reply_to')
117 if (common_config('search', 'type') == 'fulltext') {
118 $def['fulltext indexes'] = array('content' => array('content'));
125 const LOCAL_PUBLIC = 1;
127 const LOCAL_NONPUBLIC = -1;
130 const PUBLIC_SCOPE = 0; // Useful fake constant
131 const SITE_SCOPE = 1;
132 const ADDRESSEE_SCOPE = 2;
133 const GROUP_SCOPE = 4;
134 const FOLLOWER_SCOPE = 8;
136 protected $_profile = array();
139 * Will always return a profile, if anything fails it will
140 * (through _setProfile) throw a NoProfileException.
142 public function getProfile()
144 if (!isset($this->_profile[$this->profile_id])) {
145 // We could've sent getKV directly to _setProfile, but occasionally we get
146 // a "false" (instead of null), likely because it indicates a cache miss.
147 $profile = Profile::getKV('id', $this->profile_id);
148 $this->_setProfile($profile instanceof Profile ? $profile : null);
150 return $this->_profile[$this->profile_id];
153 public function _setProfile(Profile $profile=null)
155 if (!$profile instanceof Profile) {
156 throw new NoProfileException($this->profile_id);
158 $this->_profile[$this->profile_id] = $profile;
161 function delete($useWhere=false)
163 // For auditing purposes, save a record that the notice
166 // @fixme we have some cases where things get re-run and so the
168 $deleted = Deleted_notice::getKV('id', $this->id);
170 if (!$deleted instanceof Deleted_notice) {
171 $deleted = Deleted_notice::getKV('uri', $this->uri);
174 if (!$deleted instanceof Deleted_notice) {
175 $deleted = new Deleted_notice();
177 $deleted->id = $this->id;
178 $deleted->profile_id = $this->profile_id;
179 $deleted->uri = $this->uri;
180 $deleted->created = $this->created;
181 $deleted->deleted = common_sql_now();
186 if (Event::handle('NoticeDeleteRelated', array($this))) {
188 // Clear related records
190 $this->clearReplies();
191 $this->clearLocation();
192 $this->clearRepeats();
194 $this->clearGroupInboxes();
196 $this->clearAttentions();
198 // NOTE: we don't clear queue items
201 $result = parent::delete($useWhere);
203 $this->blowOnDelete();
207 public function getUri()
213 * Get a Notice object by URI. Will call external plugins for help
214 * using the event StartGetNoticeFromURI.
216 * @param string $uri A unique identifier for a resource (notice in this case)
218 static function fromUri($uri)
222 if (Event::handle('StartGetNoticeFromUri', array($uri, &$notice))) {
223 $notice = Notice::getKV('uri', $uri);
224 Event::handle('EndGetNoticeFromUri', array($uri, $notice));
227 if (!$notice instanceof Notice) {
228 throw new UnknownUriException($uri);
235 * @param $root boolean If true, link to just the conversation root.
237 * @return URL to conversation
239 public function getConversationUrl($anchor=true)
241 return Conversation::getUrlFromNotice($this, $anchor);
245 * Get the local representation URL of this notice.
247 public function getLocalUrl()
249 return common_local_url('shownotice', array('notice' => $this->id), null, null, false);
252 public function getTitle()
255 if (Event::handle('GetNoticeTitle', array($this, &$title))) {
256 // TRANS: Title of a notice posted without a title value.
257 // TRANS: %1$s is a user name, %2$s is the notice creation date/time.
258 $title = sprintf(_('%1$s\'s status on %2$s'),
259 $this->getProfile()->getFancyName(),
260 common_exact_date($this->created));
265 public function getContent()
267 return $this->content;
271 * Get the original representation URL of this notice.
273 * @param boolean $fallback Whether to fall back to generate a local URL or throw InvalidUrlException
275 public function getUrl($fallback=false)
277 // The risk is we start having empty urls and non-http uris...
278 // and we can't really handle any other protocol right now.
280 case common_valid_http_url($this->url): // should we allow non-http/https URLs?
282 case !$this->isLocal() && common_valid_http_url($this->uri): // Sometimes we only have the URI for remote posts.
284 case $this->isLocal() || $fallback:
285 // let's generate a valid link to our locally available notice on demand
286 return common_local_url('shownotice', array('notice' => $this->id), null, null, false);
288 common_debug('No URL available for notice: id='.$this->id);
289 throw new InvalidUrlException($this->url);
293 public function get_object_type($canonical=false) {
295 ? ActivityObject::canonicalType($this->object_type)
296 : $this->object_type;
299 public static function getByUri($uri)
301 $notice = new Notice();
303 if (!$notice->find(true)) {
304 throw new NoResultException($notice);
310 * Extract #hashtags from this notice's content and save them to the database.
314 /* extract all #hastags */
315 $count = preg_match_all('/(?:^|\s)#([\pL\pN_\-\.]{1,64})/u', strtolower($this->content), $match);
320 /* Add them to the database */
321 return $this->saveKnownTags($match[1]);
325 * Record the given set of hash tags in the db for this notice.
326 * Given tag strings will be normalized and checked for dupes.
328 function saveKnownTags(array $hashtags)
330 //turn each into their canonical tag
331 //this is needed to remove dupes before saving e.g. #hash.tag = #hashtag
332 for($i=0; $i<count($hashtags); $i++) {
333 /* elide characters we don't want in the tag */
334 $hashtags[$i] = common_canonical_tag($hashtags[$i]);
337 foreach(array_unique($hashtags) as $hashtag) {
338 $this->saveTag($hashtag);
339 self::blow('profile:notice_ids_tagged:%d:%s', $this->profile_id, $hashtag);
345 * Record a single hash tag as associated with this notice.
346 * Tag format and uniqueness must be validated by caller.
348 function saveTag($hashtag)
350 $tag = new Notice_tag();
351 $tag->notice_id = $this->id;
352 $tag->tag = $hashtag;
353 $tag->created = $this->created;
354 $id = $tag->insert();
357 // TRANS: Server exception. %s are the error details.
358 throw new ServerException(sprintf(_('Database error inserting hashtag: %s.'),
359 $last_error->message));
363 // if it's saved, blow its cache
364 $tag->blowCache(false);
368 * Save a new notice and push it out to subscribers' inboxes.
369 * Poster's permissions are checked before sending.
371 * @param int $profile_id Profile ID of the poster
372 * @param string $content source message text; links may be shortened
373 * per current user's preference
374 * @param string $source source key ('web', 'api', etc)
375 * @param array $options Associative array of optional properties:
376 * string 'created' timestamp of notice; defaults to now
377 * int 'is_local' source/gateway ID, one of:
378 * Notice::LOCAL_PUBLIC - Local, ok to appear in public timeline
379 * Notice::REMOTE - Sent from a remote service;
380 * hide from public timeline but show in
381 * local "and friends" timelines
382 * Notice::LOCAL_NONPUBLIC - Local, but hide from public timeline
383 * Notice::GATEWAY - From another non-OStatus service;
384 * will not appear in public views
385 * float 'lat' decimal latitude for geolocation
386 * float 'lon' decimal longitude for geolocation
387 * int 'location_id' geoname identifier
388 * int 'location_ns' geoname namespace to interpret location_id
389 * int 'reply_to'; notice ID this is a reply to
390 * int 'repeat_of'; notice ID this is a repeat of
391 * string 'uri' unique ID for notice; a unique tag uri (can be url or anything too)
392 * string 'url' permalink to notice; defaults to local notice URL
393 * string 'rendered' rendered HTML version of content
394 * array 'replies' list of profile URIs for reply delivery in
395 * place of extracting @-replies from content.
396 * array 'groups' list of group IDs to deliver to, in place of
397 * extracting ! tags from content
398 * array 'tags' list of hashtag strings to save with the notice
399 * in place of extracting # tags from content
400 * array 'urls' list of attached/referred URLs to save with the
401 * notice in place of extracting links from content
402 * boolean 'distribute' whether to distribute the notice, default true
403 * string 'object_type' URL of the associated object type (default ActivityObject::NOTE)
404 * string 'verb' URL of the associated verb (default ActivityVerb::POST)
405 * int 'scope' Scope bitmask; default to SITE_SCOPE on private sites, 0 otherwise
407 * @fixme tag override
410 * @throws ClientException
412 static function saveNew($profile_id, $content, $source, array $options=array()) {
413 $defaults = array('uri' => null,
415 'conversation' => null, // URI of conversation
416 'reply_to' => null, // This will override convo URI if the parent is known
417 'repeat_of' => null, // This will override convo URI if the repeated notice is known
419 'distribute' => true,
420 'object_type' => null,
424 * Above type-hint is already array, so simply count it, this saves
427 if (count($options) > 0) {
428 $options = array_merge($defaults, $options);
433 if (!isset($is_local)) {
434 $is_local = Notice::LOCAL_PUBLIC;
437 $profile = Profile::getKV('id', $profile_id);
438 if (!$profile instanceof Profile) {
439 // TRANS: Client exception thrown when trying to save a notice for an unknown user.
440 throw new ClientException(_('Problem saving notice. Unknown user.'));
443 $user = User::getKV('id', $profile_id);
444 if ($user instanceof User) {
445 // Use the local user's shortening preferences, if applicable.
446 $final = $user->shortenLinks($content);
448 $final = common_shorten_links($content);
451 if (Notice::contentTooLong($final)) {
452 // TRANS: Client exception thrown if a notice contains too many characters.
453 throw new ClientException(_('Problem saving notice. Too long.'));
456 if (common_config('throttle', 'enabled') && !Notice::checkEditThrottle($profile_id)) {
457 common_log(LOG_WARNING, 'Excessive posting by profile #' . $profile_id . '; throttled.');
458 // TRANS: Client exception thrown when a user tries to post too many notices in a given time frame.
459 throw new ClientException(_('Too many notices too fast; take a breather '.
460 'and post again in a few minutes.'));
463 if (common_config('site', 'dupelimit') > 0 && !Notice::checkDupes($profile_id, $final)) {
464 common_log(LOG_WARNING, 'Dupe posting by profile #' . $profile_id . '; throttled.');
465 // TRANS: Client exception thrown when a user tries to post too many duplicate notices in a given time frame.
466 throw new ClientException(_('Too many duplicate messages too quickly;'.
467 ' take a breather and post again in a few minutes.'));
470 if (!$profile->hasRight(Right::NEWNOTICE)) {
471 common_log(LOG_WARNING, "Attempted post from user disallowed to post: " . $profile->nickname);
473 // TRANS: Client exception thrown when a user tries to post while being banned.
474 throw new ClientException(_('You are banned from posting notices on this site.'), 403);
477 $notice = new Notice();
478 $notice->profile_id = $profile_id;
480 $autosource = common_config('public', 'autosource');
482 // Sandboxed are non-false, but not 1, either
484 if (!$profile->hasRight(Right::PUBLICNOTICE) ||
485 ($source && $autosource && in_array($source, $autosource))) {
486 $notice->is_local = Notice::LOCAL_NONPUBLIC;
488 $notice->is_local = $is_local;
491 if (!empty($created)) {
492 $notice->created = $created;
494 $notice->created = common_sql_now();
497 if (!$notice->isLocal()) {
498 // Only do these checks for non-local notices. Local notices will generate these values later.
499 if (!common_valid_http_url($url)) {
500 common_debug('Bad notice URL: ['.$url.'], URI: ['.$uri.']. Cannot link back to original! This is normal for shared notices etc.');
503 throw new ServerException('No URI for remote notice. Cannot accept that.');
507 $notice->content = $final;
509 $notice->source = $source;
513 // Get the groups here so we can figure out replies and such
514 if (!isset($groups)) {
515 $groups = User_group::idsFromText($notice->content, $profile);
520 // Handle repeat case
522 if (!empty($options['repeat_of'])) {
524 // Check for a private one
526 $repeat = Notice::getByID($options['repeat_of']);
528 if ($profile->sameAs($repeat->getProfile())) {
529 // TRANS: Client error displayed when trying to repeat an own notice.
530 throw new ClientException(_('You cannot repeat your own notice.'));
533 if ($repeat->isPrivateScope()) {
534 // TRANS: Client error displayed when trying to repeat a non-public notice.
535 throw new ClientException(_('Cannot repeat a private notice.'), 403);
538 if (!$repeat->inScope($profile)) {
539 // The generic checks above should cover this, but let's be sure!
540 // TRANS: Client error displayed when trying to repeat a notice you cannot access.
541 throw new ClientException(_('Cannot repeat a notice you cannot read.'), 403);
544 if ($profile->hasRepeated($repeat)) {
545 // TRANS: Client error displayed when trying to repeat an already repeated notice.
546 throw new ClientException(_('You already repeated that notice.'));
549 $notice->repeat_of = $repeat->id;
550 $notice->conversation = $repeat->conversation;
554 // If $reply_to is specified, we check that it exists, and then
555 // return it if it does
556 if (!empty($reply_to)) {
557 $reply = Notice::getKV('id', $reply_to);
558 } elseif (in_array($source, array('xmpp', 'mail', 'sms'))) {
559 // If the source lacks capability of sending the "reply_to"
560 // metadata, let's try to find an inline replyto-reference.
561 $reply = self::getInlineReplyTo($profile, $final);
564 if ($reply instanceof Notice) {
565 if (!$reply->inScope($profile)) {
566 // TRANS: Client error displayed when trying to reply to a notice a the target has no access to.
567 // TRANS: %1$s is a user nickname, %2$d is a notice ID (number).
568 throw new ClientException(sprintf(_('%1$s has no access to notice %2$d.'),
569 $profile->nickname, $reply->id), 403);
572 // If it's a repeat, the reply_to should be to the original
573 if ($reply->isRepeat()) {
574 $notice->reply_to = $reply->repeat_of;
576 $notice->reply_to = $reply->id;
578 // But the conversation ought to be the same :)
579 $notice->conversation = $reply->conversation;
581 // If the original is private to a group, and notice has
582 // no group specified, make it to the same group(s)
584 if (empty($groups) && ($reply->scope & Notice::GROUP_SCOPE)) {
586 $replyGroups = $reply->getGroups();
587 foreach ($replyGroups as $group) {
588 if ($profile->isMember($group)) {
589 $groups[] = $group->id;
597 // If we don't know the reply, we might know the conversation!
598 // This will happen if a known remote user replies to an
599 // unknown remote user - within a known conversation.
600 if (empty($notice->conversation) and !empty($options['conversation'])) {
601 $conv = Conversation::getKV('uri', $options['conversation']);
602 if ($conv instanceof Conversation) {
603 common_debug('Conversation stitched together from (probably) a reply to unknown remote user. Activity creation time ('.$notice->created.') should maybe be compared to conversation creation time ('.$conv->created.').');
604 $notice->conversation = $conv->id;
606 // Conversation URI was not found, so we must create it. But we can't create it
607 // until we have a Notice ID because of the database layout...
608 // $options['conversation'] will be used later after the $notice->insert();
609 common_debug('Conversation URI not found, so we have to create it after inserting this Notice: '.$options['conversation']);
612 // If we're not using the attached conversation URI let's remove it
613 // so we don't mistake ourselves later, when creating our own Conversation.
614 // This implies that the notice knows which conversation it belongs to.
615 $options['conversation'] = null;
619 $notloc = new Notice_location();
620 if (!empty($lat) && !empty($lon)) {
625 if (!empty($location_ns) && !empty($location_id)) {
626 $notloc->location_id = $location_id;
627 $notloc->location_ns = $location_ns;
630 if (!empty($rendered)) {
631 $notice->rendered = $rendered;
633 $notice->rendered = common_render_content($final, $notice);
637 if ($notice->isRepeat()) {
638 $notice->verb = ActivityVerb::SHARE;
639 $notice->object_type = ActivityObject::ACTIVITY;
641 $notice->verb = ActivityVerb::POST;
644 $notice->verb = $verb;
647 if (empty($object_type)) {
648 $notice->object_type = (empty($notice->reply_to)) ? ActivityObject::NOTE : ActivityObject::COMMENT;
650 $notice->object_type = $object_type;
653 if (is_null($scope) && $reply instanceof Notice) {
654 $notice->scope = $reply->scope;
656 $notice->scope = $scope;
659 $notice->scope = self::figureOutScope($profile, $groups, $notice->scope);
661 if (Event::handle('StartNoticeSave', array(&$notice))) {
663 // XXX: some of these functions write to the DB
666 $notice->insert(); // throws exception on failure, if successful we have an ->id
668 if (($notloc->lat && $notloc->lon) || ($notloc->location_id && $notloc->location_ns)) {
669 $notloc->notice_id = $notice->getID();
670 $notloc->insert(); // store the notice location if it had any information
673 // If it's not part of a conversation, it's
674 // the beginning of a new conversation.
675 if (empty($notice->conversation)) {
676 $orig = clone($notice);
677 // $act->context->conversation will be null if it was not provided
679 $conv = Conversation::create($notice, $options['conversation']);
680 $notice->conversation = $conv->id;
681 $notice->update($orig);
683 } catch (Exception $e) {
684 // Let's test if we managed initial insert, which would imply
685 // failing on some update-part (check 'insert()'). Delete if
686 // something had been stored to the database.
687 if (!empty($notice->id)) {
694 // Clear the cache for subscribed users, so they'll update at next request
695 // XXX: someone clever could prepend instead of clearing the cache
697 // Save per-notice metadata...
699 if (isset($replies)) {
700 $notice->saveKnownReplies($replies);
702 $notice->saveReplies();
706 $notice->saveKnownTags($tags);
711 // Note: groups may save tags, so must be run after tags are saved
712 // to avoid errors on duplicates.
713 // Note: groups should always be set.
715 $notice->saveKnownGroups($groups);
718 $notice->saveKnownUrls($urls);
724 // Prepare inbox delivery, may be queued to background.
725 $notice->distribute();
731 static function saveActivity(Activity $act, Profile $actor, array $options=array())
733 // First check if we're going to let this Activity through from the specific actor
734 if (!$actor->hasRight(Right::NEWNOTICE)) {
735 common_log(LOG_WARNING, "Attempted post from user disallowed to post: " . $actor->getNickname());
737 // TRANS: Client exception thrown when a user tries to post while being banned.
738 throw new ClientException(_m('You are banned from posting notices on this site.'), 403);
740 if (common_config('throttle', 'enabled') && !self::checkEditThrottle($actor->id)) {
741 common_log(LOG_WARNING, 'Excessive posting by profile #' . $actor->id . '; throttled.');
742 // TRANS: Client exception thrown when a user tries to post too many notices in a given time frame.
743 throw new ClientException(_m('Too many notices too fast; take a breather '.
744 'and post again in a few minutes.'));
747 // Get ActivityObject properties
748 if (!empty($act->id)) {
750 $options['uri'] = $act->id;
751 $options['url'] = $act->link;
753 $actobj = count($act->objects)==1 ? $act->objects[0] : null;
754 if (!is_null($actobj) && !empty($actobj->id)) {
755 $options['uri'] = $actobj->id;
757 $options['url'] = $actobj->link;
758 } elseif (preg_match('!^https?://!', $actobj->id)) {
759 $options['url'] = $actobj->id;
766 'is_local' => self::LOCAL_PUBLIC,
767 'mentions' => array(),
771 'source' => 'unknown',
776 'distribute' => true);
778 // options will have default values when nothing has been supplied
779 $options = array_merge($defaults, $options);
780 foreach (array_keys($defaults) as $key) {
781 // Only convert the keynames we specify ourselves from 'defaults' array into variables
782 $$key = $options[$key];
784 extract($options, EXTR_SKIP);
786 $stored = new Notice();
789 if ($stored->find()) {
790 common_debug('cannot create duplicate Notice URI: '.$stored->uri);
791 throw new Exception('Notice URI already exists');
795 $stored->profile_id = $actor->id;
796 $stored->source = $source;
799 $stored->verb = $act->verb;
801 // Use the local user's shortening preferences, if applicable.
802 $stored->rendered = $actor->isLocal()
803 ? $actor->shortenLinks($act->content)
805 $stored->content = common_strip_html($stored->rendered);
807 $autosource = common_config('public', 'autosource');
809 // Sandboxed are non-false, but not 1, either
810 if (!$actor->hasRight(Right::PUBLICNOTICE) ||
811 ($source && $autosource && in_array($source, $autosource))) {
812 $stored->is_local = Notice::LOCAL_NONPUBLIC;
815 // Maybe a missing act-time should be fatal if the actor is not local?
816 if (!empty($act->time)) {
817 $stored->created = common_sql_date($act->time);
819 $stored->created = common_sql_now();
823 if ($act->context instanceof ActivityContext && !empty($act->context->replyToID)) {
824 $reply = self::getKV('uri', $act->context->replyToID);
826 if (!$reply instanceof Notice && $act->target instanceof ActivityObject) {
827 $reply = self::getKV('uri', $act->target->id);
830 if ($reply instanceof Notice) {
831 if (!$reply->inScope($actor)) {
832 // TRANS: Client error displayed when trying to reply to a notice a the target has no access to.
833 // TRANS: %1$s is a user nickname, %2$d is a notice ID (number).
834 throw new ClientException(sprintf(_m('%1$s has no right to reply to notice %2$d.'), $actor->getNickname(), $reply->id), 403);
837 $stored->reply_to = $reply->id;
838 $stored->conversation = $reply->conversation;
840 // If the original is private to a group, and notice has no group specified,
841 // make it to the same group(s)
842 if (empty($groups) && ($reply->scope & Notice::GROUP_SCOPE)) {
844 $replyGroups = $reply->getGroups();
845 foreach ($replyGroups as $group) {
846 if ($actor->isMember($group)) {
847 $groups[] = $group->id;
852 if (is_null($scope)) {
853 $scope = $reply->scope;
856 // If we don't know the reply, we might know the conversation!
857 // This will happen if a known remote user replies to an
858 // unknown remote user - within a known conversation.
859 if (empty($stored->conversation) and !empty($act->context->conversation)) {
860 $conv = Conversation::getKV('uri', $act->context->conversation);
861 if ($conv instanceof Conversation) {
862 common_debug('Conversation stitched together from (probably) a reply activity to unknown remote user. Activity creation time ('.$stored->created.') should maybe be compared to conversation creation time ('.$conv->created.').');
863 $stored->conversation = $conv->id;
865 // Conversation URI was not found, so we must create it. But we can't create it
866 // until we have a Notice ID because of the database layout...
867 // $options['conversation'] will be used later after the $stored->insert();
868 common_debug('Conversation URI from activity context not found, so we have to create it after inserting this Notice: '.$act->context->conversation);
874 if ($act->context instanceof ActivityContext) {
875 if ($act->context->location instanceof Location) {
876 $notloc = Notice_location::fromLocation($act->context->location);
879 $act->context = new ActivityContext();
882 $stored->scope = self::figureOutScope($actor, $groups, $scope);
884 foreach ($act->categories as $cat) {
886 $term = common_canonical_tag($cat->term);
893 foreach ($act->enclosures as $href) {
894 // @todo FIXME: Save these locally or....?
898 if (Event::handle('StartNoticeSave', array(&$stored))) {
899 // XXX: some of these functions write to the DB
902 $stored->insert(); // throws exception on error
904 if ($notloc instanceof Notice_location) {
905 $notloc->notice_id = $stored->getID();
909 $orig = clone($stored); // for updating later in this try clause
912 Event::handle('StoreActivityObject', array($act, $stored, $options, &$object));
913 if (empty($object)) {
914 throw new ServerException('Unsuccessful call to StoreActivityObject '.$stored->uri . ': '.$act->asString());
917 // If it's not part of a conversation, it's the beginning
918 // of a new one (or belongs to a previously unknown URI).
919 if (empty($stored->conversation)) {
920 // $act->context->conversation will be null if it was not provided
921 common_debug('Creating a new conversation for stored notice ID='.$stored->getID().' with URI: '.$act->context->conversation);
922 $conv = Conversation::create($stored, $act->context->conversation);
923 $stored->conversation = $conv->id;
926 $stored->update($orig);
927 } catch (Exception $e) {
928 if (empty($stored->id)) {
929 common_debug('Failed to save stored object entry in database ('.$e->getMessage().')');
931 common_debug('Failed to store activity object in database ('.$e->getMessage().'), deleting notice id '.$stored->id);
937 if (!$stored instanceof Notice) {
938 throw new ServerException('StartNoticeSave did not give back a Notice');
941 // Save per-notice metadata...
945 // This event lets plugins filter out non-local recipients (attentions we don't care about)
946 // Used primarily for OStatus (and if we don't federate, all attentions would be local anyway)
947 Event::handle('GetLocalAttentions', array($actor, $act->context->attention, &$mentions, &$groups));
949 if (!empty($mentions)) {
950 $stored->saveKnownReplies($mentions);
952 $stored->saveReplies();
956 $stored->saveKnownTags($tags);
961 // Note: groups may save tags, so must be run after tags are saved
962 // to avoid errors on duplicates.
963 // Note: groups should always be set.
965 $stored->saveKnownGroups($groups);
968 $stored->saveKnownUrls($urls);
974 // Prepare inbox delivery, may be queued to background.
975 $stored->distribute();
981 static public function figureOutScope(Profile $actor, array $groups, $scope=null) {
982 if (is_null($scope)) {
983 $scope = self::defaultScope();
986 // For private streams
988 $user = $actor->getUser();
989 // FIXME: We can't do bit comparison with == (Legacy StatusNet thing. Let's keep it for now.)
990 if ($user->private_stream && ($scope == Notice::PUBLIC_SCOPE || $scope == Notice::SITE_SCOPE)) {
991 $scope |= Notice::FOLLOWER_SCOPE;
993 } catch (NoSuchUserException $e) {
994 // TODO: Not a local user, so we don't know about scope preferences... yet!
997 // Force the scope for private groups
998 foreach ($groups as $group_id) {
1000 $group = User_group::getByID($group_id);
1001 if ($group->force_scope) {
1002 $scope |= Notice::GROUP_SCOPE;
1005 } catch (Exception $e) {
1006 common_log(LOG_ERR, 'Notice figureOutScope threw exception: '.$e->getMessage());
1013 function blowOnInsert($conversation = false)
1015 $this->blowStream('profile:notice_ids:%d', $this->profile_id);
1017 if ($this->isPublic()) {
1018 $this->blowStream('public');
1019 $this->blowStream('networkpublic');
1022 self::blow('notice:list-ids:conversation:%s', $this->conversation);
1023 self::blow('conversation:notice_count:%d', $this->conversation);
1025 if ($this->isRepeat()) {
1026 // XXX: we should probably only use one of these
1027 $this->blowStream('notice:repeats:%d', $this->repeat_of);
1028 self::blow('notice:list-ids:repeat_of:%d', $this->repeat_of);
1031 $original = Notice::getKV('id', $this->repeat_of);
1033 if ($original instanceof Notice) {
1034 $originalUser = User::getKV('id', $original->profile_id);
1035 if ($originalUser instanceof User) {
1036 $this->blowStream('user:repeats_of_me:%d', $originalUser->id);
1040 $profile = Profile::getKV($this->profile_id);
1042 if ($profile instanceof Profile) {
1043 $profile->blowNoticeCount();
1046 $ptags = $this->getProfileTags();
1047 foreach ($ptags as $ptag) {
1048 $ptag->blowNoticeStreamCache();
1053 * Clear cache entries related to this notice at delete time.
1054 * Necessary to avoid breaking paging on public, profile timelines.
1056 function blowOnDelete()
1058 $this->blowOnInsert();
1060 self::blow('profile:notice_ids:%d;last', $this->profile_id);
1062 if ($this->isPublic()) {
1063 self::blow('public;last');
1064 self::blow('networkpublic;last');
1067 self::blow('fave:by_notice', $this->id);
1069 if ($this->conversation) {
1070 // In case we're the first, will need to calc a new root.
1071 self::blow('notice:conversation_root:%d', $this->conversation);
1074 $ptags = $this->getProfileTags();
1075 foreach ($ptags as $ptag) {
1076 $ptag->blowNoticeStreamCache(true);
1080 function blowStream()
1082 $c = self::memcache();
1088 $args = func_get_args();
1089 $format = array_shift($args);
1090 $keyPart = vsprintf($format, $args);
1091 $cacheKey = Cache::key($keyPart);
1092 $c->delete($cacheKey);
1094 // delete the "last" stream, too, if this notice is
1095 // older than the top of that stream
1097 $lastKey = $cacheKey.';last';
1099 $lastStr = $c->get($lastKey);
1101 if ($lastStr !== false) {
1102 $window = explode(',', $lastStr);
1103 $lastID = $window[0];
1104 $lastNotice = Notice::getKV('id', $lastID);
1105 if (!$lastNotice instanceof Notice // just weird
1106 || strtotime($lastNotice->created) >= strtotime($this->created)) {
1107 $c->delete($lastKey);
1112 /** save all urls in the notice to the db
1114 * follow redirects and save all available file information
1115 * (mimetype, date, size, oembed, etc.)
1119 function saveUrls() {
1120 if (common_config('attachments', 'process_links')) {
1121 common_replace_urls_callback($this->content, array($this, 'saveUrl'), $this);
1126 * Save the given URLs as related links/attachments to the db
1128 * follow redirects and save all available file information
1129 * (mimetype, date, size, oembed, etc.)
1133 function saveKnownUrls(array $urls)
1135 if (common_config('attachments', 'process_links')) {
1136 // @fixme validation?
1137 foreach (array_unique($urls) as $url) {
1138 $this->saveUrl($url, $this);
1146 function saveUrl($url, Notice $notice) {
1148 File::processNew($url, $notice);
1149 } catch (ServerException $e) {
1150 // Could not save URL. Log it?
1154 static function checkDupes($profile_id, $content) {
1155 $profile = Profile::getKV($profile_id);
1156 if (!$profile instanceof Profile) {
1159 $notice = $profile->getNotices(0, CachingNoticeStream::CACHE_WINDOW);
1160 if (!empty($notice)) {
1162 while ($notice->fetch()) {
1163 if (time() - strtotime($notice->created) >= common_config('site', 'dupelimit')) {
1165 } else if ($notice->content == $content) {
1170 // If we get here, oldest item in cache window is not
1171 // old enough for dupe limit; do direct check against DB
1172 $notice = new Notice();
1173 $notice->profile_id = $profile_id;
1174 $notice->content = $content;
1175 $threshold = common_sql_date(time() - common_config('site', 'dupelimit'));
1176 $notice->whereAdd(sprintf("created > '%s'", $notice->escape($threshold)));
1178 $cnt = $notice->count();
1182 static function checkEditThrottle($profile_id) {
1183 $profile = Profile::getKV($profile_id);
1184 if (!$profile instanceof Profile) {
1187 // Get the Nth notice
1188 $notice = $profile->getNotices(common_config('throttle', 'count') - 1, 1);
1189 if ($notice && $notice->fetch()) {
1190 // If the Nth notice was posted less than timespan seconds ago
1191 if (time() - strtotime($notice->created) <= common_config('throttle', 'timespan')) {
1196 // Either not N notices in the stream, OR the Nth was not posted within timespan seconds
1200 protected $_attachments = array();
1202 function attachments() {
1203 if (isset($this->_attachments[$this->id])) {
1204 return $this->_attachments[$this->id];
1207 $f2ps = File_to_post::listGet('post_id', array($this->id));
1209 foreach ($f2ps[$this->id] as $f2p) {
1210 $ids[] = $f2p->file_id;
1213 $files = File::multiGet('id', $ids);
1214 $this->_attachments[$this->id] = $files->fetchAll();
1215 return $this->_attachments[$this->id];
1218 function _setAttachments($attachments)
1220 $this->_attachments[$this->id] = $attachments;
1223 static function publicStream($offset=0, $limit=20, $since_id=null, $max_id=null)
1225 $stream = new PublicNoticeStream();
1226 return $stream->getNotices($offset, $limit, $since_id, $max_id);
1229 static function conversationStream($id, $offset=0, $limit=20, $since_id=null, $max_id=null)
1231 $stream = new ConversationNoticeStream($id);
1232 return $stream->getNotices($offset, $limit, $since_id, $max_id);
1236 * Is this notice part of an active conversation?
1238 * @return boolean true if other messages exist in the same
1239 * conversation, false if this is the only one
1241 function hasConversation()
1243 if (empty($this->conversation)) {
1244 // this notice is not part of a conversation apparently
1245 // FIXME: all notices should have a conversation value, right?
1249 $stream = new ConversationNoticeStream($this->conversation);
1250 $notice = $stream->getNotices(/*offset*/ 1, /*limit*/ 1);
1252 // if our "offset 1, limit 1" query got a result, return true else false
1253 return $notice->N > 0;
1257 * Grab the earliest notice from this conversation.
1259 * @return Notice or null
1261 function conversationRoot($profile=-1)
1263 // XXX: can this happen?
1265 if (empty($this->conversation)) {
1269 // Get the current profile if not specified
1271 if (is_int($profile) && $profile == -1) {
1272 $profile = Profile::current();
1275 // If this notice is out of scope, no root for you!
1277 if (!$this->inScope($profile)) {
1281 // If this isn't a reply to anything, then it's its own
1282 // root if it's the earliest notice in the conversation:
1284 if (empty($this->reply_to)) {
1286 $root->conversation = $this->conversation;
1287 $root->orderBy('notice.created ASC');
1288 $root->find(true); // true means "fetch first result"
1293 if (is_null($profile)) {
1294 $keypart = sprintf('notice:conversation_root:%d:null', $this->id);
1296 $keypart = sprintf('notice:conversation_root:%d:%d',
1301 $root = self::cacheGet($keypart);
1303 if ($root !== false && $root->inScope($profile)) {
1310 $parent = $last->getParent();
1311 if ($parent->inScope($profile)) {
1315 } catch (NoParentNoticeException $e) {
1316 // Latest notice has no parent
1318 // No parent, or parent out of scope
1323 self::cacheSet($keypart, $root);
1329 * Pull up a full list of local recipients who will be getting
1330 * this notice in their inbox. Results will be cached, so don't
1331 * change the input data wily-nilly!
1333 * @param array $groups optional list of Group objects;
1334 * if left empty, will be loaded from group_inbox records
1335 * @param array $recipient optional list of reply profile ids
1336 * if left empty, will be loaded from reply records
1337 * @return array associating recipient user IDs with an inbox source constant
1339 function whoGets(array $groups=null, array $recipients=null)
1341 $c = self::memcache();
1344 $ni = $c->get(Cache::key('notice:who_gets:'.$this->id));
1345 if ($ni !== false) {
1350 if (is_null($recipients)) {
1351 $recipients = $this->getReplies();
1356 // Give plugins a chance to add folks in at start...
1357 if (Event::handle('StartNoticeWhoGets', array($this, &$ni))) {
1359 $users = $this->getSubscribedUsers();
1360 foreach ($users as $id) {
1361 $ni[$id] = NOTICE_INBOX_SOURCE_SUB;
1364 if (is_null($groups)) {
1365 $groups = $this->getGroups();
1367 foreach ($groups as $group) {
1368 $users = $group->getUserMembers();
1369 foreach ($users as $id) {
1370 if (!array_key_exists($id, $ni)) {
1371 $ni[$id] = NOTICE_INBOX_SOURCE_GROUP;
1376 $ptAtts = $this->getAttentionsFromProfileTags();
1377 foreach ($ptAtts as $key=>$val) {
1378 if (!array_key_exists($key, $ni)) {
1383 foreach ($recipients as $recipient) {
1384 if (!array_key_exists($recipient, $ni)) {
1385 $ni[$recipient] = NOTICE_INBOX_SOURCE_REPLY;
1389 // Exclude any deleted, non-local, or blocking recipients.
1390 $profile = $this->getProfile();
1391 $originalProfile = null;
1392 if ($this->isRepeat()) {
1393 // Check blocks against the original notice's poster as well.
1394 $original = Notice::getKV('id', $this->repeat_of);
1395 if ($original instanceof Notice) {
1396 $originalProfile = $original->getProfile();
1400 foreach ($ni as $id => $source) {
1402 $user = User::getKV('id', $id);
1403 if (!$user instanceof User ||
1404 $user->hasBlocked($profile) ||
1405 ($originalProfile && $user->hasBlocked($originalProfile))) {
1408 } catch (UserNoProfileException $e) {
1409 // User doesn't have a profile; invalid; skip them.
1414 // Give plugins a chance to filter out...
1415 Event::handle('EndNoticeWhoGets', array($this, &$ni));
1419 // XXX: pack this data better
1420 $c->set(Cache::key('notice:who_gets:'.$this->id), $ni);
1426 function getSubscribedUsers()
1430 if(common_config('db','quote_identifiers'))
1431 $user_table = '"user"';
1432 else $user_table = 'user';
1436 'FROM '. $user_table .' JOIN subscription '.
1437 'ON '. $user_table .'.id = subscription.subscriber ' .
1438 'WHERE subscription.subscribed = %d ';
1440 $user->query(sprintf($qry, $this->profile_id));
1444 while ($user->fetch()) {
1453 function getProfileTags()
1455 $profile = $this->getProfile();
1456 $list = $profile->getOtherTags($profile);
1459 while($list->fetch()) {
1460 $ptags[] = clone($list);
1466 public function getAttentionsFromProfileTags()
1469 $ptags = $this->getProfileTags();
1470 foreach ($ptags as $ptag) {
1471 $users = $ptag->getUserSubscribers();
1472 foreach ($users as $id) {
1473 $ni[$id] = NOTICE_INBOX_SOURCE_PROFILE_TAG;
1480 * Record this notice to the given group inboxes for delivery.
1481 * Overrides the regular parsing of !group markup.
1483 * @param string $group_ids
1484 * @fixme might prefer URIs as identifiers, as for replies?
1485 * best with generalizations on user_group to support
1486 * remote groups better.
1488 function saveKnownGroups($group_ids)
1490 if (!is_array($group_ids)) {
1491 // TRANS: Server exception thrown when no array is provided to the method saveKnownGroups().
1492 throw new ServerException(_('Bad type provided to saveKnownGroups.'));
1496 foreach (array_unique($group_ids) as $id) {
1497 $group = User_group::getKV('id', $id);
1498 if ($group instanceof User_group) {
1499 common_log(LOG_DEBUG, "Local delivery to group id $id, $group->nickname");
1500 $result = $this->addToGroupInbox($group);
1502 common_log_db_error($gi, 'INSERT', __FILE__);
1505 if (common_config('group', 'addtag')) {
1506 // we automatically add a tag for every group name, too
1508 $tag = Notice_tag::pkeyGet(array('tag' => common_canonical_tag($group->nickname),
1509 'notice_id' => $this->id));
1511 if (is_null($tag)) {
1512 $this->saveTag($group->nickname);
1516 $groups[] = clone($group);
1518 common_log(LOG_ERR, "Local delivery to group id $id skipped, doesn't exist");
1525 function addToGroupInbox(User_group $group)
1527 $gi = Group_inbox::pkeyGet(array('group_id' => $group->id,
1528 'notice_id' => $this->id));
1530 if (!$gi instanceof Group_inbox) {
1532 $gi = new Group_inbox();
1534 $gi->group_id = $group->id;
1535 $gi->notice_id = $this->id;
1536 $gi->created = $this->created;
1538 $result = $gi->insert();
1541 common_log_db_error($gi, 'INSERT', __FILE__);
1542 // TRANS: Server exception thrown when an update for a group inbox fails.
1543 throw new ServerException(_('Problem saving group inbox.'));
1546 self::blow('user_group:notice_ids:%d', $gi->group_id);
1553 * Save reply records indicating that this notice needs to be
1554 * delivered to the local users with the given URIs.
1556 * Since this is expected to be used when saving foreign-sourced
1557 * messages, we won't deliver to any remote targets as that's the
1558 * source service's responsibility.
1560 * Mail notifications etc will be handled later.
1562 * @param array $uris Array of unique identifier URIs for recipients
1564 function saveKnownReplies(array $uris)
1570 $sender = Profile::getKV($this->profile_id);
1572 foreach (array_unique($uris) as $uri) {
1574 $profile = Profile::fromUri($uri);
1575 } catch (UnknownUriException $e) {
1576 common_log(LOG_WARNING, "Unable to determine profile for URI '$uri'");
1580 if ($profile->hasBlocked($sender)) {
1581 common_log(LOG_INFO, "Not saving reply to profile {$profile->id} ($uri) from sender {$sender->id} because of a block.");
1585 $this->saveReply($profile->id);
1586 self::blow('reply:stream:%d', $profile->id);
1593 * Pull @-replies from this message's content in StatusNet markup format
1594 * and save reply records indicating that this message needs to be
1595 * delivered to those users.
1597 * Mail notifications to local profiles will be sent later.
1599 * @return array of integer profile IDs
1602 function saveReplies()
1604 // Don't save reply data for repeats
1606 if ($this->isRepeat()) {
1610 $sender = $this->getProfile();
1614 // If it's a reply, save for the replied-to author
1616 $parent = $this->getParent();
1617 $parentauthor = $parent->getProfile();
1618 $this->saveReply($parentauthor->id);
1619 $replied[$parentauthor->id] = 1;
1620 self::blow('reply:stream:%d', $parentauthor->id);
1621 } catch (NoParentNoticeException $e) {
1622 // Not a reply, since it has no parent!
1625 // @todo ideally this parser information would only
1626 // be calculated once.
1628 $mentions = common_find_mentions($this->content, $this);
1630 // store replied only for first @ (what user/notice what the reply directed,
1631 // we assume first @ is it)
1633 foreach ($mentions as $mention) {
1635 foreach ($mention['mentioned'] as $mentioned) {
1637 // skip if they're already covered
1638 if (array_key_exists($mentioned->id, $replied)) {
1642 // Don't save replies from blocked profile to local user
1644 $mentioned_user = User::getKV('id', $mentioned->id);
1645 if ($mentioned_user instanceof User && $mentioned_user->hasBlocked($sender)) {
1649 $this->saveReply($mentioned->id);
1650 $replied[$mentioned->id] = 1;
1651 self::blow('reply:stream:%d', $mentioned->id);
1655 $recipientIds = array_keys($replied);
1657 return $recipientIds;
1660 function saveReply($profileId)
1662 $reply = new Reply();
1664 $reply->notice_id = $this->id;
1665 $reply->profile_id = $profileId;
1666 $reply->modified = $this->created;
1673 protected $_replies = array();
1676 * Pull the complete list of @-mentioned profile IDs for this notice.
1678 * @return array of integer profile ids
1680 function getReplies()
1682 if (!isset($this->_replies[$this->getID()])) {
1683 $mentions = Reply::multiGet('notice_id', array($this->getID()));
1684 $this->_replies[$this->getID()] = $mentions->fetchAll('profile_id');
1686 return $this->_replies[$this->getID()];
1689 function _setReplies(array $replies)
1691 $this->_replies[$this->getID()] = $replies;
1695 * Pull the complete list of @-reply targets for this notice.
1697 * @return array of Profiles
1699 function getReplyProfiles()
1701 $ids = $this->getReplies();
1703 $profiles = Profile::multiGet('id', $ids);
1705 return $profiles->fetchAll();
1709 * Send e-mail notifications to local @-reply targets.
1711 * Replies must already have been saved; this is expected to be run
1712 * from the distrib queue handler.
1714 function sendReplyNotifications()
1716 // Don't send reply notifications for repeats
1718 if ($this->isRepeat()) {
1722 $recipientIds = $this->getReplies();
1723 if (Event::handle('StartNotifyMentioned', array($this, &$recipientIds))) {
1724 require_once INSTALLDIR.'/lib/mail.php';
1726 foreach ($recipientIds as $recipientId) {
1727 $user = User::getKV('id', $recipientId);
1728 if ($user instanceof User) {
1729 mail_notify_attn($user, $this);
1732 Event::handle('EndNotifyMentioned', array($this, $recipientIds));
1737 * Pull list of groups this notice needs to be delivered to,
1738 * as previously recorded by saveKnownGroups().
1740 * @return array of Group objects
1743 protected $_groups = array();
1745 function getGroups()
1747 // Don't save groups for repeats
1749 if (!empty($this->repeat_of)) {
1753 if (isset($this->_groups[$this->id])) {
1754 return $this->_groups[$this->id];
1757 $gis = Group_inbox::listGet('notice_id', array($this->id));
1761 foreach ($gis[$this->id] as $gi) {
1762 $ids[] = $gi->group_id;
1765 $groups = User_group::multiGet('id', $ids);
1766 $this->_setGroups($groups->fetchAll());
1767 return $this->_groups[$this->id];
1770 function _setGroups(array $groups)
1772 $this->_groups[$this->id] = $groups;
1776 * Convert a notice into an activity for export.
1778 * @param Profile $scoped The currently logged in/scoped profile
1780 * @return Activity activity object representing this Notice.
1783 function asActivity(Profile $scoped=null)
1785 $act = self::cacheGet(Cache::codeKey('notice:as-activity:'.$this->id));
1787 if ($act instanceof Activity) {
1790 $act = new Activity();
1792 if (Event::handle('StartNoticeAsActivity', array($this, $act, $scoped))) {
1794 $act->id = $this->uri;
1795 $act->time = strtotime($this->created);
1797 $act->link = $this->getUrl();
1798 } catch (InvalidUrlException $e) {
1799 // The notice is probably a share or similar, which don't
1800 // have a representational URL of their own.
1802 $act->content = common_xml_safe_str($this->rendered);
1804 $profile = $this->getProfile();
1806 $act->actor = $profile->asActivityObject();
1807 $act->actor->extra[] = $profile->profileInfo($scoped);
1809 $act->verb = $this->verb;
1811 if (!$this->repeat_of) {
1812 $act->objects[] = $this->asActivityObject();
1815 // XXX: should this be handled by default processing for object entry?
1819 $tags = $this->getTags();
1821 foreach ($tags as $tag) {
1822 $cat = new AtomCategory();
1825 $act->categories[] = $cat;
1829 // XXX: use Atom Media and/or File activity objects instead
1831 $attachments = $this->attachments();
1833 foreach ($attachments as $attachment) {
1834 // Include local attachments in Activity
1835 if (!empty($attachment->filename)) {
1836 $act->enclosures[] = $attachment->getEnclosure();
1840 $ctx = new ActivityContext();
1843 $reply = $this->getParent();
1844 $ctx->replyToID = $reply->getUri();
1845 $ctx->replyToUrl = $reply->getUrl(true); // true for fallback to local URL, less messy
1846 } catch (NoParentNoticeException $e) {
1847 // This is not a reply to something
1851 $ctx->location = Notice_location::locFromStored($this);
1852 } catch (ServerException $e) {
1853 $ctx->location = null;
1858 if (!empty($this->conversation)) {
1859 $conv = Conversation::getKV('id', $this->conversation);
1860 if ($conv instanceof Conversation) {
1861 $ctx->conversation = $conv->uri;
1865 $reply_ids = $this->getReplies();
1867 foreach ($reply_ids as $id) {
1868 $rprofile = Profile::getKV('id', $id);
1869 if ($rprofile instanceof Profile) {
1870 $ctx->attention[$rprofile->getUri()] = ActivityObject::PERSON;
1874 $groups = $this->getGroups();
1876 foreach ($groups as $group) {
1877 $ctx->attention[$group->getUri()] = ActivityObject::GROUP;
1880 switch ($this->scope) {
1881 case Notice::PUBLIC_SCOPE:
1882 $ctx->attention[ActivityContext::ATTN_PUBLIC] = ActivityObject::COLLECTION;
1884 case Notice::FOLLOWER_SCOPE:
1885 $surl = common_local_url("subscribers", array('nickname' => $profile->nickname));
1886 $ctx->attention[$surl] = ActivityObject::COLLECTION;
1890 $act->context = $ctx;
1892 $source = $this->getSource();
1894 if ($source instanceof Notice_source) {
1895 $act->generator = ActivityObject::fromNoticeSource($source);
1900 $atom_feed = $profile->getAtomFeed();
1902 if (!empty($atom_feed)) {
1904 $act->source = new ActivitySource();
1906 // XXX: we should store the actual feed ID
1908 $act->source->id = $atom_feed;
1910 // XXX: we should store the actual feed title
1912 $act->source->title = $profile->getBestName();
1914 $act->source->links['alternate'] = $profile->profileurl;
1915 $act->source->links['self'] = $atom_feed;
1917 $act->source->icon = $profile->avatarUrl(AVATAR_PROFILE_SIZE);
1919 $notice = $profile->getCurrentNotice();
1921 if ($notice instanceof Notice) {
1922 $act->source->updated = self::utcDate($notice->created);
1925 $user = User::getKV('id', $profile->id);
1927 if ($user instanceof User) {
1928 $act->source->links['license'] = common_config('license', 'url');
1932 if ($this->isLocal()) {
1933 $act->selfLink = common_local_url('ApiStatusesShow', array('id' => $this->id,
1934 'format' => 'atom'));
1935 $act->editLink = $act->selfLink;
1938 Event::handle('EndNoticeAsActivity', array($this, $act, $scoped));
1941 self::cacheSet(Cache::codeKey('notice:as-activity:'.$this->id), $act);
1946 // This has gotten way too long. Needs to be sliced up into functional bits
1947 // or ideally exported to a utility class.
1949 function asAtomEntry($namespace=false,
1952 Profile $scoped=null)
1954 $act = $this->asActivity($scoped);
1955 $act->extra[] = $this->noticeInfo($scoped);
1956 return $act->asString($namespace, $author, $source);
1960 * Extra notice info for atom entries
1962 * Clients use some extra notice info in the atom stream.
1963 * This gives it to them.
1965 * @param Profile $scoped The currently logged in/scoped profile
1967 * @return array representation of <statusnet:notice_info> element
1970 function noticeInfo(Profile $scoped=null)
1972 // local notice ID (useful to clients for ordering)
1974 $noticeInfoAttr = array('local_id' => $this->id);
1978 $ns = $this->getSource();
1980 if ($ns instanceof Notice_source) {
1981 $noticeInfoAttr['source'] = $ns->code;
1982 if (!empty($ns->url)) {
1983 $noticeInfoAttr['source_link'] = $ns->url;
1984 if (!empty($ns->name)) {
1985 $noticeInfoAttr['source'] = '<a href="'
1986 . htmlspecialchars($ns->url)
1987 . '" rel="nofollow">'
1988 . htmlspecialchars($ns->name)
1994 // favorite and repeated
1996 if ($scoped instanceof Profile) {
1997 $noticeInfoAttr['repeated'] = ($scoped->hasRepeated($this)) ? "true" : "false";
2000 if (!empty($this->repeat_of)) {
2001 $noticeInfoAttr['repeat_of'] = $this->repeat_of;
2004 Event::handle('StatusNetApiNoticeInfo', array($this, &$noticeInfoAttr, $scoped));
2006 return array('statusnet:notice_info', $noticeInfoAttr, null);
2010 * Returns an XML string fragment with a reference to a notice as an
2011 * Activity Streams noun object with the given element type.
2013 * Assumes that 'activity' namespace has been previously defined.
2015 * @param string $element one of 'subject', 'object', 'target'
2019 function asActivityNoun($element)
2021 $noun = $this->asActivityObject();
2022 return $noun->asString('activity:' . $element);
2025 public function asActivityObject()
2027 $object = new ActivityObject();
2029 if (Event::handle('StartActivityObjectFromNotice', array($this, &$object))) {
2030 $object->type = $this->object_type ?: ActivityObject::NOTE;
2031 $object->id = $this->getUri();
2032 $object->title = sprintf('New %1$s by %2$s', ActivityObject::canonicalType($object->type), $this->getProfile()->getNickname());
2033 $object->content = $this->rendered;
2034 $object->link = $this->getUrl();
2036 $object->extra[] = array('status_net', array('notice_id' => $this->id));
2038 Event::handle('EndActivityObjectFromNotice', array($this, &$object));
2045 * Determine which notice, if any, a new notice is in reply to.
2047 * For conversation tracking, we try to see where this notice fits
2048 * in the tree. Beware that this may very well give false positives
2049 * and add replies to wrong threads (if there have been newer posts
2050 * by the same user as we're replying to).
2052 * @param Profile $sender Author profile
2053 * @param string $content Final notice content
2055 * @return integer ID of replied-to notice, or null for not a reply.
2058 static function getInlineReplyTo(Profile $sender, $content)
2060 // Is there an initial @ or T?
2061 if (preg_match('/^T ([A-Z0-9]{1,64}) /', $content, $match)
2062 || preg_match('/^@([a-z0-9]{1,64})\s+/', $content, $match)) {
2063 $nickname = common_canonical_nickname($match[1]);
2068 // Figure out who that is.
2069 $recipient = common_relative_profile($sender, $nickname, common_sql_now());
2071 if ($recipient instanceof Profile) {
2072 // Get their last notice
2073 $last = $recipient->getCurrentNotice();
2074 if ($last instanceof Notice) {
2077 // Maybe in the future we want to handle something else below
2078 // so don't return getCurrentNotice() immediately.
2084 static function maxContent()
2086 $contentlimit = common_config('notice', 'contentlimit');
2087 // null => use global limit (distinct from 0!)
2088 if (is_null($contentlimit)) {
2089 $contentlimit = common_config('site', 'textlimit');
2091 return $contentlimit;
2094 static function contentTooLong($content)
2096 $contentlimit = self::maxContent();
2097 return ($contentlimit > 0 && !empty($content) && (mb_strlen($content) > $contentlimit));
2101 * Convenience function for posting a repeat of an existing message.
2103 * @param Profile $repeater Profile which is doing the repeat
2104 * @param string $source: posting source key, eg 'web', 'api', etc
2107 * @throws Exception on failure or permission problems
2109 function repeat(Profile $repeater, $source)
2111 $author = $this->getProfile();
2113 // TRANS: Message used to repeat a notice. RT is the abbreviation of 'retweet'.
2114 // TRANS: %1$s is the repeated user's name, %2$s is the repeated notice.
2115 $content = sprintf(_('RT @%1$s %2$s'),
2116 $author->getNickname(),
2119 $maxlen = self::maxContent();
2120 if ($maxlen > 0 && mb_strlen($content) > $maxlen) {
2121 // Web interface and current Twitter API clients will
2122 // pull the original notice's text, but some older
2123 // clients and RSS/Atom feeds will see this trimmed text.
2125 // Unfortunately this is likely to lose tags or URLs
2126 // at the end of long notices.
2127 $content = mb_substr($content, 0, $maxlen - 4) . ' ...';
2131 // Scope is same as this one's
2132 return self::saveNew($repeater->id,
2135 array('repeat_of' => $this->id,
2136 'scope' => $this->scope));
2139 // These are supposed to be in chron order!
2141 function repeatStream($limit=100)
2143 $cache = Cache::instance();
2145 if (empty($cache)) {
2146 $ids = $this->_repeatStreamDirect($limit);
2148 $idstr = $cache->get(Cache::key('notice:repeats:'.$this->id));
2149 if ($idstr !== false) {
2150 if (empty($idstr)) {
2153 $ids = explode(',', $idstr);
2156 $ids = $this->_repeatStreamDirect(100);
2157 $cache->set(Cache::key('notice:repeats:'.$this->id), implode(',', $ids));
2160 // We do a max of 100, so slice down to limit
2161 $ids = array_slice($ids, 0, $limit);
2165 return NoticeStream::getStreamByIds($ids);
2168 function _repeatStreamDirect($limit)
2170 $notice = new Notice();
2172 $notice->selectAdd(); // clears it
2173 $notice->selectAdd('id');
2175 $notice->repeat_of = $this->id;
2177 $notice->orderBy('created, id'); // NB: asc!
2179 if (!is_null($limit)) {
2180 $notice->limit(0, $limit);
2183 return $notice->fetchAll('id');
2186 static function locationOptions($lat, $lon, $location_id, $location_ns, $profile = null)
2190 if (!empty($location_id) && !empty($location_ns)) {
2191 $options['location_id'] = $location_id;
2192 $options['location_ns'] = $location_ns;
2194 $location = Location::fromId($location_id, $location_ns);
2196 if ($location instanceof Location) {
2197 $options['lat'] = $location->lat;
2198 $options['lon'] = $location->lon;
2201 } else if (!empty($lat) && !empty($lon)) {
2202 $options['lat'] = $lat;
2203 $options['lon'] = $lon;
2205 $location = Location::fromLatLon($lat, $lon);
2207 if ($location instanceof Location) {
2208 $options['location_id'] = $location->location_id;
2209 $options['location_ns'] = $location->location_ns;
2211 } else if (!empty($profile)) {
2212 if (isset($profile->lat) && isset($profile->lon)) {
2213 $options['lat'] = $profile->lat;
2214 $options['lon'] = $profile->lon;
2217 if (isset($profile->location_id) && isset($profile->location_ns)) {
2218 $options['location_id'] = $profile->location_id;
2219 $options['location_ns'] = $profile->location_ns;
2226 function clearAttentions()
2228 $att = new Attention();
2229 $att->notice_id = $this->getID();
2232 while ($att->fetch()) {
2233 // Can't do delete() on the object directly since it won't remove all of it
2234 $other = clone($att);
2240 function clearReplies()
2242 $replyNotice = new Notice();
2243 $replyNotice->reply_to = $this->id;
2245 //Null any notices that are replies to this notice
2247 if ($replyNotice->find()) {
2248 while ($replyNotice->fetch()) {
2249 $orig = clone($replyNotice);
2250 $replyNotice->reply_to = null;
2251 $replyNotice->update($orig);
2257 $reply = new Reply();
2258 $reply->notice_id = $this->id;
2260 if ($reply->find()) {
2261 while($reply->fetch()) {
2262 self::blow('reply:stream:%d', $reply->profile_id);
2270 function clearLocation()
2272 $loc = new Notice_location();
2273 $loc->notice_id = $this->id;
2280 function clearFiles()
2282 $f2p = new File_to_post();
2284 $f2p->post_id = $this->id;
2287 while ($f2p->fetch()) {
2291 // FIXME: decide whether to delete File objects
2292 // ...and related (actual) files
2295 function clearRepeats()
2297 $repeatNotice = new Notice();
2298 $repeatNotice->repeat_of = $this->id;
2300 //Null any notices that are repeats of this notice
2302 if ($repeatNotice->find()) {
2303 while ($repeatNotice->fetch()) {
2304 $orig = clone($repeatNotice);
2305 $repeatNotice->repeat_of = null;
2306 $repeatNotice->update($orig);
2311 function clearTags()
2313 $tag = new Notice_tag();
2314 $tag->notice_id = $this->id;
2317 while ($tag->fetch()) {
2318 self::blow('profile:notice_ids_tagged:%d:%s', $this->profile_id, Cache::keyize($tag->tag));
2319 self::blow('profile:notice_ids_tagged:%d:%s;last', $this->profile_id, Cache::keyize($tag->tag));
2320 self::blow('notice_tag:notice_ids:%s', Cache::keyize($tag->tag));
2321 self::blow('notice_tag:notice_ids:%s;last', Cache::keyize($tag->tag));
2329 function clearGroupInboxes()
2331 $gi = new Group_inbox();
2333 $gi->notice_id = $this->id;
2336 while ($gi->fetch()) {
2337 self::blow('user_group:notice_ids:%d', $gi->group_id);
2345 function distribute()
2347 // We always insert for the author so they don't
2349 Event::handle('StartNoticeDistribute', array($this));
2351 // If there's a failure, we want to _force_
2352 // distribution at this point.
2354 $qm = QueueManager::get();
2355 $qm->enqueue($this, 'distrib');
2356 } catch (Exception $e) {
2357 // If the exception isn't transient, this
2358 // may throw more exceptions as DQH does
2359 // its own enqueueing. So, we ignore them!
2361 $handler = new DistribQueueHandler();
2362 $handler->handle($this);
2363 } catch (Exception $e) {
2364 common_log(LOG_ERR, "emergency redistribution resulted in " . $e->getMessage());
2366 // Re-throw so somebody smarter can handle it.
2373 $result = parent::insert();
2375 if ($result === false) {
2376 common_log_db_error($this, 'INSERT', __FILE__);
2377 // TRANS: Server exception thrown when a stored object entry cannot be saved.
2378 throw new ServerException('Could not save Notice');
2381 // Profile::hasRepeated() abuses pkeyGet(), so we
2382 // have to clear manually
2383 if (!empty($this->repeat_of)) {
2384 $c = self::memcache();
2386 $ck = self::multicacheKey('Notice',
2387 array('profile_id' => $this->profile_id,
2388 'repeat_of' => $this->repeat_of));
2393 // Update possibly ID-dependent columns: URI, conversation
2394 // (now that INSERT has added the notice's local id)
2395 $orig = clone($this);
2398 // We can only get here if it's a local notice, since remote notices
2399 // should've bailed out earlier due to lacking a URI.
2400 if (empty($this->uri)) {
2401 $this->uri = sprintf('%s%s=%d:%s=%s',
2403 'noticeId', $this->id,
2404 'objectType', $this->get_object_type(true));
2408 if ($changed && $this->update($orig) === false) {
2409 common_log_db_error($notice, 'UPDATE', __FILE__);
2410 // TRANS: Server exception thrown when a notice cannot be updated.
2411 throw new ServerException(_('Problem saving notice.'));
2414 $this->blowOnInsert();
2420 * Get the source of the notice
2422 * @return Notice_source $ns A notice source object. 'code' is the only attribute
2423 * guaranteed to be populated.
2425 function getSource()
2427 if (empty($this->source)) {
2431 $ns = new Notice_source();
2432 switch ($this->source) {
2439 $ns->code = $this->source;
2442 $ns = Notice_source::getKV($this->source);
2444 $ns = new Notice_source();
2445 $ns->code = $this->source;
2446 $app = Oauth_application::getKV('name', $this->source);
2448 $ns->name = $app->name;
2449 $ns->url = $app->source_url;
2459 * Determine whether the notice was locally created
2461 * @return boolean locality
2464 public function isLocal()
2466 return ($this->is_local == Notice::LOCAL_PUBLIC ||
2467 $this->is_local == Notice::LOCAL_NONPUBLIC);
2470 public function isRepeat()
2472 return !empty($this->repeat_of);
2476 * Get the list of hash tags saved with this notice.
2478 * @return array of strings
2480 public function getTags()
2482 // Check default scope (non-private notices)
2483 $inScope = (!$this->isPrivateScope());
2485 // Get current profile
2486 $profile = Profile::current();
2488 // Is the general scope check okay and the user in logged in?
2489 //* NOISY-DEBUG: */ common_debug('[' . __METHOD__ . ':' . __LINE__ . ']: inScope=' . intval($inScope) . ',profile[]=' . gettype($profile));
2490 if (($inScope === TRUE) && ($profile instanceof Profile)) {
2492 * Check scope, else a privacy leaks happens this way:
2494 * 1) Bob and Alice follow each other and write private notices
2495 * (this->scope=2) to each other.
2496 * 2) Bob uses tags in his private notice to alice (which she can
2498 * 3) Alice adds that notice (with tags) to her favorites
2500 * 4) The tags from Bob's private notice becomes visible in Alice's
2503 * This has the simple background that the scope is not being
2504 * re-checked. This has to be done here at this point because given
2505 * above scenario is a privacy leak as the tags may be *really*
2506 * private (nobody else shall see them) such as initmate words or
2507 * very political words.
2509 $inScope = $this->inScope($profile);
2510 //* NOISY-DEBUG: */ common_debug('[' . __METHOD__ . ':' . __LINE__ . ']: inScope=' . intval($inScope) . ' - After inScope() has been called.');
2515 $keypart = sprintf('notice:tags:%d', $this->id);
2517 $tagstr = self::cacheGet($keypart);
2519 if ($tagstr !== false) {
2520 $tags = explode(',', $tagstr);
2522 $tag = new Notice_tag();
2523 $tag->notice_id = $this->id;
2525 // Check scope for privacy-leak protection (see some lines above why)
2526 if (($inScope === TRUE) && ($tag->find())) {
2527 while ($tag->fetch()) {
2528 $tags[] = $tag->tag;
2531 self::cacheSet($keypart, implode(',', $tags));
2537 static private function utcDate($dt)
2539 $dateStr = date('d F Y H:i:s', strtotime($dt));
2540 $d = new DateTime($dateStr, new DateTimeZone('UTC'));
2541 return $d->format(DATE_W3C);
2545 * Look up the creation timestamp for a given notice ID, even
2546 * if it's been deleted.
2549 * @return mixed string recorded creation timestamp, or false if can't be found
2551 public static function getAsTimestamp($id)
2557 $notice = Notice::getKV('id', $id);
2559 return $notice->created;
2562 $deleted = Deleted_notice::getKV('id', $id);
2564 return $deleted->created;
2571 * Build an SQL 'where' fragment for timestamp-based sorting from a since_id
2572 * parameter, matching notices posted after the given one (exclusive).
2574 * If the referenced notice can't be found, will return false.
2577 * @param string $idField
2578 * @param string $createdField
2579 * @return mixed string or false if no match
2581 public static function whereSinceId($id, $idField='id', $createdField='created')
2583 $since = Notice::getAsTimestamp($id);
2585 return sprintf("($createdField = '%s' and $idField > %d) or ($createdField > '%s')", $since, $id, $since);
2591 * Build an SQL 'where' fragment for timestamp-based sorting from a since_id
2592 * parameter, matching notices posted after the given one (exclusive), and
2593 * if necessary add it to the data object's query.
2595 * @param DB_DataObject $obj
2597 * @param string $idField
2598 * @param string $createdField
2599 * @return mixed string or false if no match
2601 public static function addWhereSinceId(DB_DataObject $obj, $id, $idField='id', $createdField='created')
2603 $since = self::whereSinceId($id, $idField, $createdField);
2605 $obj->whereAdd($since);
2610 * Build an SQL 'where' fragment for timestamp-based sorting from a max_id
2611 * parameter, matching notices posted before the given one (inclusive).
2613 * If the referenced notice can't be found, will return false.
2616 * @param string $idField
2617 * @param string $createdField
2618 * @return mixed string or false if no match
2620 public static function whereMaxId($id, $idField='id', $createdField='created')
2622 $max = Notice::getAsTimestamp($id);
2624 return sprintf("($createdField < '%s') or ($createdField = '%s' and $idField <= %d)", $max, $max, $id);
2630 * Build an SQL 'where' fragment for timestamp-based sorting from a max_id
2631 * parameter, matching notices posted before the given one (inclusive), and
2632 * if necessary add it to the data object's query.
2634 * @param DB_DataObject $obj
2636 * @param string $idField
2637 * @param string $createdField
2638 * @return mixed string or false if no match
2640 public static function addWhereMaxId(DB_DataObject $obj, $id, $idField='id', $createdField='created')
2642 $max = self::whereMaxId($id, $idField, $createdField);
2644 $obj->whereAdd($max);
2650 return (($this->is_local != Notice::LOCAL_NONPUBLIC) &&
2651 ($this->is_local != Notice::GATEWAY));
2654 public function isPrivateScope () {
2655 return ($this->scope != Notice::SITE_SCOPE &&
2656 $this->scope != Notice::PUBLIC_SCOPE);
2660 * Check that the given profile is allowed to read, respond to, or otherwise
2661 * act on this notice.
2663 * The $scope member is a bitmask of scopes, representing a logical AND of the
2664 * scope requirement. So, 0x03 (Notice::ADDRESSEE_SCOPE | Notice::SITE_SCOPE) means
2665 * "only visible to people who are mentioned in the notice AND are users on this site."
2666 * Users on the site who are not mentioned in the notice will not be able to see the
2669 * @param Profile $profile The profile to check; pass null to check for public/unauthenticated users.
2671 * @return boolean whether the profile is in the notice's scope
2673 function inScope(Profile $profile=null)
2675 if (is_null($profile)) {
2676 $keypart = sprintf('notice:in-scope-for:%d:null', $this->id);
2678 $keypart = sprintf('notice:in-scope-for:%d:%d', $this->id, $profile->id);
2681 $result = self::cacheGet($keypart);
2683 if ($result === false) {
2685 if (Event::handle('StartNoticeInScope', array($this, $profile, &$bResult))) {
2686 $bResult = $this->_inScope($profile);
2687 Event::handle('EndNoticeInScope', array($this, $profile, &$bResult));
2689 $result = ($bResult) ? 1 : 0;
2690 self::cacheSet($keypart, $result, 0, 300);
2693 return ($result == 1) ? true : false;
2696 protected function _inScope(Profile $profile=null)
2698 if (!is_null($this->scope)) {
2699 $scope = $this->scope;
2701 $scope = self::defaultScope();
2704 if ($scope == 0 && !$this->getProfile()->isPrivateStream()) { // Not scoping, so it is public.
2705 return !$this->isHiddenSpam($profile);
2708 // If there's scope, anon cannot be in scope
2709 if (empty($profile)) {
2713 // Author is always in scope
2714 if ($this->profile_id == $profile->id) {
2718 // Only for users on this site
2719 if (($scope & Notice::SITE_SCOPE) && !$profile->isLocal()) {
2723 // Only for users mentioned in the notice
2724 if ($scope & Notice::ADDRESSEE_SCOPE) {
2726 $reply = Reply::pkeyGet(array('notice_id' => $this->id,
2727 'profile_id' => $profile->id));
2729 if (!$reply instanceof Reply) {
2734 // Only for members of the given group
2735 if ($scope & Notice::GROUP_SCOPE) {
2737 // XXX: just query for the single membership
2739 $groups = $this->getGroups();
2743 foreach ($groups as $group) {
2744 if ($profile->isMember($group)) {
2755 if ($scope & Notice::FOLLOWER_SCOPE || $this->getProfile()->isPrivateStream()) {
2757 if (!Subscription::exists($profile, $this->getProfile())) {
2762 return !$this->isHiddenSpam($profile);
2765 function isHiddenSpam(Profile $profile=null) {
2767 // Hide posts by silenced users from everyone but moderators.
2769 if (common_config('notice', 'hidespam')) {
2772 $author = $this->getProfile();
2773 } catch(Exception $e) {
2774 // If we can't get an author, keep it hidden.
2775 // XXX: technically not spam, but, whatever.
2779 if ($author->hasRole(Profile_role::SILENCED)) {
2780 if (!$profile instanceof Profile || (($profile->id !== $author->id) && (!$profile->hasRight(Right::REVIEWSPAM)))) {
2789 public function getParent()
2791 if (empty($this->reply_to)) {
2792 throw new NoParentNoticeException($this);
2794 return self::getByID($this->reply_to);
2798 * Magic function called at serialize() time.
2800 * We use this to drop a couple process-specific references
2801 * from DB_DataObject which can cause trouble in future
2804 * @return array of variable names to include in serialization.
2809 $vars = parent::__sleep();
2810 $skip = array('_profile', '_groups', '_attachments', '_faves', '_replies', '_repeats');
2811 return array_diff($vars, $skip);
2814 static function defaultScope()
2816 $scope = common_config('notice', 'defaultscope');
2817 if (is_null($scope)) {
2818 if (common_config('site', 'private')) {
2827 static function fillProfiles(array $notices)
2829 $map = self::getProfiles($notices);
2830 foreach ($notices as $entry=>$notice) {
2832 if (array_key_exists($notice->profile_id, $map)) {
2833 $notice->_setProfile($map[$notice->profile_id]);
2835 } catch (NoProfileException $e) {
2836 common_log(LOG_WARNING, "Failed to fill profile in Notice with non-existing entry for profile_id: {$e->profile_id}");
2837 unset($notices[$entry]);
2841 return array_values($map);
2844 static function getProfiles(array &$notices)
2847 foreach ($notices as $notice) {
2848 $ids[] = $notice->profile_id;
2850 $ids = array_unique($ids);
2851 return Profile::pivotGet('id', $ids);
2854 static function fillGroups(array &$notices)
2856 $ids = self::_idsOf($notices);
2857 $gis = Group_inbox::listGet('notice_id', $ids);
2860 foreach ($gis as $id => $gi) {
2863 $gids[] = $g->group_id;
2867 $gids = array_unique($gids);
2868 $group = User_group::pivotGet('id', $gids);
2869 foreach ($notices as $notice)
2872 $gi = $gis[$notice->id];
2873 foreach ($gi as $g) {
2874 $grps[] = $group[$g->group_id];
2876 $notice->_setGroups($grps);
2880 static function _idsOf(array &$notices)
2883 foreach ($notices as $notice) {
2884 $ids[$notice->id] = true;
2886 return array_keys($ids);
2889 static function fillAttachments(array &$notices)
2891 $ids = self::_idsOf($notices);
2892 $f2pMap = File_to_post::listGet('post_id', $ids);
2894 foreach ($f2pMap as $noticeId => $f2ps) {
2895 foreach ($f2ps as $f2p) {
2896 $fileIds[] = $f2p->file_id;
2900 $fileIds = array_unique($fileIds);
2901 $fileMap = File::pivotGet('id', $fileIds);
2902 foreach ($notices as $notice)
2905 $f2ps = $f2pMap[$notice->id];
2906 foreach ($f2ps as $f2p) {
2907 $files[] = $fileMap[$f2p->file_id];
2909 $notice->_setAttachments($files);
2913 static function fillReplies(array &$notices)
2915 $ids = self::_idsOf($notices);
2916 $replyMap = Reply::listGet('notice_id', $ids);
2917 foreach ($notices as $notice) {
2918 $replies = $replyMap[$notice->id];
2920 foreach ($replies as $reply) {
2921 $ids[] = $reply->profile_id;
2923 $notice->_setReplies($ids);
2928 * Checks whether the current profile is allowed (in scope) to see this notice.
2930 * @return $inScope Whether the current profile is allowed to see this notice
2932 function isCurrentProfileInScope () {
2933 // Check scope, default is allowed
2936 //* NOISY-DEBUG: */ common_debug('[' . __METHOD__ . ':' . __LINE__ . '] this->tag=' . $this->tag . ',this->id=' . $this->id . ',this->scope=' . $this->scope);
2938 // Is it private scope?
2939 if ($this->isPrivateScope()) {
2940 // 2) Get current profile
2941 $profile = Profile::current();
2943 // Is the profile not set?
2944 if (!$profile instanceof Profile) {
2945 // Public viewer shall not see a tag from a private dent (privacy leak)
2946 //* NOISY-DEBUG: */ common_debug('[' . __METHOD__ . ':' . __LINE__ . '] Not logged in (public view).');
2948 } elseif (!$this->inScope($profile)) {
2949 // Current profile is not in scope (not allowed to see) of notice
2950 //* NOISY-DEBUG: */ common_debug('[' . __METHOD__ . ':' . __LINE__ . '] profile->id=' . $profile->id . ' is not allowed to see this notice.');
2956 //* NOISY-DEBUG: */ common_debug('[' . __METHOD__ . ':' . __LINE__ . '] this->tag=' . $this->tag . ',this->weight=' . $this->weight . ',inScope=' . intval($inScope) . ' - EXIT!');
2960 static public function beforeSchemaUpdate()
2962 $table = strtolower(get_called_class());
2963 $schema = Schema::get();
2964 $schemadef = $schema->getTableDef($table);
2966 // 2015-09-04 We move Notice location data to Notice_location
2967 // First we see if we have to do this at all
2968 if (!isset($schemadef['fields']['lat'])
2969 && !isset($schemadef['fields']['lon'])
2970 && !isset($schemadef['fields']['location_id'])
2971 && !isset($schemadef['fields']['location_ns'])) {
2972 // We have already removed the location fields, so no need to migrate.
2975 // Then we make sure the Notice_location table is created!
2976 $schema->ensureTable('notice_location', Notice_location::schemaDef());
2978 // Then we continue on our road to migration!
2979 echo "\nFound old $table table, moving location data to 'notice_location' table... (this will probably take a LONG time, but can be aborted and continued)";
2981 $notice = new Notice();
2982 $notice->query(sprintf('SELECT id, lat, lon, location_id, location_ns FROM %1$s ' .
2983 'WHERE lat IS NOT NULL ' .
2984 'OR lon IS NOT NULL ' .
2985 'OR location_id IS NOT NULL ' .
2986 'OR location_ns IS NOT NULL',
2987 $schema->quoteIdentifier($table)));
2988 print "\nFound {$notice->N} notices with location data, inserting";
2989 while ($notice->fetch()) {
2990 $notloc = Notice_location::getKV('notice_id', $notice->id);
2991 if ($notloc instanceof Notice_location) {
2995 $notloc = new Notice_location();
2996 $notloc->notice_id = $notice->id;
2997 $notloc->lat= $notice->lat;
2998 $notloc->lon= $notice->lon;
2999 $notloc->location_id= $notice->location_id;
3000 $notloc->location_ns= $notice->location_ns;