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 getObjectType($canonical=false) {
285 ? ActivityObject::canonicalType($this->object_type)
286 : $this->object_type;
289 public static function getByUri($uri)
291 $notice = new Notice();
293 if (!$notice->find(true)) {
294 throw new NoResultException($notice);
300 * Extract #hashtags from this notice's content and save them to the database.
304 /* extract all #hastags */
305 $count = preg_match_all('/(?:^|\s)#([\pL\pN_\-\.]{1,64})/u', strtolower($this->content), $match);
310 /* Add them to the database */
311 return $this->saveKnownTags($match[1]);
315 * Record the given set of hash tags in the db for this notice.
316 * Given tag strings will be normalized and checked for dupes.
318 function saveKnownTags($hashtags)
320 //turn each into their canonical tag
321 //this is needed to remove dupes before saving e.g. #hash.tag = #hashtag
322 for($i=0; $i<count($hashtags); $i++) {
323 /* elide characters we don't want in the tag */
324 $hashtags[$i] = common_canonical_tag($hashtags[$i]);
327 foreach(array_unique($hashtags) as $hashtag) {
328 $this->saveTag($hashtag);
329 self::blow('profile:notice_ids_tagged:%d:%s', $this->profile_id, $hashtag);
335 * Record a single hash tag as associated with this notice.
336 * Tag format and uniqueness must be validated by caller.
338 function saveTag($hashtag)
340 $tag = new Notice_tag();
341 $tag->notice_id = $this->id;
342 $tag->tag = $hashtag;
343 $tag->created = $this->created;
344 $id = $tag->insert();
347 // TRANS: Server exception. %s are the error details.
348 throw new ServerException(sprintf(_('Database error inserting hashtag: %s.'),
349 $last_error->message));
353 // if it's saved, blow its cache
354 $tag->blowCache(false);
358 * Save a new notice and push it out to subscribers' inboxes.
359 * Poster's permissions are checked before sending.
361 * @param int $profile_id Profile ID of the poster
362 * @param string $content source message text; links may be shortened
363 * per current user's preference
364 * @param string $source source key ('web', 'api', etc)
365 * @param array $options Associative array of optional properties:
366 * string 'created' timestamp of notice; defaults to now
367 * int 'is_local' source/gateway ID, one of:
368 * Notice::LOCAL_PUBLIC - Local, ok to appear in public timeline
369 * Notice::REMOTE - Sent from a remote service;
370 * hide from public timeline but show in
371 * local "and friends" timelines
372 * Notice::LOCAL_NONPUBLIC - Local, but hide from public timeline
373 * Notice::GATEWAY - From another non-OStatus service;
374 * will not appear in public views
375 * float 'lat' decimal latitude for geolocation
376 * float 'lon' decimal longitude for geolocation
377 * int 'location_id' geoname identifier
378 * int 'location_ns' geoname namespace to interpret location_id
379 * int 'reply_to'; notice ID this is a reply to
380 * int 'repeat_of'; notice ID this is a repeat of
381 * string 'uri' unique ID for notice; a unique tag uri (can be url or anything too)
382 * string 'url' permalink to notice; defaults to local notice URL
383 * string 'rendered' rendered HTML version of content
384 * array 'replies' list of profile URIs for reply delivery in
385 * place of extracting @-replies from content.
386 * array 'groups' list of group IDs to deliver to, in place of
387 * extracting ! tags from content
388 * array 'tags' list of hashtag strings to save with the notice
389 * in place of extracting # tags from content
390 * array 'urls' list of attached/referred URLs to save with the
391 * notice in place of extracting links from content
392 * boolean 'distribute' whether to distribute the notice, default true
393 * string 'object_type' URL of the associated object type (default ActivityObject::NOTE)
394 * string 'verb' URL of the associated verb (default ActivityVerb::POST)
395 * int 'scope' Scope bitmask; default to SITE_SCOPE on private sites, 0 otherwise
397 * @fixme tag override
400 * @throws ClientException
402 static function saveNew($profile_id, $content, $source, array $options=null) {
403 $defaults = array('uri' => null,
405 'conversation' => null, // URI of conversation
406 'reply_to' => null, // This will override convo URI if the parent is known
407 'repeat_of' => null, // This will override convo URI if the repeated notice is known
409 'distribute' => true,
410 'object_type' => null,
413 if (!empty($options) && is_array($options)) {
414 $options = array_merge($defaults, $options);
420 if (!isset($is_local)) {
421 $is_local = Notice::LOCAL_PUBLIC;
424 $profile = Profile::getKV('id', $profile_id);
425 if (!$profile instanceof Profile) {
426 // TRANS: Client exception thrown when trying to save a notice for an unknown user.
427 throw new ClientException(_('Problem saving notice. Unknown user.'));
430 $user = User::getKV('id', $profile_id);
431 if ($user instanceof User) {
432 // Use the local user's shortening preferences, if applicable.
433 $final = $user->shortenLinks($content);
435 $final = common_shorten_links($content);
438 if (Notice::contentTooLong($final)) {
439 // TRANS: Client exception thrown if a notice contains too many characters.
440 throw new ClientException(_('Problem saving notice. Too long.'));
443 if (common_config('throttle', 'enabled') && !Notice::checkEditThrottle($profile_id)) {
444 common_log(LOG_WARNING, 'Excessive posting by profile #' . $profile_id . '; throttled.');
445 // TRANS: Client exception thrown when a user tries to post too many notices in a given time frame.
446 throw new ClientException(_('Too many notices too fast; take a breather '.
447 'and post again in a few minutes.'));
450 if (common_config('site', 'dupelimit') > 0 && !Notice::checkDupes($profile_id, $final)) {
451 common_log(LOG_WARNING, 'Dupe posting by profile #' . $profile_id . '; throttled.');
452 // TRANS: Client exception thrown when a user tries to post too many duplicate notices in a given time frame.
453 throw new ClientException(_('Too many duplicate messages too quickly;'.
454 ' take a breather and post again in a few minutes.'));
457 if (!$profile->hasRight(Right::NEWNOTICE)) {
458 common_log(LOG_WARNING, "Attempted post from user disallowed to post: " . $profile->nickname);
460 // TRANS: Client exception thrown when a user tries to post while being banned.
461 throw new ClientException(_('You are banned from posting notices on this site.'), 403);
464 $notice = new Notice();
465 $notice->profile_id = $profile_id;
467 $autosource = common_config('public', 'autosource');
469 // Sandboxed are non-false, but not 1, either
471 if (!$profile->hasRight(Right::PUBLICNOTICE) ||
472 ($source && $autosource && in_array($source, $autosource))) {
473 $notice->is_local = Notice::LOCAL_NONPUBLIC;
475 $notice->is_local = $is_local;
478 if (!empty($created)) {
479 $notice->created = $created;
481 $notice->created = common_sql_now();
484 if (!$notice->isLocal()) {
485 // Only do these checks for non-local notices. Local notices will generate these values later.
486 if (!common_valid_http_url($url)) {
487 common_debug('Bad notice URL: ['.$url.'], URI: ['.$uri.']. Cannot link back to original! This is normal for shared notices etc.');
490 throw new ServerException('No URI for remote notice. Cannot accept that.');
494 $notice->content = $final;
496 $notice->source = $source;
500 // Get the groups here so we can figure out replies and such
501 if (!isset($groups)) {
502 $groups = User_group::idsFromText($notice->content, $profile);
507 // Handle repeat case
509 if (!empty($options['repeat_of'])) {
511 // Check for a private one
513 $repeat = Notice::getByID($options['repeat_of']);
515 if ($profile->sameAs($repeat->getProfile())) {
516 // TRANS: Client error displayed when trying to repeat an own notice.
517 throw new ClientException(_('You cannot repeat your own notice.'));
520 if ($repeat->scope != Notice::SITE_SCOPE &&
521 $repeat->scope != Notice::PUBLIC_SCOPE) {
522 // TRANS: Client error displayed when trying to repeat a non-public notice.
523 throw new ClientException(_('Cannot repeat a private notice.'), 403);
526 if (!$repeat->inScope($profile)) {
527 // The generic checks above should cover this, but let's be sure!
528 // TRANS: Client error displayed when trying to repeat a notice you cannot access.
529 throw new ClientException(_('Cannot repeat a notice you cannot read.'), 403);
532 if ($profile->hasRepeated($repeat)) {
533 // TRANS: Client error displayed when trying to repeat an already repeated notice.
534 throw new ClientException(_('You already repeated that notice.'));
537 $notice->repeat_of = $repeat->id;
538 $notice->conversation = $repeat->conversation;
542 // If $reply_to is specified, we check that it exists, and then
543 // return it if it does
544 if (!empty($reply_to)) {
545 $reply = Notice::getKV('id', $reply_to);
546 } elseif (in_array($source, array('xmpp', 'mail', 'sms'))) {
547 // If the source lacks capability of sending the "reply_to"
548 // metadata, let's try to find an inline replyto-reference.
549 $reply = self::getInlineReplyTo($profile, $final);
552 if ($reply instanceof Notice) {
553 if (!$reply->inScope($profile)) {
554 // TRANS: Client error displayed when trying to reply to a notice a the target has no access to.
555 // TRANS: %1$s is a user nickname, %2$d is a notice ID (number).
556 throw new ClientException(sprintf(_('%1$s has no access to notice %2$d.'),
557 $profile->nickname, $reply->id), 403);
560 // If it's a repeat, the reply_to should be to the original
561 if ($reply->isRepeat()) {
562 $notice->reply_to = $reply->repeat_of;
564 $notice->reply_to = $reply->id;
566 // But the conversation ought to be the same :)
567 $notice->conversation = $reply->conversation;
569 // If the original is private to a group, and notice has
570 // no group specified, make it to the same group(s)
572 if (empty($groups) && ($reply->scope & Notice::GROUP_SCOPE)) {
574 $replyGroups = $reply->getGroups();
575 foreach ($replyGroups as $group) {
576 if ($profile->isMember($group)) {
577 $groups[] = $group->id;
585 // If we don't know the reply, we might know the conversation!
586 // This will happen if a known remote user replies to an
587 // unknown remote user - within a known conversation.
588 if (empty($notice->conversation) and !empty($options['conversation'])) {
589 $conv = Conversation::getKV('uri', $options['conversation']);
590 if ($conv instanceof Conversation) {
591 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.').');
592 $notice->conversation = $conv->id;
594 // Conversation URI was not found, so we must create it. But we can't create it
595 // until we have a Notice ID because of the database layout...
596 // $options['conversation'] will be used later after the $notice->insert();
597 common_debug('Conversation URI not found, so we have to create it after inserting this Notice: '.$options['conversation']);
600 // If we're not using the attached conversation URI let's remove it
601 // so we don't mistake ourselves later, when creating our own Conversation.
602 // This implies that the notice knows which conversation it belongs to.
603 $options['conversation'] = null;
607 $notloc = new Notice_location();
608 if (!empty($lat) && !empty($lon)) {
613 if (!empty($location_ns) && !empty($location_id)) {
614 $notloc->location_id = $location_id;
615 $notloc->location_ns = $location_ns;
618 if (!empty($rendered)) {
619 $notice->rendered = $rendered;
621 $notice->rendered = common_render_content($final, $notice);
625 if ($notice->isRepeat()) {
626 $notice->verb = ActivityVerb::SHARE;
627 $notice->object_type = ActivityObject::ACTIVITY;
629 $notice->verb = ActivityVerb::POST;
632 $notice->verb = $verb;
635 if (empty($object_type)) {
636 $notice->object_type = (empty($notice->reply_to)) ? ActivityObject::NOTE : ActivityObject::COMMENT;
638 $notice->object_type = $object_type;
641 if (is_null($scope) && $reply instanceof Notice) {
642 $notice->scope = $reply->scope;
644 $notice->scope = $scope;
647 $notice->scope = self::figureOutScope($profile, $groups, $notice->scope);
649 if (Event::handle('StartNoticeSave', array(&$notice))) {
651 // XXX: some of these functions write to the DB
654 $notice->insert(); // throws exception on failure, if successful we have an ->id
656 if (($notloc->lat && $notloc->lon) || ($notloc->location_id && $notloc->location_ns)) {
657 $notloc->notice_id = $notice->getID();
658 $notloc->insert(); // store the notice location if it had any information
661 // If it's not part of a conversation, it's
662 // the beginning of a new conversation.
663 if (empty($notice->conversation)) {
664 $orig = clone($notice);
665 // $act->context->conversation will be null if it was not provided
667 $conv = Conversation::create($notice, $options['conversation']);
668 $notice->conversation = $conv->id;
669 $notice->update($orig);
671 } catch (Exception $e) {
672 // Let's test if we managed initial insert, which would imply
673 // failing on some update-part (check 'insert()'). Delete if
674 // something had been stored to the database.
675 if (!empty($notice->id)) {
682 // Clear the cache for subscribed users, so they'll update at next request
683 // XXX: someone clever could prepend instead of clearing the cache
685 // Save per-notice metadata...
687 if (isset($replies)) {
688 $notice->saveKnownReplies($replies);
690 $notice->saveReplies();
694 $notice->saveKnownTags($tags);
699 // Note: groups may save tags, so must be run after tags are saved
700 // to avoid errors on duplicates.
701 // Note: groups should always be set.
703 $notice->saveKnownGroups($groups);
706 $notice->saveKnownUrls($urls);
712 // Prepare inbox delivery, may be queued to background.
713 $notice->distribute();
719 static function saveActivity(Activity $act, Profile $actor, array $options=array())
721 // First check if we're going to let this Activity through from the specific actor
722 if (!$actor->hasRight(Right::NEWNOTICE)) {
723 common_log(LOG_WARNING, "Attempted post from user disallowed to post: " . $actor->getNickname());
725 // TRANS: Client exception thrown when a user tries to post while being banned.
726 throw new ClientException(_m('You are banned from posting notices on this site.'), 403);
728 if (common_config('throttle', 'enabled') && !self::checkEditThrottle($actor->id)) {
729 common_log(LOG_WARNING, 'Excessive posting by profile #' . $actor->id . '; throttled.');
730 // TRANS: Client exception thrown when a user tries to post too many notices in a given time frame.
731 throw new ClientException(_m('Too many notices too fast; take a breather '.
732 'and post again in a few minutes.'));
735 // Get ActivityObject properties
736 if (!empty($act->id)) {
738 $options['uri'] = $act->id;
739 $options['url'] = $act->link;
741 $actobj = count($act->objects)==1 ? $act->objects[0] : null;
742 if (!is_null($actobj) && !empty($actobj->id)) {
743 $options['uri'] = $actobj->id;
745 $options['url'] = $actobj->link;
746 } elseif (preg_match('!^https?://!', $actobj->id)) {
747 $options['url'] = $actobj->id;
754 'is_local' => self::LOCAL_PUBLIC,
755 'mentions' => array(),
759 'source' => 'unknown',
764 'distribute' => true);
766 // options will have default values when nothing has been supplied
767 $options = array_merge($defaults, $options);
768 foreach (array_keys($defaults) as $key) {
769 // Only convert the keynames we specify ourselves from 'defaults' array into variables
770 $$key = $options[$key];
772 extract($options, EXTR_SKIP);
774 $stored = new Notice();
777 if ($stored->find()) {
778 common_debug('cannot create duplicate Notice URI: '.$stored->uri);
779 throw new Exception('Notice URI already exists');
783 $stored->profile_id = $actor->id;
784 $stored->source = $source;
787 $stored->verb = $act->verb;
789 // Use the local user's shortening preferences, if applicable.
790 $stored->rendered = $actor->isLocal()
791 ? $actor->shortenLinks($act->content)
793 $stored->content = common_strip_html($stored->rendered);
795 $autosource = common_config('public', 'autosource');
797 // Sandboxed are non-false, but not 1, either
798 if (!$actor->hasRight(Right::PUBLICNOTICE) ||
799 ($source && $autosource && in_array($source, $autosource))) {
800 $stored->is_local = Notice::LOCAL_NONPUBLIC;
802 $stored->is_local = $is_local;
805 // Maybe a missing act-time should be fatal if the actor is not local?
806 if (!empty($act->time)) {
807 $stored->created = common_sql_date($act->time);
809 $stored->created = common_sql_now();
813 if ($act->context instanceof ActivityContext && !empty($act->context->replyToID)) {
814 $reply = self::getKV('uri', $act->context->replyToID);
816 if (!$reply instanceof Notice && $act->target instanceof ActivityObject) {
817 $reply = self::getKV('uri', $act->target->id);
820 if ($reply instanceof Notice) {
821 if (!$reply->inScope($actor)) {
822 // TRANS: Client error displayed when trying to reply to a notice a the target has no access to.
823 // TRANS: %1$s is a user nickname, %2$d is a notice ID (number).
824 throw new ClientException(sprintf(_m('%1$s has no right to reply to notice %2$d.'), $actor->getNickname(), $reply->id), 403);
827 $stored->reply_to = $reply->id;
828 $stored->conversation = $reply->conversation;
830 // If the original is private to a group, and notice has no group specified,
831 // make it to the same group(s)
832 if (empty($groups) && ($reply->scope & Notice::GROUP_SCOPE)) {
834 $replyGroups = $reply->getGroups();
835 foreach ($replyGroups as $group) {
836 if ($actor->isMember($group)) {
837 $groups[] = $group->id;
842 if (is_null($scope)) {
843 $scope = $reply->scope;
846 // If we don't know the reply, we might know the conversation!
847 // This will happen if a known remote user replies to an
848 // unknown remote user - within a known conversation.
849 if (empty($stored->conversation) and !empty($act->context->conversation)) {
850 $conv = Conversation::getKV('uri', $act->context->conversation);
851 if ($conv instanceof Conversation) {
852 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.').');
853 $stored->conversation = $conv->getID();
855 // Conversation URI was not found, so we must create it. But we can't create it
856 // until we have a Notice ID because of the database layout...
857 // $options['conversation'] will be used later after the $stored->insert();
858 common_debug('Conversation URI from activity context not found, so we have to create it after inserting this Notice: '.$act->context->conversation);
864 if ($act->context instanceof ActivityContext) {
865 if ($act->context->location instanceof Location) {
866 $notloc = Notice_location::fromLocation($act->context->location);
869 $act->context = new ActivityContext();
872 $stored->scope = self::figureOutScope($actor, $groups, $scope);
874 foreach ($act->categories as $cat) {
876 $term = common_canonical_tag($cat->term);
883 foreach ($act->enclosures as $href) {
884 // @todo FIXME: Save these locally or....?
888 if (Event::handle('StartNoticeSave', array(&$stored))) {
889 // XXX: some of these functions write to the DB
892 $stored->insert(); // throws exception on error
894 if ($notloc instanceof Notice_location) {
895 $notloc->notice_id = $stored->getID();
899 $orig = clone($stored); // for updating later in this try clause
902 Event::handle('StoreActivityObject', array($act, $stored, $options, &$object));
903 if (empty($object)) {
904 throw new ServerException('Unsuccessful call to StoreActivityObject '.$stored->uri . ': '.$act->asString());
907 // If it's not part of a conversation, it's the beginning
908 // of a new one (or belongs to a previously unknown URI).
909 if (empty($stored->conversation)) {
910 // $act->context->conversation will be null if it was not provided
911 common_debug('Creating a new conversation for stored notice ID='.$stored->getID().' with URI: '.$act->context->conversation);
912 $conv = Conversation::create($stored, $act->context->conversation);
913 $stored->conversation = $conv->getID();
916 $stored->update($orig);
917 } catch (Exception $e) {
918 if (empty($stored->id)) {
919 common_debug('Failed to save stored object entry in database ('.$e->getMessage().')');
921 common_debug('Failed to store activity object in database ('.$e->getMessage().'), deleting notice id '.$stored->id);
927 if (!$stored instanceof Notice) {
928 throw new ServerException('StartNoticeSave did not give back a Notice');
931 // Save per-notice metadata...
935 // This event lets plugins filter out non-local recipients (attentions we don't care about)
936 // Used primarily for OStatus (and if we don't federate, all attentions would be local anyway)
937 Event::handle('GetLocalAttentions', array($actor, $act->context->attention, &$mentions, &$groups));
939 if (!empty($mentions)) {
940 $stored->saveKnownReplies($mentions);
942 $stored->saveReplies();
946 $stored->saveKnownTags($tags);
951 // Note: groups may save tags, so must be run after tags are saved
952 // to avoid errors on duplicates.
953 // Note: groups should always be set.
955 $stored->saveKnownGroups($groups);
958 $stored->saveKnownUrls($urls);
964 // Prepare inbox delivery, may be queued to background.
965 $stored->distribute();
971 static public function figureOutScope(Profile $actor, array $groups, $scope=null) {
972 if (is_null($scope)) {
973 $scope = self::defaultScope();
976 // For private streams
978 $user = $actor->getUser();
979 // FIXME: We can't do bit comparison with == (Legacy StatusNet thing. Let's keep it for now.)
980 if ($user->private_stream && ($scope == Notice::PUBLIC_SCOPE || $scope == Notice::SITE_SCOPE)) {
981 $scope |= Notice::FOLLOWER_SCOPE;
983 } catch (NoSuchUserException $e) {
984 // TODO: Not a local user, so we don't know about scope preferences... yet!
987 // Force the scope for private groups
988 foreach ($groups as $group_id) {
990 $group = User_group::getByID($group_id);
991 if ($group->force_scope) {
992 $scope |= Notice::GROUP_SCOPE;
995 } catch (Exception $e) {
996 common_log(LOG_ERR, 'Notice figureOutScope threw exception: '.$e->getMessage());
1003 function blowOnInsert($conversation = false)
1005 $this->blowStream('profile:notice_ids:%d', $this->profile_id);
1007 if ($this->isPublic()) {
1008 $this->blowStream('public');
1009 $this->blowStream('networkpublic');
1012 self::blow('notice:list-ids:conversation:%s', $this->conversation);
1013 self::blow('conversation:notice_count:%d', $this->conversation);
1015 if ($this->isRepeat()) {
1016 // XXX: we should probably only use one of these
1017 $this->blowStream('notice:repeats:%d', $this->repeat_of);
1018 self::blow('notice:list-ids:repeat_of:%d', $this->repeat_of);
1021 $original = Notice::getKV('id', $this->repeat_of);
1023 if ($original instanceof Notice) {
1024 $originalUser = User::getKV('id', $original->profile_id);
1025 if ($originalUser instanceof User) {
1026 $this->blowStream('user:repeats_of_me:%d', $originalUser->id);
1030 $profile = Profile::getKV($this->profile_id);
1032 if ($profile instanceof Profile) {
1033 $profile->blowNoticeCount();
1036 $ptags = $this->getProfileTags();
1037 foreach ($ptags as $ptag) {
1038 $ptag->blowNoticeStreamCache();
1043 * Clear cache entries related to this notice at delete time.
1044 * Necessary to avoid breaking paging on public, profile timelines.
1046 function blowOnDelete()
1048 $this->blowOnInsert();
1050 self::blow('profile:notice_ids:%d;last', $this->profile_id);
1052 if ($this->isPublic()) {
1053 self::blow('public;last');
1054 self::blow('networkpublic;last');
1057 self::blow('fave:by_notice', $this->id);
1059 if ($this->conversation) {
1060 // In case we're the first, will need to calc a new root.
1061 self::blow('notice:conversation_root:%d', $this->conversation);
1064 $ptags = $this->getProfileTags();
1065 foreach ($ptags as $ptag) {
1066 $ptag->blowNoticeStreamCache(true);
1070 function blowStream()
1072 $c = self::memcache();
1078 $args = func_get_args();
1079 $format = array_shift($args);
1080 $keyPart = vsprintf($format, $args);
1081 $cacheKey = Cache::key($keyPart);
1082 $c->delete($cacheKey);
1084 // delete the "last" stream, too, if this notice is
1085 // older than the top of that stream
1087 $lastKey = $cacheKey.';last';
1089 $lastStr = $c->get($lastKey);
1091 if ($lastStr !== false) {
1092 $window = explode(',', $lastStr);
1093 $lastID = $window[0];
1094 $lastNotice = Notice::getKV('id', $lastID);
1095 if (!$lastNotice instanceof Notice // just weird
1096 || strtotime($lastNotice->created) >= strtotime($this->created)) {
1097 $c->delete($lastKey);
1102 /** save all urls in the notice to the db
1104 * follow redirects and save all available file information
1105 * (mimetype, date, size, oembed, etc.)
1109 function saveUrls() {
1110 if (common_config('attachments', 'process_links')) {
1111 common_replace_urls_callback($this->content, array($this, 'saveUrl'), $this);
1116 * Save the given URLs as related links/attachments to the db
1118 * follow redirects and save all available file information
1119 * (mimetype, date, size, oembed, etc.)
1123 function saveKnownUrls($urls)
1125 if (common_config('attachments', 'process_links')) {
1126 // @fixme validation?
1127 foreach (array_unique($urls) as $url) {
1128 $this->saveUrl($url, $this);
1136 function saveUrl($url, Notice $notice) {
1138 File::processNew($url, $notice);
1139 } catch (ServerException $e) {
1140 // Could not save URL. Log it?
1144 static function checkDupes($profile_id, $content) {
1145 $profile = Profile::getKV($profile_id);
1146 if (!$profile instanceof Profile) {
1149 $notice = $profile->getNotices(0, CachingNoticeStream::CACHE_WINDOW);
1150 if (!empty($notice)) {
1152 while ($notice->fetch()) {
1153 if (time() - strtotime($notice->created) >= common_config('site', 'dupelimit')) {
1155 } else if ($notice->content == $content) {
1160 // If we get here, oldest item in cache window is not
1161 // old enough for dupe limit; do direct check against DB
1162 $notice = new Notice();
1163 $notice->profile_id = $profile_id;
1164 $notice->content = $content;
1165 $threshold = common_sql_date(time() - common_config('site', 'dupelimit'));
1166 $notice->whereAdd(sprintf("created > '%s'", $notice->escape($threshold)));
1168 $cnt = $notice->count();
1172 static function checkEditThrottle($profile_id) {
1173 $profile = Profile::getKV($profile_id);
1174 if (!$profile instanceof Profile) {
1177 // Get the Nth notice
1178 $notice = $profile->getNotices(common_config('throttle', 'count') - 1, 1);
1179 if ($notice && $notice->fetch()) {
1180 // If the Nth notice was posted less than timespan seconds ago
1181 if (time() - strtotime($notice->created) <= common_config('throttle', 'timespan')) {
1186 // Either not N notices in the stream, OR the Nth was not posted within timespan seconds
1190 protected $_attachments = array();
1192 function attachments() {
1193 if (isset($this->_attachments[$this->id])) {
1194 return $this->_attachments[$this->id];
1197 $f2ps = File_to_post::listGet('post_id', array($this->id));
1199 foreach ($f2ps[$this->id] as $f2p) {
1200 $ids[] = $f2p->file_id;
1203 $files = File::multiGet('id', $ids);
1204 $this->_attachments[$this->id] = $files->fetchAll();
1205 return $this->_attachments[$this->id];
1208 function _setAttachments($attachments)
1210 $this->_attachments[$this->id] = $attachments;
1213 static function publicStream($offset=0, $limit=20, $since_id=null, $max_id=null)
1215 $stream = new PublicNoticeStream();
1216 return $stream->getNotices($offset, $limit, $since_id, $max_id);
1219 static function conversationStream($id, $offset=0, $limit=20, $since_id=null, $max_id=null)
1221 $stream = new ConversationNoticeStream($id);
1222 return $stream->getNotices($offset, $limit, $since_id, $max_id);
1226 * Is this notice part of an active conversation?
1228 * @return boolean true if other messages exist in the same
1229 * conversation, false if this is the only one
1231 function hasConversation()
1233 if (empty($this->conversation)) {
1234 // this notice is not part of a conversation apparently
1235 // FIXME: all notices should have a conversation value, right?
1239 $stream = new ConversationNoticeStream($this->conversation);
1240 $notice = $stream->getNotices(/*offset*/ 1, /*limit*/ 1);
1242 // if our "offset 1, limit 1" query got a result, return true else false
1243 return $notice->N > 0;
1247 * Grab the earliest notice from this conversation.
1249 * @return Notice or null
1251 function conversationRoot($profile=-1)
1253 // XXX: can this happen?
1255 if (empty($this->conversation)) {
1259 // Get the current profile if not specified
1261 if (is_int($profile) && $profile == -1) {
1262 $profile = Profile::current();
1265 // If this notice is out of scope, no root for you!
1267 if (!$this->inScope($profile)) {
1271 // If this isn't a reply to anything, then it's its own
1272 // root if it's the earliest notice in the conversation:
1274 if (empty($this->reply_to)) {
1276 $root->conversation = $this->conversation;
1277 $root->orderBy('notice.created ASC');
1278 $root->find(true); // true means "fetch first result"
1283 if (is_null($profile)) {
1284 $keypart = sprintf('notice:conversation_root:%d:null', $this->id);
1286 $keypart = sprintf('notice:conversation_root:%d:%d',
1291 $root = self::cacheGet($keypart);
1293 if ($root !== false && $root->inScope($profile)) {
1300 $parent = $last->getParent();
1301 if ($parent->inScope($profile)) {
1305 } catch (NoParentNoticeException $e) {
1306 // Latest notice has no parent
1307 } catch (NoResultException $e) {
1308 // Notice was not found, so we can't go further up in the tree.
1309 // FIXME: Maybe we should do this in a more stable way where deleted
1310 // notices won't break conversation chains?
1312 // No parent, or parent out of scope
1317 self::cacheSet($keypart, $root);
1323 * Pull up a full list of local recipients who will be getting
1324 * this notice in their inbox. Results will be cached, so don't
1325 * change the input data wily-nilly!
1327 * @param array $groups optional list of Group objects;
1328 * if left empty, will be loaded from group_inbox records
1329 * @param array $recipient optional list of reply profile ids
1330 * if left empty, will be loaded from reply records
1331 * @return array associating recipient user IDs with an inbox source constant
1333 function whoGets(array $groups=null, array $recipients=null)
1335 $c = self::memcache();
1338 $ni = $c->get(Cache::key('notice:who_gets:'.$this->id));
1339 if ($ni !== false) {
1344 if (is_null($recipients)) {
1345 $recipients = $this->getReplies();
1350 // Give plugins a chance to add folks in at start...
1351 if (Event::handle('StartNoticeWhoGets', array($this, &$ni))) {
1353 $users = $this->getSubscribedUsers();
1354 foreach ($users as $id) {
1355 $ni[$id] = NOTICE_INBOX_SOURCE_SUB;
1358 if (is_null($groups)) {
1359 $groups = $this->getGroups();
1361 foreach ($groups as $group) {
1362 $users = $group->getUserMembers();
1363 foreach ($users as $id) {
1364 if (!array_key_exists($id, $ni)) {
1365 $ni[$id] = NOTICE_INBOX_SOURCE_GROUP;
1370 $ptAtts = $this->getAttentionsFromProfileTags();
1371 foreach ($ptAtts as $key=>$val) {
1372 if (!array_key_exists($key, $ni)) {
1377 foreach ($recipients as $recipient) {
1378 if (!array_key_exists($recipient, $ni)) {
1379 $ni[$recipient] = NOTICE_INBOX_SOURCE_REPLY;
1383 // Exclude any deleted, non-local, or blocking recipients.
1384 $profile = $this->getProfile();
1385 $originalProfile = null;
1386 if ($this->isRepeat()) {
1387 // Check blocks against the original notice's poster as well.
1388 $original = Notice::getKV('id', $this->repeat_of);
1389 if ($original instanceof Notice) {
1390 $originalProfile = $original->getProfile();
1394 foreach ($ni as $id => $source) {
1396 $user = User::getKV('id', $id);
1397 if (!$user instanceof User ||
1398 $user->hasBlocked($profile) ||
1399 ($originalProfile && $user->hasBlocked($originalProfile))) {
1402 } catch (UserNoProfileException $e) {
1403 // User doesn't have a profile; invalid; skip them.
1408 // Give plugins a chance to filter out...
1409 Event::handle('EndNoticeWhoGets', array($this, &$ni));
1413 // XXX: pack this data better
1414 $c->set(Cache::key('notice:who_gets:'.$this->id), $ni);
1420 function getSubscribedUsers()
1424 if(common_config('db','quote_identifiers'))
1425 $user_table = '"user"';
1426 else $user_table = 'user';
1430 'FROM '. $user_table .' JOIN subscription '.
1431 'ON '. $user_table .'.id = subscription.subscriber ' .
1432 'WHERE subscription.subscribed = %d ';
1434 $user->query(sprintf($qry, $this->profile_id));
1438 while ($user->fetch()) {
1447 function getProfileTags()
1449 $profile = $this->getProfile();
1450 $list = $profile->getOtherTags($profile);
1453 while($list->fetch()) {
1454 $ptags[] = clone($list);
1460 public function getAttentionsFromProfileTags()
1463 $ptags = $this->getProfileTags();
1464 foreach ($ptags as $ptag) {
1465 $users = $ptag->getUserSubscribers();
1466 foreach ($users as $id) {
1467 $ni[$id] = NOTICE_INBOX_SOURCE_PROFILE_TAG;
1474 * Record this notice to the given group inboxes for delivery.
1475 * Overrides the regular parsing of !group markup.
1477 * @param string $group_ids
1478 * @fixme might prefer URIs as identifiers, as for replies?
1479 * best with generalizations on user_group to support
1480 * remote groups better.
1482 function saveKnownGroups($group_ids)
1484 if (!is_array($group_ids)) {
1485 // TRANS: Server exception thrown when no array is provided to the method saveKnownGroups().
1486 throw new ServerException(_('Bad type provided to saveKnownGroups.'));
1490 foreach (array_unique($group_ids) as $id) {
1491 $group = User_group::getKV('id', $id);
1492 if ($group instanceof User_group) {
1493 common_log(LOG_DEBUG, "Local delivery to group id $id, $group->nickname");
1494 $result = $this->addToGroupInbox($group);
1496 common_log_db_error($gi, 'INSERT', __FILE__);
1499 if (common_config('group', 'addtag')) {
1500 // we automatically add a tag for every group name, too
1502 $tag = Notice_tag::pkeyGet(array('tag' => common_canonical_tag($group->nickname),
1503 'notice_id' => $this->id));
1505 if (is_null($tag)) {
1506 $this->saveTag($group->nickname);
1510 $groups[] = clone($group);
1512 common_log(LOG_ERR, "Local delivery to group id $id skipped, doesn't exist");
1519 function addToGroupInbox(User_group $group)
1521 $gi = Group_inbox::pkeyGet(array('group_id' => $group->id,
1522 'notice_id' => $this->id));
1524 if (!$gi instanceof Group_inbox) {
1526 $gi = new Group_inbox();
1528 $gi->group_id = $group->id;
1529 $gi->notice_id = $this->id;
1530 $gi->created = $this->created;
1532 $result = $gi->insert();
1535 common_log_db_error($gi, 'INSERT', __FILE__);
1536 // TRANS: Server exception thrown when an update for a group inbox fails.
1537 throw new ServerException(_('Problem saving group inbox.'));
1540 self::blow('user_group:notice_ids:%d', $gi->group_id);
1547 * Save reply records indicating that this notice needs to be
1548 * delivered to the local users with the given URIs.
1550 * Since this is expected to be used when saving foreign-sourced
1551 * messages, we won't deliver to any remote targets as that's the
1552 * source service's responsibility.
1554 * Mail notifications etc will be handled later.
1556 * @param array $uris Array of unique identifier URIs for recipients
1558 function saveKnownReplies(array $uris)
1564 $sender = Profile::getKV($this->profile_id);
1566 foreach (array_unique($uris) as $uri) {
1568 $profile = Profile::fromUri($uri);
1569 } catch (UnknownUriException $e) {
1570 common_log(LOG_WARNING, "Unable to determine profile for URI '$uri'");
1574 if ($profile->hasBlocked($sender)) {
1575 common_log(LOG_INFO, "Not saving reply to profile {$profile->id} ($uri) from sender {$sender->id} because of a block.");
1579 $this->saveReply($profile->id);
1580 self::blow('reply:stream:%d', $profile->id);
1587 * Pull @-replies from this message's content in StatusNet markup format
1588 * and save reply records indicating that this message needs to be
1589 * delivered to those users.
1591 * Mail notifications to local profiles will be sent later.
1593 * @return array of integer profile IDs
1596 function saveReplies()
1598 // Don't save reply data for repeats
1600 if ($this->isRepeat()) {
1604 $sender = $this->getProfile();
1608 // If it's a reply, save for the replied-to author
1610 $parent = $this->getParent();
1611 $parentauthor = $parent->getProfile();
1612 $this->saveReply($parentauthor->id);
1613 $replied[$parentauthor->id] = 1;
1614 self::blow('reply:stream:%d', $parentauthor->id);
1615 } catch (NoParentNoticeException $e) {
1616 // Not a reply, since it has no parent!
1617 } catch (NoResultException $e) {
1618 // Parent notice was probably deleted
1621 // @todo ideally this parser information would only
1622 // be calculated once.
1624 $mentions = common_find_mentions($this->content, $this);
1626 // store replied only for first @ (what user/notice what the reply directed,
1627 // we assume first @ is it)
1629 foreach ($mentions as $mention) {
1631 foreach ($mention['mentioned'] as $mentioned) {
1633 // skip if they're already covered
1634 if (array_key_exists($mentioned->id, $replied)) {
1638 // Don't save replies from blocked profile to local user
1640 $mentioned_user = User::getKV('id', $mentioned->id);
1641 if ($mentioned_user instanceof User && $mentioned_user->hasBlocked($sender)) {
1645 $this->saveReply($mentioned->id);
1646 $replied[$mentioned->id] = 1;
1647 self::blow('reply:stream:%d', $mentioned->id);
1651 $recipientIds = array_keys($replied);
1653 return $recipientIds;
1656 function saveReply($profileId)
1658 $reply = new Reply();
1660 $reply->notice_id = $this->id;
1661 $reply->profile_id = $profileId;
1662 $reply->modified = $this->created;
1669 protected $_replies = array();
1672 * Pull the complete list of @-mentioned profile IDs for this notice.
1674 * @return array of integer profile ids
1676 function getReplies()
1678 if (!isset($this->_replies[$this->getID()])) {
1679 $mentions = Reply::multiGet('notice_id', array($this->getID()));
1680 $this->_replies[$this->getID()] = $mentions->fetchAll('profile_id');
1682 return $this->_replies[$this->getID()];
1685 function _setReplies($replies)
1687 $this->_replies[$this->getID()] = $replies;
1691 * Pull the complete list of @-reply targets for this notice.
1693 * @return array of Profiles
1695 function getReplyProfiles()
1697 $ids = $this->getReplies();
1699 $profiles = Profile::multiGet('id', $ids);
1701 return $profiles->fetchAll();
1705 * Send e-mail notifications to local @-reply targets.
1707 * Replies must already have been saved; this is expected to be run
1708 * from the distrib queue handler.
1710 function sendReplyNotifications()
1712 // Don't send reply notifications for repeats
1714 if ($this->isRepeat()) {
1718 $recipientIds = $this->getReplies();
1719 if (Event::handle('StartNotifyMentioned', array($this, &$recipientIds))) {
1720 require_once INSTALLDIR.'/lib/mail.php';
1722 foreach ($recipientIds as $recipientId) {
1723 $user = User::getKV('id', $recipientId);
1724 if ($user instanceof User) {
1725 mail_notify_attn($user, $this);
1728 Event::handle('EndNotifyMentioned', array($this, $recipientIds));
1733 * Pull list of groups this notice needs to be delivered to,
1734 * as previously recorded by saveKnownGroups().
1736 * @return array of Group objects
1739 protected $_groups = array();
1741 function getGroups()
1743 // Don't save groups for repeats
1745 if (!empty($this->repeat_of)) {
1749 if (isset($this->_groups[$this->id])) {
1750 return $this->_groups[$this->id];
1753 $gis = Group_inbox::listGet('notice_id', array($this->id));
1757 foreach ($gis[$this->id] as $gi) {
1758 $ids[] = $gi->group_id;
1761 $groups = User_group::multiGet('id', $ids);
1762 $this->_groups[$this->id] = $groups->fetchAll();
1763 return $this->_groups[$this->id];
1766 function _setGroups($groups)
1768 $this->_groups[$this->id] = $groups;
1772 * Convert a notice into an activity for export.
1774 * @param Profile $scoped The currently logged in/scoped profile
1776 * @return Activity activity object representing this Notice.
1779 function asActivity(Profile $scoped=null)
1781 $act = self::cacheGet(Cache::codeKey('notice:as-activity:'.$this->id));
1783 if ($act instanceof Activity) {
1786 $act = new Activity();
1788 if (Event::handle('StartNoticeAsActivity', array($this, $act, $scoped))) {
1790 $act->id = $this->uri;
1791 $act->time = strtotime($this->created);
1793 $act->link = $this->getUrl();
1794 } catch (InvalidUrlException $e) {
1795 // The notice is probably a share or similar, which don't
1796 // have a representational URL of their own.
1798 $act->content = common_xml_safe_str($this->rendered);
1800 $profile = $this->getProfile();
1802 $act->actor = $profile->asActivityObject();
1803 $act->actor->extra[] = $profile->profileInfo($scoped);
1805 $act->verb = $this->verb;
1807 if (!$this->repeat_of) {
1808 $act->objects[] = $this->asActivityObject();
1811 // XXX: should this be handled by default processing for object entry?
1815 $tags = $this->getTags();
1817 foreach ($tags as $tag) {
1818 $cat = new AtomCategory();
1821 $act->categories[] = $cat;
1825 // XXX: use Atom Media and/or File activity objects instead
1827 $attachments = $this->attachments();
1829 foreach ($attachments as $attachment) {
1830 // Include local attachments in Activity
1831 if (!empty($attachment->filename)) {
1832 $act->enclosures[] = $attachment->getEnclosure();
1836 $ctx = new ActivityContext();
1839 $reply = $this->getParent();
1840 $ctx->replyToID = $reply->getUri();
1841 $ctx->replyToUrl = $reply->getUrl(true); // true for fallback to local URL, less messy
1842 } catch (NoParentNoticeException $e) {
1843 // This is not a reply to something
1844 } catch (NoResultException $e) {
1845 // Parent notice was probably deleted
1849 $ctx->location = Notice_location::locFromStored($this);
1850 } catch (ServerException $e) {
1851 $ctx->location = null;
1856 if (!empty($this->conversation)) {
1857 $conv = Conversation::getKV('id', $this->conversation);
1858 if ($conv instanceof Conversation) {
1859 $ctx->conversation = $conv->uri;
1863 $reply_ids = $this->getReplies();
1865 foreach ($reply_ids as $id) {
1866 $rprofile = Profile::getKV('id', $id);
1867 if ($rprofile instanceof Profile) {
1868 $ctx->attention[$rprofile->getUri()] = ActivityObject::PERSON;
1872 $groups = $this->getGroups();
1874 foreach ($groups as $group) {
1875 $ctx->attention[$group->getUri()] = ActivityObject::GROUP;
1878 switch ($this->scope) {
1879 case Notice::PUBLIC_SCOPE:
1880 $ctx->attention[ActivityContext::ATTN_PUBLIC] = ActivityObject::COLLECTION;
1882 case Notice::FOLLOWER_SCOPE:
1883 $surl = common_local_url("subscribers", array('nickname' => $profile->nickname));
1884 $ctx->attention[$surl] = ActivityObject::COLLECTION;
1888 $act->context = $ctx;
1890 $source = $this->getSource();
1892 if ($source instanceof Notice_source) {
1893 $act->generator = ActivityObject::fromNoticeSource($source);
1898 $atom_feed = $profile->getAtomFeed();
1900 if (!empty($atom_feed)) {
1902 $act->source = new ActivitySource();
1904 // XXX: we should store the actual feed ID
1906 $act->source->id = $atom_feed;
1908 // XXX: we should store the actual feed title
1910 $act->source->title = $profile->getBestName();
1912 $act->source->links['alternate'] = $profile->profileurl;
1913 $act->source->links['self'] = $atom_feed;
1915 $act->source->icon = $profile->avatarUrl(AVATAR_PROFILE_SIZE);
1917 $notice = $profile->getCurrentNotice();
1919 if ($notice instanceof Notice) {
1920 $act->source->updated = self::utcDate($notice->created);
1923 $user = User::getKV('id', $profile->id);
1925 if ($user instanceof User) {
1926 $act->source->links['license'] = common_config('license', 'url');
1930 if ($this->isLocal()) {
1931 $act->selfLink = common_local_url('ApiStatusesShow', array('id' => $this->id,
1932 'format' => 'atom'));
1933 $act->editLink = $act->selfLink;
1936 Event::handle('EndNoticeAsActivity', array($this, $act, $scoped));
1939 self::cacheSet(Cache::codeKey('notice:as-activity:'.$this->id), $act);
1944 // This has gotten way too long. Needs to be sliced up into functional bits
1945 // or ideally exported to a utility class.
1947 function asAtomEntry($namespace=false,
1950 Profile $scoped=null)
1952 $act = $this->asActivity($scoped);
1953 $act->extra[] = $this->noticeInfo($scoped);
1954 return $act->asString($namespace, $author, $source);
1958 * Extra notice info for atom entries
1960 * Clients use some extra notice info in the atom stream.
1961 * This gives it to them.
1963 * @param Profile $scoped The currently logged in/scoped profile
1965 * @return array representation of <statusnet:notice_info> element
1968 function noticeInfo(Profile $scoped=null)
1970 // local notice ID (useful to clients for ordering)
1972 $noticeInfoAttr = array('local_id' => $this->id);
1976 $ns = $this->getSource();
1978 if ($ns instanceof Notice_source) {
1979 $noticeInfoAttr['source'] = $ns->code;
1980 if (!empty($ns->url)) {
1981 $noticeInfoAttr['source_link'] = $ns->url;
1982 if (!empty($ns->name)) {
1983 $noticeInfoAttr['source'] = '<a href="'
1984 . htmlspecialchars($ns->url)
1985 . '" rel="nofollow">'
1986 . htmlspecialchars($ns->name)
1992 // favorite and repeated
1994 if ($scoped instanceof Profile) {
1995 $noticeInfoAttr['repeated'] = ($scoped->hasRepeated($this)) ? "true" : "false";
1998 if (!empty($this->repeat_of)) {
1999 $noticeInfoAttr['repeat_of'] = $this->repeat_of;
2002 Event::handle('StatusNetApiNoticeInfo', array($this, &$noticeInfoAttr, $scoped));
2004 return array('statusnet:notice_info', $noticeInfoAttr, null);
2008 * Returns an XML string fragment with a reference to a notice as an
2009 * Activity Streams noun object with the given element type.
2011 * Assumes that 'activity' namespace has been previously defined.
2013 * @param string $element one of 'subject', 'object', 'target'
2017 function asActivityNoun($element)
2019 $noun = $this->asActivityObject();
2020 return $noun->asString('activity:' . $element);
2023 public function asActivityObject()
2025 $object = new ActivityObject();
2027 if (Event::handle('StartActivityObjectFromNotice', array($this, &$object))) {
2028 $object->type = $this->object_type ?: ActivityObject::NOTE;
2029 $object->id = $this->getUri();
2030 $object->title = sprintf('New %1$s by %2$s', ActivityObject::canonicalType($object->type), $this->getProfile()->getNickname());
2031 $object->content = $this->rendered;
2032 $object->link = $this->getUrl();
2034 $object->extra[] = array('status_net', array('notice_id' => $this->id));
2036 Event::handle('EndActivityObjectFromNotice', array($this, &$object));
2043 * Determine which notice, if any, a new notice is in reply to.
2045 * For conversation tracking, we try to see where this notice fits
2046 * in the tree. Beware that this may very well give false positives
2047 * and add replies to wrong threads (if there have been newer posts
2048 * by the same user as we're replying to).
2050 * @param Profile $sender Author profile
2051 * @param string $content Final notice content
2053 * @return integer ID of replied-to notice, or null for not a reply.
2056 static function getInlineReplyTo(Profile $sender, $content)
2058 // Is there an initial @ or T?
2059 if (preg_match('/^T ([A-Z0-9]{1,64}) /', $content, $match)
2060 || preg_match('/^@([a-z0-9]{1,64})\s+/', $content, $match)) {
2061 $nickname = common_canonical_nickname($match[1]);
2066 // Figure out who that is.
2067 $recipient = common_relative_profile($sender, $nickname, common_sql_now());
2069 if ($recipient instanceof Profile) {
2070 // Get their last notice
2071 $last = $recipient->getCurrentNotice();
2072 if ($last instanceof Notice) {
2075 // Maybe in the future we want to handle something else below
2076 // so don't return getCurrentNotice() immediately.
2082 static function maxContent()
2084 $contentlimit = common_config('notice', 'contentlimit');
2085 // null => use global limit (distinct from 0!)
2086 if (is_null($contentlimit)) {
2087 $contentlimit = common_config('site', 'textlimit');
2089 return $contentlimit;
2092 static function contentTooLong($content)
2094 $contentlimit = self::maxContent();
2095 return ($contentlimit > 0 && !empty($content) && (mb_strlen($content) > $contentlimit));
2099 * Convenience function for posting a repeat of an existing message.
2101 * @param Profile $repeater Profile which is doing the repeat
2102 * @param string $source: posting source key, eg 'web', 'api', etc
2105 * @throws Exception on failure or permission problems
2107 function repeat(Profile $repeater, $source)
2109 $author = $this->getProfile();
2111 // TRANS: Message used to repeat a notice. RT is the abbreviation of 'retweet'.
2112 // TRANS: %1$s is the repeated user's name, %2$s is the repeated notice.
2113 $content = sprintf(_('RT @%1$s %2$s'),
2114 $author->getNickname(),
2117 $maxlen = self::maxContent();
2118 if ($maxlen > 0 && mb_strlen($content) > $maxlen) {
2119 // Web interface and current Twitter API clients will
2120 // pull the original notice's text, but some older
2121 // clients and RSS/Atom feeds will see this trimmed text.
2123 // Unfortunately this is likely to lose tags or URLs
2124 // at the end of long notices.
2125 $content = mb_substr($content, 0, $maxlen - 4) . ' ...';
2129 // Scope is same as this one's
2130 return self::saveNew($repeater->id,
2133 array('repeat_of' => $this->id,
2134 'scope' => $this->scope));
2137 // These are supposed to be in chron order!
2139 function repeatStream($limit=100)
2141 $cache = Cache::instance();
2143 if (empty($cache)) {
2144 $ids = $this->_repeatStreamDirect($limit);
2146 $idstr = $cache->get(Cache::key('notice:repeats:'.$this->id));
2147 if ($idstr !== false) {
2148 if (empty($idstr)) {
2151 $ids = explode(',', $idstr);
2154 $ids = $this->_repeatStreamDirect(100);
2155 $cache->set(Cache::key('notice:repeats:'.$this->id), implode(',', $ids));
2158 // We do a max of 100, so slice down to limit
2159 $ids = array_slice($ids, 0, $limit);
2163 return NoticeStream::getStreamByIds($ids);
2166 function _repeatStreamDirect($limit)
2168 $notice = new Notice();
2170 $notice->selectAdd(); // clears it
2171 $notice->selectAdd('id');
2173 $notice->repeat_of = $this->id;
2175 $notice->orderBy('created, id'); // NB: asc!
2177 if (!is_null($limit)) {
2178 $notice->limit(0, $limit);
2181 return $notice->fetchAll('id');
2184 static function locationOptions($lat, $lon, $location_id, $location_ns, $profile = null)
2188 if (!empty($location_id) && !empty($location_ns)) {
2189 $options['location_id'] = $location_id;
2190 $options['location_ns'] = $location_ns;
2192 $location = Location::fromId($location_id, $location_ns);
2194 if ($location instanceof Location) {
2195 $options['lat'] = $location->lat;
2196 $options['lon'] = $location->lon;
2199 } else if (!empty($lat) && !empty($lon)) {
2200 $options['lat'] = $lat;
2201 $options['lon'] = $lon;
2203 $location = Location::fromLatLon($lat, $lon);
2205 if ($location instanceof Location) {
2206 $options['location_id'] = $location->location_id;
2207 $options['location_ns'] = $location->location_ns;
2209 } else if (!empty($profile)) {
2210 if (isset($profile->lat) && isset($profile->lon)) {
2211 $options['lat'] = $profile->lat;
2212 $options['lon'] = $profile->lon;
2215 if (isset($profile->location_id) && isset($profile->location_ns)) {
2216 $options['location_id'] = $profile->location_id;
2217 $options['location_ns'] = $profile->location_ns;
2224 function clearAttentions()
2226 $att = new Attention();
2227 $att->notice_id = $this->getID();
2230 while ($att->fetch()) {
2231 // Can't do delete() on the object directly since it won't remove all of it
2232 $other = clone($att);
2238 function clearReplies()
2240 $replyNotice = new Notice();
2241 $replyNotice->reply_to = $this->id;
2243 //Null any notices that are replies to this notice
2245 if ($replyNotice->find()) {
2246 while ($replyNotice->fetch()) {
2247 $orig = clone($replyNotice);
2248 $replyNotice->reply_to = null;
2249 $replyNotice->update($orig);
2255 $reply = new Reply();
2256 $reply->notice_id = $this->id;
2258 if ($reply->find()) {
2259 while($reply->fetch()) {
2260 self::blow('reply:stream:%d', $reply->profile_id);
2268 function clearLocation()
2270 $loc = new Notice_location();
2271 $loc->notice_id = $this->id;
2278 function clearFiles()
2280 $f2p = new File_to_post();
2282 $f2p->post_id = $this->id;
2285 while ($f2p->fetch()) {
2289 // FIXME: decide whether to delete File objects
2290 // ...and related (actual) files
2293 function clearRepeats()
2295 $repeatNotice = new Notice();
2296 $repeatNotice->repeat_of = $this->id;
2298 //Null any notices that are repeats of this notice
2300 if ($repeatNotice->find()) {
2301 while ($repeatNotice->fetch()) {
2302 $orig = clone($repeatNotice);
2303 $repeatNotice->repeat_of = null;
2304 $repeatNotice->update($orig);
2309 function clearTags()
2311 $tag = new Notice_tag();
2312 $tag->notice_id = $this->id;
2315 while ($tag->fetch()) {
2316 self::blow('profile:notice_ids_tagged:%d:%s', $this->profile_id, Cache::keyize($tag->tag));
2317 self::blow('profile:notice_ids_tagged:%d:%s;last', $this->profile_id, Cache::keyize($tag->tag));
2318 self::blow('notice_tag:notice_ids:%s', Cache::keyize($tag->tag));
2319 self::blow('notice_tag:notice_ids:%s;last', Cache::keyize($tag->tag));
2327 function clearGroupInboxes()
2329 $gi = new Group_inbox();
2331 $gi->notice_id = $this->id;
2334 while ($gi->fetch()) {
2335 self::blow('user_group:notice_ids:%d', $gi->group_id);
2343 function distribute()
2345 // We always insert for the author so they don't
2347 Event::handle('StartNoticeDistribute', array($this));
2349 // If there's a failure, we want to _force_
2350 // distribution at this point.
2352 $qm = QueueManager::get();
2353 $qm->enqueue($this, 'distrib');
2354 } catch (Exception $e) {
2355 // If the exception isn't transient, this
2356 // may throw more exceptions as DQH does
2357 // its own enqueueing. So, we ignore them!
2359 $handler = new DistribQueueHandler();
2360 $handler->handle($this);
2361 } catch (Exception $e) {
2362 common_log(LOG_ERR, "emergency redistribution resulted in " . $e->getMessage());
2364 // Re-throw so somebody smarter can handle it.
2371 $result = parent::insert();
2373 if ($result === false) {
2374 common_log_db_error($this, 'INSERT', __FILE__);
2375 // TRANS: Server exception thrown when a stored object entry cannot be saved.
2376 throw new ServerException('Could not save Notice');
2379 // Profile::hasRepeated() abuses pkeyGet(), so we
2380 // have to clear manually
2381 if (!empty($this->repeat_of)) {
2382 $c = self::memcache();
2384 $ck = self::multicacheKey('Notice',
2385 array('profile_id' => $this->profile_id,
2386 'repeat_of' => $this->repeat_of));
2391 // Update possibly ID-dependent columns: URI, conversation
2392 // (now that INSERT has added the notice's local id)
2393 $orig = clone($this);
2396 // We can only get here if it's a local notice, since remote notices
2397 // should've bailed out earlier due to lacking a URI.
2398 if (empty($this->uri)) {
2399 $this->uri = sprintf('%s%s=%d:%s=%s',
2401 'noticeId', $this->id,
2402 'objectType', $this->getObjectType(true));
2406 if ($changed && $this->update($orig) === false) {
2407 common_log_db_error($notice, 'UPDATE', __FILE__);
2408 // TRANS: Server exception thrown when a notice cannot be updated.
2409 throw new ServerException(_('Problem saving notice.'));
2412 $this->blowOnInsert();
2418 * Get the source of the notice
2420 * @return Notice_source $ns A notice source object. 'code' is the only attribute
2421 * guaranteed to be populated.
2423 function getSource()
2425 if (empty($this->source)) {
2429 $ns = new Notice_source();
2430 switch ($this->source) {
2437 $ns->code = $this->source;
2440 $ns = Notice_source::getKV($this->source);
2442 $ns = new Notice_source();
2443 $ns->code = $this->source;
2444 $app = Oauth_application::getKV('name', $this->source);
2446 $ns->name = $app->name;
2447 $ns->url = $app->source_url;
2457 * Determine whether the notice was locally created
2459 * @return boolean locality
2462 public function isLocal()
2464 return ($this->is_local == Notice::LOCAL_PUBLIC ||
2465 $this->is_local == Notice::LOCAL_NONPUBLIC);
2468 public function isRepeat()
2470 return !empty($this->repeat_of);
2474 * Get the list of hash tags saved with this notice.
2476 * @return array of strings
2478 public function getTags()
2482 $keypart = sprintf('notice:tags:%d', $this->id);
2484 $tagstr = self::cacheGet($keypart);
2486 if ($tagstr !== false) {
2487 $tags = explode(',', $tagstr);
2489 $tag = new Notice_tag();
2490 $tag->notice_id = $this->id;
2492 while ($tag->fetch()) {
2493 $tags[] = $tag->tag;
2496 self::cacheSet($keypart, implode(',', $tags));
2502 static private function utcDate($dt)
2504 $dateStr = date('d F Y H:i:s', strtotime($dt));
2505 $d = new DateTime($dateStr, new DateTimeZone('UTC'));
2506 return $d->format(DATE_W3C);
2510 * Look up the creation timestamp for a given notice ID, even
2511 * if it's been deleted.
2514 * @return mixed string recorded creation timestamp, or false if can't be found
2516 public static function getAsTimestamp($id)
2522 $notice = Notice::getKV('id', $id);
2524 return $notice->created;
2527 $deleted = Deleted_notice::getKV('id', $id);
2529 return $deleted->created;
2536 * Build an SQL 'where' fragment for timestamp-based sorting from a since_id
2537 * parameter, matching notices posted after the given one (exclusive).
2539 * If the referenced notice can't be found, will return false.
2542 * @param string $idField
2543 * @param string $createdField
2544 * @return mixed string or false if no match
2546 public static function whereSinceId($id, $idField='id', $createdField='created')
2548 $since = Notice::getAsTimestamp($id);
2550 return sprintf("($createdField = '%s' and $idField > %d) or ($createdField > '%s')", $since, $id, $since);
2556 * Build an SQL 'where' fragment for timestamp-based sorting from a since_id
2557 * parameter, matching notices posted after the given one (exclusive), and
2558 * if necessary add it to the data object's query.
2560 * @param DB_DataObject $obj
2562 * @param string $idField
2563 * @param string $createdField
2564 * @return mixed string or false if no match
2566 public static function addWhereSinceId(DB_DataObject $obj, $id, $idField='id', $createdField='created')
2568 $since = self::whereSinceId($id, $idField, $createdField);
2570 $obj->whereAdd($since);
2575 * Build an SQL 'where' fragment for timestamp-based sorting from a max_id
2576 * parameter, matching notices posted before the given one (inclusive).
2578 * If the referenced notice can't be found, will return false.
2581 * @param string $idField
2582 * @param string $createdField
2583 * @return mixed string or false if no match
2585 public static function whereMaxId($id, $idField='id', $createdField='created')
2587 $max = Notice::getAsTimestamp($id);
2589 return sprintf("($createdField < '%s') or ($createdField = '%s' and $idField <= %d)", $max, $max, $id);
2595 * Build an SQL 'where' fragment for timestamp-based sorting from a max_id
2596 * parameter, matching notices posted before the given one (inclusive), and
2597 * if necessary add it to the data object's query.
2599 * @param DB_DataObject $obj
2601 * @param string $idField
2602 * @param string $createdField
2603 * @return mixed string or false if no match
2605 public static function addWhereMaxId(DB_DataObject $obj, $id, $idField='id', $createdField='created')
2607 $max = self::whereMaxId($id, $idField, $createdField);
2609 $obj->whereAdd($max);
2615 return (($this->is_local != Notice::LOCAL_NONPUBLIC) &&
2616 ($this->is_local != Notice::GATEWAY));
2620 * Check that the given profile is allowed to read, respond to, or otherwise
2621 * act on this notice.
2623 * The $scope member is a bitmask of scopes, representing a logical AND of the
2624 * scope requirement. So, 0x03 (Notice::ADDRESSEE_SCOPE | Notice::SITE_SCOPE) means
2625 * "only visible to people who are mentioned in the notice AND are users on this site."
2626 * Users on the site who are not mentioned in the notice will not be able to see the
2629 * @param Profile $profile The profile to check; pass null to check for public/unauthenticated users.
2631 * @return boolean whether the profile is in the notice's scope
2633 function inScope($profile)
2635 if (is_null($profile)) {
2636 $keypart = sprintf('notice:in-scope-for:%d:null', $this->id);
2638 $keypart = sprintf('notice:in-scope-for:%d:%d', $this->id, $profile->id);
2641 $result = self::cacheGet($keypart);
2643 if ($result === false) {
2645 if (Event::handle('StartNoticeInScope', array($this, $profile, &$bResult))) {
2646 $bResult = $this->_inScope($profile);
2647 Event::handle('EndNoticeInScope', array($this, $profile, &$bResult));
2649 $result = ($bResult) ? 1 : 0;
2650 self::cacheSet($keypart, $result, 0, 300);
2653 return ($result == 1) ? true : false;
2656 protected function _inScope($profile)
2658 if (!is_null($this->scope)) {
2659 $scope = $this->scope;
2661 $scope = self::defaultScope();
2664 if ($scope == 0 && !$this->getProfile()->isPrivateStream()) { // Not scoping, so it is public.
2665 return !$this->isHiddenSpam($profile);
2668 // If there's scope, anon cannot be in scope
2669 if (empty($profile)) {
2673 // Author is always in scope
2674 if ($this->profile_id == $profile->id) {
2678 // Only for users on this site
2679 if (($scope & Notice::SITE_SCOPE) && !$profile->isLocal()) {
2683 // Only for users mentioned in the notice
2684 if ($scope & Notice::ADDRESSEE_SCOPE) {
2686 $reply = Reply::pkeyGet(array('notice_id' => $this->id,
2687 'profile_id' => $profile->id));
2689 if (!$reply instanceof Reply) {
2694 // Only for members of the given group
2695 if ($scope & Notice::GROUP_SCOPE) {
2697 // XXX: just query for the single membership
2699 $groups = $this->getGroups();
2703 foreach ($groups as $group) {
2704 if ($profile->isMember($group)) {
2715 if ($scope & Notice::FOLLOWER_SCOPE || $this->getProfile()->isPrivateStream()) {
2717 if (!Subscription::exists($profile, $this->getProfile())) {
2722 return !$this->isHiddenSpam($profile);
2725 function isHiddenSpam($profile) {
2727 // Hide posts by silenced users from everyone but moderators.
2729 if (common_config('notice', 'hidespam')) {
2732 $author = $this->getProfile();
2733 } catch(Exception $e) {
2734 // If we can't get an author, keep it hidden.
2735 // XXX: technically not spam, but, whatever.
2739 if ($author->hasRole(Profile_role::SILENCED)) {
2740 if (!$profile instanceof Profile || (($profile->id !== $author->id) && (!$profile->hasRight(Right::REVIEWSPAM)))) {
2749 public function getParent()
2751 if (empty($this->reply_to)) {
2752 throw new NoParentNoticeException($this);
2754 return self::getByID($this->reply_to);
2758 * Magic function called at serialize() time.
2760 * We use this to drop a couple process-specific references
2761 * from DB_DataObject which can cause trouble in future
2764 * @return array of variable names to include in serialization.
2769 $vars = parent::__sleep();
2770 $skip = array('_profile', '_groups', '_attachments', '_faves', '_replies', '_repeats');
2771 return array_diff($vars, $skip);
2774 static function defaultScope()
2776 $scope = common_config('notice', 'defaultscope');
2777 if (is_null($scope)) {
2778 if (common_config('site', 'private')) {
2787 static function fillProfiles($notices)
2789 $map = self::getProfiles($notices);
2790 foreach ($notices as $entry=>$notice) {
2792 if (array_key_exists($notice->profile_id, $map)) {
2793 $notice->_setProfile($map[$notice->profile_id]);
2795 } catch (NoProfileException $e) {
2796 common_log(LOG_WARNING, "Failed to fill profile in Notice with non-existing entry for profile_id: {$e->profile_id}");
2797 unset($notices[$entry]);
2801 return array_values($map);
2804 static function getProfiles(&$notices)
2807 foreach ($notices as $notice) {
2808 $ids[] = $notice->profile_id;
2810 $ids = array_unique($ids);
2811 return Profile::pivotGet('id', $ids);
2814 static function fillGroups(&$notices)
2816 $ids = self::_idsOf($notices);
2817 $gis = Group_inbox::listGet('notice_id', $ids);
2820 foreach ($gis as $id => $gi) {
2823 $gids[] = $g->group_id;
2827 $gids = array_unique($gids);
2828 $group = User_group::pivotGet('id', $gids);
2829 foreach ($notices as $notice)
2832 $gi = $gis[$notice->id];
2833 foreach ($gi as $g) {
2834 $grps[] = $group[$g->group_id];
2836 $notice->_setGroups($grps);
2840 static function _idsOf(array &$notices)
2843 foreach ($notices as $notice) {
2844 $ids[$notice->id] = true;
2846 return array_keys($ids);
2849 static function fillAttachments(&$notices)
2851 $ids = self::_idsOf($notices);
2852 $f2pMap = File_to_post::listGet('post_id', $ids);
2854 foreach ($f2pMap as $noticeId => $f2ps) {
2855 foreach ($f2ps as $f2p) {
2856 $fileIds[] = $f2p->file_id;
2860 $fileIds = array_unique($fileIds);
2861 $fileMap = File::pivotGet('id', $fileIds);
2862 foreach ($notices as $notice)
2865 $f2ps = $f2pMap[$notice->id];
2866 foreach ($f2ps as $f2p) {
2867 $files[] = $fileMap[$f2p->file_id];
2869 $notice->_setAttachments($files);
2873 static function fillReplies(&$notices)
2875 $ids = self::_idsOf($notices);
2876 $replyMap = Reply::listGet('notice_id', $ids);
2877 foreach ($notices as $notice) {
2878 $replies = $replyMap[$notice->id];
2880 foreach ($replies as $reply) {
2881 $ids[] = $reply->profile_id;
2883 $notice->_setReplies($ids);
2887 static public function beforeSchemaUpdate()
2889 $table = strtolower(get_called_class());
2890 $schema = Schema::get();
2891 $schemadef = $schema->getTableDef($table);
2893 // 2015-09-04 We move Notice location data to Notice_location
2894 // First we see if we have to do this at all
2895 if (!isset($schemadef['fields']['lat'])
2896 && !isset($schemadef['fields']['lon'])
2897 && !isset($schemadef['fields']['location_id'])
2898 && !isset($schemadef['fields']['location_ns'])) {
2899 // We have already removed the location fields, so no need to migrate.
2902 // Then we make sure the Notice_location table is created!
2903 $schema->ensureTable('notice_location', Notice_location::schemaDef());
2905 // Then we continue on our road to migration!
2906 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)";
2908 $notice = new Notice();
2909 $notice->query(sprintf('SELECT id, lat, lon, location_id, location_ns FROM %1$s ' .
2910 'WHERE lat IS NOT NULL ' .
2911 'OR lon IS NOT NULL ' .
2912 'OR location_id IS NOT NULL ' .
2913 'OR location_ns IS NOT NULL',
2914 $schema->quoteIdentifier($table)));
2915 print "\nFound {$notice->N} notices with location data, inserting";
2916 while ($notice->fetch()) {
2917 $notloc = Notice_location::getKV('notice_id', $notice->id);
2918 if ($notloc instanceof Notice_location) {
2922 $notloc = new Notice_location();
2923 $notloc->notice_id = $notice->id;
2924 $notloc->lat= $notice->lat;
2925 $notloc->lon= $notice->lon;
2926 $notloc->location_id= $notice->location_id;
2927 $notloc->location_ns= $notice->location_ns;