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 $self; // varchar(191) not 255 because utf8mb4 takes more space
63 public $created; // datetime multiple_key not_null default_0000-00-00%2000%3A00%3A00
64 public $modified; // timestamp not_null default_CURRENT_TIMESTAMP
65 public $reply_to; // int(4)
66 public $is_local; // int(4)
67 public $source; // varchar(32)
68 public $conversation; // int(4)
69 public $repeat_of; // int(4)
70 public $verb; // varchar(191) not 255 because utf8mb4 takes more space
71 public $object_type; // varchar(191) not 255 because utf8mb4 takes more space
72 public $scope; // int(4)
74 /* the code above is auto generated do not remove the tag below */
77 public static function schemaDef()
81 'id' => array('type' => 'serial', 'not null' => true, 'description' => 'unique identifier'),
82 'profile_id' => array('type' => 'int', 'not null' => true, 'description' => 'who made the update'),
83 'uri' => array('type' => 'varchar', 'length' => 191, 'description' => 'universally unique identifier, usually a tag URI'),
84 'content' => array('type' => 'text', 'description' => 'update content', 'collate' => 'utf8mb4_general_ci'),
85 'rendered' => array('type' => 'text', 'description' => 'HTML version of the content'),
86 'url' => array('type' => 'varchar', 'length' => 191, 'description' => 'URL of any attachment (image, video, bookmark, whatever)'),
87 'self' => array('type' => 'varchar', 'length' => 191, 'description' => 'Resolvable URL to the (remote) Atom entry representation'),
88 'created' => array('type' => 'datetime', 'not null' => true, 'description' => 'date this record was created'),
89 'modified' => array('type' => 'timestamp', 'not null' => true, 'description' => 'date this record was modified'),
90 'reply_to' => array('type' => 'int', 'description' => 'notice replied to (usually a guess)'),
91 'is_local' => array('type' => 'int', 'size' => 'tiny', 'default' => 0, 'description' => 'notice was generated by a user'),
92 'source' => array('type' => 'varchar', 'length' => 32, 'description' => 'source of comment, like "web", "im", or "clientname"'),
93 'conversation' => array('type' => 'int', 'description' => 'the local numerical conversation id'),
94 'repeat_of' => array('type' => 'int', 'description' => 'notice this is a repeat of'),
95 'object_type' => array('type' => 'varchar', 'length' => 191, 'description' => 'URI representing activity streams object type', 'default' => null),
96 'verb' => array('type' => 'varchar', 'length' => 191, 'description' => 'URI representing activity streams verb', 'default' => 'http://activitystrea.ms/schema/1.0/post'),
97 'scope' => array('type' => 'int',
98 'description' => 'bit map for distribution scope; 0 = everywhere; 1 = this server only; 2 = addressees; 4 = followers; null = default'),
100 'primary key' => array('id'),
101 'unique keys' => array(
102 'notice_uri_key' => array('uri'),
104 'foreign keys' => array(
105 'notice_profile_id_fkey' => array('profile', array('profile_id' => 'id')),
106 'notice_reply_to_fkey' => array('notice', array('reply_to' => 'id')),
107 'notice_conversation_fkey' => array('conversation', array('conversation' => 'id')), # note... used to refer to notice.id
108 'notice_repeat_of_fkey' => array('notice', array('repeat_of' => 'id')), # @fixme: what about repeats of deleted notices?
111 'notice_created_id_is_local_idx' => array('created', 'id', 'is_local'),
112 'notice_profile_id_idx' => array('profile_id', 'created', 'id'),
113 'notice_repeat_of_created_id_idx' => array('repeat_of', 'created', 'id'),
114 'notice_conversation_created_id_idx' => array('conversation', 'created', 'id'),
115 'notice_object_type_idx' => array('object_type'),
116 'notice_verb_idx' => array('verb'),
117 'notice_profile_id_verb_idx' => array('profile_id', 'verb'),
118 'notice_url_idx' => array('url'), // Qvitter wants this
119 'notice_replyto_idx' => array('reply_to')
123 if (common_config('search', 'type') == 'fulltext') {
124 $def['fulltext indexes'] = array('content' => array('content'));
131 const LOCAL_PUBLIC = 1;
133 const LOCAL_NONPUBLIC = -1;
136 const PUBLIC_SCOPE = 0; // Useful fake constant
137 const SITE_SCOPE = 1;
138 const ADDRESSEE_SCOPE = 2;
139 const GROUP_SCOPE = 4;
140 const FOLLOWER_SCOPE = 8;
142 protected $_profile = array();
145 * Will always return a profile, if anything fails it will
146 * (through _setProfile) throw a NoProfileException.
148 public function getProfile()
150 if (!isset($this->_profile[$this->profile_id])) {
151 // We could've sent getKV directly to _setProfile, but occasionally we get
152 // a "false" (instead of null), likely because it indicates a cache miss.
153 $profile = Profile::getKV('id', $this->profile_id);
154 $this->_setProfile($profile instanceof Profile ? $profile : null);
156 return $this->_profile[$this->profile_id];
159 public function _setProfile(Profile $profile=null)
161 if (!$profile instanceof Profile) {
162 throw new NoProfileException($this->profile_id);
164 $this->_profile[$this->profile_id] = $profile;
167 public function deleteAs(Profile $actor, $delete_event=true)
169 if (!$this->getProfile()->sameAs($actor) && !$actor->hasRight(Right::DELETEOTHERSNOTICE)) {
170 throw new AuthorizationException(_('You are not allowed to delete another user\'s notice.'));
174 if (!$delete_event || Event::handle('DeleteNoticeAsProfile', array($this, $actor, &$result))) {
175 // If $delete_event is true, we run the event. If the Event then
176 // returns false it is assumed everything was handled properly
177 // and the notice was deleted.
178 $result = $this->delete();
183 protected function deleteRelated()
185 if (Event::handle('NoticeDeleteRelated', array($this))) {
186 // Clear related records
187 $this->clearReplies();
188 $this->clearLocation();
189 $this->clearRepeats();
191 $this->clearGroupInboxes();
193 $this->clearAttentions();
194 // NOTE: we don't clear queue items
198 public function delete($useWhere=false)
200 $this->deleteRelated();
202 $result = parent::delete($useWhere);
204 $this->blowOnDelete();
208 public function getUri()
214 * Get a Notice object by URI. Will call external plugins for help
215 * using the event StartGetNoticeFromURI.
217 * @param string $uri A unique identifier for a resource (notice in this case)
219 static function fromUri($uri)
223 if (Event::handle('StartGetNoticeFromUri', array($uri, &$notice))) {
224 $notice = Notice::getKV('uri', $uri);
225 Event::handle('EndGetNoticeFromUri', array($uri, $notice));
228 if (!$notice instanceof Notice) {
229 throw new UnknownUriException($uri);
236 * @param $root boolean If true, link to just the conversation root.
238 * @return URL to conversation
240 public function getConversationUrl($anchor=true)
242 return Conversation::getUrlFromNotice($this, $anchor);
246 * Get the local representation URL of this notice.
248 public function getLocalUrl()
250 return common_local_url('shownotice', array('notice' => $this->id), null, null, false);
253 public function getTitle($imply=true)
256 if (Event::handle('GetNoticeTitle', array($this, &$title)) && $imply) {
257 // TRANS: Title of a notice posted without a title value.
258 // TRANS: %1$s is a user name, %2$s is the notice creation date/time.
259 $title = sprintf(_('%1$s\'s status on %2$s'),
260 $this->getProfile()->getFancyName(),
261 common_exact_date($this->created));
266 public function getContent()
268 return $this->content;
271 public function getRendered()
273 // we test $this->id because if it's not inserted yet, we can't update the field
274 if (!empty($this->id) && (is_null($this->rendered) || $this->rendered === '')) {
275 // update to include rendered content on-the-fly, so we don't have to have a fix-up script in upgrade.php
276 common_debug('Rendering notice '.$this->getID().' as it had no rendered HTML content.');
277 $orig = clone($this);
278 $this->rendered = common_render_content($this->getContent(),
280 $this->hasParent() ? $this->getParent() : null);
281 $this->update($orig);
283 return $this->rendered;
286 public function getCreated()
288 return $this->created;
291 public function getVerb($make_relative=false)
293 return ActivityUtils::resolveUri($this->verb, $make_relative);
296 public function isVerb(array $verbs)
298 return ActivityUtils::compareVerbs($this->getVerb(), $verbs);
302 * Get the original representation URL of this notice.
304 * @param boolean $fallback Whether to fall back to generate a local URL or throw InvalidUrlException
306 public function getUrl($fallback=false)
308 // The risk is we start having empty urls and non-http uris...
309 // and we can't really handle any other protocol right now.
311 case $this->isLocal():
312 return common_local_url('shownotice', array('notice' => $this->getID()), null, null, false);
313 case common_valid_http_url($this->url): // should we allow non-http/https URLs?
315 case common_valid_http_url($this->uri): // Sometimes we only have the URI for remote posts.
318 // let's generate a valid link to our locally available notice on demand
319 return common_local_url('shownotice', array('notice' => $this->getID()), null, null, false);
321 throw new InvalidUrlException($this->url);
325 public function getSelfLink()
327 if ($this->isLocal()) {
328 return common_local_url('ApiStatusesShow', array('id' => $this->getID(), 'format' => 'atom'));
331 if (!common_valid_http_url($this->self)) {
332 throw new InvalidUrlException($this->url);
338 public function getObjectType($canonical=false) {
339 if (is_null($this->object_type) || $this->object_type==='') {
340 throw new NoObjectTypeException($this);
342 return ActivityUtils::resolveUri($this->object_type, $canonical);
345 public function isObjectType(array $types)
348 return ActivityUtils::compareTypes($this->getObjectType(), $types);
349 } catch (NoObjectTypeException $e) {
355 * Extract #hashtags from this notice's content and save them to the database.
359 /* extract all #hastags */
360 $count = preg_match_all('/(?:^|\s)#([\pL\pN_\-\.]{1,64})/u', strtolower($this->content), $match);
365 /* Add them to the database */
366 return $this->saveKnownTags($match[1]);
370 * Record the given set of hash tags in the db for this notice.
371 * Given tag strings will be normalized and checked for dupes.
373 function saveKnownTags($hashtags)
375 //turn each into their canonical tag
376 //this is needed to remove dupes before saving e.g. #hash.tag = #hashtag
377 for($i=0; $i<count($hashtags); $i++) {
378 /* elide characters we don't want in the tag */
379 $hashtags[$i] = common_canonical_tag($hashtags[$i]);
382 foreach(array_unique($hashtags) as $hashtag) {
383 $this->saveTag($hashtag);
384 self::blow('profile:notice_ids_tagged:%d:%s', $this->profile_id, $hashtag);
390 * Record a single hash tag as associated with this notice.
391 * Tag format and uniqueness must be validated by caller.
393 function saveTag($hashtag)
395 $tag = new Notice_tag();
396 $tag->notice_id = $this->id;
397 $tag->tag = $hashtag;
398 $tag->created = $this->created;
399 $id = $tag->insert();
402 // TRANS: Server exception. %s are the error details.
403 throw new ServerException(sprintf(_('Database error inserting hashtag: %s.'),
404 $last_error->message));
408 // if it's saved, blow its cache
409 $tag->blowCache(false);
413 * Save a new notice and push it out to subscribers' inboxes.
414 * Poster's permissions are checked before sending.
416 * @param int $profile_id Profile ID of the poster
417 * @param string $content source message text; links may be shortened
418 * per current user's preference
419 * @param string $source source key ('web', 'api', etc)
420 * @param array $options Associative array of optional properties:
421 * string 'created' timestamp of notice; defaults to now
422 * int 'is_local' source/gateway ID, one of:
423 * Notice::LOCAL_PUBLIC - Local, ok to appear in public timeline
424 * Notice::REMOTE - Sent from a remote service;
425 * hide from public timeline but show in
426 * local "and friends" timelines
427 * Notice::LOCAL_NONPUBLIC - Local, but hide from public timeline
428 * Notice::GATEWAY - From another non-OStatus service;
429 * will not appear in public views
430 * float 'lat' decimal latitude for geolocation
431 * float 'lon' decimal longitude for geolocation
432 * int 'location_id' geoname identifier
433 * int 'location_ns' geoname namespace to interpret location_id
434 * int 'reply_to'; notice ID this is a reply to
435 * int 'repeat_of'; notice ID this is a repeat of
436 * string 'uri' unique ID for notice; a unique tag uri (can be url or anything too)
437 * string 'url' permalink to notice; defaults to local notice URL
438 * string 'rendered' rendered HTML version of content
439 * array 'replies' list of profile URIs for reply delivery in
440 * place of extracting @-replies from content.
441 * array 'groups' list of group IDs to deliver to, in place of
442 * extracting ! tags from content
443 * array 'tags' list of hashtag strings to save with the notice
444 * in place of extracting # tags from content
445 * array 'urls' list of attached/referred URLs to save with the
446 * notice in place of extracting links from content
447 * boolean 'distribute' whether to distribute the notice, default true
448 * string 'object_type' URL of the associated object type (default ActivityObject::NOTE)
449 * string 'verb' URL of the associated verb (default ActivityVerb::POST)
450 * int 'scope' Scope bitmask; default to SITE_SCOPE on private sites, 0 otherwise
452 * @fixme tag override
455 * @throws ClientException
457 static function saveNew($profile_id, $content, $source, array $options=null) {
458 $defaults = array('uri' => null,
461 'conversation' => null, // URI of conversation
462 'reply_to' => null, // This will override convo URI if the parent is known
463 'repeat_of' => null, // This will override convo URI if the repeated notice is known
465 'distribute' => true,
466 'object_type' => null,
469 if (!empty($options) && is_array($options)) {
470 $options = array_merge($defaults, $options);
476 if (!isset($is_local)) {
477 $is_local = Notice::LOCAL_PUBLIC;
480 $profile = Profile::getKV('id', $profile_id);
481 if (!$profile instanceof Profile) {
482 // TRANS: Client exception thrown when trying to save a notice for an unknown user.
483 throw new ClientException(_('Problem saving notice. Unknown user.'));
486 $user = User::getKV('id', $profile_id);
487 if ($user instanceof User) {
488 // Use the local user's shortening preferences, if applicable.
489 $final = $user->shortenLinks($content);
491 $final = common_shorten_links($content);
494 if (Notice::contentTooLong($final)) {
495 // TRANS: Client exception thrown if a notice contains too many characters.
496 throw new ClientException(_('Problem saving notice. Too long.'));
499 if (common_config('throttle', 'enabled') && !Notice::checkEditThrottle($profile_id)) {
500 common_log(LOG_WARNING, 'Excessive posting by profile #' . $profile_id . '; throttled.');
501 // TRANS: Client exception thrown when a user tries to post too many notices in a given time frame.
502 throw new ClientException(_('Too many notices too fast; take a breather '.
503 'and post again in a few minutes.'));
506 if (common_config('site', 'dupelimit') > 0 && !Notice::checkDupes($profile_id, $final)) {
507 common_log(LOG_WARNING, 'Dupe posting by profile #' . $profile_id . '; throttled.');
508 // TRANS: Client exception thrown when a user tries to post too many duplicate notices in a given time frame.
509 throw new ClientException(_('Too many duplicate messages too quickly;'.
510 ' take a breather and post again in a few minutes.'));
513 if (!$profile->hasRight(Right::NEWNOTICE)) {
514 common_log(LOG_WARNING, "Attempted post from user disallowed to post: " . $profile->nickname);
516 // TRANS: Client exception thrown when a user tries to post while being banned.
517 throw new ClientException(_('You are banned from posting notices on this site.'), 403);
520 $notice = new Notice();
521 $notice->profile_id = $profile_id;
523 if ($source && in_array($source, common_config('public', 'autosource'))) {
524 $notice->is_local = Notice::LOCAL_NONPUBLIC;
526 $notice->is_local = $is_local;
529 if (!empty($created)) {
530 $notice->created = $created;
532 $notice->created = common_sql_now();
535 if (!$notice->isLocal()) {
536 // Only do these checks for non-local notices. Local notices will generate these values later.
538 throw new ServerException('No URI for remote notice. Cannot accept that.');
542 $notice->content = $final;
544 $notice->source = $source;
547 if ($self && common_valid_http_url($self)) {
548 $notice->self = $self;
551 // Get the groups here so we can figure out replies and such
552 if (!isset($groups)) {
553 $groups = User_group::idsFromText($notice->content, $profile);
558 // Handle repeat case
560 if (!empty($options['repeat_of'])) {
562 // Check for a private one
564 $repeat = Notice::getByID($options['repeat_of']);
566 if ($profile->sameAs($repeat->getProfile())) {
567 // TRANS: Client error displayed when trying to repeat an own notice.
568 throw new ClientException(_('You cannot repeat your own notice.'));
571 if ($repeat->scope != Notice::SITE_SCOPE &&
572 $repeat->scope != Notice::PUBLIC_SCOPE) {
573 // TRANS: Client error displayed when trying to repeat a non-public notice.
574 throw new ClientException(_('Cannot repeat a private notice.'), 403);
577 if (!$repeat->inScope($profile)) {
578 // The generic checks above should cover this, but let's be sure!
579 // TRANS: Client error displayed when trying to repeat a notice you cannot access.
580 throw new ClientException(_('Cannot repeat a notice you cannot read.'), 403);
583 if ($profile->hasRepeated($repeat)) {
584 // TRANS: Client error displayed when trying to repeat an already repeated notice.
585 throw new ClientException(_('You already repeated that notice.'));
588 $notice->repeat_of = $repeat->id;
589 $notice->conversation = $repeat->conversation;
593 // If $reply_to is specified, we check that it exists, and then
594 // return it if it does
595 if (!empty($reply_to)) {
596 $reply = Notice::getKV('id', $reply_to);
597 } elseif (in_array($source, array('xmpp', 'mail', 'sms'))) {
598 // If the source lacks capability of sending the "reply_to"
599 // metadata, let's try to find an inline replyto-reference.
600 $reply = self::getInlineReplyTo($profile, $final);
603 if ($reply instanceof Notice) {
604 if (!$reply->inScope($profile)) {
605 // TRANS: Client error displayed when trying to reply to a notice a the target has no access to.
606 // TRANS: %1$s is a user nickname, %2$d is a notice ID (number).
607 throw new ClientException(sprintf(_('%1$s has no access to notice %2$d.'),
608 $profile->nickname, $reply->id), 403);
611 // If it's a repeat, the reply_to should be to the original
612 if ($reply->isRepeat()) {
613 $notice->reply_to = $reply->repeat_of;
615 $notice->reply_to = $reply->id;
617 // But the conversation ought to be the same :)
618 $notice->conversation = $reply->conversation;
620 // If the original is private to a group, and notice has
621 // no group specified, make it to the same group(s)
623 if (empty($groups) && ($reply->scope & Notice::GROUP_SCOPE)) {
625 $replyGroups = $reply->getGroups();
626 foreach ($replyGroups as $group) {
627 if ($profile->isMember($group)) {
628 $groups[] = $group->id;
636 // If we don't know the reply, we might know the conversation!
637 // This will happen if a known remote user replies to an
638 // unknown remote user - within a known conversation.
639 if (empty($notice->conversation) and !empty($options['conversation'])) {
640 $conv = Conversation::getKV('uri', $options['conversation']);
641 if ($conv instanceof Conversation) {
642 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.').');
644 // Conversation entry with specified URI was not found, so we must create it.
645 common_debug('Conversation URI not found, so we will create it with the URI given in the options to Notice::saveNew: '.$options['conversation']);
646 $convctx = new ActivityContext();
647 $convctx->conversation = $options['conversation'];
648 if (array_key_exists('conversation_url', $options)) {
649 $convctx->conversation_url = $options['conversation_url'];
651 // The insert in Conversation::create throws exception on failure
652 $conv = Conversation::create($convctx, $notice->created);
654 $notice->conversation = $conv->getID();
659 // If it's not part of a conversation, it's the beginning of a new conversation.
660 if (empty($notice->conversation)) {
661 $conv = Conversation::create();
662 $notice->conversation = $conv->getID();
667 $notloc = new Notice_location();
668 if (!empty($lat) && !empty($lon)) {
673 if (!empty($location_ns) && !empty($location_id)) {
674 $notloc->location_id = $location_id;
675 $notloc->location_ns = $location_ns;
678 if (!empty($rendered)) {
679 $notice->rendered = $rendered;
681 $notice->rendered = common_render_content($final,
682 $notice->getProfile(),
683 $notice->hasParent() ? $notice->getParent() : null);
687 if ($notice->isRepeat()) {
688 $notice->verb = ActivityVerb::SHARE;
689 $notice->object_type = ActivityObject::ACTIVITY;
691 $notice->verb = ActivityVerb::POST;
694 $notice->verb = $verb;
697 if (empty($object_type)) {
698 $notice->object_type = (empty($notice->reply_to)) ? ActivityObject::NOTE : ActivityObject::COMMENT;
700 $notice->object_type = $object_type;
703 if (is_null($scope) && $reply instanceof Notice) {
704 $notice->scope = $reply->scope;
706 $notice->scope = $scope;
709 $notice->scope = self::figureOutScope($profile, $groups, $notice->scope);
711 if (Event::handle('StartNoticeSave', array(&$notice))) {
713 // XXX: some of these functions write to the DB
716 $notice->insert(); // throws exception on failure, if successful we have an ->id
718 if (($notloc->lat && $notloc->lon) || ($notloc->location_id && $notloc->location_ns)) {
719 $notloc->notice_id = $notice->getID();
720 $notloc->insert(); // store the notice location if it had any information
722 } catch (Exception $e) {
723 // Let's test if we managed initial insert, which would imply
724 // failing on some update-part (check 'insert()'). Delete if
725 // something had been stored to the database.
726 if (!empty($notice->id)) {
733 // Only save 'attention' and metadata stuff (URLs, tags...) stuff if
734 // the activityverb is a POST (since stuff like repeat, favorite etc.
735 // reasonably handle notifications themselves.
736 if (ActivityUtils::compareVerbs($notice->verb, array(ActivityVerb::POST))) {
737 if (isset($replies)) {
738 $notice->saveKnownReplies($replies);
740 $notice->saveReplies();
744 $notice->saveKnownTags($tags);
749 // Note: groups may save tags, so must be run after tags are saved
750 // to avoid errors on duplicates.
751 // Note: groups should always be set.
753 $notice->saveKnownGroups($groups);
756 $notice->saveKnownUrls($urls);
763 // Prepare inbox delivery, may be queued to background.
764 $notice->distribute();
770 static function saveActivity(Activity $act, Profile $actor, array $options=array())
772 // First check if we're going to let this Activity through from the specific actor
773 if (!$actor->hasRight(Right::NEWNOTICE)) {
774 common_log(LOG_WARNING, "Attempted post from user disallowed to post: " . $actor->getNickname());
776 // TRANS: Client exception thrown when a user tries to post while being banned.
777 throw new ClientException(_m('You are banned from posting notices on this site.'), 403);
779 if (common_config('throttle', 'enabled') && !self::checkEditThrottle($actor->id)) {
780 common_log(LOG_WARNING, 'Excessive posting by profile #' . $actor->id . '; throttled.');
781 // TRANS: Client exception thrown when a user tries to post too many notices in a given time frame.
782 throw new ClientException(_m('Too many notices too fast; take a breather '.
783 'and post again in a few minutes.'));
786 // Get ActivityObject properties
788 if (!empty($act->id)) {
790 $options['uri'] = $act->id;
791 $options['url'] = $act->link;
792 if ($act->selfLink) {
793 $options['self'] = $act->selfLink;
796 $actobj = count($act->objects)===1 ? $act->objects[0] : null;
797 if (!is_null($actobj) && !empty($actobj->id)) {
798 $options['uri'] = $actobj->id;
800 $options['url'] = $actobj->link;
801 } elseif (preg_match('!^https?://!', $actobj->id)) {
802 $options['url'] = $actobj->id;
805 if ($actobj->selfLink) {
806 $options['self'] = $actobj->selfLink;
812 'is_local' => $actor->isLocal() ? self::LOCAL_PUBLIC : self::REMOTE,
813 'mentions' => array(),
818 'source' => 'unknown',
823 'distribute' => true);
825 // options will have default values when nothing has been supplied
826 $options = array_merge($defaults, $options);
827 foreach (array_keys($defaults) as $key) {
828 // Only convert the keynames we specify ourselves from 'defaults' array into variables
829 $$key = $options[$key];
831 extract($options, EXTR_SKIP);
834 $stored = new Notice();
835 if (!empty($uri) && !ActivityUtils::compareVerbs($act->verb, array(ActivityVerb::DELETE))) {
837 if ($stored->find()) {
838 common_debug('cannot create duplicate Notice URI: '.$stored->uri);
839 // I _assume_ saving a Notice with a colliding URI means we're really trying to
840 // save the same notice again...
841 throw new AlreadyFulfilledException('Notice URI already exists');
845 // NOTE: Sandboxed users previously got all the notices _during_
846 // sandbox period set to to is_local=Notice::LOCAL_NONPUBLIC here.
847 // Since then we have started just filtering _when_ it gets shown
848 // instead of creating a mixed jumble of differently scoped notices.
850 if ($source && in_array($source, common_config('public', 'autosource'))) {
851 $stored->is_local = Notice::LOCAL_NONPUBLIC;
853 $stored->is_local = intval($is_local);
856 if (!$stored->isLocal()) {
857 // Only do these checks for non-local notices. Local notices will generate these values later.
858 if (!common_valid_http_url($url)) {
859 common_debug('Bad notice URL: ['.$url.'], URI: ['.$uri.']. Cannot link back to original! This is normal for shared notices etc.');
862 throw new ServerException('No URI for remote notice. Cannot accept that.');
866 $stored->profile_id = $actor->getID();
867 $stored->source = $source;
870 if (common_valid_http_url($stored->self)) {
871 $stored->self = $self;
873 $stored->verb = $act->verb;
875 // we use mb_strlen because it _might_ be that the content is just the string "0"...
876 $content = mb_strlen($act->content) ? $act->content : $act->summary;
877 if (mb_strlen($content)===0 && !is_null($actobj)) {
878 $content = mb_strlen($actobj->content) ? $actobj->content : $actobj->summary;
880 // Strip out any bad HTML from $content. URI.Base is used to sort out relative URLs.
881 $stored->rendered = common_purify($content, ['URI.Base' => $stored->url ?: null]);
882 $stored->content = common_strip_html($stored->getRendered(), true, true);
883 if (trim($stored->content) === '') {
884 // TRANS: Error message when the plain text content of a notice has zero length.
885 throw new ClientException(_('Empty notice content, will not save this.'));
887 unset($content); // garbage collect
889 // Maybe a missing act-time should be fatal if the actor is not local?
890 if (!empty($act->time)) {
891 $stored->created = common_sql_date($act->time);
893 $stored->created = common_sql_now();
896 $reply = null; // this will store the in-reply-to Notice if found
897 $replyUris = []; // this keeps a list of possible URIs to look up
898 if ($act->context instanceof ActivityContext && !empty($act->context->replyToID)) {
899 $replyUris[] = $act->context->replyToID;
901 if ($act->target instanceof ActivityObject && !empty($act->target->id)) {
902 $replyUris[] = $act->target->id;
904 foreach (array_unique($replyUris) as $replyUri) {
905 $reply = self::getKV('uri', $replyUri);
906 // Only do remote fetching if we're not a private site
907 if (!common_config('site', 'private') && !$reply instanceof Notice) {
908 // the URI is the object we're looking for, $actor is a
909 // Profile that surely knows of it and &$reply where it
910 // will be stored when fetched
911 Event::handle('FetchRemoteNotice', array($replyUri, $actor, &$reply));
913 // we got what we're in-reply-to now, so let's move on
914 if ($reply instanceof Notice) {
917 // otherwise reset whatever we might've gotten from the event
920 unset($replyUris); // garbage collect
922 if ($reply instanceof Notice) {
923 if (!$reply->inScope($actor)) {
924 // TRANS: Client error displayed when trying to reply to a notice a the target has no access to.
925 // TRANS: %1$s is a user nickname, %2$d is a notice ID (number).
926 throw new ClientException(sprintf(_m('%1$s has no right to reply to notice %2$d.'), $actor->getNickname(), $reply->id), 403);
929 $stored->reply_to = $reply->id;
930 $stored->conversation = $reply->conversation;
932 // If the original is private to a group, and notice has no group specified,
933 // make it to the same group(s)
934 if (empty($groups) && ($reply->scope & Notice::GROUP_SCOPE)) {
935 $replyGroups = $reply->getGroups();
936 foreach ($replyGroups as $group) {
937 if ($actor->isMember($group)) {
938 $groups[] = $group->id;
943 if (is_null($scope)) {
944 $scope = $reply->scope;
947 // If we don't know the reply, we might know the conversation!
948 // This will happen if a known remote user replies to an
949 // unknown remote user - within a known conversation.
950 if (empty($stored->conversation) and !empty($act->context->conversation)) {
951 $conv = Conversation::getKV('uri', $act->context->conversation);
952 if ($conv instanceof Conversation) {
953 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.').');
955 // Conversation entry with specified URI was not found, so we must create it.
956 common_debug('Conversation URI not found, so we will create it with the URI given in the context of the activity: '.$act->context->conversation);
957 // The insert in Conversation::create throws exception on failure
958 $conv = Conversation::create($act->context, $stored->created);
960 $stored->conversation = $conv->getID();
964 unset($reply); // garbage collect
966 // If it's not part of a conversation, it's the beginning of a new conversation.
967 if (empty($stored->conversation)) {
968 $conv = Conversation::create();
969 $stored->conversation = $conv->getID();
974 if ($act->context instanceof ActivityContext) {
975 if ($act->context->location instanceof Location) {
976 $notloc = Notice_location::fromLocation($act->context->location);
979 $act->context = new ActivityContext();
982 if (array_key_exists(ActivityContext::ATTN_PUBLIC, $act->context->attention)) {
983 $stored->scope = Notice::PUBLIC_SCOPE;
984 // TODO: maybe we should actually keep this? if the saveAttentions thing wants to use it...
985 unset($act->context->attention[ActivityContext::ATTN_PUBLIC]);
987 $stored->scope = self::figureOutScope($actor, $groups, $scope);
990 foreach ($act->categories as $cat) {
992 $term = common_canonical_tag($cat->term);
999 foreach ($act->enclosures as $href) {
1000 // @todo FIXME: Save these locally or....?
1004 if (ActivityUtils::compareVerbs($stored->verb, array(ActivityVerb::POST))) {
1005 if (empty($act->objects[0]->type)) {
1006 // Default type for the post verb is 'note', but we know it's
1007 // a 'comment' if it is in reply to something.
1008 $stored->object_type = empty($stored->reply_to) ? ActivityObject::NOTE : ActivityObject::COMMENT;
1010 //TODO: Is it safe to always return a relative URI? The
1011 // JSON version of ActivityStreams always use it, so we
1012 // should definitely be able to handle it...
1013 $stored->object_type = ActivityUtils::resolveUri($act->objects[0]->type, true);
1017 if (Event::handle('StartNoticeSave', array(&$stored))) {
1018 // XXX: some of these functions write to the DB
1021 $result = $stored->insert(); // throws exception on error
1023 if ($notloc instanceof Notice_location) {
1024 $notloc->notice_id = $stored->getID();
1028 $orig = clone($stored); // for updating later in this try clause
1031 Event::handle('StoreActivityObject', array($act, $stored, $options, &$object));
1032 if (empty($object)) {
1033 throw new NoticeSaveException('Unsuccessful call to StoreActivityObject '._ve($stored->getUri()) . ': '._ve($act->asString()));
1037 // If something changed in the Notice during StoreActivityObject
1038 $stored->update($orig);
1039 } catch (Exception $e) {
1040 if (empty($stored->id)) {
1041 common_debug('Failed to save stored object entry in database ('.$e->getMessage().')');
1043 common_debug('Failed to store activity object in database ('.$e->getMessage().'), deleting notice id '.$stored->id);
1049 unset($notloc); // garbage collect
1051 if (!$stored instanceof Notice) {
1052 throw new ServerException('StartNoticeSave did not give back a Notice.');
1053 } elseif (empty($stored->id)) {
1054 throw new ServerException('Supposedly saved Notice has no ID.');
1057 // Only save 'attention' and metadata stuff (URLs, tags...) stuff if
1058 // the activityverb is a POST (since stuff like repeat, favorite etc.
1059 // reasonably handle notifications themselves.
1060 if (ActivityUtils::compareVerbs($stored->verb, array(ActivityVerb::POST))) {
1062 if (!empty($tags)) {
1063 $stored->saveKnownTags($tags);
1065 $stored->saveTags();
1068 // Note: groups may save tags, so must be run after tags are saved
1069 // to avoid errors on duplicates.
1070 $stored->saveAttentions($act->context->attention);
1072 if (!empty($urls)) {
1073 $stored->saveKnownUrls($urls);
1075 $stored->saveUrls();
1080 // Prepare inbox delivery, may be queued to background.
1081 $stored->distribute();
1087 static public function figureOutScope(Profile $actor, array $groups, $scope=null) {
1088 $scope = is_null($scope) ? self::defaultScope() : intval($scope);
1090 // For private streams
1092 $user = $actor->getUser();
1093 // FIXME: We can't do bit comparison with == (Legacy StatusNet thing. Let's keep it for now.)
1094 if ($user->private_stream && ($scope === Notice::PUBLIC_SCOPE || $scope === Notice::SITE_SCOPE)) {
1095 $scope |= Notice::FOLLOWER_SCOPE;
1097 } catch (NoSuchUserException $e) {
1098 // TODO: Not a local user, so we don't know about scope preferences... yet!
1101 // Force the scope for private groups
1102 foreach ($groups as $group_id) {
1104 $group = User_group::getByID($group_id);
1105 if ($group->force_scope) {
1106 $scope |= Notice::GROUP_SCOPE;
1109 } catch (Exception $e) {
1110 common_log(LOG_ERR, 'Notice figureOutScope threw exception: '.$e->getMessage());
1117 function blowOnInsert($conversation = false)
1119 $this->blowStream('profile:notice_ids:%d', $this->profile_id);
1121 if ($this->isPublic()) {
1122 $this->blowStream('public');
1123 $this->blowStream('networkpublic');
1126 if ($this->conversation) {
1127 self::blow('notice:list-ids:conversation:%s', $this->conversation);
1128 self::blow('conversation:notice_count:%d', $this->conversation);
1131 if ($this->isRepeat()) {
1132 // XXX: we should probably only use one of these
1133 $this->blowStream('notice:repeats:%d', $this->repeat_of);
1134 self::blow('notice:list-ids:repeat_of:%d', $this->repeat_of);
1137 $original = Notice::getKV('id', $this->repeat_of);
1139 if ($original instanceof Notice) {
1140 $originalUser = User::getKV('id', $original->profile_id);
1141 if ($originalUser instanceof User) {
1142 $this->blowStream('user:repeats_of_me:%d', $originalUser->id);
1146 $profile = Profile::getKV($this->profile_id);
1148 if ($profile instanceof Profile) {
1149 $profile->blowNoticeCount();
1152 $ptags = $this->getProfileTags();
1153 foreach ($ptags as $ptag) {
1154 $ptag->blowNoticeStreamCache();
1159 * Clear cache entries related to this notice at delete time.
1160 * Necessary to avoid breaking paging on public, profile timelines.
1162 function blowOnDelete()
1164 $this->blowOnInsert();
1166 self::blow('profile:notice_ids:%d;last', $this->profile_id);
1168 if ($this->isPublic()) {
1169 self::blow('public;last');
1170 self::blow('networkpublic;last');
1173 self::blow('fave:by_notice', $this->id);
1175 if ($this->conversation) {
1176 // In case we're the first, will need to calc a new root.
1177 self::blow('notice:conversation_root:%d', $this->conversation);
1180 $ptags = $this->getProfileTags();
1181 foreach ($ptags as $ptag) {
1182 $ptag->blowNoticeStreamCache(true);
1186 function blowStream()
1188 $c = self::memcache();
1194 $args = func_get_args();
1195 $format = array_shift($args);
1196 $keyPart = vsprintf($format, $args);
1197 $cacheKey = Cache::key($keyPart);
1198 $c->delete($cacheKey);
1200 // delete the "last" stream, too, if this notice is
1201 // older than the top of that stream
1203 $lastKey = $cacheKey.';last';
1205 $lastStr = $c->get($lastKey);
1207 if ($lastStr !== false) {
1208 $window = explode(',', $lastStr);
1209 $lastID = $window[0];
1210 $lastNotice = Notice::getKV('id', $lastID);
1211 if (!$lastNotice instanceof Notice // just weird
1212 || strtotime($lastNotice->created) >= strtotime($this->created)) {
1213 $c->delete($lastKey);
1218 /** save all urls in the notice to the db
1220 * follow redirects and save all available file information
1221 * (mimetype, date, size, oembed, etc.)
1225 function saveUrls() {
1226 if (common_config('attachments', 'process_links')) {
1227 common_replace_urls_callback($this->content, array($this, 'saveUrl'), $this);
1232 * Save the given URLs as related links/attachments to the db
1234 * follow redirects and save all available file information
1235 * (mimetype, date, size, oembed, etc.)
1239 function saveKnownUrls($urls)
1241 if (common_config('attachments', 'process_links')) {
1242 // @fixme validation?
1243 foreach (array_unique($urls) as $url) {
1244 $this->saveUrl($url, $this);
1252 function saveUrl($url, Notice $notice) {
1254 File::processNew($url, $notice);
1255 } catch (ServerException $e) {
1256 // Could not save URL. Log it?
1260 static function checkDupes($profile_id, $content) {
1261 $profile = Profile::getKV($profile_id);
1262 if (!$profile instanceof Profile) {
1265 $notice = $profile->getNotices(0, CachingNoticeStream::CACHE_WINDOW);
1266 if (!empty($notice)) {
1268 while ($notice->fetch()) {
1269 if (time() - strtotime($notice->created) >= common_config('site', 'dupelimit')) {
1271 } else if ($notice->content == $content) {
1276 // If we get here, oldest item in cache window is not
1277 // old enough for dupe limit; do direct check against DB
1278 $notice = new Notice();
1279 $notice->profile_id = $profile_id;
1280 $notice->content = $content;
1281 $threshold = common_sql_date(time() - common_config('site', 'dupelimit'));
1282 $notice->whereAdd(sprintf("created > '%s'", $notice->escape($threshold)));
1284 $cnt = $notice->count();
1288 static function checkEditThrottle($profile_id) {
1289 $profile = Profile::getKV($profile_id);
1290 if (!$profile instanceof Profile) {
1293 // Get the Nth notice
1294 $notice = $profile->getNotices(common_config('throttle', 'count') - 1, 1);
1295 if ($notice && $notice->fetch()) {
1296 // If the Nth notice was posted less than timespan seconds ago
1297 if (time() - strtotime($notice->created) <= common_config('throttle', 'timespan')) {
1302 // Either not N notices in the stream, OR the Nth was not posted within timespan seconds
1306 protected $_attachments = array();
1308 function attachments() {
1309 if (isset($this->_attachments[$this->id])) {
1310 return $this->_attachments[$this->id];
1313 $f2ps = File_to_post::listGet('post_id', array($this->id));
1315 foreach ($f2ps[$this->id] as $f2p) {
1316 $ids[] = $f2p->file_id;
1319 return $this->_setAttachments(File::multiGet('id', $ids)->fetchAll());
1322 public function _setAttachments(array $attachments)
1324 return $this->_attachments[$this->id] = $attachments;
1327 static function publicStream($offset=0, $limit=20, $since_id=null, $max_id=null)
1329 $stream = new PublicNoticeStream();
1330 return $stream->getNotices($offset, $limit, $since_id, $max_id);
1333 static function conversationStream($id, $offset=0, $limit=20, $since_id=null, $max_id=null, Profile $scoped=null)
1335 $stream = new ConversationNoticeStream($id, $scoped);
1336 return $stream->getNotices($offset, $limit, $since_id, $max_id);
1340 * Is this notice part of an active conversation?
1342 * @return boolean true if other messages exist in the same
1343 * conversation, false if this is the only one
1345 function hasConversation()
1347 if (empty($this->conversation)) {
1348 // this notice is not part of a conversation apparently
1349 // FIXME: all notices should have a conversation value, right?
1353 //FIXME: Get the Profile::current() stuff some other way
1354 // to avoid confusion between queue processing and session.
1355 $notice = self::conversationStream($this->conversation, 1, 1, null, null, Profile::current());
1357 // if our "offset 1, limit 1" query got a result, return true else false
1358 return $notice->N > 0;
1362 * Grab the earliest notice from this conversation.
1364 * @return Notice or null
1366 function conversationRoot($profile=-1)
1368 // XXX: can this happen?
1370 if (empty($this->conversation)) {
1374 // Get the current profile if not specified
1376 if (is_int($profile) && $profile == -1) {
1377 $profile = Profile::current();
1380 // If this notice is out of scope, no root for you!
1382 if (!$this->inScope($profile)) {
1386 // If this isn't a reply to anything, then it's its own
1387 // root if it's the earliest notice in the conversation:
1389 if (empty($this->reply_to)) {
1391 $root->conversation = $this->conversation;
1392 $root->orderBy('notice.created ASC');
1393 $root->find(true); // true means "fetch first result"
1398 if (is_null($profile)) {
1399 $keypart = sprintf('notice:conversation_root:%d:null', $this->id);
1401 $keypart = sprintf('notice:conversation_root:%d:%d',
1406 $root = self::cacheGet($keypart);
1408 if ($root !== false && $root->inScope($profile)) {
1415 $parent = $last->getParent();
1416 if ($parent->inScope($profile)) {
1420 } catch (NoParentNoticeException $e) {
1421 // Latest notice has no parent
1422 } catch (NoResultException $e) {
1423 // Notice was not found, so we can't go further up in the tree.
1424 // FIXME: Maybe we should do this in a more stable way where deleted
1425 // notices won't break conversation chains?
1427 // No parent, or parent out of scope
1432 self::cacheSet($keypart, $root);
1438 * Pull up a full list of local recipients who will be getting
1439 * this notice in their inbox. Results will be cached, so don't
1440 * change the input data wily-nilly!
1442 * @param array $groups optional list of Group objects;
1443 * if left empty, will be loaded from group_inbox records
1444 * @param array $recipient optional list of reply profile ids
1445 * if left empty, will be loaded from reply records
1446 * @return array associating recipient user IDs with an inbox source constant
1448 function whoGets(array $groups=null, array $recipients=null)
1450 $c = self::memcache();
1453 $ni = $c->get(Cache::key('notice:who_gets:'.$this->id));
1454 if ($ni !== false) {
1459 if (is_null($recipients)) {
1460 $recipients = $this->getReplies();
1465 // Give plugins a chance to add folks in at start...
1466 if (Event::handle('StartNoticeWhoGets', array($this, &$ni))) {
1468 $users = $this->getSubscribedUsers();
1469 foreach ($users as $id) {
1470 $ni[$id] = NOTICE_INBOX_SOURCE_SUB;
1473 if (is_null($groups)) {
1474 $groups = $this->getGroups();
1476 foreach ($groups as $group) {
1477 $users = $group->getUserMembers();
1478 foreach ($users as $id) {
1479 if (!array_key_exists($id, $ni)) {
1480 $ni[$id] = NOTICE_INBOX_SOURCE_GROUP;
1485 $ptAtts = $this->getAttentionsFromProfileTags();
1486 foreach ($ptAtts as $key=>$val) {
1487 if (!array_key_exists($key, $ni)) {
1492 foreach ($recipients as $recipient) {
1493 if (!array_key_exists($recipient, $ni)) {
1494 $ni[$recipient] = NOTICE_INBOX_SOURCE_REPLY;
1498 // Exclude any deleted, non-local, or blocking recipients.
1499 $profile = $this->getProfile();
1500 $originalProfile = null;
1501 if ($this->isRepeat()) {
1502 // Check blocks against the original notice's poster as well.
1503 $original = Notice::getKV('id', $this->repeat_of);
1504 if ($original instanceof Notice) {
1505 $originalProfile = $original->getProfile();
1509 foreach ($ni as $id => $source) {
1511 $user = User::getKV('id', $id);
1512 if (!$user instanceof User ||
1513 $user->hasBlocked($profile) ||
1514 ($originalProfile && $user->hasBlocked($originalProfile))) {
1517 } catch (UserNoProfileException $e) {
1518 // User doesn't have a profile; invalid; skip them.
1523 // Give plugins a chance to filter out...
1524 Event::handle('EndNoticeWhoGets', array($this, &$ni));
1528 // XXX: pack this data better
1529 $c->set(Cache::key('notice:who_gets:'.$this->id), $ni);
1535 function getSubscribedUsers()
1539 if(common_config('db','quote_identifiers'))
1540 $user_table = '"user"';
1541 else $user_table = 'user';
1545 'FROM '. $user_table .' JOIN subscription '.
1546 'ON '. $user_table .'.id = subscription.subscriber ' .
1547 'WHERE subscription.subscribed = %d ';
1549 $user->query(sprintf($qry, $this->profile_id));
1553 while ($user->fetch()) {
1562 function getProfileTags()
1566 $profile = $this->getProfile();
1567 $list = $profile->getOtherTags($profile);
1569 while($list->fetch()) {
1570 $ptags[] = clone($list);
1572 } catch (Exception $e) {
1573 common_log(LOG_ERR, "Error during Notice->getProfileTags() for id=={$this->getID()}: {$e->getMessage()}");
1579 public function getAttentionsFromProfileTags()
1582 $ptags = $this->getProfileTags();
1583 foreach ($ptags as $ptag) {
1584 $users = $ptag->getUserSubscribers();
1585 foreach ($users as $id) {
1586 $ni[$id] = NOTICE_INBOX_SOURCE_PROFILE_TAG;
1593 * Record this notice to the given group inboxes for delivery.
1594 * Overrides the regular parsing of !group markup.
1596 * @param string $group_ids
1597 * @fixme might prefer URIs as identifiers, as for replies?
1598 * best with generalizations on user_group to support
1599 * remote groups better.
1601 function saveKnownGroups(array $group_ids)
1604 foreach (array_unique($group_ids) as $id) {
1605 $group = User_group::getKV('id', $id);
1606 if ($group instanceof User_group) {
1607 common_log(LOG_DEBUG, "Local delivery to group id $id, $group->nickname");
1608 $result = $this->addToGroupInbox($group);
1610 common_log_db_error($gi, 'INSERT', __FILE__);
1613 if (common_config('group', 'addtag')) {
1614 // we automatically add a tag for every group name, too
1615 common_debug('Adding hashtag matching group nickname: '._ve($group->getNickname()));
1616 $tag = Notice_tag::pkeyGet(array('tag' => common_canonical_tag($group->getNickname()),
1617 'notice_id' => $this->getID()));
1619 if (is_null($tag)) {
1620 $this->saveTag($group->getNickname());
1624 $groups[] = clone($group);
1626 common_log(LOG_ERR, "Local delivery to group id $id skipped, doesn't exist");
1633 function addToGroupInbox(User_group $group)
1635 $gi = Group_inbox::pkeyGet(array('group_id' => $group->id,
1636 'notice_id' => $this->id));
1638 if (!$gi instanceof Group_inbox) {
1640 $gi = new Group_inbox();
1642 $gi->group_id = $group->id;
1643 $gi->notice_id = $this->id;
1644 $gi->created = $this->created;
1646 $result = $gi->insert();
1649 common_log_db_error($gi, 'INSERT', __FILE__);
1650 // TRANS: Server exception thrown when an update for a group inbox fails.
1651 throw new ServerException(_('Problem saving group inbox.'));
1654 self::blow('user_group:notice_ids:%d', $gi->group_id);
1660 function saveAttentions(array $uris)
1662 foreach ($uris as $uri=>$type) {
1664 $target = Profile::fromUri($uri);
1665 } catch (UnknownUriException $e) {
1666 common_log(LOG_WARNING, "Unable to determine profile for URI '$uri'");
1671 $this->saveAttention($target);
1672 } catch (AlreadyFulfilledException $e) {
1673 common_debug('Attention already exists: '.var_export($e->getMessage(),true));
1674 } catch (Exception $e) {
1675 common_log(LOG_ERR, "Could not save notice id=={$this->getID()} attention for profile id=={$target->getID()}: {$e->getMessage()}");
1681 * Saves an attention for a profile (user or group) which means
1682 * it shows up in their home feed and such.
1684 function saveAttention(Profile $target, $reason=null)
1686 if ($target->isGroup()) {
1687 // FIXME: Make sure we check (for both local and remote) users are in the groups they send to!
1689 // legacy notification method, will still be in use for quite a while I think
1690 $this->addToGroupInbox($target->getGroup());
1692 if ($target->hasBlocked($this->getProfile())) {
1693 common_log(LOG_INFO, "Not saving reply to profile {$target->id} ($uri) from sender {$sender->id} because of a block.");
1698 if ($target->isLocal()) {
1699 // legacy notification method, will still be in use for quite a while I think
1700 $this->saveReply($target->getID());
1703 $att = Attention::saveNew($this, $target, $reason);
1708 * Save reply records indicating that this notice needs to be
1709 * delivered to the local users with the given URIs.
1711 * Since this is expected to be used when saving foreign-sourced
1712 * messages, we won't deliver to any remote targets as that's the
1713 * source service's responsibility.
1715 * Mail notifications etc will be handled later.
1717 * @param array $uris Array of unique identifier URIs for recipients
1719 function saveKnownReplies(array $uris)
1725 $sender = $this->getProfile();
1727 foreach (array_unique($uris) as $uri) {
1729 $profile = Profile::fromUri($uri);
1730 } catch (UnknownUriException $e) {
1731 common_log(LOG_WARNING, "Unable to determine profile for URI '$uri'");
1735 if ($profile->hasBlocked($sender)) {
1736 common_log(LOG_INFO, "Not saving reply to profile {$profile->id} ($uri) from sender {$sender->id} because of a block.");
1740 $this->saveReply($profile->getID());
1741 self::blow('reply:stream:%d', $profile->getID());
1746 * Pull @-replies from this message's content in StatusNet markup format
1747 * and save reply records indicating that this message needs to be
1748 * delivered to those users.
1750 * Mail notifications to local profiles will be sent later.
1752 * @return array of integer profile IDs
1755 function saveReplies()
1757 $sender = $this->getProfile();
1761 // If it's a reply, save for the replied-to author
1763 $parent = $this->getParent();
1764 $parentauthor = $parent->getProfile();
1765 $this->saveReply($parentauthor->getID());
1766 $replied[$parentauthor->getID()] = 1;
1767 self::blow('reply:stream:%d', $parentauthor->getID());
1768 } catch (NoParentNoticeException $e) {
1769 // Not a reply, since it has no parent!
1771 } catch (NoResultException $e) {
1772 // Parent notice was probably deleted
1776 // @todo ideally this parser information would only
1777 // be calculated once.
1779 $mentions = common_find_mentions($this->content, $sender, $parent);
1781 foreach ($mentions as $mention) {
1783 foreach ($mention['mentioned'] as $mentioned) {
1785 // skip if they're already covered
1786 if (array_key_exists($mentioned->id, $replied)) {
1790 // Don't save replies from blocked profile to local user
1791 if ($mentioned->hasBlocked($sender)) {
1795 $this->saveReply($mentioned->id);
1796 $replied[$mentioned->id] = 1;
1797 self::blow('reply:stream:%d', $mentioned->id);
1801 $recipientIds = array_keys($replied);
1803 return $recipientIds;
1806 function saveReply($profileId)
1808 $reply = new Reply();
1810 $reply->notice_id = $this->id;
1811 $reply->profile_id = $profileId;
1812 $reply->modified = $this->created;
1819 protected $_attentionids = array();
1822 * Pull the complete list of known activity context attentions for this notice.
1824 * @return array of integer profile ids (also group profiles)
1826 function getAttentionProfileIDs()
1828 if (!isset($this->_attentionids[$this->getID()])) {
1829 $atts = Attention::multiGet('notice_id', array($this->getID()));
1830 // (array)null means empty array
1831 $this->_attentionids[$this->getID()] = (array)$atts->fetchAll('profile_id');
1833 return $this->_attentionids[$this->getID()];
1836 protected $_replies = array();
1839 * Pull the complete list of @-mentioned profile IDs for this notice.
1841 * @return array of integer profile ids
1843 function getReplies()
1845 if (!isset($this->_replies[$this->getID()])) {
1846 $mentions = Reply::multiGet('notice_id', array($this->getID()));
1847 $this->_replies[$this->getID()] = $mentions->fetchAll('profile_id');
1849 return $this->_replies[$this->getID()];
1852 function _setReplies($replies)
1854 $this->_replies[$this->getID()] = $replies;
1858 * Pull the complete list of @-reply targets for this notice.
1860 * @return array of Profiles
1862 function getAttentionProfiles()
1864 $ids = array_unique(array_merge($this->getReplies(), $this->getGroupProfileIDs(), $this->getAttentionProfileIDs()));
1866 $profiles = Profile::multiGet('id', (array)$ids);
1868 return $profiles->fetchAll();
1872 * Send e-mail notifications to local @-reply targets.
1874 * Replies must already have been saved; this is expected to be run
1875 * from the distrib queue handler.
1877 function sendReplyNotifications()
1879 // Don't send reply notifications for repeats
1880 if ($this->isRepeat()) {
1884 $recipientIds = $this->getReplies();
1885 if (Event::handle('StartNotifyMentioned', array($this, &$recipientIds))) {
1886 require_once INSTALLDIR.'/lib/mail.php';
1888 foreach ($recipientIds as $recipientId) {
1890 $user = User::getByID($recipientId);
1891 mail_notify_attn($user->getProfile(), $this);
1892 } catch (NoResultException $e) {
1896 Event::handle('EndNotifyMentioned', array($this, $recipientIds));
1901 * Pull list of Profile IDs of groups this notice addresses.
1903 * @return array of Group _profile_ IDs
1906 function getGroupProfileIDs()
1910 foreach ($this->getGroups() as $group) {
1911 $ids[] = $group->profile_id;
1918 * Pull list of groups this notice needs to be delivered to,
1919 * as previously recorded by saveKnownGroups().
1921 * @return array of Group objects
1924 protected $_groups = array();
1926 function getGroups()
1928 // Don't save groups for repeats
1930 if (!empty($this->repeat_of)) {
1934 if (isset($this->_groups[$this->id])) {
1935 return $this->_groups[$this->id];
1938 $gis = Group_inbox::listGet('notice_id', array($this->id));
1942 foreach ($gis[$this->id] as $gi) {
1943 $ids[] = $gi->group_id;
1946 $groups = User_group::multiGet('id', $ids);
1947 $this->_groups[$this->id] = $groups->fetchAll();
1948 return $this->_groups[$this->id];
1951 function _setGroups($groups)
1953 $this->_groups[$this->id] = $groups;
1957 * Convert a notice into an activity for export.
1959 * @param Profile $scoped The currently logged in/scoped profile
1961 * @return Activity activity object representing this Notice.
1964 function asActivity(Profile $scoped=null)
1966 $act = self::cacheGet(Cache::codeKey('notice:as-activity:'.$this->id));
1968 if ($act instanceof Activity) {
1971 $act = new Activity();
1973 if (Event::handle('StartNoticeAsActivity', array($this, $act, $scoped))) {
1975 $act->id = $this->uri;
1976 $act->time = strtotime($this->created);
1978 $act->link = $this->getUrl();
1979 } catch (InvalidUrlException $e) {
1980 // The notice is probably a share or similar, which don't
1981 // have a representational URL of their own.
1983 $act->content = common_xml_safe_str($this->getRendered());
1985 $profile = $this->getProfile();
1987 $act->actor = $profile->asActivityObject();
1988 $act->actor->extra[] = $profile->profileInfo($scoped);
1990 $act->verb = $this->verb;
1992 if (!$this->repeat_of) {
1993 $act->objects[] = $this->asActivityObject();
1996 // XXX: should this be handled by default processing for object entry?
2000 $tags = $this->getTags();
2002 foreach ($tags as $tag) {
2003 $cat = new AtomCategory();
2006 $act->categories[] = $cat;
2010 // XXX: use Atom Media and/or File activity objects instead
2012 $attachments = $this->attachments();
2014 foreach ($attachments as $attachment) {
2015 // Include local attachments in Activity
2016 if (!empty($attachment->filename)) {
2017 $act->enclosures[] = $attachment->getEnclosure();
2021 $ctx = new ActivityContext();
2024 $reply = $this->getParent();
2025 $ctx->replyToID = $reply->getUri();
2026 $ctx->replyToUrl = $reply->getUrl(true); // true for fallback to local URL, less messy
2027 } catch (NoParentNoticeException $e) {
2028 // This is not a reply to something
2029 } catch (NoResultException $e) {
2030 // Parent notice was probably deleted
2034 $ctx->location = Notice_location::locFromStored($this);
2035 } catch (ServerException $e) {
2036 $ctx->location = null;
2041 if (!empty($this->conversation)) {
2042 $conv = Conversation::getKV('id', $this->conversation);
2043 if ($conv instanceof Conversation) {
2044 $ctx->conversation = $conv->uri;
2045 $ctx->conversation_url = $conv->url;
2049 // This covers the legacy getReplies and getGroups too which get their data
2050 // from entries stored via Notice::saveNew (which we want to move away from)...
2051 foreach ($this->getAttentionProfiles() as $target) {
2052 // User and group profiles which get the attention of this notice
2053 $ctx->attention[$target->getUri()] = $target->getObjectType();
2056 switch ($this->scope) {
2057 case Notice::PUBLIC_SCOPE:
2058 $ctx->attention[ActivityContext::ATTN_PUBLIC] = ActivityObject::COLLECTION;
2060 case Notice::FOLLOWER_SCOPE:
2061 $surl = common_local_url("subscribers", array('nickname' => $profile->nickname));
2062 $ctx->attention[$surl] = ActivityObject::COLLECTION;
2066 $act->context = $ctx;
2068 $source = $this->getSource();
2070 if ($source instanceof Notice_source) {
2071 $act->generator = ActivityObject::fromNoticeSource($source);
2076 $atom_feed = $profile->getAtomFeed();
2078 if (!empty($atom_feed)) {
2080 $act->source = new ActivitySource();
2082 // XXX: we should store the actual feed ID
2084 $act->source->id = $atom_feed;
2086 // XXX: we should store the actual feed title
2088 $act->source->title = $profile->getBestName();
2090 $act->source->links['alternate'] = $profile->profileurl;
2091 $act->source->links['self'] = $atom_feed;
2093 $act->source->icon = $profile->avatarUrl(AVATAR_PROFILE_SIZE);
2095 $notice = $profile->getCurrentNotice();
2097 if ($notice instanceof Notice) {
2098 $act->source->updated = self::utcDate($notice->created);
2101 $user = User::getKV('id', $profile->id);
2103 if ($user instanceof User) {
2104 $act->source->links['license'] = common_config('license', 'url');
2109 $act->selfLink = $this->getSelfLink();
2110 } catch (InvalidUrlException $e) {
2111 $act->selfLink = null;
2113 if ($this->isLocal()) {
2114 $act->editLink = $act->selfLink;
2117 Event::handle('EndNoticeAsActivity', array($this, $act, $scoped));
2120 self::cacheSet(Cache::codeKey('notice:as-activity:'.$this->id), $act);
2125 // This has gotten way too long. Needs to be sliced up into functional bits
2126 // or ideally exported to a utility class.
2128 function asAtomEntry($namespace=false,
2131 Profile $scoped=null)
2133 $act = $this->asActivity($scoped);
2134 $act->extra[] = $this->noticeInfo($scoped);
2135 return $act->asString($namespace, $author, $source);
2139 * Extra notice info for atom entries
2141 * Clients use some extra notice info in the atom stream.
2142 * This gives it to them.
2144 * @param Profile $scoped The currently logged in/scoped profile
2146 * @return array representation of <statusnet:notice_info> element
2149 function noticeInfo(Profile $scoped=null)
2151 // local notice ID (useful to clients for ordering)
2153 $noticeInfoAttr = array('local_id' => $this->id);
2157 $ns = $this->getSource();
2159 if ($ns instanceof Notice_source) {
2160 $noticeInfoAttr['source'] = $ns->code;
2161 if (!empty($ns->url)) {
2162 $noticeInfoAttr['source_link'] = $ns->url;
2163 if (!empty($ns->name)) {
2164 $noticeInfoAttr['source'] = $ns->name;
2169 // favorite and repeated
2171 if ($scoped instanceof Profile) {
2172 $noticeInfoAttr['repeated'] = ($scoped->hasRepeated($this)) ? "true" : "false";
2175 if (!empty($this->repeat_of)) {
2176 $noticeInfoAttr['repeat_of'] = $this->repeat_of;
2179 Event::handle('StatusNetApiNoticeInfo', array($this, &$noticeInfoAttr, $scoped));
2181 return array('statusnet:notice_info', $noticeInfoAttr, null);
2185 * Returns an XML string fragment with a reference to a notice as an
2186 * Activity Streams noun object with the given element type.
2188 * Assumes that 'activity' namespace has been previously defined.
2190 * @param string $element one of 'subject', 'object', 'target'
2194 function asActivityNoun($element)
2196 $noun = $this->asActivityObject();
2197 return $noun->asString('activity:' . $element);
2200 public function asActivityObject()
2202 $object = new ActivityObject();
2204 if (Event::handle('StartActivityObjectFromNotice', array($this, &$object))) {
2205 $object->type = $this->object_type ?: ActivityObject::NOTE;
2206 $object->id = $this->getUri();
2207 //FIXME: = $object->title ?: sprintf(... because we might get a title from StartActivityObjectFromNotice
2208 $object->title = sprintf('New %1$s by %2$s', ActivityObject::canonicalType($object->type), $this->getProfile()->getNickname());
2209 $object->content = $this->getRendered();
2210 $object->link = $this->getUrl();
2212 $object->selfLink = $this->getSelfLink();
2213 } catch (InvalidUrlException $e) {
2214 $object->selfLink = null;
2217 $object->extra[] = array('status_net', array('notice_id' => $this->id));
2219 Event::handle('EndActivityObjectFromNotice', array($this, &$object));
2222 if (!$object instanceof ActivityObject) {
2223 common_log(LOG_ERR, 'Notice asActivityObject created something else for uri=='._ve($this->getUri()).': '._ve($object));
2224 throw new ServerException('Notice asActivityObject created something else.');
2231 * Determine which notice, if any, a new notice is in reply to.
2233 * For conversation tracking, we try to see where this notice fits
2234 * in the tree. Beware that this may very well give false positives
2235 * and add replies to wrong threads (if there have been newer posts
2236 * by the same user as we're replying to).
2238 * @param Profile $sender Author profile
2239 * @param string $content Final notice content
2241 * @return integer ID of replied-to notice, or null for not a reply.
2244 static function getInlineReplyTo(Profile $sender, $content)
2246 // Is there an initial @ or T?
2247 if (preg_match('/^T ([A-Z0-9]{1,64}) /', $content, $match)
2248 || preg_match('/^@([a-z0-9]{1,64})\s+/', $content, $match)) {
2249 $nickname = common_canonical_nickname($match[1]);
2254 // Figure out who that is.
2255 $recipient = common_relative_profile($sender, $nickname, common_sql_now());
2257 if ($recipient instanceof Profile) {
2258 // Get their last notice
2259 $last = $recipient->getCurrentNotice();
2260 if ($last instanceof Notice) {
2263 // Maybe in the future we want to handle something else below
2264 // so don't return getCurrentNotice() immediately.
2270 static function maxContent()
2272 $contentlimit = common_config('notice', 'contentlimit');
2273 // null => use global limit (distinct from 0!)
2274 if (is_null($contentlimit)) {
2275 $contentlimit = common_config('site', 'textlimit');
2277 return $contentlimit;
2280 static function contentTooLong($content)
2282 $contentlimit = self::maxContent();
2283 return ($contentlimit > 0 && !empty($content) && (mb_strlen($content) > $contentlimit));
2287 * Convenience function for posting a repeat of an existing message.
2289 * @param Profile $repeater Profile which is doing the repeat
2290 * @param string $source: posting source key, eg 'web', 'api', etc
2293 * @throws Exception on failure or permission problems
2295 function repeat(Profile $repeater, $source)
2297 $author = $this->getProfile();
2299 // TRANS: Message used to repeat a notice. RT is the abbreviation of 'retweet'.
2300 // TRANS: %1$s is the repeated user's name, %2$s is the repeated notice.
2301 $content = sprintf(_('RT @%1$s %2$s'),
2302 $author->getNickname(),
2305 $maxlen = self::maxContent();
2306 if ($maxlen > 0 && mb_strlen($content) > $maxlen) {
2307 // Web interface and current Twitter API clients will
2308 // pull the original notice's text, but some older
2309 // clients and RSS/Atom feeds will see this trimmed text.
2311 // Unfortunately this is likely to lose tags or URLs
2312 // at the end of long notices.
2313 $content = mb_substr($content, 0, $maxlen - 4) . ' ...';
2317 // Scope is same as this one's
2318 return self::saveNew($repeater->id,
2321 array('repeat_of' => $this->id,
2322 'scope' => $this->scope));
2325 // These are supposed to be in chron order!
2327 function repeatStream($limit=100)
2329 $cache = Cache::instance();
2331 if (empty($cache)) {
2332 $ids = $this->_repeatStreamDirect($limit);
2334 $idstr = $cache->get(Cache::key('notice:repeats:'.$this->id));
2335 if ($idstr !== false) {
2336 if (empty($idstr)) {
2339 $ids = explode(',', $idstr);
2342 $ids = $this->_repeatStreamDirect(100);
2343 $cache->set(Cache::key('notice:repeats:'.$this->id), implode(',', $ids));
2346 // We do a max of 100, so slice down to limit
2347 $ids = array_slice($ids, 0, $limit);
2351 return NoticeStream::getStreamByIds($ids);
2354 function _repeatStreamDirect($limit)
2356 $notice = new Notice();
2358 $notice->selectAdd(); // clears it
2359 $notice->selectAdd('id');
2361 $notice->repeat_of = $this->id;
2363 $notice->orderBy('created, id'); // NB: asc!
2365 if (!is_null($limit)) {
2366 $notice->limit(0, $limit);
2369 return $notice->fetchAll('id');
2372 static function locationOptions($lat, $lon, $location_id, $location_ns, $profile = null)
2376 if (!empty($location_id) && !empty($location_ns)) {
2377 $options['location_id'] = $location_id;
2378 $options['location_ns'] = $location_ns;
2380 $location = Location::fromId($location_id, $location_ns);
2382 if ($location instanceof Location) {
2383 $options['lat'] = $location->lat;
2384 $options['lon'] = $location->lon;
2387 } else if (!empty($lat) && !empty($lon)) {
2388 $options['lat'] = $lat;
2389 $options['lon'] = $lon;
2391 $location = Location::fromLatLon($lat, $lon);
2393 if ($location instanceof Location) {
2394 $options['location_id'] = $location->location_id;
2395 $options['location_ns'] = $location->location_ns;
2397 } else if (!empty($profile)) {
2398 if (isset($profile->lat) && isset($profile->lon)) {
2399 $options['lat'] = $profile->lat;
2400 $options['lon'] = $profile->lon;
2403 if (isset($profile->location_id) && isset($profile->location_ns)) {
2404 $options['location_id'] = $profile->location_id;
2405 $options['location_ns'] = $profile->location_ns;
2412 function clearAttentions()
2414 $att = new Attention();
2415 $att->notice_id = $this->getID();
2418 while ($att->fetch()) {
2419 // Can't do delete() on the object directly since it won't remove all of it
2420 $other = clone($att);
2426 function clearReplies()
2428 $replyNotice = new Notice();
2429 $replyNotice->reply_to = $this->id;
2431 //Null any notices that are replies to this notice
2433 if ($replyNotice->find()) {
2434 while ($replyNotice->fetch()) {
2435 $orig = clone($replyNotice);
2436 $replyNotice->reply_to = null;
2437 $replyNotice->update($orig);
2443 $reply = new Reply();
2444 $reply->notice_id = $this->id;
2446 if ($reply->find()) {
2447 while($reply->fetch()) {
2448 self::blow('reply:stream:%d', $reply->profile_id);
2456 function clearLocation()
2458 $loc = new Notice_location();
2459 $loc->notice_id = $this->id;
2466 function clearFiles()
2468 $f2p = new File_to_post();
2470 $f2p->post_id = $this->id;
2473 while ($f2p->fetch()) {
2477 // FIXME: decide whether to delete File objects
2478 // ...and related (actual) files
2481 function clearRepeats()
2483 $repeatNotice = new Notice();
2484 $repeatNotice->repeat_of = $this->id;
2486 //Null any notices that are repeats of this notice
2488 if ($repeatNotice->find()) {
2489 while ($repeatNotice->fetch()) {
2490 $orig = clone($repeatNotice);
2491 $repeatNotice->repeat_of = null;
2492 $repeatNotice->update($orig);
2497 function clearTags()
2499 $tag = new Notice_tag();
2500 $tag->notice_id = $this->id;
2503 while ($tag->fetch()) {
2504 self::blow('profile:notice_ids_tagged:%d:%s', $this->profile_id, Cache::keyize($tag->tag));
2505 self::blow('profile:notice_ids_tagged:%d:%s;last', $this->profile_id, Cache::keyize($tag->tag));
2506 self::blow('notice_tag:notice_ids:%s', Cache::keyize($tag->tag));
2507 self::blow('notice_tag:notice_ids:%s;last', Cache::keyize($tag->tag));
2515 function clearGroupInboxes()
2517 $gi = new Group_inbox();
2519 $gi->notice_id = $this->id;
2522 while ($gi->fetch()) {
2523 self::blow('user_group:notice_ids:%d', $gi->group_id);
2531 function distribute()
2533 // We always insert for the author so they don't
2535 Event::handle('StartNoticeDistribute', array($this));
2537 // If there's a failure, we want to _force_
2538 // distribution at this point.
2540 $json = json_encode((object)array('id' => $this->getID(),
2543 $qm = QueueManager::get();
2544 $qm->enqueue($json, 'distrib');
2545 } catch (Exception $e) {
2546 // If the exception isn't transient, this
2547 // may throw more exceptions as DQH does
2548 // its own enqueueing. So, we ignore them!
2550 $handler = new DistribQueueHandler();
2551 $handler->handle($this);
2552 } catch (Exception $e) {
2553 common_log(LOG_ERR, "emergency redistribution resulted in " . $e->getMessage());
2555 // Re-throw so somebody smarter can handle it.
2562 $result = parent::insert();
2564 if ($result === false) {
2565 common_log_db_error($this, 'INSERT', __FILE__);
2566 // TRANS: Server exception thrown when a stored object entry cannot be saved.
2567 throw new ServerException('Could not save Notice');
2570 // Profile::hasRepeated() abuses pkeyGet(), so we
2571 // have to clear manually
2572 if (!empty($this->repeat_of)) {
2573 $c = self::memcache();
2575 $ck = self::multicacheKey('Notice',
2576 array('profile_id' => $this->profile_id,
2577 'repeat_of' => $this->repeat_of));
2582 // Update possibly ID-dependent columns: URI, conversation
2583 // (now that INSERT has added the notice's local id)
2584 $orig = clone($this);
2587 // We can only get here if it's a local notice, since remote notices
2588 // should've bailed out earlier due to lacking a URI.
2589 if (empty($this->uri)) {
2590 $this->uri = sprintf('%s%s=%d:%s=%s',
2592 'noticeId', $this->id,
2593 'objectType', $this->getObjectType(true));
2597 if ($changed && $this->update($orig) === false) {
2598 common_log_db_error($notice, 'UPDATE', __FILE__);
2599 // TRANS: Server exception thrown when a notice cannot be updated.
2600 throw new ServerException(_('Problem saving notice.'));
2603 $this->blowOnInsert();
2609 * Get the source of the notice
2611 * @return Notice_source $ns A notice source object. 'code' is the only attribute
2612 * guaranteed to be populated.
2614 function getSource()
2616 if (empty($this->source)) {
2620 $ns = new Notice_source();
2621 switch ($this->source) {
2628 $ns->code = $this->source;
2631 $ns = Notice_source::getKV($this->source);
2633 $ns = new Notice_source();
2634 $ns->code = $this->source;
2635 $app = Oauth_application::getKV('name', $this->source);
2637 $ns->name = $app->name;
2638 $ns->url = $app->source_url;
2648 * Determine whether the notice was locally created
2650 * @return boolean locality
2653 public function isLocal()
2655 $is_local = intval($this->is_local);
2656 return ($is_local === self::LOCAL_PUBLIC || $is_local === self::LOCAL_NONPUBLIC);
2659 public function getScope()
2661 return intval($this->scope);
2664 public function isRepeat()
2666 return !empty($this->repeat_of);
2669 public function isRepeated()
2672 $n->repeat_of = $this->getID();
2673 return $n->find() && $n->N > 0;
2677 * Get the list of hash tags saved with this notice.
2679 * @return array of strings
2681 public function getTags()
2685 $keypart = sprintf('notice:tags:%d', $this->id);
2687 $tagstr = self::cacheGet($keypart);
2689 if ($tagstr !== false) {
2690 $tags = explode(',', $tagstr);
2692 $tag = new Notice_tag();
2693 $tag->notice_id = $this->id;
2695 while ($tag->fetch()) {
2696 $tags[] = $tag->tag;
2699 self::cacheSet($keypart, implode(',', $tags));
2705 static private function utcDate($dt)
2707 $dateStr = date('d F Y H:i:s', strtotime($dt));
2708 $d = new DateTime($dateStr, new DateTimeZone('UTC'));
2709 return $d->format(DATE_W3C);
2713 * Look up the creation timestamp for a given notice ID, even
2714 * if it's been deleted.
2717 * @return mixed string recorded creation timestamp, or false if can't be found
2719 public static function getAsTimestamp($id)
2722 throw new EmptyPkeyValueException('Notice', 'id');
2726 if (Event::handle('GetNoticeSqlTimestamp', array($id, &$timestamp))) {
2727 // getByID throws exception if $id isn't found
2728 $notice = Notice::getByID($id);
2729 $timestamp = $notice->created;
2732 if (empty($timestamp)) {
2733 throw new ServerException('No timestamp found for Notice with id=='._ve($id));
2739 * Build an SQL 'where' fragment for timestamp-based sorting from a since_id
2740 * parameter, matching notices posted after the given one (exclusive).
2742 * If the referenced notice can't be found, will return false.
2745 * @param string $idField
2746 * @param string $createdField
2747 * @return mixed string or false if no match
2749 public static function whereSinceId($id, $idField='id', $createdField='created')
2752 $since = Notice::getAsTimestamp($id);
2753 } catch (Exception $e) {
2756 return sprintf("($createdField = '%s' and $idField > %d) or ($createdField > '%s')", $since, $id, $since);
2760 * Build an SQL 'where' fragment for timestamp-based sorting from a since_id
2761 * parameter, matching notices posted after the given one (exclusive), and
2762 * if necessary add it to the data object's query.
2764 * @param DB_DataObject $obj
2766 * @param string $idField
2767 * @param string $createdField
2768 * @return mixed string or false if no match
2770 public static function addWhereSinceId(DB_DataObject $obj, $id, $idField='id', $createdField='created')
2772 $since = self::whereSinceId($id, $idField, $createdField);
2774 $obj->whereAdd($since);
2779 * Build an SQL 'where' fragment for timestamp-based sorting from a max_id
2780 * parameter, matching notices posted before the given one (inclusive).
2782 * If the referenced notice can't be found, will return false.
2785 * @param string $idField
2786 * @param string $createdField
2787 * @return mixed string or false if no match
2789 public static function whereMaxId($id, $idField='id', $createdField='created')
2792 $max = Notice::getAsTimestamp($id);
2793 } catch (Exception $e) {
2796 return sprintf("($createdField < '%s') or ($createdField = '%s' and $idField <= %d)", $max, $max, $id);
2800 * Build an SQL 'where' fragment for timestamp-based sorting from a max_id
2801 * parameter, matching notices posted before the given one (inclusive), and
2802 * if necessary add it to the data object's query.
2804 * @param DB_DataObject $obj
2806 * @param string $idField
2807 * @param string $createdField
2808 * @return mixed string or false if no match
2810 public static function addWhereMaxId(DB_DataObject $obj, $id, $idField='id', $createdField='created')
2812 $max = self::whereMaxId($id, $idField, $createdField);
2814 $obj->whereAdd($max);
2818 public function isPublic()
2820 $is_local = intval($this->is_local);
2821 return !($is_local === Notice::LOCAL_NONPUBLIC || $is_local === Notice::GATEWAY);
2825 * Check that the given profile is allowed to read, respond to, or otherwise
2826 * act on this notice.
2828 * The $scope member is a bitmask of scopes, representing a logical AND of the
2829 * scope requirement. So, 0x03 (Notice::ADDRESSEE_SCOPE | Notice::SITE_SCOPE) means
2830 * "only visible to people who are mentioned in the notice AND are users on this site."
2831 * Users on the site who are not mentioned in the notice will not be able to see the
2834 * @param Profile $profile The profile to check; pass null to check for public/unauthenticated users.
2836 * @return boolean whether the profile is in the notice's scope
2838 function inScope($profile)
2840 if (is_null($profile)) {
2841 $keypart = sprintf('notice:in-scope-for:%d:null', $this->id);
2843 $keypart = sprintf('notice:in-scope-for:%d:%d', $this->id, $profile->id);
2846 $result = self::cacheGet($keypart);
2848 if ($result === false) {
2850 if (Event::handle('StartNoticeInScope', array($this, $profile, &$bResult))) {
2851 $bResult = $this->_inScope($profile);
2852 Event::handle('EndNoticeInScope', array($this, $profile, &$bResult));
2854 $result = ($bResult) ? 1 : 0;
2855 self::cacheSet($keypart, $result, 0, 300);
2858 return ($result == 1) ? true : false;
2861 protected function _inScope($profile)
2863 $scope = is_null($this->scope) ? self::defaultScope() : $this->getScope();
2865 if ($scope === 0 && !$this->getProfile()->isPrivateStream()) { // Not scoping, so it is public.
2866 return !$this->isHiddenSpam($profile);
2869 // If there's scope, anon cannot be in scope
2870 if (empty($profile)) {
2874 // Author is always in scope
2875 if ($this->profile_id == $profile->id) {
2879 // Only for users on this site
2880 if (($scope & Notice::SITE_SCOPE) && !$profile->isLocal()) {
2884 // Only for users mentioned in the notice
2885 if ($scope & Notice::ADDRESSEE_SCOPE) {
2887 $reply = Reply::pkeyGet(array('notice_id' => $this->id,
2888 'profile_id' => $profile->id));
2890 if (!$reply instanceof Reply) {
2895 // Only for members of the given group
2896 if ($scope & Notice::GROUP_SCOPE) {
2898 // XXX: just query for the single membership
2900 $groups = $this->getGroups();
2904 foreach ($groups as $group) {
2905 if ($profile->isMember($group)) {
2916 if ($scope & Notice::FOLLOWER_SCOPE || $this->getProfile()->isPrivateStream()) {
2918 if (!Subscription::exists($profile, $this->getProfile())) {
2923 return !$this->isHiddenSpam($profile);
2926 function isHiddenSpam($profile) {
2928 // Hide posts by silenced users from everyone but moderators.
2930 if (common_config('notice', 'hidespam')) {
2933 $author = $this->getProfile();
2934 } catch(Exception $e) {
2935 // If we can't get an author, keep it hidden.
2936 // XXX: technically not spam, but, whatever.
2940 if ($author->hasRole(Profile_role::SILENCED)) {
2941 if (!$profile instanceof Profile || (($profile->id !== $author->id) && (!$profile->hasRight(Right::REVIEWSPAM)))) {
2950 public function hasParent()
2954 } catch (NoParentNoticeException $e) {
2960 public function getParent()
2962 $reply_to_id = null;
2964 if (empty($this->reply_to)) {
2965 throw new NoParentNoticeException($this);
2968 // The reply_to ID in the table Notice could exist with a number
2969 // however, the replied to notice might not exist in the database.
2970 // Thus we need to catch the exception and throw the NoParentNoticeException else
2971 // the timeline will not display correctly.
2973 $reply_to_id = self::getByID($this->reply_to);
2974 } catch(Exception $e){
2975 throw new NoParentNoticeException($this);
2978 return $reply_to_id;
2982 * Magic function called at serialize() time.
2984 * We use this to drop a couple process-specific references
2985 * from DB_DataObject which can cause trouble in future
2988 * @return array of variable names to include in serialization.
2993 $vars = parent::__sleep();
2994 $skip = array('_profile', '_groups', '_attachments', '_faves', '_replies', '_repeats');
2995 return array_diff($vars, $skip);
2998 static function defaultScope()
3000 $scope = common_config('notice', 'defaultscope');
3001 if (is_null($scope)) {
3002 if (common_config('site', 'private')) {
3011 static function fillProfiles($notices)
3013 $map = self::getProfiles($notices);
3014 foreach ($notices as $entry=>$notice) {
3016 if (array_key_exists($notice->profile_id, $map)) {
3017 $notice->_setProfile($map[$notice->profile_id]);
3019 } catch (NoProfileException $e) {
3020 common_log(LOG_WARNING, "Failed to fill profile in Notice with non-existing entry for profile_id: {$e->profile_id}");
3021 unset($notices[$entry]);
3025 return array_values($map);
3028 static function getProfiles(&$notices)
3031 foreach ($notices as $notice) {
3032 $ids[] = $notice->profile_id;
3034 $ids = array_unique($ids);
3035 return Profile::pivotGet('id', $ids);
3038 static function fillGroups(&$notices)
3040 $ids = self::_idsOf($notices);
3041 $gis = Group_inbox::listGet('notice_id', $ids);
3044 foreach ($gis as $id => $gi) {
3047 $gids[] = $g->group_id;
3051 $gids = array_unique($gids);
3052 $group = User_group::pivotGet('id', $gids);
3053 foreach ($notices as $notice)
3056 $gi = $gis[$notice->id];
3057 foreach ($gi as $g) {
3058 $grps[] = $group[$g->group_id];
3060 $notice->_setGroups($grps);
3064 static function _idsOf(array &$notices)
3067 foreach ($notices as $notice) {
3068 $ids[$notice->id] = true;
3070 return array_keys($ids);
3073 static function fillAttachments(&$notices)
3075 $ids = self::_idsOf($notices);
3076 $f2pMap = File_to_post::listGet('post_id', $ids);
3078 foreach ($f2pMap as $noticeId => $f2ps) {
3079 foreach ($f2ps as $f2p) {
3080 $fileIds[] = $f2p->file_id;
3084 $fileIds = array_unique($fileIds);
3085 $fileMap = File::pivotGet('id', $fileIds);
3086 foreach ($notices as $notice)
3089 $f2ps = $f2pMap[$notice->id];
3090 foreach ($f2ps as $f2p) {
3091 if (!isset($fileMap[$f2p->file_id])) {
3092 // We have probably deleted value from fileMap since
3093 // it as a NULL entry (see the following elseif).
3095 } elseif (is_null($fileMap[$f2p->file_id])) {
3096 // If the file id lookup returned a NULL value, it doesn't
3097 // exist in our file table! So this is a remnant file_to_post
3098 // entry that is no longer valid and should be removed.
3099 common_debug('ATTACHMENT deleting f2p for post_id='.$f2p->post_id.' file_id='.$f2p->file_id);
3101 unset($fileMap[$f2p->file_id]);
3104 $files[] = $fileMap[$f2p->file_id];
3106 $notice->_setAttachments($files);
3110 static function fillReplies(&$notices)
3112 $ids = self::_idsOf($notices);
3113 $replyMap = Reply::listGet('notice_id', $ids);
3114 foreach ($notices as $notice) {
3115 $replies = $replyMap[$notice->id];
3117 foreach ($replies as $reply) {
3118 $ids[] = $reply->profile_id;
3120 $notice->_setReplies($ids);
3124 static public function beforeSchemaUpdate()
3126 $table = strtolower(get_called_class());
3127 $schema = Schema::get();
3128 $schemadef = $schema->getTableDef($table);
3130 // 2015-09-04 We move Notice location data to Notice_location
3131 // First we see if we have to do this at all
3132 if (isset($schemadef['fields']['lat'])
3133 && isset($schemadef['fields']['lon'])
3134 && isset($schemadef['fields']['location_id'])
3135 && isset($schemadef['fields']['location_ns'])) {
3136 // Then we make sure the Notice_location table is created!
3137 $schema->ensureTable('notice_location', Notice_location::schemaDef());
3139 // Then we continue on our road to migration!
3140 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)";
3142 $notice = new Notice();
3143 $notice->query(sprintf('SELECT id, lat, lon, location_id, location_ns FROM %1$s ' .
3144 'WHERE lat IS NOT NULL ' .
3145 'OR lon IS NOT NULL ' .
3146 'OR location_id IS NOT NULL ' .
3147 'OR location_ns IS NOT NULL',
3148 $schema->quoteIdentifier($table)));
3149 print "\nFound {$notice->N} notices with location data, inserting";
3150 while ($notice->fetch()) {
3151 $notloc = Notice_location::getKV('notice_id', $notice->id);
3152 if ($notloc instanceof Notice_location) {
3156 $notloc = new Notice_location();
3157 $notloc->notice_id = $notice->id;
3158 $notloc->lat= $notice->lat;
3159 $notloc->lon= $notice->lon;
3160 $notloc->location_id= $notice->location_id;
3161 $notloc->location_ns= $notice->location_ns;
3169 * Make sure constraints are met before upgrading, if foreign keys
3170 * are not already in use.
3173 if (!isset($schemadef['foreign keys'])) {
3174 $newschemadef = self::schemaDef();
3175 printfnq("\nConstraint checking Notice table...\n");
3177 * Improve typing and make sure no NULL values in any id-related columns are 0
3180 foreach (['reply_to', 'repeat_of'] as $field) {
3181 $notice = new Notice(); // reset the object
3182 $notice->query(sprintf('UPDATE %1$s SET %2$s=NULL WHERE %2$s=0', $notice->escapedTableName(), $field));
3183 // Now we're sure that no Notice entries have repeat_of=0, only an id > 0 or NULL
3188 * This Will find foreign keys which do not fulfill the constraints and fix
3189 * where appropriate, such as delete when "repeat_of" ID not found in notice.id
3190 * or set to NULL for "reply_to" in the same case.
3193 * XXX: How does this work if we would use multicolumn foreign keys?
3195 foreach (['reply_to' => 'reset', 'repeat_of' => 'delete', 'profile_id' => 'delete'] as $field=>$action) {
3196 $notice = new Notice();
3198 $fkeyname = $notice->tableName().'_'.$field.'_fkey';
3199 assert(isset($newschemadef['foreign keys'][$fkeyname]));
3200 assert($newschemadef['foreign keys'][$fkeyname]);
3202 $foreign_key = $newschemadef['foreign keys'][$fkeyname];
3203 $fkeytable = $foreign_key[0];
3204 assert(isset($foreign_key[1][$field]));
3205 $fkeycol = $foreign_key[1][$field];
3207 printfnq("* {$fkeyname} ({$field} => {$fkeytable}.{$fkeycol})\n");
3209 // NOTE: Above we set all repeat_of to NULL if they were 0, so this really gets them all.
3210 $notice->whereAdd(sprintf('%1$s NOT IN (SELECT %2$s FROM %3$s)', $field, $fkeycol, $fkeytable));
3211 if ($notice->find()) {
3212 printfnq("\tFound {$notice->N} notices with {$field} NOT IN notice.id, {$action}ing...");
3214 case 'delete': // since it's a directly dependant notice for an unknown ID we don't want it in our DB
3215 while ($notice->fetch()) {
3219 case 'reset': // just set it to NULL to be compatible with our constraints, if it was related to an unknown ID
3221 foreach ($notice->fetchAll('id') as $id) {
3222 settype($id, 'int');
3226 $notice = new Notice();
3227 $notice->query(sprintf('UPDATE %1$s SET %2$s=NULL WHERE id IN (%3$s)',
3228 $notice->escapedTableName(),
3230 implode(',', $ids)));
3233 throw new ServerException('The programmer sucks, invalid action name when fixing table.');
3235 printfnq("DONE.\n");