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 $self; // varchar(191) not 255 because utf8mb4 takes more space
63 public $created; // datetime multiple_key not_null default_0000-00-00%2000%3A00%3A00
64 public $modified; // timestamp not_null default_CURRENT_TIMESTAMP
65 public $reply_to; // int(4)
66 public $is_local; // int(4)
67 public $source; // varchar(32)
68 public $conversation; // int(4)
69 public $repeat_of; // int(4)
70 public $verb; // varchar(191) not 255 because utf8mb4 takes more space
71 public $object_type; // varchar(191) not 255 because utf8mb4 takes more space
72 public $scope; // int(4)
74 /* the code above is auto generated do not remove the tag below */
77 public static function schemaDef()
81 'id' => array('type' => 'serial', 'not null' => true, 'description' => 'unique identifier'),
82 'profile_id' => array('type' => 'int', 'not null' => true, 'description' => 'who made the update'),
83 'uri' => array('type' => 'varchar', 'length' => 191, 'description' => 'universally unique identifier, usually a tag URI'),
84 'content' => array('type' => 'text', 'description' => 'update content', 'collate' => 'utf8mb4_general_ci'),
85 'rendered' => array('type' => 'text', 'description' => 'HTML version of the content'),
86 'url' => array('type' => 'varchar', 'length' => 191, 'description' => 'URL of any attachment (image, video, bookmark, whatever)'),
87 'self' => array('type' => 'varchar', 'length' => 191, 'description' => 'Resolvable URL to the (remote) Atom entry representation'),
88 'created' => array('type' => 'datetime', 'not null' => true, 'description' => 'date this record was created'),
89 'modified' => array('type' => 'timestamp', 'not null' => true, 'description' => 'date this record was modified'),
90 'reply_to' => array('type' => 'int', 'description' => 'notice replied to (usually a guess)'),
91 'is_local' => array('type' => 'int', 'size' => 'tiny', 'default' => 0, 'description' => 'notice was generated by a user'),
92 'source' => array('type' => 'varchar', 'length' => 32, 'description' => 'source of comment, like "web", "im", or "clientname"'),
93 'conversation' => array('type' => 'int', 'description' => 'id of root notice in this conversation'),
94 'repeat_of' => array('type' => 'int', 'description' => 'notice this is a repeat of'),
95 'object_type' => array('type' => 'varchar', 'length' => 191, 'description' => 'URI representing activity streams object type', 'default' => null),
96 'verb' => array('type' => 'varchar', 'length' => 191, 'description' => 'URI representing activity streams verb', 'default' => 'http://activitystrea.ms/schema/1.0/post'),
97 'scope' => array('type' => 'int',
98 'description' => 'bit map for distribution scope; 0 = everywhere; 1 = this server only; 2 = addressees; 4 = followers; null = default'),
100 'primary key' => array('id'),
101 'unique keys' => array(
102 'notice_uri_key' => array('uri'),
104 'foreign keys' => array(
105 'notice_profile_id_fkey' => array('profile', array('profile_id' => 'id')),
106 'notice_reply_to_fkey' => array('notice', array('reply_to' => 'id')),
107 'notice_conversation_fkey' => array('conversation', array('conversation' => 'id')), # note... used to refer to notice.id
108 'notice_repeat_of_fkey' => array('notice', array('repeat_of' => 'id')), # @fixme: what about repeats of deleted notices?
111 'notice_created_id_is_local_idx' => array('created', 'id', 'is_local'),
112 'notice_profile_id_idx' => array('profile_id', 'created', 'id'),
113 'notice_repeat_of_created_id_idx' => array('repeat_of', 'created', 'id'),
114 'notice_conversation_created_id_idx' => array('conversation', 'created', 'id'),
115 'notice_verb_idx' => array('verb'),
116 'notice_replyto_idx' => array('reply_to')
120 if (common_config('search', 'type') == 'fulltext') {
121 $def['fulltext indexes'] = array('content' => array('content'));
128 const LOCAL_PUBLIC = 1;
130 const LOCAL_NONPUBLIC = -1;
133 const PUBLIC_SCOPE = 0; // Useful fake constant
134 const SITE_SCOPE = 1;
135 const ADDRESSEE_SCOPE = 2;
136 const GROUP_SCOPE = 4;
137 const FOLLOWER_SCOPE = 8;
139 protected $_profile = array();
142 * Will always return a profile, if anything fails it will
143 * (through _setProfile) throw a NoProfileException.
145 public function getProfile()
147 if (!isset($this->_profile[$this->profile_id])) {
148 // We could've sent getKV directly to _setProfile, but occasionally we get
149 // a "false" (instead of null), likely because it indicates a cache miss.
150 $profile = Profile::getKV('id', $this->profile_id);
151 $this->_setProfile($profile instanceof Profile ? $profile : null);
153 return $this->_profile[$this->profile_id];
156 public function _setProfile(Profile $profile=null)
158 if (!$profile instanceof Profile) {
159 throw new NoProfileException($this->profile_id);
161 $this->_profile[$this->profile_id] = $profile;
164 public function deleteAs(Profile $actor, $delete_event=true)
166 if (!$this->getProfile()->sameAs($actor) && !$actor->hasRight(Right::DELETEOTHERSNOTICE)) {
167 throw new AuthorizationException(_('You are not allowed to delete another user\'s notice.'));
170 if (Event::handle('NoticeDeleteRelated', array($this))) {
171 // Clear related records
172 $this->clearReplies();
173 $this->clearLocation();
174 $this->clearRepeats();
176 $this->clearGroupInboxes();
178 $this->clearAttentions();
179 // NOTE: we don't clear queue items
183 if (!$delete_event || Event::handle('DeleteNoticeAsProfile', array($this, $actor, &$result))) {
184 // If $delete_event is true, we run the event. If the Event then
185 // returns false it is assumed everything was handled properly
186 // and the notice was deleted.
187 $result = $this->delete();
192 public function delete($useWhere=false)
194 $result = parent::delete($useWhere);
196 $this->blowOnDelete();
200 public function getUri()
206 * Get a Notice object by URI. Will call external plugins for help
207 * using the event StartGetNoticeFromURI.
209 * @param string $uri A unique identifier for a resource (notice in this case)
211 static function fromUri($uri)
215 if (Event::handle('StartGetNoticeFromUri', array($uri, &$notice))) {
216 $notice = Notice::getKV('uri', $uri);
217 Event::handle('EndGetNoticeFromUri', array($uri, $notice));
220 if (!$notice instanceof Notice) {
221 throw new UnknownUriException($uri);
228 * @param $root boolean If true, link to just the conversation root.
230 * @return URL to conversation
232 public function getConversationUrl($anchor=true)
234 return Conversation::getUrlFromNotice($this, $anchor);
238 * Get the local representation URL of this notice.
240 public function getLocalUrl()
242 return common_local_url('shownotice', array('notice' => $this->id), null, null, false);
245 public function getTitle()
248 if (Event::handle('GetNoticeTitle', array($this, &$title))) {
249 // TRANS: Title of a notice posted without a title value.
250 // TRANS: %1$s is a user name, %2$s is the notice creation date/time.
251 $title = sprintf(_('%1$s\'s status on %2$s'),
252 $this->getProfile()->getFancyName(),
253 common_exact_date($this->created));
258 public function getContent()
260 return $this->content;
263 public function getRendered()
265 // we test $this->id because if it's not inserted yet, we can't update the field
266 if (!empty($this->id) && (is_null($this->rendered) || $this->rendered === '')) {
267 // update to include rendered content on-the-fly, so we don't have to have a fix-up script in upgrade.php
268 common_debug('Rendering notice '.$this->getID().' as it had no rendered HTML content.');
269 $orig = clone($this);
270 $this->rendered = common_render_content($this->getContent(),
272 $this->hasParent() ? $this->getParent() : null);
273 $this->update($orig);
275 return $this->rendered;
278 public function getCreated()
280 return $this->created;
283 public function getVerb($make_relative=false)
285 return ActivityUtils::resolveUri($this->verb, $make_relative);
288 public function isVerb(array $verbs)
290 return ActivityUtils::compareVerbs($this->getVerb(), $verbs);
294 * Get the original representation URL of this notice.
296 * @param boolean $fallback Whether to fall back to generate a local URL or throw InvalidUrlException
298 public function getUrl($fallback=false)
300 // The risk is we start having empty urls and non-http uris...
301 // and we can't really handle any other protocol right now.
303 case $this->isLocal():
304 return common_local_url('shownotice', array('notice' => $this->getID()), null, null, false);
305 case common_valid_http_url($this->url): // should we allow non-http/https URLs?
307 case common_valid_http_url($this->uri): // Sometimes we only have the URI for remote posts.
310 // let's generate a valid link to our locally available notice on demand
311 return common_local_url('shownotice', array('notice' => $this->getID()), null, null, false);
313 common_debug('No URL available for notice: id='.$this->getID());
314 throw new InvalidUrlException($this->url);
318 public function getObjectType($canonical=false) {
319 if (is_null($this->object_type) || $this->object_type==='') {
320 throw new NoObjectTypeException($this);
322 return ActivityUtils::resolveUri($this->object_type, $canonical);
325 public function isObjectType(array $types)
328 return ActivityUtils::compareTypes($this->getObjectType(), $types);
329 } catch (NoObjectTypeException $e) {
334 public static function getByUri($uri)
336 $notice = new Notice();
338 if (!$notice->find(true)) {
339 throw new NoResultException($notice);
345 * Extract #hashtags from this notice's content and save them to the database.
349 /* extract all #hastags */
350 $count = preg_match_all('/(?:^|\s)#([\pL\pN_\-\.]{1,64})/u', strtolower($this->content), $match);
355 /* Add them to the database */
356 return $this->saveKnownTags($match[1]);
360 * Record the given set of hash tags in the db for this notice.
361 * Given tag strings will be normalized and checked for dupes.
363 function saveKnownTags($hashtags)
365 //turn each into their canonical tag
366 //this is needed to remove dupes before saving e.g. #hash.tag = #hashtag
367 for($i=0; $i<count($hashtags); $i++) {
368 /* elide characters we don't want in the tag */
369 $hashtags[$i] = common_canonical_tag($hashtags[$i]);
372 foreach(array_unique($hashtags) as $hashtag) {
373 $this->saveTag($hashtag);
374 self::blow('profile:notice_ids_tagged:%d:%s', $this->profile_id, $hashtag);
380 * Record a single hash tag as associated with this notice.
381 * Tag format and uniqueness must be validated by caller.
383 function saveTag($hashtag)
385 $tag = new Notice_tag();
386 $tag->notice_id = $this->id;
387 $tag->tag = $hashtag;
388 $tag->created = $this->created;
389 $id = $tag->insert();
392 // TRANS: Server exception. %s are the error details.
393 throw new ServerException(sprintf(_('Database error inserting hashtag: %s.'),
394 $last_error->message));
398 // if it's saved, blow its cache
399 $tag->blowCache(false);
403 * Save a new notice and push it out to subscribers' inboxes.
404 * Poster's permissions are checked before sending.
406 * @param int $profile_id Profile ID of the poster
407 * @param string $content source message text; links may be shortened
408 * per current user's preference
409 * @param string $source source key ('web', 'api', etc)
410 * @param array $options Associative array of optional properties:
411 * string 'created' timestamp of notice; defaults to now
412 * int 'is_local' source/gateway ID, one of:
413 * Notice::LOCAL_PUBLIC - Local, ok to appear in public timeline
414 * Notice::REMOTE - Sent from a remote service;
415 * hide from public timeline but show in
416 * local "and friends" timelines
417 * Notice::LOCAL_NONPUBLIC - Local, but hide from public timeline
418 * Notice::GATEWAY - From another non-OStatus service;
419 * will not appear in public views
420 * float 'lat' decimal latitude for geolocation
421 * float 'lon' decimal longitude for geolocation
422 * int 'location_id' geoname identifier
423 * int 'location_ns' geoname namespace to interpret location_id
424 * int 'reply_to'; notice ID this is a reply to
425 * int 'repeat_of'; notice ID this is a repeat of
426 * string 'uri' unique ID for notice; a unique tag uri (can be url or anything too)
427 * string 'url' permalink to notice; defaults to local notice URL
428 * string 'rendered' rendered HTML version of content
429 * array 'replies' list of profile URIs for reply delivery in
430 * place of extracting @-replies from content.
431 * array 'groups' list of group IDs to deliver to, in place of
432 * extracting ! tags from content
433 * array 'tags' list of hashtag strings to save with the notice
434 * in place of extracting # tags from content
435 * array 'urls' list of attached/referred URLs to save with the
436 * notice in place of extracting links from content
437 * boolean 'distribute' whether to distribute the notice, default true
438 * string 'object_type' URL of the associated object type (default ActivityObject::NOTE)
439 * string 'verb' URL of the associated verb (default ActivityVerb::POST)
440 * int 'scope' Scope bitmask; default to SITE_SCOPE on private sites, 0 otherwise
442 * @fixme tag override
445 * @throws ClientException
447 static function saveNew($profile_id, $content, $source, array $options=null) {
448 $defaults = array('uri' => null,
451 'conversation' => null, // URI of conversation
452 'reply_to' => null, // This will override convo URI if the parent is known
453 'repeat_of' => null, // This will override convo URI if the repeated notice is known
455 'distribute' => true,
456 'object_type' => null,
459 if (!empty($options) && is_array($options)) {
460 $options = array_merge($defaults, $options);
466 if (!isset($is_local)) {
467 $is_local = Notice::LOCAL_PUBLIC;
470 $profile = Profile::getKV('id', $profile_id);
471 if (!$profile instanceof Profile) {
472 // TRANS: Client exception thrown when trying to save a notice for an unknown user.
473 throw new ClientException(_('Problem saving notice. Unknown user.'));
476 $user = User::getKV('id', $profile_id);
477 if ($user instanceof User) {
478 // Use the local user's shortening preferences, if applicable.
479 $final = $user->shortenLinks($content);
481 $final = common_shorten_links($content);
484 if (Notice::contentTooLong($final)) {
485 // TRANS: Client exception thrown if a notice contains too many characters.
486 throw new ClientException(_('Problem saving notice. Too long.'));
489 if (common_config('throttle', 'enabled') && !Notice::checkEditThrottle($profile_id)) {
490 common_log(LOG_WARNING, 'Excessive posting by profile #' . $profile_id . '; throttled.');
491 // TRANS: Client exception thrown when a user tries to post too many notices in a given time frame.
492 throw new ClientException(_('Too many notices too fast; take a breather '.
493 'and post again in a few minutes.'));
496 if (common_config('site', 'dupelimit') > 0 && !Notice::checkDupes($profile_id, $final)) {
497 common_log(LOG_WARNING, 'Dupe posting by profile #' . $profile_id . '; throttled.');
498 // TRANS: Client exception thrown when a user tries to post too many duplicate notices in a given time frame.
499 throw new ClientException(_('Too many duplicate messages too quickly;'.
500 ' take a breather and post again in a few minutes.'));
503 if (!$profile->hasRight(Right::NEWNOTICE)) {
504 common_log(LOG_WARNING, "Attempted post from user disallowed to post: " . $profile->nickname);
506 // TRANS: Client exception thrown when a user tries to post while being banned.
507 throw new ClientException(_('You are banned from posting notices on this site.'), 403);
510 $notice = new Notice();
511 $notice->profile_id = $profile_id;
513 $autosource = common_config('public', 'autosource');
515 // Sandboxed are non-false, but not 1, either
517 if (!$profile->hasRight(Right::PUBLICNOTICE) ||
518 ($source && $autosource && in_array($source, $autosource))) {
519 $notice->is_local = Notice::LOCAL_NONPUBLIC;
521 $notice->is_local = $is_local;
524 if (!empty($created)) {
525 $notice->created = $created;
527 $notice->created = common_sql_now();
530 if (!$notice->isLocal()) {
531 // Only do these checks for non-local notices. Local notices will generate these values later.
532 if (!common_valid_http_url($url)) {
533 common_debug('Bad notice URL: ['.$url.'], URI: ['.$uri.']. Cannot link back to original! This is normal for shared notices etc.');
536 throw new ServerException('No URI for remote notice. Cannot accept that.');
540 $notice->content = $final;
542 $notice->source = $source;
545 if ($self && common_valid_http_url($self)) {
546 $notice->self = $self;
549 // Get the groups here so we can figure out replies and such
550 if (!isset($groups)) {
551 $groups = User_group::idsFromText($notice->content, $profile);
556 // Handle repeat case
558 if (!empty($options['repeat_of'])) {
560 // Check for a private one
562 $repeat = Notice::getByID($options['repeat_of']);
564 if ($profile->sameAs($repeat->getProfile())) {
565 // TRANS: Client error displayed when trying to repeat an own notice.
566 throw new ClientException(_('You cannot repeat your own notice.'));
569 if ($repeat->scope != Notice::SITE_SCOPE &&
570 $repeat->scope != Notice::PUBLIC_SCOPE) {
571 // TRANS: Client error displayed when trying to repeat a non-public notice.
572 throw new ClientException(_('Cannot repeat a private notice.'), 403);
575 if (!$repeat->inScope($profile)) {
576 // The generic checks above should cover this, but let's be sure!
577 // TRANS: Client error displayed when trying to repeat a notice you cannot access.
578 throw new ClientException(_('Cannot repeat a notice you cannot read.'), 403);
581 if ($profile->hasRepeated($repeat)) {
582 // TRANS: Client error displayed when trying to repeat an already repeated notice.
583 throw new ClientException(_('You already repeated that notice.'));
586 $notice->repeat_of = $repeat->id;
587 $notice->conversation = $repeat->conversation;
591 // If $reply_to is specified, we check that it exists, and then
592 // return it if it does
593 if (!empty($reply_to)) {
594 $reply = Notice::getKV('id', $reply_to);
595 } elseif (in_array($source, array('xmpp', 'mail', 'sms'))) {
596 // If the source lacks capability of sending the "reply_to"
597 // metadata, let's try to find an inline replyto-reference.
598 $reply = self::getInlineReplyTo($profile, $final);
601 if ($reply instanceof Notice) {
602 if (!$reply->inScope($profile)) {
603 // TRANS: Client error displayed when trying to reply to a notice a the target has no access to.
604 // TRANS: %1$s is a user nickname, %2$d is a notice ID (number).
605 throw new ClientException(sprintf(_('%1$s has no access to notice %2$d.'),
606 $profile->nickname, $reply->id), 403);
609 // If it's a repeat, the reply_to should be to the original
610 if ($reply->isRepeat()) {
611 $notice->reply_to = $reply->repeat_of;
613 $notice->reply_to = $reply->id;
615 // But the conversation ought to be the same :)
616 $notice->conversation = $reply->conversation;
618 // If the original is private to a group, and notice has
619 // no group specified, make it to the same group(s)
621 if (empty($groups) && ($reply->scope & Notice::GROUP_SCOPE)) {
623 $replyGroups = $reply->getGroups();
624 foreach ($replyGroups as $group) {
625 if ($profile->isMember($group)) {
626 $groups[] = $group->id;
634 // If we don't know the reply, we might know the conversation!
635 // This will happen if a known remote user replies to an
636 // unknown remote user - within a known conversation.
637 if (empty($notice->conversation) and !empty($options['conversation'])) {
638 $conv = Conversation::getKV('uri', $options['conversation']);
639 if ($conv instanceof Conversation) {
640 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.').');
642 // Conversation entry with specified URI was not found, so we must create it.
643 common_debug('Conversation URI not found, so we will create it with the URI given in the options to Notice::saveNew: '.$options['conversation']);
644 // The insert in Conversation::create throws exception on failure
645 $conv = Conversation::create($options['conversation'], $notice->created);
647 $notice->conversation = $conv->getID();
652 // If it's not part of a conversation, it's the beginning of a new conversation.
653 if (empty($notice->conversation)) {
654 $conv = Conversation::create();
655 $notice->conversation = $conv->getID();
660 $notloc = new Notice_location();
661 if (!empty($lat) && !empty($lon)) {
666 if (!empty($location_ns) && !empty($location_id)) {
667 $notloc->location_id = $location_id;
668 $notloc->location_ns = $location_ns;
671 if (!empty($rendered)) {
672 $notice->rendered = $rendered;
674 $notice->rendered = common_render_content($final,
675 $notice->getProfile(),
676 $notice->hasParent() ? $notice->getParent() : null);
680 if ($notice->isRepeat()) {
681 $notice->verb = ActivityVerb::SHARE;
682 $notice->object_type = ActivityObject::ACTIVITY;
684 $notice->verb = ActivityVerb::POST;
687 $notice->verb = $verb;
690 if (empty($object_type)) {
691 $notice->object_type = (empty($notice->reply_to)) ? ActivityObject::NOTE : ActivityObject::COMMENT;
693 $notice->object_type = $object_type;
696 if (is_null($scope) && $reply instanceof Notice) {
697 $notice->scope = $reply->scope;
699 $notice->scope = $scope;
702 $notice->scope = self::figureOutScope($profile, $groups, $notice->scope);
704 if (Event::handle('StartNoticeSave', array(&$notice))) {
706 // XXX: some of these functions write to the DB
709 $notice->insert(); // throws exception on failure, if successful we have an ->id
711 if (($notloc->lat && $notloc->lon) || ($notloc->location_id && $notloc->location_ns)) {
712 $notloc->notice_id = $notice->getID();
713 $notloc->insert(); // store the notice location if it had any information
715 } catch (Exception $e) {
716 // Let's test if we managed initial insert, which would imply
717 // failing on some update-part (check 'insert()'). Delete if
718 // something had been stored to the database.
719 if (!empty($notice->id)) {
726 // Only save 'attention' and metadata stuff (URLs, tags...) stuff if
727 // the activityverb is a POST (since stuff like repeat, favorite etc.
728 // reasonably handle notifications themselves.
729 if (ActivityUtils::compareVerbs($notice->verb, array(ActivityVerb::POST))) {
730 if (isset($replies)) {
731 $notice->saveKnownReplies($replies);
733 $notice->saveReplies();
737 $notice->saveKnownTags($tags);
742 // Note: groups may save tags, so must be run after tags are saved
743 // to avoid errors on duplicates.
744 // Note: groups should always be set.
746 $notice->saveKnownGroups($groups);
749 $notice->saveKnownUrls($urls);
756 // Prepare inbox delivery, may be queued to background.
757 $notice->distribute();
763 static function saveActivity(Activity $act, Profile $actor, array $options=array())
765 // First check if we're going to let this Activity through from the specific actor
766 if (!$actor->hasRight(Right::NEWNOTICE)) {
767 common_log(LOG_WARNING, "Attempted post from user disallowed to post: " . $actor->getNickname());
769 // TRANS: Client exception thrown when a user tries to post while being banned.
770 throw new ClientException(_m('You are banned from posting notices on this site.'), 403);
772 if (common_config('throttle', 'enabled') && !self::checkEditThrottle($actor->id)) {
773 common_log(LOG_WARNING, 'Excessive posting by profile #' . $actor->id . '; throttled.');
774 // TRANS: Client exception thrown when a user tries to post too many notices in a given time frame.
775 throw new ClientException(_m('Too many notices too fast; take a breather '.
776 'and post again in a few minutes.'));
779 // Get ActivityObject properties
781 if (!empty($act->id)) {
783 $options['uri'] = $act->id;
784 $options['url'] = $act->link;
785 if ($act->selfLink) {
786 $options['self'] = $act->selfLink;
789 $actobj = count($act->objects)===1 ? $act->objects[0] : null;
790 if (!is_null($actobj) && !empty($actobj->id)) {
791 $options['uri'] = $actobj->id;
793 $options['url'] = $actobj->link;
794 } elseif (preg_match('!^https?://!', $actobj->id)) {
795 $options['url'] = $actobj->id;
798 if ($actobj->selfLink) {
799 $options['self'] = $actobj->selfLink;
805 'is_local' => $actor->isLocal() ? self::LOCAL_PUBLIC : self::REMOTE,
806 'mentions' => array(),
811 'source' => 'unknown',
816 'distribute' => true);
818 // options will have default values when nothing has been supplied
819 $options = array_merge($defaults, $options);
820 foreach (array_keys($defaults) as $key) {
821 // Only convert the keynames we specify ourselves from 'defaults' array into variables
822 $$key = $options[$key];
824 extract($options, EXTR_SKIP);
827 $stored = new Notice();
828 if (!empty($uri) && !ActivityUtils::compareVerbs($act->verb, array(ActivityVerb::DELETE))) {
830 if ($stored->find()) {
831 common_debug('cannot create duplicate Notice URI: '.$stored->uri);
832 // I _assume_ saving a Notice with a colliding URI means we're really trying to
833 // save the same notice again...
834 throw new AlreadyFulfilledException('Notice URI already exists');
838 $autosource = common_config('public', 'autosource');
840 // Sandboxed are non-false, but not 1, either
841 if (!$actor->hasRight(Right::PUBLICNOTICE) ||
842 ($source && $autosource && in_array($source, $autosource))) {
843 // FIXME: ...what about remote nonpublic? Hmmm. That is, if we sandbox remote profiles...
844 $stored->is_local = Notice::LOCAL_NONPUBLIC;
846 $stored->is_local = intval($is_local);
849 if (!$stored->isLocal()) {
850 // Only do these checks for non-local notices. Local notices will generate these values later.
851 if (!common_valid_http_url($url)) {
852 common_debug('Bad notice URL: ['.$url.'], URI: ['.$uri.']. Cannot link back to original! This is normal for shared notices etc.');
855 throw new ServerException('No URI for remote notice. Cannot accept that.');
859 $stored->profile_id = $actor->id;
860 $stored->source = $source;
863 if (common_valid_http_url($stored->self)) {
864 $stored->self = $self;
866 $stored->verb = $act->verb;
868 $content = $act->content ?: $act->summary;
869 if (is_null($content) && !is_null($actobj)) {
870 $content = $actobj->content ?: $actobj->summary;
872 // Strip out any bad HTML
873 $stored->rendered = common_purify($content);
874 $stored->content = common_strip_html($stored->getRendered(), true, true);
875 if (trim($stored->content) === '') {
876 // TRANS: Error message when the plain text content of a notice has zero length.
877 throw new ClientException(_('Empty notice content, will not save this.'));
880 // Maybe a missing act-time should be fatal if the actor is not local?
881 if (!empty($act->time)) {
882 $stored->created = common_sql_date($act->time);
884 $stored->created = common_sql_now();
888 if ($act->context instanceof ActivityContext && !empty($act->context->replyToID)) {
889 $reply = self::getKV('uri', $act->context->replyToID);
891 if (!$reply instanceof Notice && $act->target instanceof ActivityObject) {
892 $reply = self::getKV('uri', $act->target->id);
895 if ($reply instanceof Notice) {
896 if (!$reply->inScope($actor)) {
897 // TRANS: Client error displayed when trying to reply to a notice a the target has no access to.
898 // TRANS: %1$s is a user nickname, %2$d is a notice ID (number).
899 throw new ClientException(sprintf(_m('%1$s has no right to reply to notice %2$d.'), $actor->getNickname(), $reply->id), 403);
902 $stored->reply_to = $reply->id;
903 $stored->conversation = $reply->conversation;
905 // If the original is private to a group, and notice has no group specified,
906 // make it to the same group(s)
907 if (empty($groups) && ($reply->scope & Notice::GROUP_SCOPE)) {
908 $replyGroups = $reply->getGroups();
909 foreach ($replyGroups as $group) {
910 if ($actor->isMember($group)) {
911 $groups[] = $group->id;
916 if (is_null($scope)) {
917 $scope = $reply->scope;
920 // If we don't know the reply, we might know the conversation!
921 // This will happen if a known remote user replies to an
922 // unknown remote user - within a known conversation.
923 if (empty($stored->conversation) and !empty($act->context->conversation)) {
924 $conv = Conversation::getKV('uri', $act->context->conversation);
925 if ($conv instanceof Conversation) {
926 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.').');
928 // Conversation entry with specified URI was not found, so we must create it.
929 common_debug('Conversation URI not found, so we will create it with the URI given in the context of the activity: '.$act->context->conversation);
930 // The insert in Conversation::create throws exception on failure
931 $conv = Conversation::create($act->context->conversation, $stored->created);
933 $stored->conversation = $conv->getID();
938 // If it's not part of a conversation, it's the beginning of a new conversation.
939 if (empty($stored->conversation)) {
940 $conv = Conversation::create();
941 $stored->conversation = $conv->getID();
946 if ($act->context instanceof ActivityContext) {
947 if ($act->context->location instanceof Location) {
948 $notloc = Notice_location::fromLocation($act->context->location);
951 $act->context = new ActivityContext();
954 $stored->scope = self::figureOutScope($actor, $groups, $scope);
956 foreach ($act->categories as $cat) {
958 $term = common_canonical_tag($cat->term);
965 foreach ($act->enclosures as $href) {
966 // @todo FIXME: Save these locally or....?
970 if (ActivityUtils::compareVerbs($stored->verb, array(ActivityVerb::POST))) {
971 if (empty($act->objects[0]->type)) {
972 // Default type for the post verb is 'note', but we know it's
973 // a 'comment' if it is in reply to something.
974 $stored->object_type = empty($stored->reply_to) ? ActivityObject::NOTE : ActivityObject::COMMENT;
976 //TODO: Is it safe to always return a relative URI? The
977 // JSON version of ActivityStreams always use it, so we
978 // should definitely be able to handle it...
979 $stored->object_type = ActivityUtils::resolveUri($act->objects[0]->type, true);
983 if (Event::handle('StartNoticeSave', array(&$stored))) {
984 // XXX: some of these functions write to the DB
987 $result = $stored->insert(); // throws exception on error
989 if ($notloc instanceof Notice_location) {
990 $notloc->notice_id = $stored->getID();
994 $orig = clone($stored); // for updating later in this try clause
997 Event::handle('StoreActivityObject', array($act, $stored, $options, &$object));
998 if (empty($object)) {
999 throw new NoticeSaveException('Unsuccessful call to StoreActivityObject '._ve($stored->getUri()) . ': '._ve($act->asString()));
1002 // If something changed in the Notice during StoreActivityObject
1003 $stored->update($orig);
1004 } catch (Exception $e) {
1005 if (empty($stored->id)) {
1006 common_debug('Failed to save stored object entry in database ('.$e->getMessage().')');
1008 common_debug('Failed to store activity object in database ('.$e->getMessage().'), deleting notice id '.$stored->id);
1014 if (!$stored instanceof Notice) {
1015 throw new ServerException('StartNoticeSave did not give back a Notice');
1018 // Only save 'attention' and metadata stuff (URLs, tags...) stuff if
1019 // the activityverb is a POST (since stuff like repeat, favorite etc.
1020 // reasonably handle notifications themselves.
1021 if (ActivityUtils::compareVerbs($stored->verb, array(ActivityVerb::POST))) {
1023 if (!empty($tags)) {
1024 $stored->saveKnownTags($tags);
1026 $stored->saveTags();
1029 // Note: groups may save tags, so must be run after tags are saved
1030 // to avoid errors on duplicates.
1031 $stored->saveAttentions($act->context->attention);
1033 if (!empty($urls)) {
1034 $stored->saveKnownUrls($urls);
1036 $stored->saveUrls();
1041 // Prepare inbox delivery, may be queued to background.
1042 $stored->distribute();
1048 static public function figureOutScope(Profile $actor, array $groups, $scope=null) {
1049 $scope = is_null($scope) ? self::defaultScope() : intval($scope);
1051 // For private streams
1053 $user = $actor->getUser();
1054 // FIXME: We can't do bit comparison with == (Legacy StatusNet thing. Let's keep it for now.)
1055 if ($user->private_stream && ($scope === Notice::PUBLIC_SCOPE || $scope === Notice::SITE_SCOPE)) {
1056 $scope |= Notice::FOLLOWER_SCOPE;
1058 } catch (NoSuchUserException $e) {
1059 // TODO: Not a local user, so we don't know about scope preferences... yet!
1062 // Force the scope for private groups
1063 foreach ($groups as $group_id) {
1065 $group = User_group::getByID($group_id);
1066 if ($group->force_scope) {
1067 $scope |= Notice::GROUP_SCOPE;
1070 } catch (Exception $e) {
1071 common_log(LOG_ERR, 'Notice figureOutScope threw exception: '.$e->getMessage());
1078 function blowOnInsert($conversation = false)
1080 $this->blowStream('profile:notice_ids:%d', $this->profile_id);
1082 if ($this->isPublic()) {
1083 $this->blowStream('public');
1084 $this->blowStream('networkpublic');
1087 if ($this->conversation) {
1088 self::blow('notice:list-ids:conversation:%s', $this->conversation);
1089 self::blow('conversation:notice_count:%d', $this->conversation);
1092 if ($this->isRepeat()) {
1093 // XXX: we should probably only use one of these
1094 $this->blowStream('notice:repeats:%d', $this->repeat_of);
1095 self::blow('notice:list-ids:repeat_of:%d', $this->repeat_of);
1098 $original = Notice::getKV('id', $this->repeat_of);
1100 if ($original instanceof Notice) {
1101 $originalUser = User::getKV('id', $original->profile_id);
1102 if ($originalUser instanceof User) {
1103 $this->blowStream('user:repeats_of_me:%d', $originalUser->id);
1107 $profile = Profile::getKV($this->profile_id);
1109 if ($profile instanceof Profile) {
1110 $profile->blowNoticeCount();
1113 $ptags = $this->getProfileTags();
1114 foreach ($ptags as $ptag) {
1115 $ptag->blowNoticeStreamCache();
1120 * Clear cache entries related to this notice at delete time.
1121 * Necessary to avoid breaking paging on public, profile timelines.
1123 function blowOnDelete()
1125 $this->blowOnInsert();
1127 self::blow('profile:notice_ids:%d;last', $this->profile_id);
1129 if ($this->isPublic()) {
1130 self::blow('public;last');
1131 self::blow('networkpublic;last');
1134 self::blow('fave:by_notice', $this->id);
1136 if ($this->conversation) {
1137 // In case we're the first, will need to calc a new root.
1138 self::blow('notice:conversation_root:%d', $this->conversation);
1141 $ptags = $this->getProfileTags();
1142 foreach ($ptags as $ptag) {
1143 $ptag->blowNoticeStreamCache(true);
1147 function blowStream()
1149 $c = self::memcache();
1155 $args = func_get_args();
1156 $format = array_shift($args);
1157 $keyPart = vsprintf($format, $args);
1158 $cacheKey = Cache::key($keyPart);
1159 $c->delete($cacheKey);
1161 // delete the "last" stream, too, if this notice is
1162 // older than the top of that stream
1164 $lastKey = $cacheKey.';last';
1166 $lastStr = $c->get($lastKey);
1168 if ($lastStr !== false) {
1169 $window = explode(',', $lastStr);
1170 $lastID = $window[0];
1171 $lastNotice = Notice::getKV('id', $lastID);
1172 if (!$lastNotice instanceof Notice // just weird
1173 || strtotime($lastNotice->created) >= strtotime($this->created)) {
1174 $c->delete($lastKey);
1179 /** save all urls in the notice to the db
1181 * follow redirects and save all available file information
1182 * (mimetype, date, size, oembed, etc.)
1186 function saveUrls() {
1187 if (common_config('attachments', 'process_links')) {
1188 common_replace_urls_callback($this->content, array($this, 'saveUrl'), $this);
1193 * Save the given URLs as related links/attachments to the db
1195 * follow redirects and save all available file information
1196 * (mimetype, date, size, oembed, etc.)
1200 function saveKnownUrls($urls)
1202 if (common_config('attachments', 'process_links')) {
1203 // @fixme validation?
1204 foreach (array_unique($urls) as $url) {
1205 $this->saveUrl($url, $this);
1213 function saveUrl($url, Notice $notice) {
1215 File::processNew($url, $notice);
1216 } catch (ServerException $e) {
1217 // Could not save URL. Log it?
1221 static function checkDupes($profile_id, $content) {
1222 $profile = Profile::getKV($profile_id);
1223 if (!$profile instanceof Profile) {
1226 $notice = $profile->getNotices(0, CachingNoticeStream::CACHE_WINDOW);
1227 if (!empty($notice)) {
1229 while ($notice->fetch()) {
1230 if (time() - strtotime($notice->created) >= common_config('site', 'dupelimit')) {
1232 } else if ($notice->content == $content) {
1237 // If we get here, oldest item in cache window is not
1238 // old enough for dupe limit; do direct check against DB
1239 $notice = new Notice();
1240 $notice->profile_id = $profile_id;
1241 $notice->content = $content;
1242 $threshold = common_sql_date(time() - common_config('site', 'dupelimit'));
1243 $notice->whereAdd(sprintf("created > '%s'", $notice->escape($threshold)));
1245 $cnt = $notice->count();
1249 static function checkEditThrottle($profile_id) {
1250 $profile = Profile::getKV($profile_id);
1251 if (!$profile instanceof Profile) {
1254 // Get the Nth notice
1255 $notice = $profile->getNotices(common_config('throttle', 'count') - 1, 1);
1256 if ($notice && $notice->fetch()) {
1257 // If the Nth notice was posted less than timespan seconds ago
1258 if (time() - strtotime($notice->created) <= common_config('throttle', 'timespan')) {
1263 // Either not N notices in the stream, OR the Nth was not posted within timespan seconds
1267 protected $_attachments = array();
1269 function attachments() {
1270 if (isset($this->_attachments[$this->id])) {
1271 return $this->_attachments[$this->id];
1274 $f2ps = File_to_post::listGet('post_id', array($this->id));
1276 foreach ($f2ps[$this->id] as $f2p) {
1277 $ids[] = $f2p->file_id;
1280 $files = File::multiGet('id', $ids);
1281 $this->_attachments[$this->id] = $files->fetchAll();
1282 return $this->_attachments[$this->id];
1285 function _setAttachments($attachments)
1287 $this->_attachments[$this->id] = $attachments;
1290 static function publicStream($offset=0, $limit=20, $since_id=null, $max_id=null)
1292 $stream = new PublicNoticeStream();
1293 return $stream->getNotices($offset, $limit, $since_id, $max_id);
1296 static function conversationStream($id, $offset=0, $limit=20, $since_id=null, $max_id=null)
1298 $stream = new ConversationNoticeStream($id);
1299 return $stream->getNotices($offset, $limit, $since_id, $max_id);
1303 * Is this notice part of an active conversation?
1305 * @return boolean true if other messages exist in the same
1306 * conversation, false if this is the only one
1308 function hasConversation()
1310 if (empty($this->conversation)) {
1311 // this notice is not part of a conversation apparently
1312 // FIXME: all notices should have a conversation value, right?
1316 $stream = new ConversationNoticeStream($this->conversation);
1317 $notice = $stream->getNotices(/*offset*/ 1, /*limit*/ 1);
1319 // if our "offset 1, limit 1" query got a result, return true else false
1320 return $notice->N > 0;
1324 * Grab the earliest notice from this conversation.
1326 * @return Notice or null
1328 function conversationRoot($profile=-1)
1330 // XXX: can this happen?
1332 if (empty($this->conversation)) {
1336 // Get the current profile if not specified
1338 if (is_int($profile) && $profile == -1) {
1339 $profile = Profile::current();
1342 // If this notice is out of scope, no root for you!
1344 if (!$this->inScope($profile)) {
1348 // If this isn't a reply to anything, then it's its own
1349 // root if it's the earliest notice in the conversation:
1351 if (empty($this->reply_to)) {
1353 $root->conversation = $this->conversation;
1354 $root->orderBy('notice.created ASC');
1355 $root->find(true); // true means "fetch first result"
1360 if (is_null($profile)) {
1361 $keypart = sprintf('notice:conversation_root:%d:null', $this->id);
1363 $keypart = sprintf('notice:conversation_root:%d:%d',
1368 $root = self::cacheGet($keypart);
1370 if ($root !== false && $root->inScope($profile)) {
1377 $parent = $last->getParent();
1378 if ($parent->inScope($profile)) {
1382 } catch (NoParentNoticeException $e) {
1383 // Latest notice has no parent
1384 } catch (NoResultException $e) {
1385 // Notice was not found, so we can't go further up in the tree.
1386 // FIXME: Maybe we should do this in a more stable way where deleted
1387 // notices won't break conversation chains?
1389 // No parent, or parent out of scope
1394 self::cacheSet($keypart, $root);
1400 * Pull up a full list of local recipients who will be getting
1401 * this notice in their inbox. Results will be cached, so don't
1402 * change the input data wily-nilly!
1404 * @param array $groups optional list of Group objects;
1405 * if left empty, will be loaded from group_inbox records
1406 * @param array $recipient optional list of reply profile ids
1407 * if left empty, will be loaded from reply records
1408 * @return array associating recipient user IDs with an inbox source constant
1410 function whoGets(array $groups=null, array $recipients=null)
1412 $c = self::memcache();
1415 $ni = $c->get(Cache::key('notice:who_gets:'.$this->id));
1416 if ($ni !== false) {
1421 if (is_null($recipients)) {
1422 $recipients = $this->getReplies();
1427 // Give plugins a chance to add folks in at start...
1428 if (Event::handle('StartNoticeWhoGets', array($this, &$ni))) {
1430 $users = $this->getSubscribedUsers();
1431 foreach ($users as $id) {
1432 $ni[$id] = NOTICE_INBOX_SOURCE_SUB;
1435 if (is_null($groups)) {
1436 $groups = $this->getGroups();
1438 foreach ($groups as $group) {
1439 $users = $group->getUserMembers();
1440 foreach ($users as $id) {
1441 if (!array_key_exists($id, $ni)) {
1442 $ni[$id] = NOTICE_INBOX_SOURCE_GROUP;
1447 $ptAtts = $this->getAttentionsFromProfileTags();
1448 foreach ($ptAtts as $key=>$val) {
1449 if (!array_key_exists($key, $ni)) {
1454 foreach ($recipients as $recipient) {
1455 if (!array_key_exists($recipient, $ni)) {
1456 $ni[$recipient] = NOTICE_INBOX_SOURCE_REPLY;
1460 // Exclude any deleted, non-local, or blocking recipients.
1461 $profile = $this->getProfile();
1462 $originalProfile = null;
1463 if ($this->isRepeat()) {
1464 // Check blocks against the original notice's poster as well.
1465 $original = Notice::getKV('id', $this->repeat_of);
1466 if ($original instanceof Notice) {
1467 $originalProfile = $original->getProfile();
1471 foreach ($ni as $id => $source) {
1473 $user = User::getKV('id', $id);
1474 if (!$user instanceof User ||
1475 $user->hasBlocked($profile) ||
1476 ($originalProfile && $user->hasBlocked($originalProfile))) {
1479 } catch (UserNoProfileException $e) {
1480 // User doesn't have a profile; invalid; skip them.
1485 // Give plugins a chance to filter out...
1486 Event::handle('EndNoticeWhoGets', array($this, &$ni));
1490 // XXX: pack this data better
1491 $c->set(Cache::key('notice:who_gets:'.$this->id), $ni);
1497 function getSubscribedUsers()
1501 if(common_config('db','quote_identifiers'))
1502 $user_table = '"user"';
1503 else $user_table = 'user';
1507 'FROM '. $user_table .' JOIN subscription '.
1508 'ON '. $user_table .'.id = subscription.subscriber ' .
1509 'WHERE subscription.subscribed = %d ';
1511 $user->query(sprintf($qry, $this->profile_id));
1515 while ($user->fetch()) {
1524 function getProfileTags()
1526 $profile = $this->getProfile();
1527 $list = $profile->getOtherTags($profile);
1530 while($list->fetch()) {
1531 $ptags[] = clone($list);
1537 public function getAttentionsFromProfileTags()
1540 $ptags = $this->getProfileTags();
1541 foreach ($ptags as $ptag) {
1542 $users = $ptag->getUserSubscribers();
1543 foreach ($users as $id) {
1544 $ni[$id] = NOTICE_INBOX_SOURCE_PROFILE_TAG;
1551 * Record this notice to the given group inboxes for delivery.
1552 * Overrides the regular parsing of !group markup.
1554 * @param string $group_ids
1555 * @fixme might prefer URIs as identifiers, as for replies?
1556 * best with generalizations on user_group to support
1557 * remote groups better.
1559 function saveKnownGroups(array $group_ids)
1562 foreach (array_unique($group_ids) as $id) {
1563 $group = User_group::getKV('id', $id);
1564 if ($group instanceof User_group) {
1565 common_log(LOG_DEBUG, "Local delivery to group id $id, $group->nickname");
1566 $result = $this->addToGroupInbox($group);
1568 common_log_db_error($gi, 'INSERT', __FILE__);
1571 if (common_config('group', 'addtag')) {
1572 // we automatically add a tag for every group name, too
1574 $tag = Notice_tag::pkeyGet(array('tag' => common_canonical_tag($group->nickname),
1575 'notice_id' => $this->id));
1577 if (is_null($tag)) {
1578 $this->saveTag($group->nickname);
1582 $groups[] = clone($group);
1584 common_log(LOG_ERR, "Local delivery to group id $id skipped, doesn't exist");
1591 function addToGroupInbox(User_group $group)
1593 $gi = Group_inbox::pkeyGet(array('group_id' => $group->id,
1594 'notice_id' => $this->id));
1596 if (!$gi instanceof Group_inbox) {
1598 $gi = new Group_inbox();
1600 $gi->group_id = $group->id;
1601 $gi->notice_id = $this->id;
1602 $gi->created = $this->created;
1604 $result = $gi->insert();
1607 common_log_db_error($gi, 'INSERT', __FILE__);
1608 // TRANS: Server exception thrown when an update for a group inbox fails.
1609 throw new ServerException(_('Problem saving group inbox.'));
1612 self::blow('user_group:notice_ids:%d', $gi->group_id);
1618 function saveAttentions(array $uris)
1620 foreach ($uris as $uri=>$type) {
1622 $target = Profile::fromUri($uri);
1623 } catch (UnknownUriException $e) {
1624 common_log(LOG_WARNING, "Unable to determine profile for URI '$uri'");
1629 $this->saveAttention($target);
1630 } catch (AlreadyFulfilledException $e) {
1631 common_debug('Attention already exists: '.var_export($e->getMessage(),true));
1632 } catch (Exception $e) {
1633 common_log(LOG_ERR, "Could not save notice id=={$this->getID()} attention for profile id=={$target->getID()}: {$e->getMessage()}");
1639 * Saves an attention for a profile (user or group) which means
1640 * it shows up in their home feed and such.
1642 function saveAttention(Profile $target, $reason=null)
1644 if ($target->isGroup()) {
1645 // FIXME: Make sure we check (for both local and remote) users are in the groups they send to!
1647 // legacy notification method, will still be in use for quite a while I think
1648 $this->addToGroupInbox($target->getGroup());
1650 if ($target->hasBlocked($this->getProfile())) {
1651 common_log(LOG_INFO, "Not saving reply to profile {$target->id} ($uri) from sender {$sender->id} because of a block.");
1656 if ($target->isLocal()) {
1657 // legacy notification method, will still be in use for quite a while I think
1658 $this->saveReply($target->getID());
1661 $att = Attention::saveNew($this, $target, $reason);
1663 self::blow('reply:stream:%d', $target->getID());
1668 * Save reply records indicating that this notice needs to be
1669 * delivered to the local users with the given URIs.
1671 * Since this is expected to be used when saving foreign-sourced
1672 * messages, we won't deliver to any remote targets as that's the
1673 * source service's responsibility.
1675 * Mail notifications etc will be handled later.
1677 * @param array $uris Array of unique identifier URIs for recipients
1679 function saveKnownReplies(array $uris)
1685 $sender = $this->getProfile();
1687 foreach (array_unique($uris) as $uri) {
1689 $profile = Profile::fromUri($uri);
1690 } catch (UnknownUriException $e) {
1691 common_log(LOG_WARNING, "Unable to determine profile for URI '$uri'");
1695 if ($profile->hasBlocked($sender)) {
1696 common_log(LOG_INFO, "Not saving reply to profile {$profile->id} ($uri) from sender {$sender->id} because of a block.");
1700 $this->saveReply($profile->getID());
1701 self::blow('reply:stream:%d', $profile->getID());
1706 * Pull @-replies from this message's content in StatusNet markup format
1707 * and save reply records indicating that this message needs to be
1708 * delivered to those users.
1710 * Mail notifications to local profiles will be sent later.
1712 * @return array of integer profile IDs
1715 function saveReplies()
1717 $sender = $this->getProfile();
1721 // If it's a reply, save for the replied-to author
1723 $parent = $this->getParent();
1724 $parentauthor = $parent->getProfile();
1725 $this->saveReply($parentauthor->getID());
1726 $replied[$parentauthor->getID()] = 1;
1727 self::blow('reply:stream:%d', $parentauthor->getID());
1728 } catch (NoParentNoticeException $e) {
1729 // Not a reply, since it has no parent!
1731 } catch (NoResultException $e) {
1732 // Parent notice was probably deleted
1736 // @todo ideally this parser information would only
1737 // be calculated once.
1739 $mentions = common_find_mentions($this->content, $sender, $parent);
1741 foreach ($mentions as $mention) {
1743 foreach ($mention['mentioned'] as $mentioned) {
1745 // skip if they're already covered
1746 if (array_key_exists($mentioned->id, $replied)) {
1750 // Don't save replies from blocked profile to local user
1751 if ($mentioned->hasBlocked($sender)) {
1755 $this->saveReply($mentioned->id);
1756 $replied[$mentioned->id] = 1;
1757 self::blow('reply:stream:%d', $mentioned->id);
1761 $recipientIds = array_keys($replied);
1763 return $recipientIds;
1766 function saveReply($profileId)
1768 $reply = new Reply();
1770 $reply->notice_id = $this->id;
1771 $reply->profile_id = $profileId;
1772 $reply->modified = $this->created;
1779 protected $_attentionids = array();
1782 * Pull the complete list of known activity context attentions for this notice.
1784 * @return array of integer profile ids (also group profiles)
1786 function getAttentionProfileIDs()
1788 if (!isset($this->_attentionids[$this->getID()])) {
1789 $atts = Attention::multiGet('notice_id', array($this->getID()));
1790 // (array)null means empty array
1791 $this->_attentionids[$this->getID()] = (array)$atts->fetchAll('profile_id');
1793 return $this->_attentionids[$this->getID()];
1796 protected $_replies = array();
1799 * Pull the complete list of @-mentioned profile IDs for this notice.
1801 * @return array of integer profile ids
1803 function getReplies()
1805 if (!isset($this->_replies[$this->getID()])) {
1806 $mentions = Reply::multiGet('notice_id', array($this->getID()));
1807 $this->_replies[$this->getID()] = $mentions->fetchAll('profile_id');
1809 return $this->_replies[$this->getID()];
1812 function _setReplies($replies)
1814 $this->_replies[$this->getID()] = $replies;
1818 * Pull the complete list of @-reply targets for this notice.
1820 * @return array of Profiles
1822 function getAttentionProfiles()
1824 $ids = array_unique(array_merge($this->getReplies(), $this->getGroupProfileIDs(), $this->getAttentionProfileIDs()));
1826 $profiles = Profile::multiGet('id', (array)$ids);
1828 return $profiles->fetchAll();
1832 * Send e-mail notifications to local @-reply targets.
1834 * Replies must already have been saved; this is expected to be run
1835 * from the distrib queue handler.
1837 function sendReplyNotifications()
1839 // Don't send reply notifications for repeats
1840 if ($this->isRepeat()) {
1844 $recipientIds = $this->getReplies();
1845 if (Event::handle('StartNotifyMentioned', array($this, &$recipientIds))) {
1846 require_once INSTALLDIR.'/lib/mail.php';
1848 foreach ($recipientIds as $recipientId) {
1850 $user = User::getByID($recipientId);
1851 mail_notify_attn($user, $this);
1852 } catch (NoResultException $e) {
1856 Event::handle('EndNotifyMentioned', array($this, $recipientIds));
1861 * Pull list of Profile IDs of groups this notice addresses.
1863 * @return array of Group _profile_ IDs
1866 function getGroupProfileIDs()
1870 foreach ($this->getGroups() as $group) {
1871 $ids[] = $group->profile_id;
1878 * Pull list of groups this notice needs to be delivered to,
1879 * as previously recorded by saveKnownGroups().
1881 * @return array of Group objects
1884 protected $_groups = array();
1886 function getGroups()
1888 // Don't save groups for repeats
1890 if (!empty($this->repeat_of)) {
1894 if (isset($this->_groups[$this->id])) {
1895 return $this->_groups[$this->id];
1898 $gis = Group_inbox::listGet('notice_id', array($this->id));
1902 foreach ($gis[$this->id] as $gi) {
1903 $ids[] = $gi->group_id;
1906 $groups = User_group::multiGet('id', $ids);
1907 $this->_groups[$this->id] = $groups->fetchAll();
1908 return $this->_groups[$this->id];
1911 function _setGroups($groups)
1913 $this->_groups[$this->id] = $groups;
1917 * Convert a notice into an activity for export.
1919 * @param Profile $scoped The currently logged in/scoped profile
1921 * @return Activity activity object representing this Notice.
1924 function asActivity(Profile $scoped=null)
1926 $act = self::cacheGet(Cache::codeKey('notice:as-activity:'.$this->id));
1928 if ($act instanceof Activity) {
1931 $act = new Activity();
1933 if (Event::handle('StartNoticeAsActivity', array($this, $act, $scoped))) {
1935 $act->id = $this->uri;
1936 $act->time = strtotime($this->created);
1938 $act->link = $this->getUrl();
1939 } catch (InvalidUrlException $e) {
1940 // The notice is probably a share or similar, which don't
1941 // have a representational URL of their own.
1943 $act->content = common_xml_safe_str($this->getRendered());
1945 $profile = $this->getProfile();
1947 $act->actor = $profile->asActivityObject();
1948 $act->actor->extra[] = $profile->profileInfo($scoped);
1950 $act->verb = $this->verb;
1952 if (!$this->repeat_of) {
1953 $act->objects[] = $this->asActivityObject();
1956 // XXX: should this be handled by default processing for object entry?
1960 $tags = $this->getTags();
1962 foreach ($tags as $tag) {
1963 $cat = new AtomCategory();
1966 $act->categories[] = $cat;
1970 // XXX: use Atom Media and/or File activity objects instead
1972 $attachments = $this->attachments();
1974 foreach ($attachments as $attachment) {
1975 // Include local attachments in Activity
1976 if (!empty($attachment->filename)) {
1977 $act->enclosures[] = $attachment->getEnclosure();
1981 $ctx = new ActivityContext();
1984 $reply = $this->getParent();
1985 $ctx->replyToID = $reply->getUri();
1986 $ctx->replyToUrl = $reply->getUrl(true); // true for fallback to local URL, less messy
1987 } catch (NoParentNoticeException $e) {
1988 // This is not a reply to something
1989 } catch (NoResultException $e) {
1990 // Parent notice was probably deleted
1994 $ctx->location = Notice_location::locFromStored($this);
1995 } catch (ServerException $e) {
1996 $ctx->location = null;
2001 if (!empty($this->conversation)) {
2002 $conv = Conversation::getKV('id', $this->conversation);
2003 if ($conv instanceof Conversation) {
2004 $ctx->conversation = $conv->uri;
2008 // This covers the legacy getReplies and getGroups too which get their data
2009 // from entries stored via Notice::saveNew (which we want to move away from)...
2010 foreach ($this->getAttentionProfiles() as $target) {
2011 // User and group profiles which get the attention of this notice
2012 $ctx->attention[$target->getUri()] = $target->getObjectType();
2015 switch ($this->scope) {
2016 case Notice::PUBLIC_SCOPE:
2017 $ctx->attention[ActivityContext::ATTN_PUBLIC] = ActivityObject::COLLECTION;
2019 case Notice::FOLLOWER_SCOPE:
2020 $surl = common_local_url("subscribers", array('nickname' => $profile->nickname));
2021 $ctx->attention[$surl] = ActivityObject::COLLECTION;
2025 $act->context = $ctx;
2027 $source = $this->getSource();
2029 if ($source instanceof Notice_source) {
2030 $act->generator = ActivityObject::fromNoticeSource($source);
2035 $atom_feed = $profile->getAtomFeed();
2037 if (!empty($atom_feed)) {
2039 $act->source = new ActivitySource();
2041 // XXX: we should store the actual feed ID
2043 $act->source->id = $atom_feed;
2045 // XXX: we should store the actual feed title
2047 $act->source->title = $profile->getBestName();
2049 $act->source->links['alternate'] = $profile->profileurl;
2050 $act->source->links['self'] = $atom_feed;
2052 $act->source->icon = $profile->avatarUrl(AVATAR_PROFILE_SIZE);
2054 $notice = $profile->getCurrentNotice();
2056 if ($notice instanceof Notice) {
2057 $act->source->updated = self::utcDate($notice->created);
2060 $user = User::getKV('id', $profile->id);
2062 if ($user instanceof User) {
2063 $act->source->links['license'] = common_config('license', 'url');
2067 if ($this->isLocal()) {
2068 $act->selfLink = common_local_url('ApiStatusesShow', array('id' => $this->id,
2069 'format' => 'atom'));
2070 $act->editLink = $act->selfLink;
2073 Event::handle('EndNoticeAsActivity', array($this, $act, $scoped));
2076 self::cacheSet(Cache::codeKey('notice:as-activity:'.$this->id), $act);
2081 // This has gotten way too long. Needs to be sliced up into functional bits
2082 // or ideally exported to a utility class.
2084 function asAtomEntry($namespace=false,
2087 Profile $scoped=null)
2089 $act = $this->asActivity($scoped);
2090 $act->extra[] = $this->noticeInfo($scoped);
2091 return $act->asString($namespace, $author, $source);
2095 * Extra notice info for atom entries
2097 * Clients use some extra notice info in the atom stream.
2098 * This gives it to them.
2100 * @param Profile $scoped The currently logged in/scoped profile
2102 * @return array representation of <statusnet:notice_info> element
2105 function noticeInfo(Profile $scoped=null)
2107 // local notice ID (useful to clients for ordering)
2109 $noticeInfoAttr = array('local_id' => $this->id);
2113 $ns = $this->getSource();
2115 if ($ns instanceof Notice_source) {
2116 $noticeInfoAttr['source'] = $ns->code;
2117 if (!empty($ns->url)) {
2118 $noticeInfoAttr['source_link'] = $ns->url;
2119 if (!empty($ns->name)) {
2120 $noticeInfoAttr['source'] = $ns->name;
2125 // favorite and repeated
2127 if ($scoped instanceof Profile) {
2128 $noticeInfoAttr['repeated'] = ($scoped->hasRepeated($this)) ? "true" : "false";
2131 if (!empty($this->repeat_of)) {
2132 $noticeInfoAttr['repeat_of'] = $this->repeat_of;
2135 Event::handle('StatusNetApiNoticeInfo', array($this, &$noticeInfoAttr, $scoped));
2137 return array('statusnet:notice_info', $noticeInfoAttr, null);
2141 * Returns an XML string fragment with a reference to a notice as an
2142 * Activity Streams noun object with the given element type.
2144 * Assumes that 'activity' namespace has been previously defined.
2146 * @param string $element one of 'subject', 'object', 'target'
2150 function asActivityNoun($element)
2152 $noun = $this->asActivityObject();
2153 return $noun->asString('activity:' . $element);
2156 public function asActivityObject()
2158 $object = new ActivityObject();
2160 if (Event::handle('StartActivityObjectFromNotice', array($this, &$object))) {
2161 $object->type = $this->object_type ?: ActivityObject::NOTE;
2162 $object->id = $this->getUri();
2163 //FIXME: = $object->title ?: sprintf(... because we might get a title from StartActivityObjectFromNotice
2164 $object->title = sprintf('New %1$s by %2$s', ActivityObject::canonicalType($object->type), $this->getProfile()->getNickname());
2165 $object->content = $this->getRendered();
2166 $object->link = $this->getUrl();
2168 $object->extra[] = array('status_net', array('notice_id' => $this->id));
2170 Event::handle('EndActivityObjectFromNotice', array($this, &$object));
2173 if (!$object instanceof ActivityObject) {
2174 common_log(LOG_ERR, 'Notice asActivityObject created something else for uri=='._ve($this->getUri()).': '._ve($object));
2175 throw new ServerException('Notice asActivityObject created something else.');
2182 * Determine which notice, if any, a new notice is in reply to.
2184 * For conversation tracking, we try to see where this notice fits
2185 * in the tree. Beware that this may very well give false positives
2186 * and add replies to wrong threads (if there have been newer posts
2187 * by the same user as we're replying to).
2189 * @param Profile $sender Author profile
2190 * @param string $content Final notice content
2192 * @return integer ID of replied-to notice, or null for not a reply.
2195 static function getInlineReplyTo(Profile $sender, $content)
2197 // Is there an initial @ or T?
2198 if (preg_match('/^T ([A-Z0-9]{1,64}) /', $content, $match)
2199 || preg_match('/^@([a-z0-9]{1,64})\s+/', $content, $match)) {
2200 $nickname = common_canonical_nickname($match[1]);
2205 // Figure out who that is.
2206 $recipient = common_relative_profile($sender, $nickname, common_sql_now());
2208 if ($recipient instanceof Profile) {
2209 // Get their last notice
2210 $last = $recipient->getCurrentNotice();
2211 if ($last instanceof Notice) {
2214 // Maybe in the future we want to handle something else below
2215 // so don't return getCurrentNotice() immediately.
2221 static function maxContent()
2223 $contentlimit = common_config('notice', 'contentlimit');
2224 // null => use global limit (distinct from 0!)
2225 if (is_null($contentlimit)) {
2226 $contentlimit = common_config('site', 'textlimit');
2228 return $contentlimit;
2231 static function contentTooLong($content)
2233 $contentlimit = self::maxContent();
2234 return ($contentlimit > 0 && !empty($content) && (mb_strlen($content) > $contentlimit));
2238 * Convenience function for posting a repeat of an existing message.
2240 * @param Profile $repeater Profile which is doing the repeat
2241 * @param string $source: posting source key, eg 'web', 'api', etc
2244 * @throws Exception on failure or permission problems
2246 function repeat(Profile $repeater, $source)
2248 $author = $this->getProfile();
2250 // TRANS: Message used to repeat a notice. RT is the abbreviation of 'retweet'.
2251 // TRANS: %1$s is the repeated user's name, %2$s is the repeated notice.
2252 $content = sprintf(_('RT @%1$s %2$s'),
2253 $author->getNickname(),
2256 $maxlen = self::maxContent();
2257 if ($maxlen > 0 && mb_strlen($content) > $maxlen) {
2258 // Web interface and current Twitter API clients will
2259 // pull the original notice's text, but some older
2260 // clients and RSS/Atom feeds will see this trimmed text.
2262 // Unfortunately this is likely to lose tags or URLs
2263 // at the end of long notices.
2264 $content = mb_substr($content, 0, $maxlen - 4) . ' ...';
2268 // Scope is same as this one's
2269 return self::saveNew($repeater->id,
2272 array('repeat_of' => $this->id,
2273 'scope' => $this->scope));
2276 // These are supposed to be in chron order!
2278 function repeatStream($limit=100)
2280 $cache = Cache::instance();
2282 if (empty($cache)) {
2283 $ids = $this->_repeatStreamDirect($limit);
2285 $idstr = $cache->get(Cache::key('notice:repeats:'.$this->id));
2286 if ($idstr !== false) {
2287 if (empty($idstr)) {
2290 $ids = explode(',', $idstr);
2293 $ids = $this->_repeatStreamDirect(100);
2294 $cache->set(Cache::key('notice:repeats:'.$this->id), implode(',', $ids));
2297 // We do a max of 100, so slice down to limit
2298 $ids = array_slice($ids, 0, $limit);
2302 return NoticeStream::getStreamByIds($ids);
2305 function _repeatStreamDirect($limit)
2307 $notice = new Notice();
2309 $notice->selectAdd(); // clears it
2310 $notice->selectAdd('id');
2312 $notice->repeat_of = $this->id;
2314 $notice->orderBy('created, id'); // NB: asc!
2316 if (!is_null($limit)) {
2317 $notice->limit(0, $limit);
2320 return $notice->fetchAll('id');
2323 static function locationOptions($lat, $lon, $location_id, $location_ns, $profile = null)
2327 if (!empty($location_id) && !empty($location_ns)) {
2328 $options['location_id'] = $location_id;
2329 $options['location_ns'] = $location_ns;
2331 $location = Location::fromId($location_id, $location_ns);
2333 if ($location instanceof Location) {
2334 $options['lat'] = $location->lat;
2335 $options['lon'] = $location->lon;
2338 } else if (!empty($lat) && !empty($lon)) {
2339 $options['lat'] = $lat;
2340 $options['lon'] = $lon;
2342 $location = Location::fromLatLon($lat, $lon);
2344 if ($location instanceof Location) {
2345 $options['location_id'] = $location->location_id;
2346 $options['location_ns'] = $location->location_ns;
2348 } else if (!empty($profile)) {
2349 if (isset($profile->lat) && isset($profile->lon)) {
2350 $options['lat'] = $profile->lat;
2351 $options['lon'] = $profile->lon;
2354 if (isset($profile->location_id) && isset($profile->location_ns)) {
2355 $options['location_id'] = $profile->location_id;
2356 $options['location_ns'] = $profile->location_ns;
2363 function clearAttentions()
2365 $att = new Attention();
2366 $att->notice_id = $this->getID();
2369 while ($att->fetch()) {
2370 // Can't do delete() on the object directly since it won't remove all of it
2371 $other = clone($att);
2377 function clearReplies()
2379 $replyNotice = new Notice();
2380 $replyNotice->reply_to = $this->id;
2382 //Null any notices that are replies to this notice
2384 if ($replyNotice->find()) {
2385 while ($replyNotice->fetch()) {
2386 $orig = clone($replyNotice);
2387 $replyNotice->reply_to = null;
2388 $replyNotice->update($orig);
2394 $reply = new Reply();
2395 $reply->notice_id = $this->id;
2397 if ($reply->find()) {
2398 while($reply->fetch()) {
2399 self::blow('reply:stream:%d', $reply->profile_id);
2407 function clearLocation()
2409 $loc = new Notice_location();
2410 $loc->notice_id = $this->id;
2417 function clearFiles()
2419 $f2p = new File_to_post();
2421 $f2p->post_id = $this->id;
2424 while ($f2p->fetch()) {
2428 // FIXME: decide whether to delete File objects
2429 // ...and related (actual) files
2432 function clearRepeats()
2434 $repeatNotice = new Notice();
2435 $repeatNotice->repeat_of = $this->id;
2437 //Null any notices that are repeats of this notice
2439 if ($repeatNotice->find()) {
2440 while ($repeatNotice->fetch()) {
2441 $orig = clone($repeatNotice);
2442 $repeatNotice->repeat_of = null;
2443 $repeatNotice->update($orig);
2448 function clearTags()
2450 $tag = new Notice_tag();
2451 $tag->notice_id = $this->id;
2454 while ($tag->fetch()) {
2455 self::blow('profile:notice_ids_tagged:%d:%s', $this->profile_id, Cache::keyize($tag->tag));
2456 self::blow('profile:notice_ids_tagged:%d:%s;last', $this->profile_id, Cache::keyize($tag->tag));
2457 self::blow('notice_tag:notice_ids:%s', Cache::keyize($tag->tag));
2458 self::blow('notice_tag:notice_ids:%s;last', Cache::keyize($tag->tag));
2466 function clearGroupInboxes()
2468 $gi = new Group_inbox();
2470 $gi->notice_id = $this->id;
2473 while ($gi->fetch()) {
2474 self::blow('user_group:notice_ids:%d', $gi->group_id);
2482 function distribute()
2484 // We always insert for the author so they don't
2486 Event::handle('StartNoticeDistribute', array($this));
2488 // If there's a failure, we want to _force_
2489 // distribution at this point.
2491 $json = json_encode((object)array('id' => $this->getID(),
2494 $qm = QueueManager::get();
2495 $qm->enqueue($json, 'distrib');
2496 } catch (Exception $e) {
2497 // If the exception isn't transient, this
2498 // may throw more exceptions as DQH does
2499 // its own enqueueing. So, we ignore them!
2501 $handler = new DistribQueueHandler();
2502 $handler->handle($this);
2503 } catch (Exception $e) {
2504 common_log(LOG_ERR, "emergency redistribution resulted in " . $e->getMessage());
2506 // Re-throw so somebody smarter can handle it.
2513 $result = parent::insert();
2515 if ($result === false) {
2516 common_log_db_error($this, 'INSERT', __FILE__);
2517 // TRANS: Server exception thrown when a stored object entry cannot be saved.
2518 throw new ServerException('Could not save Notice');
2521 // Profile::hasRepeated() abuses pkeyGet(), so we
2522 // have to clear manually
2523 if (!empty($this->repeat_of)) {
2524 $c = self::memcache();
2526 $ck = self::multicacheKey('Notice',
2527 array('profile_id' => $this->profile_id,
2528 'repeat_of' => $this->repeat_of));
2533 // Update possibly ID-dependent columns: URI, conversation
2534 // (now that INSERT has added the notice's local id)
2535 $orig = clone($this);
2538 // We can only get here if it's a local notice, since remote notices
2539 // should've bailed out earlier due to lacking a URI.
2540 if (empty($this->uri)) {
2541 $this->uri = sprintf('%s%s=%d:%s=%s',
2543 'noticeId', $this->id,
2544 'objectType', $this->getObjectType(true));
2548 if ($changed && $this->update($orig) === false) {
2549 common_log_db_error($notice, 'UPDATE', __FILE__);
2550 // TRANS: Server exception thrown when a notice cannot be updated.
2551 throw new ServerException(_('Problem saving notice.'));
2554 $this->blowOnInsert();
2560 * Get the source of the notice
2562 * @return Notice_source $ns A notice source object. 'code' is the only attribute
2563 * guaranteed to be populated.
2565 function getSource()
2567 if (empty($this->source)) {
2571 $ns = new Notice_source();
2572 switch ($this->source) {
2579 $ns->code = $this->source;
2582 $ns = Notice_source::getKV($this->source);
2584 $ns = new Notice_source();
2585 $ns->code = $this->source;
2586 $app = Oauth_application::getKV('name', $this->source);
2588 $ns->name = $app->name;
2589 $ns->url = $app->source_url;
2599 * Determine whether the notice was locally created
2601 * @return boolean locality
2604 public function isLocal()
2606 $is_local = intval($this->is_local);
2607 return ($is_local === self::LOCAL_PUBLIC || $is_local === self::LOCAL_NONPUBLIC);
2610 public function getScope()
2612 return intval($this->scope);
2615 public function isRepeat()
2617 return !empty($this->repeat_of);
2621 * Get the list of hash tags saved with this notice.
2623 * @return array of strings
2625 public function getTags()
2629 $keypart = sprintf('notice:tags:%d', $this->id);
2631 $tagstr = self::cacheGet($keypart);
2633 if ($tagstr !== false) {
2634 $tags = explode(',', $tagstr);
2636 $tag = new Notice_tag();
2637 $tag->notice_id = $this->id;
2639 while ($tag->fetch()) {
2640 $tags[] = $tag->tag;
2643 self::cacheSet($keypart, implode(',', $tags));
2649 static private function utcDate($dt)
2651 $dateStr = date('d F Y H:i:s', strtotime($dt));
2652 $d = new DateTime($dateStr, new DateTimeZone('UTC'));
2653 return $d->format(DATE_W3C);
2657 * Look up the creation timestamp for a given notice ID, even
2658 * if it's been deleted.
2661 * @return mixed string recorded creation timestamp, or false if can't be found
2663 public static function getAsTimestamp($id)
2666 throw new EmptyIdException('Notice');
2670 if (Event::handle('GetNoticeSqlTimestamp', array($id, &$timestamp))) {
2671 // getByID throws exception if $id isn't found
2672 $notice = Notice::getByID($id);
2673 $timestamp = $notice->created;
2676 if (empty($timestamp)) {
2677 throw new ServerException('No timestamp found for Notice with id=='._ve($id));
2683 * Build an SQL 'where' fragment for timestamp-based sorting from a since_id
2684 * parameter, matching notices posted after the given one (exclusive).
2686 * If the referenced notice can't be found, will return false.
2689 * @param string $idField
2690 * @param string $createdField
2691 * @return mixed string or false if no match
2693 public static function whereSinceId($id, $idField='id', $createdField='created')
2696 $since = Notice::getAsTimestamp($id);
2697 } catch (Exception $e) {
2700 return sprintf("($createdField = '%s' and $idField > %d) or ($createdField > '%s')", $since, $id, $since);
2704 * Build an SQL 'where' fragment for timestamp-based sorting from a since_id
2705 * parameter, matching notices posted after the given one (exclusive), and
2706 * if necessary add it to the data object's query.
2708 * @param DB_DataObject $obj
2710 * @param string $idField
2711 * @param string $createdField
2712 * @return mixed string or false if no match
2714 public static function addWhereSinceId(DB_DataObject $obj, $id, $idField='id', $createdField='created')
2716 $since = self::whereSinceId($id, $idField, $createdField);
2718 $obj->whereAdd($since);
2723 * Build an SQL 'where' fragment for timestamp-based sorting from a max_id
2724 * parameter, matching notices posted before the given one (inclusive).
2726 * If the referenced notice can't be found, will return false.
2729 * @param string $idField
2730 * @param string $createdField
2731 * @return mixed string or false if no match
2733 public static function whereMaxId($id, $idField='id', $createdField='created')
2736 $max = Notice::getAsTimestamp($id);
2737 } catch (Exception $e) {
2740 return sprintf("($createdField < '%s') or ($createdField = '%s' and $idField <= %d)", $max, $max, $id);
2744 * Build an SQL 'where' fragment for timestamp-based sorting from a max_id
2745 * parameter, matching notices posted before the given one (inclusive), and
2746 * if necessary add it to the data object's query.
2748 * @param DB_DataObject $obj
2750 * @param string $idField
2751 * @param string $createdField
2752 * @return mixed string or false if no match
2754 public static function addWhereMaxId(DB_DataObject $obj, $id, $idField='id', $createdField='created')
2756 $max = self::whereMaxId($id, $idField, $createdField);
2758 $obj->whereAdd($max);
2764 return (($this->is_local != Notice::LOCAL_NONPUBLIC) &&
2765 ($this->is_local != Notice::GATEWAY));
2769 * Check that the given profile is allowed to read, respond to, or otherwise
2770 * act on this notice.
2772 * The $scope member is a bitmask of scopes, representing a logical AND of the
2773 * scope requirement. So, 0x03 (Notice::ADDRESSEE_SCOPE | Notice::SITE_SCOPE) means
2774 * "only visible to people who are mentioned in the notice AND are users on this site."
2775 * Users on the site who are not mentioned in the notice will not be able to see the
2778 * @param Profile $profile The profile to check; pass null to check for public/unauthenticated users.
2780 * @return boolean whether the profile is in the notice's scope
2782 function inScope($profile)
2784 if (is_null($profile)) {
2785 $keypart = sprintf('notice:in-scope-for:%d:null', $this->id);
2787 $keypart = sprintf('notice:in-scope-for:%d:%d', $this->id, $profile->id);
2790 $result = self::cacheGet($keypart);
2792 if ($result === false) {
2794 if (Event::handle('StartNoticeInScope', array($this, $profile, &$bResult))) {
2795 $bResult = $this->_inScope($profile);
2796 Event::handle('EndNoticeInScope', array($this, $profile, &$bResult));
2798 $result = ($bResult) ? 1 : 0;
2799 self::cacheSet($keypart, $result, 0, 300);
2802 return ($result == 1) ? true : false;
2805 protected function _inScope($profile)
2807 $scope = is_null($this->scope) ? self::defaultScope() : $this->getScope();
2809 if ($scope === 0 && !$this->getProfile()->isPrivateStream()) { // Not scoping, so it is public.
2810 return !$this->isHiddenSpam($profile);
2813 // If there's scope, anon cannot be in scope
2814 if (empty($profile)) {
2818 // Author is always in scope
2819 if ($this->profile_id == $profile->id) {
2823 // Only for users on this site
2824 if (($scope & Notice::SITE_SCOPE) && !$profile->isLocal()) {
2828 // Only for users mentioned in the notice
2829 if ($scope & Notice::ADDRESSEE_SCOPE) {
2831 $reply = Reply::pkeyGet(array('notice_id' => $this->id,
2832 'profile_id' => $profile->id));
2834 if (!$reply instanceof Reply) {
2839 // Only for members of the given group
2840 if ($scope & Notice::GROUP_SCOPE) {
2842 // XXX: just query for the single membership
2844 $groups = $this->getGroups();
2848 foreach ($groups as $group) {
2849 if ($profile->isMember($group)) {
2860 if ($scope & Notice::FOLLOWER_SCOPE || $this->getProfile()->isPrivateStream()) {
2862 if (!Subscription::exists($profile, $this->getProfile())) {
2867 return !$this->isHiddenSpam($profile);
2870 function isHiddenSpam($profile) {
2872 // Hide posts by silenced users from everyone but moderators.
2874 if (common_config('notice', 'hidespam')) {
2877 $author = $this->getProfile();
2878 } catch(Exception $e) {
2879 // If we can't get an author, keep it hidden.
2880 // XXX: technically not spam, but, whatever.
2884 if ($author->hasRole(Profile_role::SILENCED)) {
2885 if (!$profile instanceof Profile || (($profile->id !== $author->id) && (!$profile->hasRight(Right::REVIEWSPAM)))) {
2894 public function hasParent()
2898 } catch (NoParentNoticeException $e) {
2904 public function getParent()
2906 $reply_to_id = null;
2908 if (empty($this->reply_to)) {
2909 throw new NoParentNoticeException($this);
2912 // The reply_to ID in the table Notice could exist with a number
2913 // however, the replied to notice might not exist in the database.
2914 // Thus we need to catch the exception and throw the NoParentNoticeException else
2915 // the timeline will not display correctly.
2917 $reply_to_id = self::getByID($this->reply_to);
2918 } catch(Exception $e){
2919 throw new NoParentNoticeException($this);
2922 return $reply_to_id;
2926 * Magic function called at serialize() time.
2928 * We use this to drop a couple process-specific references
2929 * from DB_DataObject which can cause trouble in future
2932 * @return array of variable names to include in serialization.
2937 $vars = parent::__sleep();
2938 $skip = array('_profile', '_groups', '_attachments', '_faves', '_replies', '_repeats');
2939 return array_diff($vars, $skip);
2942 static function defaultScope()
2944 $scope = common_config('notice', 'defaultscope');
2945 if (is_null($scope)) {
2946 if (common_config('site', 'private')) {
2955 static function fillProfiles($notices)
2957 $map = self::getProfiles($notices);
2958 foreach ($notices as $entry=>$notice) {
2960 if (array_key_exists($notice->profile_id, $map)) {
2961 $notice->_setProfile($map[$notice->profile_id]);
2963 } catch (NoProfileException $e) {
2964 common_log(LOG_WARNING, "Failed to fill profile in Notice with non-existing entry for profile_id: {$e->profile_id}");
2965 unset($notices[$entry]);
2969 return array_values($map);
2972 static function getProfiles(&$notices)
2975 foreach ($notices as $notice) {
2976 $ids[] = $notice->profile_id;
2978 $ids = array_unique($ids);
2979 return Profile::pivotGet('id', $ids);
2982 static function fillGroups(&$notices)
2984 $ids = self::_idsOf($notices);
2985 $gis = Group_inbox::listGet('notice_id', $ids);
2988 foreach ($gis as $id => $gi) {
2991 $gids[] = $g->group_id;
2995 $gids = array_unique($gids);
2996 $group = User_group::pivotGet('id', $gids);
2997 foreach ($notices as $notice)
3000 $gi = $gis[$notice->id];
3001 foreach ($gi as $g) {
3002 $grps[] = $group[$g->group_id];
3004 $notice->_setGroups($grps);
3008 static function _idsOf(array &$notices)
3011 foreach ($notices as $notice) {
3012 $ids[$notice->id] = true;
3014 return array_keys($ids);
3017 static function fillAttachments(&$notices)
3019 $ids = self::_idsOf($notices);
3020 $f2pMap = File_to_post::listGet('post_id', $ids);
3022 foreach ($f2pMap as $noticeId => $f2ps) {
3023 foreach ($f2ps as $f2p) {
3024 $fileIds[] = $f2p->file_id;
3028 $fileIds = array_unique($fileIds);
3029 $fileMap = File::pivotGet('id', $fileIds);
3030 foreach ($notices as $notice)
3033 $f2ps = $f2pMap[$notice->id];
3034 foreach ($f2ps as $f2p) {
3035 $files[] = $fileMap[$f2p->file_id];
3037 $notice->_setAttachments($files);
3041 static function fillReplies(&$notices)
3043 $ids = self::_idsOf($notices);
3044 $replyMap = Reply::listGet('notice_id', $ids);
3045 foreach ($notices as $notice) {
3046 $replies = $replyMap[$notice->id];
3048 foreach ($replies as $reply) {
3049 $ids[] = $reply->profile_id;
3051 $notice->_setReplies($ids);
3055 static public function beforeSchemaUpdate()
3057 $table = strtolower(get_called_class());
3058 $schema = Schema::get();
3059 $schemadef = $schema->getTableDef($table);
3061 // 2015-09-04 We move Notice location data to Notice_location
3062 // First we see if we have to do this at all
3063 if (!isset($schemadef['fields']['lat'])
3064 && !isset($schemadef['fields']['lon'])
3065 && !isset($schemadef['fields']['location_id'])
3066 && !isset($schemadef['fields']['location_ns'])) {
3067 // We have already removed the location fields, so no need to migrate.
3070 // Then we make sure the Notice_location table is created!
3071 $schema->ensureTable('notice_location', Notice_location::schemaDef());
3073 // Then we continue on our road to migration!
3074 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)";
3076 $notice = new Notice();
3077 $notice->query(sprintf('SELECT id, lat, lon, location_id, location_ns FROM %1$s ' .
3078 'WHERE lat IS NOT NULL ' .
3079 'OR lon IS NOT NULL ' .
3080 'OR location_id IS NOT NULL ' .
3081 'OR location_ns IS NOT NULL',
3082 $schema->quoteIdentifier($table)));
3083 print "\nFound {$notice->N} notices with location data, inserting";
3084 while ($notice->fetch()) {
3085 $notloc = Notice_location::getKV('notice_id', $notice->id);
3086 if ($notloc instanceof Notice_location) {
3090 $notloc = new Notice_location();
3091 $notloc->notice_id = $notice->id;
3092 $notloc->lat= $notice->lat;
3093 $notloc->lon= $notice->lon;
3094 $notloc->location_id= $notice->location_id;
3095 $notloc->location_ns= $notice->location_ns;