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_replyto_idx' => array('reply_to')
118 if (common_config('search', 'type') == 'fulltext') {
119 $def['fulltext indexes'] = array('content' => array('content'));
126 const LOCAL_PUBLIC = 1;
128 const LOCAL_NONPUBLIC = -1;
131 const PUBLIC_SCOPE = 0; // Useful fake constant
132 const SITE_SCOPE = 1;
133 const ADDRESSEE_SCOPE = 2;
134 const GROUP_SCOPE = 4;
135 const FOLLOWER_SCOPE = 8;
137 protected $_profile = array();
140 * Will always return a profile, if anything fails it will
141 * (through _setProfile) throw a NoProfileException.
143 public function getProfile()
145 if (!isset($this->_profile[$this->profile_id])) {
146 // We could've sent getKV directly to _setProfile, but occasionally we get
147 // a "false" (instead of null), likely because it indicates a cache miss.
148 $profile = Profile::getKV('id', $this->profile_id);
149 $this->_setProfile($profile instanceof Profile ? $profile : null);
151 return $this->_profile[$this->profile_id];
154 public function _setProfile(Profile $profile=null)
156 if (!$profile instanceof Profile) {
157 throw new NoProfileException($this->profile_id);
159 $this->_profile[$this->profile_id] = $profile;
162 public function deleteAs(Profile $actor, $delete_event=true)
164 if (!$this->getProfile()->sameAs($actor) && !$actor->hasRight(Right::DELETEOTHERSNOTICE)) {
165 throw new AuthorizationException(_('You are not allowed to delete another user\'s notice.'));
168 if (Event::handle('NoticeDeleteRelated', array($this))) {
169 // Clear related records
170 $this->clearReplies();
171 $this->clearLocation();
172 $this->clearRepeats();
174 $this->clearGroupInboxes();
176 $this->clearAttentions();
177 // NOTE: we don't clear queue items
181 if (!$delete_event || Event::handle('DeleteNoticeAsProfile', array($this, $actor, &$result))) {
182 // If $delete_event is true, we run the event. If the Event then
183 // returns false it is assumed everything was handled properly
184 // and the notice was deleted.
185 $result = $this->delete();
190 public function delete($useWhere=false)
192 $result = parent::delete($useWhere);
194 $this->blowOnDelete();
198 public function getUri()
204 * Get a Notice object by URI. Will call external plugins for help
205 * using the event StartGetNoticeFromURI.
207 * @param string $uri A unique identifier for a resource (notice in this case)
209 static function fromUri($uri)
213 if (Event::handle('StartGetNoticeFromUri', array($uri, &$notice))) {
214 $notice = Notice::getKV('uri', $uri);
215 Event::handle('EndGetNoticeFromUri', array($uri, $notice));
218 if (!$notice instanceof Notice) {
219 throw new UnknownUriException($uri);
226 * @param $root boolean If true, link to just the conversation root.
228 * @return URL to conversation
230 public function getConversationUrl($anchor=true)
232 return Conversation::getUrlFromNotice($this, $anchor);
236 * Get the local representation URL of this notice.
238 public function getLocalUrl()
240 return common_local_url('shownotice', array('notice' => $this->id), null, null, false);
243 public function getTitle()
246 if (Event::handle('GetNoticeTitle', array($this, &$title))) {
247 // TRANS: Title of a notice posted without a title value.
248 // TRANS: %1$s is a user name, %2$s is the notice creation date/time.
249 $title = sprintf(_('%1$s\'s status on %2$s'),
250 $this->getProfile()->getFancyName(),
251 common_exact_date($this->created));
256 public function getContent()
258 return $this->content;
261 public function getRendered()
263 // we test $this->id because if it's not inserted yet, we can't update the field
264 if (!empty($this->id) && (is_null($this->rendered) || $this->rendered === '')) {
265 // update to include rendered content on-the-fly, so we don't have to have a fix-up script in upgrade.php
266 common_debug('Rendering notice '.$this->getID().' as it had no rendered HTML content.');
267 $orig = clone($this);
268 $this->rendered = common_render_content($this->getContent(),
270 $this->hasParent() ? $this->getParent() : null);
271 $this->update($orig);
273 return $this->rendered;
276 public function getCreated()
278 return $this->created;
281 public function getVerb($make_relative=false)
283 return ActivityUtils::resolveUri($this->verb, $make_relative);
286 public function isVerb(array $verbs)
288 return ActivityUtils::compareVerbs($this->getVerb(), $verbs);
292 * Get the original representation URL of this notice.
294 * @param boolean $fallback Whether to fall back to generate a local URL or throw InvalidUrlException
296 public function getUrl($fallback=false)
298 // The risk is we start having empty urls and non-http uris...
299 // and we can't really handle any other protocol right now.
301 case $this->isLocal():
302 return common_local_url('shownotice', array('notice' => $this->getID()), null, null, false);
303 case common_valid_http_url($this->url): // should we allow non-http/https URLs?
305 case common_valid_http_url($this->uri): // Sometimes we only have the URI for remote posts.
308 // let's generate a valid link to our locally available notice on demand
309 return common_local_url('shownotice', array('notice' => $this->getID()), null, null, false);
311 common_debug('No URL available for notice: id='.$this->getID());
312 throw new InvalidUrlException($this->url);
316 public function getObjectType($canonical=false) {
317 if (is_null($this->object_type) || $this->object_type==='') {
318 throw new NoObjectTypeException($this);
320 return ActivityUtils::resolveUri($this->object_type, $canonical);
323 public function isObjectType(array $types)
326 return ActivityUtils::compareTypes($this->getObjectType(), $types);
327 } catch (NoObjectTypeException $e) {
332 public static function getByUri($uri)
334 $notice = new Notice();
336 if (!$notice->find(true)) {
337 throw new NoResultException($notice);
343 * Extract #hashtags from this notice's content and save them to the database.
347 /* extract all #hastags */
348 $count = preg_match_all('/(?:^|\s)#([\pL\pN_\-\.]{1,64})/u', strtolower($this->content), $match);
353 /* Add them to the database */
354 return $this->saveKnownTags($match[1]);
358 * Record the given set of hash tags in the db for this notice.
359 * Given tag strings will be normalized and checked for dupes.
361 function saveKnownTags($hashtags)
363 //turn each into their canonical tag
364 //this is needed to remove dupes before saving e.g. #hash.tag = #hashtag
365 for($i=0; $i<count($hashtags); $i++) {
366 /* elide characters we don't want in the tag */
367 $hashtags[$i] = common_canonical_tag($hashtags[$i]);
370 foreach(array_unique($hashtags) as $hashtag) {
371 $this->saveTag($hashtag);
372 self::blow('profile:notice_ids_tagged:%d:%s', $this->profile_id, $hashtag);
378 * Record a single hash tag as associated with this notice.
379 * Tag format and uniqueness must be validated by caller.
381 function saveTag($hashtag)
383 $tag = new Notice_tag();
384 $tag->notice_id = $this->id;
385 $tag->tag = $hashtag;
386 $tag->created = $this->created;
387 $id = $tag->insert();
390 // TRANS: Server exception. %s are the error details.
391 throw new ServerException(sprintf(_('Database error inserting hashtag: %s.'),
392 $last_error->message));
396 // if it's saved, blow its cache
397 $tag->blowCache(false);
401 * Save a new notice and push it out to subscribers' inboxes.
402 * Poster's permissions are checked before sending.
404 * @param int $profile_id Profile ID of the poster
405 * @param string $content source message text; links may be shortened
406 * per current user's preference
407 * @param string $source source key ('web', 'api', etc)
408 * @param array $options Associative array of optional properties:
409 * string 'created' timestamp of notice; defaults to now
410 * int 'is_local' source/gateway ID, one of:
411 * Notice::LOCAL_PUBLIC - Local, ok to appear in public timeline
412 * Notice::REMOTE - Sent from a remote service;
413 * hide from public timeline but show in
414 * local "and friends" timelines
415 * Notice::LOCAL_NONPUBLIC - Local, but hide from public timeline
416 * Notice::GATEWAY - From another non-OStatus service;
417 * will not appear in public views
418 * float 'lat' decimal latitude for geolocation
419 * float 'lon' decimal longitude for geolocation
420 * int 'location_id' geoname identifier
421 * int 'location_ns' geoname namespace to interpret location_id
422 * int 'reply_to'; notice ID this is a reply to
423 * int 'repeat_of'; notice ID this is a repeat of
424 * string 'uri' unique ID for notice; a unique tag uri (can be url or anything too)
425 * string 'url' permalink to notice; defaults to local notice URL
426 * string 'rendered' rendered HTML version of content
427 * array 'replies' list of profile URIs for reply delivery in
428 * place of extracting @-replies from content.
429 * array 'groups' list of group IDs to deliver to, in place of
430 * extracting ! tags from content
431 * array 'tags' list of hashtag strings to save with the notice
432 * in place of extracting # tags from content
433 * array 'urls' list of attached/referred URLs to save with the
434 * notice in place of extracting links from content
435 * boolean 'distribute' whether to distribute the notice, default true
436 * string 'object_type' URL of the associated object type (default ActivityObject::NOTE)
437 * string 'verb' URL of the associated verb (default ActivityVerb::POST)
438 * int 'scope' Scope bitmask; default to SITE_SCOPE on private sites, 0 otherwise
440 * @fixme tag override
443 * @throws ClientException
445 static function saveNew($profile_id, $content, $source, array $options=null) {
446 $defaults = array('uri' => null,
448 'conversation' => null, // URI of conversation
449 'reply_to' => null, // This will override convo URI if the parent is known
450 'repeat_of' => null, // This will override convo URI if the repeated notice is known
452 'distribute' => true,
453 'object_type' => null,
456 if (!empty($options) && is_array($options)) {
457 $options = array_merge($defaults, $options);
463 if (!isset($is_local)) {
464 $is_local = Notice::LOCAL_PUBLIC;
467 $profile = Profile::getKV('id', $profile_id);
468 if (!$profile instanceof Profile) {
469 // TRANS: Client exception thrown when trying to save a notice for an unknown user.
470 throw new ClientException(_('Problem saving notice. Unknown user.'));
473 $user = User::getKV('id', $profile_id);
474 if ($user instanceof User) {
475 // Use the local user's shortening preferences, if applicable.
476 $final = $user->shortenLinks($content);
478 $final = common_shorten_links($content);
481 if (Notice::contentTooLong($final)) {
482 // TRANS: Client exception thrown if a notice contains too many characters.
483 throw new ClientException(_('Problem saving notice. Too long.'));
486 if (common_config('throttle', 'enabled') && !Notice::checkEditThrottle($profile_id)) {
487 common_log(LOG_WARNING, 'Excessive posting by profile #' . $profile_id . '; throttled.');
488 // TRANS: Client exception thrown when a user tries to post too many notices in a given time frame.
489 throw new ClientException(_('Too many notices too fast; take a breather '.
490 'and post again in a few minutes.'));
493 if (common_config('site', 'dupelimit') > 0 && !Notice::checkDupes($profile_id, $final)) {
494 common_log(LOG_WARNING, 'Dupe posting by profile #' . $profile_id . '; throttled.');
495 // TRANS: Client exception thrown when a user tries to post too many duplicate notices in a given time frame.
496 throw new ClientException(_('Too many duplicate messages too quickly;'.
497 ' take a breather and post again in a few minutes.'));
500 if (!$profile->hasRight(Right::NEWNOTICE)) {
501 common_log(LOG_WARNING, "Attempted post from user disallowed to post: " . $profile->nickname);
503 // TRANS: Client exception thrown when a user tries to post while being banned.
504 throw new ClientException(_('You are banned from posting notices on this site.'), 403);
507 $notice = new Notice();
508 $notice->profile_id = $profile_id;
510 if ($source && in_array($source, common_config('public', 'autosource'))) {
511 $notice->is_local = Notice::LOCAL_NONPUBLIC;
513 $notice->is_local = $is_local;
516 if (!empty($created)) {
517 $notice->created = $created;
519 $notice->created = common_sql_now();
522 if (!$notice->isLocal()) {
523 // Only do these checks for non-local notices. Local notices will generate these values later.
524 if (!common_valid_http_url($url)) {
525 common_debug('Bad notice URL: ['.$url.'], URI: ['.$uri.']. Cannot link back to original! This is normal for shared notices etc.');
528 throw new ServerException('No URI for remote notice. Cannot accept that.');
532 $notice->content = $final;
534 $notice->source = $source;
538 // Get the groups here so we can figure out replies and such
539 if (!isset($groups)) {
540 $groups = User_group::idsFromText($notice->content, $profile);
545 // Handle repeat case
547 if (!empty($options['repeat_of'])) {
549 // Check for a private one
551 $repeat = Notice::getByID($options['repeat_of']);
553 if ($profile->sameAs($repeat->getProfile())) {
554 // TRANS: Client error displayed when trying to repeat an own notice.
555 throw new ClientException(_('You cannot repeat your own notice.'));
558 if ($repeat->scope != Notice::SITE_SCOPE &&
559 $repeat->scope != Notice::PUBLIC_SCOPE) {
560 // TRANS: Client error displayed when trying to repeat a non-public notice.
561 throw new ClientException(_('Cannot repeat a private notice.'), 403);
564 if (!$repeat->inScope($profile)) {
565 // The generic checks above should cover this, but let's be sure!
566 // TRANS: Client error displayed when trying to repeat a notice you cannot access.
567 throw new ClientException(_('Cannot repeat a notice you cannot read.'), 403);
570 if ($profile->hasRepeated($repeat)) {
571 // TRANS: Client error displayed when trying to repeat an already repeated notice.
572 throw new ClientException(_('You already repeated that notice.'));
575 $notice->repeat_of = $repeat->id;
576 $notice->conversation = $repeat->conversation;
580 // If $reply_to is specified, we check that it exists, and then
581 // return it if it does
582 if (!empty($reply_to)) {
583 $reply = Notice::getKV('id', $reply_to);
584 } elseif (in_array($source, array('xmpp', 'mail', 'sms'))) {
585 // If the source lacks capability of sending the "reply_to"
586 // metadata, let's try to find an inline replyto-reference.
587 $reply = self::getInlineReplyTo($profile, $final);
590 if ($reply instanceof Notice) {
591 if (!$reply->inScope($profile)) {
592 // TRANS: Client error displayed when trying to reply to a notice a the target has no access to.
593 // TRANS: %1$s is a user nickname, %2$d is a notice ID (number).
594 throw new ClientException(sprintf(_('%1$s has no access to notice %2$d.'),
595 $profile->nickname, $reply->id), 403);
598 // If it's a repeat, the reply_to should be to the original
599 if ($reply->isRepeat()) {
600 $notice->reply_to = $reply->repeat_of;
602 $notice->reply_to = $reply->id;
604 // But the conversation ought to be the same :)
605 $notice->conversation = $reply->conversation;
607 // If the original is private to a group, and notice has
608 // no group specified, make it to the same group(s)
610 if (empty($groups) && ($reply->scope & Notice::GROUP_SCOPE)) {
612 $replyGroups = $reply->getGroups();
613 foreach ($replyGroups as $group) {
614 if ($profile->isMember($group)) {
615 $groups[] = $group->id;
623 // If we don't know the reply, we might know the conversation!
624 // This will happen if a known remote user replies to an
625 // unknown remote user - within a known conversation.
626 if (empty($notice->conversation) and !empty($options['conversation'])) {
627 $conv = Conversation::getKV('uri', $options['conversation']);
628 if ($conv instanceof Conversation) {
629 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.').');
631 // Conversation entry with specified URI was not found, so we must create it.
632 common_debug('Conversation URI not found, so we will create it with the URI given in the options to Notice::saveNew: '.$options['conversation']);
633 // The insert in Conversation::create throws exception on failure
634 $conv = Conversation::create($options['conversation'], $notice->created);
636 $notice->conversation = $conv->getID();
641 // If it's not part of a conversation, it's the beginning of a new conversation.
642 if (empty($notice->conversation)) {
643 $conv = Conversation::create();
644 $notice->conversation = $conv->getID();
649 $notloc = new Notice_location();
650 if (!empty($lat) && !empty($lon)) {
655 if (!empty($location_ns) && !empty($location_id)) {
656 $notloc->location_id = $location_id;
657 $notloc->location_ns = $location_ns;
660 if (!empty($rendered)) {
661 $notice->rendered = $rendered;
663 $notice->rendered = common_render_content($final,
664 $notice->getProfile(),
665 $notice->hasParent() ? $notice->getParent() : null);
669 if ($notice->isRepeat()) {
670 $notice->verb = ActivityVerb::SHARE;
671 $notice->object_type = ActivityObject::ACTIVITY;
673 $notice->verb = ActivityVerb::POST;
676 $notice->verb = $verb;
679 if (empty($object_type)) {
680 $notice->object_type = (empty($notice->reply_to)) ? ActivityObject::NOTE : ActivityObject::COMMENT;
682 $notice->object_type = $object_type;
685 if (is_null($scope) && $reply instanceof Notice) {
686 $notice->scope = $reply->scope;
688 $notice->scope = $scope;
691 $notice->scope = self::figureOutScope($profile, $groups, $notice->scope);
693 if (Event::handle('StartNoticeSave', array(&$notice))) {
695 // XXX: some of these functions write to the DB
698 $notice->insert(); // throws exception on failure, if successful we have an ->id
700 if (($notloc->lat && $notloc->lon) || ($notloc->location_id && $notloc->location_ns)) {
701 $notloc->notice_id = $notice->getID();
702 $notloc->insert(); // store the notice location if it had any information
704 } catch (Exception $e) {
705 // Let's test if we managed initial insert, which would imply
706 // failing on some update-part (check 'insert()'). Delete if
707 // something had been stored to the database.
708 if (!empty($notice->id)) {
715 // Only save 'attention' and metadata stuff (URLs, tags...) stuff if
716 // the activityverb is a POST (since stuff like repeat, favorite etc.
717 // reasonably handle notifications themselves.
718 if (ActivityUtils::compareVerbs($notice->verb, array(ActivityVerb::POST))) {
719 if (isset($replies)) {
720 $notice->saveKnownReplies($replies);
722 $notice->saveReplies();
726 $notice->saveKnownTags($tags);
731 // Note: groups may save tags, so must be run after tags are saved
732 // to avoid errors on duplicates.
733 // Note: groups should always be set.
735 $notice->saveKnownGroups($groups);
738 $notice->saveKnownUrls($urls);
745 // Prepare inbox delivery, may be queued to background.
746 $notice->distribute();
752 static function saveActivity(Activity $act, Profile $actor, array $options=array())
754 // First check if we're going to let this Activity through from the specific actor
755 if (!$actor->hasRight(Right::NEWNOTICE)) {
756 common_log(LOG_WARNING, "Attempted post from user disallowed to post: " . $actor->getNickname());
758 // TRANS: Client exception thrown when a user tries to post while being banned.
759 throw new ClientException(_m('You are banned from posting notices on this site.'), 403);
761 if (common_config('throttle', 'enabled') && !self::checkEditThrottle($actor->id)) {
762 common_log(LOG_WARNING, 'Excessive posting by profile #' . $actor->id . '; throttled.');
763 // TRANS: Client exception thrown when a user tries to post too many notices in a given time frame.
764 throw new ClientException(_m('Too many notices too fast; take a breather '.
765 'and post again in a few minutes.'));
768 // Get ActivityObject properties
770 if (!empty($act->id)) {
772 $options['uri'] = $act->id;
773 $options['url'] = $act->link;
775 $actobj = count($act->objects)===1 ? $act->objects[0] : null;
776 if (!is_null($actobj) && !empty($actobj->id)) {
777 $options['uri'] = $actobj->id;
779 $options['url'] = $actobj->link;
780 } elseif (preg_match('!^https?://!', $actobj->id)) {
781 $options['url'] = $actobj->id;
788 'is_local' => $actor->isLocal() ? self::LOCAL_PUBLIC : self::REMOTE,
789 'mentions' => array(),
793 'source' => 'unknown',
798 'distribute' => true);
800 // options will have default values when nothing has been supplied
801 $options = array_merge($defaults, $options);
802 foreach (array_keys($defaults) as $key) {
803 // Only convert the keynames we specify ourselves from 'defaults' array into variables
804 $$key = $options[$key];
806 extract($options, EXTR_SKIP);
809 $stored = new Notice();
810 if (!empty($uri) && !ActivityUtils::compareVerbs($act->verb, array(ActivityVerb::DELETE))) {
812 if ($stored->find()) {
813 common_debug('cannot create duplicate Notice URI: '.$stored->uri);
814 // I _assume_ saving a Notice with a colliding URI means we're really trying to
815 // save the same notice again...
816 throw new AlreadyFulfilledException('Notice URI already exists');
820 // NOTE: Sandboxed users previously got all the notices _during_
821 // sandbox period set to to is_local=Notice::LOCAL_NONPUBLIC here.
822 // Since then we have started just filtering _when_ it gets shown
823 // instead of creating a mixed jumble of differently scoped notices.
825 if ($source && in_array($source, common_config('public', 'autosource'))) {
826 $stored->is_local = Notice::LOCAL_NONPUBLIC;
828 $stored->is_local = intval($is_local);
831 if (!$stored->isLocal()) {
832 // Only do these checks for non-local notices. Local notices will generate these values later.
833 if (!common_valid_http_url($url)) {
834 common_debug('Bad notice URL: ['.$url.'], URI: ['.$uri.']. Cannot link back to original! This is normal for shared notices etc.');
837 throw new ServerException('No URI for remote notice. Cannot accept that.');
841 $stored->profile_id = $actor->id;
842 $stored->source = $source;
845 $stored->verb = $act->verb;
847 // we use mb_strlen because it _might_ be that the content is just the string "0"...
848 $content = mb_strlen($act->content) ? $act->content : $act->summary;
849 if (mb_strlen($content)===0 && !is_null($actobj)) {
850 $content = mb_strlen($actobj->content) ? $actobj->content : $actobj->summary;
852 // Strip out any bad HTML from $content. URI.Base is used to sort out relative URLs.
853 $stored->rendered = common_purify($content, ['URI.Base' => $stored->url ?: null]);
854 $stored->content = common_strip_html($stored->getRendered(), true, true);
855 if (trim($stored->content) === '') {
856 // TRANS: Error message when the plain text content of a notice has zero length.
857 throw new ClientException(_('Empty notice content, will not save this.'));
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();
868 if ($act->context instanceof ActivityContext && !empty($act->context->replyToID)) {
869 $reply = self::getKV('uri', $act->context->replyToID);
871 if (!$reply instanceof Notice && $act->target instanceof ActivityObject) {
872 $reply = self::getKV('uri', $act->target->id);
875 if ($reply instanceof Notice) {
876 if (!$reply->inScope($actor)) {
877 // TRANS: Client error displayed when trying to reply to a notice a the target has no access to.
878 // TRANS: %1$s is a user nickname, %2$d is a notice ID (number).
879 throw new ClientException(sprintf(_m('%1$s has no right to reply to notice %2$d.'), $actor->getNickname(), $reply->id), 403);
882 $stored->reply_to = $reply->id;
883 $stored->conversation = $reply->conversation;
885 // If the original is private to a group, and notice has no group specified,
886 // make it to the same group(s)
887 if (empty($groups) && ($reply->scope & Notice::GROUP_SCOPE)) {
888 $replyGroups = $reply->getGroups();
889 foreach ($replyGroups as $group) {
890 if ($actor->isMember($group)) {
891 $groups[] = $group->id;
896 if (is_null($scope)) {
897 $scope = $reply->scope;
900 // If we don't know the reply, we might know the conversation!
901 // This will happen if a known remote user replies to an
902 // unknown remote user - within a known conversation.
903 if (empty($stored->conversation) and !empty($act->context->conversation)) {
904 $conv = Conversation::getKV('uri', $act->context->conversation);
905 if ($conv instanceof Conversation) {
906 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.').');
908 // Conversation entry with specified URI was not found, so we must create it.
909 common_debug('Conversation URI not found, so we will create it with the URI given in the context of the activity: '.$act->context->conversation);
910 // The insert in Conversation::create throws exception on failure
911 $conv = Conversation::create($act->context->conversation, $stored->created);
913 $stored->conversation = $conv->getID();
918 // If it's not part of a conversation, it's the beginning of a new conversation.
919 if (empty($stored->conversation)) {
920 $conv = Conversation::create();
921 $stored->conversation = $conv->getID();
926 if ($act->context instanceof ActivityContext) {
927 if ($act->context->location instanceof Location) {
928 $notloc = Notice_location::fromLocation($act->context->location);
931 $act->context = new ActivityContext();
934 $stored->scope = self::figureOutScope($actor, $groups, $scope);
936 foreach ($act->categories as $cat) {
938 $term = common_canonical_tag($cat->term);
945 foreach ($act->enclosures as $href) {
946 // @todo FIXME: Save these locally or....?
950 if (ActivityUtils::compareVerbs($stored->verb, array(ActivityVerb::POST))) {
951 if (empty($act->objects[0]->type)) {
952 // Default type for the post verb is 'note', but we know it's
953 // a 'comment' if it is in reply to something.
954 $stored->object_type = empty($stored->reply_to) ? ActivityObject::NOTE : ActivityObject::COMMENT;
956 //TODO: Is it safe to always return a relative URI? The
957 // JSON version of ActivityStreams always use it, so we
958 // should definitely be able to handle it...
959 $stored->object_type = ActivityUtils::resolveUri($act->objects[0]->type, true);
963 if (Event::handle('StartNoticeSave', array(&$stored))) {
964 // XXX: some of these functions write to the DB
967 $result = $stored->insert(); // throws exception on error
969 if ($notloc instanceof Notice_location) {
970 $notloc->notice_id = $stored->getID();
974 $orig = clone($stored); // for updating later in this try clause
977 Event::handle('StoreActivityObject', array($act, $stored, $options, &$object));
978 if (empty($object)) {
979 throw new NoticeSaveException('Unsuccessful call to StoreActivityObject '._ve($stored->getUri()) . ': '._ve($act->asString()));
982 // If something changed in the Notice during StoreActivityObject
983 $stored->update($orig);
984 } catch (Exception $e) {
985 if (empty($stored->id)) {
986 common_debug('Failed to save stored object entry in database ('.$e->getMessage().')');
988 common_debug('Failed to store activity object in database ('.$e->getMessage().'), deleting notice id '.$stored->id);
994 if (!$stored instanceof Notice) {
995 throw new ServerException('StartNoticeSave did not give back a Notice.');
996 } elseif (empty($stored->id)) {
997 throw new ServerException('Supposedly saved Notice has no ID.');
1000 // Only save 'attention' and metadata stuff (URLs, tags...) stuff if
1001 // the activityverb is a POST (since stuff like repeat, favorite etc.
1002 // reasonably handle notifications themselves.
1003 if (ActivityUtils::compareVerbs($stored->verb, array(ActivityVerb::POST))) {
1005 if (!empty($tags)) {
1006 $stored->saveKnownTags($tags);
1008 $stored->saveTags();
1011 // Note: groups may save tags, so must be run after tags are saved
1012 // to avoid errors on duplicates.
1013 $stored->saveAttentions($act->context->attention);
1015 if (!empty($urls)) {
1016 $stored->saveKnownUrls($urls);
1018 $stored->saveUrls();
1023 // Prepare inbox delivery, may be queued to background.
1024 $stored->distribute();
1030 static public function figureOutScope(Profile $actor, array $groups, $scope=null) {
1031 $scope = is_null($scope) ? self::defaultScope() : intval($scope);
1033 // For private streams
1035 $user = $actor->getUser();
1036 // FIXME: We can't do bit comparison with == (Legacy StatusNet thing. Let's keep it for now.)
1037 if ($user->private_stream && ($scope === Notice::PUBLIC_SCOPE || $scope === Notice::SITE_SCOPE)) {
1038 $scope |= Notice::FOLLOWER_SCOPE;
1040 } catch (NoSuchUserException $e) {
1041 // TODO: Not a local user, so we don't know about scope preferences... yet!
1044 // Force the scope for private groups
1045 foreach ($groups as $group_id) {
1047 $group = User_group::getByID($group_id);
1048 if ($group->force_scope) {
1049 $scope |= Notice::GROUP_SCOPE;
1052 } catch (Exception $e) {
1053 common_log(LOG_ERR, 'Notice figureOutScope threw exception: '.$e->getMessage());
1060 function blowOnInsert($conversation = false)
1062 $this->blowStream('profile:notice_ids:%d', $this->profile_id);
1064 if ($this->isPublic()) {
1065 $this->blowStream('public');
1066 $this->blowStream('networkpublic');
1069 if ($this->conversation) {
1070 self::blow('notice:list-ids:conversation:%s', $this->conversation);
1071 self::blow('conversation:notice_count:%d', $this->conversation);
1074 if ($this->isRepeat()) {
1075 // XXX: we should probably only use one of these
1076 $this->blowStream('notice:repeats:%d', $this->repeat_of);
1077 self::blow('notice:list-ids:repeat_of:%d', $this->repeat_of);
1080 $original = Notice::getKV('id', $this->repeat_of);
1082 if ($original instanceof Notice) {
1083 $originalUser = User::getKV('id', $original->profile_id);
1084 if ($originalUser instanceof User) {
1085 $this->blowStream('user:repeats_of_me:%d', $originalUser->id);
1089 $profile = Profile::getKV($this->profile_id);
1091 if ($profile instanceof Profile) {
1092 $profile->blowNoticeCount();
1095 $ptags = $this->getProfileTags();
1096 foreach ($ptags as $ptag) {
1097 $ptag->blowNoticeStreamCache();
1102 * Clear cache entries related to this notice at delete time.
1103 * Necessary to avoid breaking paging on public, profile timelines.
1105 function blowOnDelete()
1107 $this->blowOnInsert();
1109 self::blow('profile:notice_ids:%d;last', $this->profile_id);
1111 if ($this->isPublic()) {
1112 self::blow('public;last');
1113 self::blow('networkpublic;last');
1116 self::blow('fave:by_notice', $this->id);
1118 if ($this->conversation) {
1119 // In case we're the first, will need to calc a new root.
1120 self::blow('notice:conversation_root:%d', $this->conversation);
1123 $ptags = $this->getProfileTags();
1124 foreach ($ptags as $ptag) {
1125 $ptag->blowNoticeStreamCache(true);
1129 function blowStream()
1131 $c = self::memcache();
1137 $args = func_get_args();
1138 $format = array_shift($args);
1139 $keyPart = vsprintf($format, $args);
1140 $cacheKey = Cache::key($keyPart);
1141 $c->delete($cacheKey);
1143 // delete the "last" stream, too, if this notice is
1144 // older than the top of that stream
1146 $lastKey = $cacheKey.';last';
1148 $lastStr = $c->get($lastKey);
1150 if ($lastStr !== false) {
1151 $window = explode(',', $lastStr);
1152 $lastID = $window[0];
1153 $lastNotice = Notice::getKV('id', $lastID);
1154 if (!$lastNotice instanceof Notice // just weird
1155 || strtotime($lastNotice->created) >= strtotime($this->created)) {
1156 $c->delete($lastKey);
1161 /** save all urls in the notice to the db
1163 * follow redirects and save all available file information
1164 * (mimetype, date, size, oembed, etc.)
1168 function saveUrls() {
1169 if (common_config('attachments', 'process_links')) {
1170 common_replace_urls_callback($this->content, array($this, 'saveUrl'), $this);
1175 * Save the given URLs as related links/attachments to the db
1177 * follow redirects and save all available file information
1178 * (mimetype, date, size, oembed, etc.)
1182 function saveKnownUrls($urls)
1184 if (common_config('attachments', 'process_links')) {
1185 // @fixme validation?
1186 foreach (array_unique($urls) as $url) {
1187 $this->saveUrl($url, $this);
1195 function saveUrl($url, Notice $notice) {
1197 File::processNew($url, $notice);
1198 } catch (ServerException $e) {
1199 // Could not save URL. Log it?
1203 static function checkDupes($profile_id, $content) {
1204 $profile = Profile::getKV($profile_id);
1205 if (!$profile instanceof Profile) {
1208 $notice = $profile->getNotices(0, CachingNoticeStream::CACHE_WINDOW);
1209 if (!empty($notice)) {
1211 while ($notice->fetch()) {
1212 if (time() - strtotime($notice->created) >= common_config('site', 'dupelimit')) {
1214 } else if ($notice->content == $content) {
1219 // If we get here, oldest item in cache window is not
1220 // old enough for dupe limit; do direct check against DB
1221 $notice = new Notice();
1222 $notice->profile_id = $profile_id;
1223 $notice->content = $content;
1224 $threshold = common_sql_date(time() - common_config('site', 'dupelimit'));
1225 $notice->whereAdd(sprintf("created > '%s'", $notice->escape($threshold)));
1227 $cnt = $notice->count();
1231 static function checkEditThrottle($profile_id) {
1232 $profile = Profile::getKV($profile_id);
1233 if (!$profile instanceof Profile) {
1236 // Get the Nth notice
1237 $notice = $profile->getNotices(common_config('throttle', 'count') - 1, 1);
1238 if ($notice && $notice->fetch()) {
1239 // If the Nth notice was posted less than timespan seconds ago
1240 if (time() - strtotime($notice->created) <= common_config('throttle', 'timespan')) {
1245 // Either not N notices in the stream, OR the Nth was not posted within timespan seconds
1249 protected $_attachments = array();
1251 function attachments() {
1252 if (isset($this->_attachments[$this->id])) {
1253 return $this->_attachments[$this->id];
1256 $f2ps = File_to_post::listGet('post_id', array($this->id));
1258 foreach ($f2ps[$this->id] as $f2p) {
1259 $ids[] = $f2p->file_id;
1262 $files = File::multiGet('id', $ids);
1263 $this->_attachments[$this->id] = $files->fetchAll();
1264 return $this->_attachments[$this->id];
1267 function _setAttachments($attachments)
1269 $this->_attachments[$this->id] = $attachments;
1272 static function publicStream($offset=0, $limit=20, $since_id=null, $max_id=null)
1274 $stream = new PublicNoticeStream();
1275 return $stream->getNotices($offset, $limit, $since_id, $max_id);
1278 static function conversationStream($id, $offset=0, $limit=20, $since_id=null, $max_id=null, Profile $scoped=null)
1280 $stream = new ConversationNoticeStream($id, $scoped);
1281 return $stream->getNotices($offset, $limit, $since_id, $max_id);
1285 * Is this notice part of an active conversation?
1287 * @return boolean true if other messages exist in the same
1288 * conversation, false if this is the only one
1290 function hasConversation()
1292 if (empty($this->conversation)) {
1293 // this notice is not part of a conversation apparently
1294 // FIXME: all notices should have a conversation value, right?
1298 //FIXME: Get the Profile::current() stuff some other way
1299 // to avoid confusion between queue processing and session.
1300 $notice = self::conversationStream($this->conversation, 1, 1, null, null, Profile::current());
1302 // if our "offset 1, limit 1" query got a result, return true else false
1303 return $notice->N > 0;
1307 * Grab the earliest notice from this conversation.
1309 * @return Notice or null
1311 function conversationRoot($profile=-1)
1313 // XXX: can this happen?
1315 if (empty($this->conversation)) {
1319 // Get the current profile if not specified
1321 if (is_int($profile) && $profile == -1) {
1322 $profile = Profile::current();
1325 // If this notice is out of scope, no root for you!
1327 if (!$this->inScope($profile)) {
1331 // If this isn't a reply to anything, then it's its own
1332 // root if it's the earliest notice in the conversation:
1334 if (empty($this->reply_to)) {
1336 $root->conversation = $this->conversation;
1337 $root->orderBy('notice.created ASC');
1338 $root->find(true); // true means "fetch first result"
1343 if (is_null($profile)) {
1344 $keypart = sprintf('notice:conversation_root:%d:null', $this->id);
1346 $keypart = sprintf('notice:conversation_root:%d:%d',
1351 $root = self::cacheGet($keypart);
1353 if ($root !== false && $root->inScope($profile)) {
1360 $parent = $last->getParent();
1361 if ($parent->inScope($profile)) {
1365 } catch (NoParentNoticeException $e) {
1366 // Latest notice has no parent
1367 } catch (NoResultException $e) {
1368 // Notice was not found, so we can't go further up in the tree.
1369 // FIXME: Maybe we should do this in a more stable way where deleted
1370 // notices won't break conversation chains?
1372 // No parent, or parent out of scope
1377 self::cacheSet($keypart, $root);
1383 * Pull up a full list of local recipients who will be getting
1384 * this notice in their inbox. Results will be cached, so don't
1385 * change the input data wily-nilly!
1387 * @param array $groups optional list of Group objects;
1388 * if left empty, will be loaded from group_inbox records
1389 * @param array $recipient optional list of reply profile ids
1390 * if left empty, will be loaded from reply records
1391 * @return array associating recipient user IDs with an inbox source constant
1393 function whoGets(array $groups=null, array $recipients=null)
1395 $c = self::memcache();
1398 $ni = $c->get(Cache::key('notice:who_gets:'.$this->id));
1399 if ($ni !== false) {
1404 if (is_null($recipients)) {
1405 $recipients = $this->getReplies();
1410 // Give plugins a chance to add folks in at start...
1411 if (Event::handle('StartNoticeWhoGets', array($this, &$ni))) {
1413 $users = $this->getSubscribedUsers();
1414 foreach ($users as $id) {
1415 $ni[$id] = NOTICE_INBOX_SOURCE_SUB;
1418 if (is_null($groups)) {
1419 $groups = $this->getGroups();
1421 foreach ($groups as $group) {
1422 $users = $group->getUserMembers();
1423 foreach ($users as $id) {
1424 if (!array_key_exists($id, $ni)) {
1425 $ni[$id] = NOTICE_INBOX_SOURCE_GROUP;
1430 $ptAtts = $this->getAttentionsFromProfileTags();
1431 foreach ($ptAtts as $key=>$val) {
1432 if (!array_key_exists($key, $ni)) {
1437 foreach ($recipients as $recipient) {
1438 if (!array_key_exists($recipient, $ni)) {
1439 $ni[$recipient] = NOTICE_INBOX_SOURCE_REPLY;
1443 // Exclude any deleted, non-local, or blocking recipients.
1444 $profile = $this->getProfile();
1445 $originalProfile = null;
1446 if ($this->isRepeat()) {
1447 // Check blocks against the original notice's poster as well.
1448 $original = Notice::getKV('id', $this->repeat_of);
1449 if ($original instanceof Notice) {
1450 $originalProfile = $original->getProfile();
1454 foreach ($ni as $id => $source) {
1456 $user = User::getKV('id', $id);
1457 if (!$user instanceof User ||
1458 $user->hasBlocked($profile) ||
1459 ($originalProfile && $user->hasBlocked($originalProfile))) {
1462 } catch (UserNoProfileException $e) {
1463 // User doesn't have a profile; invalid; skip them.
1468 // Give plugins a chance to filter out...
1469 Event::handle('EndNoticeWhoGets', array($this, &$ni));
1473 // XXX: pack this data better
1474 $c->set(Cache::key('notice:who_gets:'.$this->id), $ni);
1480 function getSubscribedUsers()
1484 if(common_config('db','quote_identifiers'))
1485 $user_table = '"user"';
1486 else $user_table = 'user';
1490 'FROM '. $user_table .' JOIN subscription '.
1491 'ON '. $user_table .'.id = subscription.subscriber ' .
1492 'WHERE subscription.subscribed = %d ';
1494 $user->query(sprintf($qry, $this->profile_id));
1498 while ($user->fetch()) {
1507 function getProfileTags()
1509 $profile = $this->getProfile();
1510 $list = $profile->getOtherTags($profile);
1513 while($list->fetch()) {
1514 $ptags[] = clone($list);
1520 public function getAttentionsFromProfileTags()
1523 $ptags = $this->getProfileTags();
1524 foreach ($ptags as $ptag) {
1525 $users = $ptag->getUserSubscribers();
1526 foreach ($users as $id) {
1527 $ni[$id] = NOTICE_INBOX_SOURCE_PROFILE_TAG;
1534 * Record this notice to the given group inboxes for delivery.
1535 * Overrides the regular parsing of !group markup.
1537 * @param string $group_ids
1538 * @fixme might prefer URIs as identifiers, as for replies?
1539 * best with generalizations on user_group to support
1540 * remote groups better.
1542 function saveKnownGroups(array $group_ids)
1545 foreach (array_unique($group_ids) as $id) {
1546 $group = User_group::getKV('id', $id);
1547 if ($group instanceof User_group) {
1548 common_log(LOG_DEBUG, "Local delivery to group id $id, $group->nickname");
1549 $result = $this->addToGroupInbox($group);
1551 common_log_db_error($gi, 'INSERT', __FILE__);
1554 if (common_config('group', 'addtag')) {
1555 // we automatically add a tag for every group name, too
1557 $tag = Notice_tag::pkeyGet(array('tag' => common_canonical_tag($group->nickname),
1558 'notice_id' => $this->id));
1560 if (is_null($tag)) {
1561 $this->saveTag($group->nickname);
1565 $groups[] = clone($group);
1567 common_log(LOG_ERR, "Local delivery to group id $id skipped, doesn't exist");
1574 function addToGroupInbox(User_group $group)
1576 $gi = Group_inbox::pkeyGet(array('group_id' => $group->id,
1577 'notice_id' => $this->id));
1579 if (!$gi instanceof Group_inbox) {
1581 $gi = new Group_inbox();
1583 $gi->group_id = $group->id;
1584 $gi->notice_id = $this->id;
1585 $gi->created = $this->created;
1587 $result = $gi->insert();
1590 common_log_db_error($gi, 'INSERT', __FILE__);
1591 // TRANS: Server exception thrown when an update for a group inbox fails.
1592 throw new ServerException(_('Problem saving group inbox.'));
1595 self::blow('user_group:notice_ids:%d', $gi->group_id);
1601 function saveAttentions(array $uris)
1603 foreach ($uris as $uri=>$type) {
1605 $target = Profile::fromUri($uri);
1606 } catch (UnknownUriException $e) {
1607 common_log(LOG_WARNING, "Unable to determine profile for URI '$uri'");
1612 $this->saveAttention($target);
1613 } catch (AlreadyFulfilledException $e) {
1614 common_debug('Attention already exists: '.var_export($e->getMessage(),true));
1615 } catch (Exception $e) {
1616 common_log(LOG_ERR, "Could not save notice id=={$this->getID()} attention for profile id=={$target->getID()}: {$e->getMessage()}");
1622 * Saves an attention for a profile (user or group) which means
1623 * it shows up in their home feed and such.
1625 function saveAttention(Profile $target, $reason=null)
1627 if ($target->isGroup()) {
1628 // FIXME: Make sure we check (for both local and remote) users are in the groups they send to!
1630 // legacy notification method, will still be in use for quite a while I think
1631 $this->addToGroupInbox($target->getGroup());
1633 if ($target->hasBlocked($this->getProfile())) {
1634 common_log(LOG_INFO, "Not saving reply to profile {$target->id} ($uri) from sender {$sender->id} because of a block.");
1639 if ($target->isLocal()) {
1640 // legacy notification method, will still be in use for quite a while I think
1641 $this->saveReply($target->getID());
1644 $att = Attention::saveNew($this, $target, $reason);
1649 * Save reply records indicating that this notice needs to be
1650 * delivered to the local users with the given URIs.
1652 * Since this is expected to be used when saving foreign-sourced
1653 * messages, we won't deliver to any remote targets as that's the
1654 * source service's responsibility.
1656 * Mail notifications etc will be handled later.
1658 * @param array $uris Array of unique identifier URIs for recipients
1660 function saveKnownReplies(array $uris)
1666 $sender = $this->getProfile();
1668 foreach (array_unique($uris) as $uri) {
1670 $profile = Profile::fromUri($uri);
1671 } catch (UnknownUriException $e) {
1672 common_log(LOG_WARNING, "Unable to determine profile for URI '$uri'");
1676 if ($profile->hasBlocked($sender)) {
1677 common_log(LOG_INFO, "Not saving reply to profile {$profile->id} ($uri) from sender {$sender->id} because of a block.");
1681 $this->saveReply($profile->getID());
1682 self::blow('reply:stream:%d', $profile->getID());
1687 * Pull @-replies from this message's content in StatusNet markup format
1688 * and save reply records indicating that this message needs to be
1689 * delivered to those users.
1691 * Mail notifications to local profiles will be sent later.
1693 * @return array of integer profile IDs
1696 function saveReplies()
1698 $sender = $this->getProfile();
1702 // If it's a reply, save for the replied-to author
1704 $parent = $this->getParent();
1705 $parentauthor = $parent->getProfile();
1706 $this->saveReply($parentauthor->getID());
1707 $replied[$parentauthor->getID()] = 1;
1708 self::blow('reply:stream:%d', $parentauthor->getID());
1709 } catch (NoParentNoticeException $e) {
1710 // Not a reply, since it has no parent!
1712 } catch (NoResultException $e) {
1713 // Parent notice was probably deleted
1717 // @todo ideally this parser information would only
1718 // be calculated once.
1720 $mentions = common_find_mentions($this->content, $sender, $parent);
1722 foreach ($mentions as $mention) {
1724 foreach ($mention['mentioned'] as $mentioned) {
1726 // skip if they're already covered
1727 if (array_key_exists($mentioned->id, $replied)) {
1731 // Don't save replies from blocked profile to local user
1732 if ($mentioned->hasBlocked($sender)) {
1736 $this->saveReply($mentioned->id);
1737 $replied[$mentioned->id] = 1;
1738 self::blow('reply:stream:%d', $mentioned->id);
1742 $recipientIds = array_keys($replied);
1744 return $recipientIds;
1747 function saveReply($profileId)
1749 $reply = new Reply();
1751 $reply->notice_id = $this->id;
1752 $reply->profile_id = $profileId;
1753 $reply->modified = $this->created;
1760 protected $_attentionids = array();
1763 * Pull the complete list of known activity context attentions for this notice.
1765 * @return array of integer profile ids (also group profiles)
1767 function getAttentionProfileIDs()
1769 if (!isset($this->_attentionids[$this->getID()])) {
1770 $atts = Attention::multiGet('notice_id', array($this->getID()));
1771 // (array)null means empty array
1772 $this->_attentionids[$this->getID()] = (array)$atts->fetchAll('profile_id');
1774 return $this->_attentionids[$this->getID()];
1777 protected $_replies = array();
1780 * Pull the complete list of @-mentioned profile IDs for this notice.
1782 * @return array of integer profile ids
1784 function getReplies()
1786 if (!isset($this->_replies[$this->getID()])) {
1787 $mentions = Reply::multiGet('notice_id', array($this->getID()));
1788 $this->_replies[$this->getID()] = $mentions->fetchAll('profile_id');
1790 return $this->_replies[$this->getID()];
1793 function _setReplies($replies)
1795 $this->_replies[$this->getID()] = $replies;
1799 * Pull the complete list of @-reply targets for this notice.
1801 * @return array of Profiles
1803 function getAttentionProfiles()
1805 $ids = array_unique(array_merge($this->getReplies(), $this->getGroupProfileIDs(), $this->getAttentionProfileIDs()));
1807 $profiles = Profile::multiGet('id', (array)$ids);
1809 return $profiles->fetchAll();
1813 * Send e-mail notifications to local @-reply targets.
1815 * Replies must already have been saved; this is expected to be run
1816 * from the distrib queue handler.
1818 function sendReplyNotifications()
1820 // Don't send reply notifications for repeats
1821 if ($this->isRepeat()) {
1825 $recipientIds = $this->getReplies();
1826 if (Event::handle('StartNotifyMentioned', array($this, &$recipientIds))) {
1827 require_once INSTALLDIR.'/lib/mail.php';
1829 foreach ($recipientIds as $recipientId) {
1831 $user = User::getByID($recipientId);
1832 mail_notify_attn($user->getProfile(), $this);
1833 } catch (NoResultException $e) {
1837 Event::handle('EndNotifyMentioned', array($this, $recipientIds));
1842 * Pull list of Profile IDs of groups this notice addresses.
1844 * @return array of Group _profile_ IDs
1847 function getGroupProfileIDs()
1851 foreach ($this->getGroups() as $group) {
1852 $ids[] = $group->profile_id;
1859 * Pull list of groups this notice needs to be delivered to,
1860 * as previously recorded by saveKnownGroups().
1862 * @return array of Group objects
1865 protected $_groups = array();
1867 function getGroups()
1869 // Don't save groups for repeats
1871 if (!empty($this->repeat_of)) {
1875 if (isset($this->_groups[$this->id])) {
1876 return $this->_groups[$this->id];
1879 $gis = Group_inbox::listGet('notice_id', array($this->id));
1883 foreach ($gis[$this->id] as $gi) {
1884 $ids[] = $gi->group_id;
1887 $groups = User_group::multiGet('id', $ids);
1888 $this->_groups[$this->id] = $groups->fetchAll();
1889 return $this->_groups[$this->id];
1892 function _setGroups($groups)
1894 $this->_groups[$this->id] = $groups;
1898 * Convert a notice into an activity for export.
1900 * @param Profile $scoped The currently logged in/scoped profile
1902 * @return Activity activity object representing this Notice.
1905 function asActivity(Profile $scoped=null)
1907 $act = self::cacheGet(Cache::codeKey('notice:as-activity:'.$this->id));
1909 if ($act instanceof Activity) {
1912 $act = new Activity();
1914 if (Event::handle('StartNoticeAsActivity', array($this, $act, $scoped))) {
1916 $act->id = $this->uri;
1917 $act->time = strtotime($this->created);
1919 $act->link = $this->getUrl();
1920 } catch (InvalidUrlException $e) {
1921 // The notice is probably a share or similar, which don't
1922 // have a representational URL of their own.
1924 $act->content = common_xml_safe_str($this->getRendered());
1926 $profile = $this->getProfile();
1928 $act->actor = $profile->asActivityObject();
1929 $act->actor->extra[] = $profile->profileInfo($scoped);
1931 $act->verb = $this->verb;
1933 if (!$this->repeat_of) {
1934 $act->objects[] = $this->asActivityObject();
1937 // XXX: should this be handled by default processing for object entry?
1941 $tags = $this->getTags();
1943 foreach ($tags as $tag) {
1944 $cat = new AtomCategory();
1947 $act->categories[] = $cat;
1951 // XXX: use Atom Media and/or File activity objects instead
1953 $attachments = $this->attachments();
1955 foreach ($attachments as $attachment) {
1956 // Include local attachments in Activity
1957 if (!empty($attachment->filename)) {
1958 $act->enclosures[] = $attachment->getEnclosure();
1962 $ctx = new ActivityContext();
1965 $reply = $this->getParent();
1966 $ctx->replyToID = $reply->getUri();
1967 $ctx->replyToUrl = $reply->getUrl(true); // true for fallback to local URL, less messy
1968 } catch (NoParentNoticeException $e) {
1969 // This is not a reply to something
1970 } catch (NoResultException $e) {
1971 // Parent notice was probably deleted
1975 $ctx->location = Notice_location::locFromStored($this);
1976 } catch (ServerException $e) {
1977 $ctx->location = null;
1982 if (!empty($this->conversation)) {
1983 $conv = Conversation::getKV('id', $this->conversation);
1984 if ($conv instanceof Conversation) {
1985 $ctx->conversation = $conv->uri;
1989 // This covers the legacy getReplies and getGroups too which get their data
1990 // from entries stored via Notice::saveNew (which we want to move away from)...
1991 foreach ($this->getAttentionProfiles() as $target) {
1992 // User and group profiles which get the attention of this notice
1993 $ctx->attention[$target->getUri()] = $target->getObjectType();
1996 switch ($this->scope) {
1997 case Notice::PUBLIC_SCOPE:
1998 $ctx->attention[ActivityContext::ATTN_PUBLIC] = ActivityObject::COLLECTION;
2000 case Notice::FOLLOWER_SCOPE:
2001 $surl = common_local_url("subscribers", array('nickname' => $profile->nickname));
2002 $ctx->attention[$surl] = ActivityObject::COLLECTION;
2006 $act->context = $ctx;
2008 $source = $this->getSource();
2010 if ($source instanceof Notice_source) {
2011 $act->generator = ActivityObject::fromNoticeSource($source);
2016 $atom_feed = $profile->getAtomFeed();
2018 if (!empty($atom_feed)) {
2020 $act->source = new ActivitySource();
2022 // XXX: we should store the actual feed ID
2024 $act->source->id = $atom_feed;
2026 // XXX: we should store the actual feed title
2028 $act->source->title = $profile->getBestName();
2030 $act->source->links['alternate'] = $profile->profileurl;
2031 $act->source->links['self'] = $atom_feed;
2033 $act->source->icon = $profile->avatarUrl(AVATAR_PROFILE_SIZE);
2035 $notice = $profile->getCurrentNotice();
2037 if ($notice instanceof Notice) {
2038 $act->source->updated = self::utcDate($notice->created);
2041 $user = User::getKV('id', $profile->id);
2043 if ($user instanceof User) {
2044 $act->source->links['license'] = common_config('license', 'url');
2048 if ($this->isLocal()) {
2049 $act->selfLink = common_local_url('ApiStatusesShow', array('id' => $this->id,
2050 'format' => 'atom'));
2051 $act->editLink = $act->selfLink;
2054 Event::handle('EndNoticeAsActivity', array($this, $act, $scoped));
2057 self::cacheSet(Cache::codeKey('notice:as-activity:'.$this->id), $act);
2062 // This has gotten way too long. Needs to be sliced up into functional bits
2063 // or ideally exported to a utility class.
2065 function asAtomEntry($namespace=false,
2068 Profile $scoped=null)
2070 $act = $this->asActivity($scoped);
2071 $act->extra[] = $this->noticeInfo($scoped);
2072 return $act->asString($namespace, $author, $source);
2076 * Extra notice info for atom entries
2078 * Clients use some extra notice info in the atom stream.
2079 * This gives it to them.
2081 * @param Profile $scoped The currently logged in/scoped profile
2083 * @return array representation of <statusnet:notice_info> element
2086 function noticeInfo(Profile $scoped=null)
2088 // local notice ID (useful to clients for ordering)
2090 $noticeInfoAttr = array('local_id' => $this->id);
2094 $ns = $this->getSource();
2096 if ($ns instanceof Notice_source) {
2097 $noticeInfoAttr['source'] = $ns->code;
2098 if (!empty($ns->url)) {
2099 $noticeInfoAttr['source_link'] = $ns->url;
2100 if (!empty($ns->name)) {
2101 $noticeInfoAttr['source'] = '<a href="'
2102 . htmlspecialchars($ns->url)
2103 . '" rel="nofollow">'
2104 . htmlspecialchars($ns->name)
2110 // favorite and repeated
2112 if ($scoped instanceof Profile) {
2113 $noticeInfoAttr['repeated'] = ($scoped->hasRepeated($this)) ? "true" : "false";
2116 if (!empty($this->repeat_of)) {
2117 $noticeInfoAttr['repeat_of'] = $this->repeat_of;
2120 Event::handle('StatusNetApiNoticeInfo', array($this, &$noticeInfoAttr, $scoped));
2122 return array('statusnet:notice_info', $noticeInfoAttr, null);
2126 * Returns an XML string fragment with a reference to a notice as an
2127 * Activity Streams noun object with the given element type.
2129 * Assumes that 'activity' namespace has been previously defined.
2131 * @param string $element one of 'subject', 'object', 'target'
2135 function asActivityNoun($element)
2137 $noun = $this->asActivityObject();
2138 return $noun->asString('activity:' . $element);
2141 public function asActivityObject()
2143 $object = new ActivityObject();
2145 if (Event::handle('StartActivityObjectFromNotice', array($this, &$object))) {
2146 $object->type = $this->object_type ?: ActivityObject::NOTE;
2147 $object->id = $this->getUri();
2148 //FIXME: = $object->title ?: sprintf(... because we might get a title from StartActivityObjectFromNotice
2149 $object->title = sprintf('New %1$s by %2$s', ActivityObject::canonicalType($object->type), $this->getProfile()->getNickname());
2150 $object->content = $this->getRendered();
2151 $object->link = $this->getUrl();
2153 $object->extra[] = array('status_net', array('notice_id' => $this->id));
2155 Event::handle('EndActivityObjectFromNotice', array($this, &$object));
2158 if (!$object instanceof ActivityObject) {
2159 common_log(LOG_ERR, 'Notice asActivityObject created something else for uri=='._ve($this->getUri()).': '._ve($object));
2160 throw new ServerException('Notice asActivityObject created something else.');
2167 * Determine which notice, if any, a new notice is in reply to.
2169 * For conversation tracking, we try to see where this notice fits
2170 * in the tree. Beware that this may very well give false positives
2171 * and add replies to wrong threads (if there have been newer posts
2172 * by the same user as we're replying to).
2174 * @param Profile $sender Author profile
2175 * @param string $content Final notice content
2177 * @return integer ID of replied-to notice, or null for not a reply.
2180 static function getInlineReplyTo(Profile $sender, $content)
2182 // Is there an initial @ or T?
2183 if (preg_match('/^T ([A-Z0-9]{1,64}) /', $content, $match)
2184 || preg_match('/^@([a-z0-9]{1,64})\s+/', $content, $match)) {
2185 $nickname = common_canonical_nickname($match[1]);
2190 // Figure out who that is.
2191 $recipient = common_relative_profile($sender, $nickname, common_sql_now());
2193 if ($recipient instanceof Profile) {
2194 // Get their last notice
2195 $last = $recipient->getCurrentNotice();
2196 if ($last instanceof Notice) {
2199 // Maybe in the future we want to handle something else below
2200 // so don't return getCurrentNotice() immediately.
2206 static function maxContent()
2208 $contentlimit = common_config('notice', 'contentlimit');
2209 // null => use global limit (distinct from 0!)
2210 if (is_null($contentlimit)) {
2211 $contentlimit = common_config('site', 'textlimit');
2213 return $contentlimit;
2216 static function contentTooLong($content)
2218 $contentlimit = self::maxContent();
2219 return ($contentlimit > 0 && !empty($content) && (mb_strlen($content) > $contentlimit));
2223 * Convenience function for posting a repeat of an existing message.
2225 * @param Profile $repeater Profile which is doing the repeat
2226 * @param string $source: posting source key, eg 'web', 'api', etc
2229 * @throws Exception on failure or permission problems
2231 function repeat(Profile $repeater, $source)
2233 $author = $this->getProfile();
2235 // TRANS: Message used to repeat a notice. RT is the abbreviation of 'retweet'.
2236 // TRANS: %1$s is the repeated user's name, %2$s is the repeated notice.
2237 $content = sprintf(_('RT @%1$s %2$s'),
2238 $author->getNickname(),
2241 $maxlen = self::maxContent();
2242 if ($maxlen > 0 && mb_strlen($content) > $maxlen) {
2243 // Web interface and current Twitter API clients will
2244 // pull the original notice's text, but some older
2245 // clients and RSS/Atom feeds will see this trimmed text.
2247 // Unfortunately this is likely to lose tags or URLs
2248 // at the end of long notices.
2249 $content = mb_substr($content, 0, $maxlen - 4) . ' ...';
2253 // Scope is same as this one's
2254 return self::saveNew($repeater->id,
2257 array('repeat_of' => $this->id,
2258 'scope' => $this->scope));
2261 // These are supposed to be in chron order!
2263 function repeatStream($limit=100)
2265 $cache = Cache::instance();
2267 if (empty($cache)) {
2268 $ids = $this->_repeatStreamDirect($limit);
2270 $idstr = $cache->get(Cache::key('notice:repeats:'.$this->id));
2271 if ($idstr !== false) {
2272 if (empty($idstr)) {
2275 $ids = explode(',', $idstr);
2278 $ids = $this->_repeatStreamDirect(100);
2279 $cache->set(Cache::key('notice:repeats:'.$this->id), implode(',', $ids));
2282 // We do a max of 100, so slice down to limit
2283 $ids = array_slice($ids, 0, $limit);
2287 return NoticeStream::getStreamByIds($ids);
2290 function _repeatStreamDirect($limit)
2292 $notice = new Notice();
2294 $notice->selectAdd(); // clears it
2295 $notice->selectAdd('id');
2297 $notice->repeat_of = $this->id;
2299 $notice->orderBy('created, id'); // NB: asc!
2301 if (!is_null($limit)) {
2302 $notice->limit(0, $limit);
2305 return $notice->fetchAll('id');
2308 static function locationOptions($lat, $lon, $location_id, $location_ns, $profile = null)
2312 if (!empty($location_id) && !empty($location_ns)) {
2313 $options['location_id'] = $location_id;
2314 $options['location_ns'] = $location_ns;
2316 $location = Location::fromId($location_id, $location_ns);
2318 if ($location instanceof Location) {
2319 $options['lat'] = $location->lat;
2320 $options['lon'] = $location->lon;
2323 } else if (!empty($lat) && !empty($lon)) {
2324 $options['lat'] = $lat;
2325 $options['lon'] = $lon;
2327 $location = Location::fromLatLon($lat, $lon);
2329 if ($location instanceof Location) {
2330 $options['location_id'] = $location->location_id;
2331 $options['location_ns'] = $location->location_ns;
2333 } else if (!empty($profile)) {
2334 if (isset($profile->lat) && isset($profile->lon)) {
2335 $options['lat'] = $profile->lat;
2336 $options['lon'] = $profile->lon;
2339 if (isset($profile->location_id) && isset($profile->location_ns)) {
2340 $options['location_id'] = $profile->location_id;
2341 $options['location_ns'] = $profile->location_ns;
2348 function clearAttentions()
2350 $att = new Attention();
2351 $att->notice_id = $this->getID();
2354 while ($att->fetch()) {
2355 // Can't do delete() on the object directly since it won't remove all of it
2356 $other = clone($att);
2362 function clearReplies()
2364 $replyNotice = new Notice();
2365 $replyNotice->reply_to = $this->id;
2367 //Null any notices that are replies to this notice
2369 if ($replyNotice->find()) {
2370 while ($replyNotice->fetch()) {
2371 $orig = clone($replyNotice);
2372 $replyNotice->reply_to = null;
2373 $replyNotice->update($orig);
2379 $reply = new Reply();
2380 $reply->notice_id = $this->id;
2382 if ($reply->find()) {
2383 while($reply->fetch()) {
2384 self::blow('reply:stream:%d', $reply->profile_id);
2392 function clearLocation()
2394 $loc = new Notice_location();
2395 $loc->notice_id = $this->id;
2402 function clearFiles()
2404 $f2p = new File_to_post();
2406 $f2p->post_id = $this->id;
2409 while ($f2p->fetch()) {
2413 // FIXME: decide whether to delete File objects
2414 // ...and related (actual) files
2417 function clearRepeats()
2419 $repeatNotice = new Notice();
2420 $repeatNotice->repeat_of = $this->id;
2422 //Null any notices that are repeats of this notice
2424 if ($repeatNotice->find()) {
2425 while ($repeatNotice->fetch()) {
2426 $orig = clone($repeatNotice);
2427 $repeatNotice->repeat_of = null;
2428 $repeatNotice->update($orig);
2433 function clearTags()
2435 $tag = new Notice_tag();
2436 $tag->notice_id = $this->id;
2439 while ($tag->fetch()) {
2440 self::blow('profile:notice_ids_tagged:%d:%s', $this->profile_id, Cache::keyize($tag->tag));
2441 self::blow('profile:notice_ids_tagged:%d:%s;last', $this->profile_id, Cache::keyize($tag->tag));
2442 self::blow('notice_tag:notice_ids:%s', Cache::keyize($tag->tag));
2443 self::blow('notice_tag:notice_ids:%s;last', Cache::keyize($tag->tag));
2451 function clearGroupInboxes()
2453 $gi = new Group_inbox();
2455 $gi->notice_id = $this->id;
2458 while ($gi->fetch()) {
2459 self::blow('user_group:notice_ids:%d', $gi->group_id);
2467 function distribute()
2469 // We always insert for the author so they don't
2471 Event::handle('StartNoticeDistribute', array($this));
2473 // If there's a failure, we want to _force_
2474 // distribution at this point.
2476 $json = json_encode((object)array('id' => $this->getID(),
2479 $qm = QueueManager::get();
2480 $qm->enqueue($json, 'distrib');
2481 } catch (Exception $e) {
2482 // If the exception isn't transient, this
2483 // may throw more exceptions as DQH does
2484 // its own enqueueing. So, we ignore them!
2486 $handler = new DistribQueueHandler();
2487 $handler->handle($this);
2488 } catch (Exception $e) {
2489 common_log(LOG_ERR, "emergency redistribution resulted in " . $e->getMessage());
2491 // Re-throw so somebody smarter can handle it.
2498 $result = parent::insert();
2500 if ($result === false) {
2501 common_log_db_error($this, 'INSERT', __FILE__);
2502 // TRANS: Server exception thrown when a stored object entry cannot be saved.
2503 throw new ServerException('Could not save Notice');
2506 // Profile::hasRepeated() abuses pkeyGet(), so we
2507 // have to clear manually
2508 if (!empty($this->repeat_of)) {
2509 $c = self::memcache();
2511 $ck = self::multicacheKey('Notice',
2512 array('profile_id' => $this->profile_id,
2513 'repeat_of' => $this->repeat_of));
2518 // Update possibly ID-dependent columns: URI, conversation
2519 // (now that INSERT has added the notice's local id)
2520 $orig = clone($this);
2523 // We can only get here if it's a local notice, since remote notices
2524 // should've bailed out earlier due to lacking a URI.
2525 if (empty($this->uri)) {
2526 $this->uri = sprintf('%s%s=%d:%s=%s',
2528 'noticeId', $this->id,
2529 'objectType', $this->getObjectType(true));
2533 if ($changed && $this->update($orig) === false) {
2534 common_log_db_error($notice, 'UPDATE', __FILE__);
2535 // TRANS: Server exception thrown when a notice cannot be updated.
2536 throw new ServerException(_('Problem saving notice.'));
2539 $this->blowOnInsert();
2545 * Get the source of the notice
2547 * @return Notice_source $ns A notice source object. 'code' is the only attribute
2548 * guaranteed to be populated.
2550 function getSource()
2552 if (empty($this->source)) {
2556 $ns = new Notice_source();
2557 switch ($this->source) {
2564 $ns->code = $this->source;
2567 $ns = Notice_source::getKV($this->source);
2569 $ns = new Notice_source();
2570 $ns->code = $this->source;
2571 $app = Oauth_application::getKV('name', $this->source);
2573 $ns->name = $app->name;
2574 $ns->url = $app->source_url;
2584 * Determine whether the notice was locally created
2586 * @return boolean locality
2589 public function isLocal()
2591 $is_local = intval($this->is_local);
2592 return ($is_local === self::LOCAL_PUBLIC || $is_local === self::LOCAL_NONPUBLIC);
2595 public function getScope()
2597 return intval($this->scope);
2600 public function isRepeat()
2602 return !empty($this->repeat_of);
2606 * Get the list of hash tags saved with this notice.
2608 * @return array of strings
2610 public function getTags()
2614 $keypart = sprintf('notice:tags:%d', $this->id);
2616 $tagstr = self::cacheGet($keypart);
2618 if ($tagstr !== false) {
2619 $tags = explode(',', $tagstr);
2621 $tag = new Notice_tag();
2622 $tag->notice_id = $this->id;
2624 while ($tag->fetch()) {
2625 $tags[] = $tag->tag;
2628 self::cacheSet($keypart, implode(',', $tags));
2634 static private function utcDate($dt)
2636 $dateStr = date('d F Y H:i:s', strtotime($dt));
2637 $d = new DateTime($dateStr, new DateTimeZone('UTC'));
2638 return $d->format(DATE_W3C);
2642 * Look up the creation timestamp for a given notice ID, even
2643 * if it's been deleted.
2646 * @return mixed string recorded creation timestamp, or false if can't be found
2648 public static function getAsTimestamp($id)
2651 throw new EmptyIdException('Notice');
2655 if (Event::handle('GetNoticeSqlTimestamp', array($id, &$timestamp))) {
2656 // getByID throws exception if $id isn't found
2657 $notice = Notice::getByID($id);
2658 $timestamp = $notice->created;
2661 if (empty($timestamp)) {
2662 throw new ServerException('No timestamp found for Notice with id=='._ve($id));
2668 * Build an SQL 'where' fragment for timestamp-based sorting from a since_id
2669 * parameter, matching notices posted after the given one (exclusive).
2671 * If the referenced notice can't be found, will return false.
2674 * @param string $idField
2675 * @param string $createdField
2676 * @return mixed string or false if no match
2678 public static function whereSinceId($id, $idField='id', $createdField='created')
2681 $since = Notice::getAsTimestamp($id);
2682 } catch (Exception $e) {
2685 return sprintf("($createdField = '%s' and $idField > %d) or ($createdField > '%s')", $since, $id, $since);
2689 * Build an SQL 'where' fragment for timestamp-based sorting from a since_id
2690 * parameter, matching notices posted after the given one (exclusive), and
2691 * if necessary add it to the data object's query.
2693 * @param DB_DataObject $obj
2695 * @param string $idField
2696 * @param string $createdField
2697 * @return mixed string or false if no match
2699 public static function addWhereSinceId(DB_DataObject $obj, $id, $idField='id', $createdField='created')
2701 $since = self::whereSinceId($id, $idField, $createdField);
2703 $obj->whereAdd($since);
2708 * Build an SQL 'where' fragment for timestamp-based sorting from a max_id
2709 * parameter, matching notices posted before the given one (inclusive).
2711 * If the referenced notice can't be found, will return false.
2714 * @param string $idField
2715 * @param string $createdField
2716 * @return mixed string or false if no match
2718 public static function whereMaxId($id, $idField='id', $createdField='created')
2721 $max = Notice::getAsTimestamp($id);
2722 } catch (Exception $e) {
2725 return sprintf("($createdField < '%s') or ($createdField = '%s' and $idField <= %d)", $max, $max, $id);
2729 * Build an SQL 'where' fragment for timestamp-based sorting from a max_id
2730 * parameter, matching notices posted before the given one (inclusive), and
2731 * if necessary add it to the data object's query.
2733 * @param DB_DataObject $obj
2735 * @param string $idField
2736 * @param string $createdField
2737 * @return mixed string or false if no match
2739 public static function addWhereMaxId(DB_DataObject $obj, $id, $idField='id', $createdField='created')
2741 $max = self::whereMaxId($id, $idField, $createdField);
2743 $obj->whereAdd($max);
2749 return (($this->is_local != Notice::LOCAL_NONPUBLIC) &&
2750 ($this->is_local != Notice::GATEWAY));
2754 * Check that the given profile is allowed to read, respond to, or otherwise
2755 * act on this notice.
2757 * The $scope member is a bitmask of scopes, representing a logical AND of the
2758 * scope requirement. So, 0x03 (Notice::ADDRESSEE_SCOPE | Notice::SITE_SCOPE) means
2759 * "only visible to people who are mentioned in the notice AND are users on this site."
2760 * Users on the site who are not mentioned in the notice will not be able to see the
2763 * @param Profile $profile The profile to check; pass null to check for public/unauthenticated users.
2765 * @return boolean whether the profile is in the notice's scope
2767 function inScope($profile)
2769 if (is_null($profile)) {
2770 $keypart = sprintf('notice:in-scope-for:%d:null', $this->id);
2772 $keypart = sprintf('notice:in-scope-for:%d:%d', $this->id, $profile->id);
2775 $result = self::cacheGet($keypart);
2777 if ($result === false) {
2779 if (Event::handle('StartNoticeInScope', array($this, $profile, &$bResult))) {
2780 $bResult = $this->_inScope($profile);
2781 Event::handle('EndNoticeInScope', array($this, $profile, &$bResult));
2783 $result = ($bResult) ? 1 : 0;
2784 self::cacheSet($keypart, $result, 0, 300);
2787 return ($result == 1) ? true : false;
2790 protected function _inScope($profile)
2792 $scope = is_null($this->scope) ? self::defaultScope() : $this->getScope();
2794 if ($scope === 0 && !$this->getProfile()->isPrivateStream()) { // Not scoping, so it is public.
2795 return !$this->isHiddenSpam($profile);
2798 // If there's scope, anon cannot be in scope
2799 if (empty($profile)) {
2803 // Author is always in scope
2804 if ($this->profile_id == $profile->id) {
2808 // Only for users on this site
2809 if (($scope & Notice::SITE_SCOPE) && !$profile->isLocal()) {
2813 // Only for users mentioned in the notice
2814 if ($scope & Notice::ADDRESSEE_SCOPE) {
2816 $reply = Reply::pkeyGet(array('notice_id' => $this->id,
2817 'profile_id' => $profile->id));
2819 if (!$reply instanceof Reply) {
2824 // Only for members of the given group
2825 if ($scope & Notice::GROUP_SCOPE) {
2827 // XXX: just query for the single membership
2829 $groups = $this->getGroups();
2833 foreach ($groups as $group) {
2834 if ($profile->isMember($group)) {
2845 if ($scope & Notice::FOLLOWER_SCOPE || $this->getProfile()->isPrivateStream()) {
2847 if (!Subscription::exists($profile, $this->getProfile())) {
2852 return !$this->isHiddenSpam($profile);
2855 function isHiddenSpam($profile) {
2857 // Hide posts by silenced users from everyone but moderators.
2859 if (common_config('notice', 'hidespam')) {
2862 $author = $this->getProfile();
2863 } catch(Exception $e) {
2864 // If we can't get an author, keep it hidden.
2865 // XXX: technically not spam, but, whatever.
2869 if ($author->hasRole(Profile_role::SILENCED)) {
2870 if (!$profile instanceof Profile || (($profile->id !== $author->id) && (!$profile->hasRight(Right::REVIEWSPAM)))) {
2879 public function hasParent()
2883 } catch (NoParentNoticeException $e) {
2889 public function getParent()
2891 $reply_to_id = null;
2893 if (empty($this->reply_to)) {
2894 throw new NoParentNoticeException($this);
2897 // The reply_to ID in the table Notice could exist with a number
2898 // however, the replied to notice might not exist in the database.
2899 // Thus we need to catch the exception and throw the NoParentNoticeException else
2900 // the timeline will not display correctly.
2902 $reply_to_id = self::getByID($this->reply_to);
2903 } catch(Exception $e){
2904 throw new NoParentNoticeException($this);
2907 return $reply_to_id;
2911 * Magic function called at serialize() time.
2913 * We use this to drop a couple process-specific references
2914 * from DB_DataObject which can cause trouble in future
2917 * @return array of variable names to include in serialization.
2922 $vars = parent::__sleep();
2923 $skip = array('_profile', '_groups', '_attachments', '_faves', '_replies', '_repeats');
2924 return array_diff($vars, $skip);
2927 static function defaultScope()
2929 $scope = common_config('notice', 'defaultscope');
2930 if (is_null($scope)) {
2931 if (common_config('site', 'private')) {
2940 static function fillProfiles($notices)
2942 $map = self::getProfiles($notices);
2943 foreach ($notices as $entry=>$notice) {
2945 if (array_key_exists($notice->profile_id, $map)) {
2946 $notice->_setProfile($map[$notice->profile_id]);
2948 } catch (NoProfileException $e) {
2949 common_log(LOG_WARNING, "Failed to fill profile in Notice with non-existing entry for profile_id: {$e->profile_id}");
2950 unset($notices[$entry]);
2954 return array_values($map);
2957 static function getProfiles(&$notices)
2960 foreach ($notices as $notice) {
2961 $ids[] = $notice->profile_id;
2963 $ids = array_unique($ids);
2964 return Profile::pivotGet('id', $ids);
2967 static function fillGroups(&$notices)
2969 $ids = self::_idsOf($notices);
2970 $gis = Group_inbox::listGet('notice_id', $ids);
2973 foreach ($gis as $id => $gi) {
2976 $gids[] = $g->group_id;
2980 $gids = array_unique($gids);
2981 $group = User_group::pivotGet('id', $gids);
2982 foreach ($notices as $notice)
2985 $gi = $gis[$notice->id];
2986 foreach ($gi as $g) {
2987 $grps[] = $group[$g->group_id];
2989 $notice->_setGroups($grps);
2993 static function _idsOf(array &$notices)
2996 foreach ($notices as $notice) {
2997 $ids[$notice->id] = true;
2999 return array_keys($ids);
3002 static function fillAttachments(&$notices)
3004 $ids = self::_idsOf($notices);
3005 $f2pMap = File_to_post::listGet('post_id', $ids);
3007 foreach ($f2pMap as $noticeId => $f2ps) {
3008 foreach ($f2ps as $f2p) {
3009 $fileIds[] = $f2p->file_id;
3013 $fileIds = array_unique($fileIds);
3014 $fileMap = File::pivotGet('id', $fileIds);
3015 foreach ($notices as $notice)
3018 $f2ps = $f2pMap[$notice->id];
3019 foreach ($f2ps as $f2p) {
3020 $files[] = $fileMap[$f2p->file_id];
3022 $notice->_setAttachments($files);
3026 static function fillReplies(&$notices)
3028 $ids = self::_idsOf($notices);
3029 $replyMap = Reply::listGet('notice_id', $ids);
3030 foreach ($notices as $notice) {
3031 $replies = $replyMap[$notice->id];
3033 foreach ($replies as $reply) {
3034 $ids[] = $reply->profile_id;
3036 $notice->_setReplies($ids);
3040 static public function beforeSchemaUpdate()
3042 $table = strtolower(get_called_class());
3043 $schema = Schema::get();
3044 $schemadef = $schema->getTableDef($table);
3046 // 2015-09-04 We move Notice location data to Notice_location
3047 // First we see if we have to do this at all
3048 if (!isset($schemadef['fields']['lat'])
3049 && !isset($schemadef['fields']['lon'])
3050 && !isset($schemadef['fields']['location_id'])
3051 && !isset($schemadef['fields']['location_ns'])) {
3052 // We have already removed the location fields, so no need to migrate.
3055 // Then we make sure the Notice_location table is created!
3056 $schema->ensureTable('notice_location', Notice_location::schemaDef());
3058 // Then we continue on our road to migration!
3059 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)";
3061 $notice = new Notice();
3062 $notice->query(sprintf('SELECT id, lat, lon, location_id, location_ns FROM %1$s ' .
3063 'WHERE lat IS NOT NULL ' .
3064 'OR lon IS NOT NULL ' .
3065 'OR location_id IS NOT NULL ' .
3066 'OR location_ns IS NOT NULL',
3067 $schema->quoteIdentifier($table)));
3068 print "\nFound {$notice->N} notices with location data, inserting";
3069 while ($notice->fetch()) {
3070 $notloc = Notice_location::getKV('notice_id', $notice->id);
3071 if ($notloc instanceof Notice_location) {
3075 $notloc = new Notice_location();
3076 $notloc->notice_id = $notice->id;
3077 $notloc->lat= $notice->lat;
3078 $notloc->lon= $notice->lon;
3079 $notloc->location_id= $notice->location_id;
3080 $notloc->location_ns= $notice->location_ns;