3 * StatusNet - the distributed open-source microblogging tool
4 * Copyright (C) 2008-2011 StatusNet, Inc.
6 * This program is free software: you can redistribute it and/or modify
7 * it under the terms of the GNU Affero General Public License as published by
8 * the Free Software Foundation, either version 3 of the License, or
9 * (at your option) any later version.
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU Affero General Public License for more details.
16 * You should have received a copy of the GNU Affero General Public License
17 * along with this program. If not, see <http://www.gnu.org/licenses/>.
21 * @author Brenda Wallace <shiny@cpan.org>
22 * @author Christopher Vollick <psycotica0@gmail.com>
23 * @author CiaranG <ciaran@ciarang.com>
24 * @author Craig Andrews <candrews@integralblue.com>
25 * @author Evan Prodromou <evan@controlezvous.ca>
26 * @author Gina Haeussge <osd@foosel.net>
27 * @author Jeffery To <jeffery.to@gmail.com>
28 * @author Mike Cochrane <mikec@mikenz.geek.nz>
29 * @author Robin Millette <millette@controlyourself.ca>
30 * @author Sarven Capadisli <csarven@controlyourself.ca>
31 * @author Tom Adams <tom@holizz.com>
32 * @author Mikael Nordfeldth <mmn@hethane.se>
33 * @copyright 2009 Free Software Foundation, Inc http://www.fsf.org
34 * @license GNU Affero General Public License http://www.gnu.org/licenses/
37 if (!defined('GNUSOCIAL')) { exit(1); }
40 * Table Definition for notice
43 /* We keep 200 notices, the max number of notices available per API request,
44 * in the memcached cache. */
46 define('NOTICE_CACHE_WINDOW', CachingNoticeStream::CACHE_WINDOW);
48 define('MAX_BOXCARS', 128);
50 class Notice extends Managed_DataObject
53 /* the code below is auto generated do not remove the above tag */
55 public $__table = 'notice'; // table name
56 public $id; // int(4) primary_key not_null
57 public $profile_id; // int(4) multiple_key not_null
58 public $uri; // varchar(191) unique_key not 255 because utf8mb4 takes more space
59 public $content; // text
60 public $rendered; // text
61 public $url; // varchar(191) not 255 because utf8mb4 takes more space
62 public $created; // datetime multiple_key not_null default_0000-00-00%2000%3A00%3A00
63 public $modified; // timestamp not_null default_CURRENT_TIMESTAMP
64 public $reply_to; // int(4)
65 public $is_local; // int(4)
66 public $source; // varchar(32)
67 public $conversation; // int(4)
68 public $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(191) not 255 because utf8mb4 takes more space
74 public $object_type; // varchar(191) not 255 because utf8mb4 takes more space
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' => 191, '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' => 191, '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' => 191, 'description' => 'URI representing activity streams object type', 'default' => 'http://activitystrea.ms/schema/1.0/note'),
102 'verb' => array('type' => 'varchar', 'length' => 191, '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);
316 public static function getById($id)
318 $notice = new Notice();
320 if (!$notice->find(true)) {
321 throw new NoResultException($notice);
327 * Extract #hashtags from this notice's content and save them to the database.
331 /* extract all #hastags */
332 $count = preg_match_all('/(?:^|\s)#([\pL\pN_\-\.]{1,64})/u', strtolower($this->content), $match);
337 /* Add them to the database */
338 return $this->saveKnownTags($match[1]);
342 * Record the given set of hash tags in the db for this notice.
343 * Given tag strings will be normalized and checked for dupes.
345 function saveKnownTags(array $hashtags)
347 //turn each into their canonical tag
348 //this is needed to remove dupes before saving e.g. #hash.tag = #hashtag
349 for($i=0; $i<count($hashtags); $i++) {
350 /* elide characters we don't want in the tag */
351 $hashtags[$i] = common_canonical_tag($hashtags[$i]);
354 foreach(array_unique($hashtags) as $hashtag) {
355 $this->saveTag($hashtag);
356 self::blow('profile:notice_ids_tagged:%d:%s', $this->profile_id, $hashtag);
362 * Record a single hash tag as associated with this notice.
363 * Tag format and uniqueness must be validated by caller.
365 function saveTag($hashtag)
367 $tag = new Notice_tag();
368 $tag->notice_id = $this->id;
369 $tag->tag = $hashtag;
370 $tag->created = $this->created;
371 $id = $tag->insert();
374 // TRANS: Server exception. %s are the error details.
375 throw new ServerException(sprintf(_('Database error inserting hashtag: %s.'),
376 $last_error->message));
380 // if it's saved, blow its cache
381 $tag->blowCache(false);
385 * Save a new notice and push it out to subscribers' inboxes.
386 * Poster's permissions are checked before sending.
388 * @param int $profile_id Profile ID of the poster
389 * @param string $content source message text; links may be shortened
390 * per current user's preference
391 * @param string $source source key ('web', 'api', etc)
392 * @param array $options Associative array of optional properties:
393 * string 'created' timestamp of notice; defaults to now
394 * int 'is_local' source/gateway ID, one of:
395 * Notice::LOCAL_PUBLIC - Local, ok to appear in public timeline
396 * Notice::REMOTE - Sent from a remote service;
397 * hide from public timeline but show in
398 * local "and friends" timelines
399 * Notice::LOCAL_NONPUBLIC - Local, but hide from public timeline
400 * Notice::GATEWAY - From another non-OStatus service;
401 * will not appear in public views
402 * float 'lat' decimal latitude for geolocation
403 * float 'lon' decimal longitude for geolocation
404 * int 'location_id' geoname identifier
405 * int 'location_ns' geoname namespace to interpret location_id
406 * int 'reply_to'; notice ID this is a reply to
407 * int 'repeat_of'; notice ID this is a repeat of
408 * string 'uri' unique ID for notice; a unique tag uri (can be url or anything too)
409 * string 'url' permalink to notice; defaults to local notice URL
410 * string 'rendered' rendered HTML version of content
411 * array 'replies' list of profile URIs for reply delivery in
412 * place of extracting @-replies from content.
413 * array 'groups' list of group IDs to deliver to, in place of
414 * extracting ! tags from content
415 * array 'tags' list of hashtag strings to save with the notice
416 * in place of extracting # tags from content
417 * array 'urls' list of attached/referred URLs to save with the
418 * notice in place of extracting links from content
419 * boolean 'distribute' whether to distribute the notice, default true
420 * string 'object_type' URL of the associated object type (default ActivityObject::NOTE)
421 * string 'verb' URL of the associated verb (default ActivityVerb::POST)
422 * int 'scope' Scope bitmask; default to SITE_SCOPE on private sites, 0 otherwise
424 * @fixme tag override
427 * @throws ClientException
429 static function saveNew($profile_id, $content, $source, array $options=array()) {
430 $defaults = array('uri' => null,
432 'conversation' => null, // URI of conversation
433 'reply_to' => null, // This will override convo URI if the parent is known
434 'repeat_of' => null, // This will override convo URI if the repeated notice is known
436 'distribute' => true,
437 'object_type' => null,
441 * Above type-hint is already array, so simply count it, this saves
444 if (count($options) > 0) {
445 $options = array_merge($defaults, $options);
450 if (!isset($is_local)) {
451 $is_local = Notice::LOCAL_PUBLIC;
454 $profile = Profile::getKV('id', $profile_id);
455 if (!$profile instanceof Profile) {
456 // TRANS: Client exception thrown when trying to save a notice for an unknown user.
457 throw new ClientException(_('Problem saving notice. Unknown user.'));
460 $user = User::getKV('id', $profile_id);
461 if ($user instanceof User) {
462 // Use the local user's shortening preferences, if applicable.
463 $final = $user->shortenLinks($content);
465 $final = common_shorten_links($content);
468 if (Notice::contentTooLong($final)) {
469 // TRANS: Client exception thrown if a notice contains too many characters.
470 throw new ClientException(_('Problem saving notice. Too long.'));
473 if (common_config('throttle', 'enabled') && !Notice::checkEditThrottle($profile_id)) {
474 common_log(LOG_WARNING, 'Excessive posting by profile #' . $profile_id . '; throttled.');
475 // TRANS: Client exception thrown when a user tries to post too many notices in a given time frame.
476 throw new ClientException(_('Too many notices too fast; take a breather '.
477 'and post again in a few minutes.'));
480 if (common_config('site', 'dupelimit') > 0 && !Notice::checkDupes($profile_id, $final)) {
481 common_log(LOG_WARNING, 'Dupe posting by profile #' . $profile_id . '; throttled.');
482 // TRANS: Client exception thrown when a user tries to post too many duplicate notices in a given time frame.
483 throw new ClientException(_('Too many duplicate messages too quickly;'.
484 ' take a breather and post again in a few minutes.'));
487 if (!$profile->hasRight(Right::NEWNOTICE)) {
488 common_log(LOG_WARNING, "Attempted post from user disallowed to post: " . $profile->nickname);
490 // TRANS: Client exception thrown when a user tries to post while being banned.
491 throw new ClientException(_('You are banned from posting notices on this site.'), 403);
494 $notice = new Notice();
495 $notice->profile_id = $profile_id;
497 $autosource = common_config('public', 'autosource');
499 // Sandboxed are non-false, but not 1, either
501 if (!$profile->hasRight(Right::PUBLICNOTICE) ||
502 ($source && $autosource && in_array($source, $autosource))) {
503 $notice->is_local = Notice::LOCAL_NONPUBLIC;
505 $notice->is_local = $is_local;
508 if (!empty($created)) {
509 $notice->created = $created;
511 $notice->created = common_sql_now();
514 if (!$notice->isLocal()) {
515 // Only do these checks for non-local notices. Local notices will generate these values later.
516 if (!common_valid_http_url($url)) {
517 common_debug('Bad notice URL: ['.$url.'], URI: ['.$uri.']. Cannot link back to original! This is normal for shared notices etc.');
520 throw new ServerException('No URI for remote notice. Cannot accept that.');
524 $notice->content = $final;
526 $notice->source = $source;
530 // Get the groups here so we can figure out replies and such
531 if (!isset($groups)) {
532 $groups = User_group::idsFromText($notice->content, $profile);
537 // Handle repeat case
539 if (isset($repeat_of)) {
541 // Check for a private one
543 $repeat = Notice::getKV('id', $repeat_of);
545 if (!($repeat instanceof Notice)) {
546 // TRANS: Client exception thrown in notice when trying to repeat a missing or deleted notice.
547 throw new ClientException(_('Cannot repeat; original notice is missing or deleted.'));
550 if ($profile->id == $repeat->profile_id) {
551 // TRANS: Client error displayed when trying to repeat an own notice.
552 throw new ClientException(_('You cannot repeat your own notice.'));
555 if ($repeat->scope != Notice::SITE_SCOPE &&
556 $repeat->scope != Notice::PUBLIC_SCOPE) {
557 // TRANS: Client error displayed when trying to repeat a non-public notice.
558 throw new ClientException(_('Cannot repeat a private notice.'), 403);
561 if (!$repeat->inScope($profile)) {
562 // The generic checks above should cover this, but let's be sure!
563 // TRANS: Client error displayed when trying to repeat a notice you cannot access.
564 throw new ClientException(_('Cannot repeat a notice you cannot read.'), 403);
567 if ($profile->hasRepeated($repeat)) {
568 // TRANS: Client error displayed when trying to repeat an already repeated notice.
569 throw new ClientException(_('You already repeated that notice.'));
572 $notice->repeat_of = $repeat->id;
573 $notice->conversation = $repeat->conversation;
577 // If $reply_to is specified, we check that it exists, and then
578 // return it if it does
579 if (!empty($reply_to)) {
580 $reply = Notice::getKV('id', $reply_to);
581 } elseif (in_array($source, array('xmpp', 'mail', 'sms'))) {
582 // If the source lacks capability of sending the "reply_to"
583 // metadata, let's try to find an inline replyto-reference.
584 $reply = self::getInlineReplyTo($profile, $final);
587 if ($reply instanceof Notice) {
588 if (!$reply->inScope($profile)) {
589 // TRANS: Client error displayed when trying to reply to a notice a the target has no access to.
590 // TRANS: %1$s is a user nickname, %2$d is a notice ID (number).
591 throw new ClientException(sprintf(_('%1$s has no access to notice %2$d.'),
592 $profile->nickname, $reply->id), 403);
595 // If it's a repeat, the reply_to should be to the original
596 if ($reply->isRepeat()) {
597 $notice->reply_to = $reply->repeat_of;
599 $notice->reply_to = $reply->id;
601 // But the conversation ought to be the same :)
602 $notice->conversation = $reply->conversation;
604 // If the original is private to a group, and notice has
605 // no group specified, make it to the same group(s)
607 if (empty($groups) && ($reply->scope & Notice::GROUP_SCOPE)) {
609 $replyGroups = $reply->getGroups();
610 foreach ($replyGroups as $group) {
611 if ($profile->isMember($group)) {
612 $groups[] = $group->id;
620 // If we don't know the reply, we might know the conversation!
621 // This will happen if a known remote user replies to an
622 // unknown remote user - within a known conversation.
623 if (empty($notice->conversation) and !empty($options['conversation'])) {
624 $conv = Conversation::getKV('uri', $options['conversation']);
625 if ($conv instanceof Conversation) {
626 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.').');
627 $notice->conversation = $conv->id;
629 // Conversation URI was not found, so we must create it. But we can't create it
630 // until we have a Notice ID because of the database layout...
631 $notice->tmp_conv_uri = $options['conversation'];
634 // If we're not using the attached conversation URI let's remove it
635 // so we don't mistake ourselves later, when creating our own Conversation.
636 // This implies that the notice knows which conversation it belongs to.
637 $options['conversation'] = null;
641 if (!empty($lat) && !empty($lon)) {
646 if (!empty($location_ns) && !empty($location_id)) {
647 $notice->location_id = $location_id;
648 $notice->location_ns = $location_ns;
651 if (!empty($rendered)) {
652 $notice->rendered = $rendered;
654 $notice->rendered = common_render_content($final, $notice);
658 if ($notice->isRepeat()) {
659 $notice->verb = ActivityVerb::SHARE;
660 $notice->object_type = ActivityObject::ACTIVITY;
662 $notice->verb = ActivityVerb::POST;
665 $notice->verb = $verb;
668 if (empty($object_type)) {
669 $notice->object_type = (empty($notice->reply_to)) ? ActivityObject::NOTE : ActivityObject::COMMENT;
671 $notice->object_type = $object_type;
674 if (is_null($scope) && $reply instanceof Notice) {
675 $notice->scope = $reply->scope;
677 $notice->scope = $scope;
680 $notice->scope = self::figureOutScope($profile, $groups, $notice->scope);
682 if (Event::handle('StartNoticeSave', array(&$notice))) {
684 // XXX: some of these functions write to the DB
687 $notice->insert(); // throws exception on failure
688 // If it's not part of a conversation, it's
689 // the beginning of a new conversation.
690 if (empty($notice->conversation)) {
691 $orig = clone($notice);
692 // $act->context->conversation will be null if it was not provided
693 $conv = Conversation::create($notice, $options['conversation']);
694 $notice->conversation = $conv->id;
695 $notice->update($orig);
697 } catch (Exception $e) {
698 // Let's test if we managed initial insert, which would imply
699 // failing on some update-part (check 'insert()'). Delete if
700 // something had been stored to the database.
701 if (!empty($notice->id)) {
708 // Clear the cache for subscribed users, so they'll update at next request
709 // XXX: someone clever could prepend instead of clearing the cache
711 // Save per-notice metadata...
713 if (isset($replies)) {
714 $notice->saveKnownReplies($replies);
716 $notice->saveReplies();
720 $notice->saveKnownTags($tags);
725 // Note: groups may save tags, so must be run after tags are saved
726 // to avoid errors on duplicates.
727 // Note: groups should always be set.
729 $notice->saveKnownGroups($groups);
732 $notice->saveKnownUrls($urls);
738 // Prepare inbox delivery, may be queued to background.
739 $notice->distribute();
745 static function saveActivity(Activity $act, Profile $actor, array $options=array())
747 // First check if we're going to let this Activity through from the specific actor
748 if (!$actor->hasRight(Right::NEWNOTICE)) {
749 common_log(LOG_WARNING, "Attempted post from user disallowed to post: " . $actor->getNickname());
751 // TRANS: Client exception thrown when a user tries to post while being banned.
752 throw new ClientException(_m('You are banned from posting notices on this site.'), 403);
754 if (common_config('throttle', 'enabled') && !self::checkEditThrottle($actor->id)) {
755 common_log(LOG_WARNING, 'Excessive posting by profile #' . $actor->id . '; throttled.');
756 // TRANS: Client exception thrown when a user tries to post too many notices in a given time frame.
757 throw new ClientException(_m('Too many notices too fast; take a breather '.
758 'and post again in a few minutes.'));
761 // Get ActivityObject properties
762 if (!empty($act->id)) {
764 $options['uri'] = $act->id;
765 $options['url'] = $act->link;
767 $actobj = count($act->objects)==1 ? $act->objects[0] : null;
768 if (!is_null($actobj) && !empty($actobj->id)) {
769 $options['uri'] = $actobj->id;
771 $options['url'] = $actobj->link;
772 } elseif (preg_match('!^https?://!', $actobj->id)) {
773 $options['url'] = $actobj->id;
780 'is_local' => self::LOCAL_PUBLIC,
781 'mentions' => array(),
785 'source' => 'unknown',
790 'distribute' => true);
792 // options will have default values when nothing has been supplied
793 $options = array_merge($defaults, $options);
794 foreach (array_keys($defaults) as $key) {
795 // Only convert the keynames we specify ourselves from 'defaults' array into variables
796 $$key = $options[$key];
798 extract($options, EXTR_SKIP);
800 $stored = new Notice();
803 if ($stored->find()) {
804 common_debug('cannot create duplicate Notice URI: '.$stored->uri);
805 throw new Exception('Notice URI already exists');
809 $stored->profile_id = $actor->id;
810 $stored->source = $source;
813 $stored->verb = $act->verb;
815 // Use the local user's shortening preferences, if applicable.
816 $stored->rendered = $actor->isLocal()
817 ? $actor->shortenLinks($act->content)
819 $stored->content = common_strip_html($stored->rendered);
821 $autosource = common_config('public', 'autosource');
823 // Sandboxed are non-false, but not 1, either
824 if (!$actor->hasRight(Right::PUBLICNOTICE) ||
825 ($source && $autosource && in_array($source, $autosource))) {
826 $stored->is_local = Notice::LOCAL_NONPUBLIC;
829 // Maybe a missing act-time should be fatal if the actor is not local?
830 if (!empty($act->time)) {
831 $stored->created = common_sql_date($act->time);
833 $stored->created = common_sql_now();
837 if ($act->context instanceof ActivityContext && !empty($act->context->replyToID)) {
838 $reply = self::getKV('uri', $act->context->replyToID);
840 if (!$reply instanceof Notice && $act->target instanceof ActivityObject) {
841 $reply = self::getKV('uri', $act->target->id);
844 if ($reply instanceof Notice) {
845 if (!$reply->inScope($actor)) {
846 // TRANS: Client error displayed when trying to reply to a notice a the target has no access to.
847 // TRANS: %1$s is a user nickname, %2$d is a notice ID (number).
848 throw new ClientException(sprintf(_m('%1$s has no right to reply to notice %2$d.'), $actor->getNickname(), $reply->id), 403);
851 $stored->reply_to = $reply->id;
852 $stored->conversation = $reply->conversation;
854 // If the original is private to a group, and notice has no group specified,
855 // make it to the same group(s)
856 if (empty($groups) && ($reply->scope & Notice::GROUP_SCOPE)) {
858 $replyGroups = $reply->getGroups();
859 foreach ($replyGroups as $group) {
860 if ($actor->isMember($group)) {
861 $groups[] = $group->id;
866 if (is_null($scope)) {
867 $scope = $reply->scope;
871 if ($act->context instanceof ActivityContext) {
872 $location = $act->context->location;
874 $stored->lat = $location->lat;
875 $stored->lon = $location->lon;
876 if ($location->location_id) {
877 $stored->location_ns = $location->location_ns;
878 $stored->location_id = $location->location_id;
882 $act->context = new ActivityContext();
885 $stored->scope = self::figureOutScope($actor, $groups, $scope);
887 foreach ($act->categories as $cat) {
889 $term = common_canonical_tag($cat->term);
896 foreach ($act->enclosures as $href) {
897 // @todo FIXME: Save these locally or....?
901 if (Event::handle('StartNoticeSave', array(&$stored))) {
902 // XXX: some of these functions write to the DB
905 $stored->insert(); // throws exception on error
906 $orig = clone($stored); // for updating later in this try clause
908 // If it's not part of a conversation, it's
909 // the beginning of a new conversation.
910 if (empty($stored->conversation)) {
911 // $act->context->conversation will be null if it was not provided
912 $conv = Conversation::create($stored, $act->context->conversation);
913 $stored->conversation = $conv->id;
917 Event::handle('StoreActivityObject', array($act, $stored, $options, &$object));
918 if (empty($object)) {
919 throw new ServerException('No object from StoreActivityObject '.$stored->uri . ': '.$act->asString());
921 $stored->object_type = ActivityUtils::resolveUri($object->getObjectType(), true);
922 $stored->update($orig);
923 } catch (Exception $e) {
924 if (empty($stored->id)) {
925 common_debug('Failed to save stored object entry in database ('.$e->getMessage().')');
927 common_debug('Failed to store activity object in database ('.$e->getMessage().'), deleting notice id '.$stored->id);
933 if (!$stored instanceof Notice) {
934 throw new ServerException('StartNoticeSave did not give back a Notice');
937 // Save per-notice metadata...
941 // This event lets plugins filter out non-local recipients (attentions we don't care about)
942 // Used primarily for OStatus (and if we don't federate, all attentions would be local anyway)
943 Event::handle('GetLocalAttentions', array($actor, $act->context->attention, &$mentions, &$groups));
945 if (!empty($mentions)) {
946 $stored->saveKnownReplies($mentions);
948 $stored->saveReplies();
952 $stored->saveKnownTags($tags);
957 // Note: groups may save tags, so must be run after tags are saved
958 // to avoid errors on duplicates.
959 // Note: groups should always be set.
961 $stored->saveKnownGroups($groups);
964 $stored->saveKnownUrls($urls);
970 // Prepare inbox delivery, may be queued to background.
971 $stored->distribute();
977 static public function figureOutScope(Profile $actor, array $groups, $scope=null) {
978 if (is_null($scope)) {
979 $scope = self::defaultScope();
982 // For private streams
984 $user = $actor->getUser();
985 // FIXME: We can't do bit comparison with == (Legacy StatusNet thing. Let's keep it for now.)
986 if ($user->private_stream && ($scope == Notice::PUBLIC_SCOPE || $scope == Notice::SITE_SCOPE)) {
987 $scope |= Notice::FOLLOWER_SCOPE;
989 } catch (NoSuchUserException $e) {
990 // TODO: Not a local user, so we don't know about scope preferences... yet!
993 // Force the scope for private groups
994 foreach ($groups as $group_id) {
995 $group = User_group::staticGet('id', $group_id);
996 if ($group instanceof User_group) {
997 if ($group->force_scope) {
998 $scope |= Notice::GROUP_SCOPE;
1007 function blowOnInsert($conversation = false)
1009 $this->blowStream('profile:notice_ids:%d', $this->profile_id);
1011 if ($this->isPublic()) {
1012 $this->blowStream('public');
1013 $this->blowStream('networkpublic');
1016 self::blow('notice:list-ids:conversation:%s', $this->conversation);
1017 self::blow('conversation:notice_count:%d', $this->conversation);
1019 if ($this->isRepeat()) {
1020 // XXX: we should probably only use one of these
1021 $this->blowStream('notice:repeats:%d', $this->repeat_of);
1022 self::blow('notice:list-ids:repeat_of:%d', $this->repeat_of);
1025 $original = Notice::getKV('id', $this->repeat_of);
1027 if ($original instanceof Notice) {
1028 $originalUser = User::getKV('id', $original->profile_id);
1029 if ($originalUser instanceof User) {
1030 $this->blowStream('user:repeats_of_me:%d', $originalUser->id);
1034 $profile = Profile::getKV($this->profile_id);
1036 if ($profile instanceof Profile) {
1037 $profile->blowNoticeCount();
1040 $ptags = $this->getProfileTags();
1041 foreach ($ptags as $ptag) {
1042 $ptag->blowNoticeStreamCache();
1047 * Clear cache entries related to this notice at delete time.
1048 * Necessary to avoid breaking paging on public, profile timelines.
1050 function blowOnDelete()
1052 $this->blowOnInsert();
1054 self::blow('profile:notice_ids:%d;last', $this->profile_id);
1056 if ($this->isPublic()) {
1057 self::blow('public;last');
1058 self::blow('networkpublic;last');
1061 self::blow('fave:by_notice', $this->id);
1063 if ($this->conversation) {
1064 // In case we're the first, will need to calc a new root.
1065 self::blow('notice:conversation_root:%d', $this->conversation);
1068 $ptags = $this->getProfileTags();
1069 foreach ($ptags as $ptag) {
1070 $ptag->blowNoticeStreamCache(true);
1074 function blowStream()
1076 $c = self::memcache();
1082 $args = func_get_args();
1083 $format = array_shift($args);
1084 $keyPart = vsprintf($format, $args);
1085 $cacheKey = Cache::key($keyPart);
1086 $c->delete($cacheKey);
1088 // delete the "last" stream, too, if this notice is
1089 // older than the top of that stream
1091 $lastKey = $cacheKey.';last';
1093 $lastStr = $c->get($lastKey);
1095 if ($lastStr !== false) {
1096 $window = explode(',', $lastStr);
1097 $lastID = $window[0];
1098 $lastNotice = Notice::getKV('id', $lastID);
1099 if (!$lastNotice instanceof Notice // just weird
1100 || strtotime($lastNotice->created) >= strtotime($this->created)) {
1101 $c->delete($lastKey);
1106 /** save all urls in the notice to the db
1108 * follow redirects and save all available file information
1109 * (mimetype, date, size, oembed, etc.)
1113 function saveUrls() {
1114 if (common_config('attachments', 'process_links')) {
1115 common_replace_urls_callback($this->content, array($this, 'saveUrl'), $this->id);
1120 * Save the given URLs as related links/attachments to the db
1122 * follow redirects and save all available file information
1123 * (mimetype, date, size, oembed, etc.)
1127 function saveKnownUrls(array $urls)
1129 if (common_config('attachments', 'process_links')) {
1130 // @fixme validation?
1131 foreach (array_unique($urls) as $url) {
1133 File::processNew($url, $this->id);
1134 } catch (ServerException $e) {
1135 // Could not save URL. Log it?
1144 function saveUrl($url, $notice_id) {
1146 File::processNew($url, $notice_id);
1147 } catch (ServerException $e) {
1148 // Could not save URL. Log it?
1152 static function checkDupes($profile_id, $content) {
1153 $profile = Profile::getKV($profile_id);
1154 if (!$profile instanceof Profile) {
1157 $notice = $profile->getNotices(0, CachingNoticeStream::CACHE_WINDOW);
1158 if (!empty($notice)) {
1160 while ($notice->fetch()) {
1161 if (time() - strtotime($notice->created) >= common_config('site', 'dupelimit')) {
1163 } else if ($notice->content == $content) {
1168 // If we get here, oldest item in cache window is not
1169 // old enough for dupe limit; do direct check against DB
1170 $notice = new Notice();
1171 $notice->profile_id = $profile_id;
1172 $notice->content = $content;
1173 $threshold = common_sql_date(time() - common_config('site', 'dupelimit'));
1174 $notice->whereAdd(sprintf("created > '%s'", $notice->escape($threshold)));
1176 $cnt = $notice->count();
1180 static function checkEditThrottle($profile_id) {
1181 $profile = Profile::getKV($profile_id);
1182 if (!$profile instanceof Profile) {
1185 // Get the Nth notice
1186 $notice = $profile->getNotices(common_config('throttle', 'count') - 1, 1);
1187 if ($notice && $notice->fetch()) {
1188 // If the Nth notice was posted less than timespan seconds ago
1189 if (time() - strtotime($notice->created) <= common_config('throttle', 'timespan')) {
1194 // Either not N notices in the stream, OR the Nth was not posted within timespan seconds
1198 protected $_attachments = array();
1200 function attachments() {
1201 if (isset($this->_attachments[$this->id])) {
1202 return $this->_attachments[$this->id];
1205 $f2ps = File_to_post::listGet('post_id', array($this->id));
1207 foreach ($f2ps[$this->id] as $f2p) {
1208 $ids[] = $f2p->file_id;
1211 $files = File::multiGet('id', $ids);
1212 $this->_attachments[$this->id] = $files->fetchAll();
1213 return $this->_attachments[$this->id];
1216 function _setAttachments($attachments)
1218 $this->_attachments[$this->id] = $attachments;
1221 function publicStream($offset=0, $limit=20, $since_id=0, $max_id=0)
1223 $stream = new PublicNoticeStream();
1224 return $stream->getNotices($offset, $limit, $since_id, $max_id);
1228 function conversationStream($id, $offset=0, $limit=20, $since_id=0, $max_id=0)
1230 $stream = new ConversationNoticeStream($id);
1232 return $stream->getNotices($offset, $limit, $since_id, $max_id);
1236 * Is this notice part of an active conversation?
1238 * @return boolean true if other messages exist in the same
1239 * conversation, false if this is the only one
1241 function hasConversation()
1243 if (!empty($this->conversation)) {
1244 $conversation = Notice::conversationStream(
1245 $this->conversation,
1250 if ($conversation->N > 0) {
1258 * Grab the earliest notice from this conversation.
1260 * @return Notice or null
1262 function conversationRoot($profile=-1)
1264 // XXX: can this happen?
1266 if (empty($this->conversation)) {
1270 // Get the current profile if not specified
1272 if (is_int($profile) && $profile == -1) {
1273 $profile = Profile::current();
1276 // If this notice is out of scope, no root for you!
1278 if (!$this->inScope($profile)) {
1282 // If this isn't a reply to anything, then it's its own
1283 // root if it's the earliest notice in the conversation:
1285 if (empty($this->reply_to)) {
1287 $root->conversation = $this->conversation;
1288 $root->orderBy('notice.created ASC');
1295 if (is_null($profile)) {
1296 $keypart = sprintf('notice:conversation_root:%d:null', $this->id);
1298 $keypart = sprintf('notice:conversation_root:%d:%d',
1303 $root = self::cacheGet($keypart);
1305 if ($root !== false && $root->inScope($profile)) {
1312 $parent = $last->getParent();
1313 if ($parent->inScope($profile)) {
1317 } catch (Exception $e) {
1318 // Latest notice has no parent
1320 // No parent, or parent out of scope
1325 self::cacheSet($keypart, $root);
1331 * Pull up a full list of local recipients who will be getting
1332 * this notice in their inbox. Results will be cached, so don't
1333 * change the input data wily-nilly!
1335 * @param array $groups optional list of Group objects;
1336 * if left empty, will be loaded from group_inbox records
1337 * @param array $recipient optional list of reply profile ids
1338 * if left empty, will be loaded from reply records
1339 * @return array associating recipient user IDs with an inbox source constant
1341 function whoGets(array $groups=null, array $recipients=null)
1343 $c = self::memcache();
1346 $ni = $c->get(Cache::key('notice:who_gets:'.$this->id));
1347 if ($ni !== false) {
1352 if (is_null($recipients)) {
1353 $recipients = $this->getReplies();
1358 // Give plugins a chance to add folks in at start...
1359 if (Event::handle('StartNoticeWhoGets', array($this, &$ni))) {
1361 $users = $this->getSubscribedUsers();
1362 foreach ($users as $id) {
1363 $ni[$id] = NOTICE_INBOX_SOURCE_SUB;
1366 if (is_null($groups)) {
1367 $groups = $this->getGroups();
1369 foreach ($groups as $group) {
1370 $users = $group->getUserMembers();
1371 foreach ($users as $id) {
1372 if (!array_key_exists($id, $ni)) {
1373 $ni[$id] = NOTICE_INBOX_SOURCE_GROUP;
1378 $ptAtts = $this->getAttentionsFromProfileTags();
1379 foreach ($ptAtts as $key=>$val) {
1380 if (!array_key_exists($key, $ni)) {
1385 foreach ($recipients as $recipient) {
1386 if (!array_key_exists($recipient, $ni)) {
1387 $ni[$recipient] = NOTICE_INBOX_SOURCE_REPLY;
1391 // Exclude any deleted, non-local, or blocking recipients.
1392 $profile = $this->getProfile();
1393 $originalProfile = null;
1394 if ($this->isRepeat()) {
1395 // Check blocks against the original notice's poster as well.
1396 $original = Notice::getKV('id', $this->repeat_of);
1397 if ($original instanceof Notice) {
1398 $originalProfile = $original->getProfile();
1402 foreach ($ni as $id => $source) {
1404 $user = User::getKV('id', $id);
1405 if (!$user instanceof User ||
1406 $user->hasBlocked($profile) ||
1407 ($originalProfile && $user->hasBlocked($originalProfile))) {
1410 } catch (UserNoProfileException $e) {
1411 // User doesn't have a profile; invalid; skip them.
1416 // Give plugins a chance to filter out...
1417 Event::handle('EndNoticeWhoGets', array($this, &$ni));
1421 // XXX: pack this data better
1422 $c->set(Cache::key('notice:who_gets:'.$this->id), $ni);
1428 function getSubscribedUsers()
1432 if(common_config('db','quote_identifiers'))
1433 $user_table = '"user"';
1434 else $user_table = 'user';
1438 'FROM '. $user_table .' JOIN subscription '.
1439 'ON '. $user_table .'.id = subscription.subscriber ' .
1440 'WHERE subscription.subscribed = %d ';
1442 $user->query(sprintf($qry, $this->profile_id));
1446 while ($user->fetch()) {
1455 function getProfileTags()
1457 $profile = $this->getProfile();
1458 $list = $profile->getOtherTags($profile);
1461 while($list->fetch()) {
1462 $ptags[] = clone($list);
1468 public function getAttentionsFromProfileTags()
1471 $ptags = $this->getProfileTags();
1472 foreach ($ptags as $ptag) {
1473 $users = $ptag->getUserSubscribers();
1474 foreach ($users as $id) {
1475 $ni[$id] = NOTICE_INBOX_SOURCE_PROFILE_TAG;
1482 * Record this notice to the given group inboxes for delivery.
1483 * Overrides the regular parsing of !group markup.
1485 * @param string $group_ids
1486 * @fixme might prefer URIs as identifiers, as for replies?
1487 * best with generalizations on user_group to support
1488 * remote groups better.
1490 function saveKnownGroups($group_ids)
1492 if (!is_array($group_ids)) {
1493 // TRANS: Server exception thrown when no array is provided to the method saveKnownGroups().
1494 throw new ServerException(_('Bad type provided to saveKnownGroups.'));
1498 foreach (array_unique($group_ids) as $id) {
1499 $group = User_group::getKV('id', $id);
1500 if ($group instanceof User_group) {
1501 common_log(LOG_DEBUG, "Local delivery to group id $id, $group->nickname");
1502 $result = $this->addToGroupInbox($group);
1504 common_log_db_error($gi, 'INSERT', __FILE__);
1507 if (common_config('group', 'addtag')) {
1508 // we automatically add a tag for every group name, too
1510 $tag = Notice_tag::pkeyGet(array('tag' => common_canonical_tag($group->nickname),
1511 'notice_id' => $this->id));
1513 if (is_null($tag)) {
1514 $this->saveTag($group->nickname);
1518 $groups[] = clone($group);
1520 common_log(LOG_ERR, "Local delivery to group id $id skipped, doesn't exist");
1527 function addToGroupInbox(User_group $group)
1529 $gi = Group_inbox::pkeyGet(array('group_id' => $group->id,
1530 'notice_id' => $this->id));
1532 if (!$gi instanceof Group_inbox) {
1534 $gi = new Group_inbox();
1536 $gi->group_id = $group->id;
1537 $gi->notice_id = $this->id;
1538 $gi->created = $this->created;
1540 $result = $gi->insert();
1543 common_log_db_error($gi, 'INSERT', __FILE__);
1544 // TRANS: Server exception thrown when an update for a group inbox fails.
1545 throw new ServerException(_('Problem saving group inbox.'));
1548 self::blow('user_group:notice_ids:%d', $gi->group_id);
1555 * Save reply records indicating that this notice needs to be
1556 * delivered to the local users with the given URIs.
1558 * Since this is expected to be used when saving foreign-sourced
1559 * messages, we won't deliver to any remote targets as that's the
1560 * source service's responsibility.
1562 * Mail notifications etc will be handled later.
1564 * @param array $uris Array of unique identifier URIs for recipients
1566 function saveKnownReplies(array $uris)
1572 $sender = Profile::getKV($this->profile_id);
1574 foreach (array_unique($uris) as $uri) {
1576 $profile = Profile::fromUri($uri);
1577 } catch (UnknownUriException $e) {
1578 common_log(LOG_WARNING, "Unable to determine profile for URI '$uri'");
1582 if ($profile->hasBlocked($sender)) {
1583 common_log(LOG_INFO, "Not saving reply to profile {$profile->id} ($uri) from sender {$sender->id} because of a block.");
1587 $this->saveReply($profile->id);
1588 self::blow('reply:stream:%d', $profile->id);
1595 * Pull @-replies from this message's content in StatusNet markup format
1596 * and save reply records indicating that this message needs to be
1597 * delivered to those users.
1599 * Mail notifications to local profiles will be sent later.
1601 * @return array of integer profile IDs
1604 function saveReplies()
1606 // Don't save reply data for repeats
1608 if ($this->isRepeat()) {
1612 $sender = $this->getProfile();
1616 // If it's a reply, save for the replied-to author
1618 $parent = $this->getParent();
1619 $parentauthor = $parent->getProfile();
1620 $this->saveReply($parentauthor->id);
1621 $replied[$parentauthor->id] = 1;
1622 self::blow('reply:stream:%d', $parentauthor->id);
1623 } catch (Exception $e) {
1624 // Not a reply, since it has no parent!
1627 // @todo ideally this parser information would only
1628 // be calculated once.
1630 $mentions = common_find_mentions($this->content, $this);
1632 // store replied only for first @ (what user/notice what the reply directed,
1633 // we assume first @ is it)
1635 foreach ($mentions as $mention) {
1637 foreach ($mention['mentioned'] as $mentioned) {
1639 // skip if they're already covered
1641 if (!empty($replied[$mentioned->id])) {
1645 // Don't save replies from blocked profile to local user
1647 $mentioned_user = User::getKV('id', $mentioned->id);
1648 if ($mentioned_user instanceof User && $mentioned_user->hasBlocked($sender)) {
1652 $this->saveReply($mentioned->id);
1653 $replied[$mentioned->id] = 1;
1654 self::blow('reply:stream:%d', $mentioned->id);
1658 $recipientIds = array_keys($replied);
1660 return $recipientIds;
1663 function saveReply($profileId)
1665 $reply = new Reply();
1667 $reply->notice_id = $this->id;
1668 $reply->profile_id = $profileId;
1669 $reply->modified = $this->created;
1676 protected $_replies = array();
1679 * Pull the complete list of @-reply targets for this notice.
1681 * @return array of integer profile ids
1683 function getReplies()
1685 if (isset($this->_replies[$this->id])) {
1686 return $this->_replies[$this->id];
1689 $replyMap = Reply::listGet('notice_id', array($this->id));
1693 foreach ($replyMap[$this->id] as $reply) {
1694 $ids[] = $reply->profile_id;
1697 $this->_setReplies($ids);
1702 function _setReplies(array $replies)
1704 $this->_replies[$this->id] = $replies;
1708 * Pull the complete list of @-reply targets for this notice.
1710 * @return array of Profiles
1712 function getReplyProfiles()
1714 $ids = $this->getReplies();
1716 $profiles = Profile::multiGet('id', $ids);
1718 return $profiles->fetchAll();
1722 * Send e-mail notifications to local @-reply targets.
1724 * Replies must already have been saved; this is expected to be run
1725 * from the distrib queue handler.
1727 function sendReplyNotifications()
1729 // Don't send reply notifications for repeats
1731 if ($this->isRepeat()) {
1735 $recipientIds = $this->getReplies();
1736 if (Event::handle('StartNotifyMentioned', array($this, &$recipientIds))) {
1737 require_once INSTALLDIR.'/lib/mail.php';
1739 foreach ($recipientIds as $recipientId) {
1740 $user = User::getKV('id', $recipientId);
1741 if ($user instanceof User) {
1742 mail_notify_attn($user, $this);
1745 Event::handle('EndNotifyMentioned', array($this, $recipientIds));
1750 * Pull list of groups this notice needs to be delivered to,
1751 * as previously recorded by saveKnownGroups().
1753 * @return array of Group objects
1756 protected $_groups = array();
1758 function getGroups()
1760 // Don't save groups for repeats
1762 if (!empty($this->repeat_of)) {
1766 if (isset($this->_groups[$this->id])) {
1767 return $this->_groups[$this->id];
1770 $gis = Group_inbox::listGet('notice_id', array($this->id));
1774 foreach ($gis[$this->id] as $gi) {
1775 $ids[] = $gi->group_id;
1778 $groups = User_group::multiGet('id', $ids);
1779 $this->_setGroups($groups->fetchAll());
1780 return $this->_groups[$this->id];
1783 function _setGroups(array $groups)
1785 $this->_groups[$this->id] = $groups;
1789 * Convert a notice into an activity for export.
1791 * @param Profile $scoped The currently logged in/scoped profile
1793 * @return Activity activity object representing this Notice.
1796 function asActivity(Profile $scoped=null)
1798 $act = self::cacheGet(Cache::codeKey('notice:as-activity:'.$this->id));
1800 if ($act instanceof Activity) {
1803 $act = new Activity();
1805 if (Event::handle('StartNoticeAsActivity', array($this, $act, $scoped))) {
1807 $act->id = $this->uri;
1808 $act->time = strtotime($this->created);
1810 $act->link = $this->getUrl();
1811 } catch (InvalidUrlException $e) {
1812 // The notice is probably a share or similar, which don't
1813 // have a representational URL of their own.
1815 $act->content = common_xml_safe_str($this->rendered);
1817 $profile = $this->getProfile();
1819 $act->actor = $profile->asActivityObject();
1820 $act->actor->extra[] = $profile->profileInfo($scoped);
1822 $act->verb = $this->verb;
1824 if ($this->repeat_of) {
1825 $repeated = Notice::getKV('id', $this->repeat_of);
1826 if ($repeated instanceof Notice) {
1827 // TRANS: A repeat activity's title. %1$s is repeater's nickname
1828 // and %2$s is the repeated user's nickname.
1829 $act->title = sprintf(_('%1$s repeated a notice by %2$s'),
1830 $this->getProfile()->getNickname(),
1831 $repeated->getProfile()->getNickname());
1832 $act->objects[] = $repeated->asActivity($scoped);
1835 $act->objects[] = $this->asActivityObject();
1838 // XXX: should this be handled by default processing for object entry?
1842 $tags = $this->getTags();
1844 foreach ($tags as $tag) {
1845 $cat = new AtomCategory();
1848 $act->categories[] = $cat;
1852 // XXX: use Atom Media and/or File activity objects instead
1854 $attachments = $this->attachments();
1856 foreach ($attachments as $attachment) {
1857 // Save local attachments
1858 if (!empty($attachment->filename)) {
1859 $act->attachments[] = ActivityObject::fromFile($attachment);
1863 $ctx = new ActivityContext();
1866 $reply = $this->getParent();
1867 $ctx->replyToID = $reply->getUri();
1868 $ctx->replyToUrl = $reply->getUrl();
1869 } catch (Exception $e) {
1870 // This is not a reply to something
1873 $ctx->location = $this->getLocation();
1877 if (!empty($this->conversation)) {
1878 $conv = Conversation::getKV('id', $this->conversation);
1879 if ($conv instanceof Conversation) {
1880 $ctx->conversation = $conv->uri;
1884 $reply_ids = $this->getReplies();
1886 foreach ($reply_ids as $id) {
1887 $rprofile = Profile::getKV('id', $id);
1888 if ($rprofile instanceof Profile) {
1889 $ctx->attention[$rprofile->getUri()] = ActivityObject::PERSON;
1893 $groups = $this->getGroups();
1895 foreach ($groups as $group) {
1896 $ctx->attention[$group->getUri()] = ActivityObject::GROUP;
1899 switch ($this->scope) {
1900 case Notice::PUBLIC_SCOPE:
1901 $ctx->attention[ActivityContext::ATTN_PUBLIC] = ActivityObject::COLLECTION;
1903 case Notice::FOLLOWER_SCOPE:
1904 $surl = common_local_url("subscribers", array('nickname' => $profile->nickname));
1905 $ctx->attention[$surl] = ActivityObject::COLLECTION;
1909 $act->context = $ctx;
1911 $source = $this->getSource();
1913 if ($source instanceof Notice_source) {
1914 $act->generator = ActivityObject::fromNoticeSource($source);
1919 $atom_feed = $profile->getAtomFeed();
1921 if (!empty($atom_feed)) {
1923 $act->source = new ActivitySource();
1925 // XXX: we should store the actual feed ID
1927 $act->source->id = $atom_feed;
1929 // XXX: we should store the actual feed title
1931 $act->source->title = $profile->getBestName();
1933 $act->source->links['alternate'] = $profile->profileurl;
1934 $act->source->links['self'] = $atom_feed;
1936 $act->source->icon = $profile->avatarUrl(AVATAR_PROFILE_SIZE);
1938 $notice = $profile->getCurrentNotice();
1940 if ($notice instanceof Notice) {
1941 $act->source->updated = self::utcDate($notice->created);
1944 $user = User::getKV('id', $profile->id);
1946 if ($user instanceof User) {
1947 $act->source->links['license'] = common_config('license', 'url');
1951 if ($this->isLocal()) {
1952 $act->selfLink = common_local_url('ApiStatusesShow', array('id' => $this->id,
1953 'format' => 'atom'));
1954 $act->editLink = $act->selfLink;
1957 Event::handle('EndNoticeAsActivity', array($this, $act, $scoped));
1960 self::cacheSet(Cache::codeKey('notice:as-activity:'.$this->id), $act);
1965 // This has gotten way too long. Needs to be sliced up into functional bits
1966 // or ideally exported to a utility class.
1968 function asAtomEntry($namespace=false,
1971 Profile $scoped=null)
1973 $act = $this->asActivity($scoped);
1974 $act->extra[] = $this->noticeInfo($scoped);
1975 return $act->asString($namespace, $author, $source);
1979 * Extra notice info for atom entries
1981 * Clients use some extra notice info in the atom stream.
1982 * This gives it to them.
1984 * @param Profile $scoped The currently logged in/scoped profile
1986 * @return array representation of <statusnet:notice_info> element
1989 function noticeInfo(Profile $scoped=null)
1991 // local notice ID (useful to clients for ordering)
1993 $noticeInfoAttr = array('local_id' => $this->id);
1997 $ns = $this->getSource();
1999 if ($ns instanceof Notice_source) {
2000 $noticeInfoAttr['source'] = $ns->code;
2001 if (!empty($ns->url)) {
2002 $noticeInfoAttr['source_link'] = $ns->url;
2003 if (!empty($ns->name)) {
2004 $noticeInfoAttr['source'] = '<a href="'
2005 . htmlspecialchars($ns->url)
2006 . '" rel="nofollow">'
2007 . htmlspecialchars($ns->name)
2013 // favorite and repeated
2015 if ($scoped instanceof Profile) {
2016 $noticeInfoAttr['repeated'] = ($scoped->hasRepeated($this)) ? "true" : "false";
2019 if (!empty($this->repeat_of)) {
2020 $noticeInfoAttr['repeat_of'] = $this->repeat_of;
2023 Event::handle('StatusNetApiNoticeInfo', array($this, &$noticeInfoAttr, $scoped));
2025 return array('statusnet:notice_info', $noticeInfoAttr, null);
2029 * Returns an XML string fragment with a reference to a notice as an
2030 * Activity Streams noun object with the given element type.
2032 * Assumes that 'activity' namespace has been previously defined.
2034 * @param string $element one of 'subject', 'object', 'target'
2038 function asActivityNoun($element)
2040 $noun = $this->asActivityObject();
2041 return $noun->asString('activity:' . $element);
2044 public function asActivityObject()
2046 $object = new ActivityObject();
2048 if (Event::handle('StartActivityObjectFromNotice', array($this, &$object))) {
2049 $object->type = $this->object_type ?: ActivityObject::NOTE;
2050 $object->id = $this->getUri();
2051 $object->title = sprintf('New %1$s by %2$s', ActivityObject::canonicalType($object->type), $this->getProfile()->getNickname());
2052 $object->content = $this->rendered;
2053 $object->link = $this->getUrl();
2055 $object->extra[] = array('status_net', array('notice_id' => $this->id));
2057 Event::handle('EndActivityObjectFromNotice', array($this, &$object));
2064 * Determine which notice, if any, a new notice is in reply to.
2066 * For conversation tracking, we try to see where this notice fits
2067 * in the tree. Beware that this may very well give false positives
2068 * and add replies to wrong threads (if there have been newer posts
2069 * by the same user as we're replying to).
2071 * @param Profile $sender Author profile
2072 * @param string $content Final notice content
2074 * @return integer ID of replied-to notice, or null for not a reply.
2077 static function getInlineReplyTo(Profile $sender, $content)
2079 // Is there an initial @ or T?
2080 if (preg_match('/^T ([A-Z0-9]{1,64}) /', $content, $match)
2081 || preg_match('/^@([a-z0-9]{1,64})\s+/', $content, $match)) {
2082 $nickname = common_canonical_nickname($match[1]);
2087 // Figure out who that is.
2088 $recipient = common_relative_profile($sender, $nickname, common_sql_now());
2090 if ($recipient instanceof Profile) {
2091 // Get their last notice
2092 $last = $recipient->getCurrentNotice();
2093 if ($last instanceof Notice) {
2096 // Maybe in the future we want to handle something else below
2097 // so don't return getCurrentNotice() immediately.
2103 static function maxContent()
2105 $contentlimit = common_config('notice', 'contentlimit');
2106 // null => use global limit (distinct from 0!)
2107 if (is_null($contentlimit)) {
2108 $contentlimit = common_config('site', 'textlimit');
2110 return $contentlimit;
2113 static function contentTooLong($content)
2115 $contentlimit = self::maxContent();
2116 return ($contentlimit > 0 && !empty($content) && (mb_strlen($content) > $contentlimit));
2119 function getLocation()
2123 if (!empty($this->location_id) && !empty($this->location_ns)) {
2124 $location = Location::fromId($this->location_id, $this->location_ns);
2127 if (is_null($location)) { // no ID, or Location::fromId() failed
2128 if (!empty($this->lat) && !empty($this->lon)) {
2129 $location = Location::fromLatLon($this->lat, $this->lon);
2137 * Convenience function for posting a repeat of an existing message.
2139 * @param Profile $repeater Profile which is doing the repeat
2140 * @param string $source: posting source key, eg 'web', 'api', etc
2143 * @throws Exception on failure or permission problems
2145 function repeat(Profile $repeater, $source)
2147 $author = $this->getProfile();
2149 // TRANS: Message used to repeat a notice. RT is the abbreviation of 'retweet'.
2150 // TRANS: %1$s is the repeated user's name, %2$s is the repeated notice.
2151 $content = sprintf(_('RT @%1$s %2$s'),
2152 $author->getNickname(),
2155 $maxlen = self::maxContent();
2156 if ($maxlen > 0 && mb_strlen($content) > $maxlen) {
2157 // Web interface and current Twitter API clients will
2158 // pull the original notice's text, but some older
2159 // clients and RSS/Atom feeds will see this trimmed text.
2161 // Unfortunately this is likely to lose tags or URLs
2162 // at the end of long notices.
2163 $content = mb_substr($content, 0, $maxlen - 4) . ' ...';
2167 // Scope is same as this one's
2168 return self::saveNew($repeater->id,
2171 array('repeat_of' => $this->id,
2172 'scope' => $this->scope));
2175 // These are supposed to be in chron order!
2177 function repeatStream($limit=100)
2179 $cache = Cache::instance();
2181 if (empty($cache)) {
2182 $ids = $this->_repeatStreamDirect($limit);
2184 $idstr = $cache->get(Cache::key('notice:repeats:'.$this->id));
2185 if ($idstr !== false) {
2186 if (empty($idstr)) {
2189 $ids = explode(',', $idstr);
2192 $ids = $this->_repeatStreamDirect(100);
2193 $cache->set(Cache::key('notice:repeats:'.$this->id), implode(',', $ids));
2196 // We do a max of 100, so slice down to limit
2197 $ids = array_slice($ids, 0, $limit);
2201 return NoticeStream::getStreamByIds($ids);
2204 function _repeatStreamDirect($limit)
2206 $notice = new Notice();
2208 $notice->selectAdd(); // clears it
2209 $notice->selectAdd('id');
2211 $notice->repeat_of = $this->id;
2213 $notice->orderBy('created, id'); // NB: asc!
2215 if (!is_null($limit)) {
2216 $notice->limit(0, $limit);
2219 return $notice->fetchAll('id');
2222 function locationOptions($lat, $lon, $location_id, $location_ns, $profile = null)
2226 if (!empty($location_id) && !empty($location_ns)) {
2227 $options['location_id'] = $location_id;
2228 $options['location_ns'] = $location_ns;
2230 $location = Location::fromId($location_id, $location_ns);
2232 if ($location instanceof Location) {
2233 $options['lat'] = $location->lat;
2234 $options['lon'] = $location->lon;
2237 } else if (!empty($lat) && !empty($lon)) {
2238 $options['lat'] = $lat;
2239 $options['lon'] = $lon;
2241 $location = Location::fromLatLon($lat, $lon);
2243 if ($location instanceof Location) {
2244 $options['location_id'] = $location->location_id;
2245 $options['location_ns'] = $location->location_ns;
2247 } else if (!empty($profile)) {
2248 if (isset($profile->lat) && isset($profile->lon)) {
2249 $options['lat'] = $profile->lat;
2250 $options['lon'] = $profile->lon;
2253 if (isset($profile->location_id) && isset($profile->location_ns)) {
2254 $options['location_id'] = $profile->location_id;
2255 $options['location_ns'] = $profile->location_ns;
2262 function clearAttentions()
2264 $att = new Attention();
2265 $att->notice_id = $this->getID();
2268 while ($att->fetch()) {
2269 // Can't do delete() on the object directly since it won't remove all of it
2270 $other = clone($att);
2276 function clearReplies()
2278 $replyNotice = new Notice();
2279 $replyNotice->reply_to = $this->id;
2281 //Null any notices that are replies to this notice
2283 if ($replyNotice->find()) {
2284 while ($replyNotice->fetch()) {
2285 $orig = clone($replyNotice);
2286 $replyNotice->reply_to = null;
2287 $replyNotice->update($orig);
2293 $reply = new Reply();
2294 $reply->notice_id = $this->id;
2296 if ($reply->find()) {
2297 while($reply->fetch()) {
2298 self::blow('reply:stream:%d', $reply->profile_id);
2306 function clearFiles()
2308 $f2p = new File_to_post();
2310 $f2p->post_id = $this->id;
2313 while ($f2p->fetch()) {
2317 // FIXME: decide whether to delete File objects
2318 // ...and related (actual) files
2321 function clearRepeats()
2323 $repeatNotice = new Notice();
2324 $repeatNotice->repeat_of = $this->id;
2326 //Null any notices that are repeats of this notice
2328 if ($repeatNotice->find()) {
2329 while ($repeatNotice->fetch()) {
2330 $orig = clone($repeatNotice);
2331 $repeatNotice->repeat_of = null;
2332 $repeatNotice->update($orig);
2337 function clearTags()
2339 $tag = new Notice_tag();
2340 $tag->notice_id = $this->id;
2343 while ($tag->fetch()) {
2344 self::blow('profile:notice_ids_tagged:%d:%s', $this->profile_id, Cache::keyize($tag->tag));
2345 self::blow('profile:notice_ids_tagged:%d:%s;last', $this->profile_id, Cache::keyize($tag->tag));
2346 self::blow('notice_tag:notice_ids:%s', Cache::keyize($tag->tag));
2347 self::blow('notice_tag:notice_ids:%s;last', Cache::keyize($tag->tag));
2355 function clearGroupInboxes()
2357 $gi = new Group_inbox();
2359 $gi->notice_id = $this->id;
2362 while ($gi->fetch()) {
2363 self::blow('user_group:notice_ids:%d', $gi->group_id);
2371 function distribute()
2373 // We always insert for the author so they don't
2375 Event::handle('StartNoticeDistribute', array($this));
2377 // If there's a failure, we want to _force_
2378 // distribution at this point.
2380 $qm = QueueManager::get();
2381 $qm->enqueue($this, 'distrib');
2382 } catch (Exception $e) {
2383 // If the exception isn't transient, this
2384 // may throw more exceptions as DQH does
2385 // its own enqueueing. So, we ignore them!
2387 $handler = new DistribQueueHandler();
2388 $handler->handle($this);
2389 } catch (Exception $e) {
2390 common_log(LOG_ERR, "emergency redistribution resulted in " . $e->getMessage());
2392 // Re-throw so somebody smarter can handle it.
2399 $result = parent::insert();
2401 if ($result === false) {
2402 common_log_db_error($this, 'INSERT', __FILE__);
2403 // TRANS: Server exception thrown when a stored object entry cannot be saved.
2404 throw new ServerException('Could not save Notice');
2407 // Profile::hasRepeated() abuses pkeyGet(), so we
2408 // have to clear manually
2409 if (!empty($this->repeat_of)) {
2410 $c = self::memcache();
2412 $ck = self::multicacheKey('Notice',
2413 array('profile_id' => $this->profile_id,
2414 'repeat_of' => $this->repeat_of));
2419 // Update possibly ID-dependent columns: URI, conversation
2420 // (now that INSERT has added the notice's local id)
2421 $orig = clone($this);
2424 // We can only get here if it's a local notice, since remote notices
2425 // should've bailed out earlier due to lacking a URI.
2426 if (empty($this->uri)) {
2427 $this->uri = sprintf('%s%s=%d:%s=%s',
2429 'noticeId', $this->id,
2430 'objectType', $this->get_object_type(true));
2434 if ($changed && $this->update($orig) === false) {
2435 common_log_db_error($notice, 'UPDATE', __FILE__);
2436 // TRANS: Server exception thrown when a notice cannot be updated.
2437 throw new ServerException(_('Problem saving notice.'));
2440 $this->blowOnInsert();
2446 * Get the source of the notice
2448 * @return Notice_source $ns A notice source object. 'code' is the only attribute
2449 * guaranteed to be populated.
2451 function getSource()
2453 if (empty($this->source)) {
2457 $ns = new Notice_source();
2458 switch ($this->source) {
2465 $ns->code = $this->source;
2468 $ns = Notice_source::getKV($this->source);
2470 $ns = new Notice_source();
2471 $ns->code = $this->source;
2472 $app = Oauth_application::getKV('name', $this->source);
2474 $ns->name = $app->name;
2475 $ns->url = $app->source_url;
2485 * Determine whether the notice was locally created
2487 * @return boolean locality
2490 public function isLocal()
2492 return ($this->is_local == Notice::LOCAL_PUBLIC ||
2493 $this->is_local == Notice::LOCAL_NONPUBLIC);
2496 public function isRepeat()
2498 return !empty($this->repeat_of);
2502 * Get the list of hash tags saved with this notice.
2504 * @return array of strings
2506 public function getTags()
2510 $keypart = sprintf('notice:tags:%d', $this->id);
2512 $tagstr = self::cacheGet($keypart);
2514 if ($tagstr !== false) {
2515 $tags = explode(',', $tagstr);
2517 $tag = new Notice_tag();
2518 $tag->notice_id = $this->id;
2520 while ($tag->fetch()) {
2521 $tags[] = $tag->tag;
2524 self::cacheSet($keypart, implode(',', $tags));
2530 static private function utcDate($dt)
2532 $dateStr = date('d F Y H:i:s', strtotime($dt));
2533 $d = new DateTime($dateStr, new DateTimeZone('UTC'));
2534 return $d->format(DATE_W3C);
2538 * Look up the creation timestamp for a given notice ID, even
2539 * if it's been deleted.
2542 * @return mixed string recorded creation timestamp, or false if can't be found
2544 public static function getAsTimestamp($id)
2550 $notice = Notice::getKV('id', $id);
2552 return $notice->created;
2555 $deleted = Deleted_notice::getKV('id', $id);
2557 return $deleted->created;
2564 * Build an SQL 'where' fragment for timestamp-based sorting from a since_id
2565 * parameter, matching notices posted after the given one (exclusive).
2567 * If the referenced notice can't be found, will return false.
2570 * @param string $idField
2571 * @param string $createdField
2572 * @return mixed string or false if no match
2574 public static function whereSinceId($id, $idField='id', $createdField='created')
2576 $since = Notice::getAsTimestamp($id);
2578 return sprintf("($createdField = '%s' and $idField > %d) or ($createdField > '%s')", $since, $id, $since);
2584 * Build an SQL 'where' fragment for timestamp-based sorting from a since_id
2585 * parameter, matching notices posted after the given one (exclusive), and
2586 * if necessary add it to the data object's query.
2588 * @param DB_DataObject $obj
2590 * @param string $idField
2591 * @param string $createdField
2592 * @return mixed string or false if no match
2594 public static function addWhereSinceId(DB_DataObject $obj, $id, $idField='id', $createdField='created')
2596 $since = self::whereSinceId($id, $idField, $createdField);
2598 $obj->whereAdd($since);
2603 * Build an SQL 'where' fragment for timestamp-based sorting from a max_id
2604 * parameter, matching notices posted before the given one (inclusive).
2606 * If the referenced notice can't be found, will return false.
2609 * @param string $idField
2610 * @param string $createdField
2611 * @return mixed string or false if no match
2613 public static function whereMaxId($id, $idField='id', $createdField='created')
2615 $max = Notice::getAsTimestamp($id);
2617 return sprintf("($createdField < '%s') or ($createdField = '%s' and $idField <= %d)", $max, $max, $id);
2623 * Build an SQL 'where' fragment for timestamp-based sorting from a max_id
2624 * parameter, matching notices posted before the given one (inclusive), and
2625 * if necessary add it to the data object's query.
2627 * @param DB_DataObject $obj
2629 * @param string $idField
2630 * @param string $createdField
2631 * @return mixed string or false if no match
2633 public static function addWhereMaxId(DB_DataObject $obj, $id, $idField='id', $createdField='created')
2635 $max = self::whereMaxId($id, $idField, $createdField);
2637 $obj->whereAdd($max);
2643 return (($this->is_local != Notice::LOCAL_NONPUBLIC) &&
2644 ($this->is_local != Notice::GATEWAY));
2648 * Check that the given profile is allowed to read, respond to, or otherwise
2649 * act on this notice.
2651 * The $scope member is a bitmask of scopes, representing a logical AND of the
2652 * scope requirement. So, 0x03 (Notice::ADDRESSEE_SCOPE | Notice::SITE_SCOPE) means
2653 * "only visible to people who are mentioned in the notice AND are users on this site."
2654 * Users on the site who are not mentioned in the notice will not be able to see the
2657 * @param Profile $profile The profile to check; pass null to check for public/unauthenticated users.
2659 * @return boolean whether the profile is in the notice's scope
2661 function inScope(Profile $profile=null)
2663 if (is_null($profile)) {
2664 $keypart = sprintf('notice:in-scope-for:%d:null', $this->id);
2666 $keypart = sprintf('notice:in-scope-for:%d:%d', $this->id, $profile->id);
2669 $result = self::cacheGet($keypart);
2671 if ($result === false) {
2673 if (Event::handle('StartNoticeInScope', array($this, $profile, &$bResult))) {
2674 $bResult = $this->_inScope($profile);
2675 Event::handle('EndNoticeInScope', array($this, $profile, &$bResult));
2677 $result = ($bResult) ? 1 : 0;
2678 self::cacheSet($keypart, $result, 0, 300);
2681 return ($result == 1) ? true : false;
2684 protected function _inScope(Profile $profile=null)
2686 if (!is_null($this->scope)) {
2687 $scope = $this->scope;
2689 $scope = self::defaultScope();
2692 if ($scope == 0 && !$this->getProfile()->isPrivateStream()) { // Not scoping, so it is public.
2693 return !$this->isHiddenSpam($profile);
2696 // If there's scope, anon cannot be in scope
2697 if (empty($profile)) {
2701 // Author is always in scope
2702 if ($this->profile_id == $profile->id) {
2706 // Only for users on this site
2707 if (($scope & Notice::SITE_SCOPE) && !$profile->isLocal()) {
2711 // Only for users mentioned in the notice
2712 if ($scope & Notice::ADDRESSEE_SCOPE) {
2714 $reply = Reply::pkeyGet(array('notice_id' => $this->id,
2715 'profile_id' => $profile->id));
2717 if (!$reply instanceof Reply) {
2722 // Only for members of the given group
2723 if ($scope & Notice::GROUP_SCOPE) {
2725 // XXX: just query for the single membership
2727 $groups = $this->getGroups();
2731 foreach ($groups as $group) {
2732 if ($profile->isMember($group)) {
2743 if ($scope & Notice::FOLLOWER_SCOPE || $this->getProfile()->isPrivateStream()) {
2745 if (!Subscription::exists($profile, $this->getProfile())) {
2750 return !$this->isHiddenSpam($profile);
2753 function isHiddenSpam(Profile $profile=null) {
2755 // Hide posts by silenced users from everyone but moderators.
2757 if (common_config('notice', 'hidespam')) {
2760 $author = $this->getProfile();
2761 } catch(Exception $e) {
2762 // If we can't get an author, keep it hidden.
2763 // XXX: technically not spam, but, whatever.
2767 if ($author->hasRole(Profile_role::SILENCED)) {
2768 if (!$profile instanceof Profile || (($profile->id !== $author->id) && (!$profile->hasRight(Right::REVIEWSPAM)))) {
2777 public function getParent()
2779 $parent = Notice::getKV('id', $this->reply_to);
2781 if (!$parent instanceof Notice) {
2782 throw new ServerException('Notice has no parent');
2789 * Magic function called at serialize() time.
2791 * We use this to drop a couple process-specific references
2792 * from DB_DataObject which can cause trouble in future
2795 * @return array of variable names to include in serialization.
2800 $vars = parent::__sleep();
2801 $skip = array('_profile', '_groups', '_attachments', '_faves', '_replies', '_repeats');
2802 return array_diff($vars, $skip);
2805 static function defaultScope()
2807 $scope = common_config('notice', 'defaultscope');
2808 if (is_null($scope)) {
2809 if (common_config('site', 'private')) {
2818 static function fillProfiles(array $notices)
2820 $map = self::getProfiles($notices);
2821 foreach ($notices as $entry=>$notice) {
2823 if (array_key_exists($notice->profile_id, $map)) {
2824 $notice->_setProfile($map[$notice->profile_id]);
2826 } catch (NoProfileException $e) {
2827 common_log(LOG_WARNING, "Failed to fill profile in Notice with non-existing entry for profile_id: {$e->profile_id}");
2828 unset($notices[$entry]);
2832 return array_values($map);
2835 static function getProfiles(array &$notices)
2838 foreach ($notices as $notice) {
2839 $ids[] = $notice->profile_id;
2841 $ids = array_unique($ids);
2842 return Profile::pivotGet('id', $ids);
2845 static function fillGroups(array &$notices)
2847 $ids = self::_idsOf($notices);
2848 $gis = Group_inbox::listGet('notice_id', $ids);
2851 foreach ($gis as $id => $gi) {
2854 $gids[] = $g->group_id;
2858 $gids = array_unique($gids);
2859 $group = User_group::pivotGet('id', $gids);
2860 foreach ($notices as $notice)
2863 $gi = $gis[$notice->id];
2864 foreach ($gi as $g) {
2865 $grps[] = $group[$g->group_id];
2867 $notice->_setGroups($grps);
2871 static function _idsOf(array &$notices)
2874 foreach ($notices as $notice) {
2875 $ids[$notice->id] = true;
2877 return array_keys($ids);
2880 static function fillAttachments(array &$notices)
2882 $ids = self::_idsOf($notices);
2883 $f2pMap = File_to_post::listGet('post_id', $ids);
2885 foreach ($f2pMap as $noticeId => $f2ps) {
2886 foreach ($f2ps as $f2p) {
2887 $fileIds[] = $f2p->file_id;
2891 $fileIds = array_unique($fileIds);
2892 $fileMap = File::pivotGet('id', $fileIds);
2893 foreach ($notices as $notice)
2896 $f2ps = $f2pMap[$notice->id];
2897 foreach ($f2ps as $f2p) {
2898 $files[] = $fileMap[$f2p->file_id];
2900 $notice->_setAttachments($files);
2904 static function fillReplies(array &$notices)
2906 $ids = self::_idsOf($notices);
2907 $replyMap = Reply::listGet('notice_id', $ids);
2908 foreach ($notices as $notice) {
2909 $replies = $replyMap[$notice->id];
2911 foreach ($replies as $reply) {
2912 $ids[] = $reply->profile_id;
2914 $notice->_setReplies($ids);
2918 protected $_repeats = array();
2920 function getRepeats()
2922 if (isset($this->_repeats[$this->id])) {
2923 return $this->_repeats[$this->id];
2925 $repeatMap = Notice::listGet('repeat_of', array($this->id));
2926 $this->_setRepeats($repeatMap[$this->id]);
2927 return $this->_repeats[$this->id];
2930 function _setRepeats(array $repeats)
2932 $this->_repeats[$this->id] = $repeats;
2935 static function fillRepeats(array &$notices)
2937 $ids = self::_idsOf($notices);
2938 $repeatMap = Notice::listGet('repeat_of', $ids);
2939 foreach ($notices as $notice) {
2940 $repeats = $repeatMap[$notice->id];
2941 $notice->_setRepeats($repeats);