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 (ActivityUtils::compareVerbs($stored->verb, array(ActivityVerb::POST))) {
889 $stored->object_type = $act->type ?: $act->objects[0]->type;
890 if (empty($stored->object_type)) {
891 // Default type for the post verb is 'note', but we know it's
892 // a 'comment' if it is in reply to something.
893 $stored->object_type = empty($stored->reply_to) ? ActivityObject::NOTE : ActivityObject::COMMENT;
897 if (Event::handle('StartNoticeSave', array(&$stored))) {
898 // XXX: some of these functions write to the DB
901 $stored->insert(); // throws exception on error
903 if ($notloc instanceof Notice_location) {
904 $notloc->notice_id = $stored->getID();
908 $orig = clone($stored); // for updating later in this try clause
911 Event::handle('StoreActivityObject', array($act, $stored, $options, &$object));
912 if (empty($object)) {
913 throw new ServerException('Unsuccessful call to StoreActivityObject '.$stored->uri . ': '.$act->asString());
916 // If it's not part of a conversation, it's the beginning
917 // of a new one (or belongs to a previously unknown URI).
918 if (empty($stored->conversation)) {
919 // $act->context->conversation will be null if it was not provided
920 common_debug('Creating a new conversation for stored notice ID='.$stored->getID().' with URI: '.$act->context->conversation);
921 $conv = Conversation::create($stored, $act->context->conversation);
922 $stored->conversation = $conv->getID();
925 $stored->update($orig);
926 } catch (Exception $e) {
927 if (empty($stored->id)) {
928 common_debug('Failed to save stored object entry in database ('.$e->getMessage().')');
930 common_debug('Failed to store activity object in database ('.$e->getMessage().'), deleting notice id '.$stored->id);
936 if (!$stored instanceof Notice) {
937 throw new ServerException('StartNoticeSave did not give back a Notice');
940 // Save per-notice metadata...
944 // This event lets plugins filter out non-local recipients (attentions we don't care about)
945 // Used primarily for OStatus (and if we don't federate, all attentions would be local anyway)
946 Event::handle('GetLocalAttentions', array($actor, $act->context->attention, &$mentions, &$groups));
948 if (!empty($mentions)) {
949 $stored->saveKnownReplies($mentions);
951 $stored->saveReplies();
955 $stored->saveKnownTags($tags);
960 // Note: groups may save tags, so must be run after tags are saved
961 // to avoid errors on duplicates.
962 // Note: groups should always be set.
964 $stored->saveKnownGroups($groups);
967 $stored->saveKnownUrls($urls);
973 // Prepare inbox delivery, may be queued to background.
974 $stored->distribute();
980 static public function figureOutScope(Profile $actor, array $groups, $scope=null) {
981 if (is_null($scope)) {
982 $scope = self::defaultScope();
985 // For private streams
987 $user = $actor->getUser();
988 // FIXME: We can't do bit comparison with == (Legacy StatusNet thing. Let's keep it for now.)
989 if ($user->private_stream && ($scope == Notice::PUBLIC_SCOPE || $scope == Notice::SITE_SCOPE)) {
990 $scope |= Notice::FOLLOWER_SCOPE;
992 } catch (NoSuchUserException $e) {
993 // TODO: Not a local user, so we don't know about scope preferences... yet!
996 // Force the scope for private groups
997 foreach ($groups as $group_id) {
999 $group = User_group::getByID($group_id);
1000 if ($group->force_scope) {
1001 $scope |= Notice::GROUP_SCOPE;
1004 } catch (Exception $e) {
1005 common_log(LOG_ERR, 'Notice figureOutScope threw exception: '.$e->getMessage());
1012 function blowOnInsert($conversation = false)
1014 $this->blowStream('profile:notice_ids:%d', $this->profile_id);
1016 if ($this->isPublic()) {
1017 $this->blowStream('public');
1018 $this->blowStream('networkpublic');
1021 self::blow('notice:list-ids:conversation:%s', $this->conversation);
1022 self::blow('conversation:notice_count:%d', $this->conversation);
1024 if ($this->isRepeat()) {
1025 // XXX: we should probably only use one of these
1026 $this->blowStream('notice:repeats:%d', $this->repeat_of);
1027 self::blow('notice:list-ids:repeat_of:%d', $this->repeat_of);
1030 $original = Notice::getKV('id', $this->repeat_of);
1032 if ($original instanceof Notice) {
1033 $originalUser = User::getKV('id', $original->profile_id);
1034 if ($originalUser instanceof User) {
1035 $this->blowStream('user:repeats_of_me:%d', $originalUser->id);
1039 $profile = Profile::getKV($this->profile_id);
1041 if ($profile instanceof Profile) {
1042 $profile->blowNoticeCount();
1045 $ptags = $this->getProfileTags();
1046 foreach ($ptags as $ptag) {
1047 $ptag->blowNoticeStreamCache();
1052 * Clear cache entries related to this notice at delete time.
1053 * Necessary to avoid breaking paging on public, profile timelines.
1055 function blowOnDelete()
1057 $this->blowOnInsert();
1059 self::blow('profile:notice_ids:%d;last', $this->profile_id);
1061 if ($this->isPublic()) {
1062 self::blow('public;last');
1063 self::blow('networkpublic;last');
1066 self::blow('fave:by_notice', $this->id);
1068 if ($this->conversation) {
1069 // In case we're the first, will need to calc a new root.
1070 self::blow('notice:conversation_root:%d', $this->conversation);
1073 $ptags = $this->getProfileTags();
1074 foreach ($ptags as $ptag) {
1075 $ptag->blowNoticeStreamCache(true);
1079 function blowStream()
1081 $c = self::memcache();
1087 $args = func_get_args();
1088 $format = array_shift($args);
1089 $keyPart = vsprintf($format, $args);
1090 $cacheKey = Cache::key($keyPart);
1091 $c->delete($cacheKey);
1093 // delete the "last" stream, too, if this notice is
1094 // older than the top of that stream
1096 $lastKey = $cacheKey.';last';
1098 $lastStr = $c->get($lastKey);
1100 if ($lastStr !== false) {
1101 $window = explode(',', $lastStr);
1102 $lastID = $window[0];
1103 $lastNotice = Notice::getKV('id', $lastID);
1104 if (!$lastNotice instanceof Notice // just weird
1105 || strtotime($lastNotice->created) >= strtotime($this->created)) {
1106 $c->delete($lastKey);
1111 /** save all urls in the notice to the db
1113 * follow redirects and save all available file information
1114 * (mimetype, date, size, oembed, etc.)
1118 function saveUrls() {
1119 if (common_config('attachments', 'process_links')) {
1120 common_replace_urls_callback($this->content, array($this, 'saveUrl'), $this);
1125 * Save the given URLs as related links/attachments to the db
1127 * follow redirects and save all available file information
1128 * (mimetype, date, size, oembed, etc.)
1132 function saveKnownUrls($urls)
1134 if (common_config('attachments', 'process_links')) {
1135 // @fixme validation?
1136 foreach (array_unique($urls) as $url) {
1137 $this->saveUrl($url, $this);
1145 function saveUrl($url, Notice $notice) {
1147 File::processNew($url, $notice);
1148 } catch (ServerException $e) {
1149 // Could not save URL. Log it?
1153 static function checkDupes($profile_id, $content) {
1154 $profile = Profile::getKV($profile_id);
1155 if (!$profile instanceof Profile) {
1158 $notice = $profile->getNotices(0, CachingNoticeStream::CACHE_WINDOW);
1159 if (!empty($notice)) {
1161 while ($notice->fetch()) {
1162 if (time() - strtotime($notice->created) >= common_config('site', 'dupelimit')) {
1164 } else if ($notice->content == $content) {
1169 // If we get here, oldest item in cache window is not
1170 // old enough for dupe limit; do direct check against DB
1171 $notice = new Notice();
1172 $notice->profile_id = $profile_id;
1173 $notice->content = $content;
1174 $threshold = common_sql_date(time() - common_config('site', 'dupelimit'));
1175 $notice->whereAdd(sprintf("created > '%s'", $notice->escape($threshold)));
1177 $cnt = $notice->count();
1181 static function checkEditThrottle($profile_id) {
1182 $profile = Profile::getKV($profile_id);
1183 if (!$profile instanceof Profile) {
1186 // Get the Nth notice
1187 $notice = $profile->getNotices(common_config('throttle', 'count') - 1, 1);
1188 if ($notice && $notice->fetch()) {
1189 // If the Nth notice was posted less than timespan seconds ago
1190 if (time() - strtotime($notice->created) <= common_config('throttle', 'timespan')) {
1195 // Either not N notices in the stream, OR the Nth was not posted within timespan seconds
1199 protected $_attachments = array();
1201 function attachments() {
1202 if (isset($this->_attachments[$this->id])) {
1203 return $this->_attachments[$this->id];
1206 $f2ps = File_to_post::listGet('post_id', array($this->id));
1208 foreach ($f2ps[$this->id] as $f2p) {
1209 $ids[] = $f2p->file_id;
1212 $files = File::multiGet('id', $ids);
1213 $this->_attachments[$this->id] = $files->fetchAll();
1214 return $this->_attachments[$this->id];
1217 function _setAttachments($attachments)
1219 $this->_attachments[$this->id] = $attachments;
1222 static function publicStream($offset=0, $limit=20, $since_id=null, $max_id=null)
1224 $stream = new PublicNoticeStream();
1225 return $stream->getNotices($offset, $limit, $since_id, $max_id);
1228 static function conversationStream($id, $offset=0, $limit=20, $since_id=null, $max_id=null)
1230 $stream = new ConversationNoticeStream($id);
1231 return $stream->getNotices($offset, $limit, $since_id, $max_id);
1235 * Is this notice part of an active conversation?
1237 * @return boolean true if other messages exist in the same
1238 * conversation, false if this is the only one
1240 function hasConversation()
1242 if (empty($this->conversation)) {
1243 // this notice is not part of a conversation apparently
1244 // FIXME: all notices should have a conversation value, right?
1248 $stream = new ConversationNoticeStream($this->conversation);
1249 $notice = $stream->getNotices(/*offset*/ 1, /*limit*/ 1);
1251 // if our "offset 1, limit 1" query got a result, return true else false
1252 return $notice->N > 0;
1256 * Grab the earliest notice from this conversation.
1258 * @return Notice or null
1260 function conversationRoot($profile=-1)
1262 // XXX: can this happen?
1264 if (empty($this->conversation)) {
1268 // Get the current profile if not specified
1270 if (is_int($profile) && $profile == -1) {
1271 $profile = Profile::current();
1274 // If this notice is out of scope, no root for you!
1276 if (!$this->inScope($profile)) {
1280 // If this isn't a reply to anything, then it's its own
1281 // root if it's the earliest notice in the conversation:
1283 if (empty($this->reply_to)) {
1285 $root->conversation = $this->conversation;
1286 $root->orderBy('notice.created ASC');
1287 $root->find(true); // true means "fetch first result"
1292 if (is_null($profile)) {
1293 $keypart = sprintf('notice:conversation_root:%d:null', $this->id);
1295 $keypart = sprintf('notice:conversation_root:%d:%d',
1300 $root = self::cacheGet($keypart);
1302 if ($root !== false && $root->inScope($profile)) {
1309 $parent = $last->getParent();
1310 if ($parent->inScope($profile)) {
1314 } catch (NoParentNoticeException $e) {
1315 // Latest notice has no parent
1316 } catch (NoResultException $e) {
1317 // Notice was not found, so we can't go further up in the tree.
1318 // FIXME: Maybe we should do this in a more stable way where deleted
1319 // notices won't break conversation chains?
1321 // No parent, or parent out of scope
1326 self::cacheSet($keypart, $root);
1332 * Pull up a full list of local recipients who will be getting
1333 * this notice in their inbox. Results will be cached, so don't
1334 * change the input data wily-nilly!
1336 * @param array $groups optional list of Group objects;
1337 * if left empty, will be loaded from group_inbox records
1338 * @param array $recipient optional list of reply profile ids
1339 * if left empty, will be loaded from reply records
1340 * @return array associating recipient user IDs with an inbox source constant
1342 function whoGets(array $groups=null, array $recipients=null)
1344 $c = self::memcache();
1347 $ni = $c->get(Cache::key('notice:who_gets:'.$this->id));
1348 if ($ni !== false) {
1353 if (is_null($recipients)) {
1354 $recipients = $this->getReplies();
1359 // Give plugins a chance to add folks in at start...
1360 if (Event::handle('StartNoticeWhoGets', array($this, &$ni))) {
1362 $users = $this->getSubscribedUsers();
1363 foreach ($users as $id) {
1364 $ni[$id] = NOTICE_INBOX_SOURCE_SUB;
1367 if (is_null($groups)) {
1368 $groups = $this->getGroups();
1370 foreach ($groups as $group) {
1371 $users = $group->getUserMembers();
1372 foreach ($users as $id) {
1373 if (!array_key_exists($id, $ni)) {
1374 $ni[$id] = NOTICE_INBOX_SOURCE_GROUP;
1379 $ptAtts = $this->getAttentionsFromProfileTags();
1380 foreach ($ptAtts as $key=>$val) {
1381 if (!array_key_exists($key, $ni)) {
1386 foreach ($recipients as $recipient) {
1387 if (!array_key_exists($recipient, $ni)) {
1388 $ni[$recipient] = NOTICE_INBOX_SOURCE_REPLY;
1392 // Exclude any deleted, non-local, or blocking recipients.
1393 $profile = $this->getProfile();
1394 $originalProfile = null;
1395 if ($this->isRepeat()) {
1396 // Check blocks against the original notice's poster as well.
1397 $original = Notice::getKV('id', $this->repeat_of);
1398 if ($original instanceof Notice) {
1399 $originalProfile = $original->getProfile();
1403 foreach ($ni as $id => $source) {
1405 $user = User::getKV('id', $id);
1406 if (!$user instanceof User ||
1407 $user->hasBlocked($profile) ||
1408 ($originalProfile && $user->hasBlocked($originalProfile))) {
1411 } catch (UserNoProfileException $e) {
1412 // User doesn't have a profile; invalid; skip them.
1417 // Give plugins a chance to filter out...
1418 Event::handle('EndNoticeWhoGets', array($this, &$ni));
1422 // XXX: pack this data better
1423 $c->set(Cache::key('notice:who_gets:'.$this->id), $ni);
1429 function getSubscribedUsers()
1433 if(common_config('db','quote_identifiers'))
1434 $user_table = '"user"';
1435 else $user_table = 'user';
1439 'FROM '. $user_table .' JOIN subscription '.
1440 'ON '. $user_table .'.id = subscription.subscriber ' .
1441 'WHERE subscription.subscribed = %d ';
1443 $user->query(sprintf($qry, $this->profile_id));
1447 while ($user->fetch()) {
1456 function getProfileTags()
1458 $profile = $this->getProfile();
1459 $list = $profile->getOtherTags($profile);
1462 while($list->fetch()) {
1463 $ptags[] = clone($list);
1469 public function getAttentionsFromProfileTags()
1472 $ptags = $this->getProfileTags();
1473 foreach ($ptags as $ptag) {
1474 $users = $ptag->getUserSubscribers();
1475 foreach ($users as $id) {
1476 $ni[$id] = NOTICE_INBOX_SOURCE_PROFILE_TAG;
1483 * Record this notice to the given group inboxes for delivery.
1484 * Overrides the regular parsing of !group markup.
1486 * @param string $group_ids
1487 * @fixme might prefer URIs as identifiers, as for replies?
1488 * best with generalizations on user_group to support
1489 * remote groups better.
1491 function saveKnownGroups($group_ids)
1493 if (!is_array($group_ids)) {
1494 // TRANS: Server exception thrown when no array is provided to the method saveKnownGroups().
1495 throw new ServerException(_('Bad type provided to saveKnownGroups.'));
1499 foreach (array_unique($group_ids) as $id) {
1500 $group = User_group::getKV('id', $id);
1501 if ($group instanceof User_group) {
1502 common_log(LOG_DEBUG, "Local delivery to group id $id, $group->nickname");
1503 $result = $this->addToGroupInbox($group);
1505 common_log_db_error($gi, 'INSERT', __FILE__);
1508 if (common_config('group', 'addtag')) {
1509 // we automatically add a tag for every group name, too
1511 $tag = Notice_tag::pkeyGet(array('tag' => common_canonical_tag($group->nickname),
1512 'notice_id' => $this->id));
1514 if (is_null($tag)) {
1515 $this->saveTag($group->nickname);
1519 $groups[] = clone($group);
1521 common_log(LOG_ERR, "Local delivery to group id $id skipped, doesn't exist");
1528 function addToGroupInbox(User_group $group)
1530 $gi = Group_inbox::pkeyGet(array('group_id' => $group->id,
1531 'notice_id' => $this->id));
1533 if (!$gi instanceof Group_inbox) {
1535 $gi = new Group_inbox();
1537 $gi->group_id = $group->id;
1538 $gi->notice_id = $this->id;
1539 $gi->created = $this->created;
1541 $result = $gi->insert();
1544 common_log_db_error($gi, 'INSERT', __FILE__);
1545 // TRANS: Server exception thrown when an update for a group inbox fails.
1546 throw new ServerException(_('Problem saving group inbox.'));
1549 self::blow('user_group:notice_ids:%d', $gi->group_id);
1556 * Save reply records indicating that this notice needs to be
1557 * delivered to the local users with the given URIs.
1559 * Since this is expected to be used when saving foreign-sourced
1560 * messages, we won't deliver to any remote targets as that's the
1561 * source service's responsibility.
1563 * Mail notifications etc will be handled later.
1565 * @param array $uris Array of unique identifier URIs for recipients
1567 function saveKnownReplies(array $uris)
1573 $sender = Profile::getKV($this->profile_id);
1575 foreach (array_unique($uris) as $uri) {
1577 $profile = Profile::fromUri($uri);
1578 } catch (UnknownUriException $e) {
1579 common_log(LOG_WARNING, "Unable to determine profile for URI '$uri'");
1583 if ($profile->hasBlocked($sender)) {
1584 common_log(LOG_INFO, "Not saving reply to profile {$profile->id} ($uri) from sender {$sender->id} because of a block.");
1588 $this->saveReply($profile->id);
1589 self::blow('reply:stream:%d', $profile->id);
1596 * Pull @-replies from this message's content in StatusNet markup format
1597 * and save reply records indicating that this message needs to be
1598 * delivered to those users.
1600 * Mail notifications to local profiles will be sent later.
1602 * @return array of integer profile IDs
1605 function saveReplies()
1607 // Don't save reply data for repeats
1609 if ($this->isRepeat()) {
1613 $sender = $this->getProfile();
1617 // If it's a reply, save for the replied-to author
1619 $parent = $this->getParent();
1620 $parentauthor = $parent->getProfile();
1621 $this->saveReply($parentauthor->id);
1622 $replied[$parentauthor->id] = 1;
1623 self::blow('reply:stream:%d', $parentauthor->id);
1624 } catch (NoParentNoticeException $e) {
1625 // Not a reply, since it has no parent!
1626 } catch (NoResultException $e) {
1627 // Parent notice was probably deleted
1630 // @todo ideally this parser information would only
1631 // be calculated once.
1633 $mentions = common_find_mentions($this->content, $this);
1635 // store replied only for first @ (what user/notice what the reply directed,
1636 // we assume first @ is it)
1638 foreach ($mentions as $mention) {
1640 foreach ($mention['mentioned'] as $mentioned) {
1642 // skip if they're already covered
1643 if (array_key_exists($mentioned->id, $replied)) {
1647 // Don't save replies from blocked profile to local user
1649 $mentioned_user = User::getKV('id', $mentioned->id);
1650 if ($mentioned_user instanceof User && $mentioned_user->hasBlocked($sender)) {
1654 $this->saveReply($mentioned->id);
1655 $replied[$mentioned->id] = 1;
1656 self::blow('reply:stream:%d', $mentioned->id);
1660 $recipientIds = array_keys($replied);
1662 return $recipientIds;
1665 function saveReply($profileId)
1667 $reply = new Reply();
1669 $reply->notice_id = $this->id;
1670 $reply->profile_id = $profileId;
1671 $reply->modified = $this->created;
1678 protected $_replies = array();
1681 * Pull the complete list of @-mentioned profile IDs for this notice.
1683 * @return array of integer profile ids
1685 function getReplies()
1687 if (!isset($this->_replies[$this->getID()])) {
1688 $mentions = Reply::multiGet('notice_id', array($this->getID()));
1689 $this->_replies[$this->getID()] = $mentions->fetchAll('profile_id');
1691 return $this->_replies[$this->getID()];
1694 function _setReplies($replies)
1696 $this->_replies[$this->getID()] = $replies;
1700 * Pull the complete list of @-reply targets for this notice.
1702 * @return array of Profiles
1704 function getReplyProfiles()
1706 $ids = $this->getReplies();
1708 $profiles = Profile::multiGet('id', $ids);
1710 return $profiles->fetchAll();
1714 * Send e-mail notifications to local @-reply targets.
1716 * Replies must already have been saved; this is expected to be run
1717 * from the distrib queue handler.
1719 function sendReplyNotifications()
1721 // Don't send reply notifications for repeats
1723 if ($this->isRepeat()) {
1727 $recipientIds = $this->getReplies();
1728 if (Event::handle('StartNotifyMentioned', array($this, &$recipientIds))) {
1729 require_once INSTALLDIR.'/lib/mail.php';
1731 foreach ($recipientIds as $recipientId) {
1732 $user = User::getKV('id', $recipientId);
1733 if ($user instanceof User) {
1734 mail_notify_attn($user, $this);
1737 Event::handle('EndNotifyMentioned', array($this, $recipientIds));
1742 * Pull list of groups this notice needs to be delivered to,
1743 * as previously recorded by saveKnownGroups().
1745 * @return array of Group objects
1748 protected $_groups = array();
1750 function getGroups()
1752 // Don't save groups for repeats
1754 if (!empty($this->repeat_of)) {
1758 if (isset($this->_groups[$this->id])) {
1759 return $this->_groups[$this->id];
1762 $gis = Group_inbox::listGet('notice_id', array($this->id));
1766 foreach ($gis[$this->id] as $gi) {
1767 $ids[] = $gi->group_id;
1770 $groups = User_group::multiGet('id', $ids);
1771 $this->_groups[$this->id] = $groups->fetchAll();
1772 return $this->_groups[$this->id];
1775 function _setGroups($groups)
1777 $this->_groups[$this->id] = $groups;
1781 * Convert a notice into an activity for export.
1783 * @param Profile $scoped The currently logged in/scoped profile
1785 * @return Activity activity object representing this Notice.
1788 function asActivity(Profile $scoped=null)
1790 $act = self::cacheGet(Cache::codeKey('notice:as-activity:'.$this->id));
1792 if ($act instanceof Activity) {
1795 $act = new Activity();
1797 if (Event::handle('StartNoticeAsActivity', array($this, $act, $scoped))) {
1799 $act->id = $this->uri;
1800 $act->time = strtotime($this->created);
1802 $act->link = $this->getUrl();
1803 } catch (InvalidUrlException $e) {
1804 // The notice is probably a share or similar, which don't
1805 // have a representational URL of their own.
1807 $act->content = common_xml_safe_str($this->rendered);
1809 $profile = $this->getProfile();
1811 $act->actor = $profile->asActivityObject();
1812 $act->actor->extra[] = $profile->profileInfo($scoped);
1814 $act->verb = $this->verb;
1816 if (!$this->repeat_of) {
1817 $act->objects[] = $this->asActivityObject();
1820 // XXX: should this be handled by default processing for object entry?
1824 $tags = $this->getTags();
1826 foreach ($tags as $tag) {
1827 $cat = new AtomCategory();
1830 $act->categories[] = $cat;
1834 // XXX: use Atom Media and/or File activity objects instead
1836 $attachments = $this->attachments();
1838 foreach ($attachments as $attachment) {
1839 // Include local attachments in Activity
1840 if (!empty($attachment->filename)) {
1841 $act->enclosures[] = $attachment->getEnclosure();
1845 $ctx = new ActivityContext();
1848 $reply = $this->getParent();
1849 $ctx->replyToID = $reply->getUri();
1850 $ctx->replyToUrl = $reply->getUrl(true); // true for fallback to local URL, less messy
1851 } catch (NoParentNoticeException $e) {
1852 // This is not a reply to something
1853 } catch (NoResultException $e) {
1854 // Parent notice was probably deleted
1858 $ctx->location = Notice_location::locFromStored($this);
1859 } catch (ServerException $e) {
1860 $ctx->location = null;
1865 if (!empty($this->conversation)) {
1866 $conv = Conversation::getKV('id', $this->conversation);
1867 if ($conv instanceof Conversation) {
1868 $ctx->conversation = $conv->uri;
1872 $reply_ids = $this->getReplies();
1874 foreach ($reply_ids as $id) {
1875 $rprofile = Profile::getKV('id', $id);
1876 if ($rprofile instanceof Profile) {
1877 $ctx->attention[$rprofile->getUri()] = ActivityObject::PERSON;
1881 $groups = $this->getGroups();
1883 foreach ($groups as $group) {
1884 $ctx->attention[$group->getUri()] = ActivityObject::GROUP;
1887 switch ($this->scope) {
1888 case Notice::PUBLIC_SCOPE:
1889 $ctx->attention[ActivityContext::ATTN_PUBLIC] = ActivityObject::COLLECTION;
1891 case Notice::FOLLOWER_SCOPE:
1892 $surl = common_local_url("subscribers", array('nickname' => $profile->nickname));
1893 $ctx->attention[$surl] = ActivityObject::COLLECTION;
1897 $act->context = $ctx;
1899 $source = $this->getSource();
1901 if ($source instanceof Notice_source) {
1902 $act->generator = ActivityObject::fromNoticeSource($source);
1907 $atom_feed = $profile->getAtomFeed();
1909 if (!empty($atom_feed)) {
1911 $act->source = new ActivitySource();
1913 // XXX: we should store the actual feed ID
1915 $act->source->id = $atom_feed;
1917 // XXX: we should store the actual feed title
1919 $act->source->title = $profile->getBestName();
1921 $act->source->links['alternate'] = $profile->profileurl;
1922 $act->source->links['self'] = $atom_feed;
1924 $act->source->icon = $profile->avatarUrl(AVATAR_PROFILE_SIZE);
1926 $notice = $profile->getCurrentNotice();
1928 if ($notice instanceof Notice) {
1929 $act->source->updated = self::utcDate($notice->created);
1932 $user = User::getKV('id', $profile->id);
1934 if ($user instanceof User) {
1935 $act->source->links['license'] = common_config('license', 'url');
1939 if ($this->isLocal()) {
1940 $act->selfLink = common_local_url('ApiStatusesShow', array('id' => $this->id,
1941 'format' => 'atom'));
1942 $act->editLink = $act->selfLink;
1945 Event::handle('EndNoticeAsActivity', array($this, $act, $scoped));
1948 self::cacheSet(Cache::codeKey('notice:as-activity:'.$this->id), $act);
1953 // This has gotten way too long. Needs to be sliced up into functional bits
1954 // or ideally exported to a utility class.
1956 function asAtomEntry($namespace=false,
1959 Profile $scoped=null)
1961 $act = $this->asActivity($scoped);
1962 $act->extra[] = $this->noticeInfo($scoped);
1963 return $act->asString($namespace, $author, $source);
1967 * Extra notice info for atom entries
1969 * Clients use some extra notice info in the atom stream.
1970 * This gives it to them.
1972 * @param Profile $scoped The currently logged in/scoped profile
1974 * @return array representation of <statusnet:notice_info> element
1977 function noticeInfo(Profile $scoped=null)
1979 // local notice ID (useful to clients for ordering)
1981 $noticeInfoAttr = array('local_id' => $this->id);
1985 $ns = $this->getSource();
1987 if ($ns instanceof Notice_source) {
1988 $noticeInfoAttr['source'] = $ns->code;
1989 if (!empty($ns->url)) {
1990 $noticeInfoAttr['source_link'] = $ns->url;
1991 if (!empty($ns->name)) {
1992 $noticeInfoAttr['source'] = '<a href="'
1993 . htmlspecialchars($ns->url)
1994 . '" rel="nofollow">'
1995 . htmlspecialchars($ns->name)
2001 // favorite and repeated
2003 if ($scoped instanceof Profile) {
2004 $noticeInfoAttr['repeated'] = ($scoped->hasRepeated($this)) ? "true" : "false";
2007 if (!empty($this->repeat_of)) {
2008 $noticeInfoAttr['repeat_of'] = $this->repeat_of;
2011 Event::handle('StatusNetApiNoticeInfo', array($this, &$noticeInfoAttr, $scoped));
2013 return array('statusnet:notice_info', $noticeInfoAttr, null);
2017 * Returns an XML string fragment with a reference to a notice as an
2018 * Activity Streams noun object with the given element type.
2020 * Assumes that 'activity' namespace has been previously defined.
2022 * @param string $element one of 'subject', 'object', 'target'
2026 function asActivityNoun($element)
2028 $noun = $this->asActivityObject();
2029 return $noun->asString('activity:' . $element);
2032 public function asActivityObject()
2034 $object = new ActivityObject();
2036 if (Event::handle('StartActivityObjectFromNotice', array($this, &$object))) {
2037 $object->type = $this->object_type ?: ActivityObject::NOTE;
2038 $object->id = $this->getUri();
2039 $object->title = sprintf('New %1$s by %2$s', ActivityObject::canonicalType($object->type), $this->getProfile()->getNickname());
2040 $object->content = $this->rendered;
2041 $object->link = $this->getUrl();
2043 $object->extra[] = array('status_net', array('notice_id' => $this->id));
2045 Event::handle('EndActivityObjectFromNotice', array($this, &$object));
2052 * Determine which notice, if any, a new notice is in reply to.
2054 * For conversation tracking, we try to see where this notice fits
2055 * in the tree. Beware that this may very well give false positives
2056 * and add replies to wrong threads (if there have been newer posts
2057 * by the same user as we're replying to).
2059 * @param Profile $sender Author profile
2060 * @param string $content Final notice content
2062 * @return integer ID of replied-to notice, or null for not a reply.
2065 static function getInlineReplyTo(Profile $sender, $content)
2067 // Is there an initial @ or T?
2068 if (preg_match('/^T ([A-Z0-9]{1,64}) /', $content, $match)
2069 || preg_match('/^@([a-z0-9]{1,64})\s+/', $content, $match)) {
2070 $nickname = common_canonical_nickname($match[1]);
2075 // Figure out who that is.
2076 $recipient = common_relative_profile($sender, $nickname, common_sql_now());
2078 if ($recipient instanceof Profile) {
2079 // Get their last notice
2080 $last = $recipient->getCurrentNotice();
2081 if ($last instanceof Notice) {
2084 // Maybe in the future we want to handle something else below
2085 // so don't return getCurrentNotice() immediately.
2091 static function maxContent()
2093 $contentlimit = common_config('notice', 'contentlimit');
2094 // null => use global limit (distinct from 0!)
2095 if (is_null($contentlimit)) {
2096 $contentlimit = common_config('site', 'textlimit');
2098 return $contentlimit;
2101 static function contentTooLong($content)
2103 $contentlimit = self::maxContent();
2104 return ($contentlimit > 0 && !empty($content) && (mb_strlen($content) > $contentlimit));
2108 * Convenience function for posting a repeat of an existing message.
2110 * @param Profile $repeater Profile which is doing the repeat
2111 * @param string $source: posting source key, eg 'web', 'api', etc
2114 * @throws Exception on failure or permission problems
2116 function repeat(Profile $repeater, $source)
2118 $author = $this->getProfile();
2120 // TRANS: Message used to repeat a notice. RT is the abbreviation of 'retweet'.
2121 // TRANS: %1$s is the repeated user's name, %2$s is the repeated notice.
2122 $content = sprintf(_('RT @%1$s %2$s'),
2123 $author->getNickname(),
2126 $maxlen = self::maxContent();
2127 if ($maxlen > 0 && mb_strlen($content) > $maxlen) {
2128 // Web interface and current Twitter API clients will
2129 // pull the original notice's text, but some older
2130 // clients and RSS/Atom feeds will see this trimmed text.
2132 // Unfortunately this is likely to lose tags or URLs
2133 // at the end of long notices.
2134 $content = mb_substr($content, 0, $maxlen - 4) . ' ...';
2138 // Scope is same as this one's
2139 return self::saveNew($repeater->id,
2142 array('repeat_of' => $this->id,
2143 'scope' => $this->scope));
2146 // These are supposed to be in chron order!
2148 function repeatStream($limit=100)
2150 $cache = Cache::instance();
2152 if (empty($cache)) {
2153 $ids = $this->_repeatStreamDirect($limit);
2155 $idstr = $cache->get(Cache::key('notice:repeats:'.$this->id));
2156 if ($idstr !== false) {
2157 if (empty($idstr)) {
2160 $ids = explode(',', $idstr);
2163 $ids = $this->_repeatStreamDirect(100);
2164 $cache->set(Cache::key('notice:repeats:'.$this->id), implode(',', $ids));
2167 // We do a max of 100, so slice down to limit
2168 $ids = array_slice($ids, 0, $limit);
2172 return NoticeStream::getStreamByIds($ids);
2175 function _repeatStreamDirect($limit)
2177 $notice = new Notice();
2179 $notice->selectAdd(); // clears it
2180 $notice->selectAdd('id');
2182 $notice->repeat_of = $this->id;
2184 $notice->orderBy('created, id'); // NB: asc!
2186 if (!is_null($limit)) {
2187 $notice->limit(0, $limit);
2190 return $notice->fetchAll('id');
2193 static function locationOptions($lat, $lon, $location_id, $location_ns, $profile = null)
2197 if (!empty($location_id) && !empty($location_ns)) {
2198 $options['location_id'] = $location_id;
2199 $options['location_ns'] = $location_ns;
2201 $location = Location::fromId($location_id, $location_ns);
2203 if ($location instanceof Location) {
2204 $options['lat'] = $location->lat;
2205 $options['lon'] = $location->lon;
2208 } else if (!empty($lat) && !empty($lon)) {
2209 $options['lat'] = $lat;
2210 $options['lon'] = $lon;
2212 $location = Location::fromLatLon($lat, $lon);
2214 if ($location instanceof Location) {
2215 $options['location_id'] = $location->location_id;
2216 $options['location_ns'] = $location->location_ns;
2218 } else if (!empty($profile)) {
2219 if (isset($profile->lat) && isset($profile->lon)) {
2220 $options['lat'] = $profile->lat;
2221 $options['lon'] = $profile->lon;
2224 if (isset($profile->location_id) && isset($profile->location_ns)) {
2225 $options['location_id'] = $profile->location_id;
2226 $options['location_ns'] = $profile->location_ns;
2233 function clearAttentions()
2235 $att = new Attention();
2236 $att->notice_id = $this->getID();
2239 while ($att->fetch()) {
2240 // Can't do delete() on the object directly since it won't remove all of it
2241 $other = clone($att);
2247 function clearReplies()
2249 $replyNotice = new Notice();
2250 $replyNotice->reply_to = $this->id;
2252 //Null any notices that are replies to this notice
2254 if ($replyNotice->find()) {
2255 while ($replyNotice->fetch()) {
2256 $orig = clone($replyNotice);
2257 $replyNotice->reply_to = null;
2258 $replyNotice->update($orig);
2264 $reply = new Reply();
2265 $reply->notice_id = $this->id;
2267 if ($reply->find()) {
2268 while($reply->fetch()) {
2269 self::blow('reply:stream:%d', $reply->profile_id);
2277 function clearLocation()
2279 $loc = new Notice_location();
2280 $loc->notice_id = $this->id;
2287 function clearFiles()
2289 $f2p = new File_to_post();
2291 $f2p->post_id = $this->id;
2294 while ($f2p->fetch()) {
2298 // FIXME: decide whether to delete File objects
2299 // ...and related (actual) files
2302 function clearRepeats()
2304 $repeatNotice = new Notice();
2305 $repeatNotice->repeat_of = $this->id;
2307 //Null any notices that are repeats of this notice
2309 if ($repeatNotice->find()) {
2310 while ($repeatNotice->fetch()) {
2311 $orig = clone($repeatNotice);
2312 $repeatNotice->repeat_of = null;
2313 $repeatNotice->update($orig);
2318 function clearTags()
2320 $tag = new Notice_tag();
2321 $tag->notice_id = $this->id;
2324 while ($tag->fetch()) {
2325 self::blow('profile:notice_ids_tagged:%d:%s', $this->profile_id, Cache::keyize($tag->tag));
2326 self::blow('profile:notice_ids_tagged:%d:%s;last', $this->profile_id, Cache::keyize($tag->tag));
2327 self::blow('notice_tag:notice_ids:%s', Cache::keyize($tag->tag));
2328 self::blow('notice_tag:notice_ids:%s;last', Cache::keyize($tag->tag));
2336 function clearGroupInboxes()
2338 $gi = new Group_inbox();
2340 $gi->notice_id = $this->id;
2343 while ($gi->fetch()) {
2344 self::blow('user_group:notice_ids:%d', $gi->group_id);
2352 function distribute()
2354 // We always insert for the author so they don't
2356 Event::handle('StartNoticeDistribute', array($this));
2358 // If there's a failure, we want to _force_
2359 // distribution at this point.
2361 $qm = QueueManager::get();
2362 $qm->enqueue($this, 'distrib');
2363 } catch (Exception $e) {
2364 // If the exception isn't transient, this
2365 // may throw more exceptions as DQH does
2366 // its own enqueueing. So, we ignore them!
2368 $handler = new DistribQueueHandler();
2369 $handler->handle($this);
2370 } catch (Exception $e) {
2371 common_log(LOG_ERR, "emergency redistribution resulted in " . $e->getMessage());
2373 // Re-throw so somebody smarter can handle it.
2380 $result = parent::insert();
2382 if ($result === false) {
2383 common_log_db_error($this, 'INSERT', __FILE__);
2384 // TRANS: Server exception thrown when a stored object entry cannot be saved.
2385 throw new ServerException('Could not save Notice');
2388 // Profile::hasRepeated() abuses pkeyGet(), so we
2389 // have to clear manually
2390 if (!empty($this->repeat_of)) {
2391 $c = self::memcache();
2393 $ck = self::multicacheKey('Notice',
2394 array('profile_id' => $this->profile_id,
2395 'repeat_of' => $this->repeat_of));
2400 // Update possibly ID-dependent columns: URI, conversation
2401 // (now that INSERT has added the notice's local id)
2402 $orig = clone($this);
2405 // We can only get here if it's a local notice, since remote notices
2406 // should've bailed out earlier due to lacking a URI.
2407 if (empty($this->uri)) {
2408 $this->uri = sprintf('%s%s=%d:%s=%s',
2410 'noticeId', $this->id,
2411 'objectType', $this->getObjectType(true));
2415 if ($changed && $this->update($orig) === false) {
2416 common_log_db_error($notice, 'UPDATE', __FILE__);
2417 // TRANS: Server exception thrown when a notice cannot be updated.
2418 throw new ServerException(_('Problem saving notice.'));
2421 $this->blowOnInsert();
2427 * Get the source of the notice
2429 * @return Notice_source $ns A notice source object. 'code' is the only attribute
2430 * guaranteed to be populated.
2432 function getSource()
2434 if (empty($this->source)) {
2438 $ns = new Notice_source();
2439 switch ($this->source) {
2446 $ns->code = $this->source;
2449 $ns = Notice_source::getKV($this->source);
2451 $ns = new Notice_source();
2452 $ns->code = $this->source;
2453 $app = Oauth_application::getKV('name', $this->source);
2455 $ns->name = $app->name;
2456 $ns->url = $app->source_url;
2466 * Determine whether the notice was locally created
2468 * @return boolean locality
2471 public function isLocal()
2473 return ($this->is_local == Notice::LOCAL_PUBLIC ||
2474 $this->is_local == Notice::LOCAL_NONPUBLIC);
2477 public function isRepeat()
2479 return !empty($this->repeat_of);
2483 * Get the list of hash tags saved with this notice.
2485 * @return array of strings
2487 public function getTags()
2491 $keypart = sprintf('notice:tags:%d', $this->id);
2493 $tagstr = self::cacheGet($keypart);
2495 if ($tagstr !== false) {
2496 $tags = explode(',', $tagstr);
2498 $tag = new Notice_tag();
2499 $tag->notice_id = $this->id;
2501 while ($tag->fetch()) {
2502 $tags[] = $tag->tag;
2505 self::cacheSet($keypart, implode(',', $tags));
2511 static private function utcDate($dt)
2513 $dateStr = date('d F Y H:i:s', strtotime($dt));
2514 $d = new DateTime($dateStr, new DateTimeZone('UTC'));
2515 return $d->format(DATE_W3C);
2519 * Look up the creation timestamp for a given notice ID, even
2520 * if it's been deleted.
2523 * @return mixed string recorded creation timestamp, or false if can't be found
2525 public static function getAsTimestamp($id)
2531 $notice = Notice::getKV('id', $id);
2533 return $notice->created;
2536 $deleted = Deleted_notice::getKV('id', $id);
2538 return $deleted->created;
2545 * Build an SQL 'where' fragment for timestamp-based sorting from a since_id
2546 * parameter, matching notices posted after the given one (exclusive).
2548 * If the referenced notice can't be found, will return false.
2551 * @param string $idField
2552 * @param string $createdField
2553 * @return mixed string or false if no match
2555 public static function whereSinceId($id, $idField='id', $createdField='created')
2557 $since = Notice::getAsTimestamp($id);
2559 return sprintf("($createdField = '%s' and $idField > %d) or ($createdField > '%s')", $since, $id, $since);
2565 * Build an SQL 'where' fragment for timestamp-based sorting from a since_id
2566 * parameter, matching notices posted after the given one (exclusive), and
2567 * if necessary add it to the data object's query.
2569 * @param DB_DataObject $obj
2571 * @param string $idField
2572 * @param string $createdField
2573 * @return mixed string or false if no match
2575 public static function addWhereSinceId(DB_DataObject $obj, $id, $idField='id', $createdField='created')
2577 $since = self::whereSinceId($id, $idField, $createdField);
2579 $obj->whereAdd($since);
2584 * Build an SQL 'where' fragment for timestamp-based sorting from a max_id
2585 * parameter, matching notices posted before the given one (inclusive).
2587 * If the referenced notice can't be found, will return false.
2590 * @param string $idField
2591 * @param string $createdField
2592 * @return mixed string or false if no match
2594 public static function whereMaxId($id, $idField='id', $createdField='created')
2596 $max = Notice::getAsTimestamp($id);
2598 return sprintf("($createdField < '%s') or ($createdField = '%s' and $idField <= %d)", $max, $max, $id);
2604 * Build an SQL 'where' fragment for timestamp-based sorting from a max_id
2605 * parameter, matching notices posted before the given one (inclusive), and
2606 * if necessary add it to the data object's query.
2608 * @param DB_DataObject $obj
2610 * @param string $idField
2611 * @param string $createdField
2612 * @return mixed string or false if no match
2614 public static function addWhereMaxId(DB_DataObject $obj, $id, $idField='id', $createdField='created')
2616 $max = self::whereMaxId($id, $idField, $createdField);
2618 $obj->whereAdd($max);
2624 return (($this->is_local != Notice::LOCAL_NONPUBLIC) &&
2625 ($this->is_local != Notice::GATEWAY));
2629 * Check that the given profile is allowed to read, respond to, or otherwise
2630 * act on this notice.
2632 * The $scope member is a bitmask of scopes, representing a logical AND of the
2633 * scope requirement. So, 0x03 (Notice::ADDRESSEE_SCOPE | Notice::SITE_SCOPE) means
2634 * "only visible to people who are mentioned in the notice AND are users on this site."
2635 * Users on the site who are not mentioned in the notice will not be able to see the
2638 * @param Profile $profile The profile to check; pass null to check for public/unauthenticated users.
2640 * @return boolean whether the profile is in the notice's scope
2642 function inScope($profile)
2644 if (is_null($profile)) {
2645 $keypart = sprintf('notice:in-scope-for:%d:null', $this->id);
2647 $keypart = sprintf('notice:in-scope-for:%d:%d', $this->id, $profile->id);
2650 $result = self::cacheGet($keypart);
2652 if ($result === false) {
2654 if (Event::handle('StartNoticeInScope', array($this, $profile, &$bResult))) {
2655 $bResult = $this->_inScope($profile);
2656 Event::handle('EndNoticeInScope', array($this, $profile, &$bResult));
2658 $result = ($bResult) ? 1 : 0;
2659 self::cacheSet($keypart, $result, 0, 300);
2662 return ($result == 1) ? true : false;
2665 protected function _inScope($profile)
2667 if (!is_null($this->scope)) {
2668 $scope = $this->scope;
2670 $scope = self::defaultScope();
2673 if ($scope == 0 && !$this->getProfile()->isPrivateStream()) { // Not scoping, so it is public.
2674 return !$this->isHiddenSpam($profile);
2677 // If there's scope, anon cannot be in scope
2678 if (empty($profile)) {
2682 // Author is always in scope
2683 if ($this->profile_id == $profile->id) {
2687 // Only for users on this site
2688 if (($scope & Notice::SITE_SCOPE) && !$profile->isLocal()) {
2692 // Only for users mentioned in the notice
2693 if ($scope & Notice::ADDRESSEE_SCOPE) {
2695 $reply = Reply::pkeyGet(array('notice_id' => $this->id,
2696 'profile_id' => $profile->id));
2698 if (!$reply instanceof Reply) {
2703 // Only for members of the given group
2704 if ($scope & Notice::GROUP_SCOPE) {
2706 // XXX: just query for the single membership
2708 $groups = $this->getGroups();
2712 foreach ($groups as $group) {
2713 if ($profile->isMember($group)) {
2724 if ($scope & Notice::FOLLOWER_SCOPE || $this->getProfile()->isPrivateStream()) {
2726 if (!Subscription::exists($profile, $this->getProfile())) {
2731 return !$this->isHiddenSpam($profile);
2734 function isHiddenSpam($profile) {
2736 // Hide posts by silenced users from everyone but moderators.
2738 if (common_config('notice', 'hidespam')) {
2741 $author = $this->getProfile();
2742 } catch(Exception $e) {
2743 // If we can't get an author, keep it hidden.
2744 // XXX: technically not spam, but, whatever.
2748 if ($author->hasRole(Profile_role::SILENCED)) {
2749 if (!$profile instanceof Profile || (($profile->id !== $author->id) && (!$profile->hasRight(Right::REVIEWSPAM)))) {
2758 public function getParent()
2760 if (empty($this->reply_to)) {
2761 throw new NoParentNoticeException($this);
2763 return self::getByID($this->reply_to);
2767 * Magic function called at serialize() time.
2769 * We use this to drop a couple process-specific references
2770 * from DB_DataObject which can cause trouble in future
2773 * @return array of variable names to include in serialization.
2778 $vars = parent::__sleep();
2779 $skip = array('_profile', '_groups', '_attachments', '_faves', '_replies', '_repeats');
2780 return array_diff($vars, $skip);
2783 static function defaultScope()
2785 $scope = common_config('notice', 'defaultscope');
2786 if (is_null($scope)) {
2787 if (common_config('site', 'private')) {
2796 static function fillProfiles($notices)
2798 $map = self::getProfiles($notices);
2799 foreach ($notices as $entry=>$notice) {
2801 if (array_key_exists($notice->profile_id, $map)) {
2802 $notice->_setProfile($map[$notice->profile_id]);
2804 } catch (NoProfileException $e) {
2805 common_log(LOG_WARNING, "Failed to fill profile in Notice with non-existing entry for profile_id: {$e->profile_id}");
2806 unset($notices[$entry]);
2810 return array_values($map);
2813 static function getProfiles(&$notices)
2816 foreach ($notices as $notice) {
2817 $ids[] = $notice->profile_id;
2819 $ids = array_unique($ids);
2820 return Profile::pivotGet('id', $ids);
2823 static function fillGroups(&$notices)
2825 $ids = self::_idsOf($notices);
2826 $gis = Group_inbox::listGet('notice_id', $ids);
2829 foreach ($gis as $id => $gi) {
2832 $gids[] = $g->group_id;
2836 $gids = array_unique($gids);
2837 $group = User_group::pivotGet('id', $gids);
2838 foreach ($notices as $notice)
2841 $gi = $gis[$notice->id];
2842 foreach ($gi as $g) {
2843 $grps[] = $group[$g->group_id];
2845 $notice->_setGroups($grps);
2849 static function _idsOf(array &$notices)
2852 foreach ($notices as $notice) {
2853 $ids[$notice->id] = true;
2855 return array_keys($ids);
2858 static function fillAttachments(&$notices)
2860 $ids = self::_idsOf($notices);
2861 $f2pMap = File_to_post::listGet('post_id', $ids);
2863 foreach ($f2pMap as $noticeId => $f2ps) {
2864 foreach ($f2ps as $f2p) {
2865 $fileIds[] = $f2p->file_id;
2869 $fileIds = array_unique($fileIds);
2870 $fileMap = File::pivotGet('id', $fileIds);
2871 foreach ($notices as $notice)
2874 $f2ps = $f2pMap[$notice->id];
2875 foreach ($f2ps as $f2p) {
2876 $files[] = $fileMap[$f2p->file_id];
2878 $notice->_setAttachments($files);
2882 static function fillReplies(&$notices)
2884 $ids = self::_idsOf($notices);
2885 $replyMap = Reply::listGet('notice_id', $ids);
2886 foreach ($notices as $notice) {
2887 $replies = $replyMap[$notice->id];
2889 foreach ($replies as $reply) {
2890 $ids[] = $reply->profile_id;
2892 $notice->_setReplies($ids);
2896 static public function beforeSchemaUpdate()
2898 $table = strtolower(get_called_class());
2899 $schema = Schema::get();
2900 $schemadef = $schema->getTableDef($table);
2902 // 2015-09-04 We move Notice location data to Notice_location
2903 // First we see if we have to do this at all
2904 if (!isset($schemadef['fields']['lat'])
2905 && !isset($schemadef['fields']['lon'])
2906 && !isset($schemadef['fields']['location_id'])
2907 && !isset($schemadef['fields']['location_ns'])) {
2908 // We have already removed the location fields, so no need to migrate.
2911 // Then we make sure the Notice_location table is created!
2912 $schema->ensureTable('notice_location', Notice_location::schemaDef());
2914 // Then we continue on our road to migration!
2915 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)";
2917 $notice = new Notice();
2918 $notice->query(sprintf('SELECT id, lat, lon, location_id, location_ns FROM %1$s ' .
2919 'WHERE lat IS NOT NULL ' .
2920 'OR lon IS NOT NULL ' .
2921 'OR location_id IS NOT NULL ' .
2922 'OR location_ns IS NOT NULL',
2923 $schema->quoteIdentifier($table)));
2924 print "\nFound {$notice->N} notices with location data, inserting";
2925 while ($notice->fetch()) {
2926 $notloc = Notice_location::getKV('notice_id', $notice->id);
2927 if ($notloc instanceof Notice_location) {
2931 $notloc = new Notice_location();
2932 $notloc->notice_id = $notice->id;
2933 $notloc->lat= $notice->lat;
2934 $notloc->lon= $notice->lon;
2935 $notloc->location_id= $notice->location_id;
2936 $notloc->location_ns= $notice->location_ns;