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(255) unique_key
59 public $content; // text
60 public $rendered; // text
61 public $url; // varchar(255)
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 $lat; // decimal(10,7)
69 public $lon; // decimal(10,7)
70 public $location_id; // int(4)
71 public $location_ns; // int(4)
72 public $repeat_of; // int(4)
73 public $verb; // varchar(255)
74 public $object_type; // varchar(255)
75 public $scope; // int(4)
77 /* the code above is auto generated do not remove the tag below */
80 public static function schemaDef()
84 'id' => array('type' => 'serial', 'not null' => true, 'description' => 'unique identifier'),
85 'profile_id' => array('type' => 'int', 'not null' => true, 'description' => 'who made the update'),
86 'uri' => array('type' => 'varchar', 'length' => 255, 'description' => 'universally unique identifier, usually a tag URI'),
87 'content' => array('type' => 'text', 'description' => 'update content', 'collate' => 'utf8_general_ci'),
88 'rendered' => array('type' => 'text', 'description' => 'HTML version of the content'),
89 'url' => array('type' => 'varchar', 'length' => 255, 'description' => 'URL of any attachment (image, video, bookmark, whatever)'),
90 'created' => array('type' => 'datetime', 'not null' => true, 'description' => 'date this record was created'),
91 'modified' => array('type' => 'timestamp', 'not null' => true, 'description' => 'date this record was modified'),
92 'reply_to' => array('type' => 'int', 'description' => 'notice replied to (usually a guess)'),
93 'is_local' => array('type' => 'int', 'size' => 'tiny', 'default' => 0, 'description' => 'notice was generated by a user'),
94 'source' => array('type' => 'varchar', 'length' => 32, 'description' => 'source of comment, like "web", "im", or "clientname"'),
95 'conversation' => array('type' => 'int', 'description' => 'id of root notice in this conversation'),
96 'lat' => array('type' => 'numeric', 'precision' => 10, 'scale' => 7, 'description' => 'latitude'),
97 'lon' => array('type' => 'numeric', 'precision' => 10, 'scale' => 7, 'description' => 'longitude'),
98 'location_id' => array('type' => 'int', 'description' => 'location id if possible'),
99 'location_ns' => array('type' => 'int', 'description' => 'namespace for location'),
100 'repeat_of' => array('type' => 'int', 'description' => 'notice this is a repeat of'),
101 'object_type' => array('type' => 'varchar', 'length' => 255, 'description' => 'URI representing activity streams object type', 'default' => 'http://activitystrea.ms/schema/1.0/note'),
102 'verb' => array('type' => 'varchar', 'length' => 255, 'description' => 'URI representing activity streams verb', 'default' => 'http://activitystrea.ms/schema/1.0/post'),
103 'scope' => array('type' => 'int',
104 'description' => 'bit map for distribution scope; 0 = everywhere; 1 = this server only; 2 = addressees; 4 = followers; null = default'),
106 'primary key' => array('id'),
107 'unique keys' => array(
108 'notice_uri_key' => array('uri'),
110 'foreign keys' => array(
111 'notice_profile_id_fkey' => array('profile', array('profile_id' => 'id')),
112 'notice_reply_to_fkey' => array('notice', array('reply_to' => 'id')),
113 'notice_conversation_fkey' => array('conversation', array('conversation' => 'id')), # note... used to refer to notice.id
114 'notice_repeat_of_fkey' => array('notice', array('repeat_of' => 'id')), # @fixme: what about repeats of deleted notices?
117 'notice_created_id_is_local_idx' => array('created', 'id', 'is_local'),
118 'notice_profile_id_idx' => array('profile_id', 'created', 'id'),
119 'notice_repeat_of_created_id_idx' => array('repeat_of', 'created', 'id'),
120 'notice_conversation_created_id_idx' => array('conversation', 'created', 'id'),
121 'notice_replyto_idx' => array('reply_to')
125 if (common_config('search', 'type') == 'fulltext') {
126 $def['fulltext indexes'] = array('content' => array('content'));
133 const LOCAL_PUBLIC = 1;
135 const LOCAL_NONPUBLIC = -1;
138 const PUBLIC_SCOPE = 0; // Useful fake constant
139 const SITE_SCOPE = 1;
140 const ADDRESSEE_SCOPE = 2;
141 const GROUP_SCOPE = 4;
142 const FOLLOWER_SCOPE = 8;
144 protected $_profile = array();
147 * Will always return a profile, if anything fails it will
148 * (through _setProfile) throw a NoProfileException.
150 public function getProfile()
152 if (!isset($this->_profile[$this->profile_id])) {
153 $this->_setProfile(Profile::getKV('id', $this->profile_id));
155 return $this->_profile[$this->profile_id];
158 public function _setProfile(Profile $profile=null)
160 if (!$profile instanceof Profile) {
161 throw new NoProfileException($this->profile_id);
163 $this->_profile[$this->profile_id] = $profile;
166 function delete($useWhere=false)
168 // For auditing purposes, save a record that the notice
171 // @fixme we have some cases where things get re-run and so the
173 $deleted = Deleted_notice::getKV('id', $this->id);
175 if (!$deleted instanceof Deleted_notice) {
176 $deleted = Deleted_notice::getKV('uri', $this->uri);
179 if (!$deleted instanceof Deleted_notice) {
180 $deleted = new Deleted_notice();
182 $deleted->id = $this->id;
183 $deleted->profile_id = $this->profile_id;
184 $deleted->uri = $this->uri;
185 $deleted->created = $this->created;
186 $deleted->deleted = common_sql_now();
191 if (Event::handle('NoticeDeleteRelated', array($this))) {
193 // Clear related records
195 $this->clearReplies();
196 $this->clearRepeats();
199 $this->clearGroupInboxes();
201 $this->clearAttentions();
203 // NOTE: we don't clear queue items
206 $result = parent::delete($useWhere);
208 $this->blowOnDelete();
212 public function getUri()
218 * @param $root boolean If true, link to just the conversation root.
220 * @return URL to conversation
222 public function getConversationUrl($anchor=true)
224 return Conversation::getUrlFromNotice($this, $anchor);
228 * Get the local representation URL of this notice.
230 public function getLocalUrl()
232 return common_local_url('shownotice', array('notice' => $this->id), null, null, false);
235 public function getTitle()
238 if (Event::handle('GetNoticeTitle', array($this, &$title))) {
239 // TRANS: Title of a notice posted without a title value.
240 // TRANS: %1$s is a user name, %2$s is the notice creation date/time.
241 $title = sprintf(_('%1$s\'s status on %2$s'),
242 $this->getProfile()->getFancyName(),
243 common_exact_date($this->created));
249 * Get the original representation URL of this notice.
251 public function getUrl()
253 // The risk is we start having empty urls and non-http uris...
254 // and we can't really handle any other protocol right now.
256 case common_valid_http_url($this->url): // should we allow non-http/https URLs?
258 case $this->isLocal():
259 // let's generate a valid link to our locally available notice on demand
260 return common_local_url('shownotice', array('notice' => $this->id), null, null, false);
261 case common_valid_http_url($this->uri):
264 common_debug('No URL available for notice: id='.$this->id);
265 throw new InvalidUrlException($this->url);
269 public function get_object_type($canonical=false) {
271 ? ActivityObject::canonicalType($this->object_type)
272 : $this->object_type;
275 public static function getByUri($uri)
277 $notice = new Notice();
279 if (!$notice->find(true)) {
280 throw new NoResultException($notice);
286 * Extract #hashtags from this notice's content and save them to the database.
290 /* extract all #hastags */
291 $count = preg_match_all('/(?:^|\s)#([\pL\pN_\-\.]{1,64})/u', strtolower($this->content), $match);
296 /* Add them to the database */
297 return $this->saveKnownTags($match[1]);
301 * Record the given set of hash tags in the db for this notice.
302 * Given tag strings will be normalized and checked for dupes.
304 function saveKnownTags($hashtags)
306 //turn each into their canonical tag
307 //this is needed to remove dupes before saving e.g. #hash.tag = #hashtag
308 for($i=0; $i<count($hashtags); $i++) {
309 /* elide characters we don't want in the tag */
310 $hashtags[$i] = common_canonical_tag($hashtags[$i]);
313 foreach(array_unique($hashtags) as $hashtag) {
314 $this->saveTag($hashtag);
315 self::blow('profile:notice_ids_tagged:%d:%s', $this->profile_id, $hashtag);
321 * Record a single hash tag as associated with this notice.
322 * Tag format and uniqueness must be validated by caller.
324 function saveTag($hashtag)
326 $tag = new Notice_tag();
327 $tag->notice_id = $this->id;
328 $tag->tag = $hashtag;
329 $tag->created = $this->created;
330 $id = $tag->insert();
333 // TRANS: Server exception. %s are the error details.
334 throw new ServerException(sprintf(_('Database error inserting hashtag: %s.'),
335 $last_error->message));
339 // if it's saved, blow its cache
340 $tag->blowCache(false);
344 * Save a new notice and push it out to subscribers' inboxes.
345 * Poster's permissions are checked before sending.
347 * @param int $profile_id Profile ID of the poster
348 * @param string $content source message text; links may be shortened
349 * per current user's preference
350 * @param string $source source key ('web', 'api', etc)
351 * @param array $options Associative array of optional properties:
352 * string 'created' timestamp of notice; defaults to now
353 * int 'is_local' source/gateway ID, one of:
354 * Notice::LOCAL_PUBLIC - Local, ok to appear in public timeline
355 * Notice::REMOTE - Sent from a remote service;
356 * hide from public timeline but show in
357 * local "and friends" timelines
358 * Notice::LOCAL_NONPUBLIC - Local, but hide from public timeline
359 * Notice::GATEWAY - From another non-OStatus service;
360 * will not appear in public views
361 * float 'lat' decimal latitude for geolocation
362 * float 'lon' decimal longitude for geolocation
363 * int 'location_id' geoname identifier
364 * int 'location_ns' geoname namespace to interpret location_id
365 * int 'reply_to'; notice ID this is a reply to
366 * int 'repeat_of'; notice ID this is a repeat of
367 * string 'uri' unique ID for notice; a unique tag uri (can be url or anything too)
368 * string 'url' permalink to notice; defaults to local notice URL
369 * string 'rendered' rendered HTML version of content
370 * array 'replies' list of profile URIs for reply delivery in
371 * place of extracting @-replies from content.
372 * array 'groups' list of group IDs to deliver to, in place of
373 * extracting ! tags from content
374 * array 'tags' list of hashtag strings to save with the notice
375 * in place of extracting # tags from content
376 * array 'urls' list of attached/referred URLs to save with the
377 * notice in place of extracting links from content
378 * boolean 'distribute' whether to distribute the notice, default true
379 * string 'object_type' URL of the associated object type (default ActivityObject::NOTE)
380 * string 'verb' URL of the associated verb (default ActivityVerb::POST)
381 * int 'scope' Scope bitmask; default to SITE_SCOPE on private sites, 0 otherwise
383 * @fixme tag override
386 * @throws ClientException
388 static function saveNew($profile_id, $content, $source, array $options=null) {
389 $defaults = array('uri' => null,
394 'distribute' => true,
395 'object_type' => null,
398 if (!empty($options) && is_array($options)) {
399 $options = array_merge($defaults, $options);
405 if (!isset($is_local)) {
406 $is_local = Notice::LOCAL_PUBLIC;
409 $profile = Profile::getKV('id', $profile_id);
410 if (!$profile instanceof Profile) {
411 // TRANS: Client exception thrown when trying to save a notice for an unknown user.
412 throw new ClientException(_('Problem saving notice. Unknown user.'));
415 $user = User::getKV('id', $profile_id);
416 if ($user instanceof User) {
417 // Use the local user's shortening preferences, if applicable.
418 $final = $user->shortenLinks($content);
420 $final = common_shorten_links($content);
423 if (Notice::contentTooLong($final)) {
424 // TRANS: Client exception thrown if a notice contains too many characters.
425 throw new ClientException(_('Problem saving notice. Too long.'));
428 if (common_config('throttle', 'enabled') && !Notice::checkEditThrottle($profile_id)) {
429 common_log(LOG_WARNING, 'Excessive posting by profile #' . $profile_id . '; throttled.');
430 // TRANS: Client exception thrown when a user tries to post too many notices in a given time frame.
431 throw new ClientException(_('Too many notices too fast; take a breather '.
432 'and post again in a few minutes.'));
435 if (common_config('site', 'dupelimit') > 0 && !Notice::checkDupes($profile_id, $final)) {
436 common_log(LOG_WARNING, 'Dupe posting by profile #' . $profile_id . '; throttled.');
437 // TRANS: Client exception thrown when a user tries to post too many duplicate notices in a given time frame.
438 throw new ClientException(_('Too many duplicate messages too quickly;'.
439 ' take a breather and post again in a few minutes.'));
442 if (!$profile->hasRight(Right::NEWNOTICE)) {
443 common_log(LOG_WARNING, "Attempted post from user disallowed to post: " . $profile->nickname);
445 // TRANS: Client exception thrown when a user tries to post while being banned.
446 throw new ClientException(_('You are banned from posting notices on this site.'), 403);
449 $notice = new Notice();
450 $notice->profile_id = $profile_id;
452 $autosource = common_config('public', 'autosource');
454 // Sandboxed are non-false, but not 1, either
456 if (!$profile->hasRight(Right::PUBLICNOTICE) ||
457 ($source && $autosource && in_array($source, $autosource))) {
458 $notice->is_local = Notice::LOCAL_NONPUBLIC;
460 $notice->is_local = $is_local;
463 if (!empty($created)) {
464 $notice->created = $created;
466 $notice->created = common_sql_now();
469 if (!$notice->isLocal()) {
470 // Only do these checks for non-local notices. Local notices will generate these values later.
471 if (!common_valid_http_url($url)) {
472 common_debug('Bad notice URL: ['.$url.'], URI: ['.$uri.']. Cannot link back to original! This is normal for shared notices etc.');
475 throw new ServerException('No URI for remote notice. Cannot accept that.');
479 $notice->content = $final;
481 $notice->source = $source;
485 // Get the groups here so we can figure out replies and such
486 if (!isset($groups)) {
487 $groups = User_group::idsFromText($notice->content, $profile);
492 // Handle repeat case
494 if (isset($repeat_of)) {
496 // Check for a private one
498 $repeat = Notice::getKV('id', $repeat_of);
500 if (!($repeat instanceof Notice)) {
501 // TRANS: Client exception thrown in notice when trying to repeat a missing or deleted notice.
502 throw new ClientException(_('Cannot repeat; original notice is missing or deleted.'));
505 if ($profile->id == $repeat->profile_id) {
506 // TRANS: Client error displayed when trying to repeat an own notice.
507 throw new ClientException(_('You cannot repeat your own notice.'));
510 if ($repeat->scope != Notice::SITE_SCOPE &&
511 $repeat->scope != Notice::PUBLIC_SCOPE) {
512 // TRANS: Client error displayed when trying to repeat a non-public notice.
513 throw new ClientException(_('Cannot repeat a private notice.'), 403);
516 if (!$repeat->inScope($profile)) {
517 // The generic checks above should cover this, but let's be sure!
518 // TRANS: Client error displayed when trying to repeat a notice you cannot access.
519 throw new ClientException(_('Cannot repeat a notice you cannot read.'), 403);
522 if ($profile->hasRepeated($repeat)) {
523 // TRANS: Client error displayed when trying to repeat an already repeated notice.
524 throw new ClientException(_('You already repeated that notice.'));
527 $notice->repeat_of = $repeat->id;
528 $notice->conversation = $repeat->conversation;
532 // If $reply_to is specified, we check that it exists, and then
533 // return it if it does
534 if (!empty($reply_to)) {
535 $reply = Notice::getKV('id', $reply_to);
536 } elseif (in_array($source, array('xmpp', 'mail', 'sms'))) {
537 // If the source lacks capability of sending the "reply_to"
538 // metadata, let's try to find an inline replyto-reference.
539 $reply = self::getInlineReplyTo($profile, $final);
542 if ($reply instanceof Notice) {
543 if (!$reply->inScope($profile)) {
544 // TRANS: Client error displayed when trying to reply to a notice a the target has no access to.
545 // TRANS: %1$s is a user nickname, %2$d is a notice ID (number).
546 throw new ClientException(sprintf(_('%1$s has no access to notice %2$d.'),
547 $profile->nickname, $reply->id), 403);
550 // If it's a repeat, the reply_to should be to the original
551 if (!empty($reply->repeat_of)) {
552 $notice->reply_to = $reply->repeat_of;
554 $notice->reply_to = $reply->id;
556 // But the conversation ought to be the same :)
557 $notice->conversation = $reply->conversation;
559 // If the original is private to a group, and notice has
560 // no group specified, make it to the same group(s)
562 if (empty($groups) && ($reply->scope & Notice::GROUP_SCOPE)) {
564 $replyGroups = $reply->getGroups();
565 foreach ($replyGroups as $group) {
566 if ($profile->isMember($group)) {
567 $groups[] = $group->id;
576 if (!empty($lat) && !empty($lon)) {
581 if (!empty($location_ns) && !empty($location_id)) {
582 $notice->location_id = $location_id;
583 $notice->location_ns = $location_ns;
586 if (!empty($rendered)) {
587 $notice->rendered = $rendered;
589 $notice->rendered = common_render_content($final, $notice);
593 if (!empty($notice->repeat_of)) {
594 $notice->verb = ActivityVerb::SHARE;
595 $notice->object_type = ActivityObject::ACTIVITY;
597 $notice->verb = ActivityVerb::POST;
600 $notice->verb = $verb;
603 if (empty($object_type)) {
604 $notice->object_type = (empty($notice->reply_to)) ? ActivityObject::NOTE : ActivityObject::COMMENT;
606 $notice->object_type = $object_type;
609 if (is_null($scope)) { // 0 is a valid value
610 if (!empty($reply)) {
611 $notice->scope = $reply->scope;
613 $notice->scope = self::defaultScope();
616 $notice->scope = $scope;
619 // For private streams
622 $user = $profile->getUser();
624 if ($user->private_stream &&
625 ($notice->scope == Notice::PUBLIC_SCOPE ||
626 $notice->scope == Notice::SITE_SCOPE)) {
627 $notice->scope |= Notice::FOLLOWER_SCOPE;
629 } catch (NoSuchUserException $e) {
630 // Cannot handle private streams for remote profiles
633 // Force the scope for private groups
635 foreach ($groups as $groupId) {
636 $group = User_group::getKV('id', $groupId);
637 if ($group instanceof User_group) {
638 if ($group->force_scope) {
639 $notice->scope |= Notice::GROUP_SCOPE;
645 if (Event::handle('StartNoticeSave', array(&$notice))) {
647 // XXX: some of these functions write to the DB
649 $id = $notice->insert();
652 common_log_db_error($notice, 'INSERT', __FILE__);
653 // TRANS: Server exception thrown when a notice cannot be saved.
654 throw new ServerException(_('Problem saving notice.'));
657 // Update ID-dependent columns: URI, conversation
659 $orig = clone($notice);
663 // We can only get here if it's a local notice, since remote notices
664 // should've bailed out earlier due to lacking a URI.
665 if (empty($notice->uri)) {
666 $notice->uri = sprintf('%s%s=%d:%s=%s',
668 'noticeId', $notice->id,
669 'objectType', $notice->get_object_type(true));
673 // If it's not part of a conversation, it's
674 // the beginning of a new conversation.
676 if (empty($notice->conversation)) {
677 $conv = Conversation::create($notice);
678 $notice->conversation = $conv->id;
683 if ($notice->update($orig) === false) {
684 common_log_db_error($notice, 'UPDATE', __FILE__);
685 // TRANS: Server exception thrown when a notice cannot be updated.
686 throw new ServerException(_('Problem saving notice.'));
692 // Clear the cache for subscribed users, so they'll update at next request
693 // XXX: someone clever could prepend instead of clearing the cache
695 $notice->blowOnInsert();
697 // Save per-notice metadata...
699 if (isset($replies)) {
700 $notice->saveKnownReplies($replies);
702 $notice->saveReplies();
706 $notice->saveKnownTags($tags);
711 // Note: groups may save tags, so must be run after tags are saved
712 // to avoid errors on duplicates.
713 // Note: groups should always be set.
715 $notice->saveKnownGroups($groups);
718 $notice->saveKnownUrls($urls);
724 // Prepare inbox delivery, may be queued to background.
725 $notice->distribute();
731 function blowOnInsert($conversation = false)
733 $this->blowStream('profile:notice_ids:%d', $this->profile_id);
735 if ($this->isPublic()) {
736 $this->blowStream('public');
739 self::blow('notice:list-ids:conversation:%s', $this->conversation);
740 self::blow('conversation:notice_count:%d', $this->conversation);
742 if (!empty($this->repeat_of)) {
743 // XXX: we should probably only use one of these
744 $this->blowStream('notice:repeats:%d', $this->repeat_of);
745 self::blow('notice:list-ids:repeat_of:%d', $this->repeat_of);
748 $original = Notice::getKV('id', $this->repeat_of);
750 if ($original instanceof Notice) {
751 $originalUser = User::getKV('id', $original->profile_id);
752 if ($originalUser instanceof User) {
753 $this->blowStream('user:repeats_of_me:%d', $originalUser->id);
757 $profile = Profile::getKV($this->profile_id);
759 if ($profile instanceof Profile) {
760 $profile->blowNoticeCount();
763 $ptags = $this->getProfileTags();
764 foreach ($ptags as $ptag) {
765 $ptag->blowNoticeStreamCache();
770 * Clear cache entries related to this notice at delete time.
771 * Necessary to avoid breaking paging on public, profile timelines.
773 function blowOnDelete()
775 $this->blowOnInsert();
777 self::blow('profile:notice_ids:%d;last', $this->profile_id);
779 if ($this->isPublic()) {
780 self::blow('public;last');
783 self::blow('fave:by_notice', $this->id);
785 if ($this->conversation) {
786 // In case we're the first, will need to calc a new root.
787 self::blow('notice:conversation_root:%d', $this->conversation);
790 $ptags = $this->getProfileTags();
791 foreach ($ptags as $ptag) {
792 $ptag->blowNoticeStreamCache(true);
796 function blowStream()
798 $c = self::memcache();
804 $args = func_get_args();
806 $format = array_shift($args);
808 $keyPart = vsprintf($format, $args);
810 $cacheKey = Cache::key($keyPart);
812 $c->delete($cacheKey);
814 // delete the "last" stream, too, if this notice is
815 // older than the top of that stream
817 $lastKey = $cacheKey.';last';
819 $lastStr = $c->get($lastKey);
821 if ($lastStr !== false) {
822 $window = explode(',', $lastStr);
823 $lastID = $window[0];
824 $lastNotice = Notice::getKV('id', $lastID);
825 if (!$lastNotice instanceof Notice // just weird
826 || strtotime($lastNotice->created) >= strtotime($this->created)) {
827 $c->delete($lastKey);
832 /** save all urls in the notice to the db
834 * follow redirects and save all available file information
835 * (mimetype, date, size, oembed, etc.)
839 function saveUrls() {
840 if (common_config('attachments', 'process_links')) {
841 common_replace_urls_callback($this->content, array($this, 'saveUrl'), $this->id);
846 * Save the given URLs as related links/attachments to the db
848 * follow redirects and save all available file information
849 * (mimetype, date, size, oembed, etc.)
853 function saveKnownUrls($urls)
855 if (common_config('attachments', 'process_links')) {
856 // @fixme validation?
857 foreach (array_unique($urls) as $url) {
859 File::processNew($url, $this->id);
860 } catch (ServerException $e) {
861 // Could not save URL. Log it?
870 function saveUrl($url, $notice_id) {
872 File::processNew($url, $notice_id);
873 } catch (ServerException $e) {
874 // Could not save URL. Log it?
878 static function checkDupes($profile_id, $content) {
879 $profile = Profile::getKV($profile_id);
880 if (!$profile instanceof Profile) {
883 $notice = $profile->getNotices(0, CachingNoticeStream::CACHE_WINDOW);
884 if (!empty($notice)) {
886 while ($notice->fetch()) {
887 if (time() - strtotime($notice->created) >= common_config('site', 'dupelimit')) {
889 } else if ($notice->content == $content) {
894 // If we get here, oldest item in cache window is not
895 // old enough for dupe limit; do direct check against DB
896 $notice = new Notice();
897 $notice->profile_id = $profile_id;
898 $notice->content = $content;
899 $threshold = common_sql_date(time() - common_config('site', 'dupelimit'));
900 $notice->whereAdd(sprintf("created > '%s'", $notice->escape($threshold)));
902 $cnt = $notice->count();
906 static function checkEditThrottle($profile_id) {
907 $profile = Profile::getKV($profile_id);
908 if (!$profile instanceof Profile) {
911 // Get the Nth notice
912 $notice = $profile->getNotices(common_config('throttle', 'count') - 1, 1);
913 if ($notice && $notice->fetch()) {
914 // If the Nth notice was posted less than timespan seconds ago
915 if (time() - strtotime($notice->created) <= common_config('throttle', 'timespan')) {
920 // Either not N notices in the stream, OR the Nth was not posted within timespan seconds
924 protected $_attachments = array();
926 function attachments() {
927 if (isset($this->_attachments[$this->id])) {
928 return $this->_attachments[$this->id];
931 $f2ps = File_to_post::listGet('post_id', array($this->id));
935 foreach ($f2ps[$this->id] as $f2p) {
936 $ids[] = $f2p->file_id;
939 $files = File::multiGet('id', $ids);
941 $this->_attachments[$this->id] = $files->fetchAll();
943 return $this->_attachments[$this->id];
946 function _setAttachments($attachments)
948 $this->_attachments[$this->id] = $attachments;
951 function publicStream($offset=0, $limit=20, $since_id=0, $max_id=0)
953 $stream = new PublicNoticeStream();
954 return $stream->getNotices($offset, $limit, $since_id, $max_id);
958 function conversationStream($id, $offset=0, $limit=20, $since_id=0, $max_id=0)
960 $stream = new ConversationNoticeStream($id);
962 return $stream->getNotices($offset, $limit, $since_id, $max_id);
966 * Is this notice part of an active conversation?
968 * @return boolean true if other messages exist in the same
969 * conversation, false if this is the only one
971 function hasConversation()
973 if (!empty($this->conversation)) {
974 $conversation = Notice::conversationStream(
980 if ($conversation->N > 0) {
988 * Grab the earliest notice from this conversation.
990 * @return Notice or null
992 function conversationRoot($profile=-1)
994 // XXX: can this happen?
996 if (empty($this->conversation)) {
1000 // Get the current profile if not specified
1002 if (is_int($profile) && $profile == -1) {
1003 $profile = Profile::current();
1006 // If this notice is out of scope, no root for you!
1008 if (!$this->inScope($profile)) {
1012 // If this isn't a reply to anything, then it's its own
1015 if (empty($this->reply_to)) {
1019 if (is_null($profile)) {
1020 $keypart = sprintf('notice:conversation_root:%d:null', $this->id);
1022 $keypart = sprintf('notice:conversation_root:%d:%d',
1027 $root = self::cacheGet($keypart);
1029 if ($root !== false && $root->inScope($profile)) {
1036 $parent = $last->getParent();
1037 if ($parent->inScope($profile)) {
1041 } catch (Exception $e) {
1042 // Latest notice has no parent
1044 // No parent, or parent out of scope
1049 self::cacheSet($keypart, $root);
1055 * Pull up a full list of local recipients who will be getting
1056 * this notice in their inbox. Results will be cached, so don't
1057 * change the input data wily-nilly!
1059 * @param array $groups optional list of Group objects;
1060 * if left empty, will be loaded from group_inbox records
1061 * @param array $recipient optional list of reply profile ids
1062 * if left empty, will be loaded from reply records
1063 * @return array associating recipient user IDs with an inbox source constant
1065 function whoGets(array $groups=null, array $recipients=null)
1067 $c = self::memcache();
1070 $ni = $c->get(Cache::key('notice:who_gets:'.$this->id));
1071 if ($ni !== false) {
1076 if (is_null($recipients)) {
1077 $recipients = $this->getReplies();
1082 // Give plugins a chance to add folks in at start...
1083 if (Event::handle('StartNoticeWhoGets', array($this, &$ni))) {
1085 $users = $this->getSubscribedUsers();
1086 foreach ($users as $id) {
1087 $ni[$id] = NOTICE_INBOX_SOURCE_SUB;
1090 if (is_null($groups)) {
1091 $groups = $this->getGroups();
1093 foreach ($groups as $group) {
1094 $users = $group->getUserMembers();
1095 foreach ($users as $id) {
1096 if (!array_key_exists($id, $ni)) {
1097 $ni[$id] = NOTICE_INBOX_SOURCE_GROUP;
1102 $ptAtts = $this->getAttentionsFromProfileTags();
1103 foreach ($ptAtts as $key=>$val) {
1104 if (!array_key_exists($key, $ni)) {
1109 foreach ($recipients as $recipient) {
1110 if (!array_key_exists($recipient, $ni)) {
1111 $ni[$recipient] = NOTICE_INBOX_SOURCE_REPLY;
1115 // Exclude any deleted, non-local, or blocking recipients.
1116 $profile = $this->getProfile();
1117 $originalProfile = null;
1118 if ($this->repeat_of) {
1119 // Check blocks against the original notice's poster as well.
1120 $original = Notice::getKV('id', $this->repeat_of);
1121 if ($original instanceof Notice) {
1122 $originalProfile = $original->getProfile();
1126 foreach ($ni as $id => $source) {
1128 $user = User::getKV('id', $id);
1129 if (!$user instanceof User ||
1130 $user->hasBlocked($profile) ||
1131 ($originalProfile && $user->hasBlocked($originalProfile))) {
1134 } catch (UserNoProfileException $e) {
1135 // User doesn't have a profile; invalid; skip them.
1140 // Give plugins a chance to filter out...
1141 Event::handle('EndNoticeWhoGets', array($this, &$ni));
1145 // XXX: pack this data better
1146 $c->set(Cache::key('notice:who_gets:'.$this->id), $ni);
1152 function getSubscribedUsers()
1156 if(common_config('db','quote_identifiers'))
1157 $user_table = '"user"';
1158 else $user_table = 'user';
1162 'FROM '. $user_table .' JOIN subscription '.
1163 'ON '. $user_table .'.id = subscription.subscriber ' .
1164 'WHERE subscription.subscribed = %d ';
1166 $user->query(sprintf($qry, $this->profile_id));
1170 while ($user->fetch()) {
1179 function getProfileTags()
1181 $profile = $this->getProfile();
1182 $list = $profile->getOtherTags($profile);
1185 while($list->fetch()) {
1186 $ptags[] = clone($list);
1192 public function getAttentionsFromProfileTags()
1195 $ptags = $this->getProfileTags();
1196 foreach ($ptags as $ptag) {
1197 $users = $ptag->getUserSubscribers();
1198 foreach ($users as $id) {
1199 $ni[$id] = NOTICE_INBOX_SOURCE_PROFILE_TAG;
1206 * Record this notice to the given group inboxes for delivery.
1207 * Overrides the regular parsing of !group markup.
1209 * @param string $group_ids
1210 * @fixme might prefer URIs as identifiers, as for replies?
1211 * best with generalizations on user_group to support
1212 * remote groups better.
1214 function saveKnownGroups($group_ids)
1216 if (!is_array($group_ids)) {
1217 // TRANS: Server exception thrown when no array is provided to the method saveKnownGroups().
1218 throw new ServerException(_('Bad type provided to saveKnownGroups.'));
1222 foreach (array_unique($group_ids) as $id) {
1223 $group = User_group::getKV('id', $id);
1224 if ($group instanceof User_group) {
1225 common_log(LOG_ERR, "Local delivery to group id $id, $group->nickname");
1226 $result = $this->addToGroupInbox($group);
1228 common_log_db_error($gi, 'INSERT', __FILE__);
1231 if (common_config('group', 'addtag')) {
1232 // we automatically add a tag for every group name, too
1234 $tag = Notice_tag::pkeyGet(array('tag' => common_canonical_tag($group->nickname),
1235 'notice_id' => $this->id));
1237 if (is_null($tag)) {
1238 $this->saveTag($group->nickname);
1242 $groups[] = clone($group);
1244 common_log(LOG_ERR, "Local delivery to group id $id skipped, doesn't exist");
1251 function addToGroupInbox(User_group $group)
1253 $gi = Group_inbox::pkeyGet(array('group_id' => $group->id,
1254 'notice_id' => $this->id));
1256 if (!$gi instanceof Group_inbox) {
1258 $gi = new Group_inbox();
1260 $gi->group_id = $group->id;
1261 $gi->notice_id = $this->id;
1262 $gi->created = $this->created;
1264 $result = $gi->insert();
1267 common_log_db_error($gi, 'INSERT', __FILE__);
1268 // TRANS: Server exception thrown when an update for a group inbox fails.
1269 throw new ServerException(_('Problem saving group inbox.'));
1272 self::blow('user_group:notice_ids:%d', $gi->group_id);
1279 * Save reply records indicating that this notice needs to be
1280 * delivered to the local users with the given URIs.
1282 * Since this is expected to be used when saving foreign-sourced
1283 * messages, we won't deliver to any remote targets as that's the
1284 * source service's responsibility.
1286 * Mail notifications etc will be handled later.
1288 * @param array $uris Array of unique identifier URIs for recipients
1290 function saveKnownReplies(array $uris)
1296 $sender = Profile::getKV($this->profile_id);
1298 foreach (array_unique($uris) as $uri) {
1300 $profile = Profile::fromUri($uri);
1301 } catch (UnknownUriException $e) {
1302 common_log(LOG_WARNING, "Unable to determine profile for URI '$uri'");
1306 if ($profile->hasBlocked($sender)) {
1307 common_log(LOG_INFO, "Not saving reply to profile {$profile->id} ($uri) from sender {$sender->id} because of a block.");
1311 $this->saveReply($profile->id);
1312 self::blow('reply:stream:%d', $profile->id);
1319 * Pull @-replies from this message's content in StatusNet markup format
1320 * and save reply records indicating that this message needs to be
1321 * delivered to those users.
1323 * Mail notifications to local profiles will be sent later.
1325 * @return array of integer profile IDs
1328 function saveReplies()
1330 // Don't save reply data for repeats
1332 if (!empty($this->repeat_of)) {
1336 $sender = $this->getProfile();
1340 // If it's a reply, save for the replied-to author
1342 $parent = $this->getParent();
1343 $parentauthor = $parent->getProfile();
1344 $this->saveReply($parentauthor->id);
1345 $replied[$parentauthor->id] = 1;
1346 self::blow('reply:stream:%d', $parentauthor->id);
1347 } catch (Exception $e) {
1348 // Not a reply, since it has no parent!
1351 // @todo ideally this parser information would only
1352 // be calculated once.
1354 $mentions = common_find_mentions($this->content, $this);
1356 // store replied only for first @ (what user/notice what the reply directed,
1357 // we assume first @ is it)
1359 foreach ($mentions as $mention) {
1361 foreach ($mention['mentioned'] as $mentioned) {
1363 // skip if they're already covered
1365 if (!empty($replied[$mentioned->id])) {
1369 // Don't save replies from blocked profile to local user
1371 $mentioned_user = User::getKV('id', $mentioned->id);
1372 if ($mentioned_user instanceof User && $mentioned_user->hasBlocked($sender)) {
1376 $this->saveReply($mentioned->id);
1377 $replied[$mentioned->id] = 1;
1378 self::blow('reply:stream:%d', $mentioned->id);
1382 $recipientIds = array_keys($replied);
1384 return $recipientIds;
1387 function saveReply($profileId)
1389 $reply = new Reply();
1391 $reply->notice_id = $this->id;
1392 $reply->profile_id = $profileId;
1393 $reply->modified = $this->created;
1400 protected $_replies = array();
1403 * Pull the complete list of @-reply targets for this notice.
1405 * @return array of integer profile ids
1407 function getReplies()
1409 if (isset($this->_replies[$this->id])) {
1410 return $this->_replies[$this->id];
1413 $replyMap = Reply::listGet('notice_id', array($this->id));
1417 foreach ($replyMap[$this->id] as $reply) {
1418 $ids[] = $reply->profile_id;
1421 $this->_replies[$this->id] = $ids;
1426 function _setReplies($replies)
1428 $this->_replies[$this->id] = $replies;
1432 * Pull the complete list of @-reply targets for this notice.
1434 * @return array of Profiles
1436 function getReplyProfiles()
1438 $ids = $this->getReplies();
1440 $profiles = Profile::multiGet('id', $ids);
1442 return $profiles->fetchAll();
1446 * Send e-mail notifications to local @-reply targets.
1448 * Replies must already have been saved; this is expected to be run
1449 * from the distrib queue handler.
1451 function sendReplyNotifications()
1453 // Don't send reply notifications for repeats
1455 if (!empty($this->repeat_of)) {
1459 $recipientIds = $this->getReplies();
1461 foreach ($recipientIds as $recipientId) {
1462 $user = User::getKV('id', $recipientId);
1463 if ($user instanceof User) {
1464 mail_notify_attn($user, $this);
1470 * Pull list of groups this notice needs to be delivered to,
1471 * as previously recorded by saveKnownGroups().
1473 * @return array of Group objects
1476 protected $_groups = array();
1478 function getGroups()
1480 // Don't save groups for repeats
1482 if (!empty($this->repeat_of)) {
1486 if (isset($this->_groups[$this->id])) {
1487 return $this->_groups[$this->id];
1490 $gis = Group_inbox::listGet('notice_id', array($this->id));
1494 foreach ($gis[$this->id] as $gi)
1496 $ids[] = $gi->group_id;
1499 $groups = User_group::multiGet('id', $ids);
1501 $this->_groups[$this->id] = $groups->fetchAll();
1503 return $this->_groups[$this->id];
1506 function _setGroups($groups)
1508 $this->_groups[$this->id] = $groups;
1512 * Convert a notice into an activity for export.
1514 * @param User $cur Current user
1516 * @return Activity activity object representing this Notice.
1519 function asActivity($cur=null)
1521 $act = self::cacheGet(Cache::codeKey('notice:as-activity:'.$this->id));
1523 if ($act instanceof Activity) {
1526 $act = new Activity();
1528 if (Event::handle('StartNoticeAsActivity', array($this, &$act))) {
1530 $act->id = $this->uri;
1531 $act->time = strtotime($this->created);
1533 $act->link = $this->getUrl();
1534 } catch (InvalidUrlException $e) {
1535 // The notice is probably a share or similar, which don't
1536 // have a representational URL of their own.
1538 $act->content = common_xml_safe_str($this->rendered);
1540 $profile = $this->getProfile();
1542 $act->actor = ActivityObject::fromProfile($profile);
1543 $act->actor->extra[] = $profile->profileInfo($cur);
1545 $act->verb = $this->verb;
1547 if ($this->repeat_of) {
1548 $repeated = Notice::getKV('id', $this->repeat_of);
1549 if ($repeated instanceof Notice) {
1550 $act->objects[] = $repeated->asActivity($cur);
1553 $act->objects[] = ActivityObject::fromNotice($this);
1556 // XXX: should this be handled by default processing for object entry?
1560 $tags = $this->getTags();
1562 foreach ($tags as $tag) {
1563 $cat = new AtomCategory();
1566 $act->categories[] = $cat;
1570 // XXX: use Atom Media and/or File activity objects instead
1572 $attachments = $this->attachments();
1574 foreach ($attachments as $attachment) {
1575 // Save local attachments
1576 if (!empty($attachment->filename)) {
1577 $act->attachments[] = ActivityObject::fromFile($attachment);
1581 $ctx = new ActivityContext();
1584 $reply = $this->getParent();
1585 $ctx->replyToID = $reply->getUri();
1586 $ctx->replyToUrl = $reply->getUrl();
1587 } catch (Exception $e) {
1588 // This is not a reply to something
1591 $ctx->location = $this->getLocation();
1595 if (!empty($this->conversation)) {
1596 $conv = Conversation::getKV('id', $this->conversation);
1597 if ($conv instanceof Conversation) {
1598 $ctx->conversation = $conv->uri;
1602 $reply_ids = $this->getReplies();
1604 foreach ($reply_ids as $id) {
1605 $rprofile = Profile::getKV('id', $id);
1606 if ($rprofile instanceof Profile) {
1607 $ctx->attention[$rprofile->getUri()] = ActivityObject::PERSON;
1611 $groups = $this->getGroups();
1613 foreach ($groups as $group) {
1614 $ctx->attention[$group->getUri()] = ActivityObject::GROUP;
1617 switch ($this->scope) {
1618 case Notice::PUBLIC_SCOPE:
1619 $ctx->attention[ActivityContext::ATTN_PUBLIC] = ActivityObject::COLLECTION;
1621 case Notice::FOLLOWER_SCOPE:
1622 $surl = common_local_url("subscribers", array('nickname' => $profile->nickname));
1623 $ctx->attention[$surl] = ActivityObject::COLLECTION;
1627 $act->context = $ctx;
1629 $source = $this->getSource();
1631 if ($source instanceof Notice_source) {
1632 $act->generator = ActivityObject::fromNoticeSource($source);
1637 $atom_feed = $profile->getAtomFeed();
1639 if (!empty($atom_feed)) {
1641 $act->source = new ActivitySource();
1643 // XXX: we should store the actual feed ID
1645 $act->source->id = $atom_feed;
1647 // XXX: we should store the actual feed title
1649 $act->source->title = $profile->getBestName();
1651 $act->source->links['alternate'] = $profile->profileurl;
1652 $act->source->links['self'] = $atom_feed;
1654 $act->source->icon = $profile->avatarUrl(AVATAR_PROFILE_SIZE);
1656 $notice = $profile->getCurrentNotice();
1658 if ($notice instanceof Notice) {
1659 $act->source->updated = self::utcDate($notice->created);
1662 $user = User::getKV('id', $profile->id);
1664 if ($user instanceof User) {
1665 $act->source->links['license'] = common_config('license', 'url');
1669 if ($this->isLocal()) {
1670 $act->selfLink = common_local_url('ApiStatusesShow', array('id' => $this->id,
1671 'format' => 'atom'));
1672 $act->editLink = $act->selfLink;
1675 Event::handle('EndNoticeAsActivity', array($this, &$act));
1678 self::cacheSet(Cache::codeKey('notice:as-activity:'.$this->id), $act);
1683 // This has gotten way too long. Needs to be sliced up into functional bits
1684 // or ideally exported to a utility class.
1686 function asAtomEntry($namespace=false,
1691 $act = $this->asActivity($cur);
1692 $act->extra[] = $this->noticeInfo($cur);
1693 return $act->asString($namespace, $author, $source);
1697 * Extra notice info for atom entries
1699 * Clients use some extra notice info in the atom stream.
1700 * This gives it to them.
1702 * @param User $cur Current user
1704 * @return array representation of <statusnet:notice_info> element
1707 function noticeInfo($cur)
1709 // local notice ID (useful to clients for ordering)
1711 $noticeInfoAttr = array('local_id' => $this->id);
1715 $ns = $this->getSource();
1717 if ($ns instanceof Notice_source) {
1718 $noticeInfoAttr['source'] = $ns->code;
1719 if (!empty($ns->url)) {
1720 $noticeInfoAttr['source_link'] = $ns->url;
1721 if (!empty($ns->name)) {
1722 $noticeInfoAttr['source'] = '<a href="'
1723 . htmlspecialchars($ns->url)
1724 . '" rel="nofollow">'
1725 . htmlspecialchars($ns->name)
1731 // favorite and repeated
1734 $cp = $cur->getProfile();
1735 $noticeInfoAttr['favorite'] = ($cp->hasFave($this)) ? "true" : "false";
1736 $noticeInfoAttr['repeated'] = ($cp->hasRepeated($this)) ? "true" : "false";
1739 if (!empty($this->repeat_of)) {
1740 $noticeInfoAttr['repeat_of'] = $this->repeat_of;
1743 return array('statusnet:notice_info', $noticeInfoAttr, null);
1747 * Returns an XML string fragment with a reference to a notice as an
1748 * Activity Streams noun object with the given element type.
1750 * Assumes that 'activity' namespace has been previously defined.
1752 * @param string $element one of 'subject', 'object', 'target'
1756 function asActivityNoun($element)
1758 $noun = ActivityObject::fromNotice($this);
1759 return $noun->asString('activity:' . $element);
1763 * Determine which notice, if any, a new notice is in reply to.
1765 * For conversation tracking, we try to see where this notice fits
1766 * in the tree. Beware that this may very well give false positives
1767 * and add replies to wrong threads (if there have been newer posts
1768 * by the same user as we're replying to).
1770 * @param Profile $sender Author profile
1771 * @param string $content Final notice content
1773 * @return integer ID of replied-to notice, or null for not a reply.
1776 static function getInlineReplyTo(Profile $sender, $content)
1778 // Is there an initial @ or T?
1779 if (preg_match('/^T ([A-Z0-9]{1,64}) /', $content, $match)
1780 || preg_match('/^@([a-z0-9]{1,64})\s+/', $content, $match)) {
1781 $nickname = common_canonical_nickname($match[1]);
1786 // Figure out who that is.
1787 $recipient = common_relative_profile($sender, $nickname, common_sql_now());
1789 if ($recipient instanceof Profile) {
1790 // Get their last notice
1791 $last = $recipient->getCurrentNotice();
1792 if ($last instanceof Notice) {
1795 // Maybe in the future we want to handle something else below
1796 // so don't return getCurrentNotice() immediately.
1802 static function maxContent()
1804 $contentlimit = common_config('notice', 'contentlimit');
1805 // null => use global limit (distinct from 0!)
1806 if (is_null($contentlimit)) {
1807 $contentlimit = common_config('site', 'textlimit');
1809 return $contentlimit;
1812 static function contentTooLong($content)
1814 $contentlimit = self::maxContent();
1815 return ($contentlimit > 0 && !empty($content) && (mb_strlen($content) > $contentlimit));
1818 function getLocation()
1822 if (!empty($this->location_id) && !empty($this->location_ns)) {
1823 $location = Location::fromId($this->location_id, $this->location_ns);
1826 if (is_null($location)) { // no ID, or Location::fromId() failed
1827 if (!empty($this->lat) && !empty($this->lon)) {
1828 $location = Location::fromLatLon($this->lat, $this->lon);
1836 * Convenience function for posting a repeat of an existing message.
1838 * @param Profile $repeater Profile which is doing the repeat
1839 * @param string $source: posting source key, eg 'web', 'api', etc
1842 * @throws Exception on failure or permission problems
1844 function repeat(Profile $repeater, $source)
1846 $author = $this->getProfile();
1848 // TRANS: Message used to repeat a notice. RT is the abbreviation of 'retweet'.
1849 // TRANS: %1$s is the repeated user's name, %2$s is the repeated notice.
1850 $content = sprintf(_('RT @%1$s %2$s'),
1851 $author->getNickname(),
1854 // Scope is same as this one's
1855 return self::saveNew($repeater->id,
1858 array('repeat_of' => $this->id,
1859 'scope' => $this->scope));
1862 // These are supposed to be in chron order!
1864 function repeatStream($limit=100)
1866 $cache = Cache::instance();
1868 if (empty($cache)) {
1869 $ids = $this->_repeatStreamDirect($limit);
1871 $idstr = $cache->get(Cache::key('notice:repeats:'.$this->id));
1872 if ($idstr !== false) {
1873 if (empty($idstr)) {
1876 $ids = explode(',', $idstr);
1879 $ids = $this->_repeatStreamDirect(100);
1880 $cache->set(Cache::key('notice:repeats:'.$this->id), implode(',', $ids));
1883 // We do a max of 100, so slice down to limit
1884 $ids = array_slice($ids, 0, $limit);
1888 return NoticeStream::getStreamByIds($ids);
1891 function _repeatStreamDirect($limit)
1893 $notice = new Notice();
1895 $notice->selectAdd(); // clears it
1896 $notice->selectAdd('id');
1898 $notice->repeat_of = $this->id;
1900 $notice->orderBy('created, id'); // NB: asc!
1902 if (!is_null($limit)) {
1903 $notice->limit(0, $limit);
1906 return $notice->fetchAll('id');
1909 function locationOptions($lat, $lon, $location_id, $location_ns, $profile = null)
1913 if (!empty($location_id) && !empty($location_ns)) {
1914 $options['location_id'] = $location_id;
1915 $options['location_ns'] = $location_ns;
1917 $location = Location::fromId($location_id, $location_ns);
1919 if ($location instanceof Location) {
1920 $options['lat'] = $location->lat;
1921 $options['lon'] = $location->lon;
1924 } else if (!empty($lat) && !empty($lon)) {
1925 $options['lat'] = $lat;
1926 $options['lon'] = $lon;
1928 $location = Location::fromLatLon($lat, $lon);
1930 if ($location instanceof Location) {
1931 $options['location_id'] = $location->location_id;
1932 $options['location_ns'] = $location->location_ns;
1934 } else if (!empty($profile)) {
1935 if (isset($profile->lat) && isset($profile->lon)) {
1936 $options['lat'] = $profile->lat;
1937 $options['lon'] = $profile->lon;
1940 if (isset($profile->location_id) && isset($profile->location_ns)) {
1941 $options['location_id'] = $profile->location_id;
1942 $options['location_ns'] = $profile->location_ns;
1949 function clearAttentions()
1951 $att = new Attention();
1952 $att->notice_id = $this->getID();
1955 while ($att->fetch()) {
1956 // Can't do delete() on the object directly since it won't remove all of it
1957 $other = clone($att);
1963 function clearReplies()
1965 $replyNotice = new Notice();
1966 $replyNotice->reply_to = $this->id;
1968 //Null any notices that are replies to this notice
1970 if ($replyNotice->find()) {
1971 while ($replyNotice->fetch()) {
1972 $orig = clone($replyNotice);
1973 $replyNotice->reply_to = null;
1974 $replyNotice->update($orig);
1980 $reply = new Reply();
1981 $reply->notice_id = $this->id;
1983 if ($reply->find()) {
1984 while($reply->fetch()) {
1985 self::blow('reply:stream:%d', $reply->profile_id);
1993 function clearFiles()
1995 $f2p = new File_to_post();
1997 $f2p->post_id = $this->id;
2000 while ($f2p->fetch()) {
2004 // FIXME: decide whether to delete File objects
2005 // ...and related (actual) files
2008 function clearRepeats()
2010 $repeatNotice = new Notice();
2011 $repeatNotice->repeat_of = $this->id;
2013 //Null any notices that are repeats of this notice
2015 if ($repeatNotice->find()) {
2016 while ($repeatNotice->fetch()) {
2017 $orig = clone($repeatNotice);
2018 $repeatNotice->repeat_of = null;
2019 $repeatNotice->update($orig);
2024 function clearFaves()
2027 $fave->notice_id = $this->id;
2029 if ($fave->find()) {
2030 while ($fave->fetch()) {
2031 self::blow('fave:ids_by_user_own:%d', $fave->user_id);
2032 self::blow('fave:ids_by_user_own:%d;last', $fave->user_id);
2033 self::blow('fave:ids_by_user:%d', $fave->user_id);
2034 self::blow('fave:ids_by_user:%d;last', $fave->user_id);
2042 function clearTags()
2044 $tag = new Notice_tag();
2045 $tag->notice_id = $this->id;
2048 while ($tag->fetch()) {
2049 self::blow('profile:notice_ids_tagged:%d:%s', $this->profile_id, Cache::keyize($tag->tag));
2050 self::blow('profile:notice_ids_tagged:%d:%s;last', $this->profile_id, Cache::keyize($tag->tag));
2051 self::blow('notice_tag:notice_ids:%s', Cache::keyize($tag->tag));
2052 self::blow('notice_tag:notice_ids:%s;last', Cache::keyize($tag->tag));
2060 function clearGroupInboxes()
2062 $gi = new Group_inbox();
2064 $gi->notice_id = $this->id;
2067 while ($gi->fetch()) {
2068 self::blow('user_group:notice_ids:%d', $gi->group_id);
2076 function distribute()
2078 // We always insert for the author so they don't
2080 Event::handle('StartNoticeDistribute', array($this));
2082 // If there's a failure, we want to _force_
2083 // distribution at this point.
2085 $qm = QueueManager::get();
2086 $qm->enqueue($this, 'distrib');
2087 } catch (Exception $e) {
2088 // If the exception isn't transient, this
2089 // may throw more exceptions as DQH does
2090 // its own enqueueing. So, we ignore them!
2092 $handler = new DistribQueueHandler();
2093 $handler->handle($this);
2094 } catch (Exception $e) {
2095 common_log(LOG_ERR, "emergency redistribution resulted in " . $e->getMessage());
2097 // Re-throw so somebody smarter can handle it.
2104 $result = parent::insert();
2106 if ($result !== false) {
2107 // Profile::hasRepeated() abuses pkeyGet(), so we
2108 // have to clear manually
2109 if (!empty($this->repeat_of)) {
2110 $c = self::memcache();
2112 $ck = self::multicacheKey('Notice',
2113 array('profile_id' => $this->profile_id,
2114 'repeat_of' => $this->repeat_of));
2124 * Get the source of the notice
2126 * @return Notice_source $ns A notice source object. 'code' is the only attribute
2127 * guaranteed to be populated.
2129 function getSource()
2131 $ns = new Notice_source();
2132 if (!empty($this->source)) {
2133 switch ($this->source) {
2140 $ns->code = $this->source;
2143 $ns = Notice_source::getKV($this->source);
2145 $ns = new Notice_source();
2146 $ns->code = $this->source;
2147 $app = Oauth_application::getKV('name', $this->source);
2149 $ns->name = $app->name;
2150 $ns->url = $app->source_url;
2160 * Determine whether the notice was locally created
2162 * @return boolean locality
2165 public function isLocal()
2167 return ($this->is_local == Notice::LOCAL_PUBLIC ||
2168 $this->is_local == Notice::LOCAL_NONPUBLIC);
2172 * Get the list of hash tags saved with this notice.
2174 * @return array of strings
2176 public function getTags()
2180 $keypart = sprintf('notice:tags:%d', $this->id);
2182 $tagstr = self::cacheGet($keypart);
2184 if ($tagstr !== false) {
2185 $tags = explode(',', $tagstr);
2187 $tag = new Notice_tag();
2188 $tag->notice_id = $this->id;
2190 while ($tag->fetch()) {
2191 $tags[] = $tag->tag;
2194 self::cacheSet($keypart, implode(',', $tags));
2200 static private function utcDate($dt)
2202 $dateStr = date('d F Y H:i:s', strtotime($dt));
2203 $d = new DateTime($dateStr, new DateTimeZone('UTC'));
2204 return $d->format(DATE_W3C);
2208 * Look up the creation timestamp for a given notice ID, even
2209 * if it's been deleted.
2212 * @return mixed string recorded creation timestamp, or false if can't be found
2214 public static function getAsTimestamp($id)
2220 $notice = Notice::getKV('id', $id);
2222 return $notice->created;
2225 $deleted = Deleted_notice::getKV('id', $id);
2227 return $deleted->created;
2234 * Build an SQL 'where' fragment for timestamp-based sorting from a since_id
2235 * parameter, matching notices posted after the given one (exclusive).
2237 * If the referenced notice can't be found, will return false.
2240 * @param string $idField
2241 * @param string $createdField
2242 * @return mixed string or false if no match
2244 public static function whereSinceId($id, $idField='id', $createdField='created')
2246 $since = Notice::getAsTimestamp($id);
2248 return sprintf("($createdField = '%s' and $idField > %d) or ($createdField > '%s')", $since, $id, $since);
2254 * Build an SQL 'where' fragment for timestamp-based sorting from a since_id
2255 * parameter, matching notices posted after the given one (exclusive), and
2256 * if necessary add it to the data object's query.
2258 * @param DB_DataObject $obj
2260 * @param string $idField
2261 * @param string $createdField
2262 * @return mixed string or false if no match
2264 public static function addWhereSinceId(DB_DataObject $obj, $id, $idField='id', $createdField='created')
2266 $since = self::whereSinceId($id, $idField, $createdField);
2268 $obj->whereAdd($since);
2273 * Build an SQL 'where' fragment for timestamp-based sorting from a max_id
2274 * parameter, matching notices posted before the given one (inclusive).
2276 * If the referenced notice can't be found, will return false.
2279 * @param string $idField
2280 * @param string $createdField
2281 * @return mixed string or false if no match
2283 public static function whereMaxId($id, $idField='id', $createdField='created')
2285 $max = Notice::getAsTimestamp($id);
2287 return sprintf("($createdField < '%s') or ($createdField = '%s' and $idField <= %d)", $max, $max, $id);
2293 * Build an SQL 'where' fragment for timestamp-based sorting from a max_id
2294 * parameter, matching notices posted before the given one (inclusive), and
2295 * if necessary add it to the data object's query.
2297 * @param DB_DataObject $obj
2299 * @param string $idField
2300 * @param string $createdField
2301 * @return mixed string or false if no match
2303 public static function addWhereMaxId(DB_DataObject $obj, $id, $idField='id', $createdField='created')
2305 $max = self::whereMaxId($id, $idField, $createdField);
2307 $obj->whereAdd($max);
2313 if (common_config('public', 'localonly')) {
2314 return ($this->is_local == Notice::LOCAL_PUBLIC);
2316 return (($this->is_local != Notice::LOCAL_NONPUBLIC) &&
2317 ($this->is_local != Notice::GATEWAY));
2322 * Check that the given profile is allowed to read, respond to, or otherwise
2323 * act on this notice.
2325 * The $scope member is a bitmask of scopes, representing a logical AND of the
2326 * scope requirement. So, 0x03 (Notice::ADDRESSEE_SCOPE | Notice::SITE_SCOPE) means
2327 * "only visible to people who are mentioned in the notice AND are users on this site."
2328 * Users on the site who are not mentioned in the notice will not be able to see the
2331 * @param Profile $profile The profile to check; pass null to check for public/unauthenticated users.
2333 * @return boolean whether the profile is in the notice's scope
2335 function inScope($profile)
2337 if (is_null($profile)) {
2338 $keypart = sprintf('notice:in-scope-for:%d:null', $this->id);
2340 $keypart = sprintf('notice:in-scope-for:%d:%d', $this->id, $profile->id);
2343 $result = self::cacheGet($keypart);
2345 if ($result === false) {
2347 if (Event::handle('StartNoticeInScope', array($this, $profile, &$bResult))) {
2348 $bResult = $this->_inScope($profile);
2349 Event::handle('EndNoticeInScope', array($this, $profile, &$bResult));
2351 $result = ($bResult) ? 1 : 0;
2352 self::cacheSet($keypart, $result, 0, 300);
2355 return ($result == 1) ? true : false;
2358 protected function _inScope($profile)
2360 if (!is_null($this->scope)) {
2361 $scope = $this->scope;
2363 $scope = self::defaultScope();
2366 // If there's no scope, anyone (even anon) is in scope.
2368 if ($scope == 0) { // Not private
2370 return !$this->isHiddenSpam($profile);
2372 } else { // Private, somehow
2374 // If there's scope, anon cannot be in scope
2376 if (empty($profile)) {
2380 // Author is always in scope
2382 if ($this->profile_id == $profile->id) {
2386 // Only for users on this site
2388 if (($scope & Notice::SITE_SCOPE) && !$profile->isLocal()) {
2392 // Only for users mentioned in the notice
2394 if ($scope & Notice::ADDRESSEE_SCOPE) {
2396 $reply = Reply::pkeyGet(array('notice_id' => $this->id,
2397 'profile_id' => $profile->id));
2399 if (!$reply instanceof Reply) {
2404 // Only for members of the given group
2406 if ($scope & Notice::GROUP_SCOPE) {
2408 // XXX: just query for the single membership
2410 $groups = $this->getGroups();
2414 foreach ($groups as $group) {
2415 if ($profile->isMember($group)) {
2426 // Only for followers of the author
2430 if ($scope & Notice::FOLLOWER_SCOPE) {
2433 $author = $this->getProfile();
2434 } catch (Exception $e) {
2438 if (!Subscription::exists($profile, $author)) {
2443 return !$this->isHiddenSpam($profile);
2447 function isHiddenSpam($profile) {
2449 // Hide posts by silenced users from everyone but moderators.
2451 if (common_config('notice', 'hidespam')) {
2454 $author = $this->getProfile();
2455 } catch(Exception $e) {
2456 // If we can't get an author, keep it hidden.
2457 // XXX: technically not spam, but, whatever.
2461 if ($author->hasRole(Profile_role::SILENCED)) {
2462 if (!$profile instanceof Profile || (($profile->id !== $author->id) && (!$profile->hasRight(Right::REVIEWSPAM)))) {
2471 public function getParent()
2473 $parent = Notice::getKV('id', $this->reply_to);
2475 if (!$parent instanceof Notice) {
2476 throw new ServerException('Notice has no parent');
2483 * Magic function called at serialize() time.
2485 * We use this to drop a couple process-specific references
2486 * from DB_DataObject which can cause trouble in future
2489 * @return array of variable names to include in serialization.
2494 $vars = parent::__sleep();
2495 $skip = array('_profile', '_groups', '_attachments', '_faves', '_replies', '_repeats');
2496 return array_diff($vars, $skip);
2499 static function defaultScope()
2501 $scope = common_config('notice', 'defaultscope');
2502 if (is_null($scope)) {
2503 if (common_config('site', 'private')) {
2512 static function fillProfiles($notices)
2514 $map = self::getProfiles($notices);
2516 foreach ($notices as $entry=>$notice) {
2518 if (array_key_exists($notice->profile_id, $map)) {
2519 $notice->_setProfile($map[$notice->profile_id]);
2521 } catch (NoProfileException $e) {
2522 common_log(LOG_WARNING, "Failed to fill profile in Notice with non-existing entry for profile_id: {$e->profile_id}");
2523 unset($notices[$entry]);
2527 return array_values($map);
2530 static function getProfiles(&$notices)
2533 foreach ($notices as $notice) {
2534 $ids[] = $notice->profile_id;
2537 $ids = array_unique($ids);
2539 return Profile::pivotGet('id', $ids);
2542 static function fillGroups(&$notices)
2544 $ids = self::_idsOf($notices);
2546 $gis = Group_inbox::listGet('notice_id', $ids);
2550 foreach ($gis as $id => $gi)
2554 $gids[] = $g->group_id;
2558 $gids = array_unique($gids);
2560 $group = User_group::pivotGet('id', $gids);
2562 foreach ($notices as $notice)
2565 $gi = $gis[$notice->id];
2566 foreach ($gi as $g) {
2567 $grps[] = $group[$g->group_id];
2569 $notice->_setGroups($grps);
2573 static function _idsOf(&$notices)
2576 foreach ($notices as $notice) {
2577 $ids[] = $notice->id;
2579 $ids = array_unique($ids);
2583 static function fillAttachments(&$notices)
2585 $ids = self::_idsOf($notices);
2587 $f2pMap = File_to_post::listGet('post_id', $ids);
2591 foreach ($f2pMap as $noticeId => $f2ps) {
2592 foreach ($f2ps as $f2p) {
2593 $fileIds[] = $f2p->file_id;
2597 $fileIds = array_unique($fileIds);
2599 $fileMap = File::pivotGet('id', $fileIds);
2601 foreach ($notices as $notice)
2604 $f2ps = $f2pMap[$notice->id];
2605 foreach ($f2ps as $f2p) {
2606 $files[] = $fileMap[$f2p->file_id];
2608 $notice->_setAttachments($files);
2612 protected $_faves = array();
2615 * All faves of this notice
2617 * @return array Array of Fave objects
2622 if (isset($this->_faves[$this->id])) {
2623 return $this->_faves[$this->id];
2625 $faveMap = Fave::listGet('notice_id', array($this->id));
2626 $this->_faves[$this->id] = $faveMap[$this->id];
2627 return $this->_faves[$this->id];
2630 function _setFaves($faves)
2632 $this->_faves[$this->id] = $faves;
2635 static function fillFaves(&$notices)
2637 $ids = self::_idsOf($notices);
2638 $faveMap = Fave::listGet('notice_id', $ids);
2641 foreach ($faveMap as $id => $faves) {
2642 $cnt += count($faves);
2643 if (count($faves) > 0) {
2647 foreach ($notices as $notice) {
2648 $faves = $faveMap[$notice->id];
2649 $notice->_setFaves($faves);
2653 static function fillReplies(&$notices)
2655 $ids = self::_idsOf($notices);
2656 $replyMap = Reply::listGet('notice_id', $ids);
2657 foreach ($notices as $notice) {
2658 $replies = $replyMap[$notice->id];
2660 foreach ($replies as $reply) {
2661 $ids[] = $reply->profile_id;
2663 $notice->_setReplies($ids);
2667 protected $_repeats = array();
2669 function getRepeats()
2671 if (isset($this->_repeats[$this->id])) {
2672 return $this->_repeats[$this->id];
2674 $repeatMap = Notice::listGet('repeat_of', array($this->id));
2675 $this->_repeats[$this->id] = $repeatMap[$this->id];
2676 return $this->_repeats[$this->id];
2679 function _setRepeats($repeats)
2681 $this->_repeats[$this->id] = $repeats;
2684 static function fillRepeats(&$notices)
2686 $ids = self::_idsOf($notices);
2687 $repeatMap = Notice::listGet('repeat_of', $ids);
2688 foreach ($notices as $notice) {
2689 $repeats = $repeatMap[$notice->id];
2690 $notice->_setRepeats($repeats);