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' => 'http://activitystrea.ms/schema/1.0/note'),
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_replyto_idx' => array('reply_to')
117 if (common_config('search', 'type') == 'fulltext') {
118 $def['fulltext indexes'] = array('content' => array('content'));
125 const LOCAL_PUBLIC = 1;
127 const LOCAL_NONPUBLIC = -1;
130 const PUBLIC_SCOPE = 0; // Useful fake constant
131 const SITE_SCOPE = 1;
132 const ADDRESSEE_SCOPE = 2;
133 const GROUP_SCOPE = 4;
134 const FOLLOWER_SCOPE = 8;
136 protected $_profile = array();
139 * Will always return a profile, if anything fails it will
140 * (through _setProfile) throw a NoProfileException.
142 public function getProfile()
144 if (!isset($this->_profile[$this->profile_id])) {
145 // We could've sent getKV directly to _setProfile, but occasionally we get
146 // a "false" (instead of null), likely because it indicates a cache miss.
147 $profile = Profile::getKV('id', $this->profile_id);
148 $this->_setProfile($profile instanceof Profile ? $profile : null);
150 return $this->_profile[$this->profile_id];
153 public function _setProfile(Profile $profile=null)
155 if (!$profile instanceof Profile) {
156 throw new NoProfileException($this->profile_id);
158 $this->_profile[$this->profile_id] = $profile;
161 public function deleteAs(Profile $actor, $delete_event=true)
163 if (!$this->getProfile()->sameAs($actor) && !$actor->hasRight(Right::DELETEOTHERSNOTICE)) {
164 throw new AuthorizationException(_('You are not allowed to delete another user\'s notice.'));
167 if (Event::handle('NoticeDeleteRelated', array($this))) {
168 // Clear related records
169 $this->clearReplies();
170 $this->clearLocation();
171 $this->clearRepeats();
173 $this->clearGroupInboxes();
175 $this->clearAttentions();
176 // NOTE: we don't clear queue items
180 if (!$delete_event || Event::handle('DeleteNoticeAsProfile', array($this, $actor, &$result))) {
181 // If $delete_event is true, we run the event. If the Event then
182 // returns false it is assumed everything was handled properly
183 // and the notice was deleted.
184 $result = $this->delete();
189 public function delete($useWhere=false)
191 $result = parent::delete($useWhere);
193 $this->blowOnDelete();
197 public function getUri()
203 * Get a Notice object by URI. Will call external plugins for help
204 * using the event StartGetNoticeFromURI.
206 * @param string $uri A unique identifier for a resource (notice in this case)
208 static function fromUri($uri)
212 if (Event::handle('StartGetNoticeFromUri', array($uri, &$notice))) {
213 $notice = Notice::getKV('uri', $uri);
214 Event::handle('EndGetNoticeFromUri', array($uri, $notice));
217 if (!$notice instanceof Notice) {
218 throw new UnknownUriException($uri);
225 * @param $root boolean If true, link to just the conversation root.
227 * @return URL to conversation
229 public function getConversationUrl($anchor=true)
231 return Conversation::getUrlFromNotice($this, $anchor);
235 * Get the local representation URL of this notice.
237 public function getLocalUrl()
239 return common_local_url('shownotice', array('notice' => $this->id), null, null, false);
242 public function getTitle()
245 if (Event::handle('GetNoticeTitle', array($this, &$title))) {
246 // TRANS: Title of a notice posted without a title value.
247 // TRANS: %1$s is a user name, %2$s is the notice creation date/time.
248 $title = sprintf(_('%1$s\'s status on %2$s'),
249 $this->getProfile()->getFancyName(),
250 common_exact_date($this->created));
255 public function getContent()
257 return $this->content;
260 public function getRendered()
262 return $this->rendered;
266 * Get the original representation URL of this notice.
268 * @param boolean $fallback Whether to fall back to generate a local URL or throw InvalidUrlException
270 public function getUrl($fallback=false)
272 // The risk is we start having empty urls and non-http uris...
273 // and we can't really handle any other protocol right now.
275 case common_valid_http_url($this->url): // should we allow non-http/https URLs?
277 case !$this->isLocal() && common_valid_http_url($this->uri): // Sometimes we only have the URI for remote posts.
279 case $this->isLocal() || $fallback:
280 // let's generate a valid link to our locally available notice on demand
281 return common_local_url('shownotice', array('notice' => $this->id), null, null, false);
283 common_debug('No URL available for notice: id='.$this->id);
284 throw new InvalidUrlException($this->url);
288 public function getObjectType($canonical=false) {
289 return ActivityUtils::resolveUri($this->object_type, $canonical);
292 public static function getByUri($uri)
294 $notice = new Notice();
296 if (!$notice->find(true)) {
297 throw new NoResultException($notice);
303 * Extract #hashtags from this notice's content and save them to the database.
307 /* extract all #hastags */
308 $count = preg_match_all('/(?:^|\s)#([\pL\pN_\-\.]{1,64})/u', strtolower($this->content), $match);
313 /* Add them to the database */
314 return $this->saveKnownTags($match[1]);
318 * Record the given set of hash tags in the db for this notice.
319 * Given tag strings will be normalized and checked for dupes.
321 function saveKnownTags(array $hashtags)
323 //turn each into their canonical tag
324 //this is needed to remove dupes before saving e.g. #hash.tag = #hashtag
325 for($i=0; $i<count($hashtags); $i++) {
326 /* elide characters we don't want in the tag */
327 $hashtags[$i] = common_canonical_tag($hashtags[$i]);
330 foreach(array_unique($hashtags) as $hashtag) {
331 $this->saveTag($hashtag);
332 self::blow('profile:notice_ids_tagged:%d:%s', $this->profile_id, $hashtag);
338 * Record a single hash tag as associated with this notice.
339 * Tag format and uniqueness must be validated by caller.
341 function saveTag($hashtag)
343 $tag = new Notice_tag();
344 $tag->notice_id = $this->id;
345 $tag->tag = $hashtag;
346 $tag->created = $this->created;
347 $id = $tag->insert();
350 // TRANS: Server exception. %s are the error details.
351 throw new ServerException(sprintf(_('Database error inserting hashtag: %s.'),
352 $last_error->message));
356 // if it's saved, blow its cache
357 $tag->blowCache(false);
361 * Save a new notice and push it out to subscribers' inboxes.
362 * Poster's permissions are checked before sending.
364 * @param int $profile_id Profile ID of the poster
365 * @param string $content source message text; links may be shortened
366 * per current user's preference
367 * @param string $source source key ('web', 'api', etc)
368 * @param array $options Associative array of optional properties:
369 * string 'created' timestamp of notice; defaults to now
370 * int 'is_local' source/gateway ID, one of:
371 * Notice::LOCAL_PUBLIC - Local, ok to appear in public timeline
372 * Notice::REMOTE - Sent from a remote service;
373 * hide from public timeline but show in
374 * local "and friends" timelines
375 * Notice::LOCAL_NONPUBLIC - Local, but hide from public timeline
376 * Notice::GATEWAY - From another non-OStatus service;
377 * will not appear in public views
378 * float 'lat' decimal latitude for geolocation
379 * float 'lon' decimal longitude for geolocation
380 * int 'location_id' geoname identifier
381 * int 'location_ns' geoname namespace to interpret location_id
382 * int 'reply_to'; notice ID this is a reply to
383 * int 'repeat_of'; notice ID this is a repeat of
384 * string 'uri' unique ID for notice; a unique tag uri (can be url or anything too)
385 * string 'url' permalink to notice; defaults to local notice URL
386 * string 'rendered' rendered HTML version of content
387 * array 'replies' list of profile URIs for reply delivery in
388 * place of extracting @-replies from content.
389 * array 'groups' list of group IDs to deliver to, in place of
390 * extracting ! tags from content
391 * array 'tags' list of hashtag strings to save with the notice
392 * in place of extracting # tags from content
393 * array 'urls' list of attached/referred URLs to save with the
394 * notice in place of extracting links from content
395 * boolean 'distribute' whether to distribute the notice, default true
396 * string 'object_type' URL of the associated object type (default ActivityObject::NOTE)
397 * string 'verb' URL of the associated verb (default ActivityVerb::POST)
398 * int 'scope' Scope bitmask; default to SITE_SCOPE on private sites, 0 otherwise
400 * @fixme tag override
403 * @throws ClientException
405 static function saveNew($profile_id, $content, $source, array $options=array()) {
406 $defaults = array('uri' => null,
408 'conversation' => null, // URI of conversation
409 'reply_to' => null, // This will override convo URI if the parent is known
410 'repeat_of' => null, // This will override convo URI if the repeated notice is known
412 'distribute' => true,
413 'object_type' => null,
417 * Above type-hint is already array, so simply count it, this saves
420 if (count($options) > 0) {
421 $options = array_merge($defaults, $options);
426 if (!isset($is_local)) {
427 $is_local = Notice::LOCAL_PUBLIC;
430 $profile = Profile::getKV('id', $profile_id);
431 if (!$profile instanceof Profile) {
432 // TRANS: Client exception thrown when trying to save a notice for an unknown user.
433 throw new ClientException(_('Problem saving notice. Unknown user.'));
436 $user = User::getKV('id', $profile_id);
437 if ($user instanceof User) {
438 // Use the local user's shortening preferences, if applicable.
439 $final = $user->shortenLinks($content);
441 $final = common_shorten_links($content);
444 if (Notice::contentTooLong($final)) {
445 // TRANS: Client exception thrown if a notice contains too many characters.
446 throw new ClientException(_('Problem saving notice. Too long.'));
449 if (common_config('throttle', 'enabled') && !Notice::checkEditThrottle($profile_id)) {
450 common_log(LOG_WARNING, 'Excessive posting by profile #' . $profile_id . '; throttled.');
451 // TRANS: Client exception thrown when a user tries to post too many notices in a given time frame.
452 throw new ClientException(_('Too many notices too fast; take a breather '.
453 'and post again in a few minutes.'));
456 if (common_config('site', 'dupelimit') > 0 && !Notice::checkDupes($profile_id, $final)) {
457 common_log(LOG_WARNING, 'Dupe posting by profile #' . $profile_id . '; throttled.');
458 // TRANS: Client exception thrown when a user tries to post too many duplicate notices in a given time frame.
459 throw new ClientException(_('Too many duplicate messages too quickly;'.
460 ' take a breather and post again in a few minutes.'));
463 if (!$profile->hasRight(Right::NEWNOTICE)) {
464 common_log(LOG_WARNING, "Attempted post from user disallowed to post: " . $profile->nickname);
466 // TRANS: Client exception thrown when a user tries to post while being banned.
467 throw new ClientException(_('You are banned from posting notices on this site.'), 403);
470 $notice = new Notice();
471 $notice->profile_id = $profile_id;
473 $autosource = common_config('public', 'autosource');
475 // Sandboxed are non-false, but not 1, either
477 if (!$profile->hasRight(Right::PUBLICNOTICE) ||
478 ($source && $autosource && in_array($source, $autosource))) {
479 $notice->is_local = Notice::LOCAL_NONPUBLIC;
481 $notice->is_local = $is_local;
484 if (!empty($created)) {
485 $notice->created = $created;
487 $notice->created = common_sql_now();
490 if (!$notice->isLocal()) {
491 // Only do these checks for non-local notices. Local notices will generate these values later.
492 if (!common_valid_http_url($url)) {
493 common_debug('Bad notice URL: ['.$url.'], URI: ['.$uri.']. Cannot link back to original! This is normal for shared notices etc.');
496 throw new ServerException('No URI for remote notice. Cannot accept that.');
500 $notice->content = $final;
502 $notice->source = $source;
506 // Get the groups here so we can figure out replies and such
507 if (!isset($groups)) {
508 $groups = User_group::idsFromText($notice->content, $profile);
513 // Handle repeat case
515 if (!empty($options['repeat_of'])) {
517 // Check for a private one
519 $repeat = Notice::getByID($options['repeat_of']);
521 if ($profile->sameAs($repeat->getProfile())) {
522 // TRANS: Client error displayed when trying to repeat an own notice.
523 throw new ClientException(_('You cannot repeat your own notice.'));
526 if ($repeat->isPrivateScope()) {
527 // TRANS: Client error displayed when trying to repeat a non-public notice.
528 throw new ClientException(_('Cannot repeat a private notice.'), 403);
531 if (!$repeat->inScope($profile)) {
532 // The generic checks above should cover this, but let's be sure!
533 // TRANS: Client error displayed when trying to repeat a notice you cannot access.
534 throw new ClientException(_('Cannot repeat a notice you cannot read.'), 403);
537 if ($profile->hasRepeated($repeat)) {
538 // TRANS: Client error displayed when trying to repeat an already repeated notice.
539 throw new ClientException(_('You already repeated that notice.'));
542 $notice->repeat_of = $repeat->id;
543 $notice->conversation = $repeat->conversation;
547 // If $reply_to is specified, we check that it exists, and then
548 // return it if it does
549 if (!empty($reply_to)) {
550 $reply = Notice::getKV('id', $reply_to);
551 } elseif (in_array($source, array('xmpp', 'mail', 'sms'))) {
552 // If the source lacks capability of sending the "reply_to"
553 // metadata, let's try to find an inline replyto-reference.
554 $reply = self::getInlineReplyTo($profile, $final);
557 if ($reply instanceof Notice) {
558 if (!$reply->inScope($profile)) {
559 // TRANS: Client error displayed when trying to reply to a notice a the target has no access to.
560 // TRANS: %1$s is a user nickname, %2$d is a notice ID (number).
561 throw new ClientException(sprintf(_('%1$s has no access to notice %2$d.'),
562 $profile->nickname, $reply->id), 403);
565 // If it's a repeat, the reply_to should be to the original
566 if ($reply->isRepeat()) {
567 $notice->reply_to = $reply->repeat_of;
569 $notice->reply_to = $reply->id;
571 // But the conversation ought to be the same :)
572 $notice->conversation = $reply->conversation;
574 // If the original is private to a group, and notice has
575 // no group specified, make it to the same group(s)
577 if (empty($groups) && ($reply->scope & Notice::GROUP_SCOPE)) {
579 $replyGroups = $reply->getGroups();
580 foreach ($replyGroups as $group) {
581 if ($profile->isMember($group)) {
582 $groups[] = $group->id;
590 // If we don't know the reply, we might know the conversation!
591 // This will happen if a known remote user replies to an
592 // unknown remote user - within a known conversation.
593 if (empty($notice->conversation) and !empty($options['conversation'])) {
594 $conv = Conversation::getKV('uri', $options['conversation']);
595 if ($conv instanceof Conversation) {
596 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.').');
597 $notice->conversation = $conv->id;
599 // Conversation URI was not found, so we must create it. But we can't create it
600 // until we have a Notice ID because of the database layout...
601 // $options['conversation'] will be used later after the $notice->insert();
602 common_debug('Conversation URI not found, so we have to create it after inserting this Notice: '.$options['conversation']);
605 // If we're not using the attached conversation URI let's remove it
606 // so we don't mistake ourselves later, when creating our own Conversation.
607 // This implies that the notice knows which conversation it belongs to.
608 $options['conversation'] = null;
612 $notloc = new Notice_location();
613 if (!empty($lat) && !empty($lon)) {
618 if (!empty($location_ns) && !empty($location_id)) {
619 $notloc->location_id = $location_id;
620 $notloc->location_ns = $location_ns;
623 if (!empty($rendered)) {
624 $notice->rendered = $rendered;
626 $notice->rendered = common_render_content($final,
627 $notice->getProfile(),
628 $notice->hasParent() ? $notice->getParent() : null);
632 if ($notice->isRepeat()) {
633 $notice->verb = ActivityVerb::SHARE;
634 $notice->object_type = ActivityObject::ACTIVITY;
636 $notice->verb = ActivityVerb::POST;
639 $notice->verb = $verb;
642 if (empty($object_type)) {
643 $notice->object_type = (empty($notice->reply_to)) ? ActivityObject::NOTE : ActivityObject::COMMENT;
645 $notice->object_type = $object_type;
648 if (is_null($scope) && $reply instanceof Notice) {
649 $notice->scope = $reply->scope;
651 $notice->scope = $scope;
654 $notice->scope = self::figureOutScope($profile, $groups, $notice->scope);
656 if (Event::handle('StartNoticeSave', array(&$notice))) {
658 // XXX: some of these functions write to the DB
661 $notice->insert(); // throws exception on failure, if successful we have an ->id
663 if (($notloc->lat && $notloc->lon) || ($notloc->location_id && $notloc->location_ns)) {
664 $notloc->notice_id = $notice->getID();
665 $notloc->insert(); // store the notice location if it had any information
668 // If it's not part of a conversation, it's
669 // the beginning of a new conversation.
670 if (empty($notice->conversation)) {
671 $orig = clone($notice);
672 // $act->context->conversation will be null if it was not provided
674 $conv = Conversation::create($notice, $options['conversation']);
675 $notice->conversation = $conv->id;
676 $notice->update($orig);
678 } catch (Exception $e) {
679 // Let's test if we managed initial insert, which would imply
680 // failing on some update-part (check 'insert()'). Delete if
681 // something had been stored to the database.
682 if (!empty($notice->id)) {
689 // Only save 'attention' and metadata stuff (URLs, tags...) stuff if
690 // the activityverb is a POST (since stuff like repeat, favorite etc.
691 // reasonably handle notifications themselves.
692 if (ActivityUtils::compareVerbs($notice->verb, array(ActivityVerb::POST))) {
693 if (isset($replies)) {
694 $notice->saveKnownReplies($replies);
696 $notice->saveReplies();
700 $notice->saveKnownTags($tags);
705 // Note: groups may save tags, so must be run after tags are saved
706 // to avoid errors on duplicates.
707 // Note: groups should always be set.
709 $notice->saveKnownGroups($groups);
712 $notice->saveKnownUrls($urls);
719 // Prepare inbox delivery, may be queued to background.
720 $notice->distribute();
726 static function saveActivity(Activity $act, Profile $actor, array $options=array())
728 // First check if we're going to let this Activity through from the specific actor
729 if (!$actor->hasRight(Right::NEWNOTICE)) {
730 common_log(LOG_WARNING, "Attempted post from user disallowed to post: " . $actor->getNickname());
732 // TRANS: Client exception thrown when a user tries to post while being banned.
733 throw new ClientException(_m('You are banned from posting notices on this site.'), 403);
735 if (common_config('throttle', 'enabled') && !self::checkEditThrottle($actor->id)) {
736 common_log(LOG_WARNING, 'Excessive posting by profile #' . $actor->id . '; throttled.');
737 // TRANS: Client exception thrown when a user tries to post too many notices in a given time frame.
738 throw new ClientException(_m('Too many notices too fast; take a breather '.
739 'and post again in a few minutes.'));
742 // Get ActivityObject properties
744 if (!empty($act->id)) {
746 $options['uri'] = $act->id;
747 $options['url'] = $act->link;
749 $actobj = count($act->objects)==1 ? $act->objects[0] : null;
750 if (!is_null($actobj) && !empty($actobj->id)) {
751 $options['uri'] = $actobj->id;
753 $options['url'] = $actobj->link;
754 } elseif (preg_match('!^https?://!', $actobj->id)) {
755 $options['url'] = $actobj->id;
762 'is_local' => $actor->isLocal() ? self::LOCAL_PUBLIC : self::REMOTE,
763 'mentions' => array(),
767 'source' => 'unknown',
772 'distribute' => true);
774 // options will have default values when nothing has been supplied
775 $options = array_merge($defaults, $options);
776 foreach (array_keys($defaults) as $key) {
777 // Only convert the keynames we specify ourselves from 'defaults' array into variables
778 $$key = $options[$key];
780 extract($options, EXTR_SKIP);
783 $stored = new Notice();
784 if (!empty($uri) && !ActivityUtils::compareVerbs($act->verb, array(ActivityVerb::DELETE))) {
786 if ($stored->find()) {
787 common_debug('cannot create duplicate Notice URI: '.$stored->uri);
788 // I _assume_ saving a Notice with a colliding URI means we're really trying to
789 // save the same notice again...
790 throw new AlreadyFulfilledException('Notice URI already exists');
794 $autosource = common_config('public', 'autosource');
796 // Sandboxed are non-false, but not 1, either
797 if (!$actor->hasRight(Right::PUBLICNOTICE) ||
798 ($source && $autosource && in_array($source, $autosource))) {
799 // FIXME: ...what about remote nonpublic? Hmmm. That is, if we sandbox remote profiles...
800 $stored->is_local = Notice::LOCAL_NONPUBLIC;
802 $stored->is_local = intval($is_local);
805 if (!$stored->isLocal()) {
806 // Only do these checks for non-local notices. Local notices will generate these values later.
807 if (!common_valid_http_url($url)) {
808 common_debug('Bad notice URL: ['.$url.'], URI: ['.$uri.']. Cannot link back to original! This is normal for shared notices etc.');
811 throw new ServerException('No URI for remote notice. Cannot accept that.');
815 $stored->profile_id = $actor->id;
816 $stored->source = $source;
819 $stored->verb = $act->verb;
821 // Notice content. We trust local users to provide HTML we like, but of course not remote users.
822 // FIXME: What about local users importing feeds? Mirror functions must filter out bad HTML first...
823 $content = $act->content ?: $act->summary;
824 if (is_null($content) && !is_null($actobj)) {
825 $content = $actobj->content ?: $actobj->summary;
827 $stored->rendered = $actor->isLocal() ? $content : common_purify($content);
828 $stored->content = common_strip_html($stored->rendered);
830 // Reject notice if it is too long (without the HTML)
831 // FIXME: Reject if too short (empty) too? But we have to pass the
832 if ($actor->isLocal() && Notice::contentTooLong($stored->content)) {
833 // TRANS: Client error displayed when the parameter "status" is missing.
834 // TRANS: %d is the maximum number of character for a notice.
835 throw new ClientException(sprintf(_m('That\'s too long. Maximum notice size is %d character.',
836 'That\'s too long. Maximum notice size is %d characters.',
837 Notice::maxContent()),
838 Notice::maxContent()));
841 // Maybe a missing act-time should be fatal if the actor is not local?
842 if (!empty($act->time)) {
843 $stored->created = common_sql_date($act->time);
845 $stored->created = common_sql_now();
849 if ($act->context instanceof ActivityContext && !empty($act->context->replyToID)) {
850 $reply = self::getKV('uri', $act->context->replyToID);
852 if (!$reply instanceof Notice && $act->target instanceof ActivityObject) {
853 $reply = self::getKV('uri', $act->target->id);
856 if ($reply instanceof Notice) {
857 if (!$reply->inScope($actor)) {
858 // TRANS: Client error displayed when trying to reply to a notice a the target has no access to.
859 // TRANS: %1$s is a user nickname, %2$d is a notice ID (number).
860 throw new ClientException(sprintf(_m('%1$s has no right to reply to notice %2$d.'), $actor->getNickname(), $reply->id), 403);
863 $stored->reply_to = $reply->id;
864 $stored->conversation = $reply->conversation;
866 // If the original is private to a group, and notice has no group specified,
867 // make it to the same group(s)
868 if (empty($groups) && ($reply->scope & Notice::GROUP_SCOPE)) {
869 $replyGroups = $reply->getGroups();
870 foreach ($replyGroups as $group) {
871 if ($actor->isMember($group)) {
872 $groups[] = $group->id;
877 if (is_null($scope)) {
878 $scope = $reply->scope;
881 // If we don't know the reply, we might know the conversation!
882 // This will happen if a known remote user replies to an
883 // unknown remote user - within a known conversation.
884 if (empty($stored->conversation) and !empty($act->context->conversation)) {
885 $conv = Conversation::getKV('uri', $act->context->conversation);
886 if ($conv instanceof Conversation) {
887 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.').');
888 $stored->conversation = $conv->getID();
890 // Conversation URI was not found, so we must create it. But we can't create it
891 // until we have a Notice ID because of the database layout...
892 // $options['conversation'] will be used later after the $stored->insert();
893 common_debug('Conversation URI from activity context not found, so we have to create it after inserting this Notice: '.$act->context->conversation);
899 if ($act->context instanceof ActivityContext) {
900 if ($act->context->location instanceof Location) {
901 $notloc = Notice_location::fromLocation($act->context->location);
904 $act->context = new ActivityContext();
907 $stored->scope = self::figureOutScope($actor, $groups, $scope);
909 foreach ($act->categories as $cat) {
911 $term = common_canonical_tag($cat->term);
918 foreach ($act->enclosures as $href) {
919 // @todo FIXME: Save these locally or....?
923 if (ActivityUtils::compareVerbs($stored->verb, array(ActivityVerb::POST))) {
924 if (empty($act->objects[0]->type)) {
925 // Default type for the post verb is 'note', but we know it's
926 // a 'comment' if it is in reply to something.
927 $stored->object_type = empty($stored->reply_to) ? ActivityObject::NOTE : ActivityObject::COMMENT;
929 //TODO: Is it safe to always return a relative URI? The
930 // JSON version of ActivityStreams always use it, so we
931 // should definitely be able to handle it...
932 $stored->object_type = ActivityUtils::resolveUri($act->objects[0]->type, true);
936 if (Event::handle('StartNoticeSave', array(&$stored))) {
937 // XXX: some of these functions write to the DB
940 $result = $stored->insert(); // throws exception on error
942 if ($notloc instanceof Notice_location) {
943 $notloc->notice_id = $stored->getID();
947 $orig = clone($stored); // for updating later in this try clause
950 Event::handle('StoreActivityObject', array($act, $stored, $options, &$object));
951 if (empty($object)) {
952 throw new ServerException('Unsuccessful call to StoreActivityObject '.$stored->getUri() . ': '.$act->asString());
955 // If it's not part of a conversation, it's the beginning
956 // of a new one (or belongs to a previously unknown URI).
957 if (empty($stored->conversation)) {
958 // $act->context->conversation will be null if it was not provided
959 common_debug('Creating a new conversation for stored notice ID='.$stored->getID().' with URI: '.$act->context->conversation);
960 $conv = Conversation::create($stored, $act->context->conversation);
961 $stored->conversation = $conv->getID();
964 $stored->update($orig);
965 } catch (Exception $e) {
966 if (empty($stored->id)) {
967 common_debug('Failed to save stored object entry in database ('.$e->getMessage().')');
969 common_debug('Failed to store activity object in database ('.$e->getMessage().'), deleting notice id '.$stored->id);
975 if (!$stored instanceof Notice) {
976 throw new ServerException('StartNoticeSave did not give back a Notice');
979 // Save per-notice metadata...
981 $group_ids = array();
983 // This event lets plugins filter out non-local recipients (attentions we don't care about)
984 // Used primarily for OStatus (and if we don't federate, all attentions would be local anyway)
985 Event::handle('GetLocalAttentions', array($actor, $act->context->attention, &$mentions, &$group_ids));
987 // Only save 'attention' and metadata stuff (URLs, tags...) stuff if
988 // the activityverb is a POST (since stuff like repeat, favorite etc.
989 // reasonably handle notifications themselves.
990 if (ActivityUtils::compareVerbs($stored->verb, array(ActivityVerb::POST))) {
991 if (!empty($mentions)) {
992 $stored->saveKnownReplies($mentions);
994 $stored->saveReplies();
998 $stored->saveKnownTags($tags);
1000 $stored->saveTags();
1003 // Note: groups may save tags, so must be run after tags are saved
1004 // to avoid errors on duplicates.
1005 // Note: groups should always be set.
1007 $stored->saveKnownGroups($group_ids);
1009 if (!empty($urls)) {
1010 $stored->saveKnownUrls($urls);
1012 $stored->saveUrls();
1017 // Prepare inbox delivery, may be queued to background.
1018 $stored->distribute();
1024 static public function figureOutScope(Profile $actor, array $groups, $scope=null) {
1025 $scope = is_null($scope) ? self::defaultScope() : intval($scope);
1027 // For private streams
1029 $user = $actor->getUser();
1030 // FIXME: We can't do bit comparison with == (Legacy StatusNet thing. Let's keep it for now.)
1031 if ($user->private_stream && ($scope === Notice::PUBLIC_SCOPE || $scope === Notice::SITE_SCOPE)) {
1032 $scope |= Notice::FOLLOWER_SCOPE;
1034 } catch (NoSuchUserException $e) {
1035 // TODO: Not a local user, so we don't know about scope preferences... yet!
1038 // Force the scope for private groups
1039 foreach ($groups as $group_id) {
1041 $group = User_group::getByID($group_id);
1042 if ($group->force_scope) {
1043 $scope |= Notice::GROUP_SCOPE;
1046 } catch (Exception $e) {
1047 common_log(LOG_ERR, 'Notice figureOutScope threw exception: '.$e->getMessage());
1054 function blowOnInsert($conversation = false)
1056 $this->blowStream('profile:notice_ids:%d', $this->profile_id);
1058 if ($this->isPublic()) {
1059 $this->blowStream('public');
1060 $this->blowStream('networkpublic');
1063 if ($this->conversation) {
1064 self::blow('notice:list-ids:conversation:%s', $this->conversation);
1065 self::blow('conversation:notice_count:%d', $this->conversation);
1068 if ($this->isRepeat()) {
1069 // XXX: we should probably only use one of these
1070 $this->blowStream('notice:repeats:%d', $this->repeat_of);
1071 self::blow('notice:list-ids:repeat_of:%d', $this->repeat_of);
1074 $original = Notice::getKV('id', $this->repeat_of);
1076 if ($original instanceof Notice) {
1077 $originalUser = User::getKV('id', $original->profile_id);
1078 if ($originalUser instanceof User) {
1079 $this->blowStream('user:repeats_of_me:%d', $originalUser->id);
1083 $profile = Profile::getKV($this->profile_id);
1085 if ($profile instanceof Profile) {
1086 $profile->blowNoticeCount();
1089 $ptags = $this->getProfileTags();
1090 foreach ($ptags as $ptag) {
1091 $ptag->blowNoticeStreamCache();
1096 * Clear cache entries related to this notice at delete time.
1097 * Necessary to avoid breaking paging on public, profile timelines.
1099 function blowOnDelete()
1101 $this->blowOnInsert();
1103 self::blow('profile:notice_ids:%d;last', $this->profile_id);
1105 if ($this->isPublic()) {
1106 self::blow('public;last');
1107 self::blow('networkpublic;last');
1110 self::blow('fave:by_notice', $this->id);
1112 if ($this->conversation) {
1113 // In case we're the first, will need to calc a new root.
1114 self::blow('notice:conversation_root:%d', $this->conversation);
1117 $ptags = $this->getProfileTags();
1118 foreach ($ptags as $ptag) {
1119 $ptag->blowNoticeStreamCache(true);
1123 function blowStream()
1125 $c = self::memcache();
1131 $args = func_get_args();
1132 $format = array_shift($args);
1133 $keyPart = vsprintf($format, $args);
1134 $cacheKey = Cache::key($keyPart);
1135 $c->delete($cacheKey);
1137 // delete the "last" stream, too, if this notice is
1138 // older than the top of that stream
1140 $lastKey = $cacheKey.';last';
1142 $lastStr = $c->get($lastKey);
1144 if ($lastStr !== false) {
1145 $window = explode(',', $lastStr);
1146 $lastID = $window[0];
1147 $lastNotice = Notice::getKV('id', $lastID);
1148 if (!$lastNotice instanceof Notice // just weird
1149 || strtotime($lastNotice->created) >= strtotime($this->created)) {
1150 $c->delete($lastKey);
1155 /** save all urls in the notice to the db
1157 * follow redirects and save all available file information
1158 * (mimetype, date, size, oembed, etc.)
1162 function saveUrls() {
1163 if (common_config('attachments', 'process_links')) {
1164 common_replace_urls_callback($this->content, array($this, 'saveUrl'), $this);
1169 * Save the given URLs as related links/attachments to the db
1171 * follow redirects and save all available file information
1172 * (mimetype, date, size, oembed, etc.)
1176 function saveKnownUrls(array $urls)
1178 if (common_config('attachments', 'process_links')) {
1179 // @fixme validation?
1180 foreach (array_unique($urls) as $url) {
1181 $this->saveUrl($url, $this);
1189 function saveUrl($url, Notice $notice) {
1191 File::processNew($url, $notice);
1192 } catch (ServerException $e) {
1193 // Could not save URL. Log it?
1197 static function checkDupes($profile_id, $content) {
1198 $profile = Profile::getKV($profile_id);
1199 if (!$profile instanceof Profile) {
1202 $notice = $profile->getNotices(0, CachingNoticeStream::CACHE_WINDOW);
1203 if (!empty($notice)) {
1205 while ($notice->fetch()) {
1206 if (time() - strtotime($notice->created) >= common_config('site', 'dupelimit')) {
1208 } else if ($notice->content == $content) {
1213 // If we get here, oldest item in cache window is not
1214 // old enough for dupe limit; do direct check against DB
1215 $notice = new Notice();
1216 $notice->profile_id = $profile_id;
1217 $notice->content = $content;
1218 $threshold = common_sql_date(time() - common_config('site', 'dupelimit'));
1219 $notice->whereAdd(sprintf("created > '%s'", $notice->escape($threshold)));
1221 $cnt = $notice->count();
1225 static function checkEditThrottle($profile_id) {
1226 $profile = Profile::getKV($profile_id);
1227 if (!$profile instanceof Profile) {
1230 // Get the Nth notice
1231 $notice = $profile->getNotices(common_config('throttle', 'count') - 1, 1);
1232 if ($notice && $notice->fetch()) {
1233 // If the Nth notice was posted less than timespan seconds ago
1234 if (time() - strtotime($notice->created) <= common_config('throttle', 'timespan')) {
1239 // Either not N notices in the stream, OR the Nth was not posted within timespan seconds
1243 protected $_attachments = array();
1245 function attachments() {
1246 if (isset($this->_attachments[$this->id])) {
1247 return $this->_attachments[$this->id];
1250 $f2ps = File_to_post::listGet('post_id', array($this->id));
1252 foreach ($f2ps[$this->id] as $f2p) {
1253 $ids[] = $f2p->file_id;
1256 $files = File::multiGet('id', $ids);
1257 $this->_attachments[$this->id] = $files->fetchAll();
1258 return $this->_attachments[$this->id];
1261 function _setAttachments($attachments)
1263 $this->_attachments[$this->id] = $attachments;
1266 static function publicStream($offset=0, $limit=20, $since_id=null, $max_id=null)
1268 $stream = new PublicNoticeStream();
1269 return $stream->getNotices($offset, $limit, $since_id, $max_id);
1272 static function conversationStream($id, $offset=0, $limit=20, $since_id=null, $max_id=null)
1274 $stream = new ConversationNoticeStream($id);
1275 return $stream->getNotices($offset, $limit, $since_id, $max_id);
1279 * Is this notice part of an active conversation?
1281 * @return boolean true if other messages exist in the same
1282 * conversation, false if this is the only one
1284 function hasConversation()
1286 if (empty($this->conversation)) {
1287 // this notice is not part of a conversation apparently
1288 // FIXME: all notices should have a conversation value, right?
1292 $stream = new ConversationNoticeStream($this->conversation);
1293 $notice = $stream->getNotices(/*offset*/ 1, /*limit*/ 1);
1295 // if our "offset 1, limit 1" query got a result, return true else false
1296 return $notice->N > 0;
1300 * Grab the earliest notice from this conversation.
1302 * @return Notice or null
1304 function conversationRoot($profile=-1)
1306 // XXX: can this happen?
1308 if (empty($this->conversation)) {
1312 // Get the current profile if not specified
1314 if (is_int($profile) && $profile == -1) {
1315 $profile = Profile::current();
1318 // If this notice is out of scope, no root for you!
1320 if (!$this->inScope($profile)) {
1324 // If this isn't a reply to anything, then it's its own
1325 // root if it's the earliest notice in the conversation:
1327 if (empty($this->reply_to)) {
1329 $root->conversation = $this->conversation;
1330 $root->orderBy('notice.created ASC');
1331 $root->find(true); // true means "fetch first result"
1336 if (is_null($profile)) {
1337 $keypart = sprintf('notice:conversation_root:%d:null', $this->id);
1339 $keypart = sprintf('notice:conversation_root:%d:%d',
1344 $root = self::cacheGet($keypart);
1346 if ($root !== false && $root->inScope($profile)) {
1353 $parent = $last->getParent();
1354 if ($parent->inScope($profile)) {
1358 } catch (NoParentNoticeException $e) {
1359 // Latest notice has no parent
1360 } catch (NoResultException $e) {
1361 // Notice was not found, so we can't go further up in the tree.
1362 // FIXME: Maybe we should do this in a more stable way where deleted
1363 // notices won't break conversation chains?
1365 // No parent, or parent out of scope
1370 self::cacheSet($keypart, $root);
1376 * Pull up a full list of local recipients who will be getting
1377 * this notice in their inbox. Results will be cached, so don't
1378 * change the input data wily-nilly!
1380 * @param array $groups optional list of Group objects;
1381 * if left empty, will be loaded from group_inbox records
1382 * @param array $recipient optional list of reply profile ids
1383 * if left empty, will be loaded from reply records
1384 * @return array associating recipient user IDs with an inbox source constant
1386 function whoGets(array $groups=null, array $recipients=null)
1388 $c = self::memcache();
1391 $ni = $c->get(Cache::key('notice:who_gets:'.$this->id));
1392 if ($ni !== false) {
1397 if (is_null($recipients)) {
1398 $recipients = $this->getReplies();
1403 // Give plugins a chance to add folks in at start...
1404 if (Event::handle('StartNoticeWhoGets', array($this, &$ni))) {
1406 $users = $this->getSubscribedUsers();
1407 foreach ($users as $id) {
1408 $ni[$id] = NOTICE_INBOX_SOURCE_SUB;
1411 if (is_null($groups)) {
1412 $groups = $this->getGroups();
1414 foreach ($groups as $group) {
1415 $users = $group->getUserMembers();
1416 foreach ($users as $id) {
1417 if (!array_key_exists($id, $ni)) {
1418 $ni[$id] = NOTICE_INBOX_SOURCE_GROUP;
1423 $ptAtts = $this->getAttentionsFromProfileTags();
1424 foreach ($ptAtts as $key=>$val) {
1425 if (!array_key_exists($key, $ni)) {
1430 foreach ($recipients as $recipient) {
1431 if (!array_key_exists($recipient, $ni)) {
1432 $ni[$recipient] = NOTICE_INBOX_SOURCE_REPLY;
1436 // Exclude any deleted, non-local, or blocking recipients.
1437 $profile = $this->getProfile();
1438 $originalProfile = null;
1439 if ($this->isRepeat()) {
1440 // Check blocks against the original notice's poster as well.
1441 $original = Notice::getKV('id', $this->repeat_of);
1442 if ($original instanceof Notice) {
1443 $originalProfile = $original->getProfile();
1447 foreach ($ni as $id => $source) {
1449 $user = User::getKV('id', $id);
1450 if (!$user instanceof User ||
1451 $user->hasBlocked($profile) ||
1452 ($originalProfile && $user->hasBlocked($originalProfile))) {
1455 } catch (UserNoProfileException $e) {
1456 // User doesn't have a profile; invalid; skip them.
1461 // Give plugins a chance to filter out...
1462 Event::handle('EndNoticeWhoGets', array($this, &$ni));
1466 // XXX: pack this data better
1467 $c->set(Cache::key('notice:who_gets:'.$this->id), $ni);
1473 function getSubscribedUsers()
1477 if(common_config('db','quote_identifiers'))
1478 $user_table = '"user"';
1479 else $user_table = 'user';
1483 'FROM '. $user_table .' JOIN subscription '.
1484 'ON '. $user_table .'.id = subscription.subscriber ' .
1485 'WHERE subscription.subscribed = %d ';
1487 $user->query(sprintf($qry, $this->profile_id));
1491 while ($user->fetch()) {
1500 function getProfileTags()
1502 $profile = $this->getProfile();
1503 $list = $profile->getOtherTags($profile);
1506 while($list->fetch()) {
1507 $ptags[] = clone($list);
1513 public function getAttentionsFromProfileTags()
1516 $ptags = $this->getProfileTags();
1517 foreach ($ptags as $ptag) {
1518 $users = $ptag->getUserSubscribers();
1519 foreach ($users as $id) {
1520 $ni[$id] = NOTICE_INBOX_SOURCE_PROFILE_TAG;
1527 * Record this notice to the given group inboxes for delivery.
1528 * Overrides the regular parsing of !group markup.
1530 * @param string $group_ids
1531 * @fixme might prefer URIs as identifiers, as for replies?
1532 * best with generalizations on user_group to support
1533 * remote groups better.
1535 function saveKnownGroups(array $group_ids)
1538 foreach (array_unique($group_ids) as $id) {
1539 $group = User_group::getKV('id', $id);
1540 if ($group instanceof User_group) {
1541 common_log(LOG_DEBUG, "Local delivery to group id $id, $group->nickname");
1542 $result = $this->addToGroupInbox($group);
1544 common_log_db_error($gi, 'INSERT', __FILE__);
1547 if (common_config('group', 'addtag')) {
1548 // we automatically add a tag for every group name, too
1550 $tag = Notice_tag::pkeyGet(array('tag' => common_canonical_tag($group->nickname),
1551 'notice_id' => $this->id));
1553 if (is_null($tag)) {
1554 $this->saveTag($group->nickname);
1558 $groups[] = clone($group);
1560 common_log(LOG_ERR, "Local delivery to group id $id skipped, doesn't exist");
1567 function addToGroupInbox(User_group $group)
1569 $gi = Group_inbox::pkeyGet(array('group_id' => $group->id,
1570 'notice_id' => $this->id));
1572 if (!$gi instanceof Group_inbox) {
1574 $gi = new Group_inbox();
1576 $gi->group_id = $group->id;
1577 $gi->notice_id = $this->id;
1578 $gi->created = $this->created;
1580 $result = $gi->insert();
1583 common_log_db_error($gi, 'INSERT', __FILE__);
1584 // TRANS: Server exception thrown when an update for a group inbox fails.
1585 throw new ServerException(_('Problem saving group inbox.'));
1588 self::blow('user_group:notice_ids:%d', $gi->group_id);
1595 * Save reply records indicating that this notice needs to be
1596 * delivered to the local users with the given URIs.
1598 * Since this is expected to be used when saving foreign-sourced
1599 * messages, we won't deliver to any remote targets as that's the
1600 * source service's responsibility.
1602 * Mail notifications etc will be handled later.
1604 * @param array $uris Array of unique identifier URIs for recipients
1606 function saveKnownReplies(array $uris)
1612 $sender = $this->getProfile();
1614 foreach (array_unique($uris) as $uri) {
1616 $profile = Profile::fromUri($uri);
1617 } catch (UnknownUriException $e) {
1618 common_log(LOG_WARNING, "Unable to determine profile for URI '$uri'");
1622 if ($profile->hasBlocked($sender)) {
1623 common_log(LOG_INFO, "Not saving reply to profile {$profile->id} ($uri) from sender {$sender->id} because of a block.");
1627 $this->saveReply($profile->getID());
1628 self::blow('reply:stream:%d', $profile->getID());
1633 * Pull @-replies from this message's content in StatusNet markup format
1634 * and save reply records indicating that this message needs to be
1635 * delivered to those users.
1637 * Mail notifications to local profiles will be sent later.
1639 * @return array of integer profile IDs
1642 function saveReplies()
1644 $sender = $this->getProfile();
1648 // If it's a reply, save for the replied-to author
1650 $parent = $this->getParent();
1651 $parentauthor = $parent->getProfile();
1652 $this->saveReply($parentauthor->getID());
1653 $replied[$parentauthor->getID()] = 1;
1654 self::blow('reply:stream:%d', $parentauthor->getID());
1655 } catch (NoParentNoticeException $e) {
1656 // Not a reply, since it has no parent!
1658 } catch (NoResultException $e) {
1659 // Parent notice was probably deleted
1663 // @todo ideally this parser information would only
1664 // be calculated once.
1666 $mentions = common_find_mentions($this->content, $sender, $parent);
1668 // store replied only for first @ (what user/notice what the reply directed,
1669 // we assume first @ is it)
1671 foreach ($mentions as $mention) {
1673 foreach ($mention['mentioned'] as $mentioned) {
1675 // skip if they're already covered
1676 if (array_key_exists($mentioned->id, $replied)) {
1680 // Don't save replies from blocked profile to local user
1682 $mentioned_user = User::getKV('id', $mentioned->id);
1683 if ($mentioned_user instanceof User && $mentioned_user->hasBlocked($sender)) {
1687 $this->saveReply($mentioned->id);
1688 $replied[$mentioned->id] = 1;
1689 self::blow('reply:stream:%d', $mentioned->id);
1693 $recipientIds = array_keys($replied);
1695 return $recipientIds;
1698 function saveReply($profileId)
1700 $reply = new Reply();
1702 $reply->notice_id = $this->id;
1703 $reply->profile_id = $profileId;
1704 $reply->modified = $this->created;
1711 protected $_replies = array();
1714 * Pull the complete list of @-mentioned profile IDs for this notice.
1716 * @return array of integer profile ids
1718 function getReplies()
1720 if (!isset($this->_replies[$this->getID()])) {
1721 $mentions = Reply::multiGet('notice_id', array($this->getID()));
1722 $this->_replies[$this->getID()] = $mentions->fetchAll('profile_id');
1724 return $this->_replies[$this->getID()];
1727 function _setReplies(array $replies)
1729 $this->_replies[$this->getID()] = $replies;
1733 * Pull the complete list of @-reply targets for this notice.
1735 * @return array of Profiles
1737 function getReplyProfiles()
1739 $ids = $this->getReplies();
1741 $profiles = Profile::multiGet('id', $ids);
1743 return $profiles->fetchAll();
1747 * Send e-mail notifications to local @-reply targets.
1749 * Replies must already have been saved; this is expected to be run
1750 * from the distrib queue handler.
1752 function sendReplyNotifications()
1754 // Don't send reply notifications for repeats
1755 if ($this->isRepeat()) {
1759 $recipientIds = $this->getReplies();
1760 if (Event::handle('StartNotifyMentioned', array($this, &$recipientIds))) {
1761 require_once INSTALLDIR.'/lib/mail.php';
1763 foreach ($recipientIds as $recipientId) {
1765 $user = User::getByID($recipientId);
1766 mail_notify_attn($user, $this);
1767 } catch (NoResultException $e) {
1771 Event::handle('EndNotifyMentioned', array($this, $recipientIds));
1776 * Pull list of groups this notice needs to be delivered to,
1777 * as previously recorded by saveKnownGroups().
1779 * @return array of Group objects
1782 protected $_groups = array();
1784 function getGroups()
1786 // Don't save groups for repeats
1788 if (!empty($this->repeat_of)) {
1792 if (isset($this->_groups[$this->id])) {
1793 return $this->_groups[$this->id];
1796 $gis = Group_inbox::listGet('notice_id', array($this->id));
1800 foreach ($gis[$this->id] as $gi) {
1801 $ids[] = $gi->group_id;
1804 $groups = User_group::multiGet('id', $ids);
1805 $this->_setGroups($groups->fetchAll());
1806 return $this->_groups[$this->id];
1809 function _setGroups(array $groups)
1811 $this->_groups[$this->id] = $groups;
1815 * Convert a notice into an activity for export.
1817 * @param Profile $scoped The currently logged in/scoped profile
1819 * @return Activity activity object representing this Notice.
1822 function asActivity(Profile $scoped=null)
1824 $act = self::cacheGet(Cache::codeKey('notice:as-activity:'.$this->id));
1826 if ($act instanceof Activity) {
1829 $act = new Activity();
1831 if (Event::handle('StartNoticeAsActivity', array($this, $act, $scoped))) {
1833 $act->id = $this->uri;
1834 $act->time = strtotime($this->created);
1836 $act->link = $this->getUrl();
1837 } catch (InvalidUrlException $e) {
1838 // The notice is probably a share or similar, which don't
1839 // have a representational URL of their own.
1841 $act->content = common_xml_safe_str($this->rendered);
1843 $profile = $this->getProfile();
1845 $act->actor = $profile->asActivityObject();
1846 $act->actor->extra[] = $profile->profileInfo($scoped);
1848 $act->verb = $this->verb;
1850 if (!$this->repeat_of) {
1851 $act->objects[] = $this->asActivityObject();
1854 // XXX: should this be handled by default processing for object entry?
1858 $tags = $this->getTags();
1860 foreach ($tags as $tag) {
1861 $cat = new AtomCategory();
1864 $act->categories[] = $cat;
1868 // XXX: use Atom Media and/or File activity objects instead
1870 $attachments = $this->attachments();
1872 foreach ($attachments as $attachment) {
1873 // Include local attachments in Activity
1874 if (!empty($attachment->filename)) {
1875 $act->enclosures[] = $attachment->getEnclosure();
1879 $ctx = new ActivityContext();
1882 $reply = $this->getParent();
1883 $ctx->replyToID = $reply->getUri();
1884 $ctx->replyToUrl = $reply->getUrl(true); // true for fallback to local URL, less messy
1885 } catch (NoParentNoticeException $e) {
1886 // This is not a reply to something
1887 } catch (NoResultException $e) {
1888 // Parent notice was probably deleted
1892 $ctx->location = Notice_location::locFromStored($this);
1893 } catch (ServerException $e) {
1894 $ctx->location = null;
1899 if (!empty($this->conversation)) {
1900 $conv = Conversation::getKV('id', $this->conversation);
1901 if ($conv instanceof Conversation) {
1902 $ctx->conversation = $conv->uri;
1906 $reply_ids = $this->getReplies();
1908 foreach ($reply_ids as $id) {
1909 $rprofile = Profile::getKV('id', $id);
1910 if ($rprofile instanceof Profile) {
1911 $ctx->attention[$rprofile->getUri()] = ActivityObject::PERSON;
1915 $groups = $this->getGroups();
1917 foreach ($groups as $group) {
1918 $ctx->attention[$group->getUri()] = ActivityObject::GROUP;
1921 switch ($this->scope) {
1922 case Notice::PUBLIC_SCOPE:
1923 $ctx->attention[ActivityContext::ATTN_PUBLIC] = ActivityObject::COLLECTION;
1925 case Notice::FOLLOWER_SCOPE:
1926 $surl = common_local_url("subscribers", array('nickname' => $profile->nickname));
1927 $ctx->attention[$surl] = ActivityObject::COLLECTION;
1931 $act->context = $ctx;
1933 $source = $this->getSource();
1935 if ($source instanceof Notice_source) {
1936 $act->generator = ActivityObject::fromNoticeSource($source);
1941 $atom_feed = $profile->getAtomFeed();
1943 if (!empty($atom_feed)) {
1945 $act->source = new ActivitySource();
1947 // XXX: we should store the actual feed ID
1949 $act->source->id = $atom_feed;
1951 // XXX: we should store the actual feed title
1953 $act->source->title = $profile->getBestName();
1955 $act->source->links['alternate'] = $profile->profileurl;
1956 $act->source->links['self'] = $atom_feed;
1958 $act->source->icon = $profile->avatarUrl(AVATAR_PROFILE_SIZE);
1960 $notice = $profile->getCurrentNotice();
1962 if ($notice instanceof Notice) {
1963 $act->source->updated = self::utcDate($notice->created);
1966 $user = User::getKV('id', $profile->id);
1968 if ($user instanceof User) {
1969 $act->source->links['license'] = common_config('license', 'url');
1973 if ($this->isLocal()) {
1974 $act->selfLink = common_local_url('ApiStatusesShow', array('id' => $this->id,
1975 'format' => 'atom'));
1976 $act->editLink = $act->selfLink;
1979 Event::handle('EndNoticeAsActivity', array($this, $act, $scoped));
1982 self::cacheSet(Cache::codeKey('notice:as-activity:'.$this->id), $act);
1987 // This has gotten way too long. Needs to be sliced up into functional bits
1988 // or ideally exported to a utility class.
1990 function asAtomEntry($namespace=false,
1993 Profile $scoped=null)
1995 $act = $this->asActivity($scoped);
1996 $act->extra[] = $this->noticeInfo($scoped);
1997 return $act->asString($namespace, $author, $source);
2001 * Extra notice info for atom entries
2003 * Clients use some extra notice info in the atom stream.
2004 * This gives it to them.
2006 * @param Profile $scoped The currently logged in/scoped profile
2008 * @return array representation of <statusnet:notice_info> element
2011 function noticeInfo(Profile $scoped=null)
2013 // local notice ID (useful to clients for ordering)
2015 $noticeInfoAttr = array('local_id' => $this->id);
2019 $ns = $this->getSource();
2021 if ($ns instanceof Notice_source) {
2022 $noticeInfoAttr['source'] = $ns->code;
2023 if (!empty($ns->url)) {
2024 $noticeInfoAttr['source_link'] = $ns->url;
2025 if (!empty($ns->name)) {
2026 $noticeInfoAttr['source'] = '<a href="'
2027 . htmlspecialchars($ns->url)
2028 . '" rel="nofollow">'
2029 . htmlspecialchars($ns->name)
2035 // favorite and repeated
2037 if ($scoped instanceof Profile) {
2038 $noticeInfoAttr['repeated'] = ($scoped->hasRepeated($this)) ? "true" : "false";
2041 if (!empty($this->repeat_of)) {
2042 $noticeInfoAttr['repeat_of'] = $this->repeat_of;
2045 Event::handle('StatusNetApiNoticeInfo', array($this, &$noticeInfoAttr, $scoped));
2047 return array('statusnet:notice_info', $noticeInfoAttr, null);
2051 * Returns an XML string fragment with a reference to a notice as an
2052 * Activity Streams noun object with the given element type.
2054 * Assumes that 'activity' namespace has been previously defined.
2056 * @param string $element one of 'subject', 'object', 'target'
2060 function asActivityNoun($element)
2062 $noun = $this->asActivityObject();
2063 return $noun->asString('activity:' . $element);
2066 public function asActivityObject()
2068 $object = new ActivityObject();
2070 if (Event::handle('StartActivityObjectFromNotice', array($this, &$object))) {
2071 $object->type = $this->object_type ?: ActivityObject::NOTE;
2072 $object->id = $this->getUri();
2073 //FIXME: = $object->title ?: sprintf(... because we might get a title from StartActivityObjectFromNotice
2074 $object->title = sprintf('New %1$s by %2$s', ActivityObject::canonicalType($object->type), $this->getProfile()->getNickname());
2075 $object->content = $this->rendered;
2076 $object->link = $this->getUrl();
2078 $object->extra[] = array('status_net', array('notice_id' => $this->id));
2080 Event::handle('EndActivityObjectFromNotice', array($this, &$object));
2087 * Determine which notice, if any, a new notice is in reply to.
2089 * For conversation tracking, we try to see where this notice fits
2090 * in the tree. Beware that this may very well give false positives
2091 * and add replies to wrong threads (if there have been newer posts
2092 * by the same user as we're replying to).
2094 * @param Profile $sender Author profile
2095 * @param string $content Final notice content
2097 * @return integer ID of replied-to notice, or null for not a reply.
2100 static function getInlineReplyTo(Profile $sender, $content)
2102 // Is there an initial @ or T?
2103 if (preg_match('/^T ([A-Z0-9]{1,64}) /', $content, $match)
2104 || preg_match('/^@([a-z0-9]{1,64})\s+/', $content, $match)) {
2105 $nickname = common_canonical_nickname($match[1]);
2110 // Figure out who that is.
2111 $recipient = common_relative_profile($sender, $nickname, common_sql_now());
2113 if ($recipient instanceof Profile) {
2114 // Get their last notice
2115 $last = $recipient->getCurrentNotice();
2116 if ($last instanceof Notice) {
2119 // Maybe in the future we want to handle something else below
2120 // so don't return getCurrentNotice() immediately.
2126 static function maxContent()
2128 $contentlimit = common_config('notice', 'contentlimit');
2129 // null => use global limit (distinct from 0!)
2130 if (is_null($contentlimit)) {
2131 $contentlimit = common_config('site', 'textlimit');
2133 return $contentlimit;
2136 static function contentTooLong($content)
2138 $contentlimit = self::maxContent();
2139 return ($contentlimit > 0 && !empty($content) && (mb_strlen($content) > $contentlimit));
2143 * Convenience function for posting a repeat of an existing message.
2145 * @param Profile $repeater Profile which is doing the repeat
2146 * @param string $source: posting source key, eg 'web', 'api', etc
2149 * @throws Exception on failure or permission problems
2151 function repeat(Profile $repeater, $source)
2153 $author = $this->getProfile();
2155 // TRANS: Message used to repeat a notice. RT is the abbreviation of 'retweet'.
2156 // TRANS: %1$s is the repeated user's name, %2$s is the repeated notice.
2157 $content = sprintf(_('RT @%1$s %2$s'),
2158 $author->getNickname(),
2161 $maxlen = self::maxContent();
2162 if ($maxlen > 0 && mb_strlen($content) > $maxlen) {
2163 // Web interface and current Twitter API clients will
2164 // pull the original notice's text, but some older
2165 // clients and RSS/Atom feeds will see this trimmed text.
2167 // Unfortunately this is likely to lose tags or URLs
2168 // at the end of long notices.
2169 $content = mb_substr($content, 0, $maxlen - 4) . ' ...';
2173 // Scope is same as this one's
2174 return self::saveNew($repeater->id,
2177 array('repeat_of' => $this->id,
2178 'scope' => $this->scope));
2181 // These are supposed to be in chron order!
2183 function repeatStream($limit=100)
2185 $cache = Cache::instance();
2187 if (empty($cache)) {
2188 $ids = $this->_repeatStreamDirect($limit);
2190 $idstr = $cache->get(Cache::key('notice:repeats:'.$this->id));
2191 if ($idstr !== false) {
2192 if (empty($idstr)) {
2195 $ids = explode(',', $idstr);
2198 $ids = $this->_repeatStreamDirect(100);
2199 $cache->set(Cache::key('notice:repeats:'.$this->id), implode(',', $ids));
2202 // We do a max of 100, so slice down to limit
2203 $ids = array_slice($ids, 0, $limit);
2207 return NoticeStream::getStreamByIds($ids);
2210 function _repeatStreamDirect($limit)
2212 $notice = new Notice();
2214 $notice->selectAdd(); // clears it
2215 $notice->selectAdd('id');
2217 $notice->repeat_of = $this->id;
2219 $notice->orderBy('created, id'); // NB: asc!
2221 if (!is_null($limit)) {
2222 $notice->limit(0, $limit);
2225 return $notice->fetchAll('id');
2228 static function locationOptions($lat, $lon, $location_id, $location_ns, $profile = null)
2232 if (!empty($location_id) && !empty($location_ns)) {
2233 $options['location_id'] = $location_id;
2234 $options['location_ns'] = $location_ns;
2236 $location = Location::fromId($location_id, $location_ns);
2238 if ($location instanceof Location) {
2239 $options['lat'] = $location->lat;
2240 $options['lon'] = $location->lon;
2243 } else if (!empty($lat) && !empty($lon)) {
2244 $options['lat'] = $lat;
2245 $options['lon'] = $lon;
2247 $location = Location::fromLatLon($lat, $lon);
2249 if ($location instanceof Location) {
2250 $options['location_id'] = $location->location_id;
2251 $options['location_ns'] = $location->location_ns;
2253 } else if (!empty($profile)) {
2254 if (isset($profile->lat) && isset($profile->lon)) {
2255 $options['lat'] = $profile->lat;
2256 $options['lon'] = $profile->lon;
2259 if (isset($profile->location_id) && isset($profile->location_ns)) {
2260 $options['location_id'] = $profile->location_id;
2261 $options['location_ns'] = $profile->location_ns;
2268 function clearAttentions()
2270 $att = new Attention();
2271 $att->notice_id = $this->getID();
2274 while ($att->fetch()) {
2275 // Can't do delete() on the object directly since it won't remove all of it
2276 $other = clone($att);
2282 function clearReplies()
2284 $replyNotice = new Notice();
2285 $replyNotice->reply_to = $this->id;
2287 //Null any notices that are replies to this notice
2289 if ($replyNotice->find()) {
2290 while ($replyNotice->fetch()) {
2291 $orig = clone($replyNotice);
2292 $replyNotice->reply_to = null;
2293 $replyNotice->update($orig);
2299 $reply = new Reply();
2300 $reply->notice_id = $this->id;
2302 if ($reply->find()) {
2303 while($reply->fetch()) {
2304 self::blow('reply:stream:%d', $reply->profile_id);
2312 function clearLocation()
2314 $loc = new Notice_location();
2315 $loc->notice_id = $this->id;
2322 function clearFiles()
2324 $f2p = new File_to_post();
2326 $f2p->post_id = $this->id;
2329 while ($f2p->fetch()) {
2333 // FIXME: decide whether to delete File objects
2334 // ...and related (actual) files
2337 function clearRepeats()
2339 $repeatNotice = new Notice();
2340 $repeatNotice->repeat_of = $this->id;
2342 //Null any notices that are repeats of this notice
2344 if ($repeatNotice->find()) {
2345 while ($repeatNotice->fetch()) {
2346 $orig = clone($repeatNotice);
2347 $repeatNotice->repeat_of = null;
2348 $repeatNotice->update($orig);
2353 function clearTags()
2355 $tag = new Notice_tag();
2356 $tag->notice_id = $this->id;
2359 while ($tag->fetch()) {
2360 self::blow('profile:notice_ids_tagged:%d:%s', $this->profile_id, Cache::keyize($tag->tag));
2361 self::blow('profile:notice_ids_tagged:%d:%s;last', $this->profile_id, Cache::keyize($tag->tag));
2362 self::blow('notice_tag:notice_ids:%s', Cache::keyize($tag->tag));
2363 self::blow('notice_tag:notice_ids:%s;last', Cache::keyize($tag->tag));
2371 function clearGroupInboxes()
2373 $gi = new Group_inbox();
2375 $gi->notice_id = $this->id;
2378 while ($gi->fetch()) {
2379 self::blow('user_group:notice_ids:%d', $gi->group_id);
2387 function distribute()
2389 // We always insert for the author so they don't
2391 Event::handle('StartNoticeDistribute', array($this));
2393 // If there's a failure, we want to _force_
2394 // distribution at this point.
2396 $qm = QueueManager::get();
2397 $qm->enqueue($this, 'distrib');
2398 } catch (Exception $e) {
2399 // If the exception isn't transient, this
2400 // may throw more exceptions as DQH does
2401 // its own enqueueing. So, we ignore them!
2403 $handler = new DistribQueueHandler();
2404 $handler->handle($this);
2405 } catch (Exception $e) {
2406 common_log(LOG_ERR, "emergency redistribution resulted in " . $e->getMessage());
2408 // Re-throw so somebody smarter can handle it.
2415 $result = parent::insert();
2417 if ($result === false) {
2418 common_log_db_error($this, 'INSERT', __FILE__);
2419 // TRANS: Server exception thrown when a stored object entry cannot be saved.
2420 throw new ServerException('Could not save Notice');
2423 // Profile::hasRepeated() abuses pkeyGet(), so we
2424 // have to clear manually
2425 if (!empty($this->repeat_of)) {
2426 $c = self::memcache();
2428 $ck = self::multicacheKey('Notice',
2429 array('profile_id' => $this->profile_id,
2430 'repeat_of' => $this->repeat_of));
2435 // Update possibly ID-dependent columns: URI, conversation
2436 // (now that INSERT has added the notice's local id)
2437 $orig = clone($this);
2440 // We can only get here if it's a local notice, since remote notices
2441 // should've bailed out earlier due to lacking a URI.
2442 if (empty($this->uri)) {
2443 $this->uri = sprintf('%s%s=%d:%s=%s',
2445 'noticeId', $this->id,
2446 'objectType', $this->getObjectType(true));
2450 if ($changed && $this->update($orig) === false) {
2451 common_log_db_error($notice, 'UPDATE', __FILE__);
2452 // TRANS: Server exception thrown when a notice cannot be updated.
2453 throw new ServerException(_('Problem saving notice.'));
2456 $this->blowOnInsert();
2462 * Get the source of the notice
2464 * @return Notice_source $ns A notice source object. 'code' is the only attribute
2465 * guaranteed to be populated.
2467 function getSource()
2469 if (empty($this->source)) {
2473 $ns = new Notice_source();
2474 switch ($this->source) {
2481 $ns->code = $this->source;
2484 $ns = Notice_source::getKV($this->source);
2486 $ns = new Notice_source();
2487 $ns->code = $this->source;
2488 $app = Oauth_application::getKV('name', $this->source);
2490 $ns->name = $app->name;
2491 $ns->url = $app->source_url;
2501 * Determine whether the notice was locally created
2503 * @return boolean locality
2506 public function isLocal()
2508 $is_local = intval($this->is_local);
2509 return ($is_local === self::LOCAL_PUBLIC || $is_local === self::LOCAL_NONPUBLIC);
2512 public function getScope()
2514 return intval($this->scope);
2517 public function isRepeat()
2519 return !empty($this->repeat_of);
2523 * Get the list of hash tags saved with this notice.
2525 * @return array of strings
2527 public function getTags()
2529 // Check default scope (non-private notices)
2530 $inScope = (!$this->isPrivateScope());
2532 // Get current profile
2533 $profile = Profile::current();
2535 // Is the general scope check okay and the user in logged in?
2536 //* NOISY-DEBUG: */ common_debug('[' . __METHOD__ . ':' . __LINE__ . ']: inScope=' . intval($inScope) . ',profile[]=' . gettype($profile));
2537 if (($inScope === TRUE) && ($profile instanceof Profile)) {
2539 * Check scope, else a privacy leaks happens this way:
2541 * 1) Bob and Alice follow each other and write private notices
2542 * (this->scope=2) to each other.
2543 * 2) Bob uses tags in his private notice to alice (which she can
2545 * 3) Alice adds that notice (with tags) to her favorites
2547 * 4) The tags from Bob's private notice becomes visible in Alice's
2550 * This has the simple background that the scope is not being
2551 * re-checked. This has to be done here at this point because given
2552 * above scenario is a privacy leak as the tags may be *really*
2553 * private (nobody else shall see them) such as initmate words or
2554 * very political words.
2556 $inScope = $this->inScope($profile);
2557 //* NOISY-DEBUG: */ common_debug('[' . __METHOD__ . ':' . __LINE__ . ']: inScope=' . intval($inScope) . ' - After inScope() has been called.');
2562 $keypart = sprintf('notice:tags:%d', $this->id);
2564 $tagstr = self::cacheGet($keypart);
2566 if ($tagstr !== false) {
2567 $tags = explode(',', $tagstr);
2569 $tag = new Notice_tag();
2570 $tag->notice_id = $this->id;
2572 // Check scope for privacy-leak protection (see some lines above why)
2573 if (($inScope === TRUE) && ($tag->find())) {
2574 while ($tag->fetch()) {
2575 $tags[] = $tag->tag;
2578 self::cacheSet($keypart, implode(',', $tags));
2584 static private function utcDate($dt)
2586 $dateStr = date('d F Y H:i:s', strtotime($dt));
2587 $d = new DateTime($dateStr, new DateTimeZone('UTC'));
2588 return $d->format(DATE_W3C);
2592 * Look up the creation timestamp for a given notice ID, even
2593 * if it's been deleted.
2596 * @return mixed string recorded creation timestamp, or false if can't be found
2598 public static function getAsTimestamp($id)
2604 $notice = Notice::getKV('id', $id);
2606 return $notice->created;
2609 $deleted = Deleted_notice::getKV('id', $id);
2611 return $deleted->created;
2618 * Build an SQL 'where' fragment for timestamp-based sorting from a since_id
2619 * parameter, matching notices posted after the given one (exclusive).
2621 * If the referenced notice can't be found, will return false.
2624 * @param string $idField
2625 * @param string $createdField
2626 * @return mixed string or false if no match
2628 public static function whereSinceId($id, $idField='id', $createdField='created')
2630 $since = Notice::getAsTimestamp($id);
2632 return sprintf("($createdField = '%s' and $idField > %d) or ($createdField > '%s')", $since, $id, $since);
2638 * Build an SQL 'where' fragment for timestamp-based sorting from a since_id
2639 * parameter, matching notices posted after the given one (exclusive), and
2640 * if necessary add it to the data object's query.
2642 * @param DB_DataObject $obj
2644 * @param string $idField
2645 * @param string $createdField
2646 * @return mixed string or false if no match
2648 public static function addWhereSinceId(DB_DataObject $obj, $id, $idField='id', $createdField='created')
2650 $since = self::whereSinceId($id, $idField, $createdField);
2652 $obj->whereAdd($since);
2657 * Build an SQL 'where' fragment for timestamp-based sorting from a max_id
2658 * parameter, matching notices posted before the given one (inclusive).
2660 * If the referenced notice can't be found, will return false.
2663 * @param string $idField
2664 * @param string $createdField
2665 * @return mixed string or false if no match
2667 public static function whereMaxId($id, $idField='id', $createdField='created')
2669 $max = Notice::getAsTimestamp($id);
2671 return sprintf("($createdField < '%s') or ($createdField = '%s' and $idField <= %d)", $max, $max, $id);
2677 * Build an SQL 'where' fragment for timestamp-based sorting from a max_id
2678 * parameter, matching notices posted before the given one (inclusive), and
2679 * if necessary add it to the data object's query.
2681 * @param DB_DataObject $obj
2683 * @param string $idField
2684 * @param string $createdField
2685 * @return mixed string or false if no match
2687 public static function addWhereMaxId(DB_DataObject $obj, $id, $idField='id', $createdField='created')
2689 $max = self::whereMaxId($id, $idField, $createdField);
2691 $obj->whereAdd($max);
2697 return (($this->is_local != Notice::LOCAL_NONPUBLIC) &&
2698 ($this->is_local != Notice::GATEWAY));
2701 public function isPrivateScope () {
2702 return ($this->scope != Notice::SITE_SCOPE &&
2703 $this->scope != Notice::PUBLIC_SCOPE);
2707 * Check that the given profile is allowed to read, respond to, or otherwise
2708 * act on this notice.
2710 * The $scope member is a bitmask of scopes, representing a logical AND of the
2711 * scope requirement. So, 0x03 (Notice::ADDRESSEE_SCOPE | Notice::SITE_SCOPE) means
2712 * "only visible to people who are mentioned in the notice AND are users on this site."
2713 * Users on the site who are not mentioned in the notice will not be able to see the
2716 * @param Profile $profile The profile to check; pass null to check for public/unauthenticated users.
2718 * @return boolean whether the profile is in the notice's scope
2720 function inScope(Profile $profile=null)
2722 if (is_null($profile)) {
2723 $keypart = sprintf('notice:in-scope-for:%d:null', $this->id);
2725 $keypart = sprintf('notice:in-scope-for:%d:%d', $this->id, $profile->id);
2728 $result = self::cacheGet($keypart);
2730 if ($result === false) {
2732 if (Event::handle('StartNoticeInScope', array($this, $profile, &$bResult))) {
2733 $bResult = $this->_inScope($profile);
2734 Event::handle('EndNoticeInScope', array($this, $profile, &$bResult));
2736 $result = ($bResult) ? 1 : 0;
2737 self::cacheSet($keypart, $result, 0, 300);
2740 return ($result == 1) ? true : false;
2743 protected function _inScope(Profile $profile=null)
2745 $scope = is_null($this->scope) ? self::defaultScope() : $this->getScope();
2747 if ($scope === 0 && !$this->getProfile()->isPrivateStream()) { // Not scoping, so it is public.
2748 return !$this->isHiddenSpam($profile);
2751 // If there's scope, anon cannot be in scope
2752 if (empty($profile)) {
2756 // Author is always in scope
2757 if ($this->profile_id == $profile->id) {
2761 // Only for users on this site
2762 if (($scope & Notice::SITE_SCOPE) && !$profile->isLocal()) {
2766 // Only for users mentioned in the notice
2767 if ($scope & Notice::ADDRESSEE_SCOPE) {
2769 $reply = Reply::pkeyGet(array('notice_id' => $this->id,
2770 'profile_id' => $profile->id));
2772 if (!$reply instanceof Reply) {
2777 // Only for members of the given group
2778 if ($scope & Notice::GROUP_SCOPE) {
2780 // XXX: just query for the single membership
2782 $groups = $this->getGroups();
2786 foreach ($groups as $group) {
2787 if ($profile->isMember($group)) {
2798 if ($scope & Notice::FOLLOWER_SCOPE || $this->getProfile()->isPrivateStream()) {
2800 if (!Subscription::exists($profile, $this->getProfile())) {
2805 return !$this->isHiddenSpam($profile);
2808 function isHiddenSpam(Profile $profile=null) {
2810 // Hide posts by silenced users from everyone but moderators.
2812 if (common_config('notice', 'hidespam')) {
2815 $author = $this->getProfile();
2816 } catch(Exception $e) {
2817 // If we can't get an author, keep it hidden.
2818 // XXX: technically not spam, but, whatever.
2822 if ($author->hasRole(Profile_role::SILENCED)) {
2823 if (!$profile instanceof Profile || (($profile->id !== $author->id) && (!$profile->hasRight(Right::REVIEWSPAM)))) {
2832 public function hasParent()
2836 } catch (NoParentNoticeException $e) {
2842 public function getParent()
2844 $reply_to_id = null;
2846 if (empty($this->reply_to)) {
2847 throw new NoParentNoticeException($this);
2850 // The reply_to ID in the table Notice could exist with a number
2851 // however, the replied to notice might not exist in the database.
2852 // Thus we need to catch the exception and throw the NoParentNoticeException else
2853 // the timeline will not display correctly.
2855 $reply_to_id = self::getByID($this->reply_to);
2856 } catch(Exception $e){
2857 throw new NoParentNoticeException($this);
2860 return $reply_to_id;
2864 * Magic function called at serialize() time.
2866 * We use this to drop a couple process-specific references
2867 * from DB_DataObject which can cause trouble in future
2870 * @return array of variable names to include in serialization.
2875 $vars = parent::__sleep();
2876 $skip = array('_profile', '_groups', '_attachments', '_faves', '_replies', '_repeats');
2877 return array_diff($vars, $skip);
2880 static function defaultScope()
2882 $scope = common_config('notice', 'defaultscope');
2883 if (is_null($scope)) {
2884 if (common_config('site', 'private')) {
2893 static function fillProfiles(array $notices)
2895 $map = self::getProfiles($notices);
2896 foreach ($notices as $entry=>$notice) {
2898 if (array_key_exists($notice->profile_id, $map)) {
2899 $notice->_setProfile($map[$notice->profile_id]);
2901 } catch (NoProfileException $e) {
2902 common_log(LOG_WARNING, "Failed to fill profile in Notice with non-existing entry for profile_id: {$e->profile_id}");
2903 unset($notices[$entry]);
2907 return array_values($map);
2910 static function getProfiles(array &$notices)
2913 foreach ($notices as $notice) {
2914 $ids[] = $notice->profile_id;
2916 $ids = array_unique($ids);
2917 return Profile::pivotGet('id', $ids);
2920 static function fillGroups(array &$notices)
2922 $ids = self::_idsOf($notices);
2923 $gis = Group_inbox::listGet('notice_id', $ids);
2926 foreach ($gis as $id => $gi) {
2929 $gids[] = $g->group_id;
2933 $gids = array_unique($gids);
2934 $group = User_group::pivotGet('id', $gids);
2935 foreach ($notices as $notice)
2938 $gi = $gis[$notice->id];
2939 foreach ($gi as $g) {
2940 $grps[] = $group[$g->group_id];
2942 $notice->_setGroups($grps);
2946 static function _idsOf(array &$notices)
2949 foreach ($notices as $notice) {
2950 $ids[$notice->id] = true;
2952 return array_keys($ids);
2955 static function fillAttachments(array &$notices)
2957 $ids = self::_idsOf($notices);
2958 $f2pMap = File_to_post::listGet('post_id', $ids);
2960 foreach ($f2pMap as $noticeId => $f2ps) {
2961 foreach ($f2ps as $f2p) {
2962 $fileIds[] = $f2p->file_id;
2966 $fileIds = array_unique($fileIds);
2967 $fileMap = File::pivotGet('id', $fileIds);
2968 foreach ($notices as $notice)
2971 $f2ps = $f2pMap[$notice->id];
2972 foreach ($f2ps as $f2p) {
2973 $files[] = $fileMap[$f2p->file_id];
2975 $notice->_setAttachments($files);
2979 static function fillReplies(array &$notices)
2981 $ids = self::_idsOf($notices);
2982 $replyMap = Reply::listGet('notice_id', $ids);
2983 foreach ($notices as $notice) {
2984 $replies = $replyMap[$notice->id];
2986 foreach ($replies as $reply) {
2987 $ids[] = $reply->profile_id;
2989 $notice->_setReplies($ids);
2994 * Checks whether the current profile is allowed (in scope) to see this notice.
2996 * @return $inScope Whether the current profile is allowed to see this notice
2998 function isCurrentProfileInScope () {
2999 // Check scope, default is allowed
3002 //* NOISY-DEBUG: */ common_debug('[' . __METHOD__ . ':' . __LINE__ . '] this->tag=' . $this->tag . ',this->id=' . $this->id . ',this->scope=' . $this->scope);
3004 // Is it private scope?
3005 if ($this->isPrivateScope()) {
3006 // 2) Get current profile
3007 $profile = Profile::current();
3009 // Is the profile not set?
3010 if (!$profile instanceof Profile) {
3011 // Public viewer shall not see a tag from a private dent (privacy leak)
3012 //* NOISY-DEBUG: */ common_debug('[' . __METHOD__ . ':' . __LINE__ . '] Not logged in (public view).');
3014 } elseif (!$this->inScope($profile)) {
3015 // Current profile is not in scope (not allowed to see) of notice
3016 //* NOISY-DEBUG: */ common_debug('[' . __METHOD__ . ':' . __LINE__ . '] profile->id=' . $profile->id . ' is not allowed to see this notice.');
3022 //* NOISY-DEBUG: */ common_debug('[' . __METHOD__ . ':' . __LINE__ . '] this->tag=' . $this->tag . ',this->weight=' . $this->weight . ',inScope=' . intval($inScope) . ' - EXIT!');
3026 static public function beforeSchemaUpdate()
3028 $table = strtolower(get_called_class());
3029 $schema = Schema::get();
3030 $schemadef = $schema->getTableDef($table);
3032 // 2015-09-04 We move Notice location data to Notice_location
3033 // First we see if we have to do this at all
3034 if (!isset($schemadef['fields']['lat'])
3035 && !isset($schemadef['fields']['lon'])
3036 && !isset($schemadef['fields']['location_id'])
3037 && !isset($schemadef['fields']['location_ns'])) {
3038 // We have already removed the location fields, so no need to migrate.
3041 // Then we make sure the Notice_location table is created!
3042 $schema->ensureTable('notice_location', Notice_location::schemaDef());
3044 // Then we continue on our road to migration!
3045 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)";
3047 $notice = new Notice();
3048 $notice->query(sprintf('SELECT id, lat, lon, location_id, location_ns FROM %1$s ' .
3049 'WHERE lat IS NOT NULL ' .
3050 'OR lon IS NOT NULL ' .
3051 'OR location_id IS NOT NULL ' .
3052 'OR location_ns IS NOT NULL',
3053 $schema->quoteIdentifier($table)));
3054 print "\nFound {$notice->N} notices with location data, inserting";
3055 while ($notice->fetch()) {
3056 $notloc = Notice_location::getKV('notice_id', $notice->id);
3057 if ($notloc instanceof Notice_location) {
3061 $notloc = new Notice_location();
3062 $notloc->notice_id = $notice->id;
3063 $notloc->lat= $notice->lat;
3064 $notloc->lon= $notice->lon;
3065 $notloc->location_id= $notice->location_id;
3066 $notloc->location_ns= $notice->location_ns;