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 public function getUrl()
282 // The risk is we start having empty urls and non-http uris...
283 // and we can't really handle any other protocol right now.
285 case common_valid_http_url($this->url): // should we allow non-http/https URLs?
287 case $this->isLocal():
288 // let's generate a valid link to our locally available notice on demand
289 return common_local_url('shownotice', array('notice' => $this->id), null, null, false);
290 case common_valid_http_url($this->uri):
293 common_debug('No URL available for notice: id='.$this->id);
294 throw new InvalidUrlException($this->url);
298 public function get_object_type($canonical=false) {
300 ? ActivityObject::canonicalType($this->object_type)
301 : $this->object_type;
304 public static function getByUri($uri)
306 $notice = new Notice();
308 if (!$notice->find(true)) {
309 throw new NoResultException($notice);
315 * Extract #hashtags from this notice's content and save them to the database.
319 /* extract all #hastags */
320 $count = preg_match_all('/(?:^|\s)#([\pL\pN_\-\.]{1,64})/u', strtolower($this->content), $match);
325 /* Add them to the database */
326 return $this->saveKnownTags($match[1]);
330 * Record the given set of hash tags in the db for this notice.
331 * Given tag strings will be normalized and checked for dupes.
333 function saveKnownTags($hashtags)
335 //turn each into their canonical tag
336 //this is needed to remove dupes before saving e.g. #hash.tag = #hashtag
337 for($i=0; $i<count($hashtags); $i++) {
338 /* elide characters we don't want in the tag */
339 $hashtags[$i] = common_canonical_tag($hashtags[$i]);
342 foreach(array_unique($hashtags) as $hashtag) {
343 $this->saveTag($hashtag);
344 self::blow('profile:notice_ids_tagged:%d:%s', $this->profile_id, $hashtag);
350 * Record a single hash tag as associated with this notice.
351 * Tag format and uniqueness must be validated by caller.
353 function saveTag($hashtag)
355 $tag = new Notice_tag();
356 $tag->notice_id = $this->id;
357 $tag->tag = $hashtag;
358 $tag->created = $this->created;
359 $id = $tag->insert();
362 // TRANS: Server exception. %s are the error details.
363 throw new ServerException(sprintf(_('Database error inserting hashtag: %s.'),
364 $last_error->message));
368 // if it's saved, blow its cache
369 $tag->blowCache(false);
373 * Save a new notice and push it out to subscribers' inboxes.
374 * Poster's permissions are checked before sending.
376 * @param int $profile_id Profile ID of the poster
377 * @param string $content source message text; links may be shortened
378 * per current user's preference
379 * @param string $source source key ('web', 'api', etc)
380 * @param array $options Associative array of optional properties:
381 * string 'created' timestamp of notice; defaults to now
382 * int 'is_local' source/gateway ID, one of:
383 * Notice::LOCAL_PUBLIC - Local, ok to appear in public timeline
384 * Notice::REMOTE - Sent from a remote service;
385 * hide from public timeline but show in
386 * local "and friends" timelines
387 * Notice::LOCAL_NONPUBLIC - Local, but hide from public timeline
388 * Notice::GATEWAY - From another non-OStatus service;
389 * will not appear in public views
390 * float 'lat' decimal latitude for geolocation
391 * float 'lon' decimal longitude for geolocation
392 * int 'location_id' geoname identifier
393 * int 'location_ns' geoname namespace to interpret location_id
394 * int 'reply_to'; notice ID this is a reply to
395 * int 'repeat_of'; notice ID this is a repeat of
396 * string 'uri' unique ID for notice; a unique tag uri (can be url or anything too)
397 * string 'url' permalink to notice; defaults to local notice URL
398 * string 'rendered' rendered HTML version of content
399 * array 'replies' list of profile URIs for reply delivery in
400 * place of extracting @-replies from content.
401 * array 'groups' list of group IDs to deliver to, in place of
402 * extracting ! tags from content
403 * array 'tags' list of hashtag strings to save with the notice
404 * in place of extracting # tags from content
405 * array 'urls' list of attached/referred URLs to save with the
406 * notice in place of extracting links from content
407 * boolean 'distribute' whether to distribute the notice, default true
408 * string 'object_type' URL of the associated object type (default ActivityObject::NOTE)
409 * string 'verb' URL of the associated verb (default ActivityVerb::POST)
410 * int 'scope' Scope bitmask; default to SITE_SCOPE on private sites, 0 otherwise
412 * @fixme tag override
415 * @throws ClientException
417 static function saveNew($profile_id, $content, $source, array $options=null) {
418 $defaults = array('uri' => null,
423 'distribute' => true,
424 'object_type' => null,
427 if (!empty($options) && is_array($options)) {
428 $options = array_merge($defaults, $options);
434 if (!isset($is_local)) {
435 $is_local = Notice::LOCAL_PUBLIC;
438 $profile = Profile::getKV('id', $profile_id);
439 if (!$profile instanceof Profile) {
440 // TRANS: Client exception thrown when trying to save a notice for an unknown user.
441 throw new ClientException(_('Problem saving notice. Unknown user.'));
444 $user = User::getKV('id', $profile_id);
445 if ($user instanceof User) {
446 // Use the local user's shortening preferences, if applicable.
447 $final = $user->shortenLinks($content);
449 $final = common_shorten_links($content);
452 if (Notice::contentTooLong($final)) {
453 // TRANS: Client exception thrown if a notice contains too many characters.
454 throw new ClientException(_('Problem saving notice. Too long.'));
457 if (common_config('throttle', 'enabled') && !Notice::checkEditThrottle($profile_id)) {
458 common_log(LOG_WARNING, 'Excessive posting by profile #' . $profile_id . '; throttled.');
459 // TRANS: Client exception thrown when a user tries to post too many notices in a given time frame.
460 throw new ClientException(_('Too many notices too fast; take a breather '.
461 'and post again in a few minutes.'));
464 if (common_config('site', 'dupelimit') > 0 && !Notice::checkDupes($profile_id, $final)) {
465 common_log(LOG_WARNING, 'Dupe posting by profile #' . $profile_id . '; throttled.');
466 // TRANS: Client exception thrown when a user tries to post too many duplicate notices in a given time frame.
467 throw new ClientException(_('Too many duplicate messages too quickly;'.
468 ' take a breather and post again in a few minutes.'));
471 if (!$profile->hasRight(Right::NEWNOTICE)) {
472 common_log(LOG_WARNING, "Attempted post from user disallowed to post: " . $profile->nickname);
474 // TRANS: Client exception thrown when a user tries to post while being banned.
475 throw new ClientException(_('You are banned from posting notices on this site.'), 403);
478 $notice = new Notice();
479 $notice->profile_id = $profile_id;
481 $autosource = common_config('public', 'autosource');
483 // Sandboxed are non-false, but not 1, either
485 if (!$profile->hasRight(Right::PUBLICNOTICE) ||
486 ($source && $autosource && in_array($source, $autosource))) {
487 $notice->is_local = Notice::LOCAL_NONPUBLIC;
489 $notice->is_local = $is_local;
492 if (!empty($created)) {
493 $notice->created = $created;
495 $notice->created = common_sql_now();
498 if (!$notice->isLocal()) {
499 // Only do these checks for non-local notices. Local notices will generate these values later.
500 if (!common_valid_http_url($url)) {
501 common_debug('Bad notice URL: ['.$url.'], URI: ['.$uri.']. Cannot link back to original! This is normal for shared notices etc.');
504 throw new ServerException('No URI for remote notice. Cannot accept that.');
508 $notice->content = $final;
510 $notice->source = $source;
514 // Get the groups here so we can figure out replies and such
515 if (!isset($groups)) {
516 $groups = User_group::idsFromText($notice->content, $profile);
521 // Handle repeat case
523 if (isset($repeat_of)) {
525 // Check for a private one
527 $repeat = Notice::getKV('id', $repeat_of);
529 if (!($repeat instanceof Notice)) {
530 // TRANS: Client exception thrown in notice when trying to repeat a missing or deleted notice.
531 throw new ClientException(_('Cannot repeat; original notice is missing or deleted.'));
534 if ($profile->id == $repeat->profile_id) {
535 // TRANS: Client error displayed when trying to repeat an own notice.
536 throw new ClientException(_('You cannot repeat your own notice.'));
539 if ($repeat->scope != Notice::SITE_SCOPE &&
540 $repeat->scope != Notice::PUBLIC_SCOPE) {
541 // TRANS: Client error displayed when trying to repeat a non-public notice.
542 throw new ClientException(_('Cannot repeat a private notice.'), 403);
545 if (!$repeat->inScope($profile)) {
546 // The generic checks above should cover this, but let's be sure!
547 // TRANS: Client error displayed when trying to repeat a notice you cannot access.
548 throw new ClientException(_('Cannot repeat a notice you cannot read.'), 403);
551 if ($profile->hasRepeated($repeat)) {
552 // TRANS: Client error displayed when trying to repeat an already repeated notice.
553 throw new ClientException(_('You already repeated that notice.'));
556 $notice->repeat_of = $repeat->id;
557 $notice->conversation = $repeat->conversation;
561 // If $reply_to is specified, we check that it exists, and then
562 // return it if it does
563 if (!empty($reply_to)) {
564 $reply = Notice::getKV('id', $reply_to);
565 } elseif (in_array($source, array('xmpp', 'mail', 'sms'))) {
566 // If the source lacks capability of sending the "reply_to"
567 // metadata, let's try to find an inline replyto-reference.
568 $reply = self::getInlineReplyTo($profile, $final);
571 if ($reply instanceof Notice) {
572 if (!$reply->inScope($profile)) {
573 // TRANS: Client error displayed when trying to reply to a notice a the target has no access to.
574 // TRANS: %1$s is a user nickname, %2$d is a notice ID (number).
575 throw new ClientException(sprintf(_('%1$s has no access to notice %2$d.'),
576 $profile->nickname, $reply->id), 403);
579 // If it's a repeat, the reply_to should be to the original
580 if ($reply->isRepeat()) {
581 $notice->reply_to = $reply->repeat_of;
583 $notice->reply_to = $reply->id;
585 // But the conversation ought to be the same :)
586 $notice->conversation = $reply->conversation;
588 // If the original is private to a group, and notice has
589 // no group specified, make it to the same group(s)
591 if (empty($groups) && ($reply->scope & Notice::GROUP_SCOPE)) {
593 $replyGroups = $reply->getGroups();
594 foreach ($replyGroups as $group) {
595 if ($profile->isMember($group)) {
596 $groups[] = $group->id;
605 if (!empty($lat) && !empty($lon)) {
610 if (!empty($location_ns) && !empty($location_id)) {
611 $notice->location_id = $location_id;
612 $notice->location_ns = $location_ns;
615 if (!empty($rendered)) {
616 $notice->rendered = $rendered;
618 $notice->rendered = common_render_content($final, $notice);
622 if ($notice->isRepeat()) {
623 $notice->verb = ActivityVerb::SHARE;
624 $notice->object_type = ActivityObject::ACTIVITY;
626 $notice->verb = ActivityVerb::POST;
629 $notice->verb = $verb;
632 if (empty($object_type)) {
633 $notice->object_type = (empty($notice->reply_to)) ? ActivityObject::NOTE : ActivityObject::COMMENT;
635 $notice->object_type = $object_type;
638 if (is_null($scope) && $reply instanceof Notice) {
639 $notice->scope = $reply->scope;
641 $notice->scope = $scope;
644 $notice->scope = self::figureOutScope($profile, $groups, $notice->scope);
646 if (Event::handle('StartNoticeSave', array(&$notice))) {
648 // XXX: some of these functions write to the DB
651 $notice->insert(); // throws exception on failure
652 } catch (Exception $e) {
653 // Let's test if we managed initial insert, which would imply
654 // failing on some update-part (check 'insert()'). Delete if
655 // something had been stored to the database.
656 if (!empty($notice->id)) {
662 // Clear the cache for subscribed users, so they'll update at next request
663 // XXX: someone clever could prepend instead of clearing the cache
665 // Save per-notice metadata...
667 if (isset($replies)) {
668 $notice->saveKnownReplies($replies);
670 $notice->saveReplies();
674 $notice->saveKnownTags($tags);
679 // Note: groups may save tags, so must be run after tags are saved
680 // to avoid errors on duplicates.
681 // Note: groups should always be set.
683 $notice->saveKnownGroups($groups);
686 $notice->saveKnownUrls($urls);
692 // Prepare inbox delivery, may be queued to background.
693 $notice->distribute();
699 static function saveActivity(Activity $act, Profile $actor, array $options=array())
701 // First check if we're going to let this Activity through from the specific actor
702 if (!$actor->hasRight(Right::NEWNOTICE)) {
703 common_log(LOG_WARNING, "Attempted post from user disallowed to post: " . $actor->getNickname());
705 // TRANS: Client exception thrown when a user tries to post while being banned.
706 throw new ClientException(_m('You are banned from posting notices on this site.'), 403);
708 if (common_config('throttle', 'enabled') && !self::checkEditThrottle($actor->id)) {
709 common_log(LOG_WARNING, 'Excessive posting by profile #' . $actor->id . '; throttled.');
710 // TRANS: Client exception thrown when a user tries to post too many notices in a given time frame.
711 throw new ClientException(_m('Too many notices too fast; take a breather '.
712 'and post again in a few minutes.'));
715 /* This interferes with stuff like Favorites from old StatusNet installations (first object in objects is the favored notice)
716 // Get ActivityObject properties
717 $actobj = count($act->objects)==1 ? $act->objects[0] : null;
718 if (!is_null($actobj) && $actobj->id) {
719 $options['uri'] = $actobj->id;
721 $options['url'] = $actobj->link;
722 } elseif ($act->link) {
723 $options['url'] = $act->link;
724 } elseif (preg_match('!^https?://!', $actobj->id)) {
725 $options['url'] = $actobj->id;
729 $options['uri'] = $act->id;
730 $options['url'] = $act->link;
736 'is_local' => self::LOCAL_PUBLIC,
737 'mentions' => array(),
741 'source' => 'unknown',
746 'distribute' => true);
748 // options will have default values when nothing has been supplied
749 $options = array_merge($defaults, $options);
750 foreach (array_keys($defaults) as $key) {
751 // Only convert the keynames we specify ourselves from 'defaults' array into variables
752 $$key = $options[$key];
754 extract($options, EXTR_SKIP);
756 $stored = new Notice();
759 if ($stored->find()) {
760 common_debug('cannot create duplicate Notice URI: '.$stored->uri);
761 throw new Exception('Notice URI already exists');
765 $stored->profile_id = $actor->id;
766 $stored->source = $source;
769 $stored->verb = $act->verb;
771 // Use the local user's shortening preferences, if applicable.
772 $stored->rendered = $actor->isLocal()
773 ? $actor->shortenLinks($act->content)
775 $stored->content = common_strip_html($stored->rendered);
777 $autosource = common_config('public', 'autosource');
779 // Sandboxed are non-false, but not 1, either
780 if (!$actor->hasRight(Right::PUBLICNOTICE) ||
781 ($source && $autosource && in_array($source, $autosource))) {
782 $stored->is_local = Notice::LOCAL_NONPUBLIC;
785 // Maybe a missing act-time should be fatal if the actor is not local?
786 if (!empty($act->time)) {
787 $stored->created = common_sql_date($act->time);
789 $stored->created = common_sql_now();
793 if ($act->context instanceof ActivityContext && !empty($act->context->replyToID)) {
794 $reply = self::getKV('uri', $act->context->replyToID);
796 if (!$reply instanceof Notice && $act->target instanceof ActivityObject) {
797 $reply = self::getKV('uri', $act->target->id);
800 if ($reply instanceof Notice) {
801 if (!$reply->inScope($actor)) {
802 // TRANS: Client error displayed when trying to reply to a notice a the target has no access to.
803 // TRANS: %1$s is a user nickname, %2$d is a notice ID (number).
804 throw new ClientException(sprintf(_m('%1$s has no right to reply to notice %2$d.'), $actor->getNickname(), $reply->id), 403);
807 $stored->reply_to = $reply->id;
808 $stored->conversation = $reply->conversation;
810 // If the original is private to a group, and notice has no group specified,
811 // make it to the same group(s)
812 if (empty($groups) && ($reply->scope & Notice::GROUP_SCOPE)) {
814 $replyGroups = $reply->getGroups();
815 foreach ($replyGroups as $group) {
816 if ($actor->isMember($group)) {
817 $groups[] = $group->id;
822 if (is_null($scope)) {
823 $scope = $reply->scope;
827 if ($act->context instanceof ActivityContext) {
828 $location = $act->context->location;
830 $stored->lat = $location->lat;
831 $stored->lon = $location->lon;
832 if ($location->location_id) {
833 $stored->location_ns = $location->location_ns;
834 $stored->location_id = $location->location_id;
838 $act->context = new ActivityContext();
841 $stored->scope = self::figureOutScope($actor, $groups, $scope);
843 foreach ($act->categories as $cat) {
845 $term = common_canonical_tag($cat->term);
852 foreach ($act->enclosures as $href) {
853 // @todo FIXME: Save these locally or....?
857 if (Event::handle('StartNoticeSave', array(&$stored))) {
858 // XXX: some of these functions write to the DB
861 $stored->insert(); // throws exception on error
864 Event::handle('StoreActivityObject', array($act, $stored, $options, &$object));
865 if (empty($object)) {
866 throw new ServerException('No object from StoreActivityObject '.$stored->uri . ': '.$act->asString());
868 $orig = clone($stored);
869 $stored->object_type = ActivityUtils::resolveUri($object->getObjectType(), true);
870 $stored->update($orig);
871 } catch (Exception $e) {
872 if (empty($stored->id)) {
873 common_debug('Failed to save stored object entry in database ('.$e->getMessage().')');
875 common_debug('Failed to store activity object in database ('.$e->getMessage().'), deleting notice id '.$stored->id);
881 if (!$stored instanceof Notice) {
882 throw new ServerException('StartNoticeSave did not give back a Notice');
885 // Save per-notice metadata...
889 // This event lets plugins filter out non-local recipients (attentions we don't care about)
890 // Used primarily for OStatus (and if we don't federate, all attentions would be local anyway)
891 Event::handle('GetLocalAttentions', array($actor, $act->context->attention, &$mentions, &$groups));
893 if (!empty($mentions)) {
894 $stored->saveKnownReplies($mentions);
896 $stored->saveReplies();
900 $stored->saveKnownTags($tags);
905 // Note: groups may save tags, so must be run after tags are saved
906 // to avoid errors on duplicates.
907 // Note: groups should always be set.
909 $stored->saveKnownGroups($groups);
912 $stored->saveKnownUrls($urls);
918 // Prepare inbox delivery, may be queued to background.
919 $stored->distribute();
925 static public function figureOutScope(Profile $actor, array $groups, $scope=null) {
926 if (is_null($scope)) {
927 $scope = self::defaultScope();
930 // For private streams
932 $user = $actor->getUser();
933 // FIXME: We can't do bit comparison with == (Legacy StatusNet thing. Let's keep it for now.)
934 if ($user->private_stream && ($scope == Notice::PUBLIC_SCOPE || $scope == Notice::SITE_SCOPE)) {
935 $scope |= Notice::FOLLOWER_SCOPE;
937 } catch (NoSuchUserException $e) {
938 // TODO: Not a local user, so we don't know about scope preferences... yet!
941 // Force the scope for private groups
942 foreach ($groups as $group_id) {
943 $group = User_group::staticGet('id', $group_id);
944 if ($group instanceof User_group) {
945 if ($group->force_scope) {
946 $scope |= Notice::GROUP_SCOPE;
955 function blowOnInsert($conversation = false)
957 $this->blowStream('profile:notice_ids:%d', $this->profile_id);
959 if ($this->isPublic()) {
960 $this->blowStream('public');
963 self::blow('notice:list-ids:conversation:%s', $this->conversation);
964 self::blow('conversation:notice_count:%d', $this->conversation);
966 if ($this->isRepeat()) {
967 // XXX: we should probably only use one of these
968 $this->blowStream('notice:repeats:%d', $this->repeat_of);
969 self::blow('notice:list-ids:repeat_of:%d', $this->repeat_of);
972 $original = Notice::getKV('id', $this->repeat_of);
974 if ($original instanceof Notice) {
975 $originalUser = User::getKV('id', $original->profile_id);
976 if ($originalUser instanceof User) {
977 $this->blowStream('user:repeats_of_me:%d', $originalUser->id);
981 $profile = Profile::getKV($this->profile_id);
983 if ($profile instanceof Profile) {
984 $profile->blowNoticeCount();
987 $ptags = $this->getProfileTags();
988 foreach ($ptags as $ptag) {
989 $ptag->blowNoticeStreamCache();
994 * Clear cache entries related to this notice at delete time.
995 * Necessary to avoid breaking paging on public, profile timelines.
997 function blowOnDelete()
999 $this->blowOnInsert();
1001 self::blow('profile:notice_ids:%d;last', $this->profile_id);
1003 if ($this->isPublic()) {
1004 self::blow('public;last');
1007 self::blow('fave:by_notice', $this->id);
1009 if ($this->conversation) {
1010 // In case we're the first, will need to calc a new root.
1011 self::blow('notice:conversation_root:%d', $this->conversation);
1014 $ptags = $this->getProfileTags();
1015 foreach ($ptags as $ptag) {
1016 $ptag->blowNoticeStreamCache(true);
1020 function blowStream()
1022 $c = self::memcache();
1028 $args = func_get_args();
1030 $format = array_shift($args);
1032 $keyPart = vsprintf($format, $args);
1034 $cacheKey = Cache::key($keyPart);
1036 $c->delete($cacheKey);
1038 // delete the "last" stream, too, if this notice is
1039 // older than the top of that stream
1041 $lastKey = $cacheKey.';last';
1043 $lastStr = $c->get($lastKey);
1045 if ($lastStr !== false) {
1046 $window = explode(',', $lastStr);
1047 $lastID = $window[0];
1048 $lastNotice = Notice::getKV('id', $lastID);
1049 if (!$lastNotice instanceof Notice // just weird
1050 || strtotime($lastNotice->created) >= strtotime($this->created)) {
1051 $c->delete($lastKey);
1056 /** save all urls in the notice to the db
1058 * follow redirects and save all available file information
1059 * (mimetype, date, size, oembed, etc.)
1063 function saveUrls() {
1064 if (common_config('attachments', 'process_links')) {
1065 common_replace_urls_callback($this->content, array($this, 'saveUrl'), $this->id);
1070 * Save the given URLs as related links/attachments to the db
1072 * follow redirects and save all available file information
1073 * (mimetype, date, size, oembed, etc.)
1077 function saveKnownUrls($urls)
1079 if (common_config('attachments', 'process_links')) {
1080 // @fixme validation?
1081 foreach (array_unique($urls) as $url) {
1083 File::processNew($url, $this->id);
1084 } catch (ServerException $e) {
1085 // Could not save URL. Log it?
1094 function saveUrl($url, $notice_id) {
1096 File::processNew($url, $notice_id);
1097 } catch (ServerException $e) {
1098 // Could not save URL. Log it?
1102 static function checkDupes($profile_id, $content) {
1103 $profile = Profile::getKV($profile_id);
1104 if (!$profile instanceof Profile) {
1107 $notice = $profile->getNotices(0, CachingNoticeStream::CACHE_WINDOW);
1108 if (!empty($notice)) {
1110 while ($notice->fetch()) {
1111 if (time() - strtotime($notice->created) >= common_config('site', 'dupelimit')) {
1113 } else if ($notice->content == $content) {
1118 // If we get here, oldest item in cache window is not
1119 // old enough for dupe limit; do direct check against DB
1120 $notice = new Notice();
1121 $notice->profile_id = $profile_id;
1122 $notice->content = $content;
1123 $threshold = common_sql_date(time() - common_config('site', 'dupelimit'));
1124 $notice->whereAdd(sprintf("created > '%s'", $notice->escape($threshold)));
1126 $cnt = $notice->count();
1130 static function checkEditThrottle($profile_id) {
1131 $profile = Profile::getKV($profile_id);
1132 if (!$profile instanceof Profile) {
1135 // Get the Nth notice
1136 $notice = $profile->getNotices(common_config('throttle', 'count') - 1, 1);
1137 if ($notice && $notice->fetch()) {
1138 // If the Nth notice was posted less than timespan seconds ago
1139 if (time() - strtotime($notice->created) <= common_config('throttle', 'timespan')) {
1144 // Either not N notices in the stream, OR the Nth was not posted within timespan seconds
1148 protected $_attachments = array();
1150 function attachments() {
1151 if (isset($this->_attachments[$this->id])) {
1152 return $this->_attachments[$this->id];
1155 $f2ps = File_to_post::listGet('post_id', array($this->id));
1159 foreach ($f2ps[$this->id] as $f2p) {
1160 $ids[] = $f2p->file_id;
1163 $files = File::multiGet('id', $ids);
1165 $this->_attachments[$this->id] = $files->fetchAll();
1167 return $this->_attachments[$this->id];
1170 function _setAttachments($attachments)
1172 $this->_attachments[$this->id] = $attachments;
1175 function publicStream($offset=0, $limit=20, $since_id=0, $max_id=0)
1177 $stream = new PublicNoticeStream();
1178 return $stream->getNotices($offset, $limit, $since_id, $max_id);
1182 function conversationStream($id, $offset=0, $limit=20, $since_id=0, $max_id=0)
1184 $stream = new ConversationNoticeStream($id);
1186 return $stream->getNotices($offset, $limit, $since_id, $max_id);
1190 * Is this notice part of an active conversation?
1192 * @return boolean true if other messages exist in the same
1193 * conversation, false if this is the only one
1195 function hasConversation()
1197 if (!empty($this->conversation)) {
1198 $conversation = Notice::conversationStream(
1199 $this->conversation,
1204 if ($conversation->N > 0) {
1212 * Grab the earliest notice from this conversation.
1214 * @return Notice or null
1216 function conversationRoot($profile=-1)
1218 // XXX: can this happen?
1220 if (empty($this->conversation)) {
1224 // Get the current profile if not specified
1226 if (is_int($profile) && $profile == -1) {
1227 $profile = Profile::current();
1230 // If this notice is out of scope, no root for you!
1232 if (!$this->inScope($profile)) {
1236 // If this isn't a reply to anything, then it's its own
1239 if (empty($this->reply_to)) {
1243 if (is_null($profile)) {
1244 $keypart = sprintf('notice:conversation_root:%d:null', $this->id);
1246 $keypart = sprintf('notice:conversation_root:%d:%d',
1251 $root = self::cacheGet($keypart);
1253 if ($root !== false && $root->inScope($profile)) {
1260 $parent = $last->getParent();
1261 if ($parent->inScope($profile)) {
1265 } catch (Exception $e) {
1266 // Latest notice has no parent
1268 // No parent, or parent out of scope
1273 self::cacheSet($keypart, $root);
1279 * Pull up a full list of local recipients who will be getting
1280 * this notice in their inbox. Results will be cached, so don't
1281 * change the input data wily-nilly!
1283 * @param array $groups optional list of Group objects;
1284 * if left empty, will be loaded from group_inbox records
1285 * @param array $recipient optional list of reply profile ids
1286 * if left empty, will be loaded from reply records
1287 * @return array associating recipient user IDs with an inbox source constant
1289 function whoGets(array $groups=null, array $recipients=null)
1291 $c = self::memcache();
1294 $ni = $c->get(Cache::key('notice:who_gets:'.$this->id));
1295 if ($ni !== false) {
1300 if (is_null($recipients)) {
1301 $recipients = $this->getReplies();
1306 // Give plugins a chance to add folks in at start...
1307 if (Event::handle('StartNoticeWhoGets', array($this, &$ni))) {
1309 $users = $this->getSubscribedUsers();
1310 foreach ($users as $id) {
1311 $ni[$id] = NOTICE_INBOX_SOURCE_SUB;
1314 if (is_null($groups)) {
1315 $groups = $this->getGroups();
1317 foreach ($groups as $group) {
1318 $users = $group->getUserMembers();
1319 foreach ($users as $id) {
1320 if (!array_key_exists($id, $ni)) {
1321 $ni[$id] = NOTICE_INBOX_SOURCE_GROUP;
1326 $ptAtts = $this->getAttentionsFromProfileTags();
1327 foreach ($ptAtts as $key=>$val) {
1328 if (!array_key_exists($key, $ni)) {
1333 foreach ($recipients as $recipient) {
1334 if (!array_key_exists($recipient, $ni)) {
1335 $ni[$recipient] = NOTICE_INBOX_SOURCE_REPLY;
1339 // Exclude any deleted, non-local, or blocking recipients.
1340 $profile = $this->getProfile();
1341 $originalProfile = null;
1342 if ($this->isRepeat()) {
1343 // Check blocks against the original notice's poster as well.
1344 $original = Notice::getKV('id', $this->repeat_of);
1345 if ($original instanceof Notice) {
1346 $originalProfile = $original->getProfile();
1350 foreach ($ni as $id => $source) {
1352 $user = User::getKV('id', $id);
1353 if (!$user instanceof User ||
1354 $user->hasBlocked($profile) ||
1355 ($originalProfile && $user->hasBlocked($originalProfile))) {
1358 } catch (UserNoProfileException $e) {
1359 // User doesn't have a profile; invalid; skip them.
1364 // Give plugins a chance to filter out...
1365 Event::handle('EndNoticeWhoGets', array($this, &$ni));
1369 // XXX: pack this data better
1370 $c->set(Cache::key('notice:who_gets:'.$this->id), $ni);
1376 function getSubscribedUsers()
1380 if(common_config('db','quote_identifiers'))
1381 $user_table = '"user"';
1382 else $user_table = 'user';
1386 'FROM '. $user_table .' JOIN subscription '.
1387 'ON '. $user_table .'.id = subscription.subscriber ' .
1388 'WHERE subscription.subscribed = %d ';
1390 $user->query(sprintf($qry, $this->profile_id));
1394 while ($user->fetch()) {
1403 function getProfileTags()
1405 $profile = $this->getProfile();
1406 $list = $profile->getOtherTags($profile);
1409 while($list->fetch()) {
1410 $ptags[] = clone($list);
1416 public function getAttentionsFromProfileTags()
1419 $ptags = $this->getProfileTags();
1420 foreach ($ptags as $ptag) {
1421 $users = $ptag->getUserSubscribers();
1422 foreach ($users as $id) {
1423 $ni[$id] = NOTICE_INBOX_SOURCE_PROFILE_TAG;
1430 * Record this notice to the given group inboxes for delivery.
1431 * Overrides the regular parsing of !group markup.
1433 * @param string $group_ids
1434 * @fixme might prefer URIs as identifiers, as for replies?
1435 * best with generalizations on user_group to support
1436 * remote groups better.
1438 function saveKnownGroups($group_ids)
1440 if (!is_array($group_ids)) {
1441 // TRANS: Server exception thrown when no array is provided to the method saveKnownGroups().
1442 throw new ServerException(_('Bad type provided to saveKnownGroups.'));
1446 foreach (array_unique($group_ids) as $id) {
1447 $group = User_group::getKV('id', $id);
1448 if ($group instanceof User_group) {
1449 common_log(LOG_ERR, "Local delivery to group id $id, $group->nickname");
1450 $result = $this->addToGroupInbox($group);
1452 common_log_db_error($gi, 'INSERT', __FILE__);
1455 if (common_config('group', 'addtag')) {
1456 // we automatically add a tag for every group name, too
1458 $tag = Notice_tag::pkeyGet(array('tag' => common_canonical_tag($group->nickname),
1459 'notice_id' => $this->id));
1461 if (is_null($tag)) {
1462 $this->saveTag($group->nickname);
1466 $groups[] = clone($group);
1468 common_log(LOG_ERR, "Local delivery to group id $id skipped, doesn't exist");
1475 function addToGroupInbox(User_group $group)
1477 $gi = Group_inbox::pkeyGet(array('group_id' => $group->id,
1478 'notice_id' => $this->id));
1480 if (!$gi instanceof Group_inbox) {
1482 $gi = new Group_inbox();
1484 $gi->group_id = $group->id;
1485 $gi->notice_id = $this->id;
1486 $gi->created = $this->created;
1488 $result = $gi->insert();
1491 common_log_db_error($gi, 'INSERT', __FILE__);
1492 // TRANS: Server exception thrown when an update for a group inbox fails.
1493 throw new ServerException(_('Problem saving group inbox.'));
1496 self::blow('user_group:notice_ids:%d', $gi->group_id);
1503 * Save reply records indicating that this notice needs to be
1504 * delivered to the local users with the given URIs.
1506 * Since this is expected to be used when saving foreign-sourced
1507 * messages, we won't deliver to any remote targets as that's the
1508 * source service's responsibility.
1510 * Mail notifications etc will be handled later.
1512 * @param array $uris Array of unique identifier URIs for recipients
1514 function saveKnownReplies(array $uris)
1520 $sender = Profile::getKV($this->profile_id);
1522 foreach (array_unique($uris) as $uri) {
1524 $profile = Profile::fromUri($uri);
1525 } catch (UnknownUriException $e) {
1526 common_log(LOG_WARNING, "Unable to determine profile for URI '$uri'");
1530 if ($profile->hasBlocked($sender)) {
1531 common_log(LOG_INFO, "Not saving reply to profile {$profile->id} ($uri) from sender {$sender->id} because of a block.");
1535 $this->saveReply($profile->id);
1536 self::blow('reply:stream:%d', $profile->id);
1543 * Pull @-replies from this message's content in StatusNet markup format
1544 * and save reply records indicating that this message needs to be
1545 * delivered to those users.
1547 * Mail notifications to local profiles will be sent later.
1549 * @return array of integer profile IDs
1552 function saveReplies()
1554 // Don't save reply data for repeats
1556 if ($this->isRepeat()) {
1560 $sender = $this->getProfile();
1564 // If it's a reply, save for the replied-to author
1566 $parent = $this->getParent();
1567 $parentauthor = $parent->getProfile();
1568 $this->saveReply($parentauthor->id);
1569 $replied[$parentauthor->id] = 1;
1570 self::blow('reply:stream:%d', $parentauthor->id);
1571 } catch (Exception $e) {
1572 // Not a reply, since it has no parent!
1575 // @todo ideally this parser information would only
1576 // be calculated once.
1578 $mentions = common_find_mentions($this->content, $this);
1580 // store replied only for first @ (what user/notice what the reply directed,
1581 // we assume first @ is it)
1583 foreach ($mentions as $mention) {
1585 foreach ($mention['mentioned'] as $mentioned) {
1587 // skip if they're already covered
1589 if (!empty($replied[$mentioned->id])) {
1593 // Don't save replies from blocked profile to local user
1595 $mentioned_user = User::getKV('id', $mentioned->id);
1596 if ($mentioned_user instanceof User && $mentioned_user->hasBlocked($sender)) {
1600 $this->saveReply($mentioned->id);
1601 $replied[$mentioned->id] = 1;
1602 self::blow('reply:stream:%d', $mentioned->id);
1606 $recipientIds = array_keys($replied);
1608 return $recipientIds;
1611 function saveReply($profileId)
1613 $reply = new Reply();
1615 $reply->notice_id = $this->id;
1616 $reply->profile_id = $profileId;
1617 $reply->modified = $this->created;
1624 protected $_replies = array();
1627 * Pull the complete list of @-reply targets for this notice.
1629 * @return array of integer profile ids
1631 function getReplies()
1633 if (isset($this->_replies[$this->id])) {
1634 return $this->_replies[$this->id];
1637 $replyMap = Reply::listGet('notice_id', array($this->id));
1641 foreach ($replyMap[$this->id] as $reply) {
1642 $ids[] = $reply->profile_id;
1645 $this->_replies[$this->id] = $ids;
1650 function _setReplies($replies)
1652 $this->_replies[$this->id] = $replies;
1656 * Pull the complete list of @-reply targets for this notice.
1658 * @return array of Profiles
1660 function getReplyProfiles()
1662 $ids = $this->getReplies();
1664 $profiles = Profile::multiGet('id', $ids);
1666 return $profiles->fetchAll();
1670 * Send e-mail notifications to local @-reply targets.
1672 * Replies must already have been saved; this is expected to be run
1673 * from the distrib queue handler.
1675 function sendReplyNotifications()
1677 // Don't send reply notifications for repeats
1679 if ($this->isRepeat()) {
1683 $recipientIds = $this->getReplies();
1684 if (Event::handle('StartNotifyMentioned', array($this, &$recipientIds))) {
1685 require_once INSTALLDIR.'/lib/mail.php';
1687 foreach ($recipientIds as $recipientId) {
1688 $user = User::getKV('id', $recipientId);
1689 if ($user instanceof User) {
1690 mail_notify_attn($user, $this);
1693 Event::handle('EndNotifyMentioned', array($this, $recipientIds));
1698 * Pull list of groups this notice needs to be delivered to,
1699 * as previously recorded by saveKnownGroups().
1701 * @return array of Group objects
1704 protected $_groups = array();
1706 function getGroups()
1708 // Don't save groups for repeats
1710 if (!empty($this->repeat_of)) {
1714 if (isset($this->_groups[$this->id])) {
1715 return $this->_groups[$this->id];
1718 $gis = Group_inbox::listGet('notice_id', array($this->id));
1722 foreach ($gis[$this->id] as $gi)
1724 $ids[] = $gi->group_id;
1727 $groups = User_group::multiGet('id', $ids);
1729 $this->_groups[$this->id] = $groups->fetchAll();
1731 return $this->_groups[$this->id];
1734 function _setGroups($groups)
1736 $this->_groups[$this->id] = $groups;
1740 * Convert a notice into an activity for export.
1742 * @param User $cur Current user
1744 * @return Activity activity object representing this Notice.
1747 function asActivity($cur=null)
1749 $act = self::cacheGet(Cache::codeKey('notice:as-activity:'.$this->id));
1751 if ($act instanceof Activity) {
1754 $act = new Activity();
1756 if (Event::handle('StartNoticeAsActivity', array($this, &$act))) {
1758 $act->id = $this->uri;
1759 $act->time = strtotime($this->created);
1761 $act->link = $this->getUrl();
1762 } catch (InvalidUrlException $e) {
1763 // The notice is probably a share or similar, which don't
1764 // have a representational URL of their own.
1766 $act->content = common_xml_safe_str($this->rendered);
1768 $profile = $this->getProfile();
1770 $act->actor = $profile->asActivityObject();
1771 $act->actor->extra[] = $profile->profileInfo($cur);
1773 $act->verb = $this->verb;
1775 if ($this->repeat_of) {
1776 $repeated = Notice::getKV('id', $this->repeat_of);
1777 if ($repeated instanceof Notice) {
1778 $act->objects[] = $repeated->asActivity($cur);
1781 $act->objects[] = $this->asActivityObject();
1784 // XXX: should this be handled by default processing for object entry?
1788 $tags = $this->getTags();
1790 foreach ($tags as $tag) {
1791 $cat = new AtomCategory();
1794 $act->categories[] = $cat;
1798 // XXX: use Atom Media and/or File activity objects instead
1800 $attachments = $this->attachments();
1802 foreach ($attachments as $attachment) {
1803 // Save local attachments
1804 if (!empty($attachment->filename)) {
1805 $act->attachments[] = ActivityObject::fromFile($attachment);
1809 $ctx = new ActivityContext();
1812 $reply = $this->getParent();
1813 $ctx->replyToID = $reply->getUri();
1814 $ctx->replyToUrl = $reply->getUrl();
1815 } catch (Exception $e) {
1816 // This is not a reply to something
1819 $ctx->location = $this->getLocation();
1823 if (!empty($this->conversation)) {
1824 $conv = Conversation::getKV('id', $this->conversation);
1825 if ($conv instanceof Conversation) {
1826 $ctx->conversation = $conv->uri;
1830 $reply_ids = $this->getReplies();
1832 foreach ($reply_ids as $id) {
1833 $rprofile = Profile::getKV('id', $id);
1834 if ($rprofile instanceof Profile) {
1835 $ctx->attention[$rprofile->getUri()] = ActivityObject::PERSON;
1839 $groups = $this->getGroups();
1841 foreach ($groups as $group) {
1842 $ctx->attention[$group->getUri()] = ActivityObject::GROUP;
1845 switch ($this->scope) {
1846 case Notice::PUBLIC_SCOPE:
1847 $ctx->attention[ActivityContext::ATTN_PUBLIC] = ActivityObject::COLLECTION;
1849 case Notice::FOLLOWER_SCOPE:
1850 $surl = common_local_url("subscribers", array('nickname' => $profile->nickname));
1851 $ctx->attention[$surl] = ActivityObject::COLLECTION;
1855 $act->context = $ctx;
1857 $source = $this->getSource();
1859 if ($source instanceof Notice_source) {
1860 $act->generator = ActivityObject::fromNoticeSource($source);
1865 $atom_feed = $profile->getAtomFeed();
1867 if (!empty($atom_feed)) {
1869 $act->source = new ActivitySource();
1871 // XXX: we should store the actual feed ID
1873 $act->source->id = $atom_feed;
1875 // XXX: we should store the actual feed title
1877 $act->source->title = $profile->getBestName();
1879 $act->source->links['alternate'] = $profile->profileurl;
1880 $act->source->links['self'] = $atom_feed;
1882 $act->source->icon = $profile->avatarUrl(AVATAR_PROFILE_SIZE);
1884 $notice = $profile->getCurrentNotice();
1886 if ($notice instanceof Notice) {
1887 $act->source->updated = self::utcDate($notice->created);
1890 $user = User::getKV('id', $profile->id);
1892 if ($user instanceof User) {
1893 $act->source->links['license'] = common_config('license', 'url');
1897 if ($this->isLocal()) {
1898 $act->selfLink = common_local_url('ApiStatusesShow', array('id' => $this->id,
1899 'format' => 'atom'));
1900 $act->editLink = $act->selfLink;
1903 Event::handle('EndNoticeAsActivity', array($this, &$act));
1906 self::cacheSet(Cache::codeKey('notice:as-activity:'.$this->id), $act);
1911 // This has gotten way too long. Needs to be sliced up into functional bits
1912 // or ideally exported to a utility class.
1914 function asAtomEntry($namespace=false,
1919 $act = $this->asActivity($cur);
1920 $act->extra[] = $this->noticeInfo($cur);
1921 return $act->asString($namespace, $author, $source);
1925 * Extra notice info for atom entries
1927 * Clients use some extra notice info in the atom stream.
1928 * This gives it to them.
1930 * @param User $cur Current user
1932 * @return array representation of <statusnet:notice_info> element
1935 function noticeInfo($cur)
1937 // local notice ID (useful to clients for ordering)
1939 $noticeInfoAttr = array('local_id' => $this->id);
1943 $ns = $this->getSource();
1945 if ($ns instanceof Notice_source) {
1946 $noticeInfoAttr['source'] = $ns->code;
1947 if (!empty($ns->url)) {
1948 $noticeInfoAttr['source_link'] = $ns->url;
1949 if (!empty($ns->name)) {
1950 $noticeInfoAttr['source'] = '<a href="'
1951 . htmlspecialchars($ns->url)
1952 . '" rel="nofollow">'
1953 . htmlspecialchars($ns->name)
1959 // favorite and repeated
1963 $scoped = $cur->getProfile();
1964 $noticeInfoAttr['repeated'] = ($scoped->hasRepeated($this)) ? "true" : "false";
1967 if (!empty($this->repeat_of)) {
1968 $noticeInfoAttr['repeat_of'] = $this->repeat_of;
1971 Event::handle('StatusNetApiNoticeInfo', array($this, &$noticeInfoAttr, $scoped));
1973 return array('statusnet:notice_info', $noticeInfoAttr, null);
1977 * Returns an XML string fragment with a reference to a notice as an
1978 * Activity Streams noun object with the given element type.
1980 * Assumes that 'activity' namespace has been previously defined.
1982 * @param string $element one of 'subject', 'object', 'target'
1986 function asActivityNoun($element)
1988 $noun = $this->asActivityObject();
1989 return $noun->asString('activity:' . $element);
1992 public function asActivityObject()
1994 $object = new ActivityObject();
1996 if (Event::handle('StartActivityObjectFromNotice', array($this, &$object))) {
1997 $object->type = $this->object_type ?: ActivityObject::NOTE;
1998 $object->id = $this->getUri();
1999 $object->title = sprintf('New %1$s by %2$s', ActivityObject::canonicalType($object->type), $this->getProfile()->getNickname());
2000 $object->content = $this->rendered;
2001 $object->link = $this->getUrl();
2003 $object->extra[] = array('status_net', array('notice_id' => $this->id));
2005 Event::handle('EndActivityObjectFromNotice', array($this, &$object));
2012 * Determine which notice, if any, a new notice is in reply to.
2014 * For conversation tracking, we try to see where this notice fits
2015 * in the tree. Beware that this may very well give false positives
2016 * and add replies to wrong threads (if there have been newer posts
2017 * by the same user as we're replying to).
2019 * @param Profile $sender Author profile
2020 * @param string $content Final notice content
2022 * @return integer ID of replied-to notice, or null for not a reply.
2025 static function getInlineReplyTo(Profile $sender, $content)
2027 // Is there an initial @ or T?
2028 if (preg_match('/^T ([A-Z0-9]{1,64}) /', $content, $match)
2029 || preg_match('/^@([a-z0-9]{1,64})\s+/', $content, $match)) {
2030 $nickname = common_canonical_nickname($match[1]);
2035 // Figure out who that is.
2036 $recipient = common_relative_profile($sender, $nickname, common_sql_now());
2038 if ($recipient instanceof Profile) {
2039 // Get their last notice
2040 $last = $recipient->getCurrentNotice();
2041 if ($last instanceof Notice) {
2044 // Maybe in the future we want to handle something else below
2045 // so don't return getCurrentNotice() immediately.
2051 static function maxContent()
2053 $contentlimit = common_config('notice', 'contentlimit');
2054 // null => use global limit (distinct from 0!)
2055 if (is_null($contentlimit)) {
2056 $contentlimit = common_config('site', 'textlimit');
2058 return $contentlimit;
2061 static function contentTooLong($content)
2063 $contentlimit = self::maxContent();
2064 return ($contentlimit > 0 && !empty($content) && (mb_strlen($content) > $contentlimit));
2067 function getLocation()
2071 if (!empty($this->location_id) && !empty($this->location_ns)) {
2072 $location = Location::fromId($this->location_id, $this->location_ns);
2075 if (is_null($location)) { // no ID, or Location::fromId() failed
2076 if (!empty($this->lat) && !empty($this->lon)) {
2077 $location = Location::fromLatLon($this->lat, $this->lon);
2085 * Convenience function for posting a repeat of an existing message.
2087 * @param Profile $repeater Profile which is doing the repeat
2088 * @param string $source: posting source key, eg 'web', 'api', etc
2091 * @throws Exception on failure or permission problems
2093 function repeat(Profile $repeater, $source)
2095 $author = $this->getProfile();
2097 // TRANS: Message used to repeat a notice. RT is the abbreviation of 'retweet'.
2098 // TRANS: %1$s is the repeated user's name, %2$s is the repeated notice.
2099 $content = sprintf(_('RT @%1$s %2$s'),
2100 $author->getNickname(),
2103 // Scope is same as this one's
2104 return self::saveNew($repeater->id,
2107 array('repeat_of' => $this->id,
2108 'scope' => $this->scope));
2111 // These are supposed to be in chron order!
2113 function repeatStream($limit=100)
2115 $cache = Cache::instance();
2117 if (empty($cache)) {
2118 $ids = $this->_repeatStreamDirect($limit);
2120 $idstr = $cache->get(Cache::key('notice:repeats:'.$this->id));
2121 if ($idstr !== false) {
2122 if (empty($idstr)) {
2125 $ids = explode(',', $idstr);
2128 $ids = $this->_repeatStreamDirect(100);
2129 $cache->set(Cache::key('notice:repeats:'.$this->id), implode(',', $ids));
2132 // We do a max of 100, so slice down to limit
2133 $ids = array_slice($ids, 0, $limit);
2137 return NoticeStream::getStreamByIds($ids);
2140 function _repeatStreamDirect($limit)
2142 $notice = new Notice();
2144 $notice->selectAdd(); // clears it
2145 $notice->selectAdd('id');
2147 $notice->repeat_of = $this->id;
2149 $notice->orderBy('created, id'); // NB: asc!
2151 if (!is_null($limit)) {
2152 $notice->limit(0, $limit);
2155 return $notice->fetchAll('id');
2158 function locationOptions($lat, $lon, $location_id, $location_ns, $profile = null)
2162 if (!empty($location_id) && !empty($location_ns)) {
2163 $options['location_id'] = $location_id;
2164 $options['location_ns'] = $location_ns;
2166 $location = Location::fromId($location_id, $location_ns);
2168 if ($location instanceof Location) {
2169 $options['lat'] = $location->lat;
2170 $options['lon'] = $location->lon;
2173 } else if (!empty($lat) && !empty($lon)) {
2174 $options['lat'] = $lat;
2175 $options['lon'] = $lon;
2177 $location = Location::fromLatLon($lat, $lon);
2179 if ($location instanceof Location) {
2180 $options['location_id'] = $location->location_id;
2181 $options['location_ns'] = $location->location_ns;
2183 } else if (!empty($profile)) {
2184 if (isset($profile->lat) && isset($profile->lon)) {
2185 $options['lat'] = $profile->lat;
2186 $options['lon'] = $profile->lon;
2189 if (isset($profile->location_id) && isset($profile->location_ns)) {
2190 $options['location_id'] = $profile->location_id;
2191 $options['location_ns'] = $profile->location_ns;
2198 function clearAttentions()
2200 $att = new Attention();
2201 $att->notice_id = $this->getID();
2204 while ($att->fetch()) {
2205 // Can't do delete() on the object directly since it won't remove all of it
2206 $other = clone($att);
2212 function clearReplies()
2214 $replyNotice = new Notice();
2215 $replyNotice->reply_to = $this->id;
2217 //Null any notices that are replies to this notice
2219 if ($replyNotice->find()) {
2220 while ($replyNotice->fetch()) {
2221 $orig = clone($replyNotice);
2222 $replyNotice->reply_to = null;
2223 $replyNotice->update($orig);
2229 $reply = new Reply();
2230 $reply->notice_id = $this->id;
2232 if ($reply->find()) {
2233 while($reply->fetch()) {
2234 self::blow('reply:stream:%d', $reply->profile_id);
2242 function clearFiles()
2244 $f2p = new File_to_post();
2246 $f2p->post_id = $this->id;
2249 while ($f2p->fetch()) {
2253 // FIXME: decide whether to delete File objects
2254 // ...and related (actual) files
2257 function clearRepeats()
2259 $repeatNotice = new Notice();
2260 $repeatNotice->repeat_of = $this->id;
2262 //Null any notices that are repeats of this notice
2264 if ($repeatNotice->find()) {
2265 while ($repeatNotice->fetch()) {
2266 $orig = clone($repeatNotice);
2267 $repeatNotice->repeat_of = null;
2268 $repeatNotice->update($orig);
2273 function clearTags()
2275 $tag = new Notice_tag();
2276 $tag->notice_id = $this->id;
2279 while ($tag->fetch()) {
2280 self::blow('profile:notice_ids_tagged:%d:%s', $this->profile_id, Cache::keyize($tag->tag));
2281 self::blow('profile:notice_ids_tagged:%d:%s;last', $this->profile_id, Cache::keyize($tag->tag));
2282 self::blow('notice_tag:notice_ids:%s', Cache::keyize($tag->tag));
2283 self::blow('notice_tag:notice_ids:%s;last', Cache::keyize($tag->tag));
2291 function clearGroupInboxes()
2293 $gi = new Group_inbox();
2295 $gi->notice_id = $this->id;
2298 while ($gi->fetch()) {
2299 self::blow('user_group:notice_ids:%d', $gi->group_id);
2307 function distribute()
2309 // We always insert for the author so they don't
2311 Event::handle('StartNoticeDistribute', array($this));
2313 // If there's a failure, we want to _force_
2314 // distribution at this point.
2316 $qm = QueueManager::get();
2317 $qm->enqueue($this, 'distrib');
2318 } catch (Exception $e) {
2319 // If the exception isn't transient, this
2320 // may throw more exceptions as DQH does
2321 // its own enqueueing. So, we ignore them!
2323 $handler = new DistribQueueHandler();
2324 $handler->handle($this);
2325 } catch (Exception $e) {
2326 common_log(LOG_ERR, "emergency redistribution resulted in " . $e->getMessage());
2328 // Re-throw so somebody smarter can handle it.
2335 $result = parent::insert();
2337 if ($result === false) {
2338 common_log_db_error($this, 'INSERT', __FILE__);
2339 // TRANS: Server exception thrown when a stored object entry cannot be saved.
2340 throw new ServerException('Could not save Notice');
2343 // Profile::hasRepeated() abuses pkeyGet(), so we
2344 // have to clear manually
2345 if (!empty($this->repeat_of)) {
2346 $c = self::memcache();
2348 $ck = self::multicacheKey('Notice',
2349 array('profile_id' => $this->profile_id,
2350 'repeat_of' => $this->repeat_of));
2355 // Update possibly ID-dependent columns: URI, conversation
2356 // (now that INSERT has added the notice's local id)
2357 $orig = clone($this);
2360 // We can only get here if it's a local notice, since remote notices
2361 // should've bailed out earlier due to lacking a URI.
2362 if (empty($this->uri)) {
2363 $this->uri = sprintf('%s%s=%d:%s=%s',
2365 'noticeId', $this->id,
2366 'objectType', $this->get_object_type(true));
2370 // If it's not part of a conversation, it's
2371 // the beginning of a new conversation.
2372 if (empty($this->conversation)) {
2373 $conv = Conversation::create($this);
2374 $this->conversation = $conv->id;
2378 if ($changed && $this->update($orig) === false) {
2379 common_log_db_error($notice, 'UPDATE', __FILE__);
2380 // TRANS: Server exception thrown when a notice cannot be updated.
2381 throw new ServerException(_('Problem saving notice.'));
2384 $this->blowOnInsert();
2390 * Get the source of the notice
2392 * @return Notice_source $ns A notice source object. 'code' is the only attribute
2393 * guaranteed to be populated.
2395 function getSource()
2397 $ns = new Notice_source();
2398 if (!empty($this->source)) {
2399 switch ($this->source) {
2406 $ns->code = $this->source;
2409 $ns = Notice_source::getKV($this->source);
2411 $ns = new Notice_source();
2412 $ns->code = $this->source;
2413 $app = Oauth_application::getKV('name', $this->source);
2415 $ns->name = $app->name;
2416 $ns->url = $app->source_url;
2426 * Determine whether the notice was locally created
2428 * @return boolean locality
2431 public function isLocal()
2433 return ($this->is_local == Notice::LOCAL_PUBLIC ||
2434 $this->is_local == Notice::LOCAL_NONPUBLIC);
2437 public function isRepeat()
2439 return !empty($this->repeat_of);
2443 * Get the list of hash tags saved with this notice.
2445 * @return array of strings
2447 public function getTags()
2451 $keypart = sprintf('notice:tags:%d', $this->id);
2453 $tagstr = self::cacheGet($keypart);
2455 if ($tagstr !== false) {
2456 $tags = explode(',', $tagstr);
2458 $tag = new Notice_tag();
2459 $tag->notice_id = $this->id;
2461 while ($tag->fetch()) {
2462 $tags[] = $tag->tag;
2465 self::cacheSet($keypart, implode(',', $tags));
2471 static private function utcDate($dt)
2473 $dateStr = date('d F Y H:i:s', strtotime($dt));
2474 $d = new DateTime($dateStr, new DateTimeZone('UTC'));
2475 return $d->format(DATE_W3C);
2479 * Look up the creation timestamp for a given notice ID, even
2480 * if it's been deleted.
2483 * @return mixed string recorded creation timestamp, or false if can't be found
2485 public static function getAsTimestamp($id)
2491 $notice = Notice::getKV('id', $id);
2493 return $notice->created;
2496 $deleted = Deleted_notice::getKV('id', $id);
2498 return $deleted->created;
2505 * Build an SQL 'where' fragment for timestamp-based sorting from a since_id
2506 * parameter, matching notices posted after the given one (exclusive).
2508 * If the referenced notice can't be found, will return false.
2511 * @param string $idField
2512 * @param string $createdField
2513 * @return mixed string or false if no match
2515 public static function whereSinceId($id, $idField='id', $createdField='created')
2517 $since = Notice::getAsTimestamp($id);
2519 return sprintf("($createdField = '%s' and $idField > %d) or ($createdField > '%s')", $since, $id, $since);
2525 * Build an SQL 'where' fragment for timestamp-based sorting from a since_id
2526 * parameter, matching notices posted after the given one (exclusive), and
2527 * if necessary add it to the data object's query.
2529 * @param DB_DataObject $obj
2531 * @param string $idField
2532 * @param string $createdField
2533 * @return mixed string or false if no match
2535 public static function addWhereSinceId(DB_DataObject $obj, $id, $idField='id', $createdField='created')
2537 $since = self::whereSinceId($id, $idField, $createdField);
2539 $obj->whereAdd($since);
2544 * Build an SQL 'where' fragment for timestamp-based sorting from a max_id
2545 * parameter, matching notices posted before the given one (inclusive).
2547 * If the referenced notice can't be found, will return false.
2550 * @param string $idField
2551 * @param string $createdField
2552 * @return mixed string or false if no match
2554 public static function whereMaxId($id, $idField='id', $createdField='created')
2556 $max = Notice::getAsTimestamp($id);
2558 return sprintf("($createdField < '%s') or ($createdField = '%s' and $idField <= %d)", $max, $max, $id);
2564 * Build an SQL 'where' fragment for timestamp-based sorting from a max_id
2565 * parameter, matching notices posted before the given one (inclusive), and
2566 * if necessary add it to the data object's query.
2568 * @param DB_DataObject $obj
2570 * @param string $idField
2571 * @param string $createdField
2572 * @return mixed string or false if no match
2574 public static function addWhereMaxId(DB_DataObject $obj, $id, $idField='id', $createdField='created')
2576 $max = self::whereMaxId($id, $idField, $createdField);
2578 $obj->whereAdd($max);
2584 if (common_config('public', 'localonly')) {
2585 return ($this->is_local == Notice::LOCAL_PUBLIC);
2587 return (($this->is_local != Notice::LOCAL_NONPUBLIC) &&
2588 ($this->is_local != Notice::GATEWAY));
2593 * Check that the given profile is allowed to read, respond to, or otherwise
2594 * act on this notice.
2596 * The $scope member is a bitmask of scopes, representing a logical AND of the
2597 * scope requirement. So, 0x03 (Notice::ADDRESSEE_SCOPE | Notice::SITE_SCOPE) means
2598 * "only visible to people who are mentioned in the notice AND are users on this site."
2599 * Users on the site who are not mentioned in the notice will not be able to see the
2602 * @param Profile $profile The profile to check; pass null to check for public/unauthenticated users.
2604 * @return boolean whether the profile is in the notice's scope
2606 function inScope($profile)
2608 if (is_null($profile)) {
2609 $keypart = sprintf('notice:in-scope-for:%d:null', $this->id);
2611 $keypart = sprintf('notice:in-scope-for:%d:%d', $this->id, $profile->id);
2614 $result = self::cacheGet($keypart);
2616 if ($result === false) {
2618 if (Event::handle('StartNoticeInScope', array($this, $profile, &$bResult))) {
2619 $bResult = $this->_inScope($profile);
2620 Event::handle('EndNoticeInScope', array($this, $profile, &$bResult));
2622 $result = ($bResult) ? 1 : 0;
2623 self::cacheSet($keypart, $result, 0, 300);
2626 return ($result == 1) ? true : false;
2629 protected function _inScope($profile)
2631 if (!is_null($this->scope)) {
2632 $scope = $this->scope;
2634 $scope = self::defaultScope();
2637 // If there's no scope, anyone (even anon) is in scope.
2639 if ($scope == 0) { // Not private
2641 return !$this->isHiddenSpam($profile);
2643 } else { // Private, somehow
2645 // If there's scope, anon cannot be in scope
2647 if (empty($profile)) {
2651 // Author is always in scope
2653 if ($this->profile_id == $profile->id) {
2657 // Only for users on this site
2659 if (($scope & Notice::SITE_SCOPE) && !$profile->isLocal()) {
2663 // Only for users mentioned in the notice
2665 if ($scope & Notice::ADDRESSEE_SCOPE) {
2667 $reply = Reply::pkeyGet(array('notice_id' => $this->id,
2668 'profile_id' => $profile->id));
2670 if (!$reply instanceof Reply) {
2675 // Only for members of the given group
2677 if ($scope & Notice::GROUP_SCOPE) {
2679 // XXX: just query for the single membership
2681 $groups = $this->getGroups();
2685 foreach ($groups as $group) {
2686 if ($profile->isMember($group)) {
2697 // Only for followers of the author
2701 if ($scope & Notice::FOLLOWER_SCOPE) {
2704 $author = $this->getProfile();
2705 } catch (Exception $e) {
2709 if (!Subscription::exists($profile, $author)) {
2714 return !$this->isHiddenSpam($profile);
2718 function isHiddenSpam($profile) {
2720 // Hide posts by silenced users from everyone but moderators.
2722 if (common_config('notice', 'hidespam')) {
2725 $author = $this->getProfile();
2726 } catch(Exception $e) {
2727 // If we can't get an author, keep it hidden.
2728 // XXX: technically not spam, but, whatever.
2732 if ($author->hasRole(Profile_role::SILENCED)) {
2733 if (!$profile instanceof Profile || (($profile->id !== $author->id) && (!$profile->hasRight(Right::REVIEWSPAM)))) {
2742 public function getParent()
2744 $parent = Notice::getKV('id', $this->reply_to);
2746 if (!$parent instanceof Notice) {
2747 throw new ServerException('Notice has no parent');
2754 * Magic function called at serialize() time.
2756 * We use this to drop a couple process-specific references
2757 * from DB_DataObject which can cause trouble in future
2760 * @return array of variable names to include in serialization.
2765 $vars = parent::__sleep();
2766 $skip = array('_profile', '_groups', '_attachments', '_faves', '_replies', '_repeats');
2767 return array_diff($vars, $skip);
2770 static function defaultScope()
2772 $scope = common_config('notice', 'defaultscope');
2773 if (is_null($scope)) {
2774 if (common_config('site', 'private')) {
2783 static function fillProfiles($notices)
2785 $map = self::getProfiles($notices);
2787 foreach ($notices as $entry=>$notice) {
2789 if (array_key_exists($notice->profile_id, $map)) {
2790 $notice->_setProfile($map[$notice->profile_id]);
2792 } catch (NoProfileException $e) {
2793 common_log(LOG_WARNING, "Failed to fill profile in Notice with non-existing entry for profile_id: {$e->profile_id}");
2794 unset($notices[$entry]);
2798 return array_values($map);
2801 static function getProfiles(&$notices)
2804 foreach ($notices as $notice) {
2805 $ids[] = $notice->profile_id;
2808 $ids = array_unique($ids);
2810 return Profile::pivotGet('id', $ids);
2813 static function fillGroups(&$notices)
2815 $ids = self::_idsOf($notices);
2817 $gis = Group_inbox::listGet('notice_id', $ids);
2821 foreach ($gis as $id => $gi)
2825 $gids[] = $g->group_id;
2829 $gids = array_unique($gids);
2831 $group = User_group::pivotGet('id', $gids);
2833 foreach ($notices as $notice)
2836 $gi = $gis[$notice->id];
2837 foreach ($gi as $g) {
2838 $grps[] = $group[$g->group_id];
2840 $notice->_setGroups($grps);
2844 static function _idsOf(array &$notices)
2847 foreach ($notices as $notice) {
2848 $ids[$notice->id] = true;
2850 return array_keys($ids);
2853 static function fillAttachments(&$notices)
2855 $ids = self::_idsOf($notices);
2857 $f2pMap = File_to_post::listGet('post_id', $ids);
2861 foreach ($f2pMap as $noticeId => $f2ps) {
2862 foreach ($f2ps as $f2p) {
2863 $fileIds[] = $f2p->file_id;
2867 $fileIds = array_unique($fileIds);
2869 $fileMap = File::pivotGet('id', $fileIds);
2871 foreach ($notices as $notice)
2874 $f2ps = $f2pMap[$notice->id];
2875 foreach ($f2ps as $f2p) {
2876 $files[] = $fileMap[$f2p->file_id];
2878 $notice->_setAttachments($files);
2882 static function fillReplies(&$notices)
2884 $ids = self::_idsOf($notices);
2885 $replyMap = Reply::listGet('notice_id', $ids);
2886 foreach ($notices as $notice) {
2887 $replies = $replyMap[$notice->id];
2889 foreach ($replies as $reply) {
2890 $ids[] = $reply->profile_id;
2892 $notice->_setReplies($ids);
2896 protected $_repeats = array();
2898 function getRepeats()
2900 if (isset($this->_repeats[$this->id])) {
2901 return $this->_repeats[$this->id];
2903 $repeatMap = Notice::listGet('repeat_of', array($this->id));
2904 $this->_repeats[$this->id] = $repeatMap[$this->id];
2905 return $this->_repeats[$this->id];
2908 function _setRepeats($repeats)
2910 $this->_repeats[$this->id] = $repeats;
2913 static function fillRepeats(&$notices)
2915 $ids = self::_idsOf($notices);
2916 $repeatMap = Notice::listGet('repeat_of', $ids);
2917 foreach ($notices as $notice) {
2918 $repeats = $repeatMap[$notice->id];
2919 $notice->_setRepeats($repeats);