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' => 'the local numerical conversation id'),
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' => null),
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_verb_idx' => array('verb'),
114 'notice_profile_id_verb_idx' => array('profile_id', 'verb'),
115 'notice_url_idx' => array('url'), // Qvitter wants this
116 'notice_replyto_idx' => array('reply_to')
120 if (common_config('search', 'type') == 'fulltext') {
121 $def['fulltext indexes'] = array('content' => array('content'));
128 const LOCAL_PUBLIC = 1;
130 const LOCAL_NONPUBLIC = -1;
133 const PUBLIC_SCOPE = 0; // Useful fake constant
134 const SITE_SCOPE = 1;
135 const ADDRESSEE_SCOPE = 2;
136 const GROUP_SCOPE = 4;
137 const FOLLOWER_SCOPE = 8;
139 protected $_profile = array();
142 * Will always return a profile, if anything fails it will
143 * (through _setProfile) throw a NoProfileException.
145 public function getProfile()
147 if (!isset($this->_profile[$this->profile_id])) {
148 // We could've sent getKV directly to _setProfile, but occasionally we get
149 // a "false" (instead of null), likely because it indicates a cache miss.
150 $profile = Profile::getKV('id', $this->profile_id);
151 $this->_setProfile($profile instanceof Profile ? $profile : null);
153 return $this->_profile[$this->profile_id];
156 public function _setProfile(Profile $profile=null)
158 if (!$profile instanceof Profile) {
159 throw new NoProfileException($this->profile_id);
161 $this->_profile[$this->profile_id] = $profile;
164 public function deleteAs(Profile $actor, $delete_event=true)
166 if (!$this->getProfile()->sameAs($actor) && !$actor->hasRight(Right::DELETEOTHERSNOTICE)) {
167 throw new AuthorizationException(_('You are not allowed to delete another user\'s notice.'));
171 if (!$delete_event || Event::handle('DeleteNoticeAsProfile', array($this, $actor, &$result))) {
172 // If $delete_event is true, we run the event. If the Event then
173 // returns false it is assumed everything was handled properly
174 // and the notice was deleted.
175 $result = $this->delete();
180 protected function deleteRelated()
182 if (Event::handle('NoticeDeleteRelated', array($this))) {
183 // Clear related records
184 $this->clearReplies();
185 $this->clearLocation();
186 $this->clearRepeats();
188 $this->clearGroupInboxes();
190 $this->clearAttentions();
191 // NOTE: we don't clear queue items
195 public function delete($useWhere=false)
197 $this->deleteRelated();
199 $result = parent::delete($useWhere);
201 $this->blowOnDelete();
205 public function getUri()
211 * Get a Notice object by URI. Will call external plugins for help
212 * using the event StartGetNoticeFromURI.
214 * @param string $uri A unique identifier for a resource (notice in this case)
216 static function fromUri($uri)
220 if (Event::handle('StartGetNoticeFromUri', array($uri, &$notice))) {
221 $notice = Notice::getKV('uri', $uri);
222 Event::handle('EndGetNoticeFromUri', array($uri, $notice));
225 if (!$notice instanceof Notice) {
226 throw new UnknownUriException($uri);
233 * @param $root boolean If true, link to just the conversation root.
235 * @return URL to conversation
237 public function getConversationUrl($anchor=true)
239 return Conversation::getUrlFromNotice($this, $anchor);
243 * Get the local representation URL of this notice.
245 public function getLocalUrl()
247 return common_local_url('shownotice', array('notice' => $this->id), null, null, false);
250 public function getTitle()
253 if (Event::handle('GetNoticeTitle', array($this, &$title))) {
254 // TRANS: Title of a notice posted without a title value.
255 // TRANS: %1$s is a user name, %2$s is the notice creation date/time.
256 $title = sprintf(_('%1$s\'s status on %2$s'),
257 $this->getProfile()->getFancyName(),
258 common_exact_date($this->created));
263 public function getContent()
265 return $this->content;
268 public function getRendered()
270 // we test $this->id because if it's not inserted yet, we can't update the field
271 if (!empty($this->id) && (is_null($this->rendered) || $this->rendered === '')) {
272 // update to include rendered content on-the-fly, so we don't have to have a fix-up script in upgrade.php
273 common_debug('Rendering notice '.$this->getID().' as it had no rendered HTML content.');
274 $orig = clone($this);
275 $this->rendered = common_render_content($this->getContent(),
277 $this->hasParent() ? $this->getParent() : null);
278 $this->update($orig);
280 return $this->rendered;
283 public function getCreated()
285 return $this->created;
288 public function getVerb($make_relative=false)
290 return ActivityUtils::resolveUri($this->verb, $make_relative);
293 public function isVerb(array $verbs)
295 return ActivityUtils::compareVerbs($this->getVerb(), $verbs);
299 * Get the original representation URL of this notice.
301 * @param boolean $fallback Whether to fall back to generate a local URL or throw InvalidUrlException
303 public function getUrl($fallback=false)
305 // The risk is we start having empty urls and non-http uris...
306 // and we can't really handle any other protocol right now.
308 case $this->isLocal():
309 return common_local_url('shownotice', array('notice' => $this->getID()), null, null, false);
310 case common_valid_http_url($this->url): // should we allow non-http/https URLs?
312 case common_valid_http_url($this->uri): // Sometimes we only have the URI for remote posts.
315 // let's generate a valid link to our locally available notice on demand
316 return common_local_url('shownotice', array('notice' => $this->getID()), null, null, false);
318 throw new InvalidUrlException($this->url);
322 public function getObjectType($canonical=false) {
323 if (is_null($this->object_type) || $this->object_type==='') {
324 throw new NoObjectTypeException($this);
326 return ActivityUtils::resolveUri($this->object_type, $canonical);
329 public function isObjectType(array $types)
332 return ActivityUtils::compareTypes($this->getObjectType(), $types);
333 } catch (NoObjectTypeException $e) {
338 public static function getByUri($uri)
340 $notice = new Notice();
342 if (!$notice->find(true)) {
343 throw new NoResultException($notice);
349 * Extract #hashtags from this notice's content and save them to the database.
353 /* extract all #hastags */
354 $count = preg_match_all('/(?:^|\s)#([\pL\pN_\-\.]{1,64})/u', strtolower($this->content), $match);
359 /* Add them to the database */
360 return $this->saveKnownTags($match[1]);
364 * Record the given set of hash tags in the db for this notice.
365 * Given tag strings will be normalized and checked for dupes.
367 function saveKnownTags($hashtags)
369 //turn each into their canonical tag
370 //this is needed to remove dupes before saving e.g. #hash.tag = #hashtag
371 for($i=0; $i<count($hashtags); $i++) {
372 /* elide characters we don't want in the tag */
373 $hashtags[$i] = common_canonical_tag($hashtags[$i]);
376 foreach(array_unique($hashtags) as $hashtag) {
377 $this->saveTag($hashtag);
378 self::blow('profile:notice_ids_tagged:%d:%s', $this->profile_id, $hashtag);
384 * Record a single hash tag as associated with this notice.
385 * Tag format and uniqueness must be validated by caller.
387 function saveTag($hashtag)
389 $tag = new Notice_tag();
390 $tag->notice_id = $this->id;
391 $tag->tag = $hashtag;
392 $tag->created = $this->created;
393 $id = $tag->insert();
396 // TRANS: Server exception. %s are the error details.
397 throw new ServerException(sprintf(_('Database error inserting hashtag: %s.'),
398 $last_error->message));
402 // if it's saved, blow its cache
403 $tag->blowCache(false);
407 * Save a new notice and push it out to subscribers' inboxes.
408 * Poster's permissions are checked before sending.
410 * @param int $profile_id Profile ID of the poster
411 * @param string $content source message text; links may be shortened
412 * per current user's preference
413 * @param string $source source key ('web', 'api', etc)
414 * @param array $options Associative array of optional properties:
415 * string 'created' timestamp of notice; defaults to now
416 * int 'is_local' source/gateway ID, one of:
417 * Notice::LOCAL_PUBLIC - Local, ok to appear in public timeline
418 * Notice::REMOTE - Sent from a remote service;
419 * hide from public timeline but show in
420 * local "and friends" timelines
421 * Notice::LOCAL_NONPUBLIC - Local, but hide from public timeline
422 * Notice::GATEWAY - From another non-OStatus service;
423 * will not appear in public views
424 * float 'lat' decimal latitude for geolocation
425 * float 'lon' decimal longitude for geolocation
426 * int 'location_id' geoname identifier
427 * int 'location_ns' geoname namespace to interpret location_id
428 * int 'reply_to'; notice ID this is a reply to
429 * int 'repeat_of'; notice ID this is a repeat of
430 * string 'uri' unique ID for notice; a unique tag uri (can be url or anything too)
431 * string 'url' permalink to notice; defaults to local notice URL
432 * string 'rendered' rendered HTML version of content
433 * array 'replies' list of profile URIs for reply delivery in
434 * place of extracting @-replies from content.
435 * array 'groups' list of group IDs to deliver to, in place of
436 * extracting ! tags from content
437 * array 'tags' list of hashtag strings to save with the notice
438 * in place of extracting # tags from content
439 * array 'urls' list of attached/referred URLs to save with the
440 * notice in place of extracting links from content
441 * boolean 'distribute' whether to distribute the notice, default true
442 * string 'object_type' URL of the associated object type (default ActivityObject::NOTE)
443 * string 'verb' URL of the associated verb (default ActivityVerb::POST)
444 * int 'scope' Scope bitmask; default to SITE_SCOPE on private sites, 0 otherwise
446 * @fixme tag override
449 * @throws ClientException
451 static function saveNew($profile_id, $content, $source, array $options=null) {
452 $defaults = array('uri' => null,
454 'conversation' => null, // URI of conversation
455 'reply_to' => null, // This will override convo URI if the parent is known
456 'repeat_of' => null, // This will override convo URI if the repeated notice is known
458 'distribute' => true,
459 'object_type' => null,
462 if (!empty($options) && is_array($options)) {
463 $options = array_merge($defaults, $options);
469 if (!isset($is_local)) {
470 $is_local = Notice::LOCAL_PUBLIC;
473 $profile = Profile::getKV('id', $profile_id);
474 if (!$profile instanceof Profile) {
475 // TRANS: Client exception thrown when trying to save a notice for an unknown user.
476 throw new ClientException(_('Problem saving notice. Unknown user.'));
479 $user = User::getKV('id', $profile_id);
480 if ($user instanceof User) {
481 // Use the local user's shortening preferences, if applicable.
482 $final = $user->shortenLinks($content);
484 $final = common_shorten_links($content);
487 if (Notice::contentTooLong($final)) {
488 // TRANS: Client exception thrown if a notice contains too many characters.
489 throw new ClientException(_('Problem saving notice. Too long.'));
492 if (common_config('throttle', 'enabled') && !Notice::checkEditThrottle($profile_id)) {
493 common_log(LOG_WARNING, 'Excessive posting by profile #' . $profile_id . '; throttled.');
494 // TRANS: Client exception thrown when a user tries to post too many notices in a given time frame.
495 throw new ClientException(_('Too many notices too fast; take a breather '.
496 'and post again in a few minutes.'));
499 if (common_config('site', 'dupelimit') > 0 && !Notice::checkDupes($profile_id, $final)) {
500 common_log(LOG_WARNING, 'Dupe posting by profile #' . $profile_id . '; throttled.');
501 // TRANS: Client exception thrown when a user tries to post too many duplicate notices in a given time frame.
502 throw new ClientException(_('Too many duplicate messages too quickly;'.
503 ' take a breather and post again in a few minutes.'));
506 if (!$profile->hasRight(Right::NEWNOTICE)) {
507 common_log(LOG_WARNING, "Attempted post from user disallowed to post: " . $profile->nickname);
509 // TRANS: Client exception thrown when a user tries to post while being banned.
510 throw new ClientException(_('You are banned from posting notices on this site.'), 403);
513 $notice = new Notice();
514 $notice->profile_id = $profile_id;
516 if ($source && in_array($source, common_config('public', 'autosource'))) {
517 $notice->is_local = Notice::LOCAL_NONPUBLIC;
519 $notice->is_local = $is_local;
522 if (!empty($created)) {
523 $notice->created = $created;
525 $notice->created = common_sql_now();
528 if (!$notice->isLocal()) {
529 // Only do these checks for non-local notices. Local notices will generate these values later.
531 throw new ServerException('No URI for remote notice. Cannot accept that.');
535 $notice->content = $final;
537 $notice->source = $source;
541 // Get the groups here so we can figure out replies and such
542 if (!isset($groups)) {
543 $groups = User_group::idsFromText($notice->content, $profile);
548 // Handle repeat case
550 if (!empty($options['repeat_of'])) {
552 // Check for a private one
554 $repeat = Notice::getByID($options['repeat_of']);
556 if ($profile->sameAs($repeat->getProfile())) {
557 // TRANS: Client error displayed when trying to repeat an own notice.
558 throw new ClientException(_('You cannot repeat your own notice.'));
561 if ($repeat->scope != Notice::SITE_SCOPE &&
562 $repeat->scope != Notice::PUBLIC_SCOPE) {
563 // TRANS: Client error displayed when trying to repeat a non-public notice.
564 throw new ClientException(_('Cannot repeat a private notice.'), 403);
567 if (!$repeat->inScope($profile)) {
568 // The generic checks above should cover this, but let's be sure!
569 // TRANS: Client error displayed when trying to repeat a notice you cannot access.
570 throw new ClientException(_('Cannot repeat a notice you cannot read.'), 403);
573 if ($profile->hasRepeated($repeat)) {
574 // TRANS: Client error displayed when trying to repeat an already repeated notice.
575 throw new ClientException(_('You already repeated that notice.'));
578 $notice->repeat_of = $repeat->id;
579 $notice->conversation = $repeat->conversation;
583 // If $reply_to is specified, we check that it exists, and then
584 // return it if it does
585 if (!empty($reply_to)) {
586 $reply = Notice::getKV('id', $reply_to);
587 } elseif (in_array($source, array('xmpp', 'mail', 'sms'))) {
588 // If the source lacks capability of sending the "reply_to"
589 // metadata, let's try to find an inline replyto-reference.
590 $reply = self::getInlineReplyTo($profile, $final);
593 if ($reply instanceof Notice) {
594 if (!$reply->inScope($profile)) {
595 // TRANS: Client error displayed when trying to reply to a notice a the target has no access to.
596 // TRANS: %1$s is a user nickname, %2$d is a notice ID (number).
597 throw new ClientException(sprintf(_('%1$s has no access to notice %2$d.'),
598 $profile->nickname, $reply->id), 403);
601 // If it's a repeat, the reply_to should be to the original
602 if ($reply->isRepeat()) {
603 $notice->reply_to = $reply->repeat_of;
605 $notice->reply_to = $reply->id;
607 // But the conversation ought to be the same :)
608 $notice->conversation = $reply->conversation;
610 // If the original is private to a group, and notice has
611 // no group specified, make it to the same group(s)
613 if (empty($groups) && ($reply->scope & Notice::GROUP_SCOPE)) {
615 $replyGroups = $reply->getGroups();
616 foreach ($replyGroups as $group) {
617 if ($profile->isMember($group)) {
618 $groups[] = $group->id;
626 // If we don't know the reply, we might know the conversation!
627 // This will happen if a known remote user replies to an
628 // unknown remote user - within a known conversation.
629 if (empty($notice->conversation) and !empty($options['conversation'])) {
630 $conv = Conversation::getKV('uri', $options['conversation']);
631 if ($conv instanceof Conversation) {
632 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.').');
634 // Conversation entry with specified URI was not found, so we must create it.
635 common_debug('Conversation URI not found, so we will create it with the URI given in the options to Notice::saveNew: '.$options['conversation']);
636 // The insert in Conversation::create throws exception on failure
637 $conv = Conversation::create($options['conversation'], $notice->created);
639 $notice->conversation = $conv->getID();
644 // If it's not part of a conversation, it's the beginning of a new conversation.
645 if (empty($notice->conversation)) {
646 $conv = Conversation::create();
647 $notice->conversation = $conv->getID();
652 $notloc = new Notice_location();
653 if (!empty($lat) && !empty($lon)) {
658 if (!empty($location_ns) && !empty($location_id)) {
659 $notloc->location_id = $location_id;
660 $notloc->location_ns = $location_ns;
663 if (!empty($rendered)) {
664 $notice->rendered = $rendered;
666 $notice->rendered = common_render_content($final,
667 $notice->getProfile(),
668 $notice->hasParent() ? $notice->getParent() : null);
672 if ($notice->isRepeat()) {
673 $notice->verb = ActivityVerb::SHARE;
674 $notice->object_type = ActivityObject::ACTIVITY;
676 $notice->verb = ActivityVerb::POST;
679 $notice->verb = $verb;
682 if (empty($object_type)) {
683 $notice->object_type = (empty($notice->reply_to)) ? ActivityObject::NOTE : ActivityObject::COMMENT;
685 $notice->object_type = $object_type;
688 if (is_null($scope) && $reply instanceof Notice) {
689 $notice->scope = $reply->scope;
691 $notice->scope = $scope;
694 $notice->scope = self::figureOutScope($profile, $groups, $notice->scope);
696 if (Event::handle('StartNoticeSave', array(&$notice))) {
698 // XXX: some of these functions write to the DB
701 $notice->insert(); // throws exception on failure, if successful we have an ->id
703 if (($notloc->lat && $notloc->lon) || ($notloc->location_id && $notloc->location_ns)) {
704 $notloc->notice_id = $notice->getID();
705 $notloc->insert(); // store the notice location if it had any information
707 } catch (Exception $e) {
708 // Let's test if we managed initial insert, which would imply
709 // failing on some update-part (check 'insert()'). Delete if
710 // something had been stored to the database.
711 if (!empty($notice->id)) {
718 // Only save 'attention' and metadata stuff (URLs, tags...) stuff if
719 // the activityverb is a POST (since stuff like repeat, favorite etc.
720 // reasonably handle notifications themselves.
721 if (ActivityUtils::compareVerbs($notice->verb, array(ActivityVerb::POST))) {
722 if (isset($replies)) {
723 $notice->saveKnownReplies($replies);
725 $notice->saveReplies();
729 $notice->saveKnownTags($tags);
734 // Note: groups may save tags, so must be run after tags are saved
735 // to avoid errors on duplicates.
736 // Note: groups should always be set.
738 $notice->saveKnownGroups($groups);
741 $notice->saveKnownUrls($urls);
748 // Prepare inbox delivery, may be queued to background.
749 $notice->distribute();
755 static function saveActivity(Activity $act, Profile $actor, array $options=array())
757 // First check if we're going to let this Activity through from the specific actor
758 if (!$actor->hasRight(Right::NEWNOTICE)) {
759 common_log(LOG_WARNING, "Attempted post from user disallowed to post: " . $actor->getNickname());
761 // TRANS: Client exception thrown when a user tries to post while being banned.
762 throw new ClientException(_m('You are banned from posting notices on this site.'), 403);
764 if (common_config('throttle', 'enabled') && !self::checkEditThrottle($actor->id)) {
765 common_log(LOG_WARNING, 'Excessive posting by profile #' . $actor->id . '; throttled.');
766 // TRANS: Client exception thrown when a user tries to post too many notices in a given time frame.
767 throw new ClientException(_m('Too many notices too fast; take a breather '.
768 'and post again in a few minutes.'));
771 // Get ActivityObject properties
773 if (!empty($act->id)) {
775 $options['uri'] = $act->id;
776 $options['url'] = $act->link;
778 $actobj = count($act->objects)===1 ? $act->objects[0] : null;
779 if (!is_null($actobj) && !empty($actobj->id)) {
780 $options['uri'] = $actobj->id;
782 $options['url'] = $actobj->link;
783 } elseif (preg_match('!^https?://!', $actobj->id)) {
784 $options['url'] = $actobj->id;
791 'is_local' => $actor->isLocal() ? self::LOCAL_PUBLIC : self::REMOTE,
792 'mentions' => array(),
796 'source' => 'unknown',
801 'distribute' => true);
803 // options will have default values when nothing has been supplied
804 $options = array_merge($defaults, $options);
805 foreach (array_keys($defaults) as $key) {
806 // Only convert the keynames we specify ourselves from 'defaults' array into variables
807 $$key = $options[$key];
809 extract($options, EXTR_SKIP);
812 $stored = new Notice();
813 if (!empty($uri) && !ActivityUtils::compareVerbs($act->verb, array(ActivityVerb::DELETE))) {
815 if ($stored->find()) {
816 common_debug('cannot create duplicate Notice URI: '.$stored->uri);
817 // I _assume_ saving a Notice with a colliding URI means we're really trying to
818 // save the same notice again...
819 throw new AlreadyFulfilledException('Notice URI already exists');
823 // NOTE: Sandboxed users previously got all the notices _during_
824 // sandbox period set to to is_local=Notice::LOCAL_NONPUBLIC here.
825 // Since then we have started just filtering _when_ it gets shown
826 // instead of creating a mixed jumble of differently scoped notices.
828 if ($source && in_array($source, common_config('public', 'autosource'))) {
829 $stored->is_local = Notice::LOCAL_NONPUBLIC;
831 $stored->is_local = intval($is_local);
834 if (!$stored->isLocal()) {
835 // Only do these checks for non-local notices. Local notices will generate these values later.
836 if (!common_valid_http_url($url)) {
837 common_debug('Bad notice URL: ['.$url.'], URI: ['.$uri.']. Cannot link back to original! This is normal for shared notices etc.');
840 throw new ServerException('No URI for remote notice. Cannot accept that.');
844 $stored->profile_id = $actor->getID();
845 $stored->source = $source;
848 $stored->verb = $act->verb;
850 // we use mb_strlen because it _might_ be that the content is just the string "0"...
851 $content = mb_strlen($act->content) ? $act->content : $act->summary;
852 if (mb_strlen($content)===0 && !is_null($actobj)) {
853 $content = mb_strlen($actobj->content) ? $actobj->content : $actobj->summary;
855 // Strip out any bad HTML from $content. URI.Base is used to sort out relative URLs.
856 $stored->rendered = common_purify($content, ['URI.Base' => $stored->url ?: null]);
857 $stored->content = common_strip_html($stored->getRendered(), true, true);
858 if (trim($stored->content) === '') {
859 // TRANS: Error message when the plain text content of a notice has zero length.
860 throw new ClientException(_('Empty notice content, will not save this.'));
862 unset($content); // garbage collect
864 // Maybe a missing act-time should be fatal if the actor is not local?
865 if (!empty($act->time)) {
866 $stored->created = common_sql_date($act->time);
868 $stored->created = common_sql_now();
871 $reply = null; // this will store the in-reply-to Notice if found
872 $replyUris = []; // this keeps a list of possible URIs to look up
873 if ($act->context instanceof ActivityContext && !empty($act->context->replyToID)) {
874 $replyUris[] = $act->context->replyToID;
876 if ($act->target instanceof ActivityObject && !empty($act->target->id)) {
877 $replyUris[] = $act->target->id;
879 foreach (array_unique($replyUris) as $replyUri) {
880 $reply = self::getKV('uri', $replyUri);
881 // Only do remote fetching if we're not a private site
882 if (!common_config('site', 'private') && !$reply instanceof Notice) {
883 // the URI is the object we're looking for, $actor is a
884 // Profile that surely knows of it and &$reply where it
885 // will be stored when fetched
886 Event::handle('FetchRemoteNotice', array($replyUri, $actor, &$reply));
888 // we got what we're in-reply-to now, so let's move on
889 if ($reply instanceof Notice) {
892 // otherwise reset whatever we might've gotten from the event
895 unset($replyUris); // garbage collect
897 if ($reply instanceof Notice) {
898 if (!$reply->inScope($actor)) {
899 // TRANS: Client error displayed when trying to reply to a notice a the target has no access to.
900 // TRANS: %1$s is a user nickname, %2$d is a notice ID (number).
901 throw new ClientException(sprintf(_m('%1$s has no right to reply to notice %2$d.'), $actor->getNickname(), $reply->id), 403);
904 $stored->reply_to = $reply->id;
905 $stored->conversation = $reply->conversation;
907 // If the original is private to a group, and notice has no group specified,
908 // make it to the same group(s)
909 if (empty($groups) && ($reply->scope & Notice::GROUP_SCOPE)) {
910 $replyGroups = $reply->getGroups();
911 foreach ($replyGroups as $group) {
912 if ($actor->isMember($group)) {
913 $groups[] = $group->id;
918 if (is_null($scope)) {
919 $scope = $reply->scope;
922 // If we don't know the reply, we might know the conversation!
923 // This will happen if a known remote user replies to an
924 // unknown remote user - within a known conversation.
925 if (empty($stored->conversation) and !empty($act->context->conversation)) {
926 $conv = Conversation::getKV('uri', $act->context->conversation);
927 if ($conv instanceof Conversation) {
928 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.').');
930 // Conversation entry with specified URI was not found, so we must create it.
931 common_debug('Conversation URI not found, so we will create it with the URI given in the context of the activity: '.$act->context->conversation);
932 // The insert in Conversation::create throws exception on failure
933 $conv = Conversation::create($act->context->conversation, $stored->created);
935 $stored->conversation = $conv->getID();
939 unset($reply); // garbage collect
941 // If it's not part of a conversation, it's the beginning of a new conversation.
942 if (empty($stored->conversation)) {
943 $conv = Conversation::create();
944 $stored->conversation = $conv->getID();
949 if ($act->context instanceof ActivityContext) {
950 if ($act->context->location instanceof Location) {
951 $notloc = Notice_location::fromLocation($act->context->location);
954 $act->context = new ActivityContext();
957 if (array_key_exists('http://activityschema.org/collection/public', $act->context->attention)) {
958 $stored->scope = Notice::PUBLIC_SCOPE;
959 // TODO: maybe we should actually keep this? if the saveAttentions thing wants to use it...
960 unset($act->context->attention['http://activityschema.org/collection/public']);
962 $stored->scope = self::figureOutScope($actor, $groups, $scope);
965 foreach ($act->categories as $cat) {
967 $term = common_canonical_tag($cat->term);
974 foreach ($act->enclosures as $href) {
975 // @todo FIXME: Save these locally or....?
979 if (ActivityUtils::compareVerbs($stored->verb, array(ActivityVerb::POST))) {
980 if (empty($act->objects[0]->type)) {
981 // Default type for the post verb is 'note', but we know it's
982 // a 'comment' if it is in reply to something.
983 $stored->object_type = empty($stored->reply_to) ? ActivityObject::NOTE : ActivityObject::COMMENT;
985 //TODO: Is it safe to always return a relative URI? The
986 // JSON version of ActivityStreams always use it, so we
987 // should definitely be able to handle it...
988 $stored->object_type = ActivityUtils::resolveUri($act->objects[0]->type, true);
992 if (Event::handle('StartNoticeSave', array(&$stored))) {
993 // XXX: some of these functions write to the DB
996 $result = $stored->insert(); // throws exception on error
998 if ($notloc instanceof Notice_location) {
999 $notloc->notice_id = $stored->getID();
1003 $orig = clone($stored); // for updating later in this try clause
1006 Event::handle('StoreActivityObject', array($act, $stored, $options, &$object));
1007 if (empty($object)) {
1008 throw new NoticeSaveException('Unsuccessful call to StoreActivityObject '._ve($stored->getUri()) . ': '._ve($act->asString()));
1012 // If something changed in the Notice during StoreActivityObject
1013 $stored->update($orig);
1014 } catch (Exception $e) {
1015 if (empty($stored->id)) {
1016 common_debug('Failed to save stored object entry in database ('.$e->getMessage().')');
1018 common_debug('Failed to store activity object in database ('.$e->getMessage().'), deleting notice id '.$stored->id);
1024 unset($notloc); // garbage collect
1026 if (!$stored instanceof Notice) {
1027 throw new ServerException('StartNoticeSave did not give back a Notice.');
1028 } elseif (empty($stored->id)) {
1029 throw new ServerException('Supposedly saved Notice has no ID.');
1032 // Only save 'attention' and metadata stuff (URLs, tags...) stuff if
1033 // the activityverb is a POST (since stuff like repeat, favorite etc.
1034 // reasonably handle notifications themselves.
1035 if (ActivityUtils::compareVerbs($stored->verb, array(ActivityVerb::POST))) {
1037 if (!empty($tags)) {
1038 $stored->saveKnownTags($tags);
1040 $stored->saveTags();
1043 // Note: groups may save tags, so must be run after tags are saved
1044 // to avoid errors on duplicates.
1045 $stored->saveAttentions($act->context->attention);
1047 if (!empty($urls)) {
1048 $stored->saveKnownUrls($urls);
1050 $stored->saveUrls();
1055 // Prepare inbox delivery, may be queued to background.
1056 $stored->distribute();
1062 static public function figureOutScope(Profile $actor, array $groups, $scope=null) {
1063 $scope = is_null($scope) ? self::defaultScope() : intval($scope);
1065 // For private streams
1067 $user = $actor->getUser();
1068 // FIXME: We can't do bit comparison with == (Legacy StatusNet thing. Let's keep it for now.)
1069 if ($user->private_stream && ($scope === Notice::PUBLIC_SCOPE || $scope === Notice::SITE_SCOPE)) {
1070 $scope |= Notice::FOLLOWER_SCOPE;
1072 } catch (NoSuchUserException $e) {
1073 // TODO: Not a local user, so we don't know about scope preferences... yet!
1076 // Force the scope for private groups
1077 foreach ($groups as $group_id) {
1079 $group = User_group::getByID($group_id);
1080 if ($group->force_scope) {
1081 $scope |= Notice::GROUP_SCOPE;
1084 } catch (Exception $e) {
1085 common_log(LOG_ERR, 'Notice figureOutScope threw exception: '.$e->getMessage());
1092 function blowOnInsert($conversation = false)
1094 $this->blowStream('profile:notice_ids:%d', $this->profile_id);
1096 if ($this->isPublic()) {
1097 $this->blowStream('public');
1098 $this->blowStream('networkpublic');
1101 if ($this->conversation) {
1102 self::blow('notice:list-ids:conversation:%s', $this->conversation);
1103 self::blow('conversation:notice_count:%d', $this->conversation);
1106 if ($this->isRepeat()) {
1107 // XXX: we should probably only use one of these
1108 $this->blowStream('notice:repeats:%d', $this->repeat_of);
1109 self::blow('notice:list-ids:repeat_of:%d', $this->repeat_of);
1112 $original = Notice::getKV('id', $this->repeat_of);
1114 if ($original instanceof Notice) {
1115 $originalUser = User::getKV('id', $original->profile_id);
1116 if ($originalUser instanceof User) {
1117 $this->blowStream('user:repeats_of_me:%d', $originalUser->id);
1121 $profile = Profile::getKV($this->profile_id);
1123 if ($profile instanceof Profile) {
1124 $profile->blowNoticeCount();
1127 $ptags = $this->getProfileTags();
1128 foreach ($ptags as $ptag) {
1129 $ptag->blowNoticeStreamCache();
1134 * Clear cache entries related to this notice at delete time.
1135 * Necessary to avoid breaking paging on public, profile timelines.
1137 function blowOnDelete()
1139 $this->blowOnInsert();
1141 self::blow('profile:notice_ids:%d;last', $this->profile_id);
1143 if ($this->isPublic()) {
1144 self::blow('public;last');
1145 self::blow('networkpublic;last');
1148 self::blow('fave:by_notice', $this->id);
1150 if ($this->conversation) {
1151 // In case we're the first, will need to calc a new root.
1152 self::blow('notice:conversation_root:%d', $this->conversation);
1155 $ptags = $this->getProfileTags();
1156 foreach ($ptags as $ptag) {
1157 $ptag->blowNoticeStreamCache(true);
1161 function blowStream()
1163 $c = self::memcache();
1169 $args = func_get_args();
1170 $format = array_shift($args);
1171 $keyPart = vsprintf($format, $args);
1172 $cacheKey = Cache::key($keyPart);
1173 $c->delete($cacheKey);
1175 // delete the "last" stream, too, if this notice is
1176 // older than the top of that stream
1178 $lastKey = $cacheKey.';last';
1180 $lastStr = $c->get($lastKey);
1182 if ($lastStr !== false) {
1183 $window = explode(',', $lastStr);
1184 $lastID = $window[0];
1185 $lastNotice = Notice::getKV('id', $lastID);
1186 if (!$lastNotice instanceof Notice // just weird
1187 || strtotime($lastNotice->created) >= strtotime($this->created)) {
1188 $c->delete($lastKey);
1193 /** save all urls in the notice to the db
1195 * follow redirects and save all available file information
1196 * (mimetype, date, size, oembed, etc.)
1200 function saveUrls() {
1201 if (common_config('attachments', 'process_links')) {
1202 common_replace_urls_callback($this->content, array($this, 'saveUrl'), $this);
1207 * Save the given URLs as related links/attachments to the db
1209 * follow redirects and save all available file information
1210 * (mimetype, date, size, oembed, etc.)
1214 function saveKnownUrls($urls)
1216 if (common_config('attachments', 'process_links')) {
1217 // @fixme validation?
1218 foreach (array_unique($urls) as $url) {
1219 $this->saveUrl($url, $this);
1227 function saveUrl($url, Notice $notice) {
1229 File::processNew($url, $notice);
1230 } catch (ServerException $e) {
1231 // Could not save URL. Log it?
1235 static function checkDupes($profile_id, $content) {
1236 $profile = Profile::getKV($profile_id);
1237 if (!$profile instanceof Profile) {
1240 $notice = $profile->getNotices(0, CachingNoticeStream::CACHE_WINDOW);
1241 if (!empty($notice)) {
1243 while ($notice->fetch()) {
1244 if (time() - strtotime($notice->created) >= common_config('site', 'dupelimit')) {
1246 } else if ($notice->content == $content) {
1251 // If we get here, oldest item in cache window is not
1252 // old enough for dupe limit; do direct check against DB
1253 $notice = new Notice();
1254 $notice->profile_id = $profile_id;
1255 $notice->content = $content;
1256 $threshold = common_sql_date(time() - common_config('site', 'dupelimit'));
1257 $notice->whereAdd(sprintf("created > '%s'", $notice->escape($threshold)));
1259 $cnt = $notice->count();
1263 static function checkEditThrottle($profile_id) {
1264 $profile = Profile::getKV($profile_id);
1265 if (!$profile instanceof Profile) {
1268 // Get the Nth notice
1269 $notice = $profile->getNotices(common_config('throttle', 'count') - 1, 1);
1270 if ($notice && $notice->fetch()) {
1271 // If the Nth notice was posted less than timespan seconds ago
1272 if (time() - strtotime($notice->created) <= common_config('throttle', 'timespan')) {
1277 // Either not N notices in the stream, OR the Nth was not posted within timespan seconds
1281 protected $_attachments = array();
1283 function attachments() {
1284 if (isset($this->_attachments[$this->id])) {
1285 return $this->_attachments[$this->id];
1288 $f2ps = File_to_post::listGet('post_id', array($this->id));
1290 foreach ($f2ps[$this->id] as $f2p) {
1291 $ids[] = $f2p->file_id;
1294 return $this->_setAttachments(File::multiGet('id', $ids)->fetchAll());
1297 public function _setAttachments(array $attachments)
1299 return $this->_attachments[$this->id] = $attachments;
1302 static function publicStream($offset=0, $limit=20, $since_id=null, $max_id=null)
1304 $stream = new PublicNoticeStream();
1305 return $stream->getNotices($offset, $limit, $since_id, $max_id);
1308 static function conversationStream($id, $offset=0, $limit=20, $since_id=null, $max_id=null, Profile $scoped=null)
1310 $stream = new ConversationNoticeStream($id, $scoped);
1311 return $stream->getNotices($offset, $limit, $since_id, $max_id);
1315 * Is this notice part of an active conversation?
1317 * @return boolean true if other messages exist in the same
1318 * conversation, false if this is the only one
1320 function hasConversation()
1322 if (empty($this->conversation)) {
1323 // this notice is not part of a conversation apparently
1324 // FIXME: all notices should have a conversation value, right?
1328 //FIXME: Get the Profile::current() stuff some other way
1329 // to avoid confusion between queue processing and session.
1330 $notice = self::conversationStream($this->conversation, 1, 1, null, null, Profile::current());
1332 // if our "offset 1, limit 1" query got a result, return true else false
1333 return $notice->N > 0;
1337 * Grab the earliest notice from this conversation.
1339 * @return Notice or null
1341 function conversationRoot($profile=-1)
1343 // XXX: can this happen?
1345 if (empty($this->conversation)) {
1349 // Get the current profile if not specified
1351 if (is_int($profile) && $profile == -1) {
1352 $profile = Profile::current();
1355 // If this notice is out of scope, no root for you!
1357 if (!$this->inScope($profile)) {
1361 // If this isn't a reply to anything, then it's its own
1362 // root if it's the earliest notice in the conversation:
1364 if (empty($this->reply_to)) {
1366 $root->conversation = $this->conversation;
1367 $root->orderBy('notice.created ASC');
1368 $root->find(true); // true means "fetch first result"
1373 if (is_null($profile)) {
1374 $keypart = sprintf('notice:conversation_root:%d:null', $this->id);
1376 $keypart = sprintf('notice:conversation_root:%d:%d',
1381 $root = self::cacheGet($keypart);
1383 if ($root !== false && $root->inScope($profile)) {
1390 $parent = $last->getParent();
1391 if ($parent->inScope($profile)) {
1395 } catch (NoParentNoticeException $e) {
1396 // Latest notice has no parent
1397 } catch (NoResultException $e) {
1398 // Notice was not found, so we can't go further up in the tree.
1399 // FIXME: Maybe we should do this in a more stable way where deleted
1400 // notices won't break conversation chains?
1402 // No parent, or parent out of scope
1407 self::cacheSet($keypart, $root);
1413 * Pull up a full list of local recipients who will be getting
1414 * this notice in their inbox. Results will be cached, so don't
1415 * change the input data wily-nilly!
1417 * @param array $groups optional list of Group objects;
1418 * if left empty, will be loaded from group_inbox records
1419 * @param array $recipient optional list of reply profile ids
1420 * if left empty, will be loaded from reply records
1421 * @return array associating recipient user IDs with an inbox source constant
1423 function whoGets(array $groups=null, array $recipients=null)
1425 $c = self::memcache();
1428 $ni = $c->get(Cache::key('notice:who_gets:'.$this->id));
1429 if ($ni !== false) {
1434 if (is_null($recipients)) {
1435 $recipients = $this->getReplies();
1440 // Give plugins a chance to add folks in at start...
1441 if (Event::handle('StartNoticeWhoGets', array($this, &$ni))) {
1443 $users = $this->getSubscribedUsers();
1444 foreach ($users as $id) {
1445 $ni[$id] = NOTICE_INBOX_SOURCE_SUB;
1448 if (is_null($groups)) {
1449 $groups = $this->getGroups();
1451 foreach ($groups as $group) {
1452 $users = $group->getUserMembers();
1453 foreach ($users as $id) {
1454 if (!array_key_exists($id, $ni)) {
1455 $ni[$id] = NOTICE_INBOX_SOURCE_GROUP;
1460 $ptAtts = $this->getAttentionsFromProfileTags();
1461 foreach ($ptAtts as $key=>$val) {
1462 if (!array_key_exists($key, $ni)) {
1467 foreach ($recipients as $recipient) {
1468 if (!array_key_exists($recipient, $ni)) {
1469 $ni[$recipient] = NOTICE_INBOX_SOURCE_REPLY;
1473 // Exclude any deleted, non-local, or blocking recipients.
1474 $profile = $this->getProfile();
1475 $originalProfile = null;
1476 if ($this->isRepeat()) {
1477 // Check blocks against the original notice's poster as well.
1478 $original = Notice::getKV('id', $this->repeat_of);
1479 if ($original instanceof Notice) {
1480 $originalProfile = $original->getProfile();
1484 foreach ($ni as $id => $source) {
1486 $user = User::getKV('id', $id);
1487 if (!$user instanceof User ||
1488 $user->hasBlocked($profile) ||
1489 ($originalProfile && $user->hasBlocked($originalProfile))) {
1492 } catch (UserNoProfileException $e) {
1493 // User doesn't have a profile; invalid; skip them.
1498 // Give plugins a chance to filter out...
1499 Event::handle('EndNoticeWhoGets', array($this, &$ni));
1503 // XXX: pack this data better
1504 $c->set(Cache::key('notice:who_gets:'.$this->id), $ni);
1510 function getSubscribedUsers()
1514 if(common_config('db','quote_identifiers'))
1515 $user_table = '"user"';
1516 else $user_table = 'user';
1520 'FROM '. $user_table .' JOIN subscription '.
1521 'ON '. $user_table .'.id = subscription.subscriber ' .
1522 'WHERE subscription.subscribed = %d ';
1524 $user->query(sprintf($qry, $this->profile_id));
1528 while ($user->fetch()) {
1537 function getProfileTags()
1539 $profile = $this->getProfile();
1540 $list = $profile->getOtherTags($profile);
1543 while($list->fetch()) {
1544 $ptags[] = clone($list);
1550 public function getAttentionsFromProfileTags()
1553 $ptags = $this->getProfileTags();
1554 foreach ($ptags as $ptag) {
1555 $users = $ptag->getUserSubscribers();
1556 foreach ($users as $id) {
1557 $ni[$id] = NOTICE_INBOX_SOURCE_PROFILE_TAG;
1564 * Record this notice to the given group inboxes for delivery.
1565 * Overrides the regular parsing of !group markup.
1567 * @param string $group_ids
1568 * @fixme might prefer URIs as identifiers, as for replies?
1569 * best with generalizations on user_group to support
1570 * remote groups better.
1572 function saveKnownGroups(array $group_ids)
1575 foreach (array_unique($group_ids) as $id) {
1576 $group = User_group::getKV('id', $id);
1577 if ($group instanceof User_group) {
1578 common_log(LOG_DEBUG, "Local delivery to group id $id, $group->nickname");
1579 $result = $this->addToGroupInbox($group);
1581 common_log_db_error($gi, 'INSERT', __FILE__);
1584 if (common_config('group', 'addtag')) {
1585 // we automatically add a tag for every group name, too
1587 $tag = Notice_tag::pkeyGet(array('tag' => common_canonical_tag($group->nickname),
1588 'notice_id' => $this->id));
1590 if (is_null($tag)) {
1591 $this->saveTag($group->nickname);
1595 $groups[] = clone($group);
1597 common_log(LOG_ERR, "Local delivery to group id $id skipped, doesn't exist");
1604 function addToGroupInbox(User_group $group)
1606 $gi = Group_inbox::pkeyGet(array('group_id' => $group->id,
1607 'notice_id' => $this->id));
1609 if (!$gi instanceof Group_inbox) {
1611 $gi = new Group_inbox();
1613 $gi->group_id = $group->id;
1614 $gi->notice_id = $this->id;
1615 $gi->created = $this->created;
1617 $result = $gi->insert();
1620 common_log_db_error($gi, 'INSERT', __FILE__);
1621 // TRANS: Server exception thrown when an update for a group inbox fails.
1622 throw new ServerException(_('Problem saving group inbox.'));
1625 self::blow('user_group:notice_ids:%d', $gi->group_id);
1631 function saveAttentions(array $uris)
1633 foreach ($uris as $uri=>$type) {
1635 $target = Profile::fromUri($uri);
1636 } catch (UnknownUriException $e) {
1637 common_log(LOG_WARNING, "Unable to determine profile for URI '$uri'");
1642 $this->saveAttention($target);
1643 } catch (AlreadyFulfilledException $e) {
1644 common_debug('Attention already exists: '.var_export($e->getMessage(),true));
1645 } catch (Exception $e) {
1646 common_log(LOG_ERR, "Could not save notice id=={$this->getID()} attention for profile id=={$target->getID()}: {$e->getMessage()}");
1652 * Saves an attention for a profile (user or group) which means
1653 * it shows up in their home feed and such.
1655 function saveAttention(Profile $target, $reason=null)
1657 if ($target->isGroup()) {
1658 // FIXME: Make sure we check (for both local and remote) users are in the groups they send to!
1660 // legacy notification method, will still be in use for quite a while I think
1661 $this->addToGroupInbox($target->getGroup());
1663 if ($target->hasBlocked($this->getProfile())) {
1664 common_log(LOG_INFO, "Not saving reply to profile {$target->id} ($uri) from sender {$sender->id} because of a block.");
1669 if ($target->isLocal()) {
1670 // legacy notification method, will still be in use for quite a while I think
1671 $this->saveReply($target->getID());
1674 $att = Attention::saveNew($this, $target, $reason);
1679 * Save reply records indicating that this notice needs to be
1680 * delivered to the local users with the given URIs.
1682 * Since this is expected to be used when saving foreign-sourced
1683 * messages, we won't deliver to any remote targets as that's the
1684 * source service's responsibility.
1686 * Mail notifications etc will be handled later.
1688 * @param array $uris Array of unique identifier URIs for recipients
1690 function saveKnownReplies(array $uris)
1696 $sender = $this->getProfile();
1698 foreach (array_unique($uris) as $uri) {
1700 $profile = Profile::fromUri($uri);
1701 } catch (UnknownUriException $e) {
1702 common_log(LOG_WARNING, "Unable to determine profile for URI '$uri'");
1706 if ($profile->hasBlocked($sender)) {
1707 common_log(LOG_INFO, "Not saving reply to profile {$profile->id} ($uri) from sender {$sender->id} because of a block.");
1711 $this->saveReply($profile->getID());
1712 self::blow('reply:stream:%d', $profile->getID());
1717 * Pull @-replies from this message's content in StatusNet markup format
1718 * and save reply records indicating that this message needs to be
1719 * delivered to those users.
1721 * Mail notifications to local profiles will be sent later.
1723 * @return array of integer profile IDs
1726 function saveReplies()
1728 $sender = $this->getProfile();
1732 // If it's a reply, save for the replied-to author
1734 $parent = $this->getParent();
1735 $parentauthor = $parent->getProfile();
1736 $this->saveReply($parentauthor->getID());
1737 $replied[$parentauthor->getID()] = 1;
1738 self::blow('reply:stream:%d', $parentauthor->getID());
1739 } catch (NoParentNoticeException $e) {
1740 // Not a reply, since it has no parent!
1742 } catch (NoResultException $e) {
1743 // Parent notice was probably deleted
1747 // @todo ideally this parser information would only
1748 // be calculated once.
1750 $mentions = common_find_mentions($this->content, $sender, $parent);
1752 foreach ($mentions as $mention) {
1754 foreach ($mention['mentioned'] as $mentioned) {
1756 // skip if they're already covered
1757 if (array_key_exists($mentioned->id, $replied)) {
1761 // Don't save replies from blocked profile to local user
1762 if ($mentioned->hasBlocked($sender)) {
1766 $this->saveReply($mentioned->id);
1767 $replied[$mentioned->id] = 1;
1768 self::blow('reply:stream:%d', $mentioned->id);
1772 $recipientIds = array_keys($replied);
1774 return $recipientIds;
1777 function saveReply($profileId)
1779 $reply = new Reply();
1781 $reply->notice_id = $this->id;
1782 $reply->profile_id = $profileId;
1783 $reply->modified = $this->created;
1790 protected $_attentionids = array();
1793 * Pull the complete list of known activity context attentions for this notice.
1795 * @return array of integer profile ids (also group profiles)
1797 function getAttentionProfileIDs()
1799 if (!isset($this->_attentionids[$this->getID()])) {
1800 $atts = Attention::multiGet('notice_id', array($this->getID()));
1801 // (array)null means empty array
1802 $this->_attentionids[$this->getID()] = (array)$atts->fetchAll('profile_id');
1804 return $this->_attentionids[$this->getID()];
1807 protected $_replies = array();
1810 * Pull the complete list of @-mentioned profile IDs for this notice.
1812 * @return array of integer profile ids
1814 function getReplies()
1816 if (!isset($this->_replies[$this->getID()])) {
1817 $mentions = Reply::multiGet('notice_id', array($this->getID()));
1818 $this->_replies[$this->getID()] = $mentions->fetchAll('profile_id');
1820 return $this->_replies[$this->getID()];
1823 function _setReplies($replies)
1825 $this->_replies[$this->getID()] = $replies;
1829 * Pull the complete list of @-reply targets for this notice.
1831 * @return array of Profiles
1833 function getAttentionProfiles()
1835 $ids = array_unique(array_merge($this->getReplies(), $this->getGroupProfileIDs(), $this->getAttentionProfileIDs()));
1837 $profiles = Profile::multiGet('id', (array)$ids);
1839 return $profiles->fetchAll();
1843 * Send e-mail notifications to local @-reply targets.
1845 * Replies must already have been saved; this is expected to be run
1846 * from the distrib queue handler.
1848 function sendReplyNotifications()
1850 // Don't send reply notifications for repeats
1851 if ($this->isRepeat()) {
1855 $recipientIds = $this->getReplies();
1856 if (Event::handle('StartNotifyMentioned', array($this, &$recipientIds))) {
1857 require_once INSTALLDIR.'/lib/mail.php';
1859 foreach ($recipientIds as $recipientId) {
1861 $user = User::getByID($recipientId);
1862 mail_notify_attn($user->getProfile(), $this);
1863 } catch (NoResultException $e) {
1867 Event::handle('EndNotifyMentioned', array($this, $recipientIds));
1872 * Pull list of Profile IDs of groups this notice addresses.
1874 * @return array of Group _profile_ IDs
1877 function getGroupProfileIDs()
1881 foreach ($this->getGroups() as $group) {
1882 $ids[] = $group->profile_id;
1889 * Pull list of groups this notice needs to be delivered to,
1890 * as previously recorded by saveKnownGroups().
1892 * @return array of Group objects
1895 protected $_groups = array();
1897 function getGroups()
1899 // Don't save groups for repeats
1901 if (!empty($this->repeat_of)) {
1905 if (isset($this->_groups[$this->id])) {
1906 return $this->_groups[$this->id];
1909 $gis = Group_inbox::listGet('notice_id', array($this->id));
1913 foreach ($gis[$this->id] as $gi) {
1914 $ids[] = $gi->group_id;
1917 $groups = User_group::multiGet('id', $ids);
1918 $this->_groups[$this->id] = $groups->fetchAll();
1919 return $this->_groups[$this->id];
1922 function _setGroups($groups)
1924 $this->_groups[$this->id] = $groups;
1928 * Convert a notice into an activity for export.
1930 * @param Profile $scoped The currently logged in/scoped profile
1932 * @return Activity activity object representing this Notice.
1935 function asActivity(Profile $scoped=null)
1937 $act = self::cacheGet(Cache::codeKey('notice:as-activity:'.$this->id));
1939 if ($act instanceof Activity) {
1942 $act = new Activity();
1944 if (Event::handle('StartNoticeAsActivity', array($this, $act, $scoped))) {
1946 $act->id = $this->uri;
1947 $act->time = strtotime($this->created);
1949 $act->link = $this->getUrl();
1950 } catch (InvalidUrlException $e) {
1951 // The notice is probably a share or similar, which don't
1952 // have a representational URL of their own.
1954 $act->content = common_xml_safe_str($this->getRendered());
1956 $profile = $this->getProfile();
1958 $act->actor = $profile->asActivityObject();
1959 $act->actor->extra[] = $profile->profileInfo($scoped);
1961 $act->verb = $this->verb;
1963 if (!$this->repeat_of) {
1964 $act->objects[] = $this->asActivityObject();
1967 // XXX: should this be handled by default processing for object entry?
1971 $tags = $this->getTags();
1973 foreach ($tags as $tag) {
1974 $cat = new AtomCategory();
1977 $act->categories[] = $cat;
1981 // XXX: use Atom Media and/or File activity objects instead
1983 $attachments = $this->attachments();
1985 foreach ($attachments as $attachment) {
1986 // Include local attachments in Activity
1987 if (!empty($attachment->filename)) {
1988 $act->enclosures[] = $attachment->getEnclosure();
1992 $ctx = new ActivityContext();
1995 $reply = $this->getParent();
1996 $ctx->replyToID = $reply->getUri();
1997 $ctx->replyToUrl = $reply->getUrl(true); // true for fallback to local URL, less messy
1998 } catch (NoParentNoticeException $e) {
1999 // This is not a reply to something
2000 } catch (NoResultException $e) {
2001 // Parent notice was probably deleted
2005 $ctx->location = Notice_location::locFromStored($this);
2006 } catch (ServerException $e) {
2007 $ctx->location = null;
2012 if (!empty($this->conversation)) {
2013 $conv = Conversation::getKV('id', $this->conversation);
2014 if ($conv instanceof Conversation) {
2015 $ctx->conversation = $conv->uri;
2019 // This covers the legacy getReplies and getGroups too which get their data
2020 // from entries stored via Notice::saveNew (which we want to move away from)...
2021 foreach ($this->getAttentionProfiles() as $target) {
2022 // User and group profiles which get the attention of this notice
2023 $ctx->attention[$target->getUri()] = $target->getObjectType();
2026 switch ($this->scope) {
2027 case Notice::PUBLIC_SCOPE:
2028 $ctx->attention[ActivityContext::ATTN_PUBLIC] = ActivityObject::COLLECTION;
2030 case Notice::FOLLOWER_SCOPE:
2031 $surl = common_local_url("subscribers", array('nickname' => $profile->nickname));
2032 $ctx->attention[$surl] = ActivityObject::COLLECTION;
2036 $act->context = $ctx;
2038 $source = $this->getSource();
2040 if ($source instanceof Notice_source) {
2041 $act->generator = ActivityObject::fromNoticeSource($source);
2046 $atom_feed = $profile->getAtomFeed();
2048 if (!empty($atom_feed)) {
2050 $act->source = new ActivitySource();
2052 // XXX: we should store the actual feed ID
2054 $act->source->id = $atom_feed;
2056 // XXX: we should store the actual feed title
2058 $act->source->title = $profile->getBestName();
2060 $act->source->links['alternate'] = $profile->profileurl;
2061 $act->source->links['self'] = $atom_feed;
2063 $act->source->icon = $profile->avatarUrl(AVATAR_PROFILE_SIZE);
2065 $notice = $profile->getCurrentNotice();
2067 if ($notice instanceof Notice) {
2068 $act->source->updated = self::utcDate($notice->created);
2071 $user = User::getKV('id', $profile->id);
2073 if ($user instanceof User) {
2074 $act->source->links['license'] = common_config('license', 'url');
2078 if ($this->isLocal()) {
2079 $act->selfLink = common_local_url('ApiStatusesShow', array('id' => $this->id,
2080 'format' => 'atom'));
2081 $act->editLink = $act->selfLink;
2084 Event::handle('EndNoticeAsActivity', array($this, $act, $scoped));
2087 self::cacheSet(Cache::codeKey('notice:as-activity:'.$this->id), $act);
2092 // This has gotten way too long. Needs to be sliced up into functional bits
2093 // or ideally exported to a utility class.
2095 function asAtomEntry($namespace=false,
2098 Profile $scoped=null)
2100 $act = $this->asActivity($scoped);
2101 $act->extra[] = $this->noticeInfo($scoped);
2102 return $act->asString($namespace, $author, $source);
2106 * Extra notice info for atom entries
2108 * Clients use some extra notice info in the atom stream.
2109 * This gives it to them.
2111 * @param Profile $scoped The currently logged in/scoped profile
2113 * @return array representation of <statusnet:notice_info> element
2116 function noticeInfo(Profile $scoped=null)
2118 // local notice ID (useful to clients for ordering)
2120 $noticeInfoAttr = array('local_id' => $this->id);
2124 $ns = $this->getSource();
2126 if ($ns instanceof Notice_source) {
2127 $noticeInfoAttr['source'] = $ns->code;
2128 if (!empty($ns->url)) {
2129 $noticeInfoAttr['source_link'] = $ns->url;
2130 if (!empty($ns->name)) {
2131 $noticeInfoAttr['source'] = '<a href="'
2132 . htmlspecialchars($ns->url)
2133 . '" rel="nofollow">'
2134 . htmlspecialchars($ns->name)
2140 // favorite and repeated
2142 if ($scoped instanceof Profile) {
2143 $noticeInfoAttr['repeated'] = ($scoped->hasRepeated($this)) ? "true" : "false";
2146 if (!empty($this->repeat_of)) {
2147 $noticeInfoAttr['repeat_of'] = $this->repeat_of;
2150 Event::handle('StatusNetApiNoticeInfo', array($this, &$noticeInfoAttr, $scoped));
2152 return array('statusnet:notice_info', $noticeInfoAttr, null);
2156 * Returns an XML string fragment with a reference to a notice as an
2157 * Activity Streams noun object with the given element type.
2159 * Assumes that 'activity' namespace has been previously defined.
2161 * @param string $element one of 'subject', 'object', 'target'
2165 function asActivityNoun($element)
2167 $noun = $this->asActivityObject();
2168 return $noun->asString('activity:' . $element);
2171 public function asActivityObject()
2173 $object = new ActivityObject();
2175 if (Event::handle('StartActivityObjectFromNotice', array($this, &$object))) {
2176 $object->type = $this->object_type ?: ActivityObject::NOTE;
2177 $object->id = $this->getUri();
2178 //FIXME: = $object->title ?: sprintf(... because we might get a title from StartActivityObjectFromNotice
2179 $object->title = sprintf('New %1$s by %2$s', ActivityObject::canonicalType($object->type), $this->getProfile()->getNickname());
2180 $object->content = $this->getRendered();
2181 $object->link = $this->getUrl();
2183 $object->extra[] = array('status_net', array('notice_id' => $this->id));
2185 Event::handle('EndActivityObjectFromNotice', array($this, &$object));
2188 if (!$object instanceof ActivityObject) {
2189 common_log(LOG_ERR, 'Notice asActivityObject created something else for uri=='._ve($this->getUri()).': '._ve($object));
2190 throw new ServerException('Notice asActivityObject created something else.');
2197 * Determine which notice, if any, a new notice is in reply to.
2199 * For conversation tracking, we try to see where this notice fits
2200 * in the tree. Beware that this may very well give false positives
2201 * and add replies to wrong threads (if there have been newer posts
2202 * by the same user as we're replying to).
2204 * @param Profile $sender Author profile
2205 * @param string $content Final notice content
2207 * @return integer ID of replied-to notice, or null for not a reply.
2210 static function getInlineReplyTo(Profile $sender, $content)
2212 // Is there an initial @ or T?
2213 if (preg_match('/^T ([A-Z0-9]{1,64}) /', $content, $match)
2214 || preg_match('/^@([a-z0-9]{1,64})\s+/', $content, $match)) {
2215 $nickname = common_canonical_nickname($match[1]);
2220 // Figure out who that is.
2221 $recipient = common_relative_profile($sender, $nickname, common_sql_now());
2223 if ($recipient instanceof Profile) {
2224 // Get their last notice
2225 $last = $recipient->getCurrentNotice();
2226 if ($last instanceof Notice) {
2229 // Maybe in the future we want to handle something else below
2230 // so don't return getCurrentNotice() immediately.
2236 static function maxContent()
2238 $contentlimit = common_config('notice', 'contentlimit');
2239 // null => use global limit (distinct from 0!)
2240 if (is_null($contentlimit)) {
2241 $contentlimit = common_config('site', 'textlimit');
2243 return $contentlimit;
2246 static function contentTooLong($content)
2248 $contentlimit = self::maxContent();
2249 return ($contentlimit > 0 && !empty($content) && (mb_strlen($content) > $contentlimit));
2253 * Convenience function for posting a repeat of an existing message.
2255 * @param Profile $repeater Profile which is doing the repeat
2256 * @param string $source: posting source key, eg 'web', 'api', etc
2259 * @throws Exception on failure or permission problems
2261 function repeat(Profile $repeater, $source)
2263 $author = $this->getProfile();
2265 // TRANS: Message used to repeat a notice. RT is the abbreviation of 'retweet'.
2266 // TRANS: %1$s is the repeated user's name, %2$s is the repeated notice.
2267 $content = sprintf(_('RT @%1$s %2$s'),
2268 $author->getNickname(),
2271 $maxlen = self::maxContent();
2272 if ($maxlen > 0 && mb_strlen($content) > $maxlen) {
2273 // Web interface and current Twitter API clients will
2274 // pull the original notice's text, but some older
2275 // clients and RSS/Atom feeds will see this trimmed text.
2277 // Unfortunately this is likely to lose tags or URLs
2278 // at the end of long notices.
2279 $content = mb_substr($content, 0, $maxlen - 4) . ' ...';
2283 // Scope is same as this one's
2284 return self::saveNew($repeater->id,
2287 array('repeat_of' => $this->id,
2288 'scope' => $this->scope));
2291 // These are supposed to be in chron order!
2293 function repeatStream($limit=100)
2295 $cache = Cache::instance();
2297 if (empty($cache)) {
2298 $ids = $this->_repeatStreamDirect($limit);
2300 $idstr = $cache->get(Cache::key('notice:repeats:'.$this->id));
2301 if ($idstr !== false) {
2302 if (empty($idstr)) {
2305 $ids = explode(',', $idstr);
2308 $ids = $this->_repeatStreamDirect(100);
2309 $cache->set(Cache::key('notice:repeats:'.$this->id), implode(',', $ids));
2312 // We do a max of 100, so slice down to limit
2313 $ids = array_slice($ids, 0, $limit);
2317 return NoticeStream::getStreamByIds($ids);
2320 function _repeatStreamDirect($limit)
2322 $notice = new Notice();
2324 $notice->selectAdd(); // clears it
2325 $notice->selectAdd('id');
2327 $notice->repeat_of = $this->id;
2329 $notice->orderBy('created, id'); // NB: asc!
2331 if (!is_null($limit)) {
2332 $notice->limit(0, $limit);
2335 return $notice->fetchAll('id');
2338 static function locationOptions($lat, $lon, $location_id, $location_ns, $profile = null)
2342 if (!empty($location_id) && !empty($location_ns)) {
2343 $options['location_id'] = $location_id;
2344 $options['location_ns'] = $location_ns;
2346 $location = Location::fromId($location_id, $location_ns);
2348 if ($location instanceof Location) {
2349 $options['lat'] = $location->lat;
2350 $options['lon'] = $location->lon;
2353 } else if (!empty($lat) && !empty($lon)) {
2354 $options['lat'] = $lat;
2355 $options['lon'] = $lon;
2357 $location = Location::fromLatLon($lat, $lon);
2359 if ($location instanceof Location) {
2360 $options['location_id'] = $location->location_id;
2361 $options['location_ns'] = $location->location_ns;
2363 } else if (!empty($profile)) {
2364 if (isset($profile->lat) && isset($profile->lon)) {
2365 $options['lat'] = $profile->lat;
2366 $options['lon'] = $profile->lon;
2369 if (isset($profile->location_id) && isset($profile->location_ns)) {
2370 $options['location_id'] = $profile->location_id;
2371 $options['location_ns'] = $profile->location_ns;
2378 function clearAttentions()
2380 $att = new Attention();
2381 $att->notice_id = $this->getID();
2384 while ($att->fetch()) {
2385 // Can't do delete() on the object directly since it won't remove all of it
2386 $other = clone($att);
2392 function clearReplies()
2394 $replyNotice = new Notice();
2395 $replyNotice->reply_to = $this->id;
2397 //Null any notices that are replies to this notice
2399 if ($replyNotice->find()) {
2400 while ($replyNotice->fetch()) {
2401 $orig = clone($replyNotice);
2402 $replyNotice->reply_to = null;
2403 $replyNotice->update($orig);
2409 $reply = new Reply();
2410 $reply->notice_id = $this->id;
2412 if ($reply->find()) {
2413 while($reply->fetch()) {
2414 self::blow('reply:stream:%d', $reply->profile_id);
2422 function clearLocation()
2424 $loc = new Notice_location();
2425 $loc->notice_id = $this->id;
2432 function clearFiles()
2434 $f2p = new File_to_post();
2436 $f2p->post_id = $this->id;
2439 while ($f2p->fetch()) {
2443 // FIXME: decide whether to delete File objects
2444 // ...and related (actual) files
2447 function clearRepeats()
2449 $repeatNotice = new Notice();
2450 $repeatNotice->repeat_of = $this->id;
2452 //Null any notices that are repeats of this notice
2454 if ($repeatNotice->find()) {
2455 while ($repeatNotice->fetch()) {
2456 $orig = clone($repeatNotice);
2457 $repeatNotice->repeat_of = null;
2458 $repeatNotice->update($orig);
2463 function clearTags()
2465 $tag = new Notice_tag();
2466 $tag->notice_id = $this->id;
2469 while ($tag->fetch()) {
2470 self::blow('profile:notice_ids_tagged:%d:%s', $this->profile_id, Cache::keyize($tag->tag));
2471 self::blow('profile:notice_ids_tagged:%d:%s;last', $this->profile_id, Cache::keyize($tag->tag));
2472 self::blow('notice_tag:notice_ids:%s', Cache::keyize($tag->tag));
2473 self::blow('notice_tag:notice_ids:%s;last', Cache::keyize($tag->tag));
2481 function clearGroupInboxes()
2483 $gi = new Group_inbox();
2485 $gi->notice_id = $this->id;
2488 while ($gi->fetch()) {
2489 self::blow('user_group:notice_ids:%d', $gi->group_id);
2497 function distribute()
2499 // We always insert for the author so they don't
2501 Event::handle('StartNoticeDistribute', array($this));
2503 // If there's a failure, we want to _force_
2504 // distribution at this point.
2506 $json = json_encode((object)array('id' => $this->getID(),
2509 $qm = QueueManager::get();
2510 $qm->enqueue($json, 'distrib');
2511 } catch (Exception $e) {
2512 // If the exception isn't transient, this
2513 // may throw more exceptions as DQH does
2514 // its own enqueueing. So, we ignore them!
2516 $handler = new DistribQueueHandler();
2517 $handler->handle($this);
2518 } catch (Exception $e) {
2519 common_log(LOG_ERR, "emergency redistribution resulted in " . $e->getMessage());
2521 // Re-throw so somebody smarter can handle it.
2528 $result = parent::insert();
2530 if ($result === false) {
2531 common_log_db_error($this, 'INSERT', __FILE__);
2532 // TRANS: Server exception thrown when a stored object entry cannot be saved.
2533 throw new ServerException('Could not save Notice');
2536 // Profile::hasRepeated() abuses pkeyGet(), so we
2537 // have to clear manually
2538 if (!empty($this->repeat_of)) {
2539 $c = self::memcache();
2541 $ck = self::multicacheKey('Notice',
2542 array('profile_id' => $this->profile_id,
2543 'repeat_of' => $this->repeat_of));
2548 // Update possibly ID-dependent columns: URI, conversation
2549 // (now that INSERT has added the notice's local id)
2550 $orig = clone($this);
2553 // We can only get here if it's a local notice, since remote notices
2554 // should've bailed out earlier due to lacking a URI.
2555 if (empty($this->uri)) {
2556 $this->uri = sprintf('%s%s=%d:%s=%s',
2558 'noticeId', $this->id,
2559 'objectType', $this->getObjectType(true));
2563 if ($changed && $this->update($orig) === false) {
2564 common_log_db_error($notice, 'UPDATE', __FILE__);
2565 // TRANS: Server exception thrown when a notice cannot be updated.
2566 throw new ServerException(_('Problem saving notice.'));
2569 $this->blowOnInsert();
2575 * Get the source of the notice
2577 * @return Notice_source $ns A notice source object. 'code' is the only attribute
2578 * guaranteed to be populated.
2580 function getSource()
2582 if (empty($this->source)) {
2586 $ns = new Notice_source();
2587 switch ($this->source) {
2594 $ns->code = $this->source;
2597 $ns = Notice_source::getKV($this->source);
2599 $ns = new Notice_source();
2600 $ns->code = $this->source;
2601 $app = Oauth_application::getKV('name', $this->source);
2603 $ns->name = $app->name;
2604 $ns->url = $app->source_url;
2614 * Determine whether the notice was locally created
2616 * @return boolean locality
2619 public function isLocal()
2621 $is_local = intval($this->is_local);
2622 return ($is_local === self::LOCAL_PUBLIC || $is_local === self::LOCAL_NONPUBLIC);
2625 public function getScope()
2627 return intval($this->scope);
2630 public function isRepeat()
2632 return !empty($this->repeat_of);
2636 * Get the list of hash tags saved with this notice.
2638 * @return array of strings
2640 public function getTags()
2644 $keypart = sprintf('notice:tags:%d', $this->id);
2646 $tagstr = self::cacheGet($keypart);
2648 if ($tagstr !== false) {
2649 $tags = explode(',', $tagstr);
2651 $tag = new Notice_tag();
2652 $tag->notice_id = $this->id;
2654 while ($tag->fetch()) {
2655 $tags[] = $tag->tag;
2658 self::cacheSet($keypart, implode(',', $tags));
2664 static private function utcDate($dt)
2666 $dateStr = date('d F Y H:i:s', strtotime($dt));
2667 $d = new DateTime($dateStr, new DateTimeZone('UTC'));
2668 return $d->format(DATE_W3C);
2672 * Look up the creation timestamp for a given notice ID, even
2673 * if it's been deleted.
2676 * @return mixed string recorded creation timestamp, or false if can't be found
2678 public static function getAsTimestamp($id)
2681 throw new EmptyIdException('Notice');
2685 if (Event::handle('GetNoticeSqlTimestamp', array($id, &$timestamp))) {
2686 // getByID throws exception if $id isn't found
2687 $notice = Notice::getByID($id);
2688 $timestamp = $notice->created;
2691 if (empty($timestamp)) {
2692 throw new ServerException('No timestamp found for Notice with id=='._ve($id));
2698 * Build an SQL 'where' fragment for timestamp-based sorting from a since_id
2699 * parameter, matching notices posted after the given one (exclusive).
2701 * If the referenced notice can't be found, will return false.
2704 * @param string $idField
2705 * @param string $createdField
2706 * @return mixed string or false if no match
2708 public static function whereSinceId($id, $idField='id', $createdField='created')
2711 $since = Notice::getAsTimestamp($id);
2712 } catch (Exception $e) {
2715 return sprintf("($createdField = '%s' and $idField > %d) or ($createdField > '%s')", $since, $id, $since);
2719 * Build an SQL 'where' fragment for timestamp-based sorting from a since_id
2720 * parameter, matching notices posted after the given one (exclusive), and
2721 * if necessary add it to the data object's query.
2723 * @param DB_DataObject $obj
2725 * @param string $idField
2726 * @param string $createdField
2727 * @return mixed string or false if no match
2729 public static function addWhereSinceId(DB_DataObject $obj, $id, $idField='id', $createdField='created')
2731 $since = self::whereSinceId($id, $idField, $createdField);
2733 $obj->whereAdd($since);
2738 * Build an SQL 'where' fragment for timestamp-based sorting from a max_id
2739 * parameter, matching notices posted before the given one (inclusive).
2741 * If the referenced notice can't be found, will return false.
2744 * @param string $idField
2745 * @param string $createdField
2746 * @return mixed string or false if no match
2748 public static function whereMaxId($id, $idField='id', $createdField='created')
2751 $max = Notice::getAsTimestamp($id);
2752 } catch (Exception $e) {
2755 return sprintf("($createdField < '%s') or ($createdField = '%s' and $idField <= %d)", $max, $max, $id);
2759 * Build an SQL 'where' fragment for timestamp-based sorting from a max_id
2760 * parameter, matching notices posted before the given one (inclusive), and
2761 * if necessary add it to the data object's query.
2763 * @param DB_DataObject $obj
2765 * @param string $idField
2766 * @param string $createdField
2767 * @return mixed string or false if no match
2769 public static function addWhereMaxId(DB_DataObject $obj, $id, $idField='id', $createdField='created')
2771 $max = self::whereMaxId($id, $idField, $createdField);
2773 $obj->whereAdd($max);
2777 public function isPublic()
2779 $is_local = intval($this->is_local);
2780 return !($is_local === Notice::LOCAL_NONPUBLIC || $is_local === Notice::GATEWAY);
2784 * Check that the given profile is allowed to read, respond to, or otherwise
2785 * act on this notice.
2787 * The $scope member is a bitmask of scopes, representing a logical AND of the
2788 * scope requirement. So, 0x03 (Notice::ADDRESSEE_SCOPE | Notice::SITE_SCOPE) means
2789 * "only visible to people who are mentioned in the notice AND are users on this site."
2790 * Users on the site who are not mentioned in the notice will not be able to see the
2793 * @param Profile $profile The profile to check; pass null to check for public/unauthenticated users.
2795 * @return boolean whether the profile is in the notice's scope
2797 function inScope($profile)
2799 if (is_null($profile)) {
2800 $keypart = sprintf('notice:in-scope-for:%d:null', $this->id);
2802 $keypart = sprintf('notice:in-scope-for:%d:%d', $this->id, $profile->id);
2805 $result = self::cacheGet($keypart);
2807 if ($result === false) {
2809 if (Event::handle('StartNoticeInScope', array($this, $profile, &$bResult))) {
2810 $bResult = $this->_inScope($profile);
2811 Event::handle('EndNoticeInScope', array($this, $profile, &$bResult));
2813 $result = ($bResult) ? 1 : 0;
2814 self::cacheSet($keypart, $result, 0, 300);
2817 return ($result == 1) ? true : false;
2820 protected function _inScope($profile)
2822 $scope = is_null($this->scope) ? self::defaultScope() : $this->getScope();
2824 if ($scope === 0 && !$this->getProfile()->isPrivateStream()) { // Not scoping, so it is public.
2825 return !$this->isHiddenSpam($profile);
2828 // If there's scope, anon cannot be in scope
2829 if (empty($profile)) {
2833 // Author is always in scope
2834 if ($this->profile_id == $profile->id) {
2838 // Only for users on this site
2839 if (($scope & Notice::SITE_SCOPE) && !$profile->isLocal()) {
2843 // Only for users mentioned in the notice
2844 if ($scope & Notice::ADDRESSEE_SCOPE) {
2846 $reply = Reply::pkeyGet(array('notice_id' => $this->id,
2847 'profile_id' => $profile->id));
2849 if (!$reply instanceof Reply) {
2854 // Only for members of the given group
2855 if ($scope & Notice::GROUP_SCOPE) {
2857 // XXX: just query for the single membership
2859 $groups = $this->getGroups();
2863 foreach ($groups as $group) {
2864 if ($profile->isMember($group)) {
2875 if ($scope & Notice::FOLLOWER_SCOPE || $this->getProfile()->isPrivateStream()) {
2877 if (!Subscription::exists($profile, $this->getProfile())) {
2882 return !$this->isHiddenSpam($profile);
2885 function isHiddenSpam($profile) {
2887 // Hide posts by silenced users from everyone but moderators.
2889 if (common_config('notice', 'hidespam')) {
2892 $author = $this->getProfile();
2893 } catch(Exception $e) {
2894 // If we can't get an author, keep it hidden.
2895 // XXX: technically not spam, but, whatever.
2899 if ($author->hasRole(Profile_role::SILENCED)) {
2900 if (!$profile instanceof Profile || (($profile->id !== $author->id) && (!$profile->hasRight(Right::REVIEWSPAM)))) {
2909 public function hasParent()
2913 } catch (NoParentNoticeException $e) {
2919 public function getParent()
2921 $reply_to_id = null;
2923 if (empty($this->reply_to)) {
2924 throw new NoParentNoticeException($this);
2927 // The reply_to ID in the table Notice could exist with a number
2928 // however, the replied to notice might not exist in the database.
2929 // Thus we need to catch the exception and throw the NoParentNoticeException else
2930 // the timeline will not display correctly.
2932 $reply_to_id = self::getByID($this->reply_to);
2933 } catch(Exception $e){
2934 throw new NoParentNoticeException($this);
2937 return $reply_to_id;
2941 * Magic function called at serialize() time.
2943 * We use this to drop a couple process-specific references
2944 * from DB_DataObject which can cause trouble in future
2947 * @return array of variable names to include in serialization.
2952 $vars = parent::__sleep();
2953 $skip = array('_profile', '_groups', '_attachments', '_faves', '_replies', '_repeats');
2954 return array_diff($vars, $skip);
2957 static function defaultScope()
2959 $scope = common_config('notice', 'defaultscope');
2960 if (is_null($scope)) {
2961 if (common_config('site', 'private')) {
2970 static function fillProfiles($notices)
2972 $map = self::getProfiles($notices);
2973 foreach ($notices as $entry=>$notice) {
2975 if (array_key_exists($notice->profile_id, $map)) {
2976 $notice->_setProfile($map[$notice->profile_id]);
2978 } catch (NoProfileException $e) {
2979 common_log(LOG_WARNING, "Failed to fill profile in Notice with non-existing entry for profile_id: {$e->profile_id}");
2980 unset($notices[$entry]);
2984 return array_values($map);
2987 static function getProfiles(&$notices)
2990 foreach ($notices as $notice) {
2991 $ids[] = $notice->profile_id;
2993 $ids = array_unique($ids);
2994 return Profile::pivotGet('id', $ids);
2997 static function fillGroups(&$notices)
2999 $ids = self::_idsOf($notices);
3000 $gis = Group_inbox::listGet('notice_id', $ids);
3003 foreach ($gis as $id => $gi) {
3006 $gids[] = $g->group_id;
3010 $gids = array_unique($gids);
3011 $group = User_group::pivotGet('id', $gids);
3012 foreach ($notices as $notice)
3015 $gi = $gis[$notice->id];
3016 foreach ($gi as $g) {
3017 $grps[] = $group[$g->group_id];
3019 $notice->_setGroups($grps);
3023 static function _idsOf(array &$notices)
3026 foreach ($notices as $notice) {
3027 $ids[$notice->id] = true;
3029 return array_keys($ids);
3032 static function fillAttachments(&$notices)
3034 $ids = self::_idsOf($notices);
3035 $f2pMap = File_to_post::listGet('post_id', $ids);
3037 foreach ($f2pMap as $noticeId => $f2ps) {
3038 foreach ($f2ps as $f2p) {
3039 $fileIds[] = $f2p->file_id;
3043 $fileIds = array_unique($fileIds);
3044 $fileMap = File::pivotGet('id', $fileIds);
3045 foreach ($notices as $notice)
3048 $f2ps = $f2pMap[$notice->id];
3049 foreach ($f2ps as $f2p) {
3050 if (!isset($fileMap[$f2p->file_id])) {
3051 // We have probably deleted value from fileMap since
3052 // it as a NULL entry (see the following elseif).
3054 } elseif (is_null($fileMap[$f2p->file_id])) {
3055 // If the file id lookup returned a NULL value, it doesn't
3056 // exist in our file table! So this is a remnant file_to_post
3057 // entry that is no longer valid and should be removed.
3058 common_debug('ATTACHMENT deleting f2p for post_id='.$f2p->post_id.' file_id='.$f2p->file_id);
3060 unset($fileMap[$f2p->file_id]);
3063 $files[] = $fileMap[$f2p->file_id];
3065 $notice->_setAttachments($files);
3069 static function fillReplies(&$notices)
3071 $ids = self::_idsOf($notices);
3072 $replyMap = Reply::listGet('notice_id', $ids);
3073 foreach ($notices as $notice) {
3074 $replies = $replyMap[$notice->id];
3076 foreach ($replies as $reply) {
3077 $ids[] = $reply->profile_id;
3079 $notice->_setReplies($ids);
3083 static public function beforeSchemaUpdate()
3085 $table = strtolower(get_called_class());
3086 $schema = Schema::get();
3087 $schemadef = $schema->getTableDef($table);
3089 // 2015-09-04 We move Notice location data to Notice_location
3090 // First we see if we have to do this at all
3091 if (!isset($schemadef['fields']['lat'])
3092 && !isset($schemadef['fields']['lon'])
3093 && !isset($schemadef['fields']['location_id'])
3094 && !isset($schemadef['fields']['location_ns'])) {
3095 // We have already removed the location fields, so no need to migrate.
3098 // Then we make sure the Notice_location table is created!
3099 $schema->ensureTable('notice_location', Notice_location::schemaDef());
3101 // Then we continue on our road to migration!
3102 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)";
3104 $notice = new Notice();
3105 $notice->query(sprintf('SELECT id, lat, lon, location_id, location_ns FROM %1$s ' .
3106 'WHERE lat IS NOT NULL ' .
3107 'OR lon IS NOT NULL ' .
3108 'OR location_id IS NOT NULL ' .
3109 'OR location_ns IS NOT NULL',
3110 $schema->quoteIdentifier($table)));
3111 print "\nFound {$notice->N} notices with location data, inserting";
3112 while ($notice->fetch()) {
3113 $notloc = Notice_location::getKV('notice_id', $notice->id);
3114 if ($notloc instanceof Notice_location) {
3118 $notloc = new Notice_location();
3119 $notloc->notice_id = $notice->id;
3120 $notloc->lat= $notice->lat;
3121 $notloc->lon= $notice->lon;
3122 $notloc->location_id= $notice->location_id;
3123 $notloc->location_ns= $notice->location_ns;