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 public function delete($useWhere=false)
171 if (Event::handle('NoticeDeleteRelated', array($this))) {
173 // Clear related records
175 $this->clearReplies();
176 $this->clearLocation();
177 $this->clearRepeats();
179 $this->clearGroupInboxes();
181 $this->clearAttentions();
183 // NOTE: we don't clear queue items
186 $result = parent::delete($useWhere);
188 $this->blowOnDelete();
192 public function getUri()
198 * Get a Notice object by URI. Will call external plugins for help
199 * using the event StartGetNoticeFromURI.
201 * @param string $uri A unique identifier for a resource (notice in this case)
203 static function fromUri($uri)
207 if (Event::handle('StartGetNoticeFromUri', array($uri, &$notice))) {
208 $notice = Notice::getKV('uri', $uri);
209 Event::handle('EndGetNoticeFromUri', array($uri, $notice));
212 if (!$notice instanceof Notice) {
213 throw new UnknownUriException($uri);
220 * @param $root boolean If true, link to just the conversation root.
222 * @return URL to conversation
224 public function getConversationUrl($anchor=true)
226 return Conversation::getUrlFromNotice($this, $anchor);
230 * Get the local representation URL of this notice.
232 public function getLocalUrl()
234 return common_local_url('shownotice', array('notice' => $this->id), null, null, false);
237 public function getTitle()
240 if (Event::handle('GetNoticeTitle', array($this, &$title))) {
241 // TRANS: Title of a notice posted without a title value.
242 // TRANS: %1$s is a user name, %2$s is the notice creation date/time.
243 $title = sprintf(_('%1$s\'s status on %2$s'),
244 $this->getProfile()->getFancyName(),
245 common_exact_date($this->created));
250 public function getContent()
252 return $this->content;
256 * Get the original representation URL of this notice.
258 * @param boolean $fallback Whether to fall back to generate a local URL or throw InvalidUrlException
260 public function getUrl($fallback=false)
262 // The risk is we start having empty urls and non-http uris...
263 // and we can't really handle any other protocol right now.
265 case common_valid_http_url($this->url): // should we allow non-http/https URLs?
267 case !$this->isLocal() && common_valid_http_url($this->uri): // Sometimes we only have the URI for remote posts.
269 case $this->isLocal() || $fallback:
270 // let's generate a valid link to our locally available notice on demand
271 return common_local_url('shownotice', array('notice' => $this->id), null, null, false);
273 common_debug('No URL available for notice: id='.$this->id);
274 throw new InvalidUrlException($this->url);
278 public function get_object_type($canonical=false) {
280 ? ActivityObject::canonicalType($this->object_type)
281 : $this->object_type;
284 public static function getByUri($uri)
286 $notice = new Notice();
288 if (!$notice->find(true)) {
289 throw new NoResultException($notice);
295 * Extract #hashtags from this notice's content and save them to the database.
299 /* extract all #hastags */
300 $count = preg_match_all('/(?:^|\s)#([\pL\pN_\-\.]{1,64})/u', strtolower($this->content), $match);
305 /* Add them to the database */
306 return $this->saveKnownTags($match[1]);
310 * Record the given set of hash tags in the db for this notice.
311 * Given tag strings will be normalized and checked for dupes.
313 function saveKnownTags($hashtags)
315 //turn each into their canonical tag
316 //this is needed to remove dupes before saving e.g. #hash.tag = #hashtag
317 for($i=0; $i<count($hashtags); $i++) {
318 /* elide characters we don't want in the tag */
319 $hashtags[$i] = common_canonical_tag($hashtags[$i]);
322 foreach(array_unique($hashtags) as $hashtag) {
323 $this->saveTag($hashtag);
324 self::blow('profile:notice_ids_tagged:%d:%s', $this->profile_id, $hashtag);
330 * Record a single hash tag as associated with this notice.
331 * Tag format and uniqueness must be validated by caller.
333 function saveTag($hashtag)
335 $tag = new Notice_tag();
336 $tag->notice_id = $this->id;
337 $tag->tag = $hashtag;
338 $tag->created = $this->created;
339 $id = $tag->insert();
342 // TRANS: Server exception. %s are the error details.
343 throw new ServerException(sprintf(_('Database error inserting hashtag: %s.'),
344 $last_error->message));
348 // if it's saved, blow its cache
349 $tag->blowCache(false);
353 * Save a new notice and push it out to subscribers' inboxes.
354 * Poster's permissions are checked before sending.
356 * @param int $profile_id Profile ID of the poster
357 * @param string $content source message text; links may be shortened
358 * per current user's preference
359 * @param string $source source key ('web', 'api', etc)
360 * @param array $options Associative array of optional properties:
361 * string 'created' timestamp of notice; defaults to now
362 * int 'is_local' source/gateway ID, one of:
363 * Notice::LOCAL_PUBLIC - Local, ok to appear in public timeline
364 * Notice::REMOTE - Sent from a remote service;
365 * hide from public timeline but show in
366 * local "and friends" timelines
367 * Notice::LOCAL_NONPUBLIC - Local, but hide from public timeline
368 * Notice::GATEWAY - From another non-OStatus service;
369 * will not appear in public views
370 * float 'lat' decimal latitude for geolocation
371 * float 'lon' decimal longitude for geolocation
372 * int 'location_id' geoname identifier
373 * int 'location_ns' geoname namespace to interpret location_id
374 * int 'reply_to'; notice ID this is a reply to
375 * int 'repeat_of'; notice ID this is a repeat of
376 * string 'uri' unique ID for notice; a unique tag uri (can be url or anything too)
377 * string 'url' permalink to notice; defaults to local notice URL
378 * string 'rendered' rendered HTML version of content
379 * array 'replies' list of profile URIs for reply delivery in
380 * place of extracting @-replies from content.
381 * array 'groups' list of group IDs to deliver to, in place of
382 * extracting ! tags from content
383 * array 'tags' list of hashtag strings to save with the notice
384 * in place of extracting # tags from content
385 * array 'urls' list of attached/referred URLs to save with the
386 * notice in place of extracting links from content
387 * boolean 'distribute' whether to distribute the notice, default true
388 * string 'object_type' URL of the associated object type (default ActivityObject::NOTE)
389 * string 'verb' URL of the associated verb (default ActivityVerb::POST)
390 * int 'scope' Scope bitmask; default to SITE_SCOPE on private sites, 0 otherwise
392 * @fixme tag override
395 * @throws ClientException
397 static function saveNew($profile_id, $content, $source, array $options=null) {
398 $defaults = array('uri' => null,
400 'conversation' => null, // URI of conversation
401 'reply_to' => null, // This will override convo URI if the parent is known
402 'repeat_of' => null, // This will override convo URI if the repeated notice is known
404 'distribute' => true,
405 'object_type' => null,
408 if (!empty($options) && is_array($options)) {
409 $options = array_merge($defaults, $options);
415 if (!isset($is_local)) {
416 $is_local = Notice::LOCAL_PUBLIC;
419 $profile = Profile::getKV('id', $profile_id);
420 if (!$profile instanceof Profile) {
421 // TRANS: Client exception thrown when trying to save a notice for an unknown user.
422 throw new ClientException(_('Problem saving notice. Unknown user.'));
425 $user = User::getKV('id', $profile_id);
426 if ($user instanceof User) {
427 // Use the local user's shortening preferences, if applicable.
428 $final = $user->shortenLinks($content);
430 $final = common_shorten_links($content);
433 if (Notice::contentTooLong($final)) {
434 // TRANS: Client exception thrown if a notice contains too many characters.
435 throw new ClientException(_('Problem saving notice. Too long.'));
438 if (common_config('throttle', 'enabled') && !Notice::checkEditThrottle($profile_id)) {
439 common_log(LOG_WARNING, 'Excessive posting by profile #' . $profile_id . '; throttled.');
440 // TRANS: Client exception thrown when a user tries to post too many notices in a given time frame.
441 throw new ClientException(_('Too many notices too fast; take a breather '.
442 'and post again in a few minutes.'));
445 if (common_config('site', 'dupelimit') > 0 && !Notice::checkDupes($profile_id, $final)) {
446 common_log(LOG_WARNING, 'Dupe posting by profile #' . $profile_id . '; throttled.');
447 // TRANS: Client exception thrown when a user tries to post too many duplicate notices in a given time frame.
448 throw new ClientException(_('Too many duplicate messages too quickly;'.
449 ' take a breather and post again in a few minutes.'));
452 if (!$profile->hasRight(Right::NEWNOTICE)) {
453 common_log(LOG_WARNING, "Attempted post from user disallowed to post: " . $profile->nickname);
455 // TRANS: Client exception thrown when a user tries to post while being banned.
456 throw new ClientException(_('You are banned from posting notices on this site.'), 403);
459 $notice = new Notice();
460 $notice->profile_id = $profile_id;
462 $autosource = common_config('public', 'autosource');
464 // Sandboxed are non-false, but not 1, either
466 if (!$profile->hasRight(Right::PUBLICNOTICE) ||
467 ($source && $autosource && in_array($source, $autosource))) {
468 $notice->is_local = Notice::LOCAL_NONPUBLIC;
470 $notice->is_local = $is_local;
473 if (!empty($created)) {
474 $notice->created = $created;
476 $notice->created = common_sql_now();
479 if (!$notice->isLocal()) {
480 // Only do these checks for non-local notices. Local notices will generate these values later.
481 if (!common_valid_http_url($url)) {
482 common_debug('Bad notice URL: ['.$url.'], URI: ['.$uri.']. Cannot link back to original! This is normal for shared notices etc.');
485 throw new ServerException('No URI for remote notice. Cannot accept that.');
489 $notice->content = $final;
491 $notice->source = $source;
495 // Get the groups here so we can figure out replies and such
496 if (!isset($groups)) {
497 $groups = User_group::idsFromText($notice->content, $profile);
502 // Handle repeat case
504 if (!empty($options['repeat_of'])) {
506 // Check for a private one
508 $repeat = Notice::getByID($options['repeat_of']);
510 if ($profile->sameAs($repeat->getProfile())) {
511 // TRANS: Client error displayed when trying to repeat an own notice.
512 throw new ClientException(_('You cannot repeat your own notice.'));
515 if ($repeat->scope != Notice::SITE_SCOPE &&
516 $repeat->scope != Notice::PUBLIC_SCOPE) {
517 // TRANS: Client error displayed when trying to repeat a non-public notice.
518 throw new ClientException(_('Cannot repeat a private notice.'), 403);
521 if (!$repeat->inScope($profile)) {
522 // The generic checks above should cover this, but let's be sure!
523 // TRANS: Client error displayed when trying to repeat a notice you cannot access.
524 throw new ClientException(_('Cannot repeat a notice you cannot read.'), 403);
527 if ($profile->hasRepeated($repeat)) {
528 // TRANS: Client error displayed when trying to repeat an already repeated notice.
529 throw new ClientException(_('You already repeated that notice.'));
532 $notice->repeat_of = $repeat->id;
533 $notice->conversation = $repeat->conversation;
537 // If $reply_to is specified, we check that it exists, and then
538 // return it if it does
539 if (!empty($reply_to)) {
540 $reply = Notice::getKV('id', $reply_to);
541 } elseif (in_array($source, array('xmpp', 'mail', 'sms'))) {
542 // If the source lacks capability of sending the "reply_to"
543 // metadata, let's try to find an inline replyto-reference.
544 $reply = self::getInlineReplyTo($profile, $final);
547 if ($reply instanceof Notice) {
548 if (!$reply->inScope($profile)) {
549 // TRANS: Client error displayed when trying to reply to a notice a the target has no access to.
550 // TRANS: %1$s is a user nickname, %2$d is a notice ID (number).
551 throw new ClientException(sprintf(_('%1$s has no access to notice %2$d.'),
552 $profile->nickname, $reply->id), 403);
555 // If it's a repeat, the reply_to should be to the original
556 if ($reply->isRepeat()) {
557 $notice->reply_to = $reply->repeat_of;
559 $notice->reply_to = $reply->id;
561 // But the conversation ought to be the same :)
562 $notice->conversation = $reply->conversation;
564 // If the original is private to a group, and notice has
565 // no group specified, make it to the same group(s)
567 if (empty($groups) && ($reply->scope & Notice::GROUP_SCOPE)) {
569 $replyGroups = $reply->getGroups();
570 foreach ($replyGroups as $group) {
571 if ($profile->isMember($group)) {
572 $groups[] = $group->id;
580 // If we don't know the reply, we might know the conversation!
581 // This will happen if a known remote user replies to an
582 // unknown remote user - within a known conversation.
583 if (empty($notice->conversation) and !empty($options['conversation'])) {
584 $conv = Conversation::getKV('uri', $options['conversation']);
585 if ($conv instanceof Conversation) {
586 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.').');
587 $notice->conversation = $conv->id;
589 // Conversation URI was not found, so we must create it. But we can't create it
590 // until we have a Notice ID because of the database layout...
591 // $options['conversation'] will be used later after the $notice->insert();
592 common_debug('Conversation URI not found, so we have to create it after inserting this Notice: '.$options['conversation']);
595 // If we're not using the attached conversation URI let's remove it
596 // so we don't mistake ourselves later, when creating our own Conversation.
597 // This implies that the notice knows which conversation it belongs to.
598 $options['conversation'] = null;
602 $notloc = new Notice_location();
603 if (!empty($lat) && !empty($lon)) {
608 if (!empty($location_ns) && !empty($location_id)) {
609 $notloc->location_id = $location_id;
610 $notloc->location_ns = $location_ns;
613 if (!empty($rendered)) {
614 $notice->rendered = $rendered;
616 $notice->rendered = common_render_content($final, $notice);
620 if ($notice->isRepeat()) {
621 $notice->verb = ActivityVerb::SHARE;
622 $notice->object_type = ActivityObject::ACTIVITY;
624 $notice->verb = ActivityVerb::POST;
627 $notice->verb = $verb;
630 if (empty($object_type)) {
631 $notice->object_type = (empty($notice->reply_to)) ? ActivityObject::NOTE : ActivityObject::COMMENT;
633 $notice->object_type = $object_type;
636 if (is_null($scope) && $reply instanceof Notice) {
637 $notice->scope = $reply->scope;
639 $notice->scope = $scope;
642 $notice->scope = self::figureOutScope($profile, $groups, $notice->scope);
644 if (Event::handle('StartNoticeSave', array(&$notice))) {
646 // XXX: some of these functions write to the DB
649 $notice->insert(); // throws exception on failure, if successful we have an ->id
651 if (($notloc->lat && $notloc->lon) || ($notloc->location_id && $notloc->location_ns)) {
652 $notloc->notice_id = $notice->getID();
653 $notloc->insert(); // store the notice location if it had any information
656 // If it's not part of a conversation, it's
657 // the beginning of a new conversation.
658 if (empty($notice->conversation)) {
659 $orig = clone($notice);
660 // $act->context->conversation will be null if it was not provided
662 $conv = Conversation::create($notice, $options['conversation']);
663 $notice->conversation = $conv->id;
664 $notice->update($orig);
666 } catch (Exception $e) {
667 // Let's test if we managed initial insert, which would imply
668 // failing on some update-part (check 'insert()'). Delete if
669 // something had been stored to the database.
670 if (!empty($notice->id)) {
677 // Clear the cache for subscribed users, so they'll update at next request
678 // XXX: someone clever could prepend instead of clearing the cache
680 // Save per-notice metadata...
682 if (isset($replies)) {
683 $notice->saveKnownReplies($replies);
685 $notice->saveReplies();
689 $notice->saveKnownTags($tags);
694 // Note: groups may save tags, so must be run after tags are saved
695 // to avoid errors on duplicates.
696 // Note: groups should always be set.
698 $notice->saveKnownGroups($groups);
701 $notice->saveKnownUrls($urls);
707 // Prepare inbox delivery, may be queued to background.
708 $notice->distribute();
714 static function saveActivity(Activity $act, Profile $actor, array $options=array())
716 // First check if we're going to let this Activity through from the specific actor
717 if (!$actor->hasRight(Right::NEWNOTICE)) {
718 common_log(LOG_WARNING, "Attempted post from user disallowed to post: " . $actor->getNickname());
720 // TRANS: Client exception thrown when a user tries to post while being banned.
721 throw new ClientException(_m('You are banned from posting notices on this site.'), 403);
723 if (common_config('throttle', 'enabled') && !self::checkEditThrottle($actor->id)) {
724 common_log(LOG_WARNING, 'Excessive posting by profile #' . $actor->id . '; throttled.');
725 // TRANS: Client exception thrown when a user tries to post too many notices in a given time frame.
726 throw new ClientException(_m('Too many notices too fast; take a breather '.
727 'and post again in a few minutes.'));
730 // Get ActivityObject properties
731 if (!empty($act->id)) {
733 $options['uri'] = $act->id;
734 $options['url'] = $act->link;
736 $actobj = count($act->objects)==1 ? $act->objects[0] : null;
737 if (!is_null($actobj) && !empty($actobj->id)) {
738 $options['uri'] = $actobj->id;
740 $options['url'] = $actobj->link;
741 } elseif (preg_match('!^https?://!', $actobj->id)) {
742 $options['url'] = $actobj->id;
749 'is_local' => self::LOCAL_PUBLIC,
750 'mentions' => array(),
754 'source' => 'unknown',
759 'distribute' => true);
761 // options will have default values when nothing has been supplied
762 $options = array_merge($defaults, $options);
763 foreach (array_keys($defaults) as $key) {
764 // Only convert the keynames we specify ourselves from 'defaults' array into variables
765 $$key = $options[$key];
767 extract($options, EXTR_SKIP);
769 $stored = new Notice();
772 if ($stored->find()) {
773 common_debug('cannot create duplicate Notice URI: '.$stored->uri);
774 throw new Exception('Notice URI already exists');
778 $stored->profile_id = $actor->id;
779 $stored->source = $source;
782 $stored->verb = $act->verb;
784 // Use the local user's shortening preferences, if applicable.
785 $stored->rendered = $actor->isLocal()
786 ? $actor->shortenLinks($act->content)
788 $stored->content = common_strip_html($stored->rendered);
790 $autosource = common_config('public', 'autosource');
792 // Sandboxed are non-false, but not 1, either
793 if (!$actor->hasRight(Right::PUBLICNOTICE) ||
794 ($source && $autosource && in_array($source, $autosource))) {
795 $stored->is_local = Notice::LOCAL_NONPUBLIC;
798 // Maybe a missing act-time should be fatal if the actor is not local?
799 if (!empty($act->time)) {
800 $stored->created = common_sql_date($act->time);
802 $stored->created = common_sql_now();
806 if ($act->context instanceof ActivityContext && !empty($act->context->replyToID)) {
807 $reply = self::getKV('uri', $act->context->replyToID);
809 if (!$reply instanceof Notice && $act->target instanceof ActivityObject) {
810 $reply = self::getKV('uri', $act->target->id);
813 if ($reply instanceof Notice) {
814 if (!$reply->inScope($actor)) {
815 // TRANS: Client error displayed when trying to reply to a notice a the target has no access to.
816 // TRANS: %1$s is a user nickname, %2$d is a notice ID (number).
817 throw new ClientException(sprintf(_m('%1$s has no right to reply to notice %2$d.'), $actor->getNickname(), $reply->id), 403);
820 $stored->reply_to = $reply->id;
821 $stored->conversation = $reply->conversation;
823 // If the original is private to a group, and notice has no group specified,
824 // make it to the same group(s)
825 if (empty($groups) && ($reply->scope & Notice::GROUP_SCOPE)) {
827 $replyGroups = $reply->getGroups();
828 foreach ($replyGroups as $group) {
829 if ($actor->isMember($group)) {
830 $groups[] = $group->id;
835 if (is_null($scope)) {
836 $scope = $reply->scope;
839 // If we don't know the reply, we might know the conversation!
840 // This will happen if a known remote user replies to an
841 // unknown remote user - within a known conversation.
842 if (empty($stored->conversation) and !empty($act->context->conversation)) {
843 $conv = Conversation::getKV('uri', $act->context->conversation);
844 if ($conv instanceof Conversation) {
845 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.').');
846 $stored->conversation = $conv->getID();
848 // Conversation URI was not found, so we must create it. But we can't create it
849 // until we have a Notice ID because of the database layout...
850 // $options['conversation'] will be used later after the $stored->insert();
851 common_debug('Conversation URI from activity context not found, so we have to create it after inserting this Notice: '.$act->context->conversation);
857 if ($act->context instanceof ActivityContext) {
858 if ($act->context->location instanceof Location) {
859 $notloc = Notice_location::fromLocation($act->context->location);
862 $act->context = new ActivityContext();
865 $stored->scope = self::figureOutScope($actor, $groups, $scope);
867 foreach ($act->categories as $cat) {
869 $term = common_canonical_tag($cat->term);
876 foreach ($act->enclosures as $href) {
877 // @todo FIXME: Save these locally or....?
881 if (Event::handle('StartNoticeSave', array(&$stored))) {
882 // XXX: some of these functions write to the DB
885 $stored->insert(); // throws exception on error
887 if ($notloc instanceof Notice_location) {
888 $notloc->notice_id = $stored->getID();
892 $orig = clone($stored); // for updating later in this try clause
895 Event::handle('StoreActivityObject', array($act, $stored, $options, &$object));
896 if (empty($object)) {
897 throw new ServerException('Unsuccessful call to StoreActivityObject '.$stored->uri . ': '.$act->asString());
900 // If it's not part of a conversation, it's the beginning
901 // of a new one (or belongs to a previously unknown URI).
902 if (empty($stored->conversation)) {
903 // $act->context->conversation will be null if it was not provided
904 common_debug('Creating a new conversation for stored notice ID='.$stored->getID().' with URI: '.$act->context->conversation);
905 $conv = Conversation::create($stored, $act->context->conversation);
906 $stored->conversation = $conv->getID();
909 $stored->update($orig);
910 } catch (Exception $e) {
911 if (empty($stored->id)) {
912 common_debug('Failed to save stored object entry in database ('.$e->getMessage().')');
914 common_debug('Failed to store activity object in database ('.$e->getMessage().'), deleting notice id '.$stored->id);
920 if (!$stored instanceof Notice) {
921 throw new ServerException('StartNoticeSave did not give back a Notice');
924 // Save per-notice metadata...
928 // This event lets plugins filter out non-local recipients (attentions we don't care about)
929 // Used primarily for OStatus (and if we don't federate, all attentions would be local anyway)
930 Event::handle('GetLocalAttentions', array($actor, $act->context->attention, &$mentions, &$groups));
932 if (!empty($mentions)) {
933 $stored->saveKnownReplies($mentions);
935 $stored->saveReplies();
939 $stored->saveKnownTags($tags);
944 // Note: groups may save tags, so must be run after tags are saved
945 // to avoid errors on duplicates.
946 // Note: groups should always be set.
948 $stored->saveKnownGroups($groups);
951 $stored->saveKnownUrls($urls);
957 // Prepare inbox delivery, may be queued to background.
958 $stored->distribute();
964 static public function figureOutScope(Profile $actor, array $groups, $scope=null) {
965 if (is_null($scope)) {
966 $scope = self::defaultScope();
969 // For private streams
971 $user = $actor->getUser();
972 // FIXME: We can't do bit comparison with == (Legacy StatusNet thing. Let's keep it for now.)
973 if ($user->private_stream && ($scope == Notice::PUBLIC_SCOPE || $scope == Notice::SITE_SCOPE)) {
974 $scope |= Notice::FOLLOWER_SCOPE;
976 } catch (NoSuchUserException $e) {
977 // TODO: Not a local user, so we don't know about scope preferences... yet!
980 // Force the scope for private groups
981 foreach ($groups as $group_id) {
983 $group = User_group::getByID($group_id);
984 if ($group->force_scope) {
985 $scope |= Notice::GROUP_SCOPE;
988 } catch (Exception $e) {
989 common_log(LOG_ERR, 'Notice figureOutScope threw exception: '.$e->getMessage());
996 function blowOnInsert($conversation = false)
998 $this->blowStream('profile:notice_ids:%d', $this->profile_id);
1000 if ($this->isPublic()) {
1001 $this->blowStream('public');
1002 $this->blowStream('networkpublic');
1005 self::blow('notice:list-ids:conversation:%s', $this->conversation);
1006 self::blow('conversation:notice_count:%d', $this->conversation);
1008 if ($this->isRepeat()) {
1009 // XXX: we should probably only use one of these
1010 $this->blowStream('notice:repeats:%d', $this->repeat_of);
1011 self::blow('notice:list-ids:repeat_of:%d', $this->repeat_of);
1014 $original = Notice::getKV('id', $this->repeat_of);
1016 if ($original instanceof Notice) {
1017 $originalUser = User::getKV('id', $original->profile_id);
1018 if ($originalUser instanceof User) {
1019 $this->blowStream('user:repeats_of_me:%d', $originalUser->id);
1023 $profile = Profile::getKV($this->profile_id);
1025 if ($profile instanceof Profile) {
1026 $profile->blowNoticeCount();
1029 $ptags = $this->getProfileTags();
1030 foreach ($ptags as $ptag) {
1031 $ptag->blowNoticeStreamCache();
1036 * Clear cache entries related to this notice at delete time.
1037 * Necessary to avoid breaking paging on public, profile timelines.
1039 function blowOnDelete()
1041 $this->blowOnInsert();
1043 self::blow('profile:notice_ids:%d;last', $this->profile_id);
1045 if ($this->isPublic()) {
1046 self::blow('public;last');
1047 self::blow('networkpublic;last');
1050 self::blow('fave:by_notice', $this->id);
1052 if ($this->conversation) {
1053 // In case we're the first, will need to calc a new root.
1054 self::blow('notice:conversation_root:%d', $this->conversation);
1057 $ptags = $this->getProfileTags();
1058 foreach ($ptags as $ptag) {
1059 $ptag->blowNoticeStreamCache(true);
1063 function blowStream()
1065 $c = self::memcache();
1071 $args = func_get_args();
1072 $format = array_shift($args);
1073 $keyPart = vsprintf($format, $args);
1074 $cacheKey = Cache::key($keyPart);
1075 $c->delete($cacheKey);
1077 // delete the "last" stream, too, if this notice is
1078 // older than the top of that stream
1080 $lastKey = $cacheKey.';last';
1082 $lastStr = $c->get($lastKey);
1084 if ($lastStr !== false) {
1085 $window = explode(',', $lastStr);
1086 $lastID = $window[0];
1087 $lastNotice = Notice::getKV('id', $lastID);
1088 if (!$lastNotice instanceof Notice // just weird
1089 || strtotime($lastNotice->created) >= strtotime($this->created)) {
1090 $c->delete($lastKey);
1095 /** save all urls in the notice to the db
1097 * follow redirects and save all available file information
1098 * (mimetype, date, size, oembed, etc.)
1102 function saveUrls() {
1103 if (common_config('attachments', 'process_links')) {
1104 common_replace_urls_callback($this->content, array($this, 'saveUrl'), $this);
1109 * Save the given URLs as related links/attachments to the db
1111 * follow redirects and save all available file information
1112 * (mimetype, date, size, oembed, etc.)
1116 function saveKnownUrls($urls)
1118 if (common_config('attachments', 'process_links')) {
1119 // @fixme validation?
1120 foreach (array_unique($urls) as $url) {
1121 $this->saveUrl($url, $this);
1129 function saveUrl($url, Notice $notice) {
1131 File::processNew($url, $notice);
1132 } catch (ServerException $e) {
1133 // Could not save URL. Log it?
1137 static function checkDupes($profile_id, $content) {
1138 $profile = Profile::getKV($profile_id);
1139 if (!$profile instanceof Profile) {
1142 $notice = $profile->getNotices(0, CachingNoticeStream::CACHE_WINDOW);
1143 if (!empty($notice)) {
1145 while ($notice->fetch()) {
1146 if (time() - strtotime($notice->created) >= common_config('site', 'dupelimit')) {
1148 } else if ($notice->content == $content) {
1153 // If we get here, oldest item in cache window is not
1154 // old enough for dupe limit; do direct check against DB
1155 $notice = new Notice();
1156 $notice->profile_id = $profile_id;
1157 $notice->content = $content;
1158 $threshold = common_sql_date(time() - common_config('site', 'dupelimit'));
1159 $notice->whereAdd(sprintf("created > '%s'", $notice->escape($threshold)));
1161 $cnt = $notice->count();
1165 static function checkEditThrottle($profile_id) {
1166 $profile = Profile::getKV($profile_id);
1167 if (!$profile instanceof Profile) {
1170 // Get the Nth notice
1171 $notice = $profile->getNotices(common_config('throttle', 'count') - 1, 1);
1172 if ($notice && $notice->fetch()) {
1173 // If the Nth notice was posted less than timespan seconds ago
1174 if (time() - strtotime($notice->created) <= common_config('throttle', 'timespan')) {
1179 // Either not N notices in the stream, OR the Nth was not posted within timespan seconds
1183 protected $_attachments = array();
1185 function attachments() {
1186 if (isset($this->_attachments[$this->id])) {
1187 return $this->_attachments[$this->id];
1190 $f2ps = File_to_post::listGet('post_id', array($this->id));
1192 foreach ($f2ps[$this->id] as $f2p) {
1193 $ids[] = $f2p->file_id;
1196 $files = File::multiGet('id', $ids);
1197 $this->_attachments[$this->id] = $files->fetchAll();
1198 return $this->_attachments[$this->id];
1201 function _setAttachments($attachments)
1203 $this->_attachments[$this->id] = $attachments;
1206 static function publicStream($offset=0, $limit=20, $since_id=null, $max_id=null)
1208 $stream = new PublicNoticeStream();
1209 return $stream->getNotices($offset, $limit, $since_id, $max_id);
1212 static function conversationStream($id, $offset=0, $limit=20, $since_id=null, $max_id=null)
1214 $stream = new ConversationNoticeStream($id);
1215 return $stream->getNotices($offset, $limit, $since_id, $max_id);
1219 * Is this notice part of an active conversation?
1221 * @return boolean true if other messages exist in the same
1222 * conversation, false if this is the only one
1224 function hasConversation()
1226 if (empty($this->conversation)) {
1227 // this notice is not part of a conversation apparently
1228 // FIXME: all notices should have a conversation value, right?
1232 $stream = new ConversationNoticeStream($this->conversation);
1233 $notice = $stream->getNotices(/*offset*/ 1, /*limit*/ 1);
1235 // if our "offset 1, limit 1" query got a result, return true else false
1236 return $notice->N > 0;
1240 * Grab the earliest notice from this conversation.
1242 * @return Notice or null
1244 function conversationRoot($profile=-1)
1246 // XXX: can this happen?
1248 if (empty($this->conversation)) {
1252 // Get the current profile if not specified
1254 if (is_int($profile) && $profile == -1) {
1255 $profile = Profile::current();
1258 // If this notice is out of scope, no root for you!
1260 if (!$this->inScope($profile)) {
1264 // If this isn't a reply to anything, then it's its own
1265 // root if it's the earliest notice in the conversation:
1267 if (empty($this->reply_to)) {
1269 $root->conversation = $this->conversation;
1270 $root->orderBy('notice.created ASC');
1271 $root->find(true); // true means "fetch first result"
1276 if (is_null($profile)) {
1277 $keypart = sprintf('notice:conversation_root:%d:null', $this->id);
1279 $keypart = sprintf('notice:conversation_root:%d:%d',
1284 $root = self::cacheGet($keypart);
1286 if ($root !== false && $root->inScope($profile)) {
1293 $parent = $last->getParent();
1294 if ($parent->inScope($profile)) {
1298 } catch (NoParentNoticeException $e) {
1299 // Latest notice has no parent
1300 } catch (NoResultException $e) {
1301 // Notice was not found, so we can't go further up in the tree.
1302 // FIXME: Maybe we should do this in a more stable way where deleted
1303 // notices won't break conversation chains?
1305 // No parent, or parent out of scope
1310 self::cacheSet($keypart, $root);
1316 * Pull up a full list of local recipients who will be getting
1317 * this notice in their inbox. Results will be cached, so don't
1318 * change the input data wily-nilly!
1320 * @param array $groups optional list of Group objects;
1321 * if left empty, will be loaded from group_inbox records
1322 * @param array $recipient optional list of reply profile ids
1323 * if left empty, will be loaded from reply records
1324 * @return array associating recipient user IDs with an inbox source constant
1326 function whoGets(array $groups=null, array $recipients=null)
1328 $c = self::memcache();
1331 $ni = $c->get(Cache::key('notice:who_gets:'.$this->id));
1332 if ($ni !== false) {
1337 if (is_null($recipients)) {
1338 $recipients = $this->getReplies();
1343 // Give plugins a chance to add folks in at start...
1344 if (Event::handle('StartNoticeWhoGets', array($this, &$ni))) {
1346 $users = $this->getSubscribedUsers();
1347 foreach ($users as $id) {
1348 $ni[$id] = NOTICE_INBOX_SOURCE_SUB;
1351 if (is_null($groups)) {
1352 $groups = $this->getGroups();
1354 foreach ($groups as $group) {
1355 $users = $group->getUserMembers();
1356 foreach ($users as $id) {
1357 if (!array_key_exists($id, $ni)) {
1358 $ni[$id] = NOTICE_INBOX_SOURCE_GROUP;
1363 $ptAtts = $this->getAttentionsFromProfileTags();
1364 foreach ($ptAtts as $key=>$val) {
1365 if (!array_key_exists($key, $ni)) {
1370 foreach ($recipients as $recipient) {
1371 if (!array_key_exists($recipient, $ni)) {
1372 $ni[$recipient] = NOTICE_INBOX_SOURCE_REPLY;
1376 // Exclude any deleted, non-local, or blocking recipients.
1377 $profile = $this->getProfile();
1378 $originalProfile = null;
1379 if ($this->isRepeat()) {
1380 // Check blocks against the original notice's poster as well.
1381 $original = Notice::getKV('id', $this->repeat_of);
1382 if ($original instanceof Notice) {
1383 $originalProfile = $original->getProfile();
1387 foreach ($ni as $id => $source) {
1389 $user = User::getKV('id', $id);
1390 if (!$user instanceof User ||
1391 $user->hasBlocked($profile) ||
1392 ($originalProfile && $user->hasBlocked($originalProfile))) {
1395 } catch (UserNoProfileException $e) {
1396 // User doesn't have a profile; invalid; skip them.
1401 // Give plugins a chance to filter out...
1402 Event::handle('EndNoticeWhoGets', array($this, &$ni));
1406 // XXX: pack this data better
1407 $c->set(Cache::key('notice:who_gets:'.$this->id), $ni);
1413 function getSubscribedUsers()
1417 if(common_config('db','quote_identifiers'))
1418 $user_table = '"user"';
1419 else $user_table = 'user';
1423 'FROM '. $user_table .' JOIN subscription '.
1424 'ON '. $user_table .'.id = subscription.subscriber ' .
1425 'WHERE subscription.subscribed = %d ';
1427 $user->query(sprintf($qry, $this->profile_id));
1431 while ($user->fetch()) {
1440 function getProfileTags()
1442 $profile = $this->getProfile();
1443 $list = $profile->getOtherTags($profile);
1446 while($list->fetch()) {
1447 $ptags[] = clone($list);
1453 public function getAttentionsFromProfileTags()
1456 $ptags = $this->getProfileTags();
1457 foreach ($ptags as $ptag) {
1458 $users = $ptag->getUserSubscribers();
1459 foreach ($users as $id) {
1460 $ni[$id] = NOTICE_INBOX_SOURCE_PROFILE_TAG;
1467 * Record this notice to the given group inboxes for delivery.
1468 * Overrides the regular parsing of !group markup.
1470 * @param string $group_ids
1471 * @fixme might prefer URIs as identifiers, as for replies?
1472 * best with generalizations on user_group to support
1473 * remote groups better.
1475 function saveKnownGroups($group_ids)
1477 if (!is_array($group_ids)) {
1478 // TRANS: Server exception thrown when no array is provided to the method saveKnownGroups().
1479 throw new ServerException(_('Bad type provided to saveKnownGroups.'));
1483 foreach (array_unique($group_ids) as $id) {
1484 $group = User_group::getKV('id', $id);
1485 if ($group instanceof User_group) {
1486 common_log(LOG_DEBUG, "Local delivery to group id $id, $group->nickname");
1487 $result = $this->addToGroupInbox($group);
1489 common_log_db_error($gi, 'INSERT', __FILE__);
1492 if (common_config('group', 'addtag')) {
1493 // we automatically add a tag for every group name, too
1495 $tag = Notice_tag::pkeyGet(array('tag' => common_canonical_tag($group->nickname),
1496 'notice_id' => $this->id));
1498 if (is_null($tag)) {
1499 $this->saveTag($group->nickname);
1503 $groups[] = clone($group);
1505 common_log(LOG_ERR, "Local delivery to group id $id skipped, doesn't exist");
1512 function addToGroupInbox(User_group $group)
1514 $gi = Group_inbox::pkeyGet(array('group_id' => $group->id,
1515 'notice_id' => $this->id));
1517 if (!$gi instanceof Group_inbox) {
1519 $gi = new Group_inbox();
1521 $gi->group_id = $group->id;
1522 $gi->notice_id = $this->id;
1523 $gi->created = $this->created;
1525 $result = $gi->insert();
1528 common_log_db_error($gi, 'INSERT', __FILE__);
1529 // TRANS: Server exception thrown when an update for a group inbox fails.
1530 throw new ServerException(_('Problem saving group inbox.'));
1533 self::blow('user_group:notice_ids:%d', $gi->group_id);
1540 * Save reply records indicating that this notice needs to be
1541 * delivered to the local users with the given URIs.
1543 * Since this is expected to be used when saving foreign-sourced
1544 * messages, we won't deliver to any remote targets as that's the
1545 * source service's responsibility.
1547 * Mail notifications etc will be handled later.
1549 * @param array $uris Array of unique identifier URIs for recipients
1551 function saveKnownReplies(array $uris)
1557 $sender = Profile::getKV($this->profile_id);
1559 foreach (array_unique($uris) as $uri) {
1561 $profile = Profile::fromUri($uri);
1562 } catch (UnknownUriException $e) {
1563 common_log(LOG_WARNING, "Unable to determine profile for URI '$uri'");
1567 if ($profile->hasBlocked($sender)) {
1568 common_log(LOG_INFO, "Not saving reply to profile {$profile->id} ($uri) from sender {$sender->id} because of a block.");
1572 $this->saveReply($profile->id);
1573 self::blow('reply:stream:%d', $profile->id);
1580 * Pull @-replies from this message's content in StatusNet markup format
1581 * and save reply records indicating that this message needs to be
1582 * delivered to those users.
1584 * Mail notifications to local profiles will be sent later.
1586 * @return array of integer profile IDs
1589 function saveReplies()
1591 // Don't save reply data for repeats
1593 if ($this->isRepeat()) {
1597 $sender = $this->getProfile();
1601 // If it's a reply, save for the replied-to author
1603 $parent = $this->getParent();
1604 $parentauthor = $parent->getProfile();
1605 $this->saveReply($parentauthor->id);
1606 $replied[$parentauthor->id] = 1;
1607 self::blow('reply:stream:%d', $parentauthor->id);
1608 } catch (NoParentNoticeException $e) {
1609 // Not a reply, since it has no parent!
1610 } catch (NoResultException $e) {
1611 // Parent notice was probably deleted
1614 // @todo ideally this parser information would only
1615 // be calculated once.
1617 $mentions = common_find_mentions($this->content, $this);
1619 // store replied only for first @ (what user/notice what the reply directed,
1620 // we assume first @ is it)
1622 foreach ($mentions as $mention) {
1624 foreach ($mention['mentioned'] as $mentioned) {
1626 // skip if they're already covered
1627 if (array_key_exists($mentioned->id, $replied)) {
1631 // Don't save replies from blocked profile to local user
1633 $mentioned_user = User::getKV('id', $mentioned->id);
1634 if ($mentioned_user instanceof User && $mentioned_user->hasBlocked($sender)) {
1638 $this->saveReply($mentioned->id);
1639 $replied[$mentioned->id] = 1;
1640 self::blow('reply:stream:%d', $mentioned->id);
1644 $recipientIds = array_keys($replied);
1646 return $recipientIds;
1649 function saveReply($profileId)
1651 $reply = new Reply();
1653 $reply->notice_id = $this->id;
1654 $reply->profile_id = $profileId;
1655 $reply->modified = $this->created;
1662 protected $_replies = array();
1665 * Pull the complete list of @-mentioned profile IDs for this notice.
1667 * @return array of integer profile ids
1669 function getReplies()
1671 if (!isset($this->_replies[$this->getID()])) {
1672 $mentions = Reply::multiGet('notice_id', array($this->getID()));
1673 $this->_replies[$this->getID()] = $mentions->fetchAll('profile_id');
1675 return $this->_replies[$this->getID()];
1678 function _setReplies($replies)
1680 $this->_replies[$this->getID()] = $replies;
1684 * Pull the complete list of @-reply targets for this notice.
1686 * @return array of Profiles
1688 function getReplyProfiles()
1690 $ids = $this->getReplies();
1692 $profiles = Profile::multiGet('id', $ids);
1694 return $profiles->fetchAll();
1698 * Send e-mail notifications to local @-reply targets.
1700 * Replies must already have been saved; this is expected to be run
1701 * from the distrib queue handler.
1703 function sendReplyNotifications()
1705 // Don't send reply notifications for repeats
1707 if ($this->isRepeat()) {
1711 $recipientIds = $this->getReplies();
1712 if (Event::handle('StartNotifyMentioned', array($this, &$recipientIds))) {
1713 require_once INSTALLDIR.'/lib/mail.php';
1715 foreach ($recipientIds as $recipientId) {
1716 $user = User::getKV('id', $recipientId);
1717 if ($user instanceof User) {
1718 mail_notify_attn($user, $this);
1721 Event::handle('EndNotifyMentioned', array($this, $recipientIds));
1726 * Pull list of groups this notice needs to be delivered to,
1727 * as previously recorded by saveKnownGroups().
1729 * @return array of Group objects
1732 protected $_groups = array();
1734 function getGroups()
1736 // Don't save groups for repeats
1738 if (!empty($this->repeat_of)) {
1742 if (isset($this->_groups[$this->id])) {
1743 return $this->_groups[$this->id];
1746 $gis = Group_inbox::listGet('notice_id', array($this->id));
1750 foreach ($gis[$this->id] as $gi) {
1751 $ids[] = $gi->group_id;
1754 $groups = User_group::multiGet('id', $ids);
1755 $this->_groups[$this->id] = $groups->fetchAll();
1756 return $this->_groups[$this->id];
1759 function _setGroups($groups)
1761 $this->_groups[$this->id] = $groups;
1765 * Convert a notice into an activity for export.
1767 * @param Profile $scoped The currently logged in/scoped profile
1769 * @return Activity activity object representing this Notice.
1772 function asActivity(Profile $scoped=null)
1774 $act = self::cacheGet(Cache::codeKey('notice:as-activity:'.$this->id));
1776 if ($act instanceof Activity) {
1779 $act = new Activity();
1781 if (Event::handle('StartNoticeAsActivity', array($this, $act, $scoped))) {
1783 $act->id = $this->uri;
1784 $act->time = strtotime($this->created);
1786 $act->link = $this->getUrl();
1787 } catch (InvalidUrlException $e) {
1788 // The notice is probably a share or similar, which don't
1789 // have a representational URL of their own.
1791 $act->content = common_xml_safe_str($this->rendered);
1793 $profile = $this->getProfile();
1795 $act->actor = $profile->asActivityObject();
1796 $act->actor->extra[] = $profile->profileInfo($scoped);
1798 $act->verb = $this->verb;
1800 if (!$this->repeat_of) {
1801 $act->objects[] = $this->asActivityObject();
1804 // XXX: should this be handled by default processing for object entry?
1808 $tags = $this->getTags();
1810 foreach ($tags as $tag) {
1811 $cat = new AtomCategory();
1814 $act->categories[] = $cat;
1818 // XXX: use Atom Media and/or File activity objects instead
1820 $attachments = $this->attachments();
1822 foreach ($attachments as $attachment) {
1823 // Include local attachments in Activity
1824 if (!empty($attachment->filename)) {
1825 $act->enclosures[] = $attachment->getEnclosure();
1829 $ctx = new ActivityContext();
1832 $reply = $this->getParent();
1833 $ctx->replyToID = $reply->getUri();
1834 $ctx->replyToUrl = $reply->getUrl(true); // true for fallback to local URL, less messy
1835 } catch (NoParentNoticeException $e) {
1836 // This is not a reply to something
1837 } catch (NoResultException $e) {
1838 // Parent notice was probably deleted
1842 $ctx->location = Notice_location::locFromStored($this);
1843 } catch (ServerException $e) {
1844 $ctx->location = null;
1849 if (!empty($this->conversation)) {
1850 $conv = Conversation::getKV('id', $this->conversation);
1851 if ($conv instanceof Conversation) {
1852 $ctx->conversation = $conv->uri;
1856 $reply_ids = $this->getReplies();
1858 foreach ($reply_ids as $id) {
1859 $rprofile = Profile::getKV('id', $id);
1860 if ($rprofile instanceof Profile) {
1861 $ctx->attention[$rprofile->getUri()] = ActivityObject::PERSON;
1865 $groups = $this->getGroups();
1867 foreach ($groups as $group) {
1868 $ctx->attention[$group->getUri()] = ActivityObject::GROUP;
1871 switch ($this->scope) {
1872 case Notice::PUBLIC_SCOPE:
1873 $ctx->attention[ActivityContext::ATTN_PUBLIC] = ActivityObject::COLLECTION;
1875 case Notice::FOLLOWER_SCOPE:
1876 $surl = common_local_url("subscribers", array('nickname' => $profile->nickname));
1877 $ctx->attention[$surl] = ActivityObject::COLLECTION;
1881 $act->context = $ctx;
1883 $source = $this->getSource();
1885 if ($source instanceof Notice_source) {
1886 $act->generator = ActivityObject::fromNoticeSource($source);
1891 $atom_feed = $profile->getAtomFeed();
1893 if (!empty($atom_feed)) {
1895 $act->source = new ActivitySource();
1897 // XXX: we should store the actual feed ID
1899 $act->source->id = $atom_feed;
1901 // XXX: we should store the actual feed title
1903 $act->source->title = $profile->getBestName();
1905 $act->source->links['alternate'] = $profile->profileurl;
1906 $act->source->links['self'] = $atom_feed;
1908 $act->source->icon = $profile->avatarUrl(AVATAR_PROFILE_SIZE);
1910 $notice = $profile->getCurrentNotice();
1912 if ($notice instanceof Notice) {
1913 $act->source->updated = self::utcDate($notice->created);
1916 $user = User::getKV('id', $profile->id);
1918 if ($user instanceof User) {
1919 $act->source->links['license'] = common_config('license', 'url');
1923 if ($this->isLocal()) {
1924 $act->selfLink = common_local_url('ApiStatusesShow', array('id' => $this->id,
1925 'format' => 'atom'));
1926 $act->editLink = $act->selfLink;
1929 Event::handle('EndNoticeAsActivity', array($this, $act, $scoped));
1932 self::cacheSet(Cache::codeKey('notice:as-activity:'.$this->id), $act);
1937 // This has gotten way too long. Needs to be sliced up into functional bits
1938 // or ideally exported to a utility class.
1940 function asAtomEntry($namespace=false,
1943 Profile $scoped=null)
1945 $act = $this->asActivity($scoped);
1946 $act->extra[] = $this->noticeInfo($scoped);
1947 return $act->asString($namespace, $author, $source);
1951 * Extra notice info for atom entries
1953 * Clients use some extra notice info in the atom stream.
1954 * This gives it to them.
1956 * @param Profile $scoped The currently logged in/scoped profile
1958 * @return array representation of <statusnet:notice_info> element
1961 function noticeInfo(Profile $scoped=null)
1963 // local notice ID (useful to clients for ordering)
1965 $noticeInfoAttr = array('local_id' => $this->id);
1969 $ns = $this->getSource();
1971 if ($ns instanceof Notice_source) {
1972 $noticeInfoAttr['source'] = $ns->code;
1973 if (!empty($ns->url)) {
1974 $noticeInfoAttr['source_link'] = $ns->url;
1975 if (!empty($ns->name)) {
1976 $noticeInfoAttr['source'] = '<a href="'
1977 . htmlspecialchars($ns->url)
1978 . '" rel="nofollow">'
1979 . htmlspecialchars($ns->name)
1985 // favorite and repeated
1987 if ($scoped instanceof Profile) {
1988 $noticeInfoAttr['repeated'] = ($scoped->hasRepeated($this)) ? "true" : "false";
1991 if (!empty($this->repeat_of)) {
1992 $noticeInfoAttr['repeat_of'] = $this->repeat_of;
1995 Event::handle('StatusNetApiNoticeInfo', array($this, &$noticeInfoAttr, $scoped));
1997 return array('statusnet:notice_info', $noticeInfoAttr, null);
2001 * Returns an XML string fragment with a reference to a notice as an
2002 * Activity Streams noun object with the given element type.
2004 * Assumes that 'activity' namespace has been previously defined.
2006 * @param string $element one of 'subject', 'object', 'target'
2010 function asActivityNoun($element)
2012 $noun = $this->asActivityObject();
2013 return $noun->asString('activity:' . $element);
2016 public function asActivityObject()
2018 $object = new ActivityObject();
2020 if (Event::handle('StartActivityObjectFromNotice', array($this, &$object))) {
2021 $object->type = $this->object_type ?: ActivityObject::NOTE;
2022 $object->id = $this->getUri();
2023 $object->title = sprintf('New %1$s by %2$s', ActivityObject::canonicalType($object->type), $this->getProfile()->getNickname());
2024 $object->content = $this->rendered;
2025 $object->link = $this->getUrl();
2027 $object->extra[] = array('status_net', array('notice_id' => $this->id));
2029 Event::handle('EndActivityObjectFromNotice', array($this, &$object));
2036 * Determine which notice, if any, a new notice is in reply to.
2038 * For conversation tracking, we try to see where this notice fits
2039 * in the tree. Beware that this may very well give false positives
2040 * and add replies to wrong threads (if there have been newer posts
2041 * by the same user as we're replying to).
2043 * @param Profile $sender Author profile
2044 * @param string $content Final notice content
2046 * @return integer ID of replied-to notice, or null for not a reply.
2049 static function getInlineReplyTo(Profile $sender, $content)
2051 // Is there an initial @ or T?
2052 if (preg_match('/^T ([A-Z0-9]{1,64}) /', $content, $match)
2053 || preg_match('/^@([a-z0-9]{1,64})\s+/', $content, $match)) {
2054 $nickname = common_canonical_nickname($match[1]);
2059 // Figure out who that is.
2060 $recipient = common_relative_profile($sender, $nickname, common_sql_now());
2062 if ($recipient instanceof Profile) {
2063 // Get their last notice
2064 $last = $recipient->getCurrentNotice();
2065 if ($last instanceof Notice) {
2068 // Maybe in the future we want to handle something else below
2069 // so don't return getCurrentNotice() immediately.
2075 static function maxContent()
2077 $contentlimit = common_config('notice', 'contentlimit');
2078 // null => use global limit (distinct from 0!)
2079 if (is_null($contentlimit)) {
2080 $contentlimit = common_config('site', 'textlimit');
2082 return $contentlimit;
2085 static function contentTooLong($content)
2087 $contentlimit = self::maxContent();
2088 return ($contentlimit > 0 && !empty($content) && (mb_strlen($content) > $contentlimit));
2092 * Convenience function for posting a repeat of an existing message.
2094 * @param Profile $repeater Profile which is doing the repeat
2095 * @param string $source: posting source key, eg 'web', 'api', etc
2098 * @throws Exception on failure or permission problems
2100 function repeat(Profile $repeater, $source)
2102 $author = $this->getProfile();
2104 // TRANS: Message used to repeat a notice. RT is the abbreviation of 'retweet'.
2105 // TRANS: %1$s is the repeated user's name, %2$s is the repeated notice.
2106 $content = sprintf(_('RT @%1$s %2$s'),
2107 $author->getNickname(),
2110 $maxlen = self::maxContent();
2111 if ($maxlen > 0 && mb_strlen($content) > $maxlen) {
2112 // Web interface and current Twitter API clients will
2113 // pull the original notice's text, but some older
2114 // clients and RSS/Atom feeds will see this trimmed text.
2116 // Unfortunately this is likely to lose tags or URLs
2117 // at the end of long notices.
2118 $content = mb_substr($content, 0, $maxlen - 4) . ' ...';
2122 // Scope is same as this one's
2123 return self::saveNew($repeater->id,
2126 array('repeat_of' => $this->id,
2127 'scope' => $this->scope));
2130 // These are supposed to be in chron order!
2132 function repeatStream($limit=100)
2134 $cache = Cache::instance();
2136 if (empty($cache)) {
2137 $ids = $this->_repeatStreamDirect($limit);
2139 $idstr = $cache->get(Cache::key('notice:repeats:'.$this->id));
2140 if ($idstr !== false) {
2141 if (empty($idstr)) {
2144 $ids = explode(',', $idstr);
2147 $ids = $this->_repeatStreamDirect(100);
2148 $cache->set(Cache::key('notice:repeats:'.$this->id), implode(',', $ids));
2151 // We do a max of 100, so slice down to limit
2152 $ids = array_slice($ids, 0, $limit);
2156 return NoticeStream::getStreamByIds($ids);
2159 function _repeatStreamDirect($limit)
2161 $notice = new Notice();
2163 $notice->selectAdd(); // clears it
2164 $notice->selectAdd('id');
2166 $notice->repeat_of = $this->id;
2168 $notice->orderBy('created, id'); // NB: asc!
2170 if (!is_null($limit)) {
2171 $notice->limit(0, $limit);
2174 return $notice->fetchAll('id');
2177 static function locationOptions($lat, $lon, $location_id, $location_ns, $profile = null)
2181 if (!empty($location_id) && !empty($location_ns)) {
2182 $options['location_id'] = $location_id;
2183 $options['location_ns'] = $location_ns;
2185 $location = Location::fromId($location_id, $location_ns);
2187 if ($location instanceof Location) {
2188 $options['lat'] = $location->lat;
2189 $options['lon'] = $location->lon;
2192 } else if (!empty($lat) && !empty($lon)) {
2193 $options['lat'] = $lat;
2194 $options['lon'] = $lon;
2196 $location = Location::fromLatLon($lat, $lon);
2198 if ($location instanceof Location) {
2199 $options['location_id'] = $location->location_id;
2200 $options['location_ns'] = $location->location_ns;
2202 } else if (!empty($profile)) {
2203 if (isset($profile->lat) && isset($profile->lon)) {
2204 $options['lat'] = $profile->lat;
2205 $options['lon'] = $profile->lon;
2208 if (isset($profile->location_id) && isset($profile->location_ns)) {
2209 $options['location_id'] = $profile->location_id;
2210 $options['location_ns'] = $profile->location_ns;
2217 function clearAttentions()
2219 $att = new Attention();
2220 $att->notice_id = $this->getID();
2223 while ($att->fetch()) {
2224 // Can't do delete() on the object directly since it won't remove all of it
2225 $other = clone($att);
2231 function clearReplies()
2233 $replyNotice = new Notice();
2234 $replyNotice->reply_to = $this->id;
2236 //Null any notices that are replies to this notice
2238 if ($replyNotice->find()) {
2239 while ($replyNotice->fetch()) {
2240 $orig = clone($replyNotice);
2241 $replyNotice->reply_to = null;
2242 $replyNotice->update($orig);
2248 $reply = new Reply();
2249 $reply->notice_id = $this->id;
2251 if ($reply->find()) {
2252 while($reply->fetch()) {
2253 self::blow('reply:stream:%d', $reply->profile_id);
2261 function clearLocation()
2263 $loc = new Notice_location();
2264 $loc->notice_id = $this->id;
2271 function clearFiles()
2273 $f2p = new File_to_post();
2275 $f2p->post_id = $this->id;
2278 while ($f2p->fetch()) {
2282 // FIXME: decide whether to delete File objects
2283 // ...and related (actual) files
2286 function clearRepeats()
2288 $repeatNotice = new Notice();
2289 $repeatNotice->repeat_of = $this->id;
2291 //Null any notices that are repeats of this notice
2293 if ($repeatNotice->find()) {
2294 while ($repeatNotice->fetch()) {
2295 $orig = clone($repeatNotice);
2296 $repeatNotice->repeat_of = null;
2297 $repeatNotice->update($orig);
2302 function clearTags()
2304 $tag = new Notice_tag();
2305 $tag->notice_id = $this->id;
2308 while ($tag->fetch()) {
2309 self::blow('profile:notice_ids_tagged:%d:%s', $this->profile_id, Cache::keyize($tag->tag));
2310 self::blow('profile:notice_ids_tagged:%d:%s;last', $this->profile_id, Cache::keyize($tag->tag));
2311 self::blow('notice_tag:notice_ids:%s', Cache::keyize($tag->tag));
2312 self::blow('notice_tag:notice_ids:%s;last', Cache::keyize($tag->tag));
2320 function clearGroupInboxes()
2322 $gi = new Group_inbox();
2324 $gi->notice_id = $this->id;
2327 while ($gi->fetch()) {
2328 self::blow('user_group:notice_ids:%d', $gi->group_id);
2336 function distribute()
2338 // We always insert for the author so they don't
2340 Event::handle('StartNoticeDistribute', array($this));
2342 // If there's a failure, we want to _force_
2343 // distribution at this point.
2345 $qm = QueueManager::get();
2346 $qm->enqueue($this, 'distrib');
2347 } catch (Exception $e) {
2348 // If the exception isn't transient, this
2349 // may throw more exceptions as DQH does
2350 // its own enqueueing. So, we ignore them!
2352 $handler = new DistribQueueHandler();
2353 $handler->handle($this);
2354 } catch (Exception $e) {
2355 common_log(LOG_ERR, "emergency redistribution resulted in " . $e->getMessage());
2357 // Re-throw so somebody smarter can handle it.
2364 $result = parent::insert();
2366 if ($result === false) {
2367 common_log_db_error($this, 'INSERT', __FILE__);
2368 // TRANS: Server exception thrown when a stored object entry cannot be saved.
2369 throw new ServerException('Could not save Notice');
2372 // Profile::hasRepeated() abuses pkeyGet(), so we
2373 // have to clear manually
2374 if (!empty($this->repeat_of)) {
2375 $c = self::memcache();
2377 $ck = self::multicacheKey('Notice',
2378 array('profile_id' => $this->profile_id,
2379 'repeat_of' => $this->repeat_of));
2384 // Update possibly ID-dependent columns: URI, conversation
2385 // (now that INSERT has added the notice's local id)
2386 $orig = clone($this);
2389 // We can only get here if it's a local notice, since remote notices
2390 // should've bailed out earlier due to lacking a URI.
2391 if (empty($this->uri)) {
2392 $this->uri = sprintf('%s%s=%d:%s=%s',
2394 'noticeId', $this->id,
2395 'objectType', $this->get_object_type(true));
2399 if ($changed && $this->update($orig) === false) {
2400 common_log_db_error($notice, 'UPDATE', __FILE__);
2401 // TRANS: Server exception thrown when a notice cannot be updated.
2402 throw new ServerException(_('Problem saving notice.'));
2405 $this->blowOnInsert();
2411 * Get the source of the notice
2413 * @return Notice_source $ns A notice source object. 'code' is the only attribute
2414 * guaranteed to be populated.
2416 function getSource()
2418 if (empty($this->source)) {
2422 $ns = new Notice_source();
2423 switch ($this->source) {
2430 $ns->code = $this->source;
2433 $ns = Notice_source::getKV($this->source);
2435 $ns = new Notice_source();
2436 $ns->code = $this->source;
2437 $app = Oauth_application::getKV('name', $this->source);
2439 $ns->name = $app->name;
2440 $ns->url = $app->source_url;
2450 * Determine whether the notice was locally created
2452 * @return boolean locality
2455 public function isLocal()
2457 return ($this->is_local == Notice::LOCAL_PUBLIC ||
2458 $this->is_local == Notice::LOCAL_NONPUBLIC);
2461 public function isRepeat()
2463 return !empty($this->repeat_of);
2467 * Get the list of hash tags saved with this notice.
2469 * @return array of strings
2471 public function getTags()
2475 $keypart = sprintf('notice:tags:%d', $this->id);
2477 $tagstr = self::cacheGet($keypart);
2479 if ($tagstr !== false) {
2480 $tags = explode(',', $tagstr);
2482 $tag = new Notice_tag();
2483 $tag->notice_id = $this->id;
2485 while ($tag->fetch()) {
2486 $tags[] = $tag->tag;
2489 self::cacheSet($keypart, implode(',', $tags));
2495 static private function utcDate($dt)
2497 $dateStr = date('d F Y H:i:s', strtotime($dt));
2498 $d = new DateTime($dateStr, new DateTimeZone('UTC'));
2499 return $d->format(DATE_W3C);
2503 * Look up the creation timestamp for a given notice ID, even
2504 * if it's been deleted.
2507 * @return mixed string recorded creation timestamp, or false if can't be found
2509 public static function getAsTimestamp($id)
2515 $notice = Notice::getKV('id', $id);
2517 return $notice->created;
2520 $deleted = Deleted_notice::getKV('id', $id);
2522 return $deleted->created;
2529 * Build an SQL 'where' fragment for timestamp-based sorting from a since_id
2530 * parameter, matching notices posted after the given one (exclusive).
2532 * If the referenced notice can't be found, will return false.
2535 * @param string $idField
2536 * @param string $createdField
2537 * @return mixed string or false if no match
2539 public static function whereSinceId($id, $idField='id', $createdField='created')
2541 $since = Notice::getAsTimestamp($id);
2543 return sprintf("($createdField = '%s' and $idField > %d) or ($createdField > '%s')", $since, $id, $since);
2549 * Build an SQL 'where' fragment for timestamp-based sorting from a since_id
2550 * parameter, matching notices posted after the given one (exclusive), and
2551 * if necessary add it to the data object's query.
2553 * @param DB_DataObject $obj
2555 * @param string $idField
2556 * @param string $createdField
2557 * @return mixed string or false if no match
2559 public static function addWhereSinceId(DB_DataObject $obj, $id, $idField='id', $createdField='created')
2561 $since = self::whereSinceId($id, $idField, $createdField);
2563 $obj->whereAdd($since);
2568 * Build an SQL 'where' fragment for timestamp-based sorting from a max_id
2569 * parameter, matching notices posted before the given one (inclusive).
2571 * If the referenced notice can't be found, will return false.
2574 * @param string $idField
2575 * @param string $createdField
2576 * @return mixed string or false if no match
2578 public static function whereMaxId($id, $idField='id', $createdField='created')
2580 $max = Notice::getAsTimestamp($id);
2582 return sprintf("($createdField < '%s') or ($createdField = '%s' and $idField <= %d)", $max, $max, $id);
2588 * Build an SQL 'where' fragment for timestamp-based sorting from a max_id
2589 * parameter, matching notices posted before the given one (inclusive), and
2590 * if necessary add it to the data object's query.
2592 * @param DB_DataObject $obj
2594 * @param string $idField
2595 * @param string $createdField
2596 * @return mixed string or false if no match
2598 public static function addWhereMaxId(DB_DataObject $obj, $id, $idField='id', $createdField='created')
2600 $max = self::whereMaxId($id, $idField, $createdField);
2602 $obj->whereAdd($max);
2608 return (($this->is_local != Notice::LOCAL_NONPUBLIC) &&
2609 ($this->is_local != Notice::GATEWAY));
2613 * Check that the given profile is allowed to read, respond to, or otherwise
2614 * act on this notice.
2616 * The $scope member is a bitmask of scopes, representing a logical AND of the
2617 * scope requirement. So, 0x03 (Notice::ADDRESSEE_SCOPE | Notice::SITE_SCOPE) means
2618 * "only visible to people who are mentioned in the notice AND are users on this site."
2619 * Users on the site who are not mentioned in the notice will not be able to see the
2622 * @param Profile $profile The profile to check; pass null to check for public/unauthenticated users.
2624 * @return boolean whether the profile is in the notice's scope
2626 function inScope($profile)
2628 if (is_null($profile)) {
2629 $keypart = sprintf('notice:in-scope-for:%d:null', $this->id);
2631 $keypart = sprintf('notice:in-scope-for:%d:%d', $this->id, $profile->id);
2634 $result = self::cacheGet($keypart);
2636 if ($result === false) {
2638 if (Event::handle('StartNoticeInScope', array($this, $profile, &$bResult))) {
2639 $bResult = $this->_inScope($profile);
2640 Event::handle('EndNoticeInScope', array($this, $profile, &$bResult));
2642 $result = ($bResult) ? 1 : 0;
2643 self::cacheSet($keypart, $result, 0, 300);
2646 return ($result == 1) ? true : false;
2649 protected function _inScope($profile)
2651 if (!is_null($this->scope)) {
2652 $scope = $this->scope;
2654 $scope = self::defaultScope();
2657 if ($scope == 0 && !$this->getProfile()->isPrivateStream()) { // Not scoping, so it is public.
2658 return !$this->isHiddenSpam($profile);
2661 // If there's scope, anon cannot be in scope
2662 if (empty($profile)) {
2666 // Author is always in scope
2667 if ($this->profile_id == $profile->id) {
2671 // Only for users on this site
2672 if (($scope & Notice::SITE_SCOPE) && !$profile->isLocal()) {
2676 // Only for users mentioned in the notice
2677 if ($scope & Notice::ADDRESSEE_SCOPE) {
2679 $reply = Reply::pkeyGet(array('notice_id' => $this->id,
2680 'profile_id' => $profile->id));
2682 if (!$reply instanceof Reply) {
2687 // Only for members of the given group
2688 if ($scope & Notice::GROUP_SCOPE) {
2690 // XXX: just query for the single membership
2692 $groups = $this->getGroups();
2696 foreach ($groups as $group) {
2697 if ($profile->isMember($group)) {
2708 if ($scope & Notice::FOLLOWER_SCOPE || $this->getProfile()->isPrivateStream()) {
2710 if (!Subscription::exists($profile, $this->getProfile())) {
2715 return !$this->isHiddenSpam($profile);
2718 function isHiddenSpam($profile) {
2720 // Hide posts by silenced users from everyone but moderators.
2722 if (common_config('notice', 'hidespam')) {
2725 $author = $this->getProfile();
2726 } catch(Exception $e) {
2727 // If we can't get an author, keep it hidden.
2728 // XXX: technically not spam, but, whatever.
2732 if ($author->hasRole(Profile_role::SILENCED)) {
2733 if (!$profile instanceof Profile || (($profile->id !== $author->id) && (!$profile->hasRight(Right::REVIEWSPAM)))) {
2742 public function getParent()
2744 if (empty($this->reply_to)) {
2745 throw new NoParentNoticeException($this);
2747 return self::getByID($this->reply_to);
2751 * Magic function called at serialize() time.
2753 * We use this to drop a couple process-specific references
2754 * from DB_DataObject which can cause trouble in future
2757 * @return array of variable names to include in serialization.
2762 $vars = parent::__sleep();
2763 $skip = array('_profile', '_groups', '_attachments', '_faves', '_replies', '_repeats');
2764 return array_diff($vars, $skip);
2767 static function defaultScope()
2769 $scope = common_config('notice', 'defaultscope');
2770 if (is_null($scope)) {
2771 if (common_config('site', 'private')) {
2780 static function fillProfiles($notices)
2782 $map = self::getProfiles($notices);
2783 foreach ($notices as $entry=>$notice) {
2785 if (array_key_exists($notice->profile_id, $map)) {
2786 $notice->_setProfile($map[$notice->profile_id]);
2788 } catch (NoProfileException $e) {
2789 common_log(LOG_WARNING, "Failed to fill profile in Notice with non-existing entry for profile_id: {$e->profile_id}");
2790 unset($notices[$entry]);
2794 return array_values($map);
2797 static function getProfiles(&$notices)
2800 foreach ($notices as $notice) {
2801 $ids[] = $notice->profile_id;
2803 $ids = array_unique($ids);
2804 return Profile::pivotGet('id', $ids);
2807 static function fillGroups(&$notices)
2809 $ids = self::_idsOf($notices);
2810 $gis = Group_inbox::listGet('notice_id', $ids);
2813 foreach ($gis as $id => $gi) {
2816 $gids[] = $g->group_id;
2820 $gids = array_unique($gids);
2821 $group = User_group::pivotGet('id', $gids);
2822 foreach ($notices as $notice)
2825 $gi = $gis[$notice->id];
2826 foreach ($gi as $g) {
2827 $grps[] = $group[$g->group_id];
2829 $notice->_setGroups($grps);
2833 static function _idsOf(array &$notices)
2836 foreach ($notices as $notice) {
2837 $ids[$notice->id] = true;
2839 return array_keys($ids);
2842 static function fillAttachments(&$notices)
2844 $ids = self::_idsOf($notices);
2845 $f2pMap = File_to_post::listGet('post_id', $ids);
2847 foreach ($f2pMap as $noticeId => $f2ps) {
2848 foreach ($f2ps as $f2p) {
2849 $fileIds[] = $f2p->file_id;
2853 $fileIds = array_unique($fileIds);
2854 $fileMap = File::pivotGet('id', $fileIds);
2855 foreach ($notices as $notice)
2858 $f2ps = $f2pMap[$notice->id];
2859 foreach ($f2ps as $f2p) {
2860 $files[] = $fileMap[$f2p->file_id];
2862 $notice->_setAttachments($files);
2866 static function fillReplies(&$notices)
2868 $ids = self::_idsOf($notices);
2869 $replyMap = Reply::listGet('notice_id', $ids);
2870 foreach ($notices as $notice) {
2871 $replies = $replyMap[$notice->id];
2873 foreach ($replies as $reply) {
2874 $ids[] = $reply->profile_id;
2876 $notice->_setReplies($ids);
2880 static public function beforeSchemaUpdate()
2882 $table = strtolower(get_called_class());
2883 $schema = Schema::get();
2884 $schemadef = $schema->getTableDef($table);
2886 // 2015-09-04 We move Notice location data to Notice_location
2887 // First we see if we have to do this at all
2888 if (!isset($schemadef['fields']['lat'])
2889 && !isset($schemadef['fields']['lon'])
2890 && !isset($schemadef['fields']['location_id'])
2891 && !isset($schemadef['fields']['location_ns'])) {
2892 // We have already removed the location fields, so no need to migrate.
2895 // Then we make sure the Notice_location table is created!
2896 $schema->ensureTable('notice_location', Notice_location::schemaDef());
2898 // Then we continue on our road to migration!
2899 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)";
2901 $notice = new Notice();
2902 $notice->query(sprintf('SELECT id, lat, lon, location_id, location_ns FROM %1$s ' .
2903 'WHERE lat IS NOT NULL ' .
2904 'OR lon IS NOT NULL ' .
2905 'OR location_id IS NOT NULL ' .
2906 'OR location_ns IS NOT NULL',
2907 $schema->quoteIdentifier($table)));
2908 print "\nFound {$notice->N} notices with location data, inserting";
2909 while ($notice->fetch()) {
2910 $notloc = Notice_location::getKV('notice_id', $notice->id);
2911 if ($notloc instanceof Notice_location) {
2915 $notloc = new Notice_location();
2916 $notloc->notice_id = $notice->id;
2917 $notloc->lat= $notice->lat;
2918 $notloc->lon= $notice->lon;
2919 $notloc->location_id= $notice->location_id;
2920 $notloc->location_ns= $notice->location_ns;