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)
163 if ($this->getProfile()->sameAs($actor) || $actor->hasRight(Right::DELETEOTHERSNOTICE)) {
164 return $this->delete();
166 throw new AuthorizationException('You are not allowed to delete other user\'s notices');
169 function delete($useWhere=false)
171 // For auditing purposes, save a record that the notice
174 // @fixme we have some cases where things get re-run and so the
176 $deleted = Deleted_notice::getKV('id', $this->id);
178 if (!$deleted instanceof Deleted_notice) {
179 $deleted = Deleted_notice::getKV('uri', $this->uri);
182 if (!$deleted instanceof Deleted_notice) {
183 $deleted = new Deleted_notice();
185 $deleted->id = $this->id;
186 $deleted->profile_id = $this->profile_id;
187 $deleted->uri = $this->uri;
188 $deleted->created = $this->created;
189 $deleted->deleted = common_sql_now();
194 if (Event::handle('NoticeDeleteRelated', array($this))) {
196 // Clear related records
198 $this->clearReplies();
199 $this->clearLocation();
200 $this->clearRepeats();
202 $this->clearGroupInboxes();
204 $this->clearAttentions();
206 // NOTE: we don't clear queue items
209 $result = parent::delete($useWhere);
211 $this->blowOnDelete();
215 public function getUri()
221 * Get a Notice object by URI. Will call external plugins for help
222 * using the event StartGetNoticeFromURI.
224 * @param string $uri A unique identifier for a resource (notice in this case)
226 static function fromUri($uri)
230 if (Event::handle('StartGetNoticeFromUri', array($uri, &$notice))) {
231 $notice = Notice::getKV('uri', $uri);
232 Event::handle('EndGetNoticeFromUri', array($uri, $notice));
235 if (!$notice instanceof Notice) {
236 throw new UnknownUriException($uri);
243 * @param $root boolean If true, link to just the conversation root.
245 * @return URL to conversation
247 public function getConversationUrl($anchor=true)
249 return Conversation::getUrlFromNotice($this, $anchor);
253 * Get the local representation URL of this notice.
255 public function getLocalUrl()
257 return common_local_url('shownotice', array('notice' => $this->id), null, null, false);
260 public function getTitle()
263 if (Event::handle('GetNoticeTitle', array($this, &$title))) {
264 // TRANS: Title of a notice posted without a title value.
265 // TRANS: %1$s is a user name, %2$s is the notice creation date/time.
266 $title = sprintf(_('%1$s\'s status on %2$s'),
267 $this->getProfile()->getFancyName(),
268 common_exact_date($this->created));
273 public function getContent()
275 return $this->content;
279 * Get the original representation URL of this notice.
281 * @param boolean $fallback Whether to fall back to generate a local URL or throw InvalidUrlException
283 public function getUrl($fallback=false)
285 // The risk is we start having empty urls and non-http uris...
286 // and we can't really handle any other protocol right now.
288 case common_valid_http_url($this->url): // should we allow non-http/https URLs?
290 case !$this->isLocal() && common_valid_http_url($this->uri): // Sometimes we only have the URI for remote posts.
292 case $this->isLocal() || $fallback:
293 // let's generate a valid link to our locally available notice on demand
294 return common_local_url('shownotice', array('notice' => $this->id), null, null, false);
296 common_debug('No URL available for notice: id='.$this->id);
297 throw new InvalidUrlException($this->url);
301 public function get_object_type($canonical=false) {
303 ? ActivityObject::canonicalType($this->object_type)
304 : $this->object_type;
307 public static function getByUri($uri)
309 $notice = new Notice();
311 if (!$notice->find(true)) {
312 throw new NoResultException($notice);
318 * Extract #hashtags from this notice's content and save them to the database.
322 /* extract all #hastags */
323 $count = preg_match_all('/(?:^|\s)#([\pL\pN_\-\.]{1,64})/u', strtolower($this->content), $match);
328 /* Add them to the database */
329 return $this->saveKnownTags($match[1]);
333 * Record the given set of hash tags in the db for this notice.
334 * Given tag strings will be normalized and checked for dupes.
336 function saveKnownTags($hashtags)
338 //turn each into their canonical tag
339 //this is needed to remove dupes before saving e.g. #hash.tag = #hashtag
340 for($i=0; $i<count($hashtags); $i++) {
341 /* elide characters we don't want in the tag */
342 $hashtags[$i] = common_canonical_tag($hashtags[$i]);
345 foreach(array_unique($hashtags) as $hashtag) {
346 $this->saveTag($hashtag);
347 self::blow('profile:notice_ids_tagged:%d:%s', $this->profile_id, $hashtag);
353 * Record a single hash tag as associated with this notice.
354 * Tag format and uniqueness must be validated by caller.
356 function saveTag($hashtag)
358 $tag = new Notice_tag();
359 $tag->notice_id = $this->id;
360 $tag->tag = $hashtag;
361 $tag->created = $this->created;
362 $id = $tag->insert();
365 // TRANS: Server exception. %s are the error details.
366 throw new ServerException(sprintf(_('Database error inserting hashtag: %s.'),
367 $last_error->message));
371 // if it's saved, blow its cache
372 $tag->blowCache(false);
376 * Save a new notice and push it out to subscribers' inboxes.
377 * Poster's permissions are checked before sending.
379 * @param int $profile_id Profile ID of the poster
380 * @param string $content source message text; links may be shortened
381 * per current user's preference
382 * @param string $source source key ('web', 'api', etc)
383 * @param array $options Associative array of optional properties:
384 * string 'created' timestamp of notice; defaults to now
385 * int 'is_local' source/gateway ID, one of:
386 * Notice::LOCAL_PUBLIC - Local, ok to appear in public timeline
387 * Notice::REMOTE - Sent from a remote service;
388 * hide from public timeline but show in
389 * local "and friends" timelines
390 * Notice::LOCAL_NONPUBLIC - Local, but hide from public timeline
391 * Notice::GATEWAY - From another non-OStatus service;
392 * will not appear in public views
393 * float 'lat' decimal latitude for geolocation
394 * float 'lon' decimal longitude for geolocation
395 * int 'location_id' geoname identifier
396 * int 'location_ns' geoname namespace to interpret location_id
397 * int 'reply_to'; notice ID this is a reply to
398 * int 'repeat_of'; notice ID this is a repeat of
399 * string 'uri' unique ID for notice; a unique tag uri (can be url or anything too)
400 * string 'url' permalink to notice; defaults to local notice URL
401 * string 'rendered' rendered HTML version of content
402 * array 'replies' list of profile URIs for reply delivery in
403 * place of extracting @-replies from content.
404 * array 'groups' list of group IDs to deliver to, in place of
405 * extracting ! tags from content
406 * array 'tags' list of hashtag strings to save with the notice
407 * in place of extracting # tags from content
408 * array 'urls' list of attached/referred URLs to save with the
409 * notice in place of extracting links from content
410 * boolean 'distribute' whether to distribute the notice, default true
411 * string 'object_type' URL of the associated object type (default ActivityObject::NOTE)
412 * string 'verb' URL of the associated verb (default ActivityVerb::POST)
413 * int 'scope' Scope bitmask; default to SITE_SCOPE on private sites, 0 otherwise
415 * @fixme tag override
418 * @throws ClientException
420 static function saveNew($profile_id, $content, $source, array $options=null) {
421 $defaults = array('uri' => null,
423 'conversation' => null, // URI of conversation
424 'reply_to' => null, // This will override convo URI if the parent is known
425 'repeat_of' => null, // This will override convo URI if the repeated notice is known
427 'distribute' => true,
428 'object_type' => null,
431 if (!empty($options) && is_array($options)) {
432 $options = array_merge($defaults, $options);
438 if (!isset($is_local)) {
439 $is_local = Notice::LOCAL_PUBLIC;
442 $profile = Profile::getKV('id', $profile_id);
443 if (!$profile instanceof Profile) {
444 // TRANS: Client exception thrown when trying to save a notice for an unknown user.
445 throw new ClientException(_('Problem saving notice. Unknown user.'));
448 $user = User::getKV('id', $profile_id);
449 if ($user instanceof User) {
450 // Use the local user's shortening preferences, if applicable.
451 $final = $user->shortenLinks($content);
453 $final = common_shorten_links($content);
456 if (Notice::contentTooLong($final)) {
457 // TRANS: Client exception thrown if a notice contains too many characters.
458 throw new ClientException(_('Problem saving notice. Too long.'));
461 if (common_config('throttle', 'enabled') && !Notice::checkEditThrottle($profile_id)) {
462 common_log(LOG_WARNING, 'Excessive posting by profile #' . $profile_id . '; throttled.');
463 // TRANS: Client exception thrown when a user tries to post too many notices in a given time frame.
464 throw new ClientException(_('Too many notices too fast; take a breather '.
465 'and post again in a few minutes.'));
468 if (common_config('site', 'dupelimit') > 0 && !Notice::checkDupes($profile_id, $final)) {
469 common_log(LOG_WARNING, 'Dupe posting by profile #' . $profile_id . '; throttled.');
470 // TRANS: Client exception thrown when a user tries to post too many duplicate notices in a given time frame.
471 throw new ClientException(_('Too many duplicate messages too quickly;'.
472 ' take a breather and post again in a few minutes.'));
475 if (!$profile->hasRight(Right::NEWNOTICE)) {
476 common_log(LOG_WARNING, "Attempted post from user disallowed to post: " . $profile->nickname);
478 // TRANS: Client exception thrown when a user tries to post while being banned.
479 throw new ClientException(_('You are banned from posting notices on this site.'), 403);
482 $notice = new Notice();
483 $notice->profile_id = $profile_id;
485 $autosource = common_config('public', 'autosource');
487 // Sandboxed are non-false, but not 1, either
489 if (!$profile->hasRight(Right::PUBLICNOTICE) ||
490 ($source && $autosource && in_array($source, $autosource))) {
491 $notice->is_local = Notice::LOCAL_NONPUBLIC;
493 $notice->is_local = $is_local;
496 if (!empty($created)) {
497 $notice->created = $created;
499 $notice->created = common_sql_now();
502 if (!$notice->isLocal()) {
503 // Only do these checks for non-local notices. Local notices will generate these values later.
504 if (!common_valid_http_url($url)) {
505 common_debug('Bad notice URL: ['.$url.'], URI: ['.$uri.']. Cannot link back to original! This is normal for shared notices etc.');
508 throw new ServerException('No URI for remote notice. Cannot accept that.');
512 $notice->content = $final;
514 $notice->source = $source;
518 // Get the groups here so we can figure out replies and such
519 if (!isset($groups)) {
520 $groups = User_group::idsFromText($notice->content, $profile);
525 // Handle repeat case
527 if (!empty($options['repeat_of'])) {
529 // Check for a private one
531 $repeat = Notice::getByID($options['repeat_of']);
533 if ($profile->sameAs($repeat->getProfile())) {
534 // TRANS: Client error displayed when trying to repeat an own notice.
535 throw new ClientException(_('You cannot repeat your own notice.'));
538 if ($repeat->scope != Notice::SITE_SCOPE &&
539 $repeat->scope != Notice::PUBLIC_SCOPE) {
540 // TRANS: Client error displayed when trying to repeat a non-public notice.
541 throw new ClientException(_('Cannot repeat a private notice.'), 403);
544 if (!$repeat->inScope($profile)) {
545 // The generic checks above should cover this, but let's be sure!
546 // TRANS: Client error displayed when trying to repeat a notice you cannot access.
547 throw new ClientException(_('Cannot repeat a notice you cannot read.'), 403);
550 if ($profile->hasRepeated($repeat)) {
551 // TRANS: Client error displayed when trying to repeat an already repeated notice.
552 throw new ClientException(_('You already repeated that notice.'));
555 $notice->repeat_of = $repeat->id;
556 $notice->conversation = $repeat->conversation;
560 // If $reply_to is specified, we check that it exists, and then
561 // return it if it does
562 if (!empty($reply_to)) {
563 $reply = Notice::getKV('id', $reply_to);
564 } elseif (in_array($source, array('xmpp', 'mail', 'sms'))) {
565 // If the source lacks capability of sending the "reply_to"
566 // metadata, let's try to find an inline replyto-reference.
567 $reply = self::getInlineReplyTo($profile, $final);
570 if ($reply instanceof Notice) {
571 if (!$reply->inScope($profile)) {
572 // TRANS: Client error displayed when trying to reply to a notice a the target has no access to.
573 // TRANS: %1$s is a user nickname, %2$d is a notice ID (number).
574 throw new ClientException(sprintf(_('%1$s has no access to notice %2$d.'),
575 $profile->nickname, $reply->id), 403);
578 // If it's a repeat, the reply_to should be to the original
579 if ($reply->isRepeat()) {
580 $notice->reply_to = $reply->repeat_of;
582 $notice->reply_to = $reply->id;
584 // But the conversation ought to be the same :)
585 $notice->conversation = $reply->conversation;
587 // If the original is private to a group, and notice has
588 // no group specified, make it to the same group(s)
590 if (empty($groups) && ($reply->scope & Notice::GROUP_SCOPE)) {
592 $replyGroups = $reply->getGroups();
593 foreach ($replyGroups as $group) {
594 if ($profile->isMember($group)) {
595 $groups[] = $group->id;
603 // If we don't know the reply, we might know the conversation!
604 // This will happen if a known remote user replies to an
605 // unknown remote user - within a known conversation.
606 if (empty($notice->conversation) and !empty($options['conversation'])) {
607 $conv = Conversation::getKV('uri', $options['conversation']);
608 if ($conv instanceof Conversation) {
609 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.').');
610 $notice->conversation = $conv->id;
612 // Conversation URI was not found, so we must create it. But we can't create it
613 // until we have a Notice ID because of the database layout...
614 // $options['conversation'] will be used later after the $notice->insert();
615 common_debug('Conversation URI not found, so we have to create it after inserting this Notice: '.$options['conversation']);
618 // If we're not using the attached conversation URI let's remove it
619 // so we don't mistake ourselves later, when creating our own Conversation.
620 // This implies that the notice knows which conversation it belongs to.
621 $options['conversation'] = null;
625 $notloc = new Notice_location();
626 if (!empty($lat) && !empty($lon)) {
631 if (!empty($location_ns) && !empty($location_id)) {
632 $notloc->location_id = $location_id;
633 $notloc->location_ns = $location_ns;
636 if (!empty($rendered)) {
637 $notice->rendered = $rendered;
639 $notice->rendered = common_render_content($final, $notice);
643 if ($notice->isRepeat()) {
644 $notice->verb = ActivityVerb::SHARE;
645 $notice->object_type = ActivityObject::ACTIVITY;
647 $notice->verb = ActivityVerb::POST;
650 $notice->verb = $verb;
653 if (empty($object_type)) {
654 $notice->object_type = (empty($notice->reply_to)) ? ActivityObject::NOTE : ActivityObject::COMMENT;
656 $notice->object_type = $object_type;
659 if (is_null($scope) && $reply instanceof Notice) {
660 $notice->scope = $reply->scope;
662 $notice->scope = $scope;
665 $notice->scope = self::figureOutScope($profile, $groups, $notice->scope);
667 if (Event::handle('StartNoticeSave', array(&$notice))) {
669 // XXX: some of these functions write to the DB
672 $notice->insert(); // throws exception on failure, if successful we have an ->id
674 if (($notloc->lat && $notloc->lon) || ($notloc->location_id && $notloc->location_ns)) {
675 $notloc->notice_id = $notice->getID();
676 $notloc->insert(); // store the notice location if it had any information
679 // If it's not part of a conversation, it's
680 // the beginning of a new conversation.
681 if (empty($notice->conversation)) {
682 $orig = clone($notice);
683 // $act->context->conversation will be null if it was not provided
685 $conv = Conversation::create($notice, $options['conversation']);
686 $notice->conversation = $conv->id;
687 $notice->update($orig);
689 } catch (Exception $e) {
690 // Let's test if we managed initial insert, which would imply
691 // failing on some update-part (check 'insert()'). Delete if
692 // something had been stored to the database.
693 if (!empty($notice->id)) {
700 // Clear the cache for subscribed users, so they'll update at next request
701 // XXX: someone clever could prepend instead of clearing the cache
703 // Save per-notice metadata...
705 if (isset($replies)) {
706 $notice->saveKnownReplies($replies);
708 $notice->saveReplies();
712 $notice->saveKnownTags($tags);
717 // Note: groups may save tags, so must be run after tags are saved
718 // to avoid errors on duplicates.
719 // Note: groups should always be set.
721 $notice->saveKnownGroups($groups);
724 $notice->saveKnownUrls($urls);
730 // Prepare inbox delivery, may be queued to background.
731 $notice->distribute();
737 static function saveActivity(Activity $act, Profile $actor, array $options=array())
739 // First check if we're going to let this Activity through from the specific actor
740 if (!$actor->hasRight(Right::NEWNOTICE)) {
741 common_log(LOG_WARNING, "Attempted post from user disallowed to post: " . $actor->getNickname());
743 // TRANS: Client exception thrown when a user tries to post while being banned.
744 throw new ClientException(_m('You are banned from posting notices on this site.'), 403);
746 if (common_config('throttle', 'enabled') && !self::checkEditThrottle($actor->id)) {
747 common_log(LOG_WARNING, 'Excessive posting by profile #' . $actor->id . '; throttled.');
748 // TRANS: Client exception thrown when a user tries to post too many notices in a given time frame.
749 throw new ClientException(_m('Too many notices too fast; take a breather '.
750 'and post again in a few minutes.'));
753 // Get ActivityObject properties
754 if (!empty($act->id)) {
756 $options['uri'] = $act->id;
757 $options['url'] = $act->link;
759 $actobj = count($act->objects)==1 ? $act->objects[0] : null;
760 if (!is_null($actobj) && !empty($actobj->id)) {
761 $options['uri'] = $actobj->id;
763 $options['url'] = $actobj->link;
764 } elseif (preg_match('!^https?://!', $actobj->id)) {
765 $options['url'] = $actobj->id;
772 'is_local' => self::LOCAL_PUBLIC,
773 'mentions' => array(),
777 'source' => 'unknown',
782 'distribute' => true);
784 // options will have default values when nothing has been supplied
785 $options = array_merge($defaults, $options);
786 foreach (array_keys($defaults) as $key) {
787 // Only convert the keynames we specify ourselves from 'defaults' array into variables
788 $$key = $options[$key];
790 extract($options, EXTR_SKIP);
792 $stored = new Notice();
795 if ($stored->find()) {
796 common_debug('cannot create duplicate Notice URI: '.$stored->uri);
797 throw new Exception('Notice URI already exists');
801 $stored->profile_id = $actor->id;
802 $stored->source = $source;
805 $stored->verb = $act->verb;
807 // Use the local user's shortening preferences, if applicable.
808 $stored->rendered = $actor->isLocal()
809 ? $actor->shortenLinks($act->content)
811 $stored->content = common_strip_html($stored->rendered);
813 $autosource = common_config('public', 'autosource');
815 // Sandboxed are non-false, but not 1, either
816 if (!$actor->hasRight(Right::PUBLICNOTICE) ||
817 ($source && $autosource && in_array($source, $autosource))) {
818 $stored->is_local = Notice::LOCAL_NONPUBLIC;
821 // Maybe a missing act-time should be fatal if the actor is not local?
822 if (!empty($act->time)) {
823 $stored->created = common_sql_date($act->time);
825 $stored->created = common_sql_now();
829 if ($act->context instanceof ActivityContext && !empty($act->context->replyToID)) {
830 $reply = self::getKV('uri', $act->context->replyToID);
832 if (!$reply instanceof Notice && $act->target instanceof ActivityObject) {
833 $reply = self::getKV('uri', $act->target->id);
836 if ($reply instanceof Notice) {
837 if (!$reply->inScope($actor)) {
838 // TRANS: Client error displayed when trying to reply to a notice a the target has no access to.
839 // TRANS: %1$s is a user nickname, %2$d is a notice ID (number).
840 throw new ClientException(sprintf(_m('%1$s has no right to reply to notice %2$d.'), $actor->getNickname(), $reply->id), 403);
843 $stored->reply_to = $reply->id;
844 $stored->conversation = $reply->conversation;
846 // If the original is private to a group, and notice has no group specified,
847 // make it to the same group(s)
848 if (empty($groups) && ($reply->scope & Notice::GROUP_SCOPE)) {
850 $replyGroups = $reply->getGroups();
851 foreach ($replyGroups as $group) {
852 if ($actor->isMember($group)) {
853 $groups[] = $group->id;
858 if (is_null($scope)) {
859 $scope = $reply->scope;
862 // If we don't know the reply, we might know the conversation!
863 // This will happen if a known remote user replies to an
864 // unknown remote user - within a known conversation.
865 if (empty($stored->conversation) and !empty($act->context->conversation)) {
866 $conv = Conversation::getKV('uri', $act->context->conversation);
867 if ($conv instanceof Conversation) {
868 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.').');
869 $stored->conversation = $conv->id;
871 // Conversation URI was not found, so we must create it. But we can't create it
872 // until we have a Notice ID because of the database layout...
873 // $options['conversation'] will be used later after the $stored->insert();
874 common_debug('Conversation URI from activity context not found, so we have to create it after inserting this Notice: '.$act->context->conversation);
880 if ($act->context instanceof ActivityContext) {
881 if ($act->context->location instanceof Location) {
882 $notloc = Notice_location::fromLocation($act->context->location);
885 $act->context = new ActivityContext();
888 $stored->scope = self::figureOutScope($actor, $groups, $scope);
890 foreach ($act->categories as $cat) {
892 $term = common_canonical_tag($cat->term);
899 foreach ($act->enclosures as $href) {
900 // @todo FIXME: Save these locally or....?
904 if (Event::handle('StartNoticeSave', array(&$stored))) {
905 // XXX: some of these functions write to the DB
908 $stored->insert(); // throws exception on error
910 if ($notloc instanceof Notice_location) {
911 $notloc->notice_id = $stored->getID();
915 $orig = clone($stored); // for updating later in this try clause
918 Event::handle('StoreActivityObject', array($act, $stored, $options, &$object));
919 if (empty($object)) {
920 throw new ServerException('Unsuccessful call to StoreActivityObject '.$stored->uri . ': '.$act->asString());
923 // If it's not part of a conversation, it's the beginning
924 // of a new one (or belongs to a previously unknown URI).
925 if (empty($stored->conversation)) {
926 // $act->context->conversation will be null if it was not provided
927 common_debug('Creating a new conversation for stored notice ID='.$stored->getID().' with URI: '.$act->context->conversation);
928 $conv = Conversation::create($stored, $act->context->conversation);
929 $stored->conversation = $conv->id;
932 $stored->update($orig);
933 } catch (Exception $e) {
934 if (empty($stored->id)) {
935 common_debug('Failed to save stored object entry in database ('.$e->getMessage().')');
937 common_debug('Failed to store activity object in database ('.$e->getMessage().'), deleting notice id '.$stored->id);
943 if (!$stored instanceof Notice) {
944 throw new ServerException('StartNoticeSave did not give back a Notice');
947 // Save per-notice metadata...
951 // This event lets plugins filter out non-local recipients (attentions we don't care about)
952 // Used primarily for OStatus (and if we don't federate, all attentions would be local anyway)
953 Event::handle('GetLocalAttentions', array($actor, $act->context->attention, &$mentions, &$groups));
955 if (!empty($mentions)) {
956 $stored->saveKnownReplies($mentions);
958 $stored->saveReplies();
962 $stored->saveKnownTags($tags);
967 // Note: groups may save tags, so must be run after tags are saved
968 // to avoid errors on duplicates.
969 // Note: groups should always be set.
971 $stored->saveKnownGroups($groups);
974 $stored->saveKnownUrls($urls);
980 // Prepare inbox delivery, may be queued to background.
981 $stored->distribute();
987 static public function figureOutScope(Profile $actor, array $groups, $scope=null) {
988 if (is_null($scope)) {
989 $scope = self::defaultScope();
992 // For private streams
994 $user = $actor->getUser();
995 // FIXME: We can't do bit comparison with == (Legacy StatusNet thing. Let's keep it for now.)
996 if ($user->private_stream && ($scope == Notice::PUBLIC_SCOPE || $scope == Notice::SITE_SCOPE)) {
997 $scope |= Notice::FOLLOWER_SCOPE;
999 } catch (NoSuchUserException $e) {
1000 // TODO: Not a local user, so we don't know about scope preferences... yet!
1003 // Force the scope for private groups
1004 foreach ($groups as $group_id) {
1006 $group = User_group::getByID($group_id);
1007 if ($group->force_scope) {
1008 $scope |= Notice::GROUP_SCOPE;
1011 } catch (Exception $e) {
1012 common_log(LOG_ERR, 'Notice figureOutScope threw exception: '.$e->getMessage());
1019 function blowOnInsert($conversation = false)
1021 $this->blowStream('profile:notice_ids:%d', $this->profile_id);
1023 if ($this->isPublic()) {
1024 $this->blowStream('public');
1025 $this->blowStream('networkpublic');
1028 self::blow('notice:list-ids:conversation:%s', $this->conversation);
1029 self::blow('conversation:notice_count:%d', $this->conversation);
1031 if ($this->isRepeat()) {
1032 // XXX: we should probably only use one of these
1033 $this->blowStream('notice:repeats:%d', $this->repeat_of);
1034 self::blow('notice:list-ids:repeat_of:%d', $this->repeat_of);
1037 $original = Notice::getKV('id', $this->repeat_of);
1039 if ($original instanceof Notice) {
1040 $originalUser = User::getKV('id', $original->profile_id);
1041 if ($originalUser instanceof User) {
1042 $this->blowStream('user:repeats_of_me:%d', $originalUser->id);
1046 $profile = Profile::getKV($this->profile_id);
1048 if ($profile instanceof Profile) {
1049 $profile->blowNoticeCount();
1052 $ptags = $this->getProfileTags();
1053 foreach ($ptags as $ptag) {
1054 $ptag->blowNoticeStreamCache();
1059 * Clear cache entries related to this notice at delete time.
1060 * Necessary to avoid breaking paging on public, profile timelines.
1062 function blowOnDelete()
1064 $this->blowOnInsert();
1066 self::blow('profile:notice_ids:%d;last', $this->profile_id);
1068 if ($this->isPublic()) {
1069 self::blow('public;last');
1070 self::blow('networkpublic;last');
1073 self::blow('fave:by_notice', $this->id);
1075 if ($this->conversation) {
1076 // In case we're the first, will need to calc a new root.
1077 self::blow('notice:conversation_root:%d', $this->conversation);
1080 $ptags = $this->getProfileTags();
1081 foreach ($ptags as $ptag) {
1082 $ptag->blowNoticeStreamCache(true);
1086 function blowStream()
1088 $c = self::memcache();
1094 $args = func_get_args();
1095 $format = array_shift($args);
1096 $keyPart = vsprintf($format, $args);
1097 $cacheKey = Cache::key($keyPart);
1098 $c->delete($cacheKey);
1100 // delete the "last" stream, too, if this notice is
1101 // older than the top of that stream
1103 $lastKey = $cacheKey.';last';
1105 $lastStr = $c->get($lastKey);
1107 if ($lastStr !== false) {
1108 $window = explode(',', $lastStr);
1109 $lastID = $window[0];
1110 $lastNotice = Notice::getKV('id', $lastID);
1111 if (!$lastNotice instanceof Notice // just weird
1112 || strtotime($lastNotice->created) >= strtotime($this->created)) {
1113 $c->delete($lastKey);
1118 /** save all urls in the notice to the db
1120 * follow redirects and save all available file information
1121 * (mimetype, date, size, oembed, etc.)
1125 function saveUrls() {
1126 if (common_config('attachments', 'process_links')) {
1127 common_replace_urls_callback($this->content, array($this, 'saveUrl'), $this);
1132 * Save the given URLs as related links/attachments to the db
1134 * follow redirects and save all available file information
1135 * (mimetype, date, size, oembed, etc.)
1139 function saveKnownUrls($urls)
1141 if (common_config('attachments', 'process_links')) {
1142 // @fixme validation?
1143 foreach (array_unique($urls) as $url) {
1144 $this->saveUrl($url, $this);
1152 function saveUrl($url, Notice $notice) {
1154 File::processNew($url, $notice);
1155 } catch (ServerException $e) {
1156 // Could not save URL. Log it?
1160 static function checkDupes($profile_id, $content) {
1161 $profile = Profile::getKV($profile_id);
1162 if (!$profile instanceof Profile) {
1165 $notice = $profile->getNotices(0, CachingNoticeStream::CACHE_WINDOW);
1166 if (!empty($notice)) {
1168 while ($notice->fetch()) {
1169 if (time() - strtotime($notice->created) >= common_config('site', 'dupelimit')) {
1171 } else if ($notice->content == $content) {
1176 // If we get here, oldest item in cache window is not
1177 // old enough for dupe limit; do direct check against DB
1178 $notice = new Notice();
1179 $notice->profile_id = $profile_id;
1180 $notice->content = $content;
1181 $threshold = common_sql_date(time() - common_config('site', 'dupelimit'));
1182 $notice->whereAdd(sprintf("created > '%s'", $notice->escape($threshold)));
1184 $cnt = $notice->count();
1188 static function checkEditThrottle($profile_id) {
1189 $profile = Profile::getKV($profile_id);
1190 if (!$profile instanceof Profile) {
1193 // Get the Nth notice
1194 $notice = $profile->getNotices(common_config('throttle', 'count') - 1, 1);
1195 if ($notice && $notice->fetch()) {
1196 // If the Nth notice was posted less than timespan seconds ago
1197 if (time() - strtotime($notice->created) <= common_config('throttle', 'timespan')) {
1202 // Either not N notices in the stream, OR the Nth was not posted within timespan seconds
1206 protected $_attachments = array();
1208 function attachments() {
1209 if (isset($this->_attachments[$this->id])) {
1210 return $this->_attachments[$this->id];
1213 $f2ps = File_to_post::listGet('post_id', array($this->id));
1215 foreach ($f2ps[$this->id] as $f2p) {
1216 $ids[] = $f2p->file_id;
1219 $files = File::multiGet('id', $ids);
1220 $this->_attachments[$this->id] = $files->fetchAll();
1221 return $this->_attachments[$this->id];
1224 function _setAttachments($attachments)
1226 $this->_attachments[$this->id] = $attachments;
1229 static function publicStream($offset=0, $limit=20, $since_id=null, $max_id=null)
1231 $stream = new PublicNoticeStream();
1232 return $stream->getNotices($offset, $limit, $since_id, $max_id);
1235 static function conversationStream($id, $offset=0, $limit=20, $since_id=null, $max_id=null)
1237 $stream = new ConversationNoticeStream($id);
1238 return $stream->getNotices($offset, $limit, $since_id, $max_id);
1242 * Is this notice part of an active conversation?
1244 * @return boolean true if other messages exist in the same
1245 * conversation, false if this is the only one
1247 function hasConversation()
1249 if (empty($this->conversation)) {
1250 // this notice is not part of a conversation apparently
1251 // FIXME: all notices should have a conversation value, right?
1255 $stream = new ConversationNoticeStream($this->conversation);
1256 $notice = $stream->getNotices(/*offset*/ 1, /*limit*/ 1);
1258 // if our "offset 1, limit 1" query got a result, return true else false
1259 return $notice->N > 0;
1263 * Grab the earliest notice from this conversation.
1265 * @return Notice or null
1267 function conversationRoot($profile=-1)
1269 // XXX: can this happen?
1271 if (empty($this->conversation)) {
1275 // Get the current profile if not specified
1277 if (is_int($profile) && $profile == -1) {
1278 $profile = Profile::current();
1281 // If this notice is out of scope, no root for you!
1283 if (!$this->inScope($profile)) {
1287 // If this isn't a reply to anything, then it's its own
1288 // root if it's the earliest notice in the conversation:
1290 if (empty($this->reply_to)) {
1292 $root->conversation = $this->conversation;
1293 $root->orderBy('notice.created ASC');
1294 $root->find(true); // true means "fetch first result"
1299 if (is_null($profile)) {
1300 $keypart = sprintf('notice:conversation_root:%d:null', $this->id);
1302 $keypart = sprintf('notice:conversation_root:%d:%d',
1307 $root = self::cacheGet($keypart);
1309 if ($root !== false && $root->inScope($profile)) {
1316 $parent = $last->getParent();
1317 if ($parent->inScope($profile)) {
1321 } catch (NoParentNoticeException $e) {
1322 // Latest notice has no parent
1324 // No parent, or parent out of scope
1329 self::cacheSet($keypart, $root);
1335 * Pull up a full list of local recipients who will be getting
1336 * this notice in their inbox. Results will be cached, so don't
1337 * change the input data wily-nilly!
1339 * @param array $groups optional list of Group objects;
1340 * if left empty, will be loaded from group_inbox records
1341 * @param array $recipient optional list of reply profile ids
1342 * if left empty, will be loaded from reply records
1343 * @return array associating recipient user IDs with an inbox source constant
1345 function whoGets(array $groups=null, array $recipients=null)
1347 $c = self::memcache();
1350 $ni = $c->get(Cache::key('notice:who_gets:'.$this->id));
1351 if ($ni !== false) {
1356 if (is_null($recipients)) {
1357 $recipients = $this->getReplies();
1362 // Give plugins a chance to add folks in at start...
1363 if (Event::handle('StartNoticeWhoGets', array($this, &$ni))) {
1365 $users = $this->getSubscribedUsers();
1366 foreach ($users as $id) {
1367 $ni[$id] = NOTICE_INBOX_SOURCE_SUB;
1370 if (is_null($groups)) {
1371 $groups = $this->getGroups();
1373 foreach ($groups as $group) {
1374 $users = $group->getUserMembers();
1375 foreach ($users as $id) {
1376 if (!array_key_exists($id, $ni)) {
1377 $ni[$id] = NOTICE_INBOX_SOURCE_GROUP;
1382 $ptAtts = $this->getAttentionsFromProfileTags();
1383 foreach ($ptAtts as $key=>$val) {
1384 if (!array_key_exists($key, $ni)) {
1389 foreach ($recipients as $recipient) {
1390 if (!array_key_exists($recipient, $ni)) {
1391 $ni[$recipient] = NOTICE_INBOX_SOURCE_REPLY;
1395 // Exclude any deleted, non-local, or blocking recipients.
1396 $profile = $this->getProfile();
1397 $originalProfile = null;
1398 if ($this->isRepeat()) {
1399 // Check blocks against the original notice's poster as well.
1400 $original = Notice::getKV('id', $this->repeat_of);
1401 if ($original instanceof Notice) {
1402 $originalProfile = $original->getProfile();
1406 foreach ($ni as $id => $source) {
1408 $user = User::getKV('id', $id);
1409 if (!$user instanceof User ||
1410 $user->hasBlocked($profile) ||
1411 ($originalProfile && $user->hasBlocked($originalProfile))) {
1414 } catch (UserNoProfileException $e) {
1415 // User doesn't have a profile; invalid; skip them.
1420 // Give plugins a chance to filter out...
1421 Event::handle('EndNoticeWhoGets', array($this, &$ni));
1425 // XXX: pack this data better
1426 $c->set(Cache::key('notice:who_gets:'.$this->id), $ni);
1432 function getSubscribedUsers()
1436 if(common_config('db','quote_identifiers'))
1437 $user_table = '"user"';
1438 else $user_table = 'user';
1442 'FROM '. $user_table .' JOIN subscription '.
1443 'ON '. $user_table .'.id = subscription.subscriber ' .
1444 'WHERE subscription.subscribed = %d ';
1446 $user->query(sprintf($qry, $this->profile_id));
1450 while ($user->fetch()) {
1459 function getProfileTags()
1461 $profile = $this->getProfile();
1462 $list = $profile->getOtherTags($profile);
1465 while($list->fetch()) {
1466 $ptags[] = clone($list);
1472 public function getAttentionsFromProfileTags()
1475 $ptags = $this->getProfileTags();
1476 foreach ($ptags as $ptag) {
1477 $users = $ptag->getUserSubscribers();
1478 foreach ($users as $id) {
1479 $ni[$id] = NOTICE_INBOX_SOURCE_PROFILE_TAG;
1486 * Record this notice to the given group inboxes for delivery.
1487 * Overrides the regular parsing of !group markup.
1489 * @param string $group_ids
1490 * @fixme might prefer URIs as identifiers, as for replies?
1491 * best with generalizations on user_group to support
1492 * remote groups better.
1494 function saveKnownGroups($group_ids)
1496 if (!is_array($group_ids)) {
1497 // TRANS: Server exception thrown when no array is provided to the method saveKnownGroups().
1498 throw new ServerException(_('Bad type provided to saveKnownGroups.'));
1502 foreach (array_unique($group_ids) as $id) {
1503 $group = User_group::getKV('id', $id);
1504 if ($group instanceof User_group) {
1505 common_log(LOG_DEBUG, "Local delivery to group id $id, $group->nickname");
1506 $result = $this->addToGroupInbox($group);
1508 common_log_db_error($gi, 'INSERT', __FILE__);
1511 if (common_config('group', 'addtag')) {
1512 // we automatically add a tag for every group name, too
1514 $tag = Notice_tag::pkeyGet(array('tag' => common_canonical_tag($group->nickname),
1515 'notice_id' => $this->id));
1517 if (is_null($tag)) {
1518 $this->saveTag($group->nickname);
1522 $groups[] = clone($group);
1524 common_log(LOG_ERR, "Local delivery to group id $id skipped, doesn't exist");
1531 function addToGroupInbox(User_group $group)
1533 $gi = Group_inbox::pkeyGet(array('group_id' => $group->id,
1534 'notice_id' => $this->id));
1536 if (!$gi instanceof Group_inbox) {
1538 $gi = new Group_inbox();
1540 $gi->group_id = $group->id;
1541 $gi->notice_id = $this->id;
1542 $gi->created = $this->created;
1544 $result = $gi->insert();
1547 common_log_db_error($gi, 'INSERT', __FILE__);
1548 // TRANS: Server exception thrown when an update for a group inbox fails.
1549 throw new ServerException(_('Problem saving group inbox.'));
1552 self::blow('user_group:notice_ids:%d', $gi->group_id);
1559 * Save reply records indicating that this notice needs to be
1560 * delivered to the local users with the given URIs.
1562 * Since this is expected to be used when saving foreign-sourced
1563 * messages, we won't deliver to any remote targets as that's the
1564 * source service's responsibility.
1566 * Mail notifications etc will be handled later.
1568 * @param array $uris Array of unique identifier URIs for recipients
1570 function saveKnownReplies(array $uris)
1576 $sender = Profile::getKV($this->profile_id);
1578 foreach (array_unique($uris) as $uri) {
1580 $profile = Profile::fromUri($uri);
1581 } catch (UnknownUriException $e) {
1582 common_log(LOG_WARNING, "Unable to determine profile for URI '$uri'");
1586 if ($profile->hasBlocked($sender)) {
1587 common_log(LOG_INFO, "Not saving reply to profile {$profile->id} ($uri) from sender {$sender->id} because of a block.");
1591 $this->saveReply($profile->id);
1592 self::blow('reply:stream:%d', $profile->id);
1599 * Pull @-replies from this message's content in StatusNet markup format
1600 * and save reply records indicating that this message needs to be
1601 * delivered to those users.
1603 * Mail notifications to local profiles will be sent later.
1605 * @return array of integer profile IDs
1608 function saveReplies()
1610 // Don't save reply data for repeats
1612 if ($this->isRepeat()) {
1616 $sender = $this->getProfile();
1620 // If it's a reply, save for the replied-to author
1622 $parent = $this->getParent();
1623 $parentauthor = $parent->getProfile();
1624 $this->saveReply($parentauthor->id);
1625 $replied[$parentauthor->id] = 1;
1626 self::blow('reply:stream:%d', $parentauthor->id);
1627 } catch (NoParentNoticeException $e) {
1628 // Not a reply, since it has no parent!
1631 // @todo ideally this parser information would only
1632 // be calculated once.
1634 $mentions = common_find_mentions($this->content, $this);
1636 // store replied only for first @ (what user/notice what the reply directed,
1637 // we assume first @ is it)
1639 foreach ($mentions as $mention) {
1641 foreach ($mention['mentioned'] as $mentioned) {
1643 // skip if they're already covered
1644 if (array_key_exists($mentioned->id, $replied)) {
1648 // Don't save replies from blocked profile to local user
1650 $mentioned_user = User::getKV('id', $mentioned->id);
1651 if ($mentioned_user instanceof User && $mentioned_user->hasBlocked($sender)) {
1655 $this->saveReply($mentioned->id);
1656 $replied[$mentioned->id] = 1;
1657 self::blow('reply:stream:%d', $mentioned->id);
1661 $recipientIds = array_keys($replied);
1663 return $recipientIds;
1666 function saveReply($profileId)
1668 $reply = new Reply();
1670 $reply->notice_id = $this->id;
1671 $reply->profile_id = $profileId;
1672 $reply->modified = $this->created;
1679 protected $_replies = array();
1682 * Pull the complete list of @-mentioned profile IDs for this notice.
1684 * @return array of integer profile ids
1686 function getReplies()
1688 if (!isset($this->_replies[$this->getID()])) {
1689 $mentions = Reply::multiGet('notice_id', array($this->getID()));
1690 $this->_replies[$this->getID()] = $mentions->fetchAll('profile_id');
1692 return $this->_replies[$this->getID()];
1695 function _setReplies($replies)
1697 $this->_replies[$this->getID()] = $replies;
1701 * Pull the complete list of @-reply targets for this notice.
1703 * @return array of Profiles
1705 function getReplyProfiles()
1707 $ids = $this->getReplies();
1709 $profiles = Profile::multiGet('id', $ids);
1711 return $profiles->fetchAll();
1715 * Send e-mail notifications to local @-reply targets.
1717 * Replies must already have been saved; this is expected to be run
1718 * from the distrib queue handler.
1720 function sendReplyNotifications()
1722 // Don't send reply notifications for repeats
1724 if ($this->isRepeat()) {
1728 $recipientIds = $this->getReplies();
1729 if (Event::handle('StartNotifyMentioned', array($this, &$recipientIds))) {
1730 require_once INSTALLDIR.'/lib/mail.php';
1732 foreach ($recipientIds as $recipientId) {
1733 $user = User::getKV('id', $recipientId);
1734 if ($user instanceof User) {
1735 mail_notify_attn($user, $this);
1738 Event::handle('EndNotifyMentioned', array($this, $recipientIds));
1743 * Pull list of groups this notice needs to be delivered to,
1744 * as previously recorded by saveKnownGroups().
1746 * @return array of Group objects
1749 protected $_groups = array();
1751 function getGroups()
1753 // Don't save groups for repeats
1755 if (!empty($this->repeat_of)) {
1759 if (isset($this->_groups[$this->id])) {
1760 return $this->_groups[$this->id];
1763 $gis = Group_inbox::listGet('notice_id', array($this->id));
1767 foreach ($gis[$this->id] as $gi) {
1768 $ids[] = $gi->group_id;
1771 $groups = User_group::multiGet('id', $ids);
1772 $this->_groups[$this->id] = $groups->fetchAll();
1773 return $this->_groups[$this->id];
1776 function _setGroups($groups)
1778 $this->_groups[$this->id] = $groups;
1782 * Convert a notice into an activity for export.
1784 * @param Profile $scoped The currently logged in/scoped profile
1786 * @return Activity activity object representing this Notice.
1789 function asActivity(Profile $scoped=null)
1791 $act = self::cacheGet(Cache::codeKey('notice:as-activity:'.$this->id));
1793 if ($act instanceof Activity) {
1796 $act = new Activity();
1798 if (Event::handle('StartNoticeAsActivity', array($this, $act, $scoped))) {
1800 $act->id = $this->uri;
1801 $act->time = strtotime($this->created);
1803 $act->link = $this->getUrl();
1804 } catch (InvalidUrlException $e) {
1805 // The notice is probably a share or similar, which don't
1806 // have a representational URL of their own.
1808 $act->content = common_xml_safe_str($this->rendered);
1810 $profile = $this->getProfile();
1812 $act->actor = $profile->asActivityObject();
1813 $act->actor->extra[] = $profile->profileInfo($scoped);
1815 $act->verb = $this->verb;
1817 if (!$this->repeat_of) {
1818 $act->objects[] = $this->asActivityObject();
1821 // XXX: should this be handled by default processing for object entry?
1825 $tags = $this->getTags();
1827 foreach ($tags as $tag) {
1828 $cat = new AtomCategory();
1831 $act->categories[] = $cat;
1835 // XXX: use Atom Media and/or File activity objects instead
1837 $attachments = $this->attachments();
1839 foreach ($attachments as $attachment) {
1840 // Include local attachments in Activity
1841 if (!empty($attachment->filename)) {
1842 $act->enclosures[] = $attachment->getEnclosure();
1846 $ctx = new ActivityContext();
1849 $reply = $this->getParent();
1850 $ctx->replyToID = $reply->getUri();
1851 $ctx->replyToUrl = $reply->getUrl(true); // true for fallback to local URL, less messy
1852 } catch (NoParentNoticeException $e) {
1853 // This is not a reply to something
1857 $ctx->location = Notice_location::locFromStored($this);
1858 } catch (ServerException $e) {
1859 $ctx->location = null;
1864 if (!empty($this->conversation)) {
1865 $conv = Conversation::getKV('id', $this->conversation);
1866 if ($conv instanceof Conversation) {
1867 $ctx->conversation = $conv->uri;
1871 $reply_ids = $this->getReplies();
1873 foreach ($reply_ids as $id) {
1874 $rprofile = Profile::getKV('id', $id);
1875 if ($rprofile instanceof Profile) {
1876 $ctx->attention[$rprofile->getUri()] = ActivityObject::PERSON;
1880 $groups = $this->getGroups();
1882 foreach ($groups as $group) {
1883 $ctx->attention[$group->getUri()] = ActivityObject::GROUP;
1886 switch ($this->scope) {
1887 case Notice::PUBLIC_SCOPE:
1888 $ctx->attention[ActivityContext::ATTN_PUBLIC] = ActivityObject::COLLECTION;
1890 case Notice::FOLLOWER_SCOPE:
1891 $surl = common_local_url("subscribers", array('nickname' => $profile->nickname));
1892 $ctx->attention[$surl] = ActivityObject::COLLECTION;
1896 $act->context = $ctx;
1898 $source = $this->getSource();
1900 if ($source instanceof Notice_source) {
1901 $act->generator = ActivityObject::fromNoticeSource($source);
1906 $atom_feed = $profile->getAtomFeed();
1908 if (!empty($atom_feed)) {
1910 $act->source = new ActivitySource();
1912 // XXX: we should store the actual feed ID
1914 $act->source->id = $atom_feed;
1916 // XXX: we should store the actual feed title
1918 $act->source->title = $profile->getBestName();
1920 $act->source->links['alternate'] = $profile->profileurl;
1921 $act->source->links['self'] = $atom_feed;
1923 $act->source->icon = $profile->avatarUrl(AVATAR_PROFILE_SIZE);
1925 $notice = $profile->getCurrentNotice();
1927 if ($notice instanceof Notice) {
1928 $act->source->updated = self::utcDate($notice->created);
1931 $user = User::getKV('id', $profile->id);
1933 if ($user instanceof User) {
1934 $act->source->links['license'] = common_config('license', 'url');
1938 if ($this->isLocal()) {
1939 $act->selfLink = common_local_url('ApiStatusesShow', array('id' => $this->id,
1940 'format' => 'atom'));
1941 $act->editLink = $act->selfLink;
1944 Event::handle('EndNoticeAsActivity', array($this, $act, $scoped));
1947 self::cacheSet(Cache::codeKey('notice:as-activity:'.$this->id), $act);
1952 // This has gotten way too long. Needs to be sliced up into functional bits
1953 // or ideally exported to a utility class.
1955 function asAtomEntry($namespace=false,
1958 Profile $scoped=null)
1960 $act = $this->asActivity($scoped);
1961 $act->extra[] = $this->noticeInfo($scoped);
1962 return $act->asString($namespace, $author, $source);
1966 * Extra notice info for atom entries
1968 * Clients use some extra notice info in the atom stream.
1969 * This gives it to them.
1971 * @param Profile $scoped The currently logged in/scoped profile
1973 * @return array representation of <statusnet:notice_info> element
1976 function noticeInfo(Profile $scoped=null)
1978 // local notice ID (useful to clients for ordering)
1980 $noticeInfoAttr = array('local_id' => $this->id);
1984 $ns = $this->getSource();
1986 if ($ns instanceof Notice_source) {
1987 $noticeInfoAttr['source'] = $ns->code;
1988 if (!empty($ns->url)) {
1989 $noticeInfoAttr['source_link'] = $ns->url;
1990 if (!empty($ns->name)) {
1991 $noticeInfoAttr['source'] = '<a href="'
1992 . htmlspecialchars($ns->url)
1993 . '" rel="nofollow">'
1994 . htmlspecialchars($ns->name)
2000 // favorite and repeated
2002 if ($scoped instanceof Profile) {
2003 $noticeInfoAttr['repeated'] = ($scoped->hasRepeated($this)) ? "true" : "false";
2006 if (!empty($this->repeat_of)) {
2007 $noticeInfoAttr['repeat_of'] = $this->repeat_of;
2010 Event::handle('StatusNetApiNoticeInfo', array($this, &$noticeInfoAttr, $scoped));
2012 return array('statusnet:notice_info', $noticeInfoAttr, null);
2016 * Returns an XML string fragment with a reference to a notice as an
2017 * Activity Streams noun object with the given element type.
2019 * Assumes that 'activity' namespace has been previously defined.
2021 * @param string $element one of 'subject', 'object', 'target'
2025 function asActivityNoun($element)
2027 $noun = $this->asActivityObject();
2028 return $noun->asString('activity:' . $element);
2031 public function asActivityObject()
2033 $object = new ActivityObject();
2035 if (Event::handle('StartActivityObjectFromNotice', array($this, &$object))) {
2036 $object->type = $this->object_type ?: ActivityObject::NOTE;
2037 $object->id = $this->getUri();
2038 $object->title = sprintf('New %1$s by %2$s', ActivityObject::canonicalType($object->type), $this->getProfile()->getNickname());
2039 $object->content = $this->rendered;
2040 $object->link = $this->getUrl();
2042 $object->extra[] = array('status_net', array('notice_id' => $this->id));
2044 Event::handle('EndActivityObjectFromNotice', array($this, &$object));
2051 * Determine which notice, if any, a new notice is in reply to.
2053 * For conversation tracking, we try to see where this notice fits
2054 * in the tree. Beware that this may very well give false positives
2055 * and add replies to wrong threads (if there have been newer posts
2056 * by the same user as we're replying to).
2058 * @param Profile $sender Author profile
2059 * @param string $content Final notice content
2061 * @return integer ID of replied-to notice, or null for not a reply.
2064 static function getInlineReplyTo(Profile $sender, $content)
2066 // Is there an initial @ or T?
2067 if (preg_match('/^T ([A-Z0-9]{1,64}) /', $content, $match)
2068 || preg_match('/^@([a-z0-9]{1,64})\s+/', $content, $match)) {
2069 $nickname = common_canonical_nickname($match[1]);
2074 // Figure out who that is.
2075 $recipient = common_relative_profile($sender, $nickname, common_sql_now());
2077 if ($recipient instanceof Profile) {
2078 // Get their last notice
2079 $last = $recipient->getCurrentNotice();
2080 if ($last instanceof Notice) {
2083 // Maybe in the future we want to handle something else below
2084 // so don't return getCurrentNotice() immediately.
2090 static function maxContent()
2092 $contentlimit = common_config('notice', 'contentlimit');
2093 // null => use global limit (distinct from 0!)
2094 if (is_null($contentlimit)) {
2095 $contentlimit = common_config('site', 'textlimit');
2097 return $contentlimit;
2100 static function contentTooLong($content)
2102 $contentlimit = self::maxContent();
2103 return ($contentlimit > 0 && !empty($content) && (mb_strlen($content) > $contentlimit));
2107 * Convenience function for posting a repeat of an existing message.
2109 * @param Profile $repeater Profile which is doing the repeat
2110 * @param string $source: posting source key, eg 'web', 'api', etc
2113 * @throws Exception on failure or permission problems
2115 function repeat(Profile $repeater, $source)
2117 $author = $this->getProfile();
2119 // TRANS: Message used to repeat a notice. RT is the abbreviation of 'retweet'.
2120 // TRANS: %1$s is the repeated user's name, %2$s is the repeated notice.
2121 $content = sprintf(_('RT @%1$s %2$s'),
2122 $author->getNickname(),
2125 $maxlen = self::maxContent();
2126 if ($maxlen > 0 && mb_strlen($content) > $maxlen) {
2127 // Web interface and current Twitter API clients will
2128 // pull the original notice's text, but some older
2129 // clients and RSS/Atom feeds will see this trimmed text.
2131 // Unfortunately this is likely to lose tags or URLs
2132 // at the end of long notices.
2133 $content = mb_substr($content, 0, $maxlen - 4) . ' ...';
2137 // Scope is same as this one's
2138 return self::saveNew($repeater->id,
2141 array('repeat_of' => $this->id,
2142 'scope' => $this->scope));
2145 // These are supposed to be in chron order!
2147 function repeatStream($limit=100)
2149 $cache = Cache::instance();
2151 if (empty($cache)) {
2152 $ids = $this->_repeatStreamDirect($limit);
2154 $idstr = $cache->get(Cache::key('notice:repeats:'.$this->id));
2155 if ($idstr !== false) {
2156 if (empty($idstr)) {
2159 $ids = explode(',', $idstr);
2162 $ids = $this->_repeatStreamDirect(100);
2163 $cache->set(Cache::key('notice:repeats:'.$this->id), implode(',', $ids));
2166 // We do a max of 100, so slice down to limit
2167 $ids = array_slice($ids, 0, $limit);
2171 return NoticeStream::getStreamByIds($ids);
2174 function _repeatStreamDirect($limit)
2176 $notice = new Notice();
2178 $notice->selectAdd(); // clears it
2179 $notice->selectAdd('id');
2181 $notice->repeat_of = $this->id;
2183 $notice->orderBy('created, id'); // NB: asc!
2185 if (!is_null($limit)) {
2186 $notice->limit(0, $limit);
2189 return $notice->fetchAll('id');
2192 static function locationOptions($lat, $lon, $location_id, $location_ns, $profile = null)
2196 if (!empty($location_id) && !empty($location_ns)) {
2197 $options['location_id'] = $location_id;
2198 $options['location_ns'] = $location_ns;
2200 $location = Location::fromId($location_id, $location_ns);
2202 if ($location instanceof Location) {
2203 $options['lat'] = $location->lat;
2204 $options['lon'] = $location->lon;
2207 } else if (!empty($lat) && !empty($lon)) {
2208 $options['lat'] = $lat;
2209 $options['lon'] = $lon;
2211 $location = Location::fromLatLon($lat, $lon);
2213 if ($location instanceof Location) {
2214 $options['location_id'] = $location->location_id;
2215 $options['location_ns'] = $location->location_ns;
2217 } else if (!empty($profile)) {
2218 if (isset($profile->lat) && isset($profile->lon)) {
2219 $options['lat'] = $profile->lat;
2220 $options['lon'] = $profile->lon;
2223 if (isset($profile->location_id) && isset($profile->location_ns)) {
2224 $options['location_id'] = $profile->location_id;
2225 $options['location_ns'] = $profile->location_ns;
2232 function clearAttentions()
2234 $att = new Attention();
2235 $att->notice_id = $this->getID();
2238 while ($att->fetch()) {
2239 // Can't do delete() on the object directly since it won't remove all of it
2240 $other = clone($att);
2246 function clearReplies()
2248 $replyNotice = new Notice();
2249 $replyNotice->reply_to = $this->id;
2251 //Null any notices that are replies to this notice
2253 if ($replyNotice->find()) {
2254 while ($replyNotice->fetch()) {
2255 $orig = clone($replyNotice);
2256 $replyNotice->reply_to = null;
2257 $replyNotice->update($orig);
2263 $reply = new Reply();
2264 $reply->notice_id = $this->id;
2266 if ($reply->find()) {
2267 while($reply->fetch()) {
2268 self::blow('reply:stream:%d', $reply->profile_id);
2276 function clearLocation()
2278 $loc = new Notice_location();
2279 $loc->notice_id = $this->id;
2286 function clearFiles()
2288 $f2p = new File_to_post();
2290 $f2p->post_id = $this->id;
2293 while ($f2p->fetch()) {
2297 // FIXME: decide whether to delete File objects
2298 // ...and related (actual) files
2301 function clearRepeats()
2303 $repeatNotice = new Notice();
2304 $repeatNotice->repeat_of = $this->id;
2306 //Null any notices that are repeats of this notice
2308 if ($repeatNotice->find()) {
2309 while ($repeatNotice->fetch()) {
2310 $orig = clone($repeatNotice);
2311 $repeatNotice->repeat_of = null;
2312 $repeatNotice->update($orig);
2317 function clearTags()
2319 $tag = new Notice_tag();
2320 $tag->notice_id = $this->id;
2323 while ($tag->fetch()) {
2324 self::blow('profile:notice_ids_tagged:%d:%s', $this->profile_id, Cache::keyize($tag->tag));
2325 self::blow('profile:notice_ids_tagged:%d:%s;last', $this->profile_id, Cache::keyize($tag->tag));
2326 self::blow('notice_tag:notice_ids:%s', Cache::keyize($tag->tag));
2327 self::blow('notice_tag:notice_ids:%s;last', Cache::keyize($tag->tag));
2335 function clearGroupInboxes()
2337 $gi = new Group_inbox();
2339 $gi->notice_id = $this->id;
2342 while ($gi->fetch()) {
2343 self::blow('user_group:notice_ids:%d', $gi->group_id);
2351 function distribute()
2353 // We always insert for the author so they don't
2355 Event::handle('StartNoticeDistribute', array($this));
2357 // If there's a failure, we want to _force_
2358 // distribution at this point.
2360 $qm = QueueManager::get();
2361 $qm->enqueue($this, 'distrib');
2362 } catch (Exception $e) {
2363 // If the exception isn't transient, this
2364 // may throw more exceptions as DQH does
2365 // its own enqueueing. So, we ignore them!
2367 $handler = new DistribQueueHandler();
2368 $handler->handle($this);
2369 } catch (Exception $e) {
2370 common_log(LOG_ERR, "emergency redistribution resulted in " . $e->getMessage());
2372 // Re-throw so somebody smarter can handle it.
2379 $result = parent::insert();
2381 if ($result === false) {
2382 common_log_db_error($this, 'INSERT', __FILE__);
2383 // TRANS: Server exception thrown when a stored object entry cannot be saved.
2384 throw new ServerException('Could not save Notice');
2387 // Profile::hasRepeated() abuses pkeyGet(), so we
2388 // have to clear manually
2389 if (!empty($this->repeat_of)) {
2390 $c = self::memcache();
2392 $ck = self::multicacheKey('Notice',
2393 array('profile_id' => $this->profile_id,
2394 'repeat_of' => $this->repeat_of));
2399 // Update possibly ID-dependent columns: URI, conversation
2400 // (now that INSERT has added the notice's local id)
2401 $orig = clone($this);
2404 // We can only get here if it's a local notice, since remote notices
2405 // should've bailed out earlier due to lacking a URI.
2406 if (empty($this->uri)) {
2407 $this->uri = sprintf('%s%s=%d:%s=%s',
2409 'noticeId', $this->id,
2410 'objectType', $this->get_object_type(true));
2414 if ($changed && $this->update($orig) === false) {
2415 common_log_db_error($notice, 'UPDATE', __FILE__);
2416 // TRANS: Server exception thrown when a notice cannot be updated.
2417 throw new ServerException(_('Problem saving notice.'));
2420 $this->blowOnInsert();
2426 * Get the source of the notice
2428 * @return Notice_source $ns A notice source object. 'code' is the only attribute
2429 * guaranteed to be populated.
2431 function getSource()
2433 if (empty($this->source)) {
2437 $ns = new Notice_source();
2438 switch ($this->source) {
2445 $ns->code = $this->source;
2448 $ns = Notice_source::getKV($this->source);
2450 $ns = new Notice_source();
2451 $ns->code = $this->source;
2452 $app = Oauth_application::getKV('name', $this->source);
2454 $ns->name = $app->name;
2455 $ns->url = $app->source_url;
2465 * Determine whether the notice was locally created
2467 * @return boolean locality
2470 public function isLocal()
2472 return ($this->is_local == Notice::LOCAL_PUBLIC ||
2473 $this->is_local == Notice::LOCAL_NONPUBLIC);
2476 public function isRepeat()
2478 return !empty($this->repeat_of);
2482 * Get the list of hash tags saved with this notice.
2484 * @return array of strings
2486 public function getTags()
2490 $keypart = sprintf('notice:tags:%d', $this->id);
2492 $tagstr = self::cacheGet($keypart);
2494 if ($tagstr !== false) {
2495 $tags = explode(',', $tagstr);
2497 $tag = new Notice_tag();
2498 $tag->notice_id = $this->id;
2500 while ($tag->fetch()) {
2501 $tags[] = $tag->tag;
2504 self::cacheSet($keypart, implode(',', $tags));
2510 static private function utcDate($dt)
2512 $dateStr = date('d F Y H:i:s', strtotime($dt));
2513 $d = new DateTime($dateStr, new DateTimeZone('UTC'));
2514 return $d->format(DATE_W3C);
2518 * Look up the creation timestamp for a given notice ID, even
2519 * if it's been deleted.
2522 * @return mixed string recorded creation timestamp, or false if can't be found
2524 public static function getAsTimestamp($id)
2530 $notice = Notice::getKV('id', $id);
2532 return $notice->created;
2535 $deleted = Deleted_notice::getKV('id', $id);
2537 return $deleted->created;
2544 * Build an SQL 'where' fragment for timestamp-based sorting from a since_id
2545 * parameter, matching notices posted after the given one (exclusive).
2547 * If the referenced notice can't be found, will return false.
2550 * @param string $idField
2551 * @param string $createdField
2552 * @return mixed string or false if no match
2554 public static function whereSinceId($id, $idField='id', $createdField='created')
2556 $since = Notice::getAsTimestamp($id);
2558 return sprintf("($createdField = '%s' and $idField > %d) or ($createdField > '%s')", $since, $id, $since);
2564 * Build an SQL 'where' fragment for timestamp-based sorting from a since_id
2565 * parameter, matching notices posted after the given one (exclusive), and
2566 * if necessary add it to the data object's query.
2568 * @param DB_DataObject $obj
2570 * @param string $idField
2571 * @param string $createdField
2572 * @return mixed string or false if no match
2574 public static function addWhereSinceId(DB_DataObject $obj, $id, $idField='id', $createdField='created')
2576 $since = self::whereSinceId($id, $idField, $createdField);
2578 $obj->whereAdd($since);
2583 * Build an SQL 'where' fragment for timestamp-based sorting from a max_id
2584 * parameter, matching notices posted before the given one (inclusive).
2586 * If the referenced notice can't be found, will return false.
2589 * @param string $idField
2590 * @param string $createdField
2591 * @return mixed string or false if no match
2593 public static function whereMaxId($id, $idField='id', $createdField='created')
2595 $max = Notice::getAsTimestamp($id);
2597 return sprintf("($createdField < '%s') or ($createdField = '%s' and $idField <= %d)", $max, $max, $id);
2603 * Build an SQL 'where' fragment for timestamp-based sorting from a max_id
2604 * parameter, matching notices posted before the given one (inclusive), and
2605 * if necessary add it to the data object's query.
2607 * @param DB_DataObject $obj
2609 * @param string $idField
2610 * @param string $createdField
2611 * @return mixed string or false if no match
2613 public static function addWhereMaxId(DB_DataObject $obj, $id, $idField='id', $createdField='created')
2615 $max = self::whereMaxId($id, $idField, $createdField);
2617 $obj->whereAdd($max);
2623 return (($this->is_local != Notice::LOCAL_NONPUBLIC) &&
2624 ($this->is_local != Notice::GATEWAY));
2628 * Check that the given profile is allowed to read, respond to, or otherwise
2629 * act on this notice.
2631 * The $scope member is a bitmask of scopes, representing a logical AND of the
2632 * scope requirement. So, 0x03 (Notice::ADDRESSEE_SCOPE | Notice::SITE_SCOPE) means
2633 * "only visible to people who are mentioned in the notice AND are users on this site."
2634 * Users on the site who are not mentioned in the notice will not be able to see the
2637 * @param Profile $profile The profile to check; pass null to check for public/unauthenticated users.
2639 * @return boolean whether the profile is in the notice's scope
2641 function inScope($profile)
2643 if (is_null($profile)) {
2644 $keypart = sprintf('notice:in-scope-for:%d:null', $this->id);
2646 $keypart = sprintf('notice:in-scope-for:%d:%d', $this->id, $profile->id);
2649 $result = self::cacheGet($keypart);
2651 if ($result === false) {
2653 if (Event::handle('StartNoticeInScope', array($this, $profile, &$bResult))) {
2654 $bResult = $this->_inScope($profile);
2655 Event::handle('EndNoticeInScope', array($this, $profile, &$bResult));
2657 $result = ($bResult) ? 1 : 0;
2658 self::cacheSet($keypart, $result, 0, 300);
2661 return ($result == 1) ? true : false;
2664 protected function _inScope($profile)
2666 if (!is_null($this->scope)) {
2667 $scope = $this->scope;
2669 $scope = self::defaultScope();
2672 if ($scope == 0 && !$this->getProfile()->isPrivateStream()) { // Not scoping, so it is public.
2673 return !$this->isHiddenSpam($profile);
2676 // If there's scope, anon cannot be in scope
2677 if (empty($profile)) {
2681 // Author is always in scope
2682 if ($this->profile_id == $profile->id) {
2686 // Only for users on this site
2687 if (($scope & Notice::SITE_SCOPE) && !$profile->isLocal()) {
2691 // Only for users mentioned in the notice
2692 if ($scope & Notice::ADDRESSEE_SCOPE) {
2694 $reply = Reply::pkeyGet(array('notice_id' => $this->id,
2695 'profile_id' => $profile->id));
2697 if (!$reply instanceof Reply) {
2702 // Only for members of the given group
2703 if ($scope & Notice::GROUP_SCOPE) {
2705 // XXX: just query for the single membership
2707 $groups = $this->getGroups();
2711 foreach ($groups as $group) {
2712 if ($profile->isMember($group)) {
2723 if ($scope & Notice::FOLLOWER_SCOPE || $this->getProfile()->isPrivateStream()) {
2725 if (!Subscription::exists($profile, $this->getProfile())) {
2730 return !$this->isHiddenSpam($profile);
2733 function isHiddenSpam($profile) {
2735 // Hide posts by silenced users from everyone but moderators.
2737 if (common_config('notice', 'hidespam')) {
2740 $author = $this->getProfile();
2741 } catch(Exception $e) {
2742 // If we can't get an author, keep it hidden.
2743 // XXX: technically not spam, but, whatever.
2747 if ($author->hasRole(Profile_role::SILENCED)) {
2748 if (!$profile instanceof Profile || (($profile->id !== $author->id) && (!$profile->hasRight(Right::REVIEWSPAM)))) {
2757 public function getParent()
2759 if (empty($this->reply_to)) {
2760 throw new NoParentNoticeException($this);
2762 return self::getByID($this->reply_to);
2766 * Magic function called at serialize() time.
2768 * We use this to drop a couple process-specific references
2769 * from DB_DataObject which can cause trouble in future
2772 * @return array of variable names to include in serialization.
2777 $vars = parent::__sleep();
2778 $skip = array('_profile', '_groups', '_attachments', '_faves', '_replies', '_repeats');
2779 return array_diff($vars, $skip);
2782 static function defaultScope()
2784 $scope = common_config('notice', 'defaultscope');
2785 if (is_null($scope)) {
2786 if (common_config('site', 'private')) {
2795 static function fillProfiles($notices)
2797 $map = self::getProfiles($notices);
2798 foreach ($notices as $entry=>$notice) {
2800 if (array_key_exists($notice->profile_id, $map)) {
2801 $notice->_setProfile($map[$notice->profile_id]);
2803 } catch (NoProfileException $e) {
2804 common_log(LOG_WARNING, "Failed to fill profile in Notice with non-existing entry for profile_id: {$e->profile_id}");
2805 unset($notices[$entry]);
2809 return array_values($map);
2812 static function getProfiles(&$notices)
2815 foreach ($notices as $notice) {
2816 $ids[] = $notice->profile_id;
2818 $ids = array_unique($ids);
2819 return Profile::pivotGet('id', $ids);
2822 static function fillGroups(&$notices)
2824 $ids = self::_idsOf($notices);
2825 $gis = Group_inbox::listGet('notice_id', $ids);
2828 foreach ($gis as $id => $gi) {
2831 $gids[] = $g->group_id;
2835 $gids = array_unique($gids);
2836 $group = User_group::pivotGet('id', $gids);
2837 foreach ($notices as $notice)
2840 $gi = $gis[$notice->id];
2841 foreach ($gi as $g) {
2842 $grps[] = $group[$g->group_id];
2844 $notice->_setGroups($grps);
2848 static function _idsOf(array &$notices)
2851 foreach ($notices as $notice) {
2852 $ids[$notice->id] = true;
2854 return array_keys($ids);
2857 static function fillAttachments(&$notices)
2859 $ids = self::_idsOf($notices);
2860 $f2pMap = File_to_post::listGet('post_id', $ids);
2862 foreach ($f2pMap as $noticeId => $f2ps) {
2863 foreach ($f2ps as $f2p) {
2864 $fileIds[] = $f2p->file_id;
2868 $fileIds = array_unique($fileIds);
2869 $fileMap = File::pivotGet('id', $fileIds);
2870 foreach ($notices as $notice)
2873 $f2ps = $f2pMap[$notice->id];
2874 foreach ($f2ps as $f2p) {
2875 $files[] = $fileMap[$f2p->file_id];
2877 $notice->_setAttachments($files);
2881 static function fillReplies(&$notices)
2883 $ids = self::_idsOf($notices);
2884 $replyMap = Reply::listGet('notice_id', $ids);
2885 foreach ($notices as $notice) {
2886 $replies = $replyMap[$notice->id];
2888 foreach ($replies as $reply) {
2889 $ids[] = $reply->profile_id;
2891 $notice->_setReplies($ids);
2895 static public function beforeSchemaUpdate()
2897 $table = strtolower(get_called_class());
2898 $schema = Schema::get();
2899 $schemadef = $schema->getTableDef($table);
2901 // 2015-09-04 We move Notice location data to Notice_location
2902 // First we see if we have to do this at all
2903 if (!isset($schemadef['fields']['lat'])
2904 && !isset($schemadef['fields']['lon'])
2905 && !isset($schemadef['fields']['location_id'])
2906 && !isset($schemadef['fields']['location_ns'])) {
2907 // We have already removed the location fields, so no need to migrate.
2910 // Then we make sure the Notice_location table is created!
2911 $schema->ensureTable('notice_location', Notice_location::schemaDef());
2913 // Then we continue on our road to migration!
2914 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)";
2916 $notice = new Notice();
2917 $notice->query(sprintf('SELECT id, lat, lon, location_id, location_ns FROM %1$s ' .
2918 'WHERE lat IS NOT NULL ' .
2919 'OR lon IS NOT NULL ' .
2920 'OR location_id IS NOT NULL ' .
2921 'OR location_ns IS NOT NULL',
2922 $schema->quoteIdentifier($table)));
2923 print "\nFound {$notice->N} notices with location data, inserting";
2924 while ($notice->fetch()) {
2925 $notloc = Notice_location::getKV('notice_id', $notice->id);
2926 if ($notloc instanceof Notice_location) {
2930 $notloc = new Notice_location();
2931 $notloc->notice_id = $notice->id;
2932 $notloc->lat= $notice->lat;
2933 $notloc->lon= $notice->lon;
2934 $notloc->location_id= $notice->location_id;
2935 $notloc->location_ns= $notice->location_ns;