3 * StatusNet - the distributed open-source microblogging tool
4 * Copyright (C) 2008-2011 StatusNet, Inc.
6 * This program is free software: you can redistribute it and/or modify
7 * it under the terms of the GNU Affero General Public License as published by
8 * the Free Software Foundation, either version 3 of the License, or
9 * (at your option) any later version.
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU Affero General Public License for more details.
16 * You should have received a copy of the GNU Affero General Public License
17 * along with this program. If not, see <http://www.gnu.org/licenses/>.
21 * @author Brenda Wallace <shiny@cpan.org>
22 * @author Christopher Vollick <psycotica0@gmail.com>
23 * @author CiaranG <ciaran@ciarang.com>
24 * @author Craig Andrews <candrews@integralblue.com>
25 * @author Evan Prodromou <evan@controlezvous.ca>
26 * @author Gina Haeussge <osd@foosel.net>
27 * @author Jeffery To <jeffery.to@gmail.com>
28 * @author Mike Cochrane <mikec@mikenz.geek.nz>
29 * @author Robin Millette <millette@controlyourself.ca>
30 * @author Sarven Capadisli <csarven@controlyourself.ca>
31 * @author Tom Adams <tom@holizz.com>
32 * @author Mikael Nordfeldth <mmn@hethane.se>
33 * @copyright 2009 Free Software Foundation, Inc http://www.fsf.org
34 * @license GNU Affero General Public License http://www.gnu.org/licenses/
37 if (!defined('GNUSOCIAL')) { exit(1); }
40 * Table Definition for notice
43 /* We keep 200 notices, the max number of notices available per API request,
44 * in the memcached cache. */
46 define('NOTICE_CACHE_WINDOW', CachingNoticeStream::CACHE_WINDOW);
48 define('MAX_BOXCARS', 128);
50 class Notice extends Managed_DataObject
53 /* the code below is auto generated do not remove the above tag */
55 public $__table = 'notice'; // table name
56 public $id; // int(4) primary_key not_null
57 public $profile_id; // int(4) multiple_key not_null
58 public $uri; // varchar(191) unique_key not 255 because utf8mb4 takes more space
59 public $content; // text
60 public $rendered; // text
61 public $url; // varchar(191) not 255 because utf8mb4 takes more space
62 public $created; // datetime multiple_key not_null default_0000-00-00%2000%3A00%3A00
63 public $modified; // timestamp not_null default_CURRENT_TIMESTAMP
64 public $reply_to; // int(4)
65 public $is_local; // int(4)
66 public $source; // varchar(32)
67 public $conversation; // int(4)
68 public $repeat_of; // int(4)
69 public $verb; // varchar(191) not 255 because utf8mb4 takes more space
70 public $object_type; // varchar(191) not 255 because utf8mb4 takes more space
71 public $scope; // int(4)
73 /* the code above is auto generated do not remove the tag below */
76 public static function schemaDef()
80 'id' => array('type' => 'serial', 'not null' => true, 'description' => 'unique identifier'),
81 'profile_id' => array('type' => 'int', 'not null' => true, 'description' => 'who made the update'),
82 'uri' => array('type' => 'varchar', 'length' => 191, 'description' => 'universally unique identifier, usually a tag URI'),
83 'content' => array('type' => 'text', 'description' => 'update content', 'collate' => 'utf8mb4_general_ci'),
84 'rendered' => array('type' => 'text', 'description' => 'HTML version of the content'),
85 'url' => array('type' => 'varchar', 'length' => 191, 'description' => 'URL of any attachment (image, video, bookmark, whatever)'),
86 'created' => array('type' => 'datetime', 'not null' => true, 'description' => 'date this record was created'),
87 'modified' => array('type' => 'timestamp', 'not null' => true, 'description' => 'date this record was modified'),
88 'reply_to' => array('type' => 'int', 'description' => 'notice replied to (usually a guess)'),
89 'is_local' => array('type' => 'int', 'size' => 'tiny', 'default' => 0, 'description' => 'notice was generated by a user'),
90 'source' => array('type' => 'varchar', 'length' => 32, 'description' => 'source of comment, like "web", "im", or "clientname"'),
91 'conversation' => array('type' => 'int', 'description' => 'id of root notice in this conversation'),
92 'repeat_of' => array('type' => 'int', 'description' => 'notice this is a repeat of'),
93 'object_type' => array('type' => 'varchar', 'length' => 191, 'description' => 'URI representing activity streams object type', 'default' => 'http://activitystrea.ms/schema/1.0/note'),
94 'verb' => array('type' => 'varchar', 'length' => 191, 'description' => 'URI representing activity streams verb', 'default' => 'http://activitystrea.ms/schema/1.0/post'),
95 'scope' => array('type' => 'int',
96 'description' => 'bit map for distribution scope; 0 = everywhere; 1 = this server only; 2 = addressees; 4 = followers; null = default'),
98 'primary key' => array('id'),
99 'unique keys' => array(
100 'notice_uri_key' => array('uri'),
102 'foreign keys' => array(
103 'notice_profile_id_fkey' => array('profile', array('profile_id' => 'id')),
104 'notice_reply_to_fkey' => array('notice', array('reply_to' => 'id')),
105 'notice_conversation_fkey' => array('conversation', array('conversation' => 'id')), # note... used to refer to notice.id
106 'notice_repeat_of_fkey' => array('notice', array('repeat_of' => 'id')), # @fixme: what about repeats of deleted notices?
109 'notice_created_id_is_local_idx' => array('created', 'id', 'is_local'),
110 'notice_profile_id_idx' => array('profile_id', 'created', 'id'),
111 'notice_repeat_of_created_id_idx' => array('repeat_of', 'created', 'id'),
112 'notice_conversation_created_id_idx' => array('conversation', 'created', 'id'),
113 'notice_replyto_idx' => array('reply_to')
117 if (common_config('search', 'type') == 'fulltext') {
118 $def['fulltext indexes'] = array('content' => array('content'));
125 const LOCAL_PUBLIC = 1;
127 const LOCAL_NONPUBLIC = -1;
130 const PUBLIC_SCOPE = 0; // Useful fake constant
131 const SITE_SCOPE = 1;
132 const ADDRESSEE_SCOPE = 2;
133 const GROUP_SCOPE = 4;
134 const FOLLOWER_SCOPE = 8;
136 protected $_profile = array();
139 * Will always return a profile, if anything fails it will
140 * (through _setProfile) throw a NoProfileException.
142 public function getProfile()
144 if (!isset($this->_profile[$this->profile_id])) {
145 // We could've sent getKV directly to _setProfile, but occasionally we get
146 // a "false" (instead of null), likely because it indicates a cache miss.
147 $profile = Profile::getKV('id', $this->profile_id);
148 $this->_setProfile($profile instanceof Profile ? $profile : null);
150 return $this->_profile[$this->profile_id];
153 public function _setProfile(Profile $profile=null)
155 if (!$profile instanceof Profile) {
156 throw new NoProfileException($this->profile_id);
158 $this->_profile[$this->profile_id] = $profile;
161 public function deleteAs(Profile $actor, $delete_event=true)
163 if (!$this->getProfile()->sameAs($actor) && !$actor->hasRight(Right::DELETEOTHERSNOTICE)) {
164 throw new AuthorizationException(_('You are not allowed to delete another user\'s notice.'));
167 if (Event::handle('NoticeDeleteRelated', array($this))) {
168 // Clear related records
169 $this->clearReplies();
170 $this->clearLocation();
171 $this->clearRepeats();
173 $this->clearGroupInboxes();
175 $this->clearAttentions();
176 // NOTE: we don't clear queue items
180 if (!$delete_event || Event::handle('DeleteNoticeAsProfile', array($this, $actor, &$result))) {
181 // If $delete_event is true, we run the event. If the Event then
182 // returns false it is assumed everything was handled properly
183 // and the notice was deleted.
184 $result = $this->delete();
189 public function delete($useWhere=false)
191 $result = parent::delete($useWhere);
193 $this->blowOnDelete();
197 public function getUri()
203 * Get a Notice object by URI. Will call external plugins for help
204 * using the event StartGetNoticeFromURI.
206 * @param string $uri A unique identifier for a resource (notice in this case)
208 static function fromUri($uri)
212 if (Event::handle('StartGetNoticeFromUri', array($uri, &$notice))) {
213 $notice = Notice::getKV('uri', $uri);
214 Event::handle('EndGetNoticeFromUri', array($uri, $notice));
217 if (!$notice instanceof Notice) {
218 throw new UnknownUriException($uri);
225 * @param $root boolean If true, link to just the conversation root.
227 * @return URL to conversation
229 public function getConversationUrl($anchor=true)
231 return Conversation::getUrlFromNotice($this, $anchor);
235 * Get the local representation URL of this notice.
237 public function getLocalUrl()
239 return common_local_url('shownotice', array('notice' => $this->id), null, null, false);
242 public function getTitle()
245 if (Event::handle('GetNoticeTitle', array($this, &$title))) {
246 // TRANS: Title of a notice posted without a title value.
247 // TRANS: %1$s is a user name, %2$s is the notice creation date/time.
248 $title = sprintf(_('%1$s\'s status on %2$s'),
249 $this->getProfile()->getFancyName(),
250 common_exact_date($this->created));
255 public function getContent()
257 return $this->content;
261 * Get the original representation URL of this notice.
263 * @param boolean $fallback Whether to fall back to generate a local URL or throw InvalidUrlException
265 public function getUrl($fallback=false)
267 // The risk is we start having empty urls and non-http uris...
268 // and we can't really handle any other protocol right now.
270 case common_valid_http_url($this->url): // should we allow non-http/https URLs?
272 case !$this->isLocal() && common_valid_http_url($this->uri): // Sometimes we only have the URI for remote posts.
274 case $this->isLocal() || $fallback:
275 // let's generate a valid link to our locally available notice on demand
276 return common_local_url('shownotice', array('notice' => $this->id), null, null, false);
278 common_debug('No URL available for notice: id='.$this->id);
279 throw new InvalidUrlException($this->url);
283 public function get_object_type($canonical=false) {
285 ? ActivityObject::canonicalType($this->object_type)
286 : $this->object_type;
289 // activity plugins tend to use this function instead, but it's the same
290 public function getObjectType()
292 return $this->get_object_type();
295 public static function getByUri($uri)
297 $notice = new Notice();
299 if (!$notice->find(true)) {
300 throw new NoResultException($notice);
306 * Extract #hashtags from this notice's content and save them to the database.
310 /* extract all #hastags */
311 $count = preg_match_all('/(?:^|\s)#([\pL\pN_\-\.]{1,64})/u', strtolower($this->content), $match);
316 /* Add them to the database */
317 return $this->saveKnownTags($match[1]);
321 * Record the given set of hash tags in the db for this notice.
322 * Given tag strings will be normalized and checked for dupes.
324 function saveKnownTags($hashtags)
326 //turn each into their canonical tag
327 //this is needed to remove dupes before saving e.g. #hash.tag = #hashtag
328 for($i=0; $i<count($hashtags); $i++) {
329 /* elide characters we don't want in the tag */
330 $hashtags[$i] = common_canonical_tag($hashtags[$i]);
333 foreach(array_unique($hashtags) as $hashtag) {
334 $this->saveTag($hashtag);
335 self::blow('profile:notice_ids_tagged:%d:%s', $this->profile_id, $hashtag);
341 * Record a single hash tag as associated with this notice.
342 * Tag format and uniqueness must be validated by caller.
344 function saveTag($hashtag)
346 $tag = new Notice_tag();
347 $tag->notice_id = $this->id;
348 $tag->tag = $hashtag;
349 $tag->created = $this->created;
350 $id = $tag->insert();
353 // TRANS: Server exception. %s are the error details.
354 throw new ServerException(sprintf(_('Database error inserting hashtag: %s.'),
355 $last_error->message));
359 // if it's saved, blow its cache
360 $tag->blowCache(false);
364 * Save a new notice and push it out to subscribers' inboxes.
365 * Poster's permissions are checked before sending.
367 * @param int $profile_id Profile ID of the poster
368 * @param string $content source message text; links may be shortened
369 * per current user's preference
370 * @param string $source source key ('web', 'api', etc)
371 * @param array $options Associative array of optional properties:
372 * string 'created' timestamp of notice; defaults to now
373 * int 'is_local' source/gateway ID, one of:
374 * Notice::LOCAL_PUBLIC - Local, ok to appear in public timeline
375 * Notice::REMOTE - Sent from a remote service;
376 * hide from public timeline but show in
377 * local "and friends" timelines
378 * Notice::LOCAL_NONPUBLIC - Local, but hide from public timeline
379 * Notice::GATEWAY - From another non-OStatus service;
380 * will not appear in public views
381 * float 'lat' decimal latitude for geolocation
382 * float 'lon' decimal longitude for geolocation
383 * int 'location_id' geoname identifier
384 * int 'location_ns' geoname namespace to interpret location_id
385 * int 'reply_to'; notice ID this is a reply to
386 * int 'repeat_of'; notice ID this is a repeat of
387 * string 'uri' unique ID for notice; a unique tag uri (can be url or anything too)
388 * string 'url' permalink to notice; defaults to local notice URL
389 * string 'rendered' rendered HTML version of content
390 * array 'replies' list of profile URIs for reply delivery in
391 * place of extracting @-replies from content.
392 * array 'groups' list of group IDs to deliver to, in place of
393 * extracting ! tags from content
394 * array 'tags' list of hashtag strings to save with the notice
395 * in place of extracting # tags from content
396 * array 'urls' list of attached/referred URLs to save with the
397 * notice in place of extracting links from content
398 * boolean 'distribute' whether to distribute the notice, default true
399 * string 'object_type' URL of the associated object type (default ActivityObject::NOTE)
400 * string 'verb' URL of the associated verb (default ActivityVerb::POST)
401 * int 'scope' Scope bitmask; default to SITE_SCOPE on private sites, 0 otherwise
403 * @fixme tag override
406 * @throws ClientException
408 static function saveNew($profile_id, $content, $source, array $options=null) {
409 $defaults = array('uri' => null,
411 'conversation' => null, // URI of conversation
412 'reply_to' => null, // This will override convo URI if the parent is known
413 'repeat_of' => null, // This will override convo URI if the repeated notice is known
415 'distribute' => true,
416 'object_type' => null,
419 if (!empty($options) && is_array($options)) {
420 $options = array_merge($defaults, $options);
426 if (!isset($is_local)) {
427 $is_local = Notice::LOCAL_PUBLIC;
430 $profile = Profile::getKV('id', $profile_id);
431 if (!$profile instanceof Profile) {
432 // TRANS: Client exception thrown when trying to save a notice for an unknown user.
433 throw new ClientException(_('Problem saving notice. Unknown user.'));
436 $user = User::getKV('id', $profile_id);
437 if ($user instanceof User) {
438 // Use the local user's shortening preferences, if applicable.
439 $final = $user->shortenLinks($content);
441 $final = common_shorten_links($content);
444 if (Notice::contentTooLong($final)) {
445 // TRANS: Client exception thrown if a notice contains too many characters.
446 throw new ClientException(_('Problem saving notice. Too long.'));
449 if (common_config('throttle', 'enabled') && !Notice::checkEditThrottle($profile_id)) {
450 common_log(LOG_WARNING, 'Excessive posting by profile #' . $profile_id . '; throttled.');
451 // TRANS: Client exception thrown when a user tries to post too many notices in a given time frame.
452 throw new ClientException(_('Too many notices too fast; take a breather '.
453 'and post again in a few minutes.'));
456 if (common_config('site', 'dupelimit') > 0 && !Notice::checkDupes($profile_id, $final)) {
457 common_log(LOG_WARNING, 'Dupe posting by profile #' . $profile_id . '; throttled.');
458 // TRANS: Client exception thrown when a user tries to post too many duplicate notices in a given time frame.
459 throw new ClientException(_('Too many duplicate messages too quickly;'.
460 ' take a breather and post again in a few minutes.'));
463 if (!$profile->hasRight(Right::NEWNOTICE)) {
464 common_log(LOG_WARNING, "Attempted post from user disallowed to post: " . $profile->nickname);
466 // TRANS: Client exception thrown when a user tries to post while being banned.
467 throw new ClientException(_('You are banned from posting notices on this site.'), 403);
470 $notice = new Notice();
471 $notice->profile_id = $profile_id;
473 $autosource = common_config('public', 'autosource');
475 // Sandboxed are non-false, but not 1, either
477 if (!$profile->hasRight(Right::PUBLICNOTICE) ||
478 ($source && $autosource && in_array($source, $autosource))) {
479 $notice->is_local = Notice::LOCAL_NONPUBLIC;
481 $notice->is_local = $is_local;
484 if (!empty($created)) {
485 $notice->created = $created;
487 $notice->created = common_sql_now();
490 if (!$notice->isLocal()) {
491 // Only do these checks for non-local notices. Local notices will generate these values later.
492 if (!common_valid_http_url($url)) {
493 common_debug('Bad notice URL: ['.$url.'], URI: ['.$uri.']. Cannot link back to original! This is normal for shared notices etc.');
496 throw new ServerException('No URI for remote notice. Cannot accept that.');
500 $notice->content = $final;
502 $notice->source = $source;
506 // Get the groups here so we can figure out replies and such
507 if (!isset($groups)) {
508 $groups = User_group::idsFromText($notice->content, $profile);
513 // Handle repeat case
515 if (!empty($options['repeat_of'])) {
517 // Check for a private one
519 $repeat = Notice::getByID($options['repeat_of']);
521 if ($profile->sameAs($repeat->getProfile())) {
522 // TRANS: Client error displayed when trying to repeat an own notice.
523 throw new ClientException(_('You cannot repeat your own notice.'));
526 if ($repeat->scope != Notice::SITE_SCOPE &&
527 $repeat->scope != Notice::PUBLIC_SCOPE) {
528 // TRANS: Client error displayed when trying to repeat a non-public notice.
529 throw new ClientException(_('Cannot repeat a private notice.'), 403);
532 if (!$repeat->inScope($profile)) {
533 // The generic checks above should cover this, but let's be sure!
534 // TRANS: Client error displayed when trying to repeat a notice you cannot access.
535 throw new ClientException(_('Cannot repeat a notice you cannot read.'), 403);
538 if ($profile->hasRepeated($repeat)) {
539 // TRANS: Client error displayed when trying to repeat an already repeated notice.
540 throw new ClientException(_('You already repeated that notice.'));
543 $notice->repeat_of = $repeat->id;
544 $notice->conversation = $repeat->conversation;
548 // If $reply_to is specified, we check that it exists, and then
549 // return it if it does
550 if (!empty($reply_to)) {
551 $reply = Notice::getKV('id', $reply_to);
552 } elseif (in_array($source, array('xmpp', 'mail', 'sms'))) {
553 // If the source lacks capability of sending the "reply_to"
554 // metadata, let's try to find an inline replyto-reference.
555 $reply = self::getInlineReplyTo($profile, $final);
558 if ($reply instanceof Notice) {
559 if (!$reply->inScope($profile)) {
560 // TRANS: Client error displayed when trying to reply to a notice a the target has no access to.
561 // TRANS: %1$s is a user nickname, %2$d is a notice ID (number).
562 throw new ClientException(sprintf(_('%1$s has no access to notice %2$d.'),
563 $profile->nickname, $reply->id), 403);
566 // If it's a repeat, the reply_to should be to the original
567 if ($reply->isRepeat()) {
568 $notice->reply_to = $reply->repeat_of;
570 $notice->reply_to = $reply->id;
572 // But the conversation ought to be the same :)
573 $notice->conversation = $reply->conversation;
575 // If the original is private to a group, and notice has
576 // no group specified, make it to the same group(s)
578 if (empty($groups) && ($reply->scope & Notice::GROUP_SCOPE)) {
580 $replyGroups = $reply->getGroups();
581 foreach ($replyGroups as $group) {
582 if ($profile->isMember($group)) {
583 $groups[] = $group->id;
591 // If we don't know the reply, we might know the conversation!
592 // This will happen if a known remote user replies to an
593 // unknown remote user - within a known conversation.
594 if (empty($notice->conversation) and !empty($options['conversation'])) {
595 $conv = Conversation::getKV('uri', $options['conversation']);
596 if ($conv instanceof Conversation) {
597 common_debug('Conversation stitched together from (probably) a reply to unknown remote user. Activity creation time ('.$notice->created.') should maybe be compared to conversation creation time ('.$conv->created.').');
598 $notice->conversation = $conv->id;
600 // Conversation URI was not found, so we must create it. But we can't create it
601 // until we have a Notice ID because of the database layout...
602 // $options['conversation'] will be used later after the $notice->insert();
603 common_debug('Conversation URI not found, so we have to create it after inserting this Notice: '.$options['conversation']);
606 // If we're not using the attached conversation URI let's remove it
607 // so we don't mistake ourselves later, when creating our own Conversation.
608 // This implies that the notice knows which conversation it belongs to.
609 $options['conversation'] = null;
613 $notloc = new Notice_location();
614 if (!empty($lat) && !empty($lon)) {
619 if (!empty($location_ns) && !empty($location_id)) {
620 $notloc->location_id = $location_id;
621 $notloc->location_ns = $location_ns;
624 if (!empty($rendered)) {
625 $notice->rendered = $rendered;
627 $notice->rendered = common_render_content($final, $notice);
631 if ($notice->isRepeat()) {
632 $notice->verb = ActivityVerb::SHARE;
633 $notice->object_type = ActivityObject::ACTIVITY;
635 $notice->verb = ActivityVerb::POST;
638 $notice->verb = $verb;
641 if (empty($object_type)) {
642 $notice->object_type = (empty($notice->reply_to)) ? ActivityObject::NOTE : ActivityObject::COMMENT;
644 $notice->object_type = $object_type;
647 if (is_null($scope) && $reply instanceof Notice) {
648 $notice->scope = $reply->scope;
650 $notice->scope = $scope;
653 $notice->scope = self::figureOutScope($profile, $groups, $notice->scope);
655 if (Event::handle('StartNoticeSave', array(&$notice))) {
657 // XXX: some of these functions write to the DB
660 $notice->insert(); // throws exception on failure, if successful we have an ->id
662 if (($notloc->lat && $notloc->lon) || ($notloc->location_id && $notloc->location_ns)) {
663 $notloc->notice_id = $notice->getID();
664 $notloc->insert(); // store the notice location if it had any information
667 // If it's not part of a conversation, it's
668 // the beginning of a new conversation.
669 if (empty($notice->conversation)) {
670 $orig = clone($notice);
671 // $act->context->conversation will be null if it was not provided
673 $conv = Conversation::create($notice, $options['conversation']);
674 $notice->conversation = $conv->id;
675 $notice->update($orig);
677 } catch (Exception $e) {
678 // Let's test if we managed initial insert, which would imply
679 // failing on some update-part (check 'insert()'). Delete if
680 // something had been stored to the database.
681 if (!empty($notice->id)) {
688 // Clear the cache for subscribed users, so they'll update at next request
689 // XXX: someone clever could prepend instead of clearing the cache
691 // Save per-notice metadata...
693 if (isset($replies)) {
694 $notice->saveKnownReplies($replies);
696 $notice->saveReplies();
700 $notice->saveKnownTags($tags);
705 // Note: groups may save tags, so must be run after tags are saved
706 // to avoid errors on duplicates.
707 // Note: groups should always be set.
709 $notice->saveKnownGroups($groups);
712 $notice->saveKnownUrls($urls);
718 // Prepare inbox delivery, may be queued to background.
719 $notice->distribute();
725 static function saveActivity(Activity $act, Profile $actor, array $options=array())
727 // First check if we're going to let this Activity through from the specific actor
728 if (!$actor->hasRight(Right::NEWNOTICE)) {
729 common_log(LOG_WARNING, "Attempted post from user disallowed to post: " . $actor->getNickname());
731 // TRANS: Client exception thrown when a user tries to post while being banned.
732 throw new ClientException(_m('You are banned from posting notices on this site.'), 403);
734 if (common_config('throttle', 'enabled') && !self::checkEditThrottle($actor->id)) {
735 common_log(LOG_WARNING, 'Excessive posting by profile #' . $actor->id . '; throttled.');
736 // TRANS: Client exception thrown when a user tries to post too many notices in a given time frame.
737 throw new ClientException(_m('Too many notices too fast; take a breather '.
738 'and post again in a few minutes.'));
741 // Get ActivityObject properties
742 if (!empty($act->id)) {
744 $options['uri'] = $act->id;
745 $options['url'] = $act->link;
747 $actobj = count($act->objects)==1 ? $act->objects[0] : null;
748 if (!is_null($actobj) && !empty($actobj->id)) {
749 $options['uri'] = $actobj->id;
751 $options['url'] = $actobj->link;
752 } elseif (preg_match('!^https?://!', $actobj->id)) {
753 $options['url'] = $actobj->id;
760 'is_local' => self::LOCAL_PUBLIC,
761 'mentions' => array(),
765 'source' => 'unknown',
770 'distribute' => true);
772 // options will have default values when nothing has been supplied
773 $options = array_merge($defaults, $options);
774 foreach (array_keys($defaults) as $key) {
775 // Only convert the keynames we specify ourselves from 'defaults' array into variables
776 $$key = $options[$key];
778 extract($options, EXTR_SKIP);
780 $stored = new Notice();
783 if ($stored->find()) {
784 common_debug('cannot create duplicate Notice URI: '.$stored->uri);
785 throw new Exception('Notice URI already exists');
789 $stored->profile_id = $actor->id;
790 $stored->source = $source;
793 $stored->verb = $act->verb;
795 // Use the local user's shortening preferences, if applicable.
796 $stored->rendered = $actor->isLocal()
797 ? $actor->shortenLinks($act->content)
799 $stored->content = common_strip_html($stored->rendered);
801 $autosource = common_config('public', 'autosource');
803 // Sandboxed are non-false, but not 1, either
804 if (!$actor->hasRight(Right::PUBLICNOTICE) ||
805 ($source && $autosource && in_array($source, $autosource))) {
806 $stored->is_local = Notice::LOCAL_NONPUBLIC;
808 $stored->is_local = $is_local;
811 // Maybe a missing act-time should be fatal if the actor is not local?
812 if (!empty($act->time)) {
813 $stored->created = common_sql_date($act->time);
815 $stored->created = common_sql_now();
819 if ($act->context instanceof ActivityContext && !empty($act->context->replyToID)) {
820 $reply = self::getKV('uri', $act->context->replyToID);
822 if (!$reply instanceof Notice && $act->target instanceof ActivityObject) {
823 $reply = self::getKV('uri', $act->target->id);
826 if ($reply instanceof Notice) {
827 if (!$reply->inScope($actor)) {
828 // TRANS: Client error displayed when trying to reply to a notice a the target has no access to.
829 // TRANS: %1$s is a user nickname, %2$d is a notice ID (number).
830 throw new ClientException(sprintf(_m('%1$s has no right to reply to notice %2$d.'), $actor->getNickname(), $reply->id), 403);
833 $stored->reply_to = $reply->id;
834 $stored->conversation = $reply->conversation;
836 // If the original is private to a group, and notice has no group specified,
837 // make it to the same group(s)
838 if (empty($groups) && ($reply->scope & Notice::GROUP_SCOPE)) {
840 $replyGroups = $reply->getGroups();
841 foreach ($replyGroups as $group) {
842 if ($actor->isMember($group)) {
843 $groups[] = $group->id;
848 if (is_null($scope)) {
849 $scope = $reply->scope;
852 // If we don't know the reply, we might know the conversation!
853 // This will happen if a known remote user replies to an
854 // unknown remote user - within a known conversation.
855 if (empty($stored->conversation) and !empty($act->context->conversation)) {
856 $conv = Conversation::getKV('uri', $act->context->conversation);
857 if ($conv instanceof Conversation) {
858 common_debug('Conversation stitched together from (probably) a reply activity to unknown remote user. Activity creation time ('.$stored->created.') should maybe be compared to conversation creation time ('.$conv->created.').');
859 $stored->conversation = $conv->getID();
861 // Conversation URI was not found, so we must create it. But we can't create it
862 // until we have a Notice ID because of the database layout...
863 // $options['conversation'] will be used later after the $stored->insert();
864 common_debug('Conversation URI from activity context not found, so we have to create it after inserting this Notice: '.$act->context->conversation);
870 if ($act->context instanceof ActivityContext) {
871 if ($act->context->location instanceof Location) {
872 $notloc = Notice_location::fromLocation($act->context->location);
875 $act->context = new ActivityContext();
878 $stored->scope = self::figureOutScope($actor, $groups, $scope);
880 foreach ($act->categories as $cat) {
882 $term = common_canonical_tag($cat->term);
889 foreach ($act->enclosures as $href) {
890 // @todo FIXME: Save these locally or....?
894 if (Event::handle('StartNoticeSave', array(&$stored))) {
895 // XXX: some of these functions write to the DB
898 $stored->insert(); // throws exception on error
900 if ($notloc instanceof Notice_location) {
901 $notloc->notice_id = $stored->getID();
905 $orig = clone($stored); // for updating later in this try clause
908 Event::handle('StoreActivityObject', array($act, $stored, $options, &$object));
909 if (empty($object)) {
910 throw new ServerException('Unsuccessful call to StoreActivityObject '.$stored->uri . ': '.$act->asString());
913 // If it's not part of a conversation, it's the beginning
914 // of a new one (or belongs to a previously unknown URI).
915 if (empty($stored->conversation)) {
916 // $act->context->conversation will be null if it was not provided
917 common_debug('Creating a new conversation for stored notice ID='.$stored->getID().' with URI: '.$act->context->conversation);
918 $conv = Conversation::create($stored, $act->context->conversation);
919 $stored->conversation = $conv->getID();
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) {
996 $group = User_group::getByID($group_id);
997 if ($group->force_scope) {
998 $scope |= Notice::GROUP_SCOPE;
1001 } catch (Exception $e) {
1002 common_log(LOG_ERR, 'Notice figureOutScope threw exception: '.$e->getMessage());
1009 function blowOnInsert($conversation = false)
1011 $this->blowStream('profile:notice_ids:%d', $this->profile_id);
1013 if ($this->isPublic()) {
1014 $this->blowStream('public');
1015 $this->blowStream('networkpublic');
1018 self::blow('notice:list-ids:conversation:%s', $this->conversation);
1019 self::blow('conversation:notice_count:%d', $this->conversation);
1021 if ($this->isRepeat()) {
1022 // XXX: we should probably only use one of these
1023 $this->blowStream('notice:repeats:%d', $this->repeat_of);
1024 self::blow('notice:list-ids:repeat_of:%d', $this->repeat_of);
1027 $original = Notice::getKV('id', $this->repeat_of);
1029 if ($original instanceof Notice) {
1030 $originalUser = User::getKV('id', $original->profile_id);
1031 if ($originalUser instanceof User) {
1032 $this->blowStream('user:repeats_of_me:%d', $originalUser->id);
1036 $profile = Profile::getKV($this->profile_id);
1038 if ($profile instanceof Profile) {
1039 $profile->blowNoticeCount();
1042 $ptags = $this->getProfileTags();
1043 foreach ($ptags as $ptag) {
1044 $ptag->blowNoticeStreamCache();
1049 * Clear cache entries related to this notice at delete time.
1050 * Necessary to avoid breaking paging on public, profile timelines.
1052 function blowOnDelete()
1054 $this->blowOnInsert();
1056 self::blow('profile:notice_ids:%d;last', $this->profile_id);
1058 if ($this->isPublic()) {
1059 self::blow('public;last');
1060 self::blow('networkpublic;last');
1063 self::blow('fave:by_notice', $this->id);
1065 if ($this->conversation) {
1066 // In case we're the first, will need to calc a new root.
1067 self::blow('notice:conversation_root:%d', $this->conversation);
1070 $ptags = $this->getProfileTags();
1071 foreach ($ptags as $ptag) {
1072 $ptag->blowNoticeStreamCache(true);
1076 function blowStream()
1078 $c = self::memcache();
1084 $args = func_get_args();
1085 $format = array_shift($args);
1086 $keyPart = vsprintf($format, $args);
1087 $cacheKey = Cache::key($keyPart);
1088 $c->delete($cacheKey);
1090 // delete the "last" stream, too, if this notice is
1091 // older than the top of that stream
1093 $lastKey = $cacheKey.';last';
1095 $lastStr = $c->get($lastKey);
1097 if ($lastStr !== false) {
1098 $window = explode(',', $lastStr);
1099 $lastID = $window[0];
1100 $lastNotice = Notice::getKV('id', $lastID);
1101 if (!$lastNotice instanceof Notice // just weird
1102 || strtotime($lastNotice->created) >= strtotime($this->created)) {
1103 $c->delete($lastKey);
1108 /** save all urls in the notice to the db
1110 * follow redirects and save all available file information
1111 * (mimetype, date, size, oembed, etc.)
1115 function saveUrls() {
1116 if (common_config('attachments', 'process_links')) {
1117 common_replace_urls_callback($this->content, array($this, 'saveUrl'), $this);
1122 * Save the given URLs as related links/attachments to the db
1124 * follow redirects and save all available file information
1125 * (mimetype, date, size, oembed, etc.)
1129 function saveKnownUrls($urls)
1131 if (common_config('attachments', 'process_links')) {
1132 // @fixme validation?
1133 foreach (array_unique($urls) as $url) {
1134 $this->saveUrl($url, $this);
1142 function saveUrl($url, Notice $notice) {
1144 File::processNew($url, $notice);
1145 } catch (ServerException $e) {
1146 // Could not save URL. Log it?
1150 static function checkDupes($profile_id, $content) {
1151 $profile = Profile::getKV($profile_id);
1152 if (!$profile instanceof Profile) {
1155 $notice = $profile->getNotices(0, CachingNoticeStream::CACHE_WINDOW);
1156 if (!empty($notice)) {
1158 while ($notice->fetch()) {
1159 if (time() - strtotime($notice->created) >= common_config('site', 'dupelimit')) {
1161 } else if ($notice->content == $content) {
1166 // If we get here, oldest item in cache window is not
1167 // old enough for dupe limit; do direct check against DB
1168 $notice = new Notice();
1169 $notice->profile_id = $profile_id;
1170 $notice->content = $content;
1171 $threshold = common_sql_date(time() - common_config('site', 'dupelimit'));
1172 $notice->whereAdd(sprintf("created > '%s'", $notice->escape($threshold)));
1174 $cnt = $notice->count();
1178 static function checkEditThrottle($profile_id) {
1179 $profile = Profile::getKV($profile_id);
1180 if (!$profile instanceof Profile) {
1183 // Get the Nth notice
1184 $notice = $profile->getNotices(common_config('throttle', 'count') - 1, 1);
1185 if ($notice && $notice->fetch()) {
1186 // If the Nth notice was posted less than timespan seconds ago
1187 if (time() - strtotime($notice->created) <= common_config('throttle', 'timespan')) {
1192 // Either not N notices in the stream, OR the Nth was not posted within timespan seconds
1196 protected $_attachments = array();
1198 function attachments() {
1199 if (isset($this->_attachments[$this->id])) {
1200 return $this->_attachments[$this->id];
1203 $f2ps = File_to_post::listGet('post_id', array($this->id));
1205 foreach ($f2ps[$this->id] as $f2p) {
1206 $ids[] = $f2p->file_id;
1209 $files = File::multiGet('id', $ids);
1210 $this->_attachments[$this->id] = $files->fetchAll();
1211 return $this->_attachments[$this->id];
1214 function _setAttachments($attachments)
1216 $this->_attachments[$this->id] = $attachments;
1219 static function publicStream($offset=0, $limit=20, $since_id=null, $max_id=null)
1221 $stream = new PublicNoticeStream();
1222 return $stream->getNotices($offset, $limit, $since_id, $max_id);
1225 static function conversationStream($id, $offset=0, $limit=20, $since_id=null, $max_id=null)
1227 $stream = new ConversationNoticeStream($id);
1228 return $stream->getNotices($offset, $limit, $since_id, $max_id);
1232 * Is this notice part of an active conversation?
1234 * @return boolean true if other messages exist in the same
1235 * conversation, false if this is the only one
1237 function hasConversation()
1239 if (empty($this->conversation)) {
1240 // this notice is not part of a conversation apparently
1241 // FIXME: all notices should have a conversation value, right?
1245 $stream = new ConversationNoticeStream($this->conversation);
1246 $notice = $stream->getNotices(/*offset*/ 1, /*limit*/ 1);
1248 // if our "offset 1, limit 1" query got a result, return true else false
1249 return $notice->N > 0;
1253 * Grab the earliest notice from this conversation.
1255 * @return Notice or null
1257 function conversationRoot($profile=-1)
1259 // XXX: can this happen?
1261 if (empty($this->conversation)) {
1265 // Get the current profile if not specified
1267 if (is_int($profile) && $profile == -1) {
1268 $profile = Profile::current();
1271 // If this notice is out of scope, no root for you!
1273 if (!$this->inScope($profile)) {
1277 // If this isn't a reply to anything, then it's its own
1278 // root if it's the earliest notice in the conversation:
1280 if (empty($this->reply_to)) {
1282 $root->conversation = $this->conversation;
1283 $root->orderBy('notice.created ASC');
1284 $root->find(true); // true means "fetch first result"
1289 if (is_null($profile)) {
1290 $keypart = sprintf('notice:conversation_root:%d:null', $this->id);
1292 $keypart = sprintf('notice:conversation_root:%d:%d',
1297 $root = self::cacheGet($keypart);
1299 if ($root !== false && $root->inScope($profile)) {
1306 $parent = $last->getParent();
1307 if ($parent->inScope($profile)) {
1311 } catch (NoParentNoticeException $e) {
1312 // Latest notice has no parent
1313 } catch (NoResultException $e) {
1314 // Notice was not found, so we can't go further up in the tree.
1315 // FIXME: Maybe we should do this in a more stable way where deleted
1316 // notices won't break conversation chains?
1318 // No parent, or parent out of scope
1323 self::cacheSet($keypart, $root);
1329 * Pull up a full list of local recipients who will be getting
1330 * this notice in their inbox. Results will be cached, so don't
1331 * change the input data wily-nilly!
1333 * @param array $groups optional list of Group objects;
1334 * if left empty, will be loaded from group_inbox records
1335 * @param array $recipient optional list of reply profile ids
1336 * if left empty, will be loaded from reply records
1337 * @return array associating recipient user IDs with an inbox source constant
1339 function whoGets(array $groups=null, array $recipients=null)
1341 $c = self::memcache();
1344 $ni = $c->get(Cache::key('notice:who_gets:'.$this->id));
1345 if ($ni !== false) {
1350 if (is_null($recipients)) {
1351 $recipients = $this->getReplies();
1356 // Give plugins a chance to add folks in at start...
1357 if (Event::handle('StartNoticeWhoGets', array($this, &$ni))) {
1359 $users = $this->getSubscribedUsers();
1360 foreach ($users as $id) {
1361 $ni[$id] = NOTICE_INBOX_SOURCE_SUB;
1364 if (is_null($groups)) {
1365 $groups = $this->getGroups();
1367 foreach ($groups as $group) {
1368 $users = $group->getUserMembers();
1369 foreach ($users as $id) {
1370 if (!array_key_exists($id, $ni)) {
1371 $ni[$id] = NOTICE_INBOX_SOURCE_GROUP;
1376 $ptAtts = $this->getAttentionsFromProfileTags();
1377 foreach ($ptAtts as $key=>$val) {
1378 if (!array_key_exists($key, $ni)) {
1383 foreach ($recipients as $recipient) {
1384 if (!array_key_exists($recipient, $ni)) {
1385 $ni[$recipient] = NOTICE_INBOX_SOURCE_REPLY;
1389 // Exclude any deleted, non-local, or blocking recipients.
1390 $profile = $this->getProfile();
1391 $originalProfile = null;
1392 if ($this->isRepeat()) {
1393 // Check blocks against the original notice's poster as well.
1394 $original = Notice::getKV('id', $this->repeat_of);
1395 if ($original instanceof Notice) {
1396 $originalProfile = $original->getProfile();
1400 foreach ($ni as $id => $source) {
1402 $user = User::getKV('id', $id);
1403 if (!$user instanceof User ||
1404 $user->hasBlocked($profile) ||
1405 ($originalProfile && $user->hasBlocked($originalProfile))) {
1408 } catch (UserNoProfileException $e) {
1409 // User doesn't have a profile; invalid; skip them.
1414 // Give plugins a chance to filter out...
1415 Event::handle('EndNoticeWhoGets', array($this, &$ni));
1419 // XXX: pack this data better
1420 $c->set(Cache::key('notice:who_gets:'.$this->id), $ni);
1426 function getSubscribedUsers()
1430 if(common_config('db','quote_identifiers'))
1431 $user_table = '"user"';
1432 else $user_table = 'user';
1436 'FROM '. $user_table .' JOIN subscription '.
1437 'ON '. $user_table .'.id = subscription.subscriber ' .
1438 'WHERE subscription.subscribed = %d ';
1440 $user->query(sprintf($qry, $this->profile_id));
1444 while ($user->fetch()) {
1453 function getProfileTags()
1455 $profile = $this->getProfile();
1456 $list = $profile->getOtherTags($profile);
1459 while($list->fetch()) {
1460 $ptags[] = clone($list);
1466 public function getAttentionsFromProfileTags()
1469 $ptags = $this->getProfileTags();
1470 foreach ($ptags as $ptag) {
1471 $users = $ptag->getUserSubscribers();
1472 foreach ($users as $id) {
1473 $ni[$id] = NOTICE_INBOX_SOURCE_PROFILE_TAG;
1480 * Record this notice to the given group inboxes for delivery.
1481 * Overrides the regular parsing of !group markup.
1483 * @param string $group_ids
1484 * @fixme might prefer URIs as identifiers, as for replies?
1485 * best with generalizations on user_group to support
1486 * remote groups better.
1488 function saveKnownGroups($group_ids)
1490 if (!is_array($group_ids)) {
1491 // TRANS: Server exception thrown when no array is provided to the method saveKnownGroups().
1492 throw new ServerException(_('Bad type provided to saveKnownGroups.'));
1496 foreach (array_unique($group_ids) as $id) {
1497 $group = User_group::getKV('id', $id);
1498 if ($group instanceof User_group) {
1499 common_log(LOG_DEBUG, "Local delivery to group id $id, $group->nickname");
1500 $result = $this->addToGroupInbox($group);
1502 common_log_db_error($gi, 'INSERT', __FILE__);
1505 if (common_config('group', 'addtag')) {
1506 // we automatically add a tag for every group name, too
1508 $tag = Notice_tag::pkeyGet(array('tag' => common_canonical_tag($group->nickname),
1509 'notice_id' => $this->id));
1511 if (is_null($tag)) {
1512 $this->saveTag($group->nickname);
1516 $groups[] = clone($group);
1518 common_log(LOG_ERR, "Local delivery to group id $id skipped, doesn't exist");
1525 function addToGroupInbox(User_group $group)
1527 $gi = Group_inbox::pkeyGet(array('group_id' => $group->id,
1528 'notice_id' => $this->id));
1530 if (!$gi instanceof Group_inbox) {
1532 $gi = new Group_inbox();
1534 $gi->group_id = $group->id;
1535 $gi->notice_id = $this->id;
1536 $gi->created = $this->created;
1538 $result = $gi->insert();
1541 common_log_db_error($gi, 'INSERT', __FILE__);
1542 // TRANS: Server exception thrown when an update for a group inbox fails.
1543 throw new ServerException(_('Problem saving group inbox.'));
1546 self::blow('user_group:notice_ids:%d', $gi->group_id);
1553 * Save reply records indicating that this notice needs to be
1554 * delivered to the local users with the given URIs.
1556 * Since this is expected to be used when saving foreign-sourced
1557 * messages, we won't deliver to any remote targets as that's the
1558 * source service's responsibility.
1560 * Mail notifications etc will be handled later.
1562 * @param array $uris Array of unique identifier URIs for recipients
1564 function saveKnownReplies(array $uris)
1570 $sender = Profile::getKV($this->profile_id);
1572 foreach (array_unique($uris) as $uri) {
1574 $profile = Profile::fromUri($uri);
1575 } catch (UnknownUriException $e) {
1576 common_log(LOG_WARNING, "Unable to determine profile for URI '$uri'");
1580 if ($profile->hasBlocked($sender)) {
1581 common_log(LOG_INFO, "Not saving reply to profile {$profile->id} ($uri) from sender {$sender->id} because of a block.");
1585 $this->saveReply($profile->id);
1586 self::blow('reply:stream:%d', $profile->id);
1593 * Pull @-replies from this message's content in StatusNet markup format
1594 * and save reply records indicating that this message needs to be
1595 * delivered to those users.
1597 * Mail notifications to local profiles will be sent later.
1599 * @return array of integer profile IDs
1602 function saveReplies()
1604 // Don't save reply data for repeats
1606 if ($this->isRepeat()) {
1610 $sender = $this->getProfile();
1614 // If it's a reply, save for the replied-to author
1616 $parent = $this->getParent();
1617 $parentauthor = $parent->getProfile();
1618 $this->saveReply($parentauthor->id);
1619 $replied[$parentauthor->id] = 1;
1620 self::blow('reply:stream:%d', $parentauthor->id);
1621 } catch (NoParentNoticeException $e) {
1622 // Not a reply, since it has no parent!
1623 } catch (NoResultException $e) {
1624 // Parent notice was probably deleted
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
1640 if (array_key_exists($mentioned->id, $replied)) {
1644 // Don't save replies from blocked profile to local user
1646 $mentioned_user = User::getKV('id', $mentioned->id);
1647 if ($mentioned_user instanceof User && $mentioned_user->hasBlocked($sender)) {
1651 $this->saveReply($mentioned->id);
1652 $replied[$mentioned->id] = 1;
1653 self::blow('reply:stream:%d', $mentioned->id);
1657 $recipientIds = array_keys($replied);
1659 return $recipientIds;
1662 function saveReply($profileId)
1664 $reply = new Reply();
1666 $reply->notice_id = $this->id;
1667 $reply->profile_id = $profileId;
1668 $reply->modified = $this->created;
1675 protected $_replies = array();
1678 * Pull the complete list of @-mentioned profile IDs for this notice.
1680 * @return array of integer profile ids
1682 function getReplies()
1684 if (!isset($this->_replies[$this->getID()])) {
1685 $mentions = Reply::multiGet('notice_id', array($this->getID()));
1686 $this->_replies[$this->getID()] = $mentions->fetchAll('profile_id');
1688 return $this->_replies[$this->getID()];
1691 function _setReplies($replies)
1693 $this->_replies[$this->getID()] = $replies;
1697 * Pull the complete list of @-reply targets for this notice.
1699 * @return array of Profiles
1701 function getReplyProfiles()
1703 $ids = $this->getReplies();
1705 $profiles = Profile::multiGet('id', $ids);
1707 return $profiles->fetchAll();
1711 * Send e-mail notifications to local @-reply targets.
1713 * Replies must already have been saved; this is expected to be run
1714 * from the distrib queue handler.
1716 function sendReplyNotifications()
1718 // Don't send reply notifications for repeats
1720 if ($this->isRepeat()) {
1724 $recipientIds = $this->getReplies();
1725 if (Event::handle('StartNotifyMentioned', array($this, &$recipientIds))) {
1726 require_once INSTALLDIR.'/lib/mail.php';
1728 foreach ($recipientIds as $recipientId) {
1729 $user = User::getKV('id', $recipientId);
1730 if ($user instanceof User) {
1731 mail_notify_attn($user, $this);
1734 Event::handle('EndNotifyMentioned', array($this, $recipientIds));
1739 * Pull list of groups this notice needs to be delivered to,
1740 * as previously recorded by saveKnownGroups().
1742 * @return array of Group objects
1745 protected $_groups = array();
1747 function getGroups()
1749 // Don't save groups for repeats
1751 if (!empty($this->repeat_of)) {
1755 if (isset($this->_groups[$this->id])) {
1756 return $this->_groups[$this->id];
1759 $gis = Group_inbox::listGet('notice_id', array($this->id));
1763 foreach ($gis[$this->id] as $gi) {
1764 $ids[] = $gi->group_id;
1767 $groups = User_group::multiGet('id', $ids);
1768 $this->_groups[$this->id] = $groups->fetchAll();
1769 return $this->_groups[$this->id];
1772 function _setGroups($groups)
1774 $this->_groups[$this->id] = $groups;
1778 * Convert a notice into an activity for export.
1780 * @param Profile $scoped The currently logged in/scoped profile
1782 * @return Activity activity object representing this Notice.
1785 function asActivity(Profile $scoped=null)
1787 $act = self::cacheGet(Cache::codeKey('notice:as-activity:'.$this->id));
1789 if ($act instanceof Activity) {
1792 $act = new Activity();
1794 if (Event::handle('StartNoticeAsActivity', array($this, $act, $scoped))) {
1796 $act->id = $this->uri;
1797 $act->time = strtotime($this->created);
1799 $act->link = $this->getUrl();
1800 } catch (InvalidUrlException $e) {
1801 // The notice is probably a share or similar, which don't
1802 // have a representational URL of their own.
1804 $act->content = common_xml_safe_str($this->rendered);
1806 $profile = $this->getProfile();
1808 $act->actor = $profile->asActivityObject();
1809 $act->actor->extra[] = $profile->profileInfo($scoped);
1811 $act->verb = $this->verb;
1813 if (!$this->repeat_of) {
1814 $act->objects[] = $this->asActivityObject();
1817 // XXX: should this be handled by default processing for object entry?
1821 $tags = $this->getTags();
1823 foreach ($tags as $tag) {
1824 $cat = new AtomCategory();
1827 $act->categories[] = $cat;
1831 // XXX: use Atom Media and/or File activity objects instead
1833 $attachments = $this->attachments();
1835 foreach ($attachments as $attachment) {
1836 // Include local attachments in Activity
1837 if (!empty($attachment->filename)) {
1838 $act->enclosures[] = $attachment->getEnclosure();
1842 $ctx = new ActivityContext();
1845 $reply = $this->getParent();
1846 $ctx->replyToID = $reply->getUri();
1847 $ctx->replyToUrl = $reply->getUrl(true); // true for fallback to local URL, less messy
1848 } catch (NoParentNoticeException $e) {
1849 // This is not a reply to something
1850 } catch (NoResultException $e) {
1851 // Parent notice was probably deleted
1855 $ctx->location = Notice_location::locFromStored($this);
1856 } catch (ServerException $e) {
1857 $ctx->location = null;
1862 if (!empty($this->conversation)) {
1863 $conv = Conversation::getKV('id', $this->conversation);
1864 if ($conv instanceof Conversation) {
1865 $ctx->conversation = $conv->uri;
1869 $reply_ids = $this->getReplies();
1871 foreach ($reply_ids as $id) {
1872 $rprofile = Profile::getKV('id', $id);
1873 if ($rprofile instanceof Profile) {
1874 $ctx->attention[$rprofile->getUri()] = ActivityObject::PERSON;
1878 $groups = $this->getGroups();
1880 foreach ($groups as $group) {
1881 $ctx->attention[$group->getUri()] = ActivityObject::GROUP;
1884 switch ($this->scope) {
1885 case Notice::PUBLIC_SCOPE:
1886 $ctx->attention[ActivityContext::ATTN_PUBLIC] = ActivityObject::COLLECTION;
1888 case Notice::FOLLOWER_SCOPE:
1889 $surl = common_local_url("subscribers", array('nickname' => $profile->nickname));
1890 $ctx->attention[$surl] = ActivityObject::COLLECTION;
1894 $act->context = $ctx;
1896 $source = $this->getSource();
1898 if ($source instanceof Notice_source) {
1899 $act->generator = ActivityObject::fromNoticeSource($source);
1904 $atom_feed = $profile->getAtomFeed();
1906 if (!empty($atom_feed)) {
1908 $act->source = new ActivitySource();
1910 // XXX: we should store the actual feed ID
1912 $act->source->id = $atom_feed;
1914 // XXX: we should store the actual feed title
1916 $act->source->title = $profile->getBestName();
1918 $act->source->links['alternate'] = $profile->profileurl;
1919 $act->source->links['self'] = $atom_feed;
1921 $act->source->icon = $profile->avatarUrl(AVATAR_PROFILE_SIZE);
1923 $notice = $profile->getCurrentNotice();
1925 if ($notice instanceof Notice) {
1926 $act->source->updated = self::utcDate($notice->created);
1929 $user = User::getKV('id', $profile->id);
1931 if ($user instanceof User) {
1932 $act->source->links['license'] = common_config('license', 'url');
1936 if ($this->isLocal()) {
1937 $act->selfLink = common_local_url('ApiStatusesShow', array('id' => $this->id,
1938 'format' => 'atom'));
1939 $act->editLink = $act->selfLink;
1942 Event::handle('EndNoticeAsActivity', array($this, $act, $scoped));
1945 self::cacheSet(Cache::codeKey('notice:as-activity:'.$this->id), $act);
1950 // This has gotten way too long. Needs to be sliced up into functional bits
1951 // or ideally exported to a utility class.
1953 function asAtomEntry($namespace=false,
1956 Profile $scoped=null)
1958 $act = $this->asActivity($scoped);
1959 $act->extra[] = $this->noticeInfo($scoped);
1960 return $act->asString($namespace, $author, $source);
1964 * Extra notice info for atom entries
1966 * Clients use some extra notice info in the atom stream.
1967 * This gives it to them.
1969 * @param Profile $scoped The currently logged in/scoped profile
1971 * @return array representation of <statusnet:notice_info> element
1974 function noticeInfo(Profile $scoped=null)
1976 // local notice ID (useful to clients for ordering)
1978 $noticeInfoAttr = array('local_id' => $this->id);
1982 $ns = $this->getSource();
1984 if ($ns instanceof Notice_source) {
1985 $noticeInfoAttr['source'] = $ns->code;
1986 if (!empty($ns->url)) {
1987 $noticeInfoAttr['source_link'] = $ns->url;
1988 if (!empty($ns->name)) {
1989 $noticeInfoAttr['source'] = '<a href="'
1990 . htmlspecialchars($ns->url)
1991 . '" rel="nofollow">'
1992 . htmlspecialchars($ns->name)
1998 // favorite and repeated
2000 if ($scoped instanceof Profile) {
2001 $noticeInfoAttr['repeated'] = ($scoped->hasRepeated($this)) ? "true" : "false";
2004 if (!empty($this->repeat_of)) {
2005 $noticeInfoAttr['repeat_of'] = $this->repeat_of;
2008 Event::handle('StatusNetApiNoticeInfo', array($this, &$noticeInfoAttr, $scoped));
2010 return array('statusnet:notice_info', $noticeInfoAttr, null);
2014 * Returns an XML string fragment with a reference to a notice as an
2015 * Activity Streams noun object with the given element type.
2017 * Assumes that 'activity' namespace has been previously defined.
2019 * @param string $element one of 'subject', 'object', 'target'
2023 function asActivityNoun($element)
2025 $noun = $this->asActivityObject();
2026 return $noun->asString('activity:' . $element);
2029 public function asActivityObject()
2031 $object = new ActivityObject();
2033 if (Event::handle('StartActivityObjectFromNotice', array($this, &$object))) {
2034 $object->type = $this->object_type ?: ActivityObject::NOTE;
2035 $object->id = $this->getUri();
2036 $object->title = sprintf('New %1$s by %2$s', ActivityObject::canonicalType($object->type), $this->getProfile()->getNickname());
2037 $object->content = $this->rendered;
2038 $object->link = $this->getUrl();
2040 $object->extra[] = array('status_net', array('notice_id' => $this->id));
2042 Event::handle('EndActivityObjectFromNotice', array($this, &$object));
2049 * Determine which notice, if any, a new notice is in reply to.
2051 * For conversation tracking, we try to see where this notice fits
2052 * in the tree. Beware that this may very well give false positives
2053 * and add replies to wrong threads (if there have been newer posts
2054 * by the same user as we're replying to).
2056 * @param Profile $sender Author profile
2057 * @param string $content Final notice content
2059 * @return integer ID of replied-to notice, or null for not a reply.
2062 static function getInlineReplyTo(Profile $sender, $content)
2064 // Is there an initial @ or T?
2065 if (preg_match('/^T ([A-Z0-9]{1,64}) /', $content, $match)
2066 || preg_match('/^@([a-z0-9]{1,64})\s+/', $content, $match)) {
2067 $nickname = common_canonical_nickname($match[1]);
2072 // Figure out who that is.
2073 $recipient = common_relative_profile($sender, $nickname, common_sql_now());
2075 if ($recipient instanceof Profile) {
2076 // Get their last notice
2077 $last = $recipient->getCurrentNotice();
2078 if ($last instanceof Notice) {
2081 // Maybe in the future we want to handle something else below
2082 // so don't return getCurrentNotice() immediately.
2088 static function maxContent()
2090 $contentlimit = common_config('notice', 'contentlimit');
2091 // null => use global limit (distinct from 0!)
2092 if (is_null($contentlimit)) {
2093 $contentlimit = common_config('site', 'textlimit');
2095 return $contentlimit;
2098 static function contentTooLong($content)
2100 $contentlimit = self::maxContent();
2101 return ($contentlimit > 0 && !empty($content) && (mb_strlen($content) > $contentlimit));
2105 * Convenience function for posting a repeat of an existing message.
2107 * @param Profile $repeater Profile which is doing the repeat
2108 * @param string $source: posting source key, eg 'web', 'api', etc
2111 * @throws Exception on failure or permission problems
2113 function repeat(Profile $repeater, $source)
2115 $author = $this->getProfile();
2117 // TRANS: Message used to repeat a notice. RT is the abbreviation of 'retweet'.
2118 // TRANS: %1$s is the repeated user's name, %2$s is the repeated notice.
2119 $content = sprintf(_('RT @%1$s %2$s'),
2120 $author->getNickname(),
2123 $maxlen = self::maxContent();
2124 if ($maxlen > 0 && mb_strlen($content) > $maxlen) {
2125 // Web interface and current Twitter API clients will
2126 // pull the original notice's text, but some older
2127 // clients and RSS/Atom feeds will see this trimmed text.
2129 // Unfortunately this is likely to lose tags or URLs
2130 // at the end of long notices.
2131 $content = mb_substr($content, 0, $maxlen - 4) . ' ...';
2135 // Scope is same as this one's
2136 return self::saveNew($repeater->id,
2139 array('repeat_of' => $this->id,
2140 'scope' => $this->scope));
2143 // These are supposed to be in chron order!
2145 function repeatStream($limit=100)
2147 $cache = Cache::instance();
2149 if (empty($cache)) {
2150 $ids = $this->_repeatStreamDirect($limit);
2152 $idstr = $cache->get(Cache::key('notice:repeats:'.$this->id));
2153 if ($idstr !== false) {
2154 if (empty($idstr)) {
2157 $ids = explode(',', $idstr);
2160 $ids = $this->_repeatStreamDirect(100);
2161 $cache->set(Cache::key('notice:repeats:'.$this->id), implode(',', $ids));
2164 // We do a max of 100, so slice down to limit
2165 $ids = array_slice($ids, 0, $limit);
2169 return NoticeStream::getStreamByIds($ids);
2172 function _repeatStreamDirect($limit)
2174 $notice = new Notice();
2176 $notice->selectAdd(); // clears it
2177 $notice->selectAdd('id');
2179 $notice->repeat_of = $this->id;
2181 $notice->orderBy('created, id'); // NB: asc!
2183 if (!is_null($limit)) {
2184 $notice->limit(0, $limit);
2187 return $notice->fetchAll('id');
2190 static function locationOptions($lat, $lon, $location_id, $location_ns, $profile = null)
2194 if (!empty($location_id) && !empty($location_ns)) {
2195 $options['location_id'] = $location_id;
2196 $options['location_ns'] = $location_ns;
2198 $location = Location::fromId($location_id, $location_ns);
2200 if ($location instanceof Location) {
2201 $options['lat'] = $location->lat;
2202 $options['lon'] = $location->lon;
2205 } else if (!empty($lat) && !empty($lon)) {
2206 $options['lat'] = $lat;
2207 $options['lon'] = $lon;
2209 $location = Location::fromLatLon($lat, $lon);
2211 if ($location instanceof Location) {
2212 $options['location_id'] = $location->location_id;
2213 $options['location_ns'] = $location->location_ns;
2215 } else if (!empty($profile)) {
2216 if (isset($profile->lat) && isset($profile->lon)) {
2217 $options['lat'] = $profile->lat;
2218 $options['lon'] = $profile->lon;
2221 if (isset($profile->location_id) && isset($profile->location_ns)) {
2222 $options['location_id'] = $profile->location_id;
2223 $options['location_ns'] = $profile->location_ns;
2230 function clearAttentions()
2232 $att = new Attention();
2233 $att->notice_id = $this->getID();
2236 while ($att->fetch()) {
2237 // Can't do delete() on the object directly since it won't remove all of it
2238 $other = clone($att);
2244 function clearReplies()
2246 $replyNotice = new Notice();
2247 $replyNotice->reply_to = $this->id;
2249 //Null any notices that are replies to this notice
2251 if ($replyNotice->find()) {
2252 while ($replyNotice->fetch()) {
2253 $orig = clone($replyNotice);
2254 $replyNotice->reply_to = null;
2255 $replyNotice->update($orig);
2261 $reply = new Reply();
2262 $reply->notice_id = $this->id;
2264 if ($reply->find()) {
2265 while($reply->fetch()) {
2266 self::blow('reply:stream:%d', $reply->profile_id);
2274 function clearLocation()
2276 $loc = new Notice_location();
2277 $loc->notice_id = $this->id;
2284 function clearFiles()
2286 $f2p = new File_to_post();
2288 $f2p->post_id = $this->id;
2291 while ($f2p->fetch()) {
2295 // FIXME: decide whether to delete File objects
2296 // ...and related (actual) files
2299 function clearRepeats()
2301 $repeatNotice = new Notice();
2302 $repeatNotice->repeat_of = $this->id;
2304 //Null any notices that are repeats of this notice
2306 if ($repeatNotice->find()) {
2307 while ($repeatNotice->fetch()) {
2308 $orig = clone($repeatNotice);
2309 $repeatNotice->repeat_of = null;
2310 $repeatNotice->update($orig);
2315 function clearTags()
2317 $tag = new Notice_tag();
2318 $tag->notice_id = $this->id;
2321 while ($tag->fetch()) {
2322 self::blow('profile:notice_ids_tagged:%d:%s', $this->profile_id, Cache::keyize($tag->tag));
2323 self::blow('profile:notice_ids_tagged:%d:%s;last', $this->profile_id, Cache::keyize($tag->tag));
2324 self::blow('notice_tag:notice_ids:%s', Cache::keyize($tag->tag));
2325 self::blow('notice_tag:notice_ids:%s;last', Cache::keyize($tag->tag));
2333 function clearGroupInboxes()
2335 $gi = new Group_inbox();
2337 $gi->notice_id = $this->id;
2340 while ($gi->fetch()) {
2341 self::blow('user_group:notice_ids:%d', $gi->group_id);
2349 function distribute()
2351 // We always insert for the author so they don't
2353 Event::handle('StartNoticeDistribute', array($this));
2355 // If there's a failure, we want to _force_
2356 // distribution at this point.
2358 $qm = QueueManager::get();
2359 $qm->enqueue($this, 'distrib');
2360 } catch (Exception $e) {
2361 // If the exception isn't transient, this
2362 // may throw more exceptions as DQH does
2363 // its own enqueueing. So, we ignore them!
2365 $handler = new DistribQueueHandler();
2366 $handler->handle($this);
2367 } catch (Exception $e) {
2368 common_log(LOG_ERR, "emergency redistribution resulted in " . $e->getMessage());
2370 // Re-throw so somebody smarter can handle it.
2377 $result = parent::insert();
2379 if ($result === false) {
2380 common_log_db_error($this, 'INSERT', __FILE__);
2381 // TRANS: Server exception thrown when a stored object entry cannot be saved.
2382 throw new ServerException('Could not save Notice');
2385 // Profile::hasRepeated() abuses pkeyGet(), so we
2386 // have to clear manually
2387 if (!empty($this->repeat_of)) {
2388 $c = self::memcache();
2390 $ck = self::multicacheKey('Notice',
2391 array('profile_id' => $this->profile_id,
2392 'repeat_of' => $this->repeat_of));
2397 // Update possibly ID-dependent columns: URI, conversation
2398 // (now that INSERT has added the notice's local id)
2399 $orig = clone($this);
2402 // We can only get here if it's a local notice, since remote notices
2403 // should've bailed out earlier due to lacking a URI.
2404 if (empty($this->uri)) {
2405 $this->uri = sprintf('%s%s=%d:%s=%s',
2407 'noticeId', $this->id,
2408 'objectType', $this->get_object_type(true));
2412 if ($changed && $this->update($orig) === false) {
2413 common_log_db_error($notice, 'UPDATE', __FILE__);
2414 // TRANS: Server exception thrown when a notice cannot be updated.
2415 throw new ServerException(_('Problem saving notice.'));
2418 $this->blowOnInsert();
2424 * Get the source of the notice
2426 * @return Notice_source $ns A notice source object. 'code' is the only attribute
2427 * guaranteed to be populated.
2429 function getSource()
2431 if (empty($this->source)) {
2435 $ns = new Notice_source();
2436 switch ($this->source) {
2443 $ns->code = $this->source;
2446 $ns = Notice_source::getKV($this->source);
2448 $ns = new Notice_source();
2449 $ns->code = $this->source;
2450 $app = Oauth_application::getKV('name', $this->source);
2452 $ns->name = $app->name;
2453 $ns->url = $app->source_url;
2463 * Determine whether the notice was locally created
2465 * @return boolean locality
2468 public function isLocal()
2470 return ($this->is_local == Notice::LOCAL_PUBLIC ||
2471 $this->is_local == Notice::LOCAL_NONPUBLIC);
2474 public function isRepeat()
2476 return !empty($this->repeat_of);
2480 * Get the list of hash tags saved with this notice.
2482 * @return array of strings
2484 public function getTags()
2488 $keypart = sprintf('notice:tags:%d', $this->id);
2490 $tagstr = self::cacheGet($keypart);
2492 if ($tagstr !== false) {
2493 $tags = explode(',', $tagstr);
2495 $tag = new Notice_tag();
2496 $tag->notice_id = $this->id;
2498 while ($tag->fetch()) {
2499 $tags[] = $tag->tag;
2502 self::cacheSet($keypart, implode(',', $tags));
2508 static private function utcDate($dt)
2510 $dateStr = date('d F Y H:i:s', strtotime($dt));
2511 $d = new DateTime($dateStr, new DateTimeZone('UTC'));
2512 return $d->format(DATE_W3C);
2516 * Look up the creation timestamp for a given notice ID, even
2517 * if it's been deleted.
2520 * @return mixed string recorded creation timestamp, or false if can't be found
2522 public static function getAsTimestamp($id)
2528 $notice = Notice::getKV('id', $id);
2530 return $notice->created;
2533 $deleted = Deleted_notice::getKV('id', $id);
2535 return $deleted->created;
2542 * Build an SQL 'where' fragment for timestamp-based sorting from a since_id
2543 * parameter, matching notices posted after the given one (exclusive).
2545 * If the referenced notice can't be found, will return false.
2548 * @param string $idField
2549 * @param string $createdField
2550 * @return mixed string or false if no match
2552 public static function whereSinceId($id, $idField='id', $createdField='created')
2554 $since = Notice::getAsTimestamp($id);
2556 return sprintf("($createdField = '%s' and $idField > %d) or ($createdField > '%s')", $since, $id, $since);
2562 * Build an SQL 'where' fragment for timestamp-based sorting from a since_id
2563 * parameter, matching notices posted after the given one (exclusive), and
2564 * if necessary add it to the data object's query.
2566 * @param DB_DataObject $obj
2568 * @param string $idField
2569 * @param string $createdField
2570 * @return mixed string or false if no match
2572 public static function addWhereSinceId(DB_DataObject $obj, $id, $idField='id', $createdField='created')
2574 $since = self::whereSinceId($id, $idField, $createdField);
2576 $obj->whereAdd($since);
2581 * Build an SQL 'where' fragment for timestamp-based sorting from a max_id
2582 * parameter, matching notices posted before the given one (inclusive).
2584 * If the referenced notice can't be found, will return false.
2587 * @param string $idField
2588 * @param string $createdField
2589 * @return mixed string or false if no match
2591 public static function whereMaxId($id, $idField='id', $createdField='created')
2593 $max = Notice::getAsTimestamp($id);
2595 return sprintf("($createdField < '%s') or ($createdField = '%s' and $idField <= %d)", $max, $max, $id);
2601 * Build an SQL 'where' fragment for timestamp-based sorting from a max_id
2602 * parameter, matching notices posted before the given one (inclusive), and
2603 * if necessary add it to the data object's query.
2605 * @param DB_DataObject $obj
2607 * @param string $idField
2608 * @param string $createdField
2609 * @return mixed string or false if no match
2611 public static function addWhereMaxId(DB_DataObject $obj, $id, $idField='id', $createdField='created')
2613 $max = self::whereMaxId($id, $idField, $createdField);
2615 $obj->whereAdd($max);
2621 return (($this->is_local != Notice::LOCAL_NONPUBLIC) &&
2622 ($this->is_local != Notice::GATEWAY));
2626 * Check that the given profile is allowed to read, respond to, or otherwise
2627 * act on this notice.
2629 * The $scope member is a bitmask of scopes, representing a logical AND of the
2630 * scope requirement. So, 0x03 (Notice::ADDRESSEE_SCOPE | Notice::SITE_SCOPE) means
2631 * "only visible to people who are mentioned in the notice AND are users on this site."
2632 * Users on the site who are not mentioned in the notice will not be able to see the
2635 * @param Profile $profile The profile to check; pass null to check for public/unauthenticated users.
2637 * @return boolean whether the profile is in the notice's scope
2639 function inScope($profile)
2641 if (is_null($profile)) {
2642 $keypart = sprintf('notice:in-scope-for:%d:null', $this->id);
2644 $keypart = sprintf('notice:in-scope-for:%d:%d', $this->id, $profile->id);
2647 $result = self::cacheGet($keypart);
2649 if ($result === false) {
2651 if (Event::handle('StartNoticeInScope', array($this, $profile, &$bResult))) {
2652 $bResult = $this->_inScope($profile);
2653 Event::handle('EndNoticeInScope', array($this, $profile, &$bResult));
2655 $result = ($bResult) ? 1 : 0;
2656 self::cacheSet($keypart, $result, 0, 300);
2659 return ($result == 1) ? true : false;
2662 protected function _inScope($profile)
2664 if (!is_null($this->scope)) {
2665 $scope = $this->scope;
2667 $scope = self::defaultScope();
2670 if ($scope == 0 && !$this->getProfile()->isPrivateStream()) { // Not scoping, so it is public.
2671 return !$this->isHiddenSpam($profile);
2674 // If there's scope, anon cannot be in scope
2675 if (empty($profile)) {
2679 // Author is always in scope
2680 if ($this->profile_id == $profile->id) {
2684 // Only for users on this site
2685 if (($scope & Notice::SITE_SCOPE) && !$profile->isLocal()) {
2689 // Only for users mentioned in the notice
2690 if ($scope & Notice::ADDRESSEE_SCOPE) {
2692 $reply = Reply::pkeyGet(array('notice_id' => $this->id,
2693 'profile_id' => $profile->id));
2695 if (!$reply instanceof Reply) {
2700 // Only for members of the given group
2701 if ($scope & Notice::GROUP_SCOPE) {
2703 // XXX: just query for the single membership
2705 $groups = $this->getGroups();
2709 foreach ($groups as $group) {
2710 if ($profile->isMember($group)) {
2721 if ($scope & Notice::FOLLOWER_SCOPE || $this->getProfile()->isPrivateStream()) {
2723 if (!Subscription::exists($profile, $this->getProfile())) {
2728 return !$this->isHiddenSpam($profile);
2731 function isHiddenSpam($profile) {
2733 // Hide posts by silenced users from everyone but moderators.
2735 if (common_config('notice', 'hidespam')) {
2738 $author = $this->getProfile();
2739 } catch(Exception $e) {
2740 // If we can't get an author, keep it hidden.
2741 // XXX: technically not spam, but, whatever.
2745 if ($author->hasRole(Profile_role::SILENCED)) {
2746 if (!$profile instanceof Profile || (($profile->id !== $author->id) && (!$profile->hasRight(Right::REVIEWSPAM)))) {
2755 public function getParent()
2757 if (empty($this->reply_to)) {
2758 throw new NoParentNoticeException($this);
2760 return self::getByID($this->reply_to);
2764 * Magic function called at serialize() time.
2766 * We use this to drop a couple process-specific references
2767 * from DB_DataObject which can cause trouble in future
2770 * @return array of variable names to include in serialization.
2775 $vars = parent::__sleep();
2776 $skip = array('_profile', '_groups', '_attachments', '_faves', '_replies', '_repeats');
2777 return array_diff($vars, $skip);
2780 static function defaultScope()
2782 $scope = common_config('notice', 'defaultscope');
2783 if (is_null($scope)) {
2784 if (common_config('site', 'private')) {
2793 static function fillProfiles($notices)
2795 $map = self::getProfiles($notices);
2796 foreach ($notices as $entry=>$notice) {
2798 if (array_key_exists($notice->profile_id, $map)) {
2799 $notice->_setProfile($map[$notice->profile_id]);
2801 } catch (NoProfileException $e) {
2802 common_log(LOG_WARNING, "Failed to fill profile in Notice with non-existing entry for profile_id: {$e->profile_id}");
2803 unset($notices[$entry]);
2807 return array_values($map);
2810 static function getProfiles(&$notices)
2813 foreach ($notices as $notice) {
2814 $ids[] = $notice->profile_id;
2816 $ids = array_unique($ids);
2817 return Profile::pivotGet('id', $ids);
2820 static function fillGroups(&$notices)
2822 $ids = self::_idsOf($notices);
2823 $gis = Group_inbox::listGet('notice_id', $ids);
2826 foreach ($gis as $id => $gi) {
2829 $gids[] = $g->group_id;
2833 $gids = array_unique($gids);
2834 $group = User_group::pivotGet('id', $gids);
2835 foreach ($notices as $notice)
2838 $gi = $gis[$notice->id];
2839 foreach ($gi as $g) {
2840 $grps[] = $group[$g->group_id];
2842 $notice->_setGroups($grps);
2846 static function _idsOf(array &$notices)
2849 foreach ($notices as $notice) {
2850 $ids[$notice->id] = true;
2852 return array_keys($ids);
2855 static function fillAttachments(&$notices)
2857 $ids = self::_idsOf($notices);
2858 $f2pMap = File_to_post::listGet('post_id', $ids);
2860 foreach ($f2pMap as $noticeId => $f2ps) {
2861 foreach ($f2ps as $f2p) {
2862 $fileIds[] = $f2p->file_id;
2866 $fileIds = array_unique($fileIds);
2867 $fileMap = File::pivotGet('id', $fileIds);
2868 foreach ($notices as $notice)
2871 $f2ps = $f2pMap[$notice->id];
2872 foreach ($f2ps as $f2p) {
2873 $files[] = $fileMap[$f2p->file_id];
2875 $notice->_setAttachments($files);
2879 static function fillReplies(&$notices)
2881 $ids = self::_idsOf($notices);
2882 $replyMap = Reply::listGet('notice_id', $ids);
2883 foreach ($notices as $notice) {
2884 $replies = $replyMap[$notice->id];
2886 foreach ($replies as $reply) {
2887 $ids[] = $reply->profile_id;
2889 $notice->_setReplies($ids);
2893 static public function beforeSchemaUpdate()
2895 $table = strtolower(get_called_class());
2896 $schema = Schema::get();
2897 $schemadef = $schema->getTableDef($table);
2899 // 2015-09-04 We move Notice location data to Notice_location
2900 // First we see if we have to do this at all
2901 if (!isset($schemadef['fields']['lat'])
2902 && !isset($schemadef['fields']['lon'])
2903 && !isset($schemadef['fields']['location_id'])
2904 && !isset($schemadef['fields']['location_ns'])) {
2905 // We have already removed the location fields, so no need to migrate.
2908 // Then we make sure the Notice_location table is created!
2909 $schema->ensureTable('notice_location', Notice_location::schemaDef());
2911 // Then we continue on our road to migration!
2912 echo "\nFound old $table table, moving location data to 'notice_location' table... (this will probably take a LONG time, but can be aborted and continued)";
2914 $notice = new Notice();
2915 $notice->query(sprintf('SELECT id, lat, lon, location_id, location_ns FROM %1$s ' .
2916 'WHERE lat IS NOT NULL ' .
2917 'OR lon IS NOT NULL ' .
2918 'OR location_id IS NOT NULL ' .
2919 'OR location_ns IS NOT NULL',
2920 $schema->quoteIdentifier($table)));
2921 print "\nFound {$notice->N} notices with location data, inserting";
2922 while ($notice->fetch()) {
2923 $notloc = Notice_location::getKV('notice_id', $notice->id);
2924 if ($notloc instanceof Notice_location) {
2928 $notloc = new Notice_location();
2929 $notloc->notice_id = $notice->id;
2930 $notloc->lat= $notice->lat;
2931 $notloc->lon= $notice->lon;
2932 $notloc->location_id= $notice->location_id;
2933 $notloc->location_ns= $notice->location_ns;