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(255) unique_key
59 public $content; // text
60 public $rendered; // text
61 public $url; // varchar(255)
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 $lat; // decimal(10,7)
69 public $lon; // decimal(10,7)
70 public $location_id; // int(4)
71 public $location_ns; // int(4)
72 public $repeat_of; // int(4)
73 public $verb; // varchar(255)
74 public $object_type; // varchar(255)
75 public $scope; // int(4)
77 /* the code above is auto generated do not remove the tag below */
80 public static function schemaDef()
84 'id' => array('type' => 'serial', 'not null' => true, 'description' => 'unique identifier'),
85 'profile_id' => array('type' => 'int', 'not null' => true, 'description' => 'who made the update'),
86 'uri' => array('type' => 'varchar', 'length' => 255, 'description' => 'universally unique identifier, usually a tag URI'),
87 'content' => array('type' => 'text', 'description' => 'update content', 'collate' => 'utf8_general_ci'),
88 'rendered' => array('type' => 'text', 'description' => 'HTML version of the content'),
89 'url' => array('type' => 'varchar', 'length' => 255, 'description' => 'URL of any attachment (image, video, bookmark, whatever)'),
90 'created' => array('type' => 'datetime', 'not null' => true, 'description' => 'date this record was created'),
91 'modified' => array('type' => 'timestamp', 'not null' => true, 'description' => 'date this record was modified'),
92 'reply_to' => array('type' => 'int', 'description' => 'notice replied to (usually a guess)'),
93 'is_local' => array('type' => 'int', 'size' => 'tiny', 'default' => 0, 'description' => 'notice was generated by a user'),
94 'source' => array('type' => 'varchar', 'length' => 32, 'description' => 'source of comment, like "web", "im", or "clientname"'),
95 'conversation' => array('type' => 'int', 'description' => 'id of root notice in this conversation'),
96 'lat' => array('type' => 'numeric', 'precision' => 10, 'scale' => 7, 'description' => 'latitude'),
97 'lon' => array('type' => 'numeric', 'precision' => 10, 'scale' => 7, 'description' => 'longitude'),
98 'location_id' => array('type' => 'int', 'description' => 'location id if possible'),
99 'location_ns' => array('type' => 'int', 'description' => 'namespace for location'),
100 'repeat_of' => array('type' => 'int', 'description' => 'notice this is a repeat of'),
101 'object_type' => array('type' => 'varchar', 'length' => 255, 'description' => 'URI representing activity streams object type', 'default' => 'http://activitystrea.ms/schema/1.0/note'),
102 'verb' => array('type' => 'varchar', 'length' => 255, 'description' => 'URI representing activity streams verb', 'default' => 'http://activitystrea.ms/schema/1.0/post'),
103 'scope' => array('type' => 'int',
104 'description' => 'bit map for distribution scope; 0 = everywhere; 1 = this server only; 2 = addressees; 4 = followers; null = default'),
106 'primary key' => array('id'),
107 'unique keys' => array(
108 'notice_uri_key' => array('uri'),
110 'foreign keys' => array(
111 'notice_profile_id_fkey' => array('profile', array('profile_id' => 'id')),
112 'notice_reply_to_fkey' => array('notice', array('reply_to' => 'id')),
113 'notice_conversation_fkey' => array('conversation', array('conversation' => 'id')), # note... used to refer to notice.id
114 'notice_repeat_of_fkey' => array('notice', array('repeat_of' => 'id')), # @fixme: what about repeats of deleted notices?
117 'notice_created_id_is_local_idx' => array('created', 'id', 'is_local'),
118 'notice_profile_id_idx' => array('profile_id', 'created', 'id'),
119 'notice_repeat_of_created_id_idx' => array('repeat_of', 'created', 'id'),
120 'notice_conversation_created_id_idx' => array('conversation', 'created', 'id'),
121 'notice_replyto_idx' => array('reply_to')
125 if (common_config('search', 'type') == 'fulltext') {
126 $def['fulltext indexes'] = array('content' => array('content'));
133 const LOCAL_PUBLIC = 1;
135 const LOCAL_NONPUBLIC = -1;
138 const PUBLIC_SCOPE = 0; // Useful fake constant
139 const SITE_SCOPE = 1;
140 const ADDRESSEE_SCOPE = 2;
141 const GROUP_SCOPE = 4;
142 const FOLLOWER_SCOPE = 8;
144 protected $_profile = array();
147 * Will always return a profile, if anything fails it will
148 * (through _setProfile) throw a NoProfileException.
150 public function getProfile()
152 if (!isset($this->_profile[$this->profile_id])) {
153 // We could've sent getKV directly to _setProfile, but occasionally we get
154 // a "false" (instead of null), likely because it indicates a cache miss.
155 $profile = Profile::getKV('id', $this->profile_id);
156 $this->_setProfile($profile instanceof Profile ? $profile : null);
158 return $this->_profile[$this->profile_id];
161 public function _setProfile(Profile $profile=null)
163 if (!$profile instanceof Profile) {
164 throw new NoProfileException($this->profile_id);
166 $this->_profile[$this->profile_id] = $profile;
169 function delete($useWhere=false)
171 // For auditing purposes, save a record that the notice
174 // @fixme we have some cases where things get re-run and so the
176 $deleted = Deleted_notice::getKV('id', $this->id);
178 if (!$deleted instanceof Deleted_notice) {
179 $deleted = Deleted_notice::getKV('uri', $this->uri);
182 if (!$deleted instanceof Deleted_notice) {
183 $deleted = new Deleted_notice();
185 $deleted->id = $this->id;
186 $deleted->profile_id = $this->profile_id;
187 $deleted->uri = $this->uri;
188 $deleted->created = $this->created;
189 $deleted->deleted = common_sql_now();
194 if (Event::handle('NoticeDeleteRelated', array($this))) {
196 // Clear related records
198 $this->clearReplies();
199 $this->clearRepeats();
201 $this->clearGroupInboxes();
203 $this->clearAttentions();
205 // NOTE: we don't clear queue items
208 $result = parent::delete($useWhere);
210 $this->blowOnDelete();
214 public function getUri()
220 * Get a Notice object by URI. Will call external plugins for help
221 * using the event StartGetNoticeFromURI.
223 * @param string $uri A unique identifier for a resource (notice in this case)
225 static function fromUri($uri)
229 if (Event::handle('StartGetNoticeFromUri', array($uri, &$notice))) {
230 $notice = Notice::getKV('uri', $uri);
231 Event::handle('EndGetNoticeFromUri', array($uri, $notice));
234 if (!$notice instanceof Notice) {
235 throw new UnknownUriException($uri);
242 * @param $root boolean If true, link to just the conversation root.
244 * @return URL to conversation
246 public function getConversationUrl($anchor=true)
248 return Conversation::getUrlFromNotice($this, $anchor);
252 * Get the local representation URL of this notice.
254 public function getLocalUrl()
256 return common_local_url('shownotice', array('notice' => $this->id), null, null, false);
259 public function getTitle()
262 if (Event::handle('GetNoticeTitle', array($this, &$title))) {
263 // TRANS: Title of a notice posted without a title value.
264 // TRANS: %1$s is a user name, %2$s is the notice creation date/time.
265 $title = sprintf(_('%1$s\'s status on %2$s'),
266 $this->getProfile()->getFancyName(),
267 common_exact_date($this->created));
272 public function getContent()
274 return $this->content;
278 * Get the original representation URL of this notice.
280 * @param boolean $fallback Whether to fall back to generate a local URL or throw InvalidUrlException
282 public function getUrl($fallback=false)
284 // The risk is we start having empty urls and non-http uris...
285 // and we can't really handle any other protocol right now.
287 case common_valid_http_url($this->url): // should we allow non-http/https URLs?
289 case !$this->isLocal() && common_valid_http_url($this->uri): // Sometimes we only have the URI for remote posts.
291 case $this->isLocal() || $fallback:
292 // let's generate a valid link to our locally available notice on demand
293 return common_local_url('shownotice', array('notice' => $this->id), null, null, false);
295 common_debug('No URL available for notice: id='.$this->id);
296 throw new InvalidUrlException($this->url);
300 public function get_object_type($canonical=false) {
302 ? ActivityObject::canonicalType($this->object_type)
303 : $this->object_type;
306 public static function getByUri($uri)
308 $notice = new Notice();
310 if (!$notice->find(true)) {
311 throw new NoResultException($notice);
317 * Extract #hashtags from this notice's content and save them to the database.
321 /* extract all #hastags */
322 $count = preg_match_all('/(?:^|\s)#([\pL\pN_\-\.]{1,64})/u', strtolower($this->content), $match);
327 /* Add them to the database */
328 return $this->saveKnownTags($match[1]);
332 * Record the given set of hash tags in the db for this notice.
333 * Given tag strings will be normalized and checked for dupes.
335 function saveKnownTags(array $hashtags)
337 //turn each into their canonical tag
338 //this is needed to remove dupes before saving e.g. #hash.tag = #hashtag
339 for($i=0; $i<count($hashtags); $i++) {
340 /* elide characters we don't want in the tag */
341 $hashtags[$i] = common_canonical_tag($hashtags[$i]);
344 foreach(array_unique($hashtags) as $hashtag) {
345 $this->saveTag($hashtag);
346 self::blow('profile:notice_ids_tagged:%d:%s', $this->profile_id, $hashtag);
352 * Record a single hash tag as associated with this notice.
353 * Tag format and uniqueness must be validated by caller.
355 function saveTag($hashtag)
357 $tag = new Notice_tag();
358 $tag->notice_id = $this->id;
359 $tag->tag = $hashtag;
360 $tag->created = $this->created;
361 $id = $tag->insert();
364 // TRANS: Server exception. %s are the error details.
365 throw new ServerException(sprintf(_('Database error inserting hashtag: %s.'),
366 $last_error->message));
370 // if it's saved, blow its cache
371 $tag->blowCache(false);
375 * Save a new notice and push it out to subscribers' inboxes.
376 * Poster's permissions are checked before sending.
378 * @param int $profile_id Profile ID of the poster
379 * @param string $content source message text; links may be shortened
380 * per current user's preference
381 * @param string $source source key ('web', 'api', etc)
382 * @param array $options Associative array of optional properties:
383 * string 'created' timestamp of notice; defaults to now
384 * int 'is_local' source/gateway ID, one of:
385 * Notice::LOCAL_PUBLIC - Local, ok to appear in public timeline
386 * Notice::REMOTE - Sent from a remote service;
387 * hide from public timeline but show in
388 * local "and friends" timelines
389 * Notice::LOCAL_NONPUBLIC - Local, but hide from public timeline
390 * Notice::GATEWAY - From another non-OStatus service;
391 * will not appear in public views
392 * float 'lat' decimal latitude for geolocation
393 * float 'lon' decimal longitude for geolocation
394 * int 'location_id' geoname identifier
395 * int 'location_ns' geoname namespace to interpret location_id
396 * int 'reply_to'; notice ID this is a reply to
397 * int 'repeat_of'; notice ID this is a repeat of
398 * string 'uri' unique ID for notice; a unique tag uri (can be url or anything too)
399 * string 'url' permalink to notice; defaults to local notice URL
400 * string 'rendered' rendered HTML version of content
401 * array 'replies' list of profile URIs for reply delivery in
402 * place of extracting @-replies from content.
403 * array 'groups' list of group IDs to deliver to, in place of
404 * extracting ! tags from content
405 * array 'tags' list of hashtag strings to save with the notice
406 * in place of extracting # tags from content
407 * array 'urls' list of attached/referred URLs to save with the
408 * notice in place of extracting links from content
409 * boolean 'distribute' whether to distribute the notice, default true
410 * string 'object_type' URL of the associated object type (default ActivityObject::NOTE)
411 * string 'verb' URL of the associated verb (default ActivityVerb::POST)
412 * int 'scope' Scope bitmask; default to SITE_SCOPE on private sites, 0 otherwise
414 * @fixme tag override
417 * @throws ClientException
419 static function saveNew($profile_id, $content, $source, array $options=null) {
420 $defaults = array('uri' => null,
422 'conversation' => null, // URI of conversation
423 'reply_to' => null, // This will override convo URI if the parent is known
424 'repeat_of' => null, // This will override convo URI if the repeated notice is known
426 'distribute' => true,
427 'object_type' => null,
430 if (!empty($options) && is_array($options)) {
431 $options = array_merge($defaults, $options);
437 if (!isset($is_local)) {
438 $is_local = Notice::LOCAL_PUBLIC;
441 $profile = Profile::getKV('id', $profile_id);
442 if (!$profile instanceof Profile) {
443 // TRANS: Client exception thrown when trying to save a notice for an unknown user.
444 throw new ClientException(_('Problem saving notice. Unknown user.'));
447 $user = User::getKV('id', $profile_id);
448 if ($user instanceof User) {
449 // Use the local user's shortening preferences, if applicable.
450 $final = $user->shortenLinks($content);
452 $final = common_shorten_links($content);
455 if (Notice::contentTooLong($final)) {
456 // TRANS: Client exception thrown if a notice contains too many characters.
457 throw new ClientException(_('Problem saving notice. Too long.'));
460 if (common_config('throttle', 'enabled') && !Notice::checkEditThrottle($profile_id)) {
461 common_log(LOG_WARNING, 'Excessive posting by profile #' . $profile_id . '; throttled.');
462 // TRANS: Client exception thrown when a user tries to post too many notices in a given time frame.
463 throw new ClientException(_('Too many notices too fast; take a breather '.
464 'and post again in a few minutes.'));
467 if (common_config('site', 'dupelimit') > 0 && !Notice::checkDupes($profile_id, $final)) {
468 common_log(LOG_WARNING, 'Dupe posting by profile #' . $profile_id . '; throttled.');
469 // TRANS: Client exception thrown when a user tries to post too many duplicate notices in a given time frame.
470 throw new ClientException(_('Too many duplicate messages too quickly;'.
471 ' take a breather and post again in a few minutes.'));
474 if (!$profile->hasRight(Right::NEWNOTICE)) {
475 common_log(LOG_WARNING, "Attempted post from user disallowed to post: " . $profile->nickname);
477 // TRANS: Client exception thrown when a user tries to post while being banned.
478 throw new ClientException(_('You are banned from posting notices on this site.'), 403);
481 $notice = new Notice();
482 $notice->profile_id = $profile_id;
484 $autosource = common_config('public', 'autosource');
486 // Sandboxed are non-false, but not 1, either
488 if (!$profile->hasRight(Right::PUBLICNOTICE) ||
489 ($source && $autosource && in_array($source, $autosource))) {
490 $notice->is_local = Notice::LOCAL_NONPUBLIC;
492 $notice->is_local = $is_local;
495 if (!empty($created)) {
496 $notice->created = $created;
498 $notice->created = common_sql_now();
501 if (!$notice->isLocal()) {
502 // Only do these checks for non-local notices. Local notices will generate these values later.
503 if (!common_valid_http_url($url)) {
504 common_debug('Bad notice URL: ['.$url.'], URI: ['.$uri.']. Cannot link back to original! This is normal for shared notices etc.');
507 throw new ServerException('No URI for remote notice. Cannot accept that.');
511 $notice->content = $final;
513 $notice->source = $source;
517 // Get the groups here so we can figure out replies and such
518 if (!isset($groups)) {
519 $groups = User_group::idsFromText($notice->content, $profile);
524 // Handle repeat case
526 if (isset($repeat_of)) {
528 // Check for a private one
530 $repeat = Notice::getKV('id', $repeat_of);
532 if (!($repeat instanceof Notice)) {
533 // TRANS: Client exception thrown in notice when trying to repeat a missing or deleted notice.
534 throw new ClientException(_('Cannot repeat; original notice is missing or deleted.'));
537 if ($profile->id == $repeat->profile_id) {
538 // TRANS: Client error displayed when trying to repeat an own notice.
539 throw new ClientException(_('You cannot repeat your own notice.'));
542 if ($repeat->scope != Notice::SITE_SCOPE &&
543 $repeat->scope != Notice::PUBLIC_SCOPE) {
544 // TRANS: Client error displayed when trying to repeat a non-public notice.
545 throw new ClientException(_('Cannot repeat a private notice.'), 403);
548 if (!$repeat->inScope($profile)) {
549 // The generic checks above should cover this, but let's be sure!
550 // TRANS: Client error displayed when trying to repeat a notice you cannot access.
551 throw new ClientException(_('Cannot repeat a notice you cannot read.'), 403);
554 if ($profile->hasRepeated($repeat)) {
555 // TRANS: Client error displayed when trying to repeat an already repeated notice.
556 throw new ClientException(_('You already repeated that notice.'));
559 $notice->repeat_of = $repeat->id;
560 $notice->conversation = $repeat->conversation;
564 // If $reply_to is specified, we check that it exists, and then
565 // return it if it does
566 if (!empty($reply_to)) {
567 $reply = Notice::getKV('id', $reply_to);
568 } elseif (in_array($source, array('xmpp', 'mail', 'sms'))) {
569 // If the source lacks capability of sending the "reply_to"
570 // metadata, let's try to find an inline replyto-reference.
571 $reply = self::getInlineReplyTo($profile, $final);
574 if ($reply instanceof Notice) {
575 if (!$reply->inScope($profile)) {
576 // TRANS: Client error displayed when trying to reply to a notice a the target has no access to.
577 // TRANS: %1$s is a user nickname, %2$d is a notice ID (number).
578 throw new ClientException(sprintf(_('%1$s has no access to notice %2$d.'),
579 $profile->nickname, $reply->id), 403);
582 // If it's a repeat, the reply_to should be to the original
583 if ($reply->isRepeat()) {
584 $notice->reply_to = $reply->repeat_of;
586 $notice->reply_to = $reply->id;
588 // But the conversation ought to be the same :)
589 $notice->conversation = $reply->conversation;
591 // If the original is private to a group, and notice has
592 // no group specified, make it to the same group(s)
594 if (empty($groups) && ($reply->scope & Notice::GROUP_SCOPE)) {
596 $replyGroups = $reply->getGroups();
597 foreach ($replyGroups as $group) {
598 if ($profile->isMember($group)) {
599 $groups[] = $group->id;
607 // If we don't know the reply, we might know the conversation!
608 // This will happen if a known remote user replies to an
609 // unknown remote user - within a known conversation.
610 if (empty($notice->conversation) and !empty($options['conversation'])) {
611 $conv = Conversation::getKV('uri', $options['conversation']);
612 if ($conv instanceof Conversation) {
613 common_debug('Conversation stitched together from (probably) reply to unknown remote user. Activity creation time ('.$notice->created.') should maybe be compared to conversation creation time ('.$conv->created.').');
614 $notice->conversation = $conv->id;
616 // Conversation URI was not found, so we must create it. But we can't create it
617 // until we have a Notice ID because of the database layout...
618 $notice->tmp_conv_uri = $options['conversation'];
621 // If we're not using the attached conversation URI let's remove it
622 // so we don't mistake ourselves later, when creating our own Conversation.
623 // This implies that the notice knows which conversation it belongs to.
624 $options['conversation'] = null;
628 if (!empty($lat) && !empty($lon)) {
633 if (!empty($location_ns) && !empty($location_id)) {
634 $notice->location_id = $location_id;
635 $notice->location_ns = $location_ns;
638 if (!empty($rendered)) {
639 $notice->rendered = $rendered;
641 $notice->rendered = common_render_content($final, $notice);
645 if ($notice->isRepeat()) {
646 $notice->verb = ActivityVerb::SHARE;
647 $notice->object_type = ActivityObject::ACTIVITY;
649 $notice->verb = ActivityVerb::POST;
652 $notice->verb = $verb;
655 if (empty($object_type)) {
656 $notice->object_type = (empty($notice->reply_to)) ? ActivityObject::NOTE : ActivityObject::COMMENT;
658 $notice->object_type = $object_type;
661 if (is_null($scope) && $reply instanceof Notice) {
662 $notice->scope = $reply->scope;
664 $notice->scope = $scope;
667 $notice->scope = self::figureOutScope($profile, $groups, $notice->scope);
669 if (Event::handle('StartNoticeSave', array(&$notice))) {
671 // XXX: some of these functions write to the DB
674 $notice->insert(); // throws exception on failure
675 // If it's not part of a conversation, it's
676 // the beginning of a new conversation.
677 if (empty($notice->conversation)) {
678 $orig = clone($notice);
679 // $act->context->conversation will be null if it was not provided
680 $conv = Conversation::create($notice, $options['conversation']);
681 $notice->conversation = $conv->id;
682 $notice->update($orig);
684 } catch (Exception $e) {
685 // Let's test if we managed initial insert, which would imply
686 // failing on some update-part (check 'insert()'). Delete if
687 // something had been stored to the database.
688 if (!empty($notice->id)) {
695 // Clear the cache for subscribed users, so they'll update at next request
696 // XXX: someone clever could prepend instead of clearing the cache
698 // Save per-notice metadata...
700 if (isset($replies)) {
701 $notice->saveKnownReplies($replies);
703 $notice->saveReplies();
707 $notice->saveKnownTags($tags);
712 // Note: groups may save tags, so must be run after tags are saved
713 // to avoid errors on duplicates.
714 // Note: groups should always be set.
716 $notice->saveKnownGroups($groups);
719 $notice->saveKnownUrls($urls);
725 // Prepare inbox delivery, may be queued to background.
726 $notice->distribute();
732 static function saveActivity(Activity $act, Profile $actor, array $options=array())
734 // First check if we're going to let this Activity through from the specific actor
735 if (!$actor->hasRight(Right::NEWNOTICE)) {
736 common_log(LOG_WARNING, "Attempted post from user disallowed to post: " . $actor->getNickname());
738 // TRANS: Client exception thrown when a user tries to post while being banned.
739 throw new ClientException(_m('You are banned from posting notices on this site.'), 403);
741 if (common_config('throttle', 'enabled') && !self::checkEditThrottle($actor->id)) {
742 common_log(LOG_WARNING, 'Excessive posting by profile #' . $actor->id . '; throttled.');
743 // TRANS: Client exception thrown when a user tries to post too many notices in a given time frame.
744 throw new ClientException(_m('Too many notices too fast; take a breather '.
745 'and post again in a few minutes.'));
748 // Get ActivityObject properties
749 if (!empty($act->id)) {
751 $options['uri'] = $act->id;
752 $options['url'] = $act->link;
754 $actobj = count($act->objects)==1 ? $act->objects[0] : null;
755 if (!is_null($actobj) && !empty($actobj->id)) {
756 $options['uri'] = $actobj->id;
758 $options['url'] = $actobj->link;
759 } elseif (preg_match('!^https?://!', $actobj->id)) {
760 $options['url'] = $actobj->id;
767 'is_local' => self::LOCAL_PUBLIC,
768 'mentions' => array(),
772 'source' => 'unknown',
777 'distribute' => true);
779 // options will have default values when nothing has been supplied
780 $options = array_merge($defaults, $options);
781 foreach (array_keys($defaults) as $key) {
782 // Only convert the keynames we specify ourselves from 'defaults' array into variables
783 $$key = $options[$key];
785 extract($options, EXTR_SKIP);
787 $stored = new Notice();
790 if ($stored->find()) {
791 common_debug('cannot create duplicate Notice URI: '.$stored->uri);
792 throw new Exception('Notice URI already exists');
796 $stored->profile_id = $actor->id;
797 $stored->source = $source;
800 $stored->verb = $act->verb;
802 // Use the local user's shortening preferences, if applicable.
803 $stored->rendered = $actor->isLocal()
804 ? $actor->shortenLinks($act->content)
806 $stored->content = common_strip_html($stored->rendered);
808 $autosource = common_config('public', 'autosource');
810 // Sandboxed are non-false, but not 1, either
811 if (!$actor->hasRight(Right::PUBLICNOTICE) ||
812 ($source && $autosource && in_array($source, $autosource))) {
813 $stored->is_local = Notice::LOCAL_NONPUBLIC;
816 // Maybe a missing act-time should be fatal if the actor is not local?
817 if (!empty($act->time)) {
818 $stored->created = common_sql_date($act->time);
820 $stored->created = common_sql_now();
824 if ($act->context instanceof ActivityContext && !empty($act->context->replyToID)) {
825 $reply = self::getKV('uri', $act->context->replyToID);
827 if (!$reply instanceof Notice && $act->target instanceof ActivityObject) {
828 $reply = self::getKV('uri', $act->target->id);
831 if ($reply instanceof Notice) {
832 if (!$reply->inScope($actor)) {
833 // TRANS: Client error displayed when trying to reply to a notice a the target has no access to.
834 // TRANS: %1$s is a user nickname, %2$d is a notice ID (number).
835 throw new ClientException(sprintf(_m('%1$s has no right to reply to notice %2$d.'), $actor->getNickname(), $reply->id), 403);
838 $stored->reply_to = $reply->id;
839 $stored->conversation = $reply->conversation;
841 // If the original is private to a group, and notice has no group specified,
842 // make it to the same group(s)
843 if (empty($groups) && ($reply->scope & Notice::GROUP_SCOPE)) {
845 $replyGroups = $reply->getGroups();
846 foreach ($replyGroups as $group) {
847 if ($actor->isMember($group)) {
848 $groups[] = $group->id;
853 if (is_null($scope)) {
854 $scope = $reply->scope;
858 if ($act->context instanceof ActivityContext) {
859 $location = $act->context->location;
861 $stored->lat = $location->lat;
862 $stored->lon = $location->lon;
863 if ($location->location_id) {
864 $stored->location_ns = $location->location_ns;
865 $stored->location_id = $location->location_id;
869 $act->context = new ActivityContext();
872 $stored->scope = self::figureOutScope($actor, $groups, $scope);
874 foreach ($act->categories as $cat) {
876 $term = common_canonical_tag($cat->term);
883 foreach ($act->enclosures as $href) {
884 // @todo FIXME: Save these locally or....?
888 if (Event::handle('StartNoticeSave', array(&$stored))) {
889 // XXX: some of these functions write to the DB
892 $stored->insert(); // throws exception on error
893 $orig = clone($stored); // for updating later in this try clause
895 // If it's not part of a conversation, it's
896 // the beginning of a new conversation.
897 if (empty($stored->conversation)) {
898 // $act->context->conversation will be null if it was not provided
899 $conv = Conversation::create($stored, $act->context->conversation);
900 $stored->conversation = $conv->id;
904 Event::handle('StoreActivityObject', array($act, $stored, $options, &$object));
905 if (empty($object)) {
906 throw new ServerException('No object from StoreActivityObject '.$stored->uri . ': '.$act->asString());
908 $stored->object_type = ActivityUtils::resolveUri($object->getObjectType(), true);
909 $stored->update($orig);
910 } catch (Exception $e) {
911 if (empty($stored->id)) {
912 common_debug('Failed to save stored object entry in database ('.$e->getMessage().')');
914 common_debug('Failed to store activity object in database ('.$e->getMessage().'), deleting notice id '.$stored->id);
920 if (!$stored instanceof Notice) {
921 throw new ServerException('StartNoticeSave did not give back a Notice');
924 // Save per-notice metadata...
928 // This event lets plugins filter out non-local recipients (attentions we don't care about)
929 // Used primarily for OStatus (and if we don't federate, all attentions would be local anyway)
930 Event::handle('GetLocalAttentions', array($actor, $act->context->attention, &$mentions, &$groups));
932 if (!empty($mentions)) {
933 $stored->saveKnownReplies($mentions);
935 $stored->saveReplies();
939 $stored->saveKnownTags($tags);
944 // Note: groups may save tags, so must be run after tags are saved
945 // to avoid errors on duplicates.
946 // Note: groups should always be set.
948 $stored->saveKnownGroups($groups);
951 $stored->saveKnownUrls($urls);
957 // Prepare inbox delivery, may be queued to background.
958 $stored->distribute();
964 static public function figureOutScope(Profile $actor, array $groups, $scope=null) {
965 if (is_null($scope)) {
966 $scope = self::defaultScope();
969 // For private streams
971 $user = $actor->getUser();
972 // FIXME: We can't do bit comparison with == (Legacy StatusNet thing. Let's keep it for now.)
973 if ($user->private_stream && ($scope == Notice::PUBLIC_SCOPE || $scope == Notice::SITE_SCOPE)) {
974 $scope |= Notice::FOLLOWER_SCOPE;
976 } catch (NoSuchUserException $e) {
977 // TODO: Not a local user, so we don't know about scope preferences... yet!
980 // Force the scope for private groups
981 foreach ($groups as $group_id) {
982 $group = User_group::staticGet('id', $group_id);
983 if ($group instanceof User_group) {
984 if ($group->force_scope) {
985 $scope |= Notice::GROUP_SCOPE;
994 function blowOnInsert($conversation = false)
996 $this->blowStream('profile:notice_ids:%d', $this->profile_id);
998 if ($this->isPublic()) {
999 $this->blowStream('public');
1000 $this->blowStream('networkpublic');
1003 self::blow('notice:list-ids:conversation:%s', $this->conversation);
1004 self::blow('conversation:notice_count:%d', $this->conversation);
1006 if ($this->isRepeat()) {
1007 // XXX: we should probably only use one of these
1008 $this->blowStream('notice:repeats:%d', $this->repeat_of);
1009 self::blow('notice:list-ids:repeat_of:%d', $this->repeat_of);
1012 $original = Notice::getKV('id', $this->repeat_of);
1014 if ($original instanceof Notice) {
1015 $originalUser = User::getKV('id', $original->profile_id);
1016 if ($originalUser instanceof User) {
1017 $this->blowStream('user:repeats_of_me:%d', $originalUser->id);
1021 $profile = Profile::getKV($this->profile_id);
1023 if ($profile instanceof Profile) {
1024 $profile->blowNoticeCount();
1027 $ptags = $this->getProfileTags();
1028 foreach ($ptags as $ptag) {
1029 $ptag->blowNoticeStreamCache();
1034 * Clear cache entries related to this notice at delete time.
1035 * Necessary to avoid breaking paging on public, profile timelines.
1037 function blowOnDelete()
1039 $this->blowOnInsert();
1041 self::blow('profile:notice_ids:%d;last', $this->profile_id);
1043 if ($this->isPublic()) {
1044 self::blow('public;last');
1045 self::blow('networkpublic;last');
1048 self::blow('fave:by_notice', $this->id);
1050 if ($this->conversation) {
1051 // In case we're the first, will need to calc a new root.
1052 self::blow('notice:conversation_root:%d', $this->conversation);
1055 $ptags = $this->getProfileTags();
1056 foreach ($ptags as $ptag) {
1057 $ptag->blowNoticeStreamCache(true);
1061 function blowStream()
1063 $c = self::memcache();
1069 $args = func_get_args();
1071 $format = array_shift($args);
1073 $keyPart = vsprintf($format, $args);
1075 $cacheKey = Cache::key($keyPart);
1077 $c->delete($cacheKey);
1079 // delete the "last" stream, too, if this notice is
1080 // older than the top of that stream
1082 $lastKey = $cacheKey.';last';
1084 $lastStr = $c->get($lastKey);
1086 if ($lastStr !== false) {
1087 $window = explode(',', $lastStr);
1088 $lastID = $window[0];
1089 $lastNotice = Notice::getKV('id', $lastID);
1090 if (!$lastNotice instanceof Notice // just weird
1091 || strtotime($lastNotice->created) >= strtotime($this->created)) {
1092 $c->delete($lastKey);
1097 /** save all urls in the notice to the db
1099 * follow redirects and save all available file information
1100 * (mimetype, date, size, oembed, etc.)
1104 function saveUrls() {
1105 if (common_config('attachments', 'process_links')) {
1106 common_replace_urls_callback($this->content, array($this, 'saveUrl'), $this->id);
1111 * Save the given URLs as related links/attachments to the db
1113 * follow redirects and save all available file information
1114 * (mimetype, date, size, oembed, etc.)
1118 function saveKnownUrls(array $urls)
1120 if (common_config('attachments', 'process_links')) {
1121 // @fixme validation?
1122 foreach (array_unique($urls) as $url) {
1124 File::processNew($url, $this->id);
1125 } catch (ServerException $e) {
1126 // Could not save URL. Log it?
1135 function saveUrl($url, $notice_id) {
1137 File::processNew($url, $notice_id);
1138 } catch (ServerException $e) {
1139 // Could not save URL. Log it?
1143 static function checkDupes($profile_id, $content) {
1144 $profile = Profile::getKV($profile_id);
1145 if (!$profile instanceof Profile) {
1148 $notice = $profile->getNotices(0, CachingNoticeStream::CACHE_WINDOW);
1149 if (!empty($notice)) {
1151 while ($notice->fetch()) {
1152 if (time() - strtotime($notice->created) >= common_config('site', 'dupelimit')) {
1154 } else if ($notice->content == $content) {
1159 // If we get here, oldest item in cache window is not
1160 // old enough for dupe limit; do direct check against DB
1161 $notice = new Notice();
1162 $notice->profile_id = $profile_id;
1163 $notice->content = $content;
1164 $threshold = common_sql_date(time() - common_config('site', 'dupelimit'));
1165 $notice->whereAdd(sprintf("created > '%s'", $notice->escape($threshold)));
1167 $cnt = $notice->count();
1171 static function checkEditThrottle($profile_id) {
1172 $profile = Profile::getKV($profile_id);
1173 if (!$profile instanceof Profile) {
1176 // Get the Nth notice
1177 $notice = $profile->getNotices(common_config('throttle', 'count') - 1, 1);
1178 if ($notice && $notice->fetch()) {
1179 // If the Nth notice was posted less than timespan seconds ago
1180 if (time() - strtotime($notice->created) <= common_config('throttle', 'timespan')) {
1185 // Either not N notices in the stream, OR the Nth was not posted within timespan seconds
1189 protected $_attachments = array();
1191 function attachments() {
1192 if (isset($this->_attachments[$this->id])) {
1193 return $this->_attachments[$this->id];
1196 $f2ps = File_to_post::listGet('post_id', array($this->id));
1200 foreach ($f2ps[$this->id] as $f2p) {
1201 $ids[] = $f2p->file_id;
1204 $files = File::multiGet('id', $ids);
1206 $this->_attachments[$this->id] = $files->fetchAll();
1208 return $this->_attachments[$this->id];
1211 function _setAttachments($attachments)
1213 $this->_attachments[$this->id] = $attachments;
1216 function publicStream($offset=0, $limit=20, $since_id=0, $max_id=0)
1218 $stream = new PublicNoticeStream();
1219 return $stream->getNotices($offset, $limit, $since_id, $max_id);
1223 function conversationStream($id, $offset=0, $limit=20, $since_id=0, $max_id=0)
1225 $stream = new ConversationNoticeStream($id);
1227 return $stream->getNotices($offset, $limit, $since_id, $max_id);
1231 * Is this notice part of an active conversation?
1233 * @return boolean true if other messages exist in the same
1234 * conversation, false if this is the only one
1236 function hasConversation()
1238 if (!empty($this->conversation)) {
1239 $conversation = Notice::conversationStream(
1240 $this->conversation,
1245 if ($conversation->N > 0) {
1253 * Grab the earliest notice from this conversation.
1255 * @return Notice or null
1257 function conversationRoot($profile=-1)
1259 // XXX: can this happen?
1261 if (empty($this->conversation)) {
1265 // Get the current profile if not specified
1267 if (is_int($profile) && $profile == -1) {
1268 $profile = Profile::current();
1271 // If this notice is out of scope, no root for you!
1273 if (!$this->inScope($profile)) {
1277 // If this isn't a reply to anything, then it's its own
1278 // root if it's the earliest notice in the conversation:
1280 if (empty($this->reply_to)) {
1282 $root->conversation = $this->conversation;
1283 $root->orderBy('notice.created ASC');
1290 if (is_null($profile)) {
1291 $keypart = sprintf('notice:conversation_root:%d:null', $this->id);
1293 $keypart = sprintf('notice:conversation_root:%d:%d',
1298 $root = self::cacheGet($keypart);
1300 if ($root !== false && $root->inScope($profile)) {
1307 $parent = $last->getParent();
1308 if ($parent->inScope($profile)) {
1312 } catch (Exception $e) {
1313 // Latest notice has no parent
1315 // No parent, or parent out of scope
1320 self::cacheSet($keypart, $root);
1326 * Pull up a full list of local recipients who will be getting
1327 * this notice in their inbox. Results will be cached, so don't
1328 * change the input data wily-nilly!
1330 * @param array $groups optional list of Group objects;
1331 * if left empty, will be loaded from group_inbox records
1332 * @param array $recipient optional list of reply profile ids
1333 * if left empty, will be loaded from reply records
1334 * @return array associating recipient user IDs with an inbox source constant
1336 function whoGets(array $groups=null, array $recipients=null)
1338 $c = self::memcache();
1341 $ni = $c->get(Cache::key('notice:who_gets:'.$this->id));
1342 if ($ni !== false) {
1347 if (is_null($recipients)) {
1348 $recipients = $this->getReplies();
1353 // Give plugins a chance to add folks in at start...
1354 if (Event::handle('StartNoticeWhoGets', array($this, &$ni))) {
1356 $users = $this->getSubscribedUsers();
1357 foreach ($users as $id) {
1358 $ni[$id] = NOTICE_INBOX_SOURCE_SUB;
1361 if (is_null($groups)) {
1362 $groups = $this->getGroups();
1364 foreach ($groups as $group) {
1365 $users = $group->getUserMembers();
1366 foreach ($users as $id) {
1367 if (!array_key_exists($id, $ni)) {
1368 $ni[$id] = NOTICE_INBOX_SOURCE_GROUP;
1373 $ptAtts = $this->getAttentionsFromProfileTags();
1374 foreach ($ptAtts as $key=>$val) {
1375 if (!array_key_exists($key, $ni)) {
1380 foreach ($recipients as $recipient) {
1381 if (!array_key_exists($recipient, $ni)) {
1382 $ni[$recipient] = NOTICE_INBOX_SOURCE_REPLY;
1386 // Exclude any deleted, non-local, or blocking recipients.
1387 $profile = $this->getProfile();
1388 $originalProfile = null;
1389 if ($this->isRepeat()) {
1390 // Check blocks against the original notice's poster as well.
1391 $original = Notice::getKV('id', $this->repeat_of);
1392 if ($original instanceof Notice) {
1393 $originalProfile = $original->getProfile();
1397 foreach ($ni as $id => $source) {
1399 $user = User::getKV('id', $id);
1400 if (!$user instanceof User ||
1401 $user->hasBlocked($profile) ||
1402 ($originalProfile && $user->hasBlocked($originalProfile))) {
1405 } catch (UserNoProfileException $e) {
1406 // User doesn't have a profile; invalid; skip them.
1411 // Give plugins a chance to filter out...
1412 Event::handle('EndNoticeWhoGets', array($this, &$ni));
1416 // XXX: pack this data better
1417 $c->set(Cache::key('notice:who_gets:'.$this->id), $ni);
1423 function getSubscribedUsers()
1427 if(common_config('db','quote_identifiers'))
1428 $user_table = '"user"';
1429 else $user_table = 'user';
1433 'FROM '. $user_table .' JOIN subscription '.
1434 'ON '. $user_table .'.id = subscription.subscriber ' .
1435 'WHERE subscription.subscribed = %d ';
1437 $user->query(sprintf($qry, $this->profile_id));
1441 while ($user->fetch()) {
1450 function getProfileTags()
1452 $profile = $this->getProfile();
1453 $list = $profile->getOtherTags($profile);
1456 while($list->fetch()) {
1457 $ptags[] = clone($list);
1463 public function getAttentionsFromProfileTags()
1466 $ptags = $this->getProfileTags();
1467 foreach ($ptags as $ptag) {
1468 $users = $ptag->getUserSubscribers();
1469 foreach ($users as $id) {
1470 $ni[$id] = NOTICE_INBOX_SOURCE_PROFILE_TAG;
1477 * Record this notice to the given group inboxes for delivery.
1478 * Overrides the regular parsing of !group markup.
1480 * @param string $group_ids
1481 * @fixme might prefer URIs as identifiers, as for replies?
1482 * best with generalizations on user_group to support
1483 * remote groups better.
1485 function saveKnownGroups($group_ids)
1487 if (!is_array($group_ids)) {
1488 // TRANS: Server exception thrown when no array is provided to the method saveKnownGroups().
1489 throw new ServerException(_('Bad type provided to saveKnownGroups.'));
1493 foreach (array_unique($group_ids) as $id) {
1494 $group = User_group::getKV('id', $id);
1495 if ($group instanceof User_group) {
1496 common_log(LOG_DEBUG, "Local delivery to group id $id, $group->nickname");
1497 $result = $this->addToGroupInbox($group);
1499 common_log_db_error($gi, 'INSERT', __FILE__);
1502 if (common_config('group', 'addtag')) {
1503 // we automatically add a tag for every group name, too
1505 $tag = Notice_tag::pkeyGet(array('tag' => common_canonical_tag($group->nickname),
1506 'notice_id' => $this->id));
1508 if (is_null($tag)) {
1509 $this->saveTag($group->nickname);
1513 $groups[] = clone($group);
1515 common_log(LOG_ERR, "Local delivery to group id $id skipped, doesn't exist");
1522 function addToGroupInbox(User_group $group)
1524 $gi = Group_inbox::pkeyGet(array('group_id' => $group->id,
1525 'notice_id' => $this->id));
1527 if (!$gi instanceof Group_inbox) {
1529 $gi = new Group_inbox();
1531 $gi->group_id = $group->id;
1532 $gi->notice_id = $this->id;
1533 $gi->created = $this->created;
1535 $result = $gi->insert();
1538 common_log_db_error($gi, 'INSERT', __FILE__);
1539 // TRANS: Server exception thrown when an update for a group inbox fails.
1540 throw new ServerException(_('Problem saving group inbox.'));
1543 self::blow('user_group:notice_ids:%d', $gi->group_id);
1550 * Save reply records indicating that this notice needs to be
1551 * delivered to the local users with the given URIs.
1553 * Since this is expected to be used when saving foreign-sourced
1554 * messages, we won't deliver to any remote targets as that's the
1555 * source service's responsibility.
1557 * Mail notifications etc will be handled later.
1559 * @param array $uris Array of unique identifier URIs for recipients
1561 function saveKnownReplies(array $uris)
1567 $sender = Profile::getKV($this->profile_id);
1569 foreach (array_unique($uris) as $uri) {
1571 $profile = Profile::fromUri($uri);
1572 } catch (UnknownUriException $e) {
1573 common_log(LOG_WARNING, "Unable to determine profile for URI '$uri'");
1577 if ($profile->hasBlocked($sender)) {
1578 common_log(LOG_INFO, "Not saving reply to profile {$profile->id} ($uri) from sender {$sender->id} because of a block.");
1582 $this->saveReply($profile->id);
1583 self::blow('reply:stream:%d', $profile->id);
1590 * Pull @-replies from this message's content in StatusNet markup format
1591 * and save reply records indicating that this message needs to be
1592 * delivered to those users.
1594 * Mail notifications to local profiles will be sent later.
1596 * @return array of integer profile IDs
1599 function saveReplies()
1601 // Don't save reply data for repeats
1603 if ($this->isRepeat()) {
1607 $sender = $this->getProfile();
1611 // If it's a reply, save for the replied-to author
1613 $parent = $this->getParent();
1614 $parentauthor = $parent->getProfile();
1615 $this->saveReply($parentauthor->id);
1616 $replied[$parentauthor->id] = 1;
1617 self::blow('reply:stream:%d', $parentauthor->id);
1618 } catch (Exception $e) {
1619 // Not a reply, since it has no parent!
1622 // @todo ideally this parser information would only
1623 // be calculated once.
1625 $mentions = common_find_mentions($this->content, $this);
1627 // store replied only for first @ (what user/notice what the reply directed,
1628 // we assume first @ is it)
1630 foreach ($mentions as $mention) {
1632 foreach ($mention['mentioned'] as $mentioned) {
1634 // skip if they're already covered
1636 if (!empty($replied[$mentioned->id])) {
1640 // Don't save replies from blocked profile to local user
1642 $mentioned_user = User::getKV('id', $mentioned->id);
1643 if ($mentioned_user instanceof User && $mentioned_user->hasBlocked($sender)) {
1647 $this->saveReply($mentioned->id);
1648 $replied[$mentioned->id] = 1;
1649 self::blow('reply:stream:%d', $mentioned->id);
1653 $recipientIds = array_keys($replied);
1655 return $recipientIds;
1658 function saveReply($profileId)
1660 $reply = new Reply();
1662 $reply->notice_id = $this->id;
1663 $reply->profile_id = $profileId;
1664 $reply->modified = $this->created;
1671 protected $_replies = array();
1674 * Pull the complete list of @-reply targets for this notice.
1676 * @return array of integer profile ids
1678 function getReplies()
1680 if (isset($this->_replies[$this->id])) {
1681 return $this->_replies[$this->id];
1684 $replyMap = Reply::listGet('notice_id', array($this->id));
1688 foreach ($replyMap[$this->id] as $reply) {
1689 $ids[] = $reply->profile_id;
1692 $this->_setReplies($ids);
1697 function _setReplies(array $replies)
1699 $this->_replies[$this->id] = $replies;
1703 * Pull the complete list of @-reply targets for this notice.
1705 * @return array of Profiles
1707 function getReplyProfiles()
1709 $ids = $this->getReplies();
1711 $profiles = Profile::multiGet('id', $ids);
1713 return $profiles->fetchAll();
1717 * Send e-mail notifications to local @-reply targets.
1719 * Replies must already have been saved; this is expected to be run
1720 * from the distrib queue handler.
1722 function sendReplyNotifications()
1724 // Don't send reply notifications for repeats
1726 if ($this->isRepeat()) {
1730 $recipientIds = $this->getReplies();
1731 if (Event::handle('StartNotifyMentioned', array($this, &$recipientIds))) {
1732 require_once INSTALLDIR.'/lib/mail.php';
1734 foreach ($recipientIds as $recipientId) {
1735 $user = User::getKV('id', $recipientId);
1736 if ($user instanceof User) {
1737 mail_notify_attn($user, $this);
1740 Event::handle('EndNotifyMentioned', array($this, $recipientIds));
1745 * Pull list of groups this notice needs to be delivered to,
1746 * as previously recorded by saveKnownGroups().
1748 * @return array of Group objects
1751 protected $_groups = array();
1753 function getGroups()
1755 // Don't save groups for repeats
1757 if (!empty($this->repeat_of)) {
1761 if (isset($this->_groups[$this->id])) {
1762 return $this->_groups[$this->id];
1765 $gis = Group_inbox::listGet('notice_id', array($this->id));
1769 foreach ($gis[$this->id] as $gi)
1771 $ids[] = $gi->group_id;
1774 $groups = User_group::multiGet('id', $ids);
1775 $this->_setGroups($groups->fetchAll());
1776 return $this->_groups[$this->id];
1779 function _setGroups(array $groups)
1781 $this->_groups[$this->id] = $groups;
1785 * Convert a notice into an activity for export.
1787 * @param Profile $scoped The currently logged in/scoped profile
1789 * @return Activity activity object representing this Notice.
1792 function asActivity(Profile $scoped=null)
1794 $act = self::cacheGet(Cache::codeKey('notice:as-activity:'.$this->id));
1796 if ($act instanceof Activity) {
1799 $act = new Activity();
1801 if (Event::handle('StartNoticeAsActivity', array($this, $act, $scoped))) {
1803 $act->id = $this->uri;
1804 $act->time = strtotime($this->created);
1806 $act->link = $this->getUrl();
1807 } catch (InvalidUrlException $e) {
1808 // The notice is probably a share or similar, which don't
1809 // have a representational URL of their own.
1811 $act->content = common_xml_safe_str($this->rendered);
1813 $profile = $this->getProfile();
1815 $act->actor = $profile->asActivityObject();
1816 $act->actor->extra[] = $profile->profileInfo($scoped);
1818 $act->verb = $this->verb;
1820 if ($this->repeat_of) {
1821 $repeated = Notice::getKV('id', $this->repeat_of);
1822 if ($repeated instanceof Notice) {
1823 // TRANS: A repeat activity's title. %1$s is repeater's nickname
1824 // and %2$s is the repeated user's nickname.
1825 $act->title = sprintf(_('%1$s repeated a notice by %2$s'),
1826 $this->getProfile()->getNickname(),
1827 $repeated->getProfile()->getNickname());
1828 $act->objects[] = $repeated->asActivity($scoped);
1831 $act->objects[] = $this->asActivityObject();
1834 // XXX: should this be handled by default processing for object entry?
1838 $tags = $this->getTags();
1840 foreach ($tags as $tag) {
1841 $cat = new AtomCategory();
1844 $act->categories[] = $cat;
1848 // XXX: use Atom Media and/or File activity objects instead
1850 $attachments = $this->attachments();
1852 foreach ($attachments as $attachment) {
1853 // Save local attachments
1854 if (!empty($attachment->filename)) {
1855 $act->attachments[] = ActivityObject::fromFile($attachment);
1859 $ctx = new ActivityContext();
1862 $reply = $this->getParent();
1863 $ctx->replyToID = $reply->getUri();
1864 $ctx->replyToUrl = $reply->getUrl();
1865 } catch (Exception $e) {
1866 // This is not a reply to something
1869 $ctx->location = $this->getLocation();
1873 if (!empty($this->conversation)) {
1874 $conv = Conversation::getKV('id', $this->conversation);
1875 if ($conv instanceof Conversation) {
1876 $ctx->conversation = $conv->uri;
1880 $reply_ids = $this->getReplies();
1882 foreach ($reply_ids as $id) {
1883 $rprofile = Profile::getKV('id', $id);
1884 if ($rprofile instanceof Profile) {
1885 $ctx->attention[$rprofile->getUri()] = ActivityObject::PERSON;
1889 $groups = $this->getGroups();
1891 foreach ($groups as $group) {
1892 $ctx->attention[$group->getUri()] = ActivityObject::GROUP;
1895 switch ($this->scope) {
1896 case Notice::PUBLIC_SCOPE:
1897 $ctx->attention[ActivityContext::ATTN_PUBLIC] = ActivityObject::COLLECTION;
1899 case Notice::FOLLOWER_SCOPE:
1900 $surl = common_local_url("subscribers", array('nickname' => $profile->nickname));
1901 $ctx->attention[$surl] = ActivityObject::COLLECTION;
1905 $act->context = $ctx;
1907 $source = $this->getSource();
1909 if ($source instanceof Notice_source) {
1910 $act->generator = ActivityObject::fromNoticeSource($source);
1915 $atom_feed = $profile->getAtomFeed();
1917 if (!empty($atom_feed)) {
1919 $act->source = new ActivitySource();
1921 // XXX: we should store the actual feed ID
1923 $act->source->id = $atom_feed;
1925 // XXX: we should store the actual feed title
1927 $act->source->title = $profile->getBestName();
1929 $act->source->links['alternate'] = $profile->profileurl;
1930 $act->source->links['self'] = $atom_feed;
1932 $act->source->icon = $profile->avatarUrl(AVATAR_PROFILE_SIZE);
1934 $notice = $profile->getCurrentNotice();
1936 if ($notice instanceof Notice) {
1937 $act->source->updated = self::utcDate($notice->created);
1940 $user = User::getKV('id', $profile->id);
1942 if ($user instanceof User) {
1943 $act->source->links['license'] = common_config('license', 'url');
1947 if ($this->isLocal()) {
1948 $act->selfLink = common_local_url('ApiStatusesShow', array('id' => $this->id,
1949 'format' => 'atom'));
1950 $act->editLink = $act->selfLink;
1953 Event::handle('EndNoticeAsActivity', array($this, $act, $scoped));
1956 self::cacheSet(Cache::codeKey('notice:as-activity:'.$this->id), $act);
1961 // This has gotten way too long. Needs to be sliced up into functional bits
1962 // or ideally exported to a utility class.
1964 function asAtomEntry($namespace=false,
1967 Profile $scoped=null)
1969 $act = $this->asActivity($scoped);
1970 $act->extra[] = $this->noticeInfo($scoped);
1971 return $act->asString($namespace, $author, $source);
1975 * Extra notice info for atom entries
1977 * Clients use some extra notice info in the atom stream.
1978 * This gives it to them.
1980 * @param Profile $scoped The currently logged in/scoped profile
1982 * @return array representation of <statusnet:notice_info> element
1985 function noticeInfo(Profile $scoped=null)
1987 // local notice ID (useful to clients for ordering)
1989 $noticeInfoAttr = array('local_id' => $this->id);
1993 $ns = $this->getSource();
1995 if ($ns instanceof Notice_source) {
1996 $noticeInfoAttr['source'] = $ns->code;
1997 if (!empty($ns->url)) {
1998 $noticeInfoAttr['source_link'] = $ns->url;
1999 if (!empty($ns->name)) {
2000 $noticeInfoAttr['source'] = '<a href="'
2001 . htmlspecialchars($ns->url)
2002 . '" rel="nofollow">'
2003 . htmlspecialchars($ns->name)
2009 // favorite and repeated
2011 if ($scoped instanceof Profile) {
2012 $noticeInfoAttr['repeated'] = ($scoped->hasRepeated($this)) ? "true" : "false";
2015 if (!empty($this->repeat_of)) {
2016 $noticeInfoAttr['repeat_of'] = $this->repeat_of;
2019 Event::handle('StatusNetApiNoticeInfo', array($this, &$noticeInfoAttr, $scoped));
2021 return array('statusnet:notice_info', $noticeInfoAttr, null);
2025 * Returns an XML string fragment with a reference to a notice as an
2026 * Activity Streams noun object with the given element type.
2028 * Assumes that 'activity' namespace has been previously defined.
2030 * @param string $element one of 'subject', 'object', 'target'
2034 function asActivityNoun($element)
2036 $noun = $this->asActivityObject();
2037 return $noun->asString('activity:' . $element);
2040 public function asActivityObject()
2042 $object = new ActivityObject();
2044 if (Event::handle('StartActivityObjectFromNotice', array($this, &$object))) {
2045 $object->type = $this->object_type ?: ActivityObject::NOTE;
2046 $object->id = $this->getUri();
2047 $object->title = sprintf('New %1$s by %2$s', ActivityObject::canonicalType($object->type), $this->getProfile()->getNickname());
2048 $object->content = $this->rendered;
2049 $object->link = $this->getUrl();
2051 $object->extra[] = array('status_net', array('notice_id' => $this->id));
2053 Event::handle('EndActivityObjectFromNotice', array($this, &$object));
2060 * Determine which notice, if any, a new notice is in reply to.
2062 * For conversation tracking, we try to see where this notice fits
2063 * in the tree. Beware that this may very well give false positives
2064 * and add replies to wrong threads (if there have been newer posts
2065 * by the same user as we're replying to).
2067 * @param Profile $sender Author profile
2068 * @param string $content Final notice content
2070 * @return integer ID of replied-to notice, or null for not a reply.
2073 static function getInlineReplyTo(Profile $sender, $content)
2075 // Is there an initial @ or T?
2076 if (preg_match('/^T ([A-Z0-9]{1,64}) /', $content, $match)
2077 || preg_match('/^@([a-z0-9]{1,64})\s+/', $content, $match)) {
2078 $nickname = common_canonical_nickname($match[1]);
2083 // Figure out who that is.
2084 $recipient = common_relative_profile($sender, $nickname, common_sql_now());
2086 if ($recipient instanceof Profile) {
2087 // Get their last notice
2088 $last = $recipient->getCurrentNotice();
2089 if ($last instanceof Notice) {
2092 // Maybe in the future we want to handle something else below
2093 // so don't return getCurrentNotice() immediately.
2099 static function maxContent()
2101 $contentlimit = common_config('notice', 'contentlimit');
2102 // null => use global limit (distinct from 0!)
2103 if (is_null($contentlimit)) {
2104 $contentlimit = common_config('site', 'textlimit');
2106 return $contentlimit;
2109 static function contentTooLong($content)
2111 $contentlimit = self::maxContent();
2112 return ($contentlimit > 0 && !empty($content) && (mb_strlen($content) > $contentlimit));
2115 function getLocation()
2119 if (!empty($this->location_id) && !empty($this->location_ns)) {
2120 $location = Location::fromId($this->location_id, $this->location_ns);
2123 if (is_null($location)) { // no ID, or Location::fromId() failed
2124 if (!empty($this->lat) && !empty($this->lon)) {
2125 $location = Location::fromLatLon($this->lat, $this->lon);
2133 * Convenience function for posting a repeat of an existing message.
2135 * @param Profile $repeater Profile which is doing the repeat
2136 * @param string $source: posting source key, eg 'web', 'api', etc
2139 * @throws Exception on failure or permission problems
2141 function repeat(Profile $repeater, $source)
2143 $author = $this->getProfile();
2145 // TRANS: Message used to repeat a notice. RT is the abbreviation of 'retweet'.
2146 // TRANS: %1$s is the repeated user's name, %2$s is the repeated notice.
2147 $content = sprintf(_('RT @%1$s %2$s'),
2148 $author->getNickname(),
2151 $maxlen = self::maxContent();
2152 if ($maxlen > 0 && mb_strlen($content) > $maxlen) {
2153 // Web interface and current Twitter API clients will
2154 // pull the original notice's text, but some older
2155 // clients and RSS/Atom feeds will see this trimmed text.
2157 // Unfortunately this is likely to lose tags or URLs
2158 // at the end of long notices.
2159 $content = mb_substr($content, 0, $maxlen - 4) . ' ...';
2163 // Scope is same as this one's
2164 return self::saveNew($repeater->id,
2167 array('repeat_of' => $this->id,
2168 'scope' => $this->scope));
2171 // These are supposed to be in chron order!
2173 function repeatStream($limit=100)
2175 $cache = Cache::instance();
2177 if (empty($cache)) {
2178 $ids = $this->_repeatStreamDirect($limit);
2180 $idstr = $cache->get(Cache::key('notice:repeats:'.$this->id));
2181 if ($idstr !== false) {
2182 if (empty($idstr)) {
2185 $ids = explode(',', $idstr);
2188 $ids = $this->_repeatStreamDirect(100);
2189 $cache->set(Cache::key('notice:repeats:'.$this->id), implode(',', $ids));
2192 // We do a max of 100, so slice down to limit
2193 $ids = array_slice($ids, 0, $limit);
2197 return NoticeStream::getStreamByIds($ids);
2200 function _repeatStreamDirect($limit)
2202 $notice = new Notice();
2204 $notice->selectAdd(); // clears it
2205 $notice->selectAdd('id');
2207 $notice->repeat_of = $this->id;
2209 $notice->orderBy('created, id'); // NB: asc!
2211 if (!is_null($limit)) {
2212 $notice->limit(0, $limit);
2215 return $notice->fetchAll('id');
2218 function locationOptions($lat, $lon, $location_id, $location_ns, $profile = null)
2222 if (!empty($location_id) && !empty($location_ns)) {
2223 $options['location_id'] = $location_id;
2224 $options['location_ns'] = $location_ns;
2226 $location = Location::fromId($location_id, $location_ns);
2228 if ($location instanceof Location) {
2229 $options['lat'] = $location->lat;
2230 $options['lon'] = $location->lon;
2233 } else if (!empty($lat) && !empty($lon)) {
2234 $options['lat'] = $lat;
2235 $options['lon'] = $lon;
2237 $location = Location::fromLatLon($lat, $lon);
2239 if ($location instanceof Location) {
2240 $options['location_id'] = $location->location_id;
2241 $options['location_ns'] = $location->location_ns;
2243 } else if (!empty($profile)) {
2244 if (isset($profile->lat) && isset($profile->lon)) {
2245 $options['lat'] = $profile->lat;
2246 $options['lon'] = $profile->lon;
2249 if (isset($profile->location_id) && isset($profile->location_ns)) {
2250 $options['location_id'] = $profile->location_id;
2251 $options['location_ns'] = $profile->location_ns;
2258 function clearAttentions()
2260 $att = new Attention();
2261 $att->notice_id = $this->getID();
2264 while ($att->fetch()) {
2265 // Can't do delete() on the object directly since it won't remove all of it
2266 $other = clone($att);
2272 function clearReplies()
2274 $replyNotice = new Notice();
2275 $replyNotice->reply_to = $this->id;
2277 //Null any notices that are replies to this notice
2279 if ($replyNotice->find()) {
2280 while ($replyNotice->fetch()) {
2281 $orig = clone($replyNotice);
2282 $replyNotice->reply_to = null;
2283 $replyNotice->update($orig);
2289 $reply = new Reply();
2290 $reply->notice_id = $this->id;
2292 if ($reply->find()) {
2293 while($reply->fetch()) {
2294 self::blow('reply:stream:%d', $reply->profile_id);
2302 function clearFiles()
2304 $f2p = new File_to_post();
2306 $f2p->post_id = $this->id;
2309 while ($f2p->fetch()) {
2313 // FIXME: decide whether to delete File objects
2314 // ...and related (actual) files
2317 function clearRepeats()
2319 $repeatNotice = new Notice();
2320 $repeatNotice->repeat_of = $this->id;
2322 //Null any notices that are repeats of this notice
2324 if ($repeatNotice->find()) {
2325 while ($repeatNotice->fetch()) {
2326 $orig = clone($repeatNotice);
2327 $repeatNotice->repeat_of = null;
2328 $repeatNotice->update($orig);
2333 function clearTags()
2335 $tag = new Notice_tag();
2336 $tag->notice_id = $this->id;
2339 while ($tag->fetch()) {
2340 self::blow('profile:notice_ids_tagged:%d:%s', $this->profile_id, Cache::keyize($tag->tag));
2341 self::blow('profile:notice_ids_tagged:%d:%s;last', $this->profile_id, Cache::keyize($tag->tag));
2342 self::blow('notice_tag:notice_ids:%s', Cache::keyize($tag->tag));
2343 self::blow('notice_tag:notice_ids:%s;last', Cache::keyize($tag->tag));
2351 function clearGroupInboxes()
2353 $gi = new Group_inbox();
2355 $gi->notice_id = $this->id;
2358 while ($gi->fetch()) {
2359 self::blow('user_group:notice_ids:%d', $gi->group_id);
2367 function distribute()
2369 // We always insert for the author so they don't
2371 Event::handle('StartNoticeDistribute', array($this));
2373 // If there's a failure, we want to _force_
2374 // distribution at this point.
2376 $qm = QueueManager::get();
2377 $qm->enqueue($this, 'distrib');
2378 } catch (Exception $e) {
2379 // If the exception isn't transient, this
2380 // may throw more exceptions as DQH does
2381 // its own enqueueing. So, we ignore them!
2383 $handler = new DistribQueueHandler();
2384 $handler->handle($this);
2385 } catch (Exception $e) {
2386 common_log(LOG_ERR, "emergency redistribution resulted in " . $e->getMessage());
2388 // Re-throw so somebody smarter can handle it.
2395 $result = parent::insert();
2397 if ($result === false) {
2398 common_log_db_error($this, 'INSERT', __FILE__);
2399 // TRANS: Server exception thrown when a stored object entry cannot be saved.
2400 throw new ServerException('Could not save Notice');
2403 // Profile::hasRepeated() abuses pkeyGet(), so we
2404 // have to clear manually
2405 if (!empty($this->repeat_of)) {
2406 $c = self::memcache();
2408 $ck = self::multicacheKey('Notice',
2409 array('profile_id' => $this->profile_id,
2410 'repeat_of' => $this->repeat_of));
2415 // Update possibly ID-dependent columns: URI, conversation
2416 // (now that INSERT has added the notice's local id)
2417 $orig = clone($this);
2420 // We can only get here if it's a local notice, since remote notices
2421 // should've bailed out earlier due to lacking a URI.
2422 if (empty($this->uri)) {
2423 $this->uri = sprintf('%s%s=%d:%s=%s',
2425 'noticeId', $this->id,
2426 'objectType', $this->get_object_type(true));
2430 if ($changed && $this->update($orig) === false) {
2431 common_log_db_error($notice, 'UPDATE', __FILE__);
2432 // TRANS: Server exception thrown when a notice cannot be updated.
2433 throw new ServerException(_('Problem saving notice.'));
2436 $this->blowOnInsert();
2442 * Get the source of the notice
2444 * @return Notice_source $ns A notice source object. 'code' is the only attribute
2445 * guaranteed to be populated.
2447 function getSource()
2449 if (empty($this->source)) {
2453 $ns = new Notice_source();
2454 switch ($this->source) {
2461 $ns->code = $this->source;
2464 $ns = Notice_source::getKV($this->source);
2466 $ns = new Notice_source();
2467 $ns->code = $this->source;
2468 $app = Oauth_application::getKV('name', $this->source);
2470 $ns->name = $app->name;
2471 $ns->url = $app->source_url;
2481 * Determine whether the notice was locally created
2483 * @return boolean locality
2486 public function isLocal()
2488 return ($this->is_local == Notice::LOCAL_PUBLIC ||
2489 $this->is_local == Notice::LOCAL_NONPUBLIC);
2492 public function isRepeat()
2494 return !empty($this->repeat_of);
2498 * Get the list of hash tags saved with this notice.
2500 * @return array of strings
2502 public function getTags()
2506 $keypart = sprintf('notice:tags:%d', $this->id);
2508 $tagstr = self::cacheGet($keypart);
2510 if ($tagstr !== false) {
2511 $tags = explode(',', $tagstr);
2513 $tag = new Notice_tag();
2514 $tag->notice_id = $this->id;
2516 while ($tag->fetch()) {
2517 $tags[] = $tag->tag;
2520 self::cacheSet($keypart, implode(',', $tags));
2526 static private function utcDate($dt)
2528 $dateStr = date('d F Y H:i:s', strtotime($dt));
2529 $d = new DateTime($dateStr, new DateTimeZone('UTC'));
2530 return $d->format(DATE_W3C);
2534 * Look up the creation timestamp for a given notice ID, even
2535 * if it's been deleted.
2538 * @return mixed string recorded creation timestamp, or false if can't be found
2540 public static function getAsTimestamp($id)
2546 $notice = Notice::getKV('id', $id);
2548 return $notice->created;
2551 $deleted = Deleted_notice::getKV('id', $id);
2553 return $deleted->created;
2560 * Build an SQL 'where' fragment for timestamp-based sorting from a since_id
2561 * parameter, matching notices posted after the given one (exclusive).
2563 * If the referenced notice can't be found, will return false.
2566 * @param string $idField
2567 * @param string $createdField
2568 * @return mixed string or false if no match
2570 public static function whereSinceId($id, $idField='id', $createdField='created')
2572 $since = Notice::getAsTimestamp($id);
2574 return sprintf("($createdField = '%s' and $idField > %d) or ($createdField > '%s')", $since, $id, $since);
2580 * Build an SQL 'where' fragment for timestamp-based sorting from a since_id
2581 * parameter, matching notices posted after the given one (exclusive), and
2582 * if necessary add it to the data object's query.
2584 * @param DB_DataObject $obj
2586 * @param string $idField
2587 * @param string $createdField
2588 * @return mixed string or false if no match
2590 public static function addWhereSinceId(DB_DataObject $obj, $id, $idField='id', $createdField='created')
2592 $since = self::whereSinceId($id, $idField, $createdField);
2594 $obj->whereAdd($since);
2599 * Build an SQL 'where' fragment for timestamp-based sorting from a max_id
2600 * parameter, matching notices posted before the given one (inclusive).
2602 * If the referenced notice can't be found, will return false.
2605 * @param string $idField
2606 * @param string $createdField
2607 * @return mixed string or false if no match
2609 public static function whereMaxId($id, $idField='id', $createdField='created')
2611 $max = Notice::getAsTimestamp($id);
2613 return sprintf("($createdField < '%s') or ($createdField = '%s' and $idField <= %d)", $max, $max, $id);
2619 * Build an SQL 'where' fragment for timestamp-based sorting from a max_id
2620 * parameter, matching notices posted before the given one (inclusive), and
2621 * if necessary add it to the data object's query.
2623 * @param DB_DataObject $obj
2625 * @param string $idField
2626 * @param string $createdField
2627 * @return mixed string or false if no match
2629 public static function addWhereMaxId(DB_DataObject $obj, $id, $idField='id', $createdField='created')
2631 $max = self::whereMaxId($id, $idField, $createdField);
2633 $obj->whereAdd($max);
2639 return (($this->is_local != Notice::LOCAL_NONPUBLIC) &&
2640 ($this->is_local != Notice::GATEWAY));
2644 * Check that the given profile is allowed to read, respond to, or otherwise
2645 * act on this notice.
2647 * The $scope member is a bitmask of scopes, representing a logical AND of the
2648 * scope requirement. So, 0x03 (Notice::ADDRESSEE_SCOPE | Notice::SITE_SCOPE) means
2649 * "only visible to people who are mentioned in the notice AND are users on this site."
2650 * Users on the site who are not mentioned in the notice will not be able to see the
2653 * @param Profile $profile The profile to check; pass null to check for public/unauthenticated users.
2655 * @return boolean whether the profile is in the notice's scope
2657 function inScope(Profile $profile=null)
2659 if (is_null($profile)) {
2660 $keypart = sprintf('notice:in-scope-for:%d:null', $this->id);
2662 $keypart = sprintf('notice:in-scope-for:%d:%d', $this->id, $profile->id);
2665 $result = self::cacheGet($keypart);
2667 if ($result === false) {
2669 if (Event::handle('StartNoticeInScope', array($this, $profile, &$bResult))) {
2670 $bResult = $this->_inScope($profile);
2671 Event::handle('EndNoticeInScope', array($this, $profile, &$bResult));
2673 $result = ($bResult) ? 1 : 0;
2674 self::cacheSet($keypart, $result, 0, 300);
2677 return ($result == 1) ? true : false;
2680 protected function _inScope(Profile $profile=null)
2682 if (!is_null($this->scope)) {
2683 $scope = $this->scope;
2685 $scope = self::defaultScope();
2688 // If there's no scope, anyone (even anon) is in scope.
2690 if ($scope == 0) { // Not private
2692 return !$this->isHiddenSpam($profile);
2694 } else { // Private, somehow
2696 // If there's scope, anon cannot be in scope
2698 if (empty($profile)) {
2702 // Author is always in scope
2704 if ($this->profile_id == $profile->id) {
2708 // Only for users on this site
2710 if (($scope & Notice::SITE_SCOPE) && !$profile->isLocal()) {
2714 // Only for users mentioned in the notice
2716 if ($scope & Notice::ADDRESSEE_SCOPE) {
2718 $reply = Reply::pkeyGet(array('notice_id' => $this->id,
2719 'profile_id' => $profile->id));
2721 if (!$reply instanceof Reply) {
2726 // Only for members of the given group
2728 if ($scope & Notice::GROUP_SCOPE) {
2730 // XXX: just query for the single membership
2732 $groups = $this->getGroups();
2736 foreach ($groups as $group) {
2737 if ($profile->isMember($group)) {
2748 // Only for followers of the author
2752 if ($scope & Notice::FOLLOWER_SCOPE) {
2755 $author = $this->getProfile();
2756 } catch (Exception $e) {
2760 if (!Subscription::exists($profile, $author)) {
2765 return !$this->isHiddenSpam($profile);
2769 function isHiddenSpam(Profile $profile=null) {
2771 // Hide posts by silenced users from everyone but moderators.
2773 if (common_config('notice', 'hidespam')) {
2776 $author = $this->getProfile();
2777 } catch(Exception $e) {
2778 // If we can't get an author, keep it hidden.
2779 // XXX: technically not spam, but, whatever.
2783 if ($author->hasRole(Profile_role::SILENCED)) {
2784 if (!$profile instanceof Profile || (($profile->id !== $author->id) && (!$profile->hasRight(Right::REVIEWSPAM)))) {
2793 public function getParent()
2795 $parent = Notice::getKV('id', $this->reply_to);
2797 if (!$parent instanceof Notice) {
2798 throw new ServerException('Notice has no parent');
2805 * Magic function called at serialize() time.
2807 * We use this to drop a couple process-specific references
2808 * from DB_DataObject which can cause trouble in future
2811 * @return array of variable names to include in serialization.
2816 $vars = parent::__sleep();
2817 $skip = array('_profile', '_groups', '_attachments', '_faves', '_replies', '_repeats');
2818 return array_diff($vars, $skip);
2821 static function defaultScope()
2823 $scope = common_config('notice', 'defaultscope');
2824 if (is_null($scope)) {
2825 if (common_config('site', 'private')) {
2834 static function fillProfiles(array $notices)
2836 $map = self::getProfiles($notices);
2838 foreach ($notices as $entry=>$notice) {
2840 if (array_key_exists($notice->profile_id, $map)) {
2841 $notice->_setProfile($map[$notice->profile_id]);
2843 } catch (NoProfileException $e) {
2844 common_log(LOG_WARNING, "Failed to fill profile in Notice with non-existing entry for profile_id: {$e->profile_id}");
2845 unset($notices[$entry]);
2849 return array_values($map);
2852 static function getProfiles(array &$notices)
2855 foreach ($notices as $notice) {
2856 $ids[] = $notice->profile_id;
2859 $ids = array_unique($ids);
2861 return Profile::pivotGet('id', $ids);
2864 static function fillGroups(array &$notices)
2866 $ids = self::_idsOf($notices);
2868 $gis = Group_inbox::listGet('notice_id', $ids);
2872 foreach ($gis as $id => $gi)
2876 $gids[] = $g->group_id;
2880 $gids = array_unique($gids);
2882 $group = User_group::pivotGet('id', $gids);
2884 foreach ($notices as $notice)
2887 $gi = $gis[$notice->id];
2888 foreach ($gi as $g) {
2889 $grps[] = $group[$g->group_id];
2891 $notice->_setGroups($grps);
2895 static function _idsOf(array &$notices)
2898 foreach ($notices as $notice) {
2899 $ids[$notice->id] = true;
2901 return array_keys($ids);
2904 static function fillAttachments(array &$notices)
2906 $ids = self::_idsOf($notices);
2908 $f2pMap = File_to_post::listGet('post_id', $ids);
2912 foreach ($f2pMap as $noticeId => $f2ps) {
2913 foreach ($f2ps as $f2p) {
2914 $fileIds[] = $f2p->file_id;
2918 $fileIds = array_unique($fileIds);
2920 $fileMap = File::pivotGet('id', $fileIds);
2922 foreach ($notices as $notice)
2925 $f2ps = $f2pMap[$notice->id];
2926 foreach ($f2ps as $f2p) {
2927 $files[] = $fileMap[$f2p->file_id];
2929 $notice->_setAttachments($files);
2933 static function fillReplies(array &$notices)
2935 $ids = self::_idsOf($notices);
2936 $replyMap = Reply::listGet('notice_id', $ids);
2937 foreach ($notices as $notice) {
2938 $replies = $replyMap[$notice->id];
2940 foreach ($replies as $reply) {
2941 $ids[] = $reply->profile_id;
2943 $notice->_setReplies($ids);
2947 protected $_repeats = array();
2949 function getRepeats()
2951 if (isset($this->_repeats[$this->id])) {
2952 return $this->_repeats[$this->id];
2954 $repeatMap = Notice::listGet('repeat_of', array($this->id));
2955 $this->_setRepeats($repeatMap[$this->id]);
2956 return $this->_repeats[$this->id];
2959 function _setRepeats(array $repeats)
2961 $this->_repeats[$this->id] = $repeats;
2964 static function fillRepeats(array &$notices)
2966 $ids = self::_idsOf($notices);
2967 $repeatMap = Notice::listGet('repeat_of', $ids);
2968 foreach ($notices as $notice) {
2969 $repeats = $repeatMap[$notice->id];
2970 $notice->_setRepeats($repeats);