3 * StatusNet - the distributed open-source microblogging tool
4 * Copyright (C) 2008-2011 StatusNet, Inc.
6 * This program is free software: you can redistribute it and/or modify
7 * it under the terms of the GNU Affero General Public License as published by
8 * the Free Software Foundation, either version 3 of the License, or
9 * (at your option) any later version.
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU Affero General Public License for more details.
16 * You should have received a copy of the GNU Affero General Public License
17 * along with this program. If not, see <http://www.gnu.org/licenses/>.
21 * @author Brenda Wallace <shiny@cpan.org>
22 * @author Christopher Vollick <psycotica0@gmail.com>
23 * @author CiaranG <ciaran@ciarang.com>
24 * @author Craig Andrews <candrews@integralblue.com>
25 * @author Evan Prodromou <evan@controlezvous.ca>
26 * @author Gina Haeussge <osd@foosel.net>
27 * @author Jeffery To <jeffery.to@gmail.com>
28 * @author Mike Cochrane <mikec@mikenz.geek.nz>
29 * @author Robin Millette <millette@controlyourself.ca>
30 * @author Sarven Capadisli <csarven@controlyourself.ca>
31 * @author Tom Adams <tom@holizz.com>
32 * @author Mikael Nordfeldth <mmn@hethane.se>
33 * @copyright 2009 Free Software Foundation, Inc http://www.fsf.org
34 * @license GNU Affero General Public License http://www.gnu.org/licenses/
37 if (!defined('GNUSOCIAL')) { exit(1); }
40 * Table Definition for notice
43 /* We keep 200 notices, the max number of notices available per API request,
44 * in the memcached cache. */
46 define('NOTICE_CACHE_WINDOW', CachingNoticeStream::CACHE_WINDOW);
48 define('MAX_BOXCARS', 128);
50 class Notice extends Managed_DataObject
53 /* the code below is auto generated do not remove the above tag */
55 public $__table = 'notice'; // table name
56 public $id; // int(4) primary_key not_null
57 public $profile_id; // int(4) multiple_key not_null
58 public $uri; // varchar(191) unique_key not 255 because utf8mb4 takes more space
59 public $content; // text
60 public $rendered; // text
61 public $url; // varchar(191) not 255 because utf8mb4 takes more space
62 public $created; // datetime multiple_key not_null default_0000-00-00%2000%3A00%3A00
63 public $modified; // timestamp not_null default_CURRENT_TIMESTAMP
64 public $reply_to; // int(4)
65 public $is_local; // int(4)
66 public $source; // varchar(32)
67 public $conversation; // int(4)
68 public $repeat_of; // int(4)
69 public $verb; // varchar(191) not 255 because utf8mb4 takes more space
70 public $object_type; // varchar(191) not 255 because utf8mb4 takes more space
71 public $scope; // int(4)
73 /* the code above is auto generated do not remove the tag below */
76 public static function schemaDef()
80 'id' => array('type' => 'serial', 'not null' => true, 'description' => 'unique identifier'),
81 'profile_id' => array('type' => 'int', 'not null' => true, 'description' => 'who made the update'),
82 'uri' => array('type' => 'varchar', 'length' => 191, 'description' => 'universally unique identifier, usually a tag URI'),
83 'content' => array('type' => 'text', 'description' => 'update content', 'collate' => 'utf8mb4_general_ci'),
84 'rendered' => array('type' => 'text', 'description' => 'HTML version of the content'),
85 'url' => array('type' => 'varchar', 'length' => 191, 'description' => 'URL of any attachment (image, video, bookmark, whatever)'),
86 'created' => array('type' => 'datetime', 'not null' => true, 'description' => 'date this record was created'),
87 'modified' => array('type' => 'timestamp', 'not null' => true, 'description' => 'date this record was modified'),
88 'reply_to' => array('type' => 'int', 'description' => 'notice replied to (usually a guess)'),
89 'is_local' => array('type' => 'int', 'size' => 'tiny', 'default' => 0, 'description' => 'notice was generated by a user'),
90 'source' => array('type' => 'varchar', 'length' => 32, 'description' => 'source of comment, like "web", "im", or "clientname"'),
91 'conversation' => array('type' => 'int', 'description' => 'id of root notice in this conversation'),
92 'repeat_of' => array('type' => 'int', 'description' => 'notice this is a repeat of'),
93 'object_type' => array('type' => 'varchar', 'length' => 191, 'description' => 'URI representing activity streams object type', 'default' => 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 if (is_null($this->rendered) || $this->rendered === '') {
264 // update to include rendered content on-the-fly, so we don't have to have a fix-up script in upgrade.php
265 common_debug('Rendering notice '.$this->getID().' as it had no rendered HTML content.');
266 $orig = clone($this);
267 $this->rendered = common_render_content($this->getContent(),
269 $this->hasParent() ? $this->getParent() : null);
270 $this->update($orig);
272 return $this->rendered;
275 public function getCreated()
277 return $this->created;
280 public function getVerb($make_relative=false)
282 return ActivityUtils::resolveUri($this->verb, $make_relative);
286 * Get the original representation URL of this notice.
288 * @param boolean $fallback Whether to fall back to generate a local URL or throw InvalidUrlException
290 public function getUrl($fallback=false)
292 // The risk is we start having empty urls and non-http uris...
293 // and we can't really handle any other protocol right now.
295 case $this->isLocal():
296 return common_local_url('shownotice', array('notice' => $this->getID()), null, null, false);
297 case common_valid_http_url($this->url): // should we allow non-http/https URLs?
299 case common_valid_http_url($this->uri): // Sometimes we only have the URI for remote posts.
302 // let's generate a valid link to our locally available notice on demand
303 return common_local_url('shownotice', array('notice' => $this->getID()), null, null, false);
305 common_debug('No URL available for notice: id='.$this->getID());
306 throw new InvalidUrlException($this->url);
310 public function getObjectType($canonical=false) {
311 if (is_null($this->object_type) || $this->object_type==='') {
312 throw new NoObjectTypeException($this);
314 return ActivityUtils::resolveUri($this->object_type, $canonical);
317 public static function getByUri($uri)
319 $notice = new Notice();
321 if (!$notice->find(true)) {
322 throw new NoResultException($notice);
328 * Extract #hashtags from this notice's content and save them to the database.
332 /* extract all #hastags */
333 $count = preg_match_all('/(?:^|\s)#([\pL\pN_\-\.]{1,64})/u', strtolower($this->content), $match);
338 /* Add them to the database */
339 return $this->saveKnownTags($match[1]);
343 * Record the given set of hash tags in the db for this notice.
344 * Given tag strings will be normalized and checked for dupes.
346 function saveKnownTags($hashtags)
348 //turn each into their canonical tag
349 //this is needed to remove dupes before saving e.g. #hash.tag = #hashtag
350 for($i=0; $i<count($hashtags); $i++) {
351 /* elide characters we don't want in the tag */
352 $hashtags[$i] = common_canonical_tag($hashtags[$i]);
355 foreach(array_unique($hashtags) as $hashtag) {
356 $this->saveTag($hashtag);
357 self::blow('profile:notice_ids_tagged:%d:%s', $this->profile_id, $hashtag);
363 * Record a single hash tag as associated with this notice.
364 * Tag format and uniqueness must be validated by caller.
366 function saveTag($hashtag)
368 $tag = new Notice_tag();
369 $tag->notice_id = $this->id;
370 $tag->tag = $hashtag;
371 $tag->created = $this->created;
372 $id = $tag->insert();
375 // TRANS: Server exception. %s are the error details.
376 throw new ServerException(sprintf(_('Database error inserting hashtag: %s.'),
377 $last_error->message));
381 // if it's saved, blow its cache
382 $tag->blowCache(false);
386 * Save a new notice and push it out to subscribers' inboxes.
387 * Poster's permissions are checked before sending.
389 * @param int $profile_id Profile ID of the poster
390 * @param string $content source message text; links may be shortened
391 * per current user's preference
392 * @param string $source source key ('web', 'api', etc)
393 * @param array $options Associative array of optional properties:
394 * string 'created' timestamp of notice; defaults to now
395 * int 'is_local' source/gateway ID, one of:
396 * Notice::LOCAL_PUBLIC - Local, ok to appear in public timeline
397 * Notice::REMOTE - Sent from a remote service;
398 * hide from public timeline but show in
399 * local "and friends" timelines
400 * Notice::LOCAL_NONPUBLIC - Local, but hide from public timeline
401 * Notice::GATEWAY - From another non-OStatus service;
402 * will not appear in public views
403 * float 'lat' decimal latitude for geolocation
404 * float 'lon' decimal longitude for geolocation
405 * int 'location_id' geoname identifier
406 * int 'location_ns' geoname namespace to interpret location_id
407 * int 'reply_to'; notice ID this is a reply to
408 * int 'repeat_of'; notice ID this is a repeat of
409 * string 'uri' unique ID for notice; a unique tag uri (can be url or anything too)
410 * string 'url' permalink to notice; defaults to local notice URL
411 * string 'rendered' rendered HTML version of content
412 * array 'replies' list of profile URIs for reply delivery in
413 * place of extracting @-replies from content.
414 * array 'groups' list of group IDs to deliver to, in place of
415 * extracting ! tags from content
416 * array 'tags' list of hashtag strings to save with the notice
417 * in place of extracting # tags from content
418 * array 'urls' list of attached/referred URLs to save with the
419 * notice in place of extracting links from content
420 * boolean 'distribute' whether to distribute the notice, default true
421 * string 'object_type' URL of the associated object type (default ActivityObject::NOTE)
422 * string 'verb' URL of the associated verb (default ActivityVerb::POST)
423 * int 'scope' Scope bitmask; default to SITE_SCOPE on private sites, 0 otherwise
425 * @fixme tag override
428 * @throws ClientException
430 static function saveNew($profile_id, $content, $source, array $options=null) {
431 $defaults = array('uri' => null,
433 'conversation' => null, // URI of conversation
434 'reply_to' => null, // This will override convo URI if the parent is known
435 'repeat_of' => null, // This will override convo URI if the repeated notice is known
437 'distribute' => true,
438 'object_type' => null,
441 if (!empty($options) && is_array($options)) {
442 $options = array_merge($defaults, $options);
448 if (!isset($is_local)) {
449 $is_local = Notice::LOCAL_PUBLIC;
452 $profile = Profile::getKV('id', $profile_id);
453 if (!$profile instanceof Profile) {
454 // TRANS: Client exception thrown when trying to save a notice for an unknown user.
455 throw new ClientException(_('Problem saving notice. Unknown user.'));
458 $user = User::getKV('id', $profile_id);
459 if ($user instanceof User) {
460 // Use the local user's shortening preferences, if applicable.
461 $final = $user->shortenLinks($content);
463 $final = common_shorten_links($content);
466 if (Notice::contentTooLong($final)) {
467 // TRANS: Client exception thrown if a notice contains too many characters.
468 throw new ClientException(_('Problem saving notice. Too long.'));
471 if (common_config('throttle', 'enabled') && !Notice::checkEditThrottle($profile_id)) {
472 common_log(LOG_WARNING, 'Excessive posting by profile #' . $profile_id . '; throttled.');
473 // TRANS: Client exception thrown when a user tries to post too many notices in a given time frame.
474 throw new ClientException(_('Too many notices too fast; take a breather '.
475 'and post again in a few minutes.'));
478 if (common_config('site', 'dupelimit') > 0 && !Notice::checkDupes($profile_id, $final)) {
479 common_log(LOG_WARNING, 'Dupe posting by profile #' . $profile_id . '; throttled.');
480 // TRANS: Client exception thrown when a user tries to post too many duplicate notices in a given time frame.
481 throw new ClientException(_('Too many duplicate messages too quickly;'.
482 ' take a breather and post again in a few minutes.'));
485 if (!$profile->hasRight(Right::NEWNOTICE)) {
486 common_log(LOG_WARNING, "Attempted post from user disallowed to post: " . $profile->nickname);
488 // TRANS: Client exception thrown when a user tries to post while being banned.
489 throw new ClientException(_('You are banned from posting notices on this site.'), 403);
492 $notice = new Notice();
493 $notice->profile_id = $profile_id;
495 $autosource = common_config('public', 'autosource');
497 // Sandboxed are non-false, but not 1, either
499 if (!$profile->hasRight(Right::PUBLICNOTICE) ||
500 ($source && $autosource && in_array($source, $autosource))) {
501 $notice->is_local = Notice::LOCAL_NONPUBLIC;
503 $notice->is_local = $is_local;
506 if (!empty($created)) {
507 $notice->created = $created;
509 $notice->created = common_sql_now();
512 if (!$notice->isLocal()) {
513 // Only do these checks for non-local notices. Local notices will generate these values later.
514 if (!common_valid_http_url($url)) {
515 common_debug('Bad notice URL: ['.$url.'], URI: ['.$uri.']. Cannot link back to original! This is normal for shared notices etc.');
518 throw new ServerException('No URI for remote notice. Cannot accept that.');
522 $notice->content = $final;
524 $notice->source = $source;
528 // Get the groups here so we can figure out replies and such
529 if (!isset($groups)) {
530 $groups = User_group::idsFromText($notice->content, $profile);
535 // Handle repeat case
537 if (!empty($options['repeat_of'])) {
539 // Check for a private one
541 $repeat = Notice::getByID($options['repeat_of']);
543 if ($profile->sameAs($repeat->getProfile())) {
544 // TRANS: Client error displayed when trying to repeat an own notice.
545 throw new ClientException(_('You cannot repeat your own notice.'));
548 if ($repeat->scope != Notice::SITE_SCOPE &&
549 $repeat->scope != Notice::PUBLIC_SCOPE) {
550 // TRANS: Client error displayed when trying to repeat a non-public notice.
551 throw new ClientException(_('Cannot repeat a private notice.'), 403);
554 if (!$repeat->inScope($profile)) {
555 // The generic checks above should cover this, but let's be sure!
556 // TRANS: Client error displayed when trying to repeat a notice you cannot access.
557 throw new ClientException(_('Cannot repeat a notice you cannot read.'), 403);
560 if ($profile->hasRepeated($repeat)) {
561 // TRANS: Client error displayed when trying to repeat an already repeated notice.
562 throw new ClientException(_('You already repeated that notice.'));
565 $notice->repeat_of = $repeat->id;
566 $notice->conversation = $repeat->conversation;
570 // If $reply_to is specified, we check that it exists, and then
571 // return it if it does
572 if (!empty($reply_to)) {
573 $reply = Notice::getKV('id', $reply_to);
574 } elseif (in_array($source, array('xmpp', 'mail', 'sms'))) {
575 // If the source lacks capability of sending the "reply_to"
576 // metadata, let's try to find an inline replyto-reference.
577 $reply = self::getInlineReplyTo($profile, $final);
580 if ($reply instanceof Notice) {
581 if (!$reply->inScope($profile)) {
582 // TRANS: Client error displayed when trying to reply to a notice a the target has no access to.
583 // TRANS: %1$s is a user nickname, %2$d is a notice ID (number).
584 throw new ClientException(sprintf(_('%1$s has no access to notice %2$d.'),
585 $profile->nickname, $reply->id), 403);
588 // If it's a repeat, the reply_to should be to the original
589 if ($reply->isRepeat()) {
590 $notice->reply_to = $reply->repeat_of;
592 $notice->reply_to = $reply->id;
594 // But the conversation ought to be the same :)
595 $notice->conversation = $reply->conversation;
597 // If the original is private to a group, and notice has
598 // no group specified, make it to the same group(s)
600 if (empty($groups) && ($reply->scope & Notice::GROUP_SCOPE)) {
602 $replyGroups = $reply->getGroups();
603 foreach ($replyGroups as $group) {
604 if ($profile->isMember($group)) {
605 $groups[] = $group->id;
613 // If we don't know the reply, we might know the conversation!
614 // This will happen if a known remote user replies to an
615 // unknown remote user - within a known conversation.
616 if (empty($notice->conversation) and !empty($options['conversation'])) {
617 $conv = Conversation::getKV('uri', $options['conversation']);
618 if ($conv instanceof Conversation) {
619 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.').');
621 // Conversation entry with specified URI was not found, so we must create it.
622 common_debug('Conversation URI not found, so we will create it with the URI given in the options to Notice::saveNew: '.$options['conversation']);
623 // The insert in Conversation::create throws exception on failure
624 $conv = Conversation::create($options['conversation'], $notice->created);
626 $notice->conversation = $conv->getID();
631 // If it's not part of a conversation, it's the beginning of a new conversation.
632 if (empty($notice->conversation)) {
633 $conv = Conversation::create();
634 $notice->conversation = $conv->getID();
639 $notloc = new Notice_location();
640 if (!empty($lat) && !empty($lon)) {
645 if (!empty($location_ns) && !empty($location_id)) {
646 $notloc->location_id = $location_id;
647 $notloc->location_ns = $location_ns;
650 if (!empty($rendered)) {
651 $notice->rendered = $rendered;
653 $notice->rendered = common_render_content($final,
654 $notice->getProfile(),
655 $notice->hasParent() ? $notice->getParent() : null);
659 if ($notice->isRepeat()) {
660 $notice->verb = ActivityVerb::SHARE;
661 $notice->object_type = ActivityObject::ACTIVITY;
663 $notice->verb = ActivityVerb::POST;
666 $notice->verb = $verb;
669 if (empty($object_type)) {
670 $notice->object_type = (empty($notice->reply_to)) ? ActivityObject::NOTE : ActivityObject::COMMENT;
672 $notice->object_type = $object_type;
675 if (is_null($scope) && $reply instanceof Notice) {
676 $notice->scope = $reply->scope;
678 $notice->scope = $scope;
681 $notice->scope = self::figureOutScope($profile, $groups, $notice->scope);
683 if (Event::handle('StartNoticeSave', array(&$notice))) {
685 // XXX: some of these functions write to the DB
688 $notice->insert(); // throws exception on failure, if successful we have an ->id
690 if (($notloc->lat && $notloc->lon) || ($notloc->location_id && $notloc->location_ns)) {
691 $notloc->notice_id = $notice->getID();
692 $notloc->insert(); // store the notice location if it had any information
694 } catch (Exception $e) {
695 // Let's test if we managed initial insert, which would imply
696 // failing on some update-part (check 'insert()'). Delete if
697 // something had been stored to the database.
698 if (!empty($notice->id)) {
705 // Only save 'attention' and metadata stuff (URLs, tags...) stuff if
706 // the activityverb is a POST (since stuff like repeat, favorite etc.
707 // reasonably handle notifications themselves.
708 if (ActivityUtils::compareVerbs($notice->verb, array(ActivityVerb::POST))) {
709 if (isset($replies)) {
710 $notice->saveKnownReplies($replies);
712 $notice->saveReplies();
716 $notice->saveKnownTags($tags);
721 // Note: groups may save tags, so must be run after tags are saved
722 // to avoid errors on duplicates.
723 // Note: groups should always be set.
725 $notice->saveKnownGroups($groups);
728 $notice->saveKnownUrls($urls);
735 // Prepare inbox delivery, may be queued to background.
736 $notice->distribute();
742 static function saveActivity(Activity $act, Profile $actor, array $options=array())
744 // First check if we're going to let this Activity through from the specific actor
745 if (!$actor->hasRight(Right::NEWNOTICE)) {
746 common_log(LOG_WARNING, "Attempted post from user disallowed to post: " . $actor->getNickname());
748 // TRANS: Client exception thrown when a user tries to post while being banned.
749 throw new ClientException(_m('You are banned from posting notices on this site.'), 403);
751 if (common_config('throttle', 'enabled') && !self::checkEditThrottle($actor->id)) {
752 common_log(LOG_WARNING, 'Excessive posting by profile #' . $actor->id . '; throttled.');
753 // TRANS: Client exception thrown when a user tries to post too many notices in a given time frame.
754 throw new ClientException(_m('Too many notices too fast; take a breather '.
755 'and post again in a few minutes.'));
758 // Get ActivityObject properties
760 if (!empty($act->id)) {
762 $options['uri'] = $act->id;
763 $options['url'] = $act->link;
765 $actobj = count($act->objects)===1 ? $act->objects[0] : null;
766 if (!is_null($actobj) && !empty($actobj->id)) {
767 $options['uri'] = $actobj->id;
769 $options['url'] = $actobj->link;
770 } elseif (preg_match('!^https?://!', $actobj->id)) {
771 $options['url'] = $actobj->id;
778 'is_local' => $actor->isLocal() ? self::LOCAL_PUBLIC : self::REMOTE,
779 'mentions' => array(),
783 'source' => 'unknown',
788 'distribute' => true);
790 // options will have default values when nothing has been supplied
791 $options = array_merge($defaults, $options);
792 foreach (array_keys($defaults) as $key) {
793 // Only convert the keynames we specify ourselves from 'defaults' array into variables
794 $$key = $options[$key];
796 extract($options, EXTR_SKIP);
799 $stored = new Notice();
800 if (!empty($uri) && !ActivityUtils::compareVerbs($act->verb, array(ActivityVerb::DELETE))) {
802 if ($stored->find()) {
803 common_debug('cannot create duplicate Notice URI: '.$stored->uri);
804 // I _assume_ saving a Notice with a colliding URI means we're really trying to
805 // save the same notice again...
806 throw new AlreadyFulfilledException('Notice URI already exists');
810 $autosource = common_config('public', 'autosource');
812 // Sandboxed are non-false, but not 1, either
813 if (!$actor->hasRight(Right::PUBLICNOTICE) ||
814 ($source && $autosource && in_array($source, $autosource))) {
815 // FIXME: ...what about remote nonpublic? Hmmm. That is, if we sandbox remote profiles...
816 $stored->is_local = Notice::LOCAL_NONPUBLIC;
818 $stored->is_local = intval($is_local);
821 if (!$stored->isLocal()) {
822 // Only do these checks for non-local notices. Local notices will generate these values later.
823 if (!common_valid_http_url($url)) {
824 common_debug('Bad notice URL: ['.$url.'], URI: ['.$uri.']. Cannot link back to original! This is normal for shared notices etc.');
827 throw new ServerException('No URI for remote notice. Cannot accept that.');
831 $stored->profile_id = $actor->id;
832 $stored->source = $source;
835 $stored->verb = $act->verb;
837 // Notice content. We trust local users to provide HTML we like, but of course not remote users.
838 // FIXME: What about local users importing feeds? Mirror functions must filter out bad HTML first...
839 $content = $act->content ?: $act->summary;
840 if (is_null($content) && !is_null($actobj)) {
841 $content = $actobj->content ?: $actobj->summary;
843 $stored->rendered = $actor->isLocal() ? $content : common_purify($content);
844 // yeah, just don't use getRendered() here since it's not inserted yet ;)
845 $stored->content = common_strip_html($stored->rendered);
846 if (trim($stored->content) === '') {
847 // TRANS: Error message when the plain text content of a notice has zero length.
848 throw new ClientException(_('Empty notice content, will not save this.'));
851 // Maybe a missing act-time should be fatal if the actor is not local?
852 if (!empty($act->time)) {
853 $stored->created = common_sql_date($act->time);
855 $stored->created = common_sql_now();
859 if ($act->context instanceof ActivityContext && !empty($act->context->replyToID)) {
860 $reply = self::getKV('uri', $act->context->replyToID);
862 if (!$reply instanceof Notice && $act->target instanceof ActivityObject) {
863 $reply = self::getKV('uri', $act->target->id);
866 if ($reply instanceof Notice) {
867 if (!$reply->inScope($actor)) {
868 // TRANS: Client error displayed when trying to reply to a notice a the target has no access to.
869 // TRANS: %1$s is a user nickname, %2$d is a notice ID (number).
870 throw new ClientException(sprintf(_m('%1$s has no right to reply to notice %2$d.'), $actor->getNickname(), $reply->id), 403);
873 $stored->reply_to = $reply->id;
874 $stored->conversation = $reply->conversation;
876 // If the original is private to a group, and notice has no group specified,
877 // make it to the same group(s)
878 if (empty($groups) && ($reply->scope & Notice::GROUP_SCOPE)) {
879 $replyGroups = $reply->getGroups();
880 foreach ($replyGroups as $group) {
881 if ($actor->isMember($group)) {
882 $groups[] = $group->id;
887 if (is_null($scope)) {
888 $scope = $reply->scope;
891 // If we don't know the reply, we might know the conversation!
892 // This will happen if a known remote user replies to an
893 // unknown remote user - within a known conversation.
894 if (empty($stored->conversation) and !empty($act->context->conversation)) {
895 $conv = Conversation::getKV('uri', $act->context->conversation);
896 if ($conv instanceof Conversation) {
897 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.').');
899 // Conversation entry with specified URI was not found, so we must create it.
900 common_debug('Conversation URI not found, so we will create it with the URI given in the context of the activity: '.$act->context->conversation);
901 // The insert in Conversation::create throws exception on failure
902 $conv = Conversation::create($act->context->conversation, $stored->created);
904 $stored->conversation = $conv->getID();
909 // If it's not part of a conversation, it's the beginning of a new conversation.
910 if (empty($stored->conversation)) {
911 $conv = Conversation::create();
912 $stored->conversation = $conv->getID();
917 if ($act->context instanceof ActivityContext) {
918 if ($act->context->location instanceof Location) {
919 $notloc = Notice_location::fromLocation($act->context->location);
922 $act->context = new ActivityContext();
925 $stored->scope = self::figureOutScope($actor, $groups, $scope);
927 foreach ($act->categories as $cat) {
929 $term = common_canonical_tag($cat->term);
936 foreach ($act->enclosures as $href) {
937 // @todo FIXME: Save these locally or....?
941 if (ActivityUtils::compareVerbs($stored->verb, array(ActivityVerb::POST))) {
942 if (empty($act->objects[0]->type)) {
943 // Default type for the post verb is 'note', but we know it's
944 // a 'comment' if it is in reply to something.
945 $stored->object_type = empty($stored->reply_to) ? ActivityObject::NOTE : ActivityObject::COMMENT;
947 //TODO: Is it safe to always return a relative URI? The
948 // JSON version of ActivityStreams always use it, so we
949 // should definitely be able to handle it...
950 $stored->object_type = ActivityUtils::resolveUri($act->objects[0]->type, true);
954 if (Event::handle('StartNoticeSave', array(&$stored))) {
955 // XXX: some of these functions write to the DB
958 $result = $stored->insert(); // throws exception on error
960 if ($notloc instanceof Notice_location) {
961 $notloc->notice_id = $stored->getID();
965 $orig = clone($stored); // for updating later in this try clause
968 Event::handle('StoreActivityObject', array($act, $stored, $options, &$object));
969 if (empty($object)) {
970 throw new NoticeSaveException('Unsuccessful call to StoreActivityObject '._ve($stored->getUri()) . ': '._ve($act->asString()));
973 // If something changed in the Notice during StoreActivityObject
974 $stored->update($orig);
975 } catch (Exception $e) {
976 if (empty($stored->id)) {
977 common_debug('Failed to save stored object entry in database ('.$e->getMessage().')');
979 common_debug('Failed to store activity object in database ('.$e->getMessage().'), deleting notice id '.$stored->id);
985 if (!$stored instanceof Notice) {
986 throw new ServerException('StartNoticeSave did not give back a Notice');
989 // Only save 'attention' and metadata stuff (URLs, tags...) stuff if
990 // the activityverb is a POST (since stuff like repeat, favorite etc.
991 // reasonably handle notifications themselves.
992 if (ActivityUtils::compareVerbs($stored->verb, array(ActivityVerb::POST))) {
995 $stored->saveKnownTags($tags);
1000 // Note: groups may save tags, so must be run after tags are saved
1001 // to avoid errors on duplicates.
1002 $stored->saveAttentions($act->context->attention);
1004 if (!empty($urls)) {
1005 $stored->saveKnownUrls($urls);
1007 $stored->saveUrls();
1012 // Prepare inbox delivery, may be queued to background.
1013 $stored->distribute();
1019 static public function figureOutScope(Profile $actor, array $groups, $scope=null) {
1020 $scope = is_null($scope) ? self::defaultScope() : intval($scope);
1022 // For private streams
1024 $user = $actor->getUser();
1025 // FIXME: We can't do bit comparison with == (Legacy StatusNet thing. Let's keep it for now.)
1026 if ($user->private_stream && ($scope === Notice::PUBLIC_SCOPE || $scope === Notice::SITE_SCOPE)) {
1027 $scope |= Notice::FOLLOWER_SCOPE;
1029 } catch (NoSuchUserException $e) {
1030 // TODO: Not a local user, so we don't know about scope preferences... yet!
1033 // Force the scope for private groups
1034 foreach ($groups as $group_id) {
1036 $group = User_group::getByID($group_id);
1037 if ($group->force_scope) {
1038 $scope |= Notice::GROUP_SCOPE;
1041 } catch (Exception $e) {
1042 common_log(LOG_ERR, 'Notice figureOutScope threw exception: '.$e->getMessage());
1049 function blowOnInsert($conversation = false)
1051 $this->blowStream('profile:notice_ids:%d', $this->profile_id);
1053 if ($this->isPublic()) {
1054 $this->blowStream('public');
1055 $this->blowStream('networkpublic');
1058 if ($this->conversation) {
1059 self::blow('notice:list-ids:conversation:%s', $this->conversation);
1060 self::blow('conversation:notice_count:%d', $this->conversation);
1063 if ($this->isRepeat()) {
1064 // XXX: we should probably only use one of these
1065 $this->blowStream('notice:repeats:%d', $this->repeat_of);
1066 self::blow('notice:list-ids:repeat_of:%d', $this->repeat_of);
1069 $original = Notice::getKV('id', $this->repeat_of);
1071 if ($original instanceof Notice) {
1072 $originalUser = User::getKV('id', $original->profile_id);
1073 if ($originalUser instanceof User) {
1074 $this->blowStream('user:repeats_of_me:%d', $originalUser->id);
1078 $profile = Profile::getKV($this->profile_id);
1080 if ($profile instanceof Profile) {
1081 $profile->blowNoticeCount();
1084 $ptags = $this->getProfileTags();
1085 foreach ($ptags as $ptag) {
1086 $ptag->blowNoticeStreamCache();
1091 * Clear cache entries related to this notice at delete time.
1092 * Necessary to avoid breaking paging on public, profile timelines.
1094 function blowOnDelete()
1096 $this->blowOnInsert();
1098 self::blow('profile:notice_ids:%d;last', $this->profile_id);
1100 if ($this->isPublic()) {
1101 self::blow('public;last');
1102 self::blow('networkpublic;last');
1105 self::blow('fave:by_notice', $this->id);
1107 if ($this->conversation) {
1108 // In case we're the first, will need to calc a new root.
1109 self::blow('notice:conversation_root:%d', $this->conversation);
1112 $ptags = $this->getProfileTags();
1113 foreach ($ptags as $ptag) {
1114 $ptag->blowNoticeStreamCache(true);
1118 function blowStream()
1120 $c = self::memcache();
1126 $args = func_get_args();
1127 $format = array_shift($args);
1128 $keyPart = vsprintf($format, $args);
1129 $cacheKey = Cache::key($keyPart);
1130 $c->delete($cacheKey);
1132 // delete the "last" stream, too, if this notice is
1133 // older than the top of that stream
1135 $lastKey = $cacheKey.';last';
1137 $lastStr = $c->get($lastKey);
1139 if ($lastStr !== false) {
1140 $window = explode(',', $lastStr);
1141 $lastID = $window[0];
1142 $lastNotice = Notice::getKV('id', $lastID);
1143 if (!$lastNotice instanceof Notice // just weird
1144 || strtotime($lastNotice->created) >= strtotime($this->created)) {
1145 $c->delete($lastKey);
1150 /** save all urls in the notice to the db
1152 * follow redirects and save all available file information
1153 * (mimetype, date, size, oembed, etc.)
1157 function saveUrls() {
1158 if (common_config('attachments', 'process_links')) {
1159 common_replace_urls_callback($this->content, array($this, 'saveUrl'), $this);
1164 * Save the given URLs as related links/attachments to the db
1166 * follow redirects and save all available file information
1167 * (mimetype, date, size, oembed, etc.)
1171 function saveKnownUrls($urls)
1173 if (common_config('attachments', 'process_links')) {
1174 // @fixme validation?
1175 foreach (array_unique($urls) as $url) {
1176 $this->saveUrl($url, $this);
1184 function saveUrl($url, Notice $notice) {
1186 File::processNew($url, $notice);
1187 } catch (ServerException $e) {
1188 // Could not save URL. Log it?
1192 static function checkDupes($profile_id, $content) {
1193 $profile = Profile::getKV($profile_id);
1194 if (!$profile instanceof Profile) {
1197 $notice = $profile->getNotices(0, CachingNoticeStream::CACHE_WINDOW);
1198 if (!empty($notice)) {
1200 while ($notice->fetch()) {
1201 if (time() - strtotime($notice->created) >= common_config('site', 'dupelimit')) {
1203 } else if ($notice->content == $content) {
1208 // If we get here, oldest item in cache window is not
1209 // old enough for dupe limit; do direct check against DB
1210 $notice = new Notice();
1211 $notice->profile_id = $profile_id;
1212 $notice->content = $content;
1213 $threshold = common_sql_date(time() - common_config('site', 'dupelimit'));
1214 $notice->whereAdd(sprintf("created > '%s'", $notice->escape($threshold)));
1216 $cnt = $notice->count();
1220 static function checkEditThrottle($profile_id) {
1221 $profile = Profile::getKV($profile_id);
1222 if (!$profile instanceof Profile) {
1225 // Get the Nth notice
1226 $notice = $profile->getNotices(common_config('throttle', 'count') - 1, 1);
1227 if ($notice && $notice->fetch()) {
1228 // If the Nth notice was posted less than timespan seconds ago
1229 if (time() - strtotime($notice->created) <= common_config('throttle', 'timespan')) {
1234 // Either not N notices in the stream, OR the Nth was not posted within timespan seconds
1238 protected $_attachments = array();
1240 function attachments() {
1241 if (isset($this->_attachments[$this->id])) {
1242 return $this->_attachments[$this->id];
1245 $f2ps = File_to_post::listGet('post_id', array($this->id));
1247 foreach ($f2ps[$this->id] as $f2p) {
1248 $ids[] = $f2p->file_id;
1251 $files = File::multiGet('id', $ids);
1252 $this->_attachments[$this->id] = $files->fetchAll();
1253 return $this->_attachments[$this->id];
1256 function _setAttachments($attachments)
1258 $this->_attachments[$this->id] = $attachments;
1261 static function publicStream($offset=0, $limit=20, $since_id=null, $max_id=null)
1263 $stream = new PublicNoticeStream();
1264 return $stream->getNotices($offset, $limit, $since_id, $max_id);
1267 static function conversationStream($id, $offset=0, $limit=20, $since_id=null, $max_id=null)
1269 $stream = new ConversationNoticeStream($id);
1270 return $stream->getNotices($offset, $limit, $since_id, $max_id);
1274 * Is this notice part of an active conversation?
1276 * @return boolean true if other messages exist in the same
1277 * conversation, false if this is the only one
1279 function hasConversation()
1281 if (empty($this->conversation)) {
1282 // this notice is not part of a conversation apparently
1283 // FIXME: all notices should have a conversation value, right?
1287 $stream = new ConversationNoticeStream($this->conversation);
1288 $notice = $stream->getNotices(/*offset*/ 1, /*limit*/ 1);
1290 // if our "offset 1, limit 1" query got a result, return true else false
1291 return $notice->N > 0;
1295 * Grab the earliest notice from this conversation.
1297 * @return Notice or null
1299 function conversationRoot($profile=-1)
1301 // XXX: can this happen?
1303 if (empty($this->conversation)) {
1307 // Get the current profile if not specified
1309 if (is_int($profile) && $profile == -1) {
1310 $profile = Profile::current();
1313 // If this notice is out of scope, no root for you!
1315 if (!$this->inScope($profile)) {
1319 // If this isn't a reply to anything, then it's its own
1320 // root if it's the earliest notice in the conversation:
1322 if (empty($this->reply_to)) {
1324 $root->conversation = $this->conversation;
1325 $root->orderBy('notice.created ASC');
1326 $root->find(true); // true means "fetch first result"
1331 if (is_null($profile)) {
1332 $keypart = sprintf('notice:conversation_root:%d:null', $this->id);
1334 $keypart = sprintf('notice:conversation_root:%d:%d',
1339 $root = self::cacheGet($keypart);
1341 if ($root !== false && $root->inScope($profile)) {
1348 $parent = $last->getParent();
1349 if ($parent->inScope($profile)) {
1353 } catch (NoParentNoticeException $e) {
1354 // Latest notice has no parent
1355 } catch (NoResultException $e) {
1356 // Notice was not found, so we can't go further up in the tree.
1357 // FIXME: Maybe we should do this in a more stable way where deleted
1358 // notices won't break conversation chains?
1360 // No parent, or parent out of scope
1365 self::cacheSet($keypart, $root);
1371 * Pull up a full list of local recipients who will be getting
1372 * this notice in their inbox. Results will be cached, so don't
1373 * change the input data wily-nilly!
1375 * @param array $groups optional list of Group objects;
1376 * if left empty, will be loaded from group_inbox records
1377 * @param array $recipient optional list of reply profile ids
1378 * if left empty, will be loaded from reply records
1379 * @return array associating recipient user IDs with an inbox source constant
1381 function whoGets(array $groups=null, array $recipients=null)
1383 $c = self::memcache();
1386 $ni = $c->get(Cache::key('notice:who_gets:'.$this->id));
1387 if ($ni !== false) {
1392 if (is_null($recipients)) {
1393 $recipients = $this->getReplies();
1398 // Give plugins a chance to add folks in at start...
1399 if (Event::handle('StartNoticeWhoGets', array($this, &$ni))) {
1401 $users = $this->getSubscribedUsers();
1402 foreach ($users as $id) {
1403 $ni[$id] = NOTICE_INBOX_SOURCE_SUB;
1406 if (is_null($groups)) {
1407 $groups = $this->getGroups();
1409 foreach ($groups as $group) {
1410 $users = $group->getUserMembers();
1411 foreach ($users as $id) {
1412 if (!array_key_exists($id, $ni)) {
1413 $ni[$id] = NOTICE_INBOX_SOURCE_GROUP;
1418 $ptAtts = $this->getAttentionsFromProfileTags();
1419 foreach ($ptAtts as $key=>$val) {
1420 if (!array_key_exists($key, $ni)) {
1425 foreach ($recipients as $recipient) {
1426 if (!array_key_exists($recipient, $ni)) {
1427 $ni[$recipient] = NOTICE_INBOX_SOURCE_REPLY;
1431 // Exclude any deleted, non-local, or blocking recipients.
1432 $profile = $this->getProfile();
1433 $originalProfile = null;
1434 if ($this->isRepeat()) {
1435 // Check blocks against the original notice's poster as well.
1436 $original = Notice::getKV('id', $this->repeat_of);
1437 if ($original instanceof Notice) {
1438 $originalProfile = $original->getProfile();
1442 foreach ($ni as $id => $source) {
1444 $user = User::getKV('id', $id);
1445 if (!$user instanceof User ||
1446 $user->hasBlocked($profile) ||
1447 ($originalProfile && $user->hasBlocked($originalProfile))) {
1450 } catch (UserNoProfileException $e) {
1451 // User doesn't have a profile; invalid; skip them.
1456 // Give plugins a chance to filter out...
1457 Event::handle('EndNoticeWhoGets', array($this, &$ni));
1461 // XXX: pack this data better
1462 $c->set(Cache::key('notice:who_gets:'.$this->id), $ni);
1468 function getSubscribedUsers()
1472 if(common_config('db','quote_identifiers'))
1473 $user_table = '"user"';
1474 else $user_table = 'user';
1478 'FROM '. $user_table .' JOIN subscription '.
1479 'ON '. $user_table .'.id = subscription.subscriber ' .
1480 'WHERE subscription.subscribed = %d ';
1482 $user->query(sprintf($qry, $this->profile_id));
1486 while ($user->fetch()) {
1495 function getProfileTags()
1497 $profile = $this->getProfile();
1498 $list = $profile->getOtherTags($profile);
1501 while($list->fetch()) {
1502 $ptags[] = clone($list);
1508 public function getAttentionsFromProfileTags()
1511 $ptags = $this->getProfileTags();
1512 foreach ($ptags as $ptag) {
1513 $users = $ptag->getUserSubscribers();
1514 foreach ($users as $id) {
1515 $ni[$id] = NOTICE_INBOX_SOURCE_PROFILE_TAG;
1522 * Record this notice to the given group inboxes for delivery.
1523 * Overrides the regular parsing of !group markup.
1525 * @param string $group_ids
1526 * @fixme might prefer URIs as identifiers, as for replies?
1527 * best with generalizations on user_group to support
1528 * remote groups better.
1530 function saveKnownGroups(array $group_ids)
1533 foreach (array_unique($group_ids) as $id) {
1534 $group = User_group::getKV('id', $id);
1535 if ($group instanceof User_group) {
1536 common_log(LOG_DEBUG, "Local delivery to group id $id, $group->nickname");
1537 $result = $this->addToGroupInbox($group);
1539 common_log_db_error($gi, 'INSERT', __FILE__);
1542 if (common_config('group', 'addtag')) {
1543 // we automatically add a tag for every group name, too
1545 $tag = Notice_tag::pkeyGet(array('tag' => common_canonical_tag($group->nickname),
1546 'notice_id' => $this->id));
1548 if (is_null($tag)) {
1549 $this->saveTag($group->nickname);
1553 $groups[] = clone($group);
1555 common_log(LOG_ERR, "Local delivery to group id $id skipped, doesn't exist");
1562 function addToGroupInbox(User_group $group)
1564 $gi = Group_inbox::pkeyGet(array('group_id' => $group->id,
1565 'notice_id' => $this->id));
1567 if (!$gi instanceof Group_inbox) {
1569 $gi = new Group_inbox();
1571 $gi->group_id = $group->id;
1572 $gi->notice_id = $this->id;
1573 $gi->created = $this->created;
1575 $result = $gi->insert();
1578 common_log_db_error($gi, 'INSERT', __FILE__);
1579 // TRANS: Server exception thrown when an update for a group inbox fails.
1580 throw new ServerException(_('Problem saving group inbox.'));
1583 self::blow('user_group:notice_ids:%d', $gi->group_id);
1589 function saveAttentions(array $uris)
1591 foreach ($uris as $uri=>$type) {
1593 $target = Profile::fromUri($uri);
1594 } catch (UnknownUriException $e) {
1595 common_log(LOG_WARNING, "Unable to determine profile for URI '$uri'");
1600 $this->saveAttention($target);
1601 } catch (AlreadyFulfilledException $e) {
1602 common_debug('Attention already exists: '.var_export($e->getMessage(),true));
1603 } catch (Exception $e) {
1604 common_log(LOG_ERR, "Could not save notice id=={$this->getID()} attention for profile id=={$target->getID()}: {$e->getMessage()}");
1610 * Saves an attention for a profile (user or group) which means
1611 * it shows up in their home feed and such.
1613 function saveAttention(Profile $target, $reason=null)
1615 if ($target->isGroup()) {
1616 // FIXME: Make sure we check (for both local and remote) users are in the groups they send to!
1618 // legacy notification method, will still be in use for quite a while I think
1619 $this->addToGroupInbox($target->getGroup());
1621 if ($target->hasBlocked($this->getProfile())) {
1622 common_log(LOG_INFO, "Not saving reply to profile {$target->id} ($uri) from sender {$sender->id} because of a block.");
1627 if ($target->isLocal()) {
1628 // legacy notification method, will still be in use for quite a while I think
1629 $this->saveReply($target->getID());
1632 $att = Attention::saveNew($this, $target, $reason);
1634 self::blow('reply:stream:%d', $target->getID());
1639 * Save reply records indicating that this notice needs to be
1640 * delivered to the local users with the given URIs.
1642 * Since this is expected to be used when saving foreign-sourced
1643 * messages, we won't deliver to any remote targets as that's the
1644 * source service's responsibility.
1646 * Mail notifications etc will be handled later.
1648 * @param array $uris Array of unique identifier URIs for recipients
1650 function saveKnownReplies(array $uris)
1656 $sender = $this->getProfile();
1658 foreach (array_unique($uris) as $uri) {
1660 $profile = Profile::fromUri($uri);
1661 } catch (UnknownUriException $e) {
1662 common_log(LOG_WARNING, "Unable to determine profile for URI '$uri'");
1666 if ($profile->hasBlocked($sender)) {
1667 common_log(LOG_INFO, "Not saving reply to profile {$profile->id} ($uri) from sender {$sender->id} because of a block.");
1671 $this->saveReply($profile->getID());
1672 self::blow('reply:stream:%d', $profile->getID());
1677 * Pull @-replies from this message's content in StatusNet markup format
1678 * and save reply records indicating that this message needs to be
1679 * delivered to those users.
1681 * Mail notifications to local profiles will be sent later.
1683 * @return array of integer profile IDs
1686 function saveReplies()
1688 $sender = $this->getProfile();
1692 // If it's a reply, save for the replied-to author
1694 $parent = $this->getParent();
1695 $parentauthor = $parent->getProfile();
1696 $this->saveReply($parentauthor->getID());
1697 $replied[$parentauthor->getID()] = 1;
1698 self::blow('reply:stream:%d', $parentauthor->getID());
1699 } catch (NoParentNoticeException $e) {
1700 // Not a reply, since it has no parent!
1702 } catch (NoResultException $e) {
1703 // Parent notice was probably deleted
1707 // @todo ideally this parser information would only
1708 // be calculated once.
1710 $mentions = common_find_mentions($this->content, $sender, $parent);
1712 foreach ($mentions as $mention) {
1714 foreach ($mention['mentioned'] as $mentioned) {
1716 // skip if they're already covered
1717 if (array_key_exists($mentioned->id, $replied)) {
1721 // Don't save replies from blocked profile to local user
1722 if ($mentioned->hasBlocked($sender)) {
1726 $this->saveReply($mentioned->id);
1727 $replied[$mentioned->id] = 1;
1728 self::blow('reply:stream:%d', $mentioned->id);
1732 $recipientIds = array_keys($replied);
1734 return $recipientIds;
1737 function saveReply($profileId)
1739 $reply = new Reply();
1741 $reply->notice_id = $this->id;
1742 $reply->profile_id = $profileId;
1743 $reply->modified = $this->created;
1750 protected $_attentionids = array();
1753 * Pull the complete list of known activity context attentions for this notice.
1755 * @return array of integer profile ids (also group profiles)
1757 function getAttentionProfileIDs()
1759 if (!isset($this->_attentionids[$this->getID()])) {
1760 $atts = Attention::multiGet('notice_id', array($this->getID()));
1761 // (array)null means empty array
1762 $this->_attentionids[$this->getID()] = (array)$atts->fetchAll('profile_id');
1764 return $this->_attentionids[$this->getID()];
1767 protected $_replies = array();
1770 * Pull the complete list of @-mentioned profile IDs for this notice.
1772 * @return array of integer profile ids
1774 function getReplies()
1776 if (!isset($this->_replies[$this->getID()])) {
1777 $mentions = Reply::multiGet('notice_id', array($this->getID()));
1778 $this->_replies[$this->getID()] = $mentions->fetchAll('profile_id');
1780 return $this->_replies[$this->getID()];
1783 function _setReplies($replies)
1785 $this->_replies[$this->getID()] = $replies;
1789 * Pull the complete list of @-reply targets for this notice.
1791 * @return array of Profiles
1793 function getAttentionProfiles()
1795 $ids = array_unique(array_merge($this->getReplies(), $this->getGroupProfileIDs(), $this->getAttentionProfileIDs()));
1797 $profiles = Profile::multiGet('id', (array)$ids);
1799 return $profiles->fetchAll();
1803 * Send e-mail notifications to local @-reply targets.
1805 * Replies must already have been saved; this is expected to be run
1806 * from the distrib queue handler.
1808 function sendReplyNotifications()
1810 // Don't send reply notifications for repeats
1811 if ($this->isRepeat()) {
1815 $recipientIds = $this->getReplies();
1816 if (Event::handle('StartNotifyMentioned', array($this, &$recipientIds))) {
1817 require_once INSTALLDIR.'/lib/mail.php';
1819 foreach ($recipientIds as $recipientId) {
1821 $user = User::getByID($recipientId);
1822 mail_notify_attn($user, $this);
1823 } catch (NoResultException $e) {
1827 Event::handle('EndNotifyMentioned', array($this, $recipientIds));
1832 * Pull list of Profile IDs of groups this notice addresses.
1834 * @return array of Group _profile_ IDs
1837 function getGroupProfileIDs()
1841 foreach ($this->getGroups() as $group) {
1842 $ids[] = $group->profile_id;
1849 * Pull list of groups this notice needs to be delivered to,
1850 * as previously recorded by saveKnownGroups().
1852 * @return array of Group objects
1855 protected $_groups = array();
1857 function getGroups()
1859 // Don't save groups for repeats
1861 if (!empty($this->repeat_of)) {
1865 if (isset($this->_groups[$this->id])) {
1866 return $this->_groups[$this->id];
1869 $gis = Group_inbox::listGet('notice_id', array($this->id));
1873 foreach ($gis[$this->id] as $gi) {
1874 $ids[] = $gi->group_id;
1877 $groups = User_group::multiGet('id', $ids);
1878 $this->_groups[$this->id] = $groups->fetchAll();
1879 return $this->_groups[$this->id];
1882 function _setGroups($groups)
1884 $this->_groups[$this->id] = $groups;
1888 * Convert a notice into an activity for export.
1890 * @param Profile $scoped The currently logged in/scoped profile
1892 * @return Activity activity object representing this Notice.
1895 function asActivity(Profile $scoped=null)
1897 $act = self::cacheGet(Cache::codeKey('notice:as-activity:'.$this->id));
1899 if ($act instanceof Activity) {
1902 $act = new Activity();
1904 if (Event::handle('StartNoticeAsActivity', array($this, $act, $scoped))) {
1906 $act->id = $this->uri;
1907 $act->time = strtotime($this->created);
1909 $act->link = $this->getUrl();
1910 } catch (InvalidUrlException $e) {
1911 // The notice is probably a share or similar, which don't
1912 // have a representational URL of their own.
1914 $act->content = common_xml_safe_str($this->getRendered());
1916 $profile = $this->getProfile();
1918 $act->actor = $profile->asActivityObject();
1919 $act->actor->extra[] = $profile->profileInfo($scoped);
1921 $act->verb = $this->verb;
1923 if (!$this->repeat_of) {
1924 $act->objects[] = $this->asActivityObject();
1927 // XXX: should this be handled by default processing for object entry?
1931 $tags = $this->getTags();
1933 foreach ($tags as $tag) {
1934 $cat = new AtomCategory();
1937 $act->categories[] = $cat;
1941 // XXX: use Atom Media and/or File activity objects instead
1943 $attachments = $this->attachments();
1945 foreach ($attachments as $attachment) {
1946 // Include local attachments in Activity
1947 if (!empty($attachment->filename)) {
1948 $act->enclosures[] = $attachment->getEnclosure();
1952 $ctx = new ActivityContext();
1955 $reply = $this->getParent();
1956 $ctx->replyToID = $reply->getUri();
1957 $ctx->replyToUrl = $reply->getUrl(true); // true for fallback to local URL, less messy
1958 } catch (NoParentNoticeException $e) {
1959 // This is not a reply to something
1960 } catch (NoResultException $e) {
1961 // Parent notice was probably deleted
1965 $ctx->location = Notice_location::locFromStored($this);
1966 } catch (ServerException $e) {
1967 $ctx->location = null;
1972 if (!empty($this->conversation)) {
1973 $conv = Conversation::getKV('id', $this->conversation);
1974 if ($conv instanceof Conversation) {
1975 $ctx->conversation = $conv->uri;
1979 // This covers the legacy getReplies and getGroups too which get their data
1980 // from entries stored via Notice::saveNew (which we want to move away from)...
1981 foreach ($this->getAttentionProfiles() as $target) {
1982 // User and group profiles which get the attention of this notice
1983 $ctx->attention[$target->getUri()] = $target->getObjectType();
1986 switch ($this->scope) {
1987 case Notice::PUBLIC_SCOPE:
1988 $ctx->attention[ActivityContext::ATTN_PUBLIC] = ActivityObject::COLLECTION;
1990 case Notice::FOLLOWER_SCOPE:
1991 $surl = common_local_url("subscribers", array('nickname' => $profile->nickname));
1992 $ctx->attention[$surl] = ActivityObject::COLLECTION;
1996 $act->context = $ctx;
1998 $source = $this->getSource();
2000 if ($source instanceof Notice_source) {
2001 $act->generator = ActivityObject::fromNoticeSource($source);
2006 $atom_feed = $profile->getAtomFeed();
2008 if (!empty($atom_feed)) {
2010 $act->source = new ActivitySource();
2012 // XXX: we should store the actual feed ID
2014 $act->source->id = $atom_feed;
2016 // XXX: we should store the actual feed title
2018 $act->source->title = $profile->getBestName();
2020 $act->source->links['alternate'] = $profile->profileurl;
2021 $act->source->links['self'] = $atom_feed;
2023 $act->source->icon = $profile->avatarUrl(AVATAR_PROFILE_SIZE);
2025 $notice = $profile->getCurrentNotice();
2027 if ($notice instanceof Notice) {
2028 $act->source->updated = self::utcDate($notice->created);
2031 $user = User::getKV('id', $profile->id);
2033 if ($user instanceof User) {
2034 $act->source->links['license'] = common_config('license', 'url');
2038 if ($this->isLocal()) {
2039 $act->selfLink = common_local_url('ApiStatusesShow', array('id' => $this->id,
2040 'format' => 'atom'));
2041 $act->editLink = $act->selfLink;
2044 Event::handle('EndNoticeAsActivity', array($this, $act, $scoped));
2047 self::cacheSet(Cache::codeKey('notice:as-activity:'.$this->id), $act);
2052 // This has gotten way too long. Needs to be sliced up into functional bits
2053 // or ideally exported to a utility class.
2055 function asAtomEntry($namespace=false,
2058 Profile $scoped=null)
2060 $act = $this->asActivity($scoped);
2061 $act->extra[] = $this->noticeInfo($scoped);
2062 return $act->asString($namespace, $author, $source);
2066 * Extra notice info for atom entries
2068 * Clients use some extra notice info in the atom stream.
2069 * This gives it to them.
2071 * @param Profile $scoped The currently logged in/scoped profile
2073 * @return array representation of <statusnet:notice_info> element
2076 function noticeInfo(Profile $scoped=null)
2078 // local notice ID (useful to clients for ordering)
2080 $noticeInfoAttr = array('local_id' => $this->id);
2084 $ns = $this->getSource();
2086 if ($ns instanceof Notice_source) {
2087 $noticeInfoAttr['source'] = $ns->code;
2088 if (!empty($ns->url)) {
2089 $noticeInfoAttr['source_link'] = $ns->url;
2090 if (!empty($ns->name)) {
2091 $noticeInfoAttr['source'] = '<a href="'
2092 . htmlspecialchars($ns->url)
2093 . '" rel="nofollow">'
2094 . htmlspecialchars($ns->name)
2100 // favorite and repeated
2102 if ($scoped instanceof Profile) {
2103 $noticeInfoAttr['repeated'] = ($scoped->hasRepeated($this)) ? "true" : "false";
2106 if (!empty($this->repeat_of)) {
2107 $noticeInfoAttr['repeat_of'] = $this->repeat_of;
2110 Event::handle('StatusNetApiNoticeInfo', array($this, &$noticeInfoAttr, $scoped));
2112 return array('statusnet:notice_info', $noticeInfoAttr, null);
2116 * Returns an XML string fragment with a reference to a notice as an
2117 * Activity Streams noun object with the given element type.
2119 * Assumes that 'activity' namespace has been previously defined.
2121 * @param string $element one of 'subject', 'object', 'target'
2125 function asActivityNoun($element)
2127 $noun = $this->asActivityObject();
2128 return $noun->asString('activity:' . $element);
2131 public function asActivityObject()
2133 $object = new ActivityObject();
2135 if (Event::handle('StartActivityObjectFromNotice', array($this, &$object))) {
2136 $object->type = $this->object_type ?: ActivityObject::NOTE;
2137 $object->id = $this->getUri();
2138 //FIXME: = $object->title ?: sprintf(... because we might get a title from StartActivityObjectFromNotice
2139 $object->title = sprintf('New %1$s by %2$s', ActivityObject::canonicalType($object->type), $this->getProfile()->getNickname());
2140 $object->content = $this->getRendered();
2141 $object->link = $this->getUrl();
2143 $object->extra[] = array('status_net', array('notice_id' => $this->id));
2145 Event::handle('EndActivityObjectFromNotice', array($this, &$object));
2148 if (!$object instanceof ActivityObject) {
2149 common_log(LOG_ERR, 'Notice asActivityObject created something else for uri=='._ve($this->getUri()).': '._ve($object));
2150 throw new ServerException('Notice asActivityObject created something else.');
2157 * Determine which notice, if any, a new notice is in reply to.
2159 * For conversation tracking, we try to see where this notice fits
2160 * in the tree. Beware that this may very well give false positives
2161 * and add replies to wrong threads (if there have been newer posts
2162 * by the same user as we're replying to).
2164 * @param Profile $sender Author profile
2165 * @param string $content Final notice content
2167 * @return integer ID of replied-to notice, or null for not a reply.
2170 static function getInlineReplyTo(Profile $sender, $content)
2172 // Is there an initial @ or T?
2173 if (preg_match('/^T ([A-Z0-9]{1,64}) /', $content, $match)
2174 || preg_match('/^@([a-z0-9]{1,64})\s+/', $content, $match)) {
2175 $nickname = common_canonical_nickname($match[1]);
2180 // Figure out who that is.
2181 $recipient = common_relative_profile($sender, $nickname, common_sql_now());
2183 if ($recipient instanceof Profile) {
2184 // Get their last notice
2185 $last = $recipient->getCurrentNotice();
2186 if ($last instanceof Notice) {
2189 // Maybe in the future we want to handle something else below
2190 // so don't return getCurrentNotice() immediately.
2196 static function maxContent()
2198 $contentlimit = common_config('notice', 'contentlimit');
2199 // null => use global limit (distinct from 0!)
2200 if (is_null($contentlimit)) {
2201 $contentlimit = common_config('site', 'textlimit');
2203 return $contentlimit;
2206 static function contentTooLong($content)
2208 $contentlimit = self::maxContent();
2209 return ($contentlimit > 0 && !empty($content) && (mb_strlen($content) > $contentlimit));
2213 * Convenience function for posting a repeat of an existing message.
2215 * @param Profile $repeater Profile which is doing the repeat
2216 * @param string $source: posting source key, eg 'web', 'api', etc
2219 * @throws Exception on failure or permission problems
2221 function repeat(Profile $repeater, $source)
2223 $author = $this->getProfile();
2225 // TRANS: Message used to repeat a notice. RT is the abbreviation of 'retweet'.
2226 // TRANS: %1$s is the repeated user's name, %2$s is the repeated notice.
2227 $content = sprintf(_('RT @%1$s %2$s'),
2228 $author->getNickname(),
2231 $maxlen = self::maxContent();
2232 if ($maxlen > 0 && mb_strlen($content) > $maxlen) {
2233 // Web interface and current Twitter API clients will
2234 // pull the original notice's text, but some older
2235 // clients and RSS/Atom feeds will see this trimmed text.
2237 // Unfortunately this is likely to lose tags or URLs
2238 // at the end of long notices.
2239 $content = mb_substr($content, 0, $maxlen - 4) . ' ...';
2243 // Scope is same as this one's
2244 return self::saveNew($repeater->id,
2247 array('repeat_of' => $this->id,
2248 'scope' => $this->scope));
2251 // These are supposed to be in chron order!
2253 function repeatStream($limit=100)
2255 $cache = Cache::instance();
2257 if (empty($cache)) {
2258 $ids = $this->_repeatStreamDirect($limit);
2260 $idstr = $cache->get(Cache::key('notice:repeats:'.$this->id));
2261 if ($idstr !== false) {
2262 if (empty($idstr)) {
2265 $ids = explode(',', $idstr);
2268 $ids = $this->_repeatStreamDirect(100);
2269 $cache->set(Cache::key('notice:repeats:'.$this->id), implode(',', $ids));
2272 // We do a max of 100, so slice down to limit
2273 $ids = array_slice($ids, 0, $limit);
2277 return NoticeStream::getStreamByIds($ids);
2280 function _repeatStreamDirect($limit)
2282 $notice = new Notice();
2284 $notice->selectAdd(); // clears it
2285 $notice->selectAdd('id');
2287 $notice->repeat_of = $this->id;
2289 $notice->orderBy('created, id'); // NB: asc!
2291 if (!is_null($limit)) {
2292 $notice->limit(0, $limit);
2295 return $notice->fetchAll('id');
2298 static function locationOptions($lat, $lon, $location_id, $location_ns, $profile = null)
2302 if (!empty($location_id) && !empty($location_ns)) {
2303 $options['location_id'] = $location_id;
2304 $options['location_ns'] = $location_ns;
2306 $location = Location::fromId($location_id, $location_ns);
2308 if ($location instanceof Location) {
2309 $options['lat'] = $location->lat;
2310 $options['lon'] = $location->lon;
2313 } else if (!empty($lat) && !empty($lon)) {
2314 $options['lat'] = $lat;
2315 $options['lon'] = $lon;
2317 $location = Location::fromLatLon($lat, $lon);
2319 if ($location instanceof Location) {
2320 $options['location_id'] = $location->location_id;
2321 $options['location_ns'] = $location->location_ns;
2323 } else if (!empty($profile)) {
2324 if (isset($profile->lat) && isset($profile->lon)) {
2325 $options['lat'] = $profile->lat;
2326 $options['lon'] = $profile->lon;
2329 if (isset($profile->location_id) && isset($profile->location_ns)) {
2330 $options['location_id'] = $profile->location_id;
2331 $options['location_ns'] = $profile->location_ns;
2338 function clearAttentions()
2340 $att = new Attention();
2341 $att->notice_id = $this->getID();
2344 while ($att->fetch()) {
2345 // Can't do delete() on the object directly since it won't remove all of it
2346 $other = clone($att);
2352 function clearReplies()
2354 $replyNotice = new Notice();
2355 $replyNotice->reply_to = $this->id;
2357 //Null any notices that are replies to this notice
2359 if ($replyNotice->find()) {
2360 while ($replyNotice->fetch()) {
2361 $orig = clone($replyNotice);
2362 $replyNotice->reply_to = null;
2363 $replyNotice->update($orig);
2369 $reply = new Reply();
2370 $reply->notice_id = $this->id;
2372 if ($reply->find()) {
2373 while($reply->fetch()) {
2374 self::blow('reply:stream:%d', $reply->profile_id);
2382 function clearLocation()
2384 $loc = new Notice_location();
2385 $loc->notice_id = $this->id;
2392 function clearFiles()
2394 $f2p = new File_to_post();
2396 $f2p->post_id = $this->id;
2399 while ($f2p->fetch()) {
2403 // FIXME: decide whether to delete File objects
2404 // ...and related (actual) files
2407 function clearRepeats()
2409 $repeatNotice = new Notice();
2410 $repeatNotice->repeat_of = $this->id;
2412 //Null any notices that are repeats of this notice
2414 if ($repeatNotice->find()) {
2415 while ($repeatNotice->fetch()) {
2416 $orig = clone($repeatNotice);
2417 $repeatNotice->repeat_of = null;
2418 $repeatNotice->update($orig);
2423 function clearTags()
2425 $tag = new Notice_tag();
2426 $tag->notice_id = $this->id;
2429 while ($tag->fetch()) {
2430 self::blow('profile:notice_ids_tagged:%d:%s', $this->profile_id, Cache::keyize($tag->tag));
2431 self::blow('profile:notice_ids_tagged:%d:%s;last', $this->profile_id, Cache::keyize($tag->tag));
2432 self::blow('notice_tag:notice_ids:%s', Cache::keyize($tag->tag));
2433 self::blow('notice_tag:notice_ids:%s;last', Cache::keyize($tag->tag));
2441 function clearGroupInboxes()
2443 $gi = new Group_inbox();
2445 $gi->notice_id = $this->id;
2448 while ($gi->fetch()) {
2449 self::blow('user_group:notice_ids:%d', $gi->group_id);
2457 function distribute()
2459 // We always insert for the author so they don't
2461 Event::handle('StartNoticeDistribute', array($this));
2463 // If there's a failure, we want to _force_
2464 // distribution at this point.
2466 $json = json_encode((object)array('id' => $this->getID(),
2469 $qm = QueueManager::get();
2470 $qm->enqueue($json, 'distrib');
2471 } catch (Exception $e) {
2472 // If the exception isn't transient, this
2473 // may throw more exceptions as DQH does
2474 // its own enqueueing. So, we ignore them!
2476 $handler = new DistribQueueHandler();
2477 $handler->handle($this);
2478 } catch (Exception $e) {
2479 common_log(LOG_ERR, "emergency redistribution resulted in " . $e->getMessage());
2481 // Re-throw so somebody smarter can handle it.
2488 $result = parent::insert();
2490 if ($result === false) {
2491 common_log_db_error($this, 'INSERT', __FILE__);
2492 // TRANS: Server exception thrown when a stored object entry cannot be saved.
2493 throw new ServerException('Could not save Notice');
2496 // Profile::hasRepeated() abuses pkeyGet(), so we
2497 // have to clear manually
2498 if (!empty($this->repeat_of)) {
2499 $c = self::memcache();
2501 $ck = self::multicacheKey('Notice',
2502 array('profile_id' => $this->profile_id,
2503 'repeat_of' => $this->repeat_of));
2508 // Update possibly ID-dependent columns: URI, conversation
2509 // (now that INSERT has added the notice's local id)
2510 $orig = clone($this);
2513 // We can only get here if it's a local notice, since remote notices
2514 // should've bailed out earlier due to lacking a URI.
2515 if (empty($this->uri)) {
2516 $this->uri = sprintf('%s%s=%d:%s=%s',
2518 'noticeId', $this->id,
2519 'objectType', $this->getObjectType(true));
2523 if ($changed && $this->update($orig) === false) {
2524 common_log_db_error($notice, 'UPDATE', __FILE__);
2525 // TRANS: Server exception thrown when a notice cannot be updated.
2526 throw new ServerException(_('Problem saving notice.'));
2529 $this->blowOnInsert();
2535 * Get the source of the notice
2537 * @return Notice_source $ns A notice source object. 'code' is the only attribute
2538 * guaranteed to be populated.
2540 function getSource()
2542 if (empty($this->source)) {
2546 $ns = new Notice_source();
2547 switch ($this->source) {
2554 $ns->code = $this->source;
2557 $ns = Notice_source::getKV($this->source);
2559 $ns = new Notice_source();
2560 $ns->code = $this->source;
2561 $app = Oauth_application::getKV('name', $this->source);
2563 $ns->name = $app->name;
2564 $ns->url = $app->source_url;
2574 * Determine whether the notice was locally created
2576 * @return boolean locality
2579 public function isLocal()
2581 $is_local = intval($this->is_local);
2582 return ($is_local === self::LOCAL_PUBLIC || $is_local === self::LOCAL_NONPUBLIC);
2585 public function getScope()
2587 return intval($this->scope);
2590 public function isRepeat()
2592 return !empty($this->repeat_of);
2596 * Get the list of hash tags saved with this notice.
2598 * @return array of strings
2600 public function getTags()
2604 $keypart = sprintf('notice:tags:%d', $this->id);
2606 $tagstr = self::cacheGet($keypart);
2608 if ($tagstr !== false) {
2609 $tags = explode(',', $tagstr);
2611 $tag = new Notice_tag();
2612 $tag->notice_id = $this->id;
2614 while ($tag->fetch()) {
2615 $tags[] = $tag->tag;
2618 self::cacheSet($keypart, implode(',', $tags));
2624 static private function utcDate($dt)
2626 $dateStr = date('d F Y H:i:s', strtotime($dt));
2627 $d = new DateTime($dateStr, new DateTimeZone('UTC'));
2628 return $d->format(DATE_W3C);
2632 * Look up the creation timestamp for a given notice ID, even
2633 * if it's been deleted.
2636 * @return mixed string recorded creation timestamp, or false if can't be found
2638 public static function getAsTimestamp($id)
2641 throw new EmptyIdException('Notice');
2645 if (Event::handle('GetNoticeSqlTimestamp', array($id, &$timestamp))) {
2646 // getByID throws exception if $id isn't found
2647 $notice = Notice::getByID($id);
2648 $timestamp = $notice->created;
2651 if (empty($timestamp)) {
2652 throw new ServerException('No timestamp found for Notice with id=='._ve($id));
2658 * Build an SQL 'where' fragment for timestamp-based sorting from a since_id
2659 * parameter, matching notices posted after the given one (exclusive).
2661 * If the referenced notice can't be found, will return false.
2664 * @param string $idField
2665 * @param string $createdField
2666 * @return mixed string or false if no match
2668 public static function whereSinceId($id, $idField='id', $createdField='created')
2671 $since = Notice::getAsTimestamp($id);
2672 } catch (Exception $e) {
2675 return sprintf("($createdField = '%s' and $idField > %d) or ($createdField > '%s')", $since, $id, $since);
2679 * Build an SQL 'where' fragment for timestamp-based sorting from a since_id
2680 * parameter, matching notices posted after the given one (exclusive), and
2681 * if necessary add it to the data object's query.
2683 * @param DB_DataObject $obj
2685 * @param string $idField
2686 * @param string $createdField
2687 * @return mixed string or false if no match
2689 public static function addWhereSinceId(DB_DataObject $obj, $id, $idField='id', $createdField='created')
2691 $since = self::whereSinceId($id, $idField, $createdField);
2693 $obj->whereAdd($since);
2698 * Build an SQL 'where' fragment for timestamp-based sorting from a max_id
2699 * parameter, matching notices posted before the given one (inclusive).
2701 * If the referenced notice can't be found, will return false.
2704 * @param string $idField
2705 * @param string $createdField
2706 * @return mixed string or false if no match
2708 public static function whereMaxId($id, $idField='id', $createdField='created')
2711 $max = Notice::getAsTimestamp($id);
2712 } catch (Exception $e) {
2715 return sprintf("($createdField < '%s') or ($createdField = '%s' and $idField <= %d)", $max, $max, $id);
2719 * Build an SQL 'where' fragment for timestamp-based sorting from a max_id
2720 * parameter, matching notices posted before the given one (inclusive), and
2721 * if necessary add it to the data object's query.
2723 * @param DB_DataObject $obj
2725 * @param string $idField
2726 * @param string $createdField
2727 * @return mixed string or false if no match
2729 public static function addWhereMaxId(DB_DataObject $obj, $id, $idField='id', $createdField='created')
2731 $max = self::whereMaxId($id, $idField, $createdField);
2733 $obj->whereAdd($max);
2739 return (($this->is_local != Notice::LOCAL_NONPUBLIC) &&
2740 ($this->is_local != Notice::GATEWAY));
2744 * Check that the given profile is allowed to read, respond to, or otherwise
2745 * act on this notice.
2747 * The $scope member is a bitmask of scopes, representing a logical AND of the
2748 * scope requirement. So, 0x03 (Notice::ADDRESSEE_SCOPE | Notice::SITE_SCOPE) means
2749 * "only visible to people who are mentioned in the notice AND are users on this site."
2750 * Users on the site who are not mentioned in the notice will not be able to see the
2753 * @param Profile $profile The profile to check; pass null to check for public/unauthenticated users.
2755 * @return boolean whether the profile is in the notice's scope
2757 function inScope($profile)
2759 if (is_null($profile)) {
2760 $keypart = sprintf('notice:in-scope-for:%d:null', $this->id);
2762 $keypart = sprintf('notice:in-scope-for:%d:%d', $this->id, $profile->id);
2765 $result = self::cacheGet($keypart);
2767 if ($result === false) {
2769 if (Event::handle('StartNoticeInScope', array($this, $profile, &$bResult))) {
2770 $bResult = $this->_inScope($profile);
2771 Event::handle('EndNoticeInScope', array($this, $profile, &$bResult));
2773 $result = ($bResult) ? 1 : 0;
2774 self::cacheSet($keypart, $result, 0, 300);
2777 return ($result == 1) ? true : false;
2780 protected function _inScope($profile)
2782 $scope = is_null($this->scope) ? self::defaultScope() : $this->getScope();
2784 if ($scope === 0 && !$this->getProfile()->isPrivateStream()) { // Not scoping, so it is public.
2785 return !$this->isHiddenSpam($profile);
2788 // If there's scope, anon cannot be in scope
2789 if (empty($profile)) {
2793 // Author is always in scope
2794 if ($this->profile_id == $profile->id) {
2798 // Only for users on this site
2799 if (($scope & Notice::SITE_SCOPE) && !$profile->isLocal()) {
2803 // Only for users mentioned in the notice
2804 if ($scope & Notice::ADDRESSEE_SCOPE) {
2806 $reply = Reply::pkeyGet(array('notice_id' => $this->id,
2807 'profile_id' => $profile->id));
2809 if (!$reply instanceof Reply) {
2814 // Only for members of the given group
2815 if ($scope & Notice::GROUP_SCOPE) {
2817 // XXX: just query for the single membership
2819 $groups = $this->getGroups();
2823 foreach ($groups as $group) {
2824 if ($profile->isMember($group)) {
2835 if ($scope & Notice::FOLLOWER_SCOPE || $this->getProfile()->isPrivateStream()) {
2837 if (!Subscription::exists($profile, $this->getProfile())) {
2842 return !$this->isHiddenSpam($profile);
2845 function isHiddenSpam($profile) {
2847 // Hide posts by silenced users from everyone but moderators.
2849 if (common_config('notice', 'hidespam')) {
2852 $author = $this->getProfile();
2853 } catch(Exception $e) {
2854 // If we can't get an author, keep it hidden.
2855 // XXX: technically not spam, but, whatever.
2859 if ($author->hasRole(Profile_role::SILENCED)) {
2860 if (!$profile instanceof Profile || (($profile->id !== $author->id) && (!$profile->hasRight(Right::REVIEWSPAM)))) {
2869 public function hasParent()
2873 } catch (NoParentNoticeException $e) {
2879 public function getParent()
2881 $reply_to_id = null;
2883 if (empty($this->reply_to)) {
2884 throw new NoParentNoticeException($this);
2887 // The reply_to ID in the table Notice could exist with a number
2888 // however, the replied to notice might not exist in the database.
2889 // Thus we need to catch the exception and throw the NoParentNoticeException else
2890 // the timeline will not display correctly.
2892 $reply_to_id = self::getByID($this->reply_to);
2893 } catch(Exception $e){
2894 throw new NoParentNoticeException($this);
2897 return $reply_to_id;
2901 * Magic function called at serialize() time.
2903 * We use this to drop a couple process-specific references
2904 * from DB_DataObject which can cause trouble in future
2907 * @return array of variable names to include in serialization.
2912 $vars = parent::__sleep();
2913 $skip = array('_profile', '_groups', '_attachments', '_faves', '_replies', '_repeats');
2914 return array_diff($vars, $skip);
2917 static function defaultScope()
2919 $scope = common_config('notice', 'defaultscope');
2920 if (is_null($scope)) {
2921 if (common_config('site', 'private')) {
2930 static function fillProfiles($notices)
2932 $map = self::getProfiles($notices);
2933 foreach ($notices as $entry=>$notice) {
2935 if (array_key_exists($notice->profile_id, $map)) {
2936 $notice->_setProfile($map[$notice->profile_id]);
2938 } catch (NoProfileException $e) {
2939 common_log(LOG_WARNING, "Failed to fill profile in Notice with non-existing entry for profile_id: {$e->profile_id}");
2940 unset($notices[$entry]);
2944 return array_values($map);
2947 static function getProfiles(&$notices)
2950 foreach ($notices as $notice) {
2951 $ids[] = $notice->profile_id;
2953 $ids = array_unique($ids);
2954 return Profile::pivotGet('id', $ids);
2957 static function fillGroups(&$notices)
2959 $ids = self::_idsOf($notices);
2960 $gis = Group_inbox::listGet('notice_id', $ids);
2963 foreach ($gis as $id => $gi) {
2966 $gids[] = $g->group_id;
2970 $gids = array_unique($gids);
2971 $group = User_group::pivotGet('id', $gids);
2972 foreach ($notices as $notice)
2975 $gi = $gis[$notice->id];
2976 foreach ($gi as $g) {
2977 $grps[] = $group[$g->group_id];
2979 $notice->_setGroups($grps);
2983 static function _idsOf(array &$notices)
2986 foreach ($notices as $notice) {
2987 $ids[$notice->id] = true;
2989 return array_keys($ids);
2992 static function fillAttachments(&$notices)
2994 $ids = self::_idsOf($notices);
2995 $f2pMap = File_to_post::listGet('post_id', $ids);
2997 foreach ($f2pMap as $noticeId => $f2ps) {
2998 foreach ($f2ps as $f2p) {
2999 $fileIds[] = $f2p->file_id;
3003 $fileIds = array_unique($fileIds);
3004 $fileMap = File::pivotGet('id', $fileIds);
3005 foreach ($notices as $notice)
3008 $f2ps = $f2pMap[$notice->id];
3009 foreach ($f2ps as $f2p) {
3010 $files[] = $fileMap[$f2p->file_id];
3012 $notice->_setAttachments($files);
3016 static function fillReplies(&$notices)
3018 $ids = self::_idsOf($notices);
3019 $replyMap = Reply::listGet('notice_id', $ids);
3020 foreach ($notices as $notice) {
3021 $replies = $replyMap[$notice->id];
3023 foreach ($replies as $reply) {
3024 $ids[] = $reply->profile_id;
3026 $notice->_setReplies($ids);
3030 static public function beforeSchemaUpdate()
3032 $table = strtolower(get_called_class());
3033 $schema = Schema::get();
3034 $schemadef = $schema->getTableDef($table);
3036 // 2015-09-04 We move Notice location data to Notice_location
3037 // First we see if we have to do this at all
3038 if (!isset($schemadef['fields']['lat'])
3039 && !isset($schemadef['fields']['lon'])
3040 && !isset($schemadef['fields']['location_id'])
3041 && !isset($schemadef['fields']['location_ns'])) {
3042 // We have already removed the location fields, so no need to migrate.
3045 // Then we make sure the Notice_location table is created!
3046 $schema->ensureTable('notice_location', Notice_location::schemaDef());
3048 // Then we continue on our road to migration!
3049 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)";
3051 $notice = new Notice();
3052 $notice->query(sprintf('SELECT id, lat, lon, location_id, location_ns FROM %1$s ' .
3053 'WHERE lat IS NOT NULL ' .
3054 'OR lon IS NOT NULL ' .
3055 'OR location_id IS NOT NULL ' .
3056 'OR location_ns IS NOT NULL',
3057 $schema->quoteIdentifier($table)));
3058 print "\nFound {$notice->N} notices with location data, inserting";
3059 while ($notice->fetch()) {
3060 $notloc = Notice_location::getKV('notice_id', $notice->id);
3061 if ($notloc instanceof Notice_location) {
3065 $notloc = new Notice_location();
3066 $notloc->notice_id = $notice->id;
3067 $notloc->lat= $notice->lat;
3068 $notloc->lon= $notice->lon;
3069 $notloc->location_id= $notice->location_id;
3070 $notloc->location_ns= $notice->location_ns;