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_object_type_idx' => array('object_type'),
114 'notice_verb_idx' => array('verb'),
115 'notice_profile_id_verb_idx' => array('profile_id', 'verb'),
116 'notice_url_idx' => array('url'), // Qvitter wants this
117 'notice_replyto_idx' => array('reply_to')
121 if (common_config('search', 'type') == 'fulltext') {
122 $def['fulltext indexes'] = array('content' => array('content'));
129 const LOCAL_PUBLIC = 1;
131 const LOCAL_NONPUBLIC = -1;
134 const PUBLIC_SCOPE = 0; // Useful fake constant
135 const SITE_SCOPE = 1;
136 const ADDRESSEE_SCOPE = 2;
137 const GROUP_SCOPE = 4;
138 const FOLLOWER_SCOPE = 8;
140 protected $_profile = array();
143 * Will always return a profile, if anything fails it will
144 * (through _setProfile) throw a NoProfileException.
146 public function getProfile()
148 if (!isset($this->_profile[$this->profile_id])) {
149 // We could've sent getKV directly to _setProfile, but occasionally we get
150 // a "false" (instead of null), likely because it indicates a cache miss.
151 $profile = Profile::getKV('id', $this->profile_id);
152 $this->_setProfile($profile instanceof Profile ? $profile : null);
154 return $this->_profile[$this->profile_id];
157 public function _setProfile(Profile $profile=null)
159 if (!$profile instanceof Profile) {
160 throw new NoProfileException($this->profile_id);
162 $this->_profile[$this->profile_id] = $profile;
165 public function deleteAs(Profile $actor, $delete_event=true)
167 if (!$this->getProfile()->sameAs($actor) && !$actor->hasRight(Right::DELETEOTHERSNOTICE)) {
168 throw new AuthorizationException(_('You are not allowed to delete another user\'s notice.'));
172 if (!$delete_event || Event::handle('DeleteNoticeAsProfile', array($this, $actor, &$result))) {
173 // If $delete_event is true, we run the event. If the Event then
174 // returns false it is assumed everything was handled properly
175 // and the notice was deleted.
176 $result = $this->delete();
181 protected function deleteRelated()
183 if (Event::handle('NoticeDeleteRelated', array($this))) {
184 // Clear related records
185 $this->clearReplies();
186 $this->clearLocation();
187 $this->clearRepeats();
189 $this->clearGroupInboxes();
191 $this->clearAttentions();
192 // NOTE: we don't clear queue items
196 public function delete($useWhere=false)
198 $this->deleteRelated();
200 $result = parent::delete($useWhere);
202 $this->blowOnDelete();
206 public function getUri()
212 * Get a Notice object by URI. Will call external plugins for help
213 * using the event StartGetNoticeFromURI.
215 * @param string $uri A unique identifier for a resource (notice in this case)
217 static function fromUri($uri)
221 if (Event::handle('StartGetNoticeFromUri', array($uri, &$notice))) {
222 $notice = Notice::getKV('uri', $uri);
223 Event::handle('EndGetNoticeFromUri', array($uri, $notice));
226 if (!$notice instanceof Notice) {
227 throw new UnknownUriException($uri);
234 * @param $root boolean If true, link to just the conversation root.
236 * @return URL to conversation
238 public function getConversationUrl($anchor=true)
240 return Conversation::getUrlFromNotice($this, $anchor);
244 * Get the local representation URL of this notice.
246 public function getLocalUrl()
248 return common_local_url('shownotice', array('notice' => $this->id), null, null, false);
251 public function getTitle($imply=true)
254 if (Event::handle('GetNoticeTitle', array($this, &$title)) && $imply) {
255 // TRANS: Title of a notice posted without a title value.
256 // TRANS: %1$s is a user name, %2$s is the notice creation date/time.
257 $title = sprintf(_('%1$s\'s status on %2$s'),
258 $this->getProfile()->getFancyName(),
259 common_exact_date($this->created));
264 public function getContent()
266 return $this->content;
269 public function getRendered()
271 // we test $this->id because if it's not inserted yet, we can't update the field
272 if (!empty($this->id) && (is_null($this->rendered) || $this->rendered === '')) {
273 // update to include rendered content on-the-fly, so we don't have to have a fix-up script in upgrade.php
274 common_debug('Rendering notice '.$this->getID().' as it had no rendered HTML content.');
275 $orig = clone($this);
276 $this->rendered = common_render_content($this->getContent(),
278 $this->hasParent() ? $this->getParent() : null);
279 $this->update($orig);
281 return $this->rendered;
284 public function getCreated()
286 return $this->created;
289 public function getVerb($make_relative=false)
291 return ActivityUtils::resolveUri($this->verb, $make_relative);
294 public function isVerb(array $verbs)
296 return ActivityUtils::compareVerbs($this->getVerb(), $verbs);
300 * Get the original representation URL of this notice.
302 * @param boolean $fallback Whether to fall back to generate a local URL or throw InvalidUrlException
304 public function getUrl($fallback=false)
306 // The risk is we start having empty urls and non-http uris...
307 // and we can't really handle any other protocol right now.
309 case $this->isLocal():
310 return common_local_url('shownotice', array('notice' => $this->getID()), null, null, false);
311 case common_valid_http_url($this->url): // should we allow non-http/https URLs?
313 case common_valid_http_url($this->uri): // Sometimes we only have the URI for remote posts.
316 // let's generate a valid link to our locally available notice on demand
317 return common_local_url('shownotice', array('notice' => $this->getID()), null, null, false);
319 throw new InvalidUrlException($this->url);
323 public function getObjectType($canonical=false) {
324 if (is_null($this->object_type) || $this->object_type==='') {
325 throw new NoObjectTypeException($this);
327 return ActivityUtils::resolveUri($this->object_type, $canonical);
330 public function isObjectType(array $types)
333 return ActivityUtils::compareTypes($this->getObjectType(), $types);
334 } catch (NoObjectTypeException $e) {
340 * Extract #hashtags from this notice's content and save them to the database.
344 /* extract all #hastags */
345 $count = preg_match_all('/(?:^|\s)#([\pL\pN_\-\.]{1,64})/u', strtolower($this->content), $match);
350 /* Add them to the database */
351 return $this->saveKnownTags($match[1]);
355 * Record the given set of hash tags in the db for this notice.
356 * Given tag strings will be normalized and checked for dupes.
358 function saveKnownTags($hashtags)
360 //turn each into their canonical tag
361 //this is needed to remove dupes before saving e.g. #hash.tag = #hashtag
362 for($i=0; $i<count($hashtags); $i++) {
363 /* elide characters we don't want in the tag */
364 $hashtags[$i] = common_canonical_tag($hashtags[$i]);
367 foreach(array_unique($hashtags) as $hashtag) {
368 $this->saveTag($hashtag);
369 self::blow('profile:notice_ids_tagged:%d:%s', $this->profile_id, $hashtag);
375 * Record a single hash tag as associated with this notice.
376 * Tag format and uniqueness must be validated by caller.
378 function saveTag($hashtag)
380 $tag = new Notice_tag();
381 $tag->notice_id = $this->id;
382 $tag->tag = $hashtag;
383 $tag->created = $this->created;
384 $id = $tag->insert();
387 // TRANS: Server exception. %s are the error details.
388 throw new ServerException(sprintf(_('Database error inserting hashtag: %s.'),
389 $last_error->message));
393 // if it's saved, blow its cache
394 $tag->blowCache(false);
398 * Save a new notice and push it out to subscribers' inboxes.
399 * Poster's permissions are checked before sending.
401 * @param int $profile_id Profile ID of the poster
402 * @param string $content source message text; links may be shortened
403 * per current user's preference
404 * @param string $source source key ('web', 'api', etc)
405 * @param array $options Associative array of optional properties:
406 * string 'created' timestamp of notice; defaults to now
407 * int 'is_local' source/gateway ID, one of:
408 * Notice::LOCAL_PUBLIC - Local, ok to appear in public timeline
409 * Notice::REMOTE - Sent from a remote service;
410 * hide from public timeline but show in
411 * local "and friends" timelines
412 * Notice::LOCAL_NONPUBLIC - Local, but hide from public timeline
413 * Notice::GATEWAY - From another non-OStatus service;
414 * will not appear in public views
415 * float 'lat' decimal latitude for geolocation
416 * float 'lon' decimal longitude for geolocation
417 * int 'location_id' geoname identifier
418 * int 'location_ns' geoname namespace to interpret location_id
419 * int 'reply_to'; notice ID this is a reply to
420 * int 'repeat_of'; notice ID this is a repeat of
421 * string 'uri' unique ID for notice; a unique tag uri (can be url or anything too)
422 * string 'url' permalink to notice; defaults to local notice URL
423 * string 'rendered' rendered HTML version of content
424 * array 'replies' list of profile URIs for reply delivery in
425 * place of extracting @-replies from content.
426 * array 'groups' list of group IDs to deliver to, in place of
427 * extracting ! tags from content
428 * array 'tags' list of hashtag strings to save with the notice
429 * in place of extracting # tags from content
430 * array 'urls' list of attached/referred URLs to save with the
431 * notice in place of extracting links from content
432 * boolean 'distribute' whether to distribute the notice, default true
433 * string 'object_type' URL of the associated object type (default ActivityObject::NOTE)
434 * string 'verb' URL of the associated verb (default ActivityVerb::POST)
435 * int 'scope' Scope bitmask; default to SITE_SCOPE on private sites, 0 otherwise
437 * @fixme tag override
440 * @throws ClientException
442 static function saveNew($profile_id, $content, $source, array $options=null) {
443 $defaults = array('uri' => null,
445 'conversation' => null, // URI of conversation
446 'reply_to' => null, // This will override convo URI if the parent is known
447 'repeat_of' => null, // This will override convo URI if the repeated notice is known
449 'distribute' => true,
450 'object_type' => null,
453 if (!empty($options) && is_array($options)) {
454 $options = array_merge($defaults, $options);
460 if (!isset($is_local)) {
461 $is_local = Notice::LOCAL_PUBLIC;
464 $profile = Profile::getKV('id', $profile_id);
465 if (!$profile instanceof Profile) {
466 // TRANS: Client exception thrown when trying to save a notice for an unknown user.
467 throw new ClientException(_('Problem saving notice. Unknown user.'));
470 $user = User::getKV('id', $profile_id);
471 if ($user instanceof User) {
472 // Use the local user's shortening preferences, if applicable.
473 $final = $user->shortenLinks($content);
475 $final = common_shorten_links($content);
478 if (Notice::contentTooLong($final)) {
479 // TRANS: Client exception thrown if a notice contains too many characters.
480 throw new ClientException(_('Problem saving notice. Too long.'));
483 if (common_config('throttle', 'enabled') && !Notice::checkEditThrottle($profile_id)) {
484 common_log(LOG_WARNING, 'Excessive posting by profile #' . $profile_id . '; throttled.');
485 // TRANS: Client exception thrown when a user tries to post too many notices in a given time frame.
486 throw new ClientException(_('Too many notices too fast; take a breather '.
487 'and post again in a few minutes.'));
490 if (common_config('site', 'dupelimit') > 0 && !Notice::checkDupes($profile_id, $final)) {
491 common_log(LOG_WARNING, 'Dupe posting by profile #' . $profile_id . '; throttled.');
492 // TRANS: Client exception thrown when a user tries to post too many duplicate notices in a given time frame.
493 throw new ClientException(_('Too many duplicate messages too quickly;'.
494 ' take a breather and post again in a few minutes.'));
497 if (!$profile->hasRight(Right::NEWNOTICE)) {
498 common_log(LOG_WARNING, "Attempted post from user disallowed to post: " . $profile->nickname);
500 // TRANS: Client exception thrown when a user tries to post while being banned.
501 throw new ClientException(_('You are banned from posting notices on this site.'), 403);
504 $notice = new Notice();
505 $notice->profile_id = $profile_id;
507 if ($source && in_array($source, common_config('public', 'autosource'))) {
508 $notice->is_local = Notice::LOCAL_NONPUBLIC;
510 $notice->is_local = $is_local;
513 if (!empty($created)) {
514 $notice->created = $created;
516 $notice->created = common_sql_now();
519 if (!$notice->isLocal()) {
520 // Only do these checks for non-local notices. Local notices will generate these values later.
522 throw new ServerException('No URI for remote notice. Cannot accept that.');
526 $notice->content = $final;
528 $notice->source = $source;
532 // Get the groups here so we can figure out replies and such
533 if (!isset($groups)) {
534 $groups = User_group::idsFromText($notice->content, $profile);
539 // Handle repeat case
541 if (!empty($options['repeat_of'])) {
543 // Check for a private one
545 $repeat = Notice::getByID($options['repeat_of']);
547 if ($profile->sameAs($repeat->getProfile())) {
548 // TRANS: Client error displayed when trying to repeat an own notice.
549 throw new ClientException(_('You cannot repeat your own notice.'));
552 if ($repeat->scope != Notice::SITE_SCOPE &&
553 $repeat->scope != Notice::PUBLIC_SCOPE) {
554 // TRANS: Client error displayed when trying to repeat a non-public notice.
555 throw new ClientException(_('Cannot repeat a private notice.'), 403);
558 if (!$repeat->inScope($profile)) {
559 // The generic checks above should cover this, but let's be sure!
560 // TRANS: Client error displayed when trying to repeat a notice you cannot access.
561 throw new ClientException(_('Cannot repeat a notice you cannot read.'), 403);
564 if ($profile->hasRepeated($repeat)) {
565 // TRANS: Client error displayed when trying to repeat an already repeated notice.
566 throw new ClientException(_('You already repeated that notice.'));
569 $notice->repeat_of = $repeat->id;
570 $notice->conversation = $repeat->conversation;
574 // If $reply_to is specified, we check that it exists, and then
575 // return it if it does
576 if (!empty($reply_to)) {
577 $reply = Notice::getKV('id', $reply_to);
578 } elseif (in_array($source, array('xmpp', 'mail', 'sms'))) {
579 // If the source lacks capability of sending the "reply_to"
580 // metadata, let's try to find an inline replyto-reference.
581 $reply = self::getInlineReplyTo($profile, $final);
584 if ($reply instanceof Notice) {
585 if (!$reply->inScope($profile)) {
586 // TRANS: Client error displayed when trying to reply to a notice a the target has no access to.
587 // TRANS: %1$s is a user nickname, %2$d is a notice ID (number).
588 throw new ClientException(sprintf(_('%1$s has no access to notice %2$d.'),
589 $profile->nickname, $reply->id), 403);
592 // If it's a repeat, the reply_to should be to the original
593 if ($reply->isRepeat()) {
594 $notice->reply_to = $reply->repeat_of;
596 $notice->reply_to = $reply->id;
598 // But the conversation ought to be the same :)
599 $notice->conversation = $reply->conversation;
601 // If the original is private to a group, and notice has
602 // no group specified, make it to the same group(s)
604 if (empty($groups) && ($reply->scope & Notice::GROUP_SCOPE)) {
606 $replyGroups = $reply->getGroups();
607 foreach ($replyGroups as $group) {
608 if ($profile->isMember($group)) {
609 $groups[] = $group->id;
617 // If we don't know the reply, we might know the conversation!
618 // This will happen if a known remote user replies to an
619 // unknown remote user - within a known conversation.
620 if (empty($notice->conversation) and !empty($options['conversation'])) {
621 $conv = Conversation::getKV('uri', $options['conversation']);
622 if ($conv instanceof Conversation) {
623 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.').');
625 // Conversation entry with specified URI was not found, so we must create it.
626 common_debug('Conversation URI not found, so we will create it with the URI given in the options to Notice::saveNew: '.$options['conversation']);
627 $convctx = new ActivityContext();
628 $convctx->conversation = $options['conversation'];
629 if (array_key_exists('conversation_url', $options)) {
630 $convctx->conversation_url = $options['conversation_url'];
632 // The insert in Conversation::create throws exception on failure
633 $conv = Conversation::create($convctx, $notice->created);
635 $notice->conversation = $conv->getID();
640 // If it's not part of a conversation, it's the beginning of a new conversation.
641 if (empty($notice->conversation)) {
642 $conv = Conversation::create();
643 $notice->conversation = $conv->getID();
648 $notloc = new Notice_location();
649 if (!empty($lat) && !empty($lon)) {
654 if (!empty($location_ns) && !empty($location_id)) {
655 $notloc->location_id = $location_id;
656 $notloc->location_ns = $location_ns;
659 if (!empty($rendered)) {
660 $notice->rendered = $rendered;
662 $notice->rendered = common_render_content($final,
663 $notice->getProfile(),
664 $notice->hasParent() ? $notice->getParent() : null);
668 if ($notice->isRepeat()) {
669 $notice->verb = ActivityVerb::SHARE;
670 $notice->object_type = ActivityObject::ACTIVITY;
672 $notice->verb = ActivityVerb::POST;
675 $notice->verb = $verb;
678 if (empty($object_type)) {
679 $notice->object_type = (empty($notice->reply_to)) ? ActivityObject::NOTE : ActivityObject::COMMENT;
681 $notice->object_type = $object_type;
684 if (is_null($scope) && $reply instanceof Notice) {
685 $notice->scope = $reply->scope;
687 $notice->scope = $scope;
690 $notice->scope = self::figureOutScope($profile, $groups, $notice->scope);
692 if (Event::handle('StartNoticeSave', array(&$notice))) {
694 // XXX: some of these functions write to the DB
697 $notice->insert(); // throws exception on failure, if successful we have an ->id
699 if (($notloc->lat && $notloc->lon) || ($notloc->location_id && $notloc->location_ns)) {
700 $notloc->notice_id = $notice->getID();
701 $notloc->insert(); // store the notice location if it had any information
703 } catch (Exception $e) {
704 // Let's test if we managed initial insert, which would imply
705 // failing on some update-part (check 'insert()'). Delete if
706 // something had been stored to the database.
707 if (!empty($notice->id)) {
714 // Only save 'attention' and metadata stuff (URLs, tags...) stuff if
715 // the activityverb is a POST (since stuff like repeat, favorite etc.
716 // reasonably handle notifications themselves.
717 if (ActivityUtils::compareVerbs($notice->verb, array(ActivityVerb::POST))) {
718 if (isset($replies)) {
719 $notice->saveKnownReplies($replies);
721 $notice->saveReplies();
725 $notice->saveKnownTags($tags);
730 // Note: groups may save tags, so must be run after tags are saved
731 // to avoid errors on duplicates.
732 // Note: groups should always be set.
734 $notice->saveKnownGroups($groups);
737 $notice->saveKnownUrls($urls);
744 // Prepare inbox delivery, may be queued to background.
745 $notice->distribute();
751 static function saveActivity(Activity $act, Profile $actor, array $options=array())
753 // First check if we're going to let this Activity through from the specific actor
754 if (!$actor->hasRight(Right::NEWNOTICE)) {
755 common_log(LOG_WARNING, "Attempted post from user disallowed to post: " . $actor->getNickname());
757 // TRANS: Client exception thrown when a user tries to post while being banned.
758 throw new ClientException(_m('You are banned from posting notices on this site.'), 403);
760 if (common_config('throttle', 'enabled') && !self::checkEditThrottle($actor->id)) {
761 common_log(LOG_WARNING, 'Excessive posting by profile #' . $actor->id . '; throttled.');
762 // TRANS: Client exception thrown when a user tries to post too many notices in a given time frame.
763 throw new ClientException(_m('Too many notices too fast; take a breather '.
764 'and post again in a few minutes.'));
767 // Get ActivityObject properties
769 if (!empty($act->id)) {
771 $options['uri'] = $act->id;
772 $options['url'] = $act->link;
774 $actobj = count($act->objects)===1 ? $act->objects[0] : null;
775 if (!is_null($actobj) && !empty($actobj->id)) {
776 $options['uri'] = $actobj->id;
778 $options['url'] = $actobj->link;
779 } elseif (preg_match('!^https?://!', $actobj->id)) {
780 $options['url'] = $actobj->id;
787 'is_local' => $actor->isLocal() ? self::LOCAL_PUBLIC : self::REMOTE,
788 'mentions' => array(),
792 'source' => 'unknown',
797 'distribute' => true);
799 // options will have default values when nothing has been supplied
800 $options = array_merge($defaults, $options);
801 foreach (array_keys($defaults) as $key) {
802 // Only convert the keynames we specify ourselves from 'defaults' array into variables
803 $$key = $options[$key];
805 extract($options, EXTR_SKIP);
808 $stored = new Notice();
809 if (!empty($uri) && !ActivityUtils::compareVerbs($act->verb, array(ActivityVerb::DELETE))) {
811 if ($stored->find()) {
812 common_debug('cannot create duplicate Notice URI: '.$stored->uri);
813 // I _assume_ saving a Notice with a colliding URI means we're really trying to
814 // save the same notice again...
815 throw new AlreadyFulfilledException('Notice URI already exists');
819 // NOTE: Sandboxed users previously got all the notices _during_
820 // sandbox period set to to is_local=Notice::LOCAL_NONPUBLIC here.
821 // Since then we have started just filtering _when_ it gets shown
822 // instead of creating a mixed jumble of differently scoped notices.
824 if ($source && in_array($source, common_config('public', 'autosource'))) {
825 $stored->is_local = Notice::LOCAL_NONPUBLIC;
827 $stored->is_local = intval($is_local);
830 if (!$stored->isLocal()) {
831 // Only do these checks for non-local notices. Local notices will generate these values later.
832 if (!common_valid_http_url($url)) {
833 common_debug('Bad notice URL: ['.$url.'], URI: ['.$uri.']. Cannot link back to original! This is normal for shared notices etc.');
836 throw new ServerException('No URI for remote notice. Cannot accept that.');
840 $stored->profile_id = $actor->getID();
841 $stored->source = $source;
844 $stored->verb = $act->verb;
846 // we use mb_strlen because it _might_ be that the content is just the string "0"...
847 $content = mb_strlen($act->content) ? $act->content : $act->summary;
848 if (mb_strlen($content)===0 && !is_null($actobj)) {
849 $content = mb_strlen($actobj->content) ? $actobj->content : $actobj->summary;
851 // Strip out any bad HTML from $content. URI.Base is used to sort out relative URLs.
852 $stored->rendered = common_purify($content, ['URI.Base' => $stored->url ?: null]);
853 $stored->content = common_strip_html($stored->getRendered(), true, true);
854 if (trim($stored->content) === '') {
855 // TRANS: Error message when the plain text content of a notice has zero length.
856 throw new ClientException(_('Empty notice content, will not save this.'));
858 unset($content); // garbage collect
860 // Maybe a missing act-time should be fatal if the actor is not local?
861 if (!empty($act->time)) {
862 $stored->created = common_sql_date($act->time);
864 $stored->created = common_sql_now();
867 $reply = null; // this will store the in-reply-to Notice if found
868 $replyUris = []; // this keeps a list of possible URIs to look up
869 if ($act->context instanceof ActivityContext && !empty($act->context->replyToID)) {
870 $replyUris[] = $act->context->replyToID;
872 if ($act->target instanceof ActivityObject && !empty($act->target->id)) {
873 $replyUris[] = $act->target->id;
875 foreach (array_unique($replyUris) as $replyUri) {
876 $reply = self::getKV('uri', $replyUri);
877 // Only do remote fetching if we're not a private site
878 if (!common_config('site', 'private') && !$reply instanceof Notice) {
879 // the URI is the object we're looking for, $actor is a
880 // Profile that surely knows of it and &$reply where it
881 // will be stored when fetched
882 Event::handle('FetchRemoteNotice', array($replyUri, $actor, &$reply));
884 // we got what we're in-reply-to now, so let's move on
885 if ($reply instanceof Notice) {
888 // otherwise reset whatever we might've gotten from the event
891 unset($replyUris); // garbage collect
893 if ($reply instanceof Notice) {
894 if (!$reply->inScope($actor)) {
895 // TRANS: Client error displayed when trying to reply to a notice a the target has no access to.
896 // TRANS: %1$s is a user nickname, %2$d is a notice ID (number).
897 throw new ClientException(sprintf(_m('%1$s has no right to reply to notice %2$d.'), $actor->getNickname(), $reply->id), 403);
900 $stored->reply_to = $reply->id;
901 $stored->conversation = $reply->conversation;
903 // If the original is private to a group, and notice has no group specified,
904 // make it to the same group(s)
905 if (empty($groups) && ($reply->scope & Notice::GROUP_SCOPE)) {
906 $replyGroups = $reply->getGroups();
907 foreach ($replyGroups as $group) {
908 if ($actor->isMember($group)) {
909 $groups[] = $group->id;
914 if (is_null($scope)) {
915 $scope = $reply->scope;
918 // If we don't know the reply, we might know the conversation!
919 // This will happen if a known remote user replies to an
920 // unknown remote user - within a known conversation.
921 if (empty($stored->conversation) and !empty($act->context->conversation)) {
922 $conv = Conversation::getKV('uri', $act->context->conversation);
923 if ($conv instanceof Conversation) {
924 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.').');
926 // Conversation entry with specified URI was not found, so we must create it.
927 common_debug('Conversation URI not found, so we will create it with the URI given in the context of the activity: '.$act->context->conversation);
928 // The insert in Conversation::create throws exception on failure
929 $conv = Conversation::create($act->context, $stored->created);
931 $stored->conversation = $conv->getID();
935 unset($reply); // garbage collect
937 // If it's not part of a conversation, it's the beginning of a new conversation.
938 if (empty($stored->conversation)) {
939 $conv = Conversation::create();
940 $stored->conversation = $conv->getID();
945 if ($act->context instanceof ActivityContext) {
946 if ($act->context->location instanceof Location) {
947 $notloc = Notice_location::fromLocation($act->context->location);
950 $act->context = new ActivityContext();
953 if (array_key_exists(ActivityContext::ATTN_PUBLIC, $act->context->attention)) {
954 $stored->scope = Notice::PUBLIC_SCOPE;
955 // TODO: maybe we should actually keep this? if the saveAttentions thing wants to use it...
956 unset($act->context->attention[ActivityContext::ATTN_PUBLIC]);
958 $stored->scope = self::figureOutScope($actor, $groups, $scope);
961 foreach ($act->categories as $cat) {
963 $term = common_canonical_tag($cat->term);
970 foreach ($act->enclosures as $href) {
971 // @todo FIXME: Save these locally or....?
975 if (ActivityUtils::compareVerbs($stored->verb, array(ActivityVerb::POST))) {
976 if (empty($act->objects[0]->type)) {
977 // Default type for the post verb is 'note', but we know it's
978 // a 'comment' if it is in reply to something.
979 $stored->object_type = empty($stored->reply_to) ? ActivityObject::NOTE : ActivityObject::COMMENT;
981 //TODO: Is it safe to always return a relative URI? The
982 // JSON version of ActivityStreams always use it, so we
983 // should definitely be able to handle it...
984 $stored->object_type = ActivityUtils::resolveUri($act->objects[0]->type, true);
988 if (Event::handle('StartNoticeSave', array(&$stored))) {
989 // XXX: some of these functions write to the DB
992 $result = $stored->insert(); // throws exception on error
994 if ($notloc instanceof Notice_location) {
995 $notloc->notice_id = $stored->getID();
999 $orig = clone($stored); // for updating later in this try clause
1002 Event::handle('StoreActivityObject', array($act, $stored, $options, &$object));
1003 if (empty($object)) {
1004 throw new NoticeSaveException('Unsuccessful call to StoreActivityObject '._ve($stored->getUri()) . ': '._ve($act->asString()));
1008 // If something changed in the Notice during StoreActivityObject
1009 $stored->update($orig);
1010 } catch (Exception $e) {
1011 if (empty($stored->id)) {
1012 common_debug('Failed to save stored object entry in database ('.$e->getMessage().')');
1014 common_debug('Failed to store activity object in database ('.$e->getMessage().'), deleting notice id '.$stored->id);
1020 unset($notloc); // garbage collect
1022 if (!$stored instanceof Notice) {
1023 throw new ServerException('StartNoticeSave did not give back a Notice.');
1024 } elseif (empty($stored->id)) {
1025 throw new ServerException('Supposedly saved Notice has no ID.');
1028 // Only save 'attention' and metadata stuff (URLs, tags...) stuff if
1029 // the activityverb is a POST (since stuff like repeat, favorite etc.
1030 // reasonably handle notifications themselves.
1031 if (ActivityUtils::compareVerbs($stored->verb, array(ActivityVerb::POST))) {
1033 if (!empty($tags)) {
1034 $stored->saveKnownTags($tags);
1036 $stored->saveTags();
1039 // Note: groups may save tags, so must be run after tags are saved
1040 // to avoid errors on duplicates.
1041 $stored->saveAttentions($act->context->attention);
1043 if (!empty($urls)) {
1044 $stored->saveKnownUrls($urls);
1046 $stored->saveUrls();
1051 // Prepare inbox delivery, may be queued to background.
1052 $stored->distribute();
1058 static public function figureOutScope(Profile $actor, array $groups, $scope=null) {
1059 $scope = is_null($scope) ? self::defaultScope() : intval($scope);
1061 // For private streams
1063 $user = $actor->getUser();
1064 // FIXME: We can't do bit comparison with == (Legacy StatusNet thing. Let's keep it for now.)
1065 if ($user->private_stream && ($scope === Notice::PUBLIC_SCOPE || $scope === Notice::SITE_SCOPE)) {
1066 $scope |= Notice::FOLLOWER_SCOPE;
1068 } catch (NoSuchUserException $e) {
1069 // TODO: Not a local user, so we don't know about scope preferences... yet!
1072 // Force the scope for private groups
1073 foreach ($groups as $group_id) {
1075 $group = User_group::getByID($group_id);
1076 if ($group->force_scope) {
1077 $scope |= Notice::GROUP_SCOPE;
1080 } catch (Exception $e) {
1081 common_log(LOG_ERR, 'Notice figureOutScope threw exception: '.$e->getMessage());
1088 function blowOnInsert($conversation = false)
1090 $this->blowStream('profile:notice_ids:%d', $this->profile_id);
1092 if ($this->isPublic()) {
1093 $this->blowStream('public');
1094 $this->blowStream('networkpublic');
1097 if ($this->conversation) {
1098 self::blow('notice:list-ids:conversation:%s', $this->conversation);
1099 self::blow('conversation:notice_count:%d', $this->conversation);
1102 if ($this->isRepeat()) {
1103 // XXX: we should probably only use one of these
1104 $this->blowStream('notice:repeats:%d', $this->repeat_of);
1105 self::blow('notice:list-ids:repeat_of:%d', $this->repeat_of);
1108 $original = Notice::getKV('id', $this->repeat_of);
1110 if ($original instanceof Notice) {
1111 $originalUser = User::getKV('id', $original->profile_id);
1112 if ($originalUser instanceof User) {
1113 $this->blowStream('user:repeats_of_me:%d', $originalUser->id);
1117 $profile = Profile::getKV($this->profile_id);
1119 if ($profile instanceof Profile) {
1120 $profile->blowNoticeCount();
1123 $ptags = $this->getProfileTags();
1124 foreach ($ptags as $ptag) {
1125 $ptag->blowNoticeStreamCache();
1130 * Clear cache entries related to this notice at delete time.
1131 * Necessary to avoid breaking paging on public, profile timelines.
1133 function blowOnDelete()
1135 $this->blowOnInsert();
1137 self::blow('profile:notice_ids:%d;last', $this->profile_id);
1139 if ($this->isPublic()) {
1140 self::blow('public;last');
1141 self::blow('networkpublic;last');
1144 self::blow('fave:by_notice', $this->id);
1146 if ($this->conversation) {
1147 // In case we're the first, will need to calc a new root.
1148 self::blow('notice:conversation_root:%d', $this->conversation);
1151 $ptags = $this->getProfileTags();
1152 foreach ($ptags as $ptag) {
1153 $ptag->blowNoticeStreamCache(true);
1157 function blowStream()
1159 $c = self::memcache();
1165 $args = func_get_args();
1166 $format = array_shift($args);
1167 $keyPart = vsprintf($format, $args);
1168 $cacheKey = Cache::key($keyPart);
1169 $c->delete($cacheKey);
1171 // delete the "last" stream, too, if this notice is
1172 // older than the top of that stream
1174 $lastKey = $cacheKey.';last';
1176 $lastStr = $c->get($lastKey);
1178 if ($lastStr !== false) {
1179 $window = explode(',', $lastStr);
1180 $lastID = $window[0];
1181 $lastNotice = Notice::getKV('id', $lastID);
1182 if (!$lastNotice instanceof Notice // just weird
1183 || strtotime($lastNotice->created) >= strtotime($this->created)) {
1184 $c->delete($lastKey);
1189 /** save all urls in the notice to the db
1191 * follow redirects and save all available file information
1192 * (mimetype, date, size, oembed, etc.)
1196 function saveUrls() {
1197 if (common_config('attachments', 'process_links')) {
1198 common_replace_urls_callback($this->content, array($this, 'saveUrl'), $this);
1203 * Save the given URLs as related links/attachments to the db
1205 * follow redirects and save all available file information
1206 * (mimetype, date, size, oembed, etc.)
1210 function saveKnownUrls($urls)
1212 if (common_config('attachments', 'process_links')) {
1213 // @fixme validation?
1214 foreach (array_unique($urls) as $url) {
1215 $this->saveUrl($url, $this);
1223 function saveUrl($url, Notice $notice) {
1225 File::processNew($url, $notice);
1226 } catch (ServerException $e) {
1227 // Could not save URL. Log it?
1231 static function checkDupes($profile_id, $content) {
1232 $profile = Profile::getKV($profile_id);
1233 if (!$profile instanceof Profile) {
1236 $notice = $profile->getNotices(0, CachingNoticeStream::CACHE_WINDOW);
1237 if (!empty($notice)) {
1239 while ($notice->fetch()) {
1240 if (time() - strtotime($notice->created) >= common_config('site', 'dupelimit')) {
1242 } else if ($notice->content == $content) {
1247 // If we get here, oldest item in cache window is not
1248 // old enough for dupe limit; do direct check against DB
1249 $notice = new Notice();
1250 $notice->profile_id = $profile_id;
1251 $notice->content = $content;
1252 $threshold = common_sql_date(time() - common_config('site', 'dupelimit'));
1253 $notice->whereAdd(sprintf("created > '%s'", $notice->escape($threshold)));
1255 $cnt = $notice->count();
1259 static function checkEditThrottle($profile_id) {
1260 $profile = Profile::getKV($profile_id);
1261 if (!$profile instanceof Profile) {
1264 // Get the Nth notice
1265 $notice = $profile->getNotices(common_config('throttle', 'count') - 1, 1);
1266 if ($notice && $notice->fetch()) {
1267 // If the Nth notice was posted less than timespan seconds ago
1268 if (time() - strtotime($notice->created) <= common_config('throttle', 'timespan')) {
1273 // Either not N notices in the stream, OR the Nth was not posted within timespan seconds
1277 protected $_attachments = array();
1279 function attachments() {
1280 if (isset($this->_attachments[$this->id])) {
1281 return $this->_attachments[$this->id];
1284 $f2ps = File_to_post::listGet('post_id', array($this->id));
1286 foreach ($f2ps[$this->id] as $f2p) {
1287 $ids[] = $f2p->file_id;
1290 return $this->_setAttachments(File::multiGet('id', $ids)->fetchAll());
1293 public function _setAttachments(array $attachments)
1295 return $this->_attachments[$this->id] = $attachments;
1298 static function publicStream($offset=0, $limit=20, $since_id=null, $max_id=null)
1300 $stream = new PublicNoticeStream();
1301 return $stream->getNotices($offset, $limit, $since_id, $max_id);
1304 static function conversationStream($id, $offset=0, $limit=20, $since_id=null, $max_id=null, Profile $scoped=null)
1306 $stream = new ConversationNoticeStream($id, $scoped);
1307 return $stream->getNotices($offset, $limit, $since_id, $max_id);
1311 * Is this notice part of an active conversation?
1313 * @return boolean true if other messages exist in the same
1314 * conversation, false if this is the only one
1316 function hasConversation()
1318 if (empty($this->conversation)) {
1319 // this notice is not part of a conversation apparently
1320 // FIXME: all notices should have a conversation value, right?
1324 //FIXME: Get the Profile::current() stuff some other way
1325 // to avoid confusion between queue processing and session.
1326 $notice = self::conversationStream($this->conversation, 1, 1, null, null, Profile::current());
1328 // if our "offset 1, limit 1" query got a result, return true else false
1329 return $notice->N > 0;
1333 * Grab the earliest notice from this conversation.
1335 * @return Notice or null
1337 function conversationRoot($profile=-1)
1339 // XXX: can this happen?
1341 if (empty($this->conversation)) {
1345 // Get the current profile if not specified
1347 if (is_int($profile) && $profile == -1) {
1348 $profile = Profile::current();
1351 // If this notice is out of scope, no root for you!
1353 if (!$this->inScope($profile)) {
1357 // If this isn't a reply to anything, then it's its own
1358 // root if it's the earliest notice in the conversation:
1360 if (empty($this->reply_to)) {
1362 $root->conversation = $this->conversation;
1363 $root->orderBy('notice.created ASC');
1364 $root->find(true); // true means "fetch first result"
1369 if (is_null($profile)) {
1370 $keypart = sprintf('notice:conversation_root:%d:null', $this->id);
1372 $keypart = sprintf('notice:conversation_root:%d:%d',
1377 $root = self::cacheGet($keypart);
1379 if ($root !== false && $root->inScope($profile)) {
1386 $parent = $last->getParent();
1387 if ($parent->inScope($profile)) {
1391 } catch (NoParentNoticeException $e) {
1392 // Latest notice has no parent
1393 } catch (NoResultException $e) {
1394 // Notice was not found, so we can't go further up in the tree.
1395 // FIXME: Maybe we should do this in a more stable way where deleted
1396 // notices won't break conversation chains?
1398 // No parent, or parent out of scope
1403 self::cacheSet($keypart, $root);
1409 * Pull up a full list of local recipients who will be getting
1410 * this notice in their inbox. Results will be cached, so don't
1411 * change the input data wily-nilly!
1413 * @param array $groups optional list of Group objects;
1414 * if left empty, will be loaded from group_inbox records
1415 * @param array $recipient optional list of reply profile ids
1416 * if left empty, will be loaded from reply records
1417 * @return array associating recipient user IDs with an inbox source constant
1419 function whoGets(array $groups=null, array $recipients=null)
1421 $c = self::memcache();
1424 $ni = $c->get(Cache::key('notice:who_gets:'.$this->id));
1425 if ($ni !== false) {
1430 if (is_null($recipients)) {
1431 $recipients = $this->getReplies();
1436 // Give plugins a chance to add folks in at start...
1437 if (Event::handle('StartNoticeWhoGets', array($this, &$ni))) {
1439 $users = $this->getSubscribedUsers();
1440 foreach ($users as $id) {
1441 $ni[$id] = NOTICE_INBOX_SOURCE_SUB;
1444 if (is_null($groups)) {
1445 $groups = $this->getGroups();
1447 foreach ($groups as $group) {
1448 $users = $group->getUserMembers();
1449 foreach ($users as $id) {
1450 if (!array_key_exists($id, $ni)) {
1451 $ni[$id] = NOTICE_INBOX_SOURCE_GROUP;
1456 $ptAtts = $this->getAttentionsFromProfileTags();
1457 foreach ($ptAtts as $key=>$val) {
1458 if (!array_key_exists($key, $ni)) {
1463 foreach ($recipients as $recipient) {
1464 if (!array_key_exists($recipient, $ni)) {
1465 $ni[$recipient] = NOTICE_INBOX_SOURCE_REPLY;
1469 // Exclude any deleted, non-local, or blocking recipients.
1470 $profile = $this->getProfile();
1471 $originalProfile = null;
1472 if ($this->isRepeat()) {
1473 // Check blocks against the original notice's poster as well.
1474 $original = Notice::getKV('id', $this->repeat_of);
1475 if ($original instanceof Notice) {
1476 $originalProfile = $original->getProfile();
1480 foreach ($ni as $id => $source) {
1482 $user = User::getKV('id', $id);
1483 if (!$user instanceof User ||
1484 $user->hasBlocked($profile) ||
1485 ($originalProfile && $user->hasBlocked($originalProfile))) {
1488 } catch (UserNoProfileException $e) {
1489 // User doesn't have a profile; invalid; skip them.
1494 // Give plugins a chance to filter out...
1495 Event::handle('EndNoticeWhoGets', array($this, &$ni));
1499 // XXX: pack this data better
1500 $c->set(Cache::key('notice:who_gets:'.$this->id), $ni);
1506 function getSubscribedUsers()
1510 if(common_config('db','quote_identifiers'))
1511 $user_table = '"user"';
1512 else $user_table = 'user';
1516 'FROM '. $user_table .' JOIN subscription '.
1517 'ON '. $user_table .'.id = subscription.subscriber ' .
1518 'WHERE subscription.subscribed = %d ';
1520 $user->query(sprintf($qry, $this->profile_id));
1524 while ($user->fetch()) {
1533 function getProfileTags()
1537 $profile = $this->getProfile();
1538 $list = $profile->getOtherTags($profile);
1540 while($list->fetch()) {
1541 $ptags[] = clone($list);
1543 } catch (Exception $e) {
1544 common_log(LOG_ERR, "Error during Notice->getProfileTags() for id=={$this->getID()}: {$e->getMessage()}");
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;
2016 $ctx->conversation_url = $conv->url;
2020 // This covers the legacy getReplies and getGroups too which get their data
2021 // from entries stored via Notice::saveNew (which we want to move away from)...
2022 foreach ($this->getAttentionProfiles() as $target) {
2023 // User and group profiles which get the attention of this notice
2024 $ctx->attention[$target->getUri()] = $target->getObjectType();
2027 switch ($this->scope) {
2028 case Notice::PUBLIC_SCOPE:
2029 $ctx->attention[ActivityContext::ATTN_PUBLIC] = ActivityObject::COLLECTION;
2031 case Notice::FOLLOWER_SCOPE:
2032 $surl = common_local_url("subscribers", array('nickname' => $profile->nickname));
2033 $ctx->attention[$surl] = ActivityObject::COLLECTION;
2037 $act->context = $ctx;
2039 $source = $this->getSource();
2041 if ($source instanceof Notice_source) {
2042 $act->generator = ActivityObject::fromNoticeSource($source);
2047 $atom_feed = $profile->getAtomFeed();
2049 if (!empty($atom_feed)) {
2051 $act->source = new ActivitySource();
2053 // XXX: we should store the actual feed ID
2055 $act->source->id = $atom_feed;
2057 // XXX: we should store the actual feed title
2059 $act->source->title = $profile->getBestName();
2061 $act->source->links['alternate'] = $profile->profileurl;
2062 $act->source->links['self'] = $atom_feed;
2064 $act->source->icon = $profile->avatarUrl(AVATAR_PROFILE_SIZE);
2066 $notice = $profile->getCurrentNotice();
2068 if ($notice instanceof Notice) {
2069 $act->source->updated = self::utcDate($notice->created);
2072 $user = User::getKV('id', $profile->id);
2074 if ($user instanceof User) {
2075 $act->source->links['license'] = common_config('license', 'url');
2079 if ($this->isLocal()) {
2080 $act->selfLink = common_local_url('ApiStatusesShow', array('id' => $this->id,
2081 'format' => 'atom'));
2082 $act->editLink = $act->selfLink;
2085 Event::handle('EndNoticeAsActivity', array($this, $act, $scoped));
2088 self::cacheSet(Cache::codeKey('notice:as-activity:'.$this->id), $act);
2093 // This has gotten way too long. Needs to be sliced up into functional bits
2094 // or ideally exported to a utility class.
2096 function asAtomEntry($namespace=false,
2099 Profile $scoped=null)
2101 $act = $this->asActivity($scoped);
2102 $act->extra[] = $this->noticeInfo($scoped);
2103 return $act->asString($namespace, $author, $source);
2107 * Extra notice info for atom entries
2109 * Clients use some extra notice info in the atom stream.
2110 * This gives it to them.
2112 * @param Profile $scoped The currently logged in/scoped profile
2114 * @return array representation of <statusnet:notice_info> element
2117 function noticeInfo(Profile $scoped=null)
2119 // local notice ID (useful to clients for ordering)
2121 $noticeInfoAttr = array('local_id' => $this->id);
2125 $ns = $this->getSource();
2127 if ($ns instanceof Notice_source) {
2128 $noticeInfoAttr['source'] = $ns->code;
2129 if (!empty($ns->url)) {
2130 $noticeInfoAttr['source_link'] = $ns->url;
2131 if (!empty($ns->name)) {
2132 $noticeInfoAttr['source'] = $ns->name;
2137 // favorite and repeated
2139 if ($scoped instanceof Profile) {
2140 $noticeInfoAttr['repeated'] = ($scoped->hasRepeated($this)) ? "true" : "false";
2143 if (!empty($this->repeat_of)) {
2144 $noticeInfoAttr['repeat_of'] = $this->repeat_of;
2147 Event::handle('StatusNetApiNoticeInfo', array($this, &$noticeInfoAttr, $scoped));
2149 return array('statusnet:notice_info', $noticeInfoAttr, null);
2153 * Returns an XML string fragment with a reference to a notice as an
2154 * Activity Streams noun object with the given element type.
2156 * Assumes that 'activity' namespace has been previously defined.
2158 * @param string $element one of 'subject', 'object', 'target'
2162 function asActivityNoun($element)
2164 $noun = $this->asActivityObject();
2165 return $noun->asString('activity:' . $element);
2168 public function asActivityObject()
2170 $object = new ActivityObject();
2172 if (Event::handle('StartActivityObjectFromNotice', array($this, &$object))) {
2173 $object->type = $this->object_type ?: ActivityObject::NOTE;
2174 $object->id = $this->getUri();
2175 //FIXME: = $object->title ?: sprintf(... because we might get a title from StartActivityObjectFromNotice
2176 $object->title = sprintf('New %1$s by %2$s', ActivityObject::canonicalType($object->type), $this->getProfile()->getNickname());
2177 $object->content = $this->getRendered();
2178 $object->link = $this->getUrl();
2180 $object->extra[] = array('status_net', array('notice_id' => $this->id));
2182 Event::handle('EndActivityObjectFromNotice', array($this, &$object));
2185 if (!$object instanceof ActivityObject) {
2186 common_log(LOG_ERR, 'Notice asActivityObject created something else for uri=='._ve($this->getUri()).': '._ve($object));
2187 throw new ServerException('Notice asActivityObject created something else.');
2194 * Determine which notice, if any, a new notice is in reply to.
2196 * For conversation tracking, we try to see where this notice fits
2197 * in the tree. Beware that this may very well give false positives
2198 * and add replies to wrong threads (if there have been newer posts
2199 * by the same user as we're replying to).
2201 * @param Profile $sender Author profile
2202 * @param string $content Final notice content
2204 * @return integer ID of replied-to notice, or null for not a reply.
2207 static function getInlineReplyTo(Profile $sender, $content)
2209 // Is there an initial @ or T?
2210 if (preg_match('/^T ([A-Z0-9]{1,64}) /', $content, $match)
2211 || preg_match('/^@([a-z0-9]{1,64})\s+/', $content, $match)) {
2212 $nickname = common_canonical_nickname($match[1]);
2217 // Figure out who that is.
2218 $recipient = common_relative_profile($sender, $nickname, common_sql_now());
2220 if ($recipient instanceof Profile) {
2221 // Get their last notice
2222 $last = $recipient->getCurrentNotice();
2223 if ($last instanceof Notice) {
2226 // Maybe in the future we want to handle something else below
2227 // so don't return getCurrentNotice() immediately.
2233 static function maxContent()
2235 $contentlimit = common_config('notice', 'contentlimit');
2236 // null => use global limit (distinct from 0!)
2237 if (is_null($contentlimit)) {
2238 $contentlimit = common_config('site', 'textlimit');
2240 return $contentlimit;
2243 static function contentTooLong($content)
2245 $contentlimit = self::maxContent();
2246 return ($contentlimit > 0 && !empty($content) && (mb_strlen($content) > $contentlimit));
2250 * Convenience function for posting a repeat of an existing message.
2252 * @param Profile $repeater Profile which is doing the repeat
2253 * @param string $source: posting source key, eg 'web', 'api', etc
2256 * @throws Exception on failure or permission problems
2258 function repeat(Profile $repeater, $source)
2260 $author = $this->getProfile();
2262 // TRANS: Message used to repeat a notice. RT is the abbreviation of 'retweet'.
2263 // TRANS: %1$s is the repeated user's name, %2$s is the repeated notice.
2264 $content = sprintf(_('RT @%1$s %2$s'),
2265 $author->getNickname(),
2268 $maxlen = self::maxContent();
2269 if ($maxlen > 0 && mb_strlen($content) > $maxlen) {
2270 // Web interface and current Twitter API clients will
2271 // pull the original notice's text, but some older
2272 // clients and RSS/Atom feeds will see this trimmed text.
2274 // Unfortunately this is likely to lose tags or URLs
2275 // at the end of long notices.
2276 $content = mb_substr($content, 0, $maxlen - 4) . ' ...';
2280 // Scope is same as this one's
2281 return self::saveNew($repeater->id,
2284 array('repeat_of' => $this->id,
2285 'scope' => $this->scope));
2288 // These are supposed to be in chron order!
2290 function repeatStream($limit=100)
2292 $cache = Cache::instance();
2294 if (empty($cache)) {
2295 $ids = $this->_repeatStreamDirect($limit);
2297 $idstr = $cache->get(Cache::key('notice:repeats:'.$this->id));
2298 if ($idstr !== false) {
2299 if (empty($idstr)) {
2302 $ids = explode(',', $idstr);
2305 $ids = $this->_repeatStreamDirect(100);
2306 $cache->set(Cache::key('notice:repeats:'.$this->id), implode(',', $ids));
2309 // We do a max of 100, so slice down to limit
2310 $ids = array_slice($ids, 0, $limit);
2314 return NoticeStream::getStreamByIds($ids);
2317 function _repeatStreamDirect($limit)
2319 $notice = new Notice();
2321 $notice->selectAdd(); // clears it
2322 $notice->selectAdd('id');
2324 $notice->repeat_of = $this->id;
2326 $notice->orderBy('created, id'); // NB: asc!
2328 if (!is_null($limit)) {
2329 $notice->limit(0, $limit);
2332 return $notice->fetchAll('id');
2335 static function locationOptions($lat, $lon, $location_id, $location_ns, $profile = null)
2339 if (!empty($location_id) && !empty($location_ns)) {
2340 $options['location_id'] = $location_id;
2341 $options['location_ns'] = $location_ns;
2343 $location = Location::fromId($location_id, $location_ns);
2345 if ($location instanceof Location) {
2346 $options['lat'] = $location->lat;
2347 $options['lon'] = $location->lon;
2350 } else if (!empty($lat) && !empty($lon)) {
2351 $options['lat'] = $lat;
2352 $options['lon'] = $lon;
2354 $location = Location::fromLatLon($lat, $lon);
2356 if ($location instanceof Location) {
2357 $options['location_id'] = $location->location_id;
2358 $options['location_ns'] = $location->location_ns;
2360 } else if (!empty($profile)) {
2361 if (isset($profile->lat) && isset($profile->lon)) {
2362 $options['lat'] = $profile->lat;
2363 $options['lon'] = $profile->lon;
2366 if (isset($profile->location_id) && isset($profile->location_ns)) {
2367 $options['location_id'] = $profile->location_id;
2368 $options['location_ns'] = $profile->location_ns;
2375 function clearAttentions()
2377 $att = new Attention();
2378 $att->notice_id = $this->getID();
2381 while ($att->fetch()) {
2382 // Can't do delete() on the object directly since it won't remove all of it
2383 $other = clone($att);
2389 function clearReplies()
2391 $replyNotice = new Notice();
2392 $replyNotice->reply_to = $this->id;
2394 //Null any notices that are replies to this notice
2396 if ($replyNotice->find()) {
2397 while ($replyNotice->fetch()) {
2398 $orig = clone($replyNotice);
2399 $replyNotice->reply_to = null;
2400 $replyNotice->update($orig);
2406 $reply = new Reply();
2407 $reply->notice_id = $this->id;
2409 if ($reply->find()) {
2410 while($reply->fetch()) {
2411 self::blow('reply:stream:%d', $reply->profile_id);
2419 function clearLocation()
2421 $loc = new Notice_location();
2422 $loc->notice_id = $this->id;
2429 function clearFiles()
2431 $f2p = new File_to_post();
2433 $f2p->post_id = $this->id;
2436 while ($f2p->fetch()) {
2440 // FIXME: decide whether to delete File objects
2441 // ...and related (actual) files
2444 function clearRepeats()
2446 $repeatNotice = new Notice();
2447 $repeatNotice->repeat_of = $this->id;
2449 //Null any notices that are repeats of this notice
2451 if ($repeatNotice->find()) {
2452 while ($repeatNotice->fetch()) {
2453 $orig = clone($repeatNotice);
2454 $repeatNotice->repeat_of = null;
2455 $repeatNotice->update($orig);
2460 function clearTags()
2462 $tag = new Notice_tag();
2463 $tag->notice_id = $this->id;
2466 while ($tag->fetch()) {
2467 self::blow('profile:notice_ids_tagged:%d:%s', $this->profile_id, Cache::keyize($tag->tag));
2468 self::blow('profile:notice_ids_tagged:%d:%s;last', $this->profile_id, Cache::keyize($tag->tag));
2469 self::blow('notice_tag:notice_ids:%s', Cache::keyize($tag->tag));
2470 self::blow('notice_tag:notice_ids:%s;last', Cache::keyize($tag->tag));
2478 function clearGroupInboxes()
2480 $gi = new Group_inbox();
2482 $gi->notice_id = $this->id;
2485 while ($gi->fetch()) {
2486 self::blow('user_group:notice_ids:%d', $gi->group_id);
2494 function distribute()
2496 // We always insert for the author so they don't
2498 Event::handle('StartNoticeDistribute', array($this));
2500 // If there's a failure, we want to _force_
2501 // distribution at this point.
2503 $json = json_encode((object)array('id' => $this->getID(),
2506 $qm = QueueManager::get();
2507 $qm->enqueue($json, 'distrib');
2508 } catch (Exception $e) {
2509 // If the exception isn't transient, this
2510 // may throw more exceptions as DQH does
2511 // its own enqueueing. So, we ignore them!
2513 $handler = new DistribQueueHandler();
2514 $handler->handle($this);
2515 } catch (Exception $e) {
2516 common_log(LOG_ERR, "emergency redistribution resulted in " . $e->getMessage());
2518 // Re-throw so somebody smarter can handle it.
2525 $result = parent::insert();
2527 if ($result === false) {
2528 common_log_db_error($this, 'INSERT', __FILE__);
2529 // TRANS: Server exception thrown when a stored object entry cannot be saved.
2530 throw new ServerException('Could not save Notice');
2533 // Profile::hasRepeated() abuses pkeyGet(), so we
2534 // have to clear manually
2535 if (!empty($this->repeat_of)) {
2536 $c = self::memcache();
2538 $ck = self::multicacheKey('Notice',
2539 array('profile_id' => $this->profile_id,
2540 'repeat_of' => $this->repeat_of));
2545 // Update possibly ID-dependent columns: URI, conversation
2546 // (now that INSERT has added the notice's local id)
2547 $orig = clone($this);
2550 // We can only get here if it's a local notice, since remote notices
2551 // should've bailed out earlier due to lacking a URI.
2552 if (empty($this->uri)) {
2553 $this->uri = sprintf('%s%s=%d:%s=%s',
2555 'noticeId', $this->id,
2556 'objectType', $this->getObjectType(true));
2560 if ($changed && $this->update($orig) === false) {
2561 common_log_db_error($notice, 'UPDATE', __FILE__);
2562 // TRANS: Server exception thrown when a notice cannot be updated.
2563 throw new ServerException(_('Problem saving notice.'));
2566 $this->blowOnInsert();
2572 * Get the source of the notice
2574 * @return Notice_source $ns A notice source object. 'code' is the only attribute
2575 * guaranteed to be populated.
2577 function getSource()
2579 if (empty($this->source)) {
2583 $ns = new Notice_source();
2584 switch ($this->source) {
2591 $ns->code = $this->source;
2594 $ns = Notice_source::getKV($this->source);
2596 $ns = new Notice_source();
2597 $ns->code = $this->source;
2598 $app = Oauth_application::getKV('name', $this->source);
2600 $ns->name = $app->name;
2601 $ns->url = $app->source_url;
2611 * Determine whether the notice was locally created
2613 * @return boolean locality
2616 public function isLocal()
2618 $is_local = intval($this->is_local);
2619 return ($is_local === self::LOCAL_PUBLIC || $is_local === self::LOCAL_NONPUBLIC);
2622 public function getScope()
2624 return intval($this->scope);
2627 public function isRepeat()
2629 return !empty($this->repeat_of);
2632 public function isRepeated()
2635 $n->repeat_of = $this->getID();
2636 return $n->find() && $n->N > 0;
2640 * Get the list of hash tags saved with this notice.
2642 * @return array of strings
2644 public function getTags()
2648 $keypart = sprintf('notice:tags:%d', $this->id);
2650 $tagstr = self::cacheGet($keypart);
2652 if ($tagstr !== false) {
2653 $tags = explode(',', $tagstr);
2655 $tag = new Notice_tag();
2656 $tag->notice_id = $this->id;
2658 while ($tag->fetch()) {
2659 $tags[] = $tag->tag;
2662 self::cacheSet($keypart, implode(',', $tags));
2668 static private function utcDate($dt)
2670 $dateStr = date('d F Y H:i:s', strtotime($dt));
2671 $d = new DateTime($dateStr, new DateTimeZone('UTC'));
2672 return $d->format(DATE_W3C);
2676 * Look up the creation timestamp for a given notice ID, even
2677 * if it's been deleted.
2680 * @return mixed string recorded creation timestamp, or false if can't be found
2682 public static function getAsTimestamp($id)
2685 throw new EmptyPkeyValueException('Notice', 'id');
2689 if (Event::handle('GetNoticeSqlTimestamp', array($id, &$timestamp))) {
2690 // getByID throws exception if $id isn't found
2691 $notice = Notice::getByID($id);
2692 $timestamp = $notice->created;
2695 if (empty($timestamp)) {
2696 throw new ServerException('No timestamp found for Notice with id=='._ve($id));
2702 * Build an SQL 'where' fragment for timestamp-based sorting from a since_id
2703 * parameter, matching notices posted after the given one (exclusive).
2705 * If the referenced notice can't be found, will return false.
2708 * @param string $idField
2709 * @param string $createdField
2710 * @return mixed string or false if no match
2712 public static function whereSinceId($id, $idField='id', $createdField='created')
2715 $since = Notice::getAsTimestamp($id);
2716 } catch (Exception $e) {
2719 return sprintf("($createdField = '%s' and $idField > %d) or ($createdField > '%s')", $since, $id, $since);
2723 * Build an SQL 'where' fragment for timestamp-based sorting from a since_id
2724 * parameter, matching notices posted after the given one (exclusive), and
2725 * if necessary add it to the data object's query.
2727 * @param DB_DataObject $obj
2729 * @param string $idField
2730 * @param string $createdField
2731 * @return mixed string or false if no match
2733 public static function addWhereSinceId(DB_DataObject $obj, $id, $idField='id', $createdField='created')
2735 $since = self::whereSinceId($id, $idField, $createdField);
2737 $obj->whereAdd($since);
2742 * Build an SQL 'where' fragment for timestamp-based sorting from a max_id
2743 * parameter, matching notices posted before the given one (inclusive).
2745 * If the referenced notice can't be found, will return false.
2748 * @param string $idField
2749 * @param string $createdField
2750 * @return mixed string or false if no match
2752 public static function whereMaxId($id, $idField='id', $createdField='created')
2755 $max = Notice::getAsTimestamp($id);
2756 } catch (Exception $e) {
2759 return sprintf("($createdField < '%s') or ($createdField = '%s' and $idField <= %d)", $max, $max, $id);
2763 * Build an SQL 'where' fragment for timestamp-based sorting from a max_id
2764 * parameter, matching notices posted before the given one (inclusive), and
2765 * if necessary add it to the data object's query.
2767 * @param DB_DataObject $obj
2769 * @param string $idField
2770 * @param string $createdField
2771 * @return mixed string or false if no match
2773 public static function addWhereMaxId(DB_DataObject $obj, $id, $idField='id', $createdField='created')
2775 $max = self::whereMaxId($id, $idField, $createdField);
2777 $obj->whereAdd($max);
2781 public function isPublic()
2783 $is_local = intval($this->is_local);
2784 return !($is_local === Notice::LOCAL_NONPUBLIC || $is_local === Notice::GATEWAY);
2788 * Check that the given profile is allowed to read, respond to, or otherwise
2789 * act on this notice.
2791 * The $scope member is a bitmask of scopes, representing a logical AND of the
2792 * scope requirement. So, 0x03 (Notice::ADDRESSEE_SCOPE | Notice::SITE_SCOPE) means
2793 * "only visible to people who are mentioned in the notice AND are users on this site."
2794 * Users on the site who are not mentioned in the notice will not be able to see the
2797 * @param Profile $profile The profile to check; pass null to check for public/unauthenticated users.
2799 * @return boolean whether the profile is in the notice's scope
2801 function inScope($profile)
2803 if (is_null($profile)) {
2804 $keypart = sprintf('notice:in-scope-for:%d:null', $this->id);
2806 $keypart = sprintf('notice:in-scope-for:%d:%d', $this->id, $profile->id);
2809 $result = self::cacheGet($keypart);
2811 if ($result === false) {
2813 if (Event::handle('StartNoticeInScope', array($this, $profile, &$bResult))) {
2814 $bResult = $this->_inScope($profile);
2815 Event::handle('EndNoticeInScope', array($this, $profile, &$bResult));
2817 $result = ($bResult) ? 1 : 0;
2818 self::cacheSet($keypart, $result, 0, 300);
2821 return ($result == 1) ? true : false;
2824 protected function _inScope($profile)
2826 $scope = is_null($this->scope) ? self::defaultScope() : $this->getScope();
2828 if ($scope === 0 && !$this->getProfile()->isPrivateStream()) { // Not scoping, so it is public.
2829 return !$this->isHiddenSpam($profile);
2832 // If there's scope, anon cannot be in scope
2833 if (empty($profile)) {
2837 // Author is always in scope
2838 if ($this->profile_id == $profile->id) {
2842 // Only for users on this site
2843 if (($scope & Notice::SITE_SCOPE) && !$profile->isLocal()) {
2847 // Only for users mentioned in the notice
2848 if ($scope & Notice::ADDRESSEE_SCOPE) {
2850 $reply = Reply::pkeyGet(array('notice_id' => $this->id,
2851 'profile_id' => $profile->id));
2853 if (!$reply instanceof Reply) {
2858 // Only for members of the given group
2859 if ($scope & Notice::GROUP_SCOPE) {
2861 // XXX: just query for the single membership
2863 $groups = $this->getGroups();
2867 foreach ($groups as $group) {
2868 if ($profile->isMember($group)) {
2879 if ($scope & Notice::FOLLOWER_SCOPE || $this->getProfile()->isPrivateStream()) {
2881 if (!Subscription::exists($profile, $this->getProfile())) {
2886 return !$this->isHiddenSpam($profile);
2889 function isHiddenSpam($profile) {
2891 // Hide posts by silenced users from everyone but moderators.
2893 if (common_config('notice', 'hidespam')) {
2896 $author = $this->getProfile();
2897 } catch(Exception $e) {
2898 // If we can't get an author, keep it hidden.
2899 // XXX: technically not spam, but, whatever.
2903 if ($author->hasRole(Profile_role::SILENCED)) {
2904 if (!$profile instanceof Profile || (($profile->id !== $author->id) && (!$profile->hasRight(Right::REVIEWSPAM)))) {
2913 public function hasParent()
2917 } catch (NoParentNoticeException $e) {
2923 public function getParent()
2925 $reply_to_id = null;
2927 if (empty($this->reply_to)) {
2928 throw new NoParentNoticeException($this);
2931 // The reply_to ID in the table Notice could exist with a number
2932 // however, the replied to notice might not exist in the database.
2933 // Thus we need to catch the exception and throw the NoParentNoticeException else
2934 // the timeline will not display correctly.
2936 $reply_to_id = self::getByID($this->reply_to);
2937 } catch(Exception $e){
2938 throw new NoParentNoticeException($this);
2941 return $reply_to_id;
2945 * Magic function called at serialize() time.
2947 * We use this to drop a couple process-specific references
2948 * from DB_DataObject which can cause trouble in future
2951 * @return array of variable names to include in serialization.
2956 $vars = parent::__sleep();
2957 $skip = array('_profile', '_groups', '_attachments', '_faves', '_replies', '_repeats');
2958 return array_diff($vars, $skip);
2961 static function defaultScope()
2963 $scope = common_config('notice', 'defaultscope');
2964 if (is_null($scope)) {
2965 if (common_config('site', 'private')) {
2974 static function fillProfiles($notices)
2976 $map = self::getProfiles($notices);
2977 foreach ($notices as $entry=>$notice) {
2979 if (array_key_exists($notice->profile_id, $map)) {
2980 $notice->_setProfile($map[$notice->profile_id]);
2982 } catch (NoProfileException $e) {
2983 common_log(LOG_WARNING, "Failed to fill profile in Notice with non-existing entry for profile_id: {$e->profile_id}");
2984 unset($notices[$entry]);
2988 return array_values($map);
2991 static function getProfiles(&$notices)
2994 foreach ($notices as $notice) {
2995 $ids[] = $notice->profile_id;
2997 $ids = array_unique($ids);
2998 return Profile::pivotGet('id', $ids);
3001 static function fillGroups(&$notices)
3003 $ids = self::_idsOf($notices);
3004 $gis = Group_inbox::listGet('notice_id', $ids);
3007 foreach ($gis as $id => $gi) {
3010 $gids[] = $g->group_id;
3014 $gids = array_unique($gids);
3015 $group = User_group::pivotGet('id', $gids);
3016 foreach ($notices as $notice)
3019 $gi = $gis[$notice->id];
3020 foreach ($gi as $g) {
3021 $grps[] = $group[$g->group_id];
3023 $notice->_setGroups($grps);
3027 static function _idsOf(array &$notices)
3030 foreach ($notices as $notice) {
3031 $ids[$notice->id] = true;
3033 return array_keys($ids);
3036 static function fillAttachments(&$notices)
3038 $ids = self::_idsOf($notices);
3039 $f2pMap = File_to_post::listGet('post_id', $ids);
3041 foreach ($f2pMap as $noticeId => $f2ps) {
3042 foreach ($f2ps as $f2p) {
3043 $fileIds[] = $f2p->file_id;
3047 $fileIds = array_unique($fileIds);
3048 $fileMap = File::pivotGet('id', $fileIds);
3049 foreach ($notices as $notice)
3052 $f2ps = $f2pMap[$notice->id];
3053 foreach ($f2ps as $f2p) {
3054 if (!isset($fileMap[$f2p->file_id])) {
3055 // We have probably deleted value from fileMap since
3056 // it as a NULL entry (see the following elseif).
3058 } elseif (is_null($fileMap[$f2p->file_id])) {
3059 // If the file id lookup returned a NULL value, it doesn't
3060 // exist in our file table! So this is a remnant file_to_post
3061 // entry that is no longer valid and should be removed.
3062 common_debug('ATTACHMENT deleting f2p for post_id='.$f2p->post_id.' file_id='.$f2p->file_id);
3064 unset($fileMap[$f2p->file_id]);
3067 $files[] = $fileMap[$f2p->file_id];
3069 $notice->_setAttachments($files);
3073 static function fillReplies(&$notices)
3075 $ids = self::_idsOf($notices);
3076 $replyMap = Reply::listGet('notice_id', $ids);
3077 foreach ($notices as $notice) {
3078 $replies = $replyMap[$notice->id];
3080 foreach ($replies as $reply) {
3081 $ids[] = $reply->profile_id;
3083 $notice->_setReplies($ids);
3087 static public function beforeSchemaUpdate()
3089 $table = strtolower(get_called_class());
3090 $schema = Schema::get();
3091 $schemadef = $schema->getTableDef($table);
3093 // 2015-09-04 We move Notice location data to Notice_location
3094 // First we see if we have to do this at all
3095 if (isset($schemadef['fields']['lat'])
3096 && isset($schemadef['fields']['lon'])
3097 && isset($schemadef['fields']['location_id'])
3098 && isset($schemadef['fields']['location_ns'])) {
3099 // Then we make sure the Notice_location table is created!
3100 $schema->ensureTable('notice_location', Notice_location::schemaDef());
3102 // Then we continue on our road to migration!
3103 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)";
3105 $notice = new Notice();
3106 $notice->query(sprintf('SELECT id, lat, lon, location_id, location_ns FROM %1$s ' .
3107 'WHERE lat IS NOT NULL ' .
3108 'OR lon IS NOT NULL ' .
3109 'OR location_id IS NOT NULL ' .
3110 'OR location_ns IS NOT NULL',
3111 $schema->quoteIdentifier($table)));
3112 print "\nFound {$notice->N} notices with location data, inserting";
3113 while ($notice->fetch()) {
3114 $notloc = Notice_location::getKV('notice_id', $notice->id);
3115 if ($notloc instanceof Notice_location) {
3119 $notloc = new Notice_location();
3120 $notloc->notice_id = $notice->id;
3121 $notloc->lat= $notice->lat;
3122 $notloc->lon= $notice->lon;
3123 $notloc->location_id= $notice->location_id;
3124 $notloc->location_ns= $notice->location_ns;
3132 * Make sure constraints are met before upgrading, if foreign keys
3133 * are not already in use.
3136 if (!isset($schemadef['foreign keys'])) {
3137 $newschemadef = self::schemaDef();
3138 printfnq("\nConstraint checking Notice table...\n");
3140 * Improve typing and make sure no NULL values in any id-related columns are 0
3143 foreach (['reply_to', 'repeat_of'] as $field) {
3144 $notice = new Notice(); // reset the object
3145 $notice->query(sprintf('UPDATE %1$s SET %2$s=NULL WHERE %2$s=0', $notice->escapedTableName(), $field));
3146 // Now we're sure that no Notice entries have repeat_of=0, only an id > 0 or NULL
3151 * This Will find foreign keys which do not fulfill the constraints and fix
3152 * where appropriate, such as delete when "repeat_of" ID not found in notice.id
3153 * or set to NULL for "reply_to" in the same case.
3156 * XXX: How does this work if we would use multicolumn foreign keys?
3158 foreach (['reply_to' => 'reset', 'repeat_of' => 'delete', 'profile_id' => 'delete'] as $field=>$action) {
3159 $notice = new Notice();
3161 $fkeyname = $notice->tableName().'_'.$field.'_fkey';
3162 assert(isset($newschemadef['foreign keys'][$fkeyname]));
3163 assert($newschemadef['foreign keys'][$fkeyname]);
3165 $foreign_key = $newschemadef['foreign keys'][$fkeyname];
3166 $fkeytable = $foreign_key[0];
3167 assert(isset($foreign_key[1][$field]));
3168 $fkeycol = $foreign_key[1][$field];
3170 printfnq("* {$fkeyname} ({$field} => {$fkeytable}.{$fkeycol})\n");
3172 // NOTE: Above we set all repeat_of to NULL if they were 0, so this really gets them all.
3173 $notice->whereAdd(sprintf('%1$s NOT IN (SELECT %2$s FROM %3$s)', $field, $fkeycol, $fkeytable));
3174 if ($notice->find()) {
3175 printfnq("\tFound {$notice->N} notices with {$field} NOT IN notice.id, {$action}ing...");
3177 case 'delete': // since it's a directly dependant notice for an unknown ID we don't want it in our DB
3178 while ($notice->fetch()) {
3182 case 'reset': // just set it to NULL to be compatible with our constraints, if it was related to an unknown ID
3184 foreach ($notice->fetchAll('id') as $id) {
3185 settype($id, 'int');
3189 $notice = new Notice();
3190 $notice->query(sprintf('UPDATE %1$s SET %2$s=NULL WHERE id IN (%3$s)',
3191 $notice->escapedTableName(),
3193 implode(',', $ids)));
3196 throw new ServerException('The programmer sucks, invalid action name when fixing table.');
3198 printfnq("DONE.\n");