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 * @copyright 2009 Free Software Foundation, Inc http://www.fsf.org
33 * @license GNU Affero General Public License http://www.gnu.org/licenses/
36 if (!defined('STATUSNET') && !defined('LACONICA')) {
41 * Table Definition for notice
43 require_once INSTALLDIR.'/classes/Memcached_DataObject.php';
45 /* We keep 200 notices, the max number of notices available per API request,
46 * in the memcached cache. */
48 define('NOTICE_CACHE_WINDOW', CachingNoticeStream::CACHE_WINDOW);
50 define('MAX_BOXCARS', 128);
52 class Notice extends Managed_DataObject
55 /* the code below is auto generated do not remove the above tag */
57 public $__table = 'notice'; // table name
58 public $id; // int(4) primary_key not_null
59 public $profile_id; // int(4) multiple_key not_null
60 public $uri; // varchar(255) unique_key
61 public $content; // text
62 public $rendered; // text
63 public $url; // varchar(255)
64 public $created; // datetime multiple_key not_null default_0000-00-00%2000%3A00%3A00
65 public $modified; // timestamp not_null default_CURRENT_TIMESTAMP
66 public $reply_to; // int(4)
67 public $is_local; // int(4)
68 public $source; // varchar(32)
69 public $conversation; // int(4)
70 public $lat; // decimal(10,7)
71 public $lon; // decimal(10,7)
72 public $location_id; // int(4)
73 public $location_ns; // int(4)
74 public $repeat_of; // int(4)
75 public $verb; // varchar(255)
76 public $object_type; // varchar(255)
77 public $scope; // int(4)
79 /* the code above is auto generated do not remove the tag below */
82 public static function schemaDef()
86 'id' => array('type' => 'serial', 'not null' => true, 'description' => 'unique identifier'),
87 'profile_id' => array('type' => 'int', 'not null' => true, 'description' => 'who made the update'),
88 'uri' => array('type' => 'varchar', 'length' => 255, 'description' => 'universally unique identifier, usually a tag URI'),
89 'content' => array('type' => 'text', 'description' => 'update content', 'collate' => 'utf8_general_ci'),
90 'rendered' => array('type' => 'text', 'description' => 'HTML version of the content'),
91 'url' => array('type' => 'varchar', 'length' => 255, 'description' => 'URL of any attachment (image, video, bookmark, whatever)'),
92 'created' => array('type' => 'datetime', 'not null' => true, 'description' => 'date this record was created'),
93 'modified' => array('type' => 'timestamp', 'not null' => true, 'description' => 'date this record was modified'),
94 'reply_to' => array('type' => 'int', 'description' => 'notice replied to (usually a guess)'),
95 'is_local' => array('type' => 'int', 'size' => 'tiny', 'default' => 0, 'description' => 'notice was generated by a user'),
96 'source' => array('type' => 'varchar', 'length' => 32, 'description' => 'source of comment, like "web", "im", or "clientname"'),
97 'conversation' => array('type' => 'int', 'description' => 'id of root notice in this conversation'),
98 'lat' => array('type' => 'numeric', 'precision' => 10, 'scale' => 7, 'description' => 'latitude'),
99 'lon' => array('type' => 'numeric', 'precision' => 10, 'scale' => 7, 'description' => 'longitude'),
100 'location_id' => array('type' => 'int', 'description' => 'location id if possible'),
101 'location_ns' => array('type' => 'int', 'description' => 'namespace for location'),
102 'repeat_of' => array('type' => 'int', 'description' => 'notice this is a repeat of'),
103 'object_type' => array('type' => 'varchar', 'length' => 255, 'description' => 'URI representing activity streams object type', 'default' => 'http://activitystrea.ms/schema/1.0/note'),
104 'verb' => array('type' => 'varchar', 'length' => 255, 'description' => 'URI representing activity streams verb', 'default' => 'http://activitystrea.ms/schema/1.0/post'),
105 'scope' => array('type' => 'int',
106 'description' => 'bit map for distribution scope; 0 = everywhere; 1 = this server only; 2 = addressees; 4 = followers; null = default'),
108 'primary key' => array('id'),
109 'unique keys' => array(
110 'notice_uri_key' => array('uri'),
112 'foreign keys' => array(
113 'notice_profile_id_fkey' => array('profile', array('profile_id' => 'id')),
114 'notice_reply_to_fkey' => array('notice', array('reply_to' => 'id')),
115 'notice_conversation_fkey' => array('conversation', array('conversation' => 'id')), # note... used to refer to notice.id
116 'notice_repeat_of_fkey' => array('notice', array('repeat_of' => 'id')), # @fixme: what about repeats of deleted notices?
119 'notice_created_id_is_local_idx' => array('created', 'id', 'is_local'),
120 'notice_profile_id_idx' => array('profile_id', 'created', 'id'),
121 'notice_repeat_of_created_id_idx' => array('repeat_of', 'created', 'id'),
122 'notice_conversation_created_id_idx' => array('conversation', 'created', 'id'),
123 'notice_replyto_idx' => array('reply_to')
127 if (common_config('search', 'type') == 'fulltext') {
128 $def['fulltext indexes'] = array('content' => array('content'));
135 const LOCAL_PUBLIC = 1;
137 const LOCAL_NONPUBLIC = -1;
140 const PUBLIC_SCOPE = 0; // Useful fake constant
141 const SITE_SCOPE = 1;
142 const ADDRESSEE_SCOPE = 2;
143 const GROUP_SCOPE = 4;
144 const FOLLOWER_SCOPE = 8;
146 protected $_profile = -1;
148 function getProfile()
150 if (is_int($this->_profile) && $this->_profile == -1) {
151 $this->_setProfile(Profile::getKV('id', $this->profile_id));
153 if (empty($this->_profile)) {
154 // TRANS: Server exception thrown when a user profile for a notice cannot be found.
155 // TRANS: %1$d is a profile ID (number), %2$d is a notice ID (number).
156 throw new ServerException(sprintf(_('No such profile (%1$d) for notice (%2$d).'), $this->profile_id, $this->id));
160 return $this->_profile;
163 function _setProfile($profile)
165 $this->_profile = $profile;
170 // For auditing purposes, save a record that the notice
173 // @fixme we have some cases where things get re-run and so the
175 $deleted = Deleted_notice::getKV('id', $this->id);
178 $deleted = Deleted_notice::getKV('uri', $this->uri);
182 $deleted = new Deleted_notice();
184 $deleted->id = $this->id;
185 $deleted->profile_id = $this->profile_id;
186 $deleted->uri = $this->uri;
187 $deleted->created = $this->created;
188 $deleted->deleted = common_sql_now();
193 if (Event::handle('NoticeDeleteRelated', array($this))) {
195 // Clear related records
197 $this->clearReplies();
198 $this->clearRepeats();
201 $this->clearGroupInboxes();
204 // NOTE: we don't clear inboxes
205 // NOTE: we don't clear queue items
208 $result = parent::delete();
210 $this->blowOnDelete();
214 public function getUri()
219 public function getUrl()
221 // The risk is we start having empty urls and non-http uris...
222 return $this->url ?: $this->uri;
226 * Extract #hashtags from this notice's content and save them to the database.
230 /* extract all #hastags */
231 $count = preg_match_all('/(?:^|\s)#([\pL\pN_\-\.]{1,64})/u', strtolower($this->content), $match);
236 /* Add them to the database */
237 return $this->saveKnownTags($match[1]);
241 * Record the given set of hash tags in the db for this notice.
242 * Given tag strings will be normalized and checked for dupes.
244 function saveKnownTags($hashtags)
246 //turn each into their canonical tag
247 //this is needed to remove dupes before saving e.g. #hash.tag = #hashtag
248 for($i=0; $i<count($hashtags); $i++) {
249 /* elide characters we don't want in the tag */
250 $hashtags[$i] = common_canonical_tag($hashtags[$i]);
253 foreach(array_unique($hashtags) as $hashtag) {
254 $this->saveTag($hashtag);
255 self::blow('profile:notice_ids_tagged:%d:%s', $this->profile_id, $hashtag);
261 * Record a single hash tag as associated with this notice.
262 * Tag format and uniqueness must be validated by caller.
264 function saveTag($hashtag)
266 $tag = new Notice_tag();
267 $tag->notice_id = $this->id;
268 $tag->tag = $hashtag;
269 $tag->created = $this->created;
270 $id = $tag->insert();
273 // TRANS: Server exception. %s are the error details.
274 throw new ServerException(sprintf(_('Database error inserting hashtag: %s.'),
275 $last_error->message));
279 // if it's saved, blow its cache
280 $tag->blowCache(false);
284 * Save a new notice and push it out to subscribers' inboxes.
285 * Poster's permissions are checked before sending.
287 * @param int $profile_id Profile ID of the poster
288 * @param string $content source message text; links may be shortened
289 * per current user's preference
290 * @param string $source source key ('web', 'api', etc)
291 * @param array $options Associative array of optional properties:
292 * string 'created' timestamp of notice; defaults to now
293 * int 'is_local' source/gateway ID, one of:
294 * Notice::LOCAL_PUBLIC - Local, ok to appear in public timeline
295 * Notice::REMOTE - Sent from a remote service;
296 * hide from public timeline but show in
297 * local "and friends" timelines
298 * Notice::LOCAL_NONPUBLIC - Local, but hide from public timeline
299 * Notice::GATEWAY - From another non-OStatus service;
300 * will not appear in public views
301 * float 'lat' decimal latitude for geolocation
302 * float 'lon' decimal longitude for geolocation
303 * int 'location_id' geoname identifier
304 * int 'location_ns' geoname namespace to interpret location_id
305 * int 'reply_to'; notice ID this is a reply to
306 * int 'repeat_of'; notice ID this is a repeat of
307 * string 'uri' unique ID for notice; defaults to local notice URL
308 * string 'url' permalink to notice; defaults to local notice URL
309 * string 'rendered' rendered HTML version of content
310 * array 'replies' list of profile URIs for reply delivery in
311 * place of extracting @-replies from content.
312 * array 'groups' list of group IDs to deliver to, in place of
313 * extracting ! tags from content
314 * array 'tags' list of hashtag strings to save with the notice
315 * in place of extracting # tags from content
316 * array 'urls' list of attached/referred URLs to save with the
317 * notice in place of extracting links from content
318 * boolean 'distribute' whether to distribute the notice, default true
319 * string 'object_type' URL of the associated object type (default ActivityObject::NOTE)
320 * string 'verb' URL of the associated verb (default ActivityVerb::POST)
321 * int 'scope' Scope bitmask; default to SITE_SCOPE on private sites, 0 otherwise
323 * @fixme tag override
326 * @throws ClientException
328 static function saveNew($profile_id, $content, $source, array $options=null) {
329 $defaults = array('uri' => null,
334 'distribute' => true,
335 'object_type' => null,
338 if (!empty($options) && is_array($options)) {
339 $options = array_merge($defaults, $options);
345 if (!isset($is_local)) {
346 $is_local = Notice::LOCAL_PUBLIC;
349 $profile = Profile::getKV('id', $profile_id);
350 $user = User::getKV('id', $profile_id);
352 // Use the local user's shortening preferences, if applicable.
353 $final = $user->shortenLinks($content);
355 $final = common_shorten_links($content);
358 if (Notice::contentTooLong($final)) {
359 // TRANS: Client exception thrown if a notice contains too many characters.
360 throw new ClientException(_('Problem saving notice. Too long.'));
363 if (empty($profile)) {
364 // TRANS: Client exception thrown when trying to save a notice for an unknown user.
365 throw new ClientException(_('Problem saving notice. Unknown user.'));
368 if (common_config('throttle', 'enabled') && !Notice::checkEditThrottle($profile_id)) {
369 common_log(LOG_WARNING, 'Excessive posting by profile #' . $profile_id . '; throttled.');
370 // TRANS: Client exception thrown when a user tries to post too many notices in a given time frame.
371 throw new ClientException(_('Too many notices too fast; take a breather '.
372 'and post again in a few minutes.'));
375 if (common_config('site', 'dupelimit') > 0 && !Notice::checkDupes($profile_id, $final)) {
376 common_log(LOG_WARNING, 'Dupe posting by profile #' . $profile_id . '; throttled.');
377 // TRANS: Client exception thrown when a user tries to post too many duplicate notices in a given time frame.
378 throw new ClientException(_('Too many duplicate messages too quickly;'.
379 ' take a breather and post again in a few minutes.'));
382 if (!$profile->hasRight(Right::NEWNOTICE)) {
383 common_log(LOG_WARNING, "Attempted post from user disallowed to post: " . $profile->nickname);
385 // TRANS: Client exception thrown when a user tries to post while being banned.
386 throw new ClientException(_('You are banned from posting notices on this site.'), 403);
389 $notice = new Notice();
390 $notice->profile_id = $profile_id;
392 $autosource = common_config('public', 'autosource');
394 // Sandboxed are non-false, but not 1, either
396 if (!$profile->hasRight(Right::PUBLICNOTICE) ||
397 ($source && $autosource && in_array($source, $autosource))) {
398 $notice->is_local = Notice::LOCAL_NONPUBLIC;
400 $notice->is_local = $is_local;
403 if (!empty($created)) {
404 $notice->created = $created;
406 $notice->created = common_sql_now();
409 $notice->content = $final;
411 $notice->source = $source;
415 // Get the groups here so we can figure out replies and such
417 if (!isset($groups)) {
418 $groups = self::groupsFromText($notice->content, $profile);
423 // Handle repeat case
425 if (isset($repeat_of)) {
427 // Check for a private one
429 $repeat = Notice::getKV('id', $repeat_of);
431 if (!($repeat instanceof Notice)) {
432 // TRANS: Client exception thrown in notice when trying to repeat a missing or deleted notice.
433 throw new ClientException(_('Cannot repeat; original notice is missing or deleted.'));
436 if ($profile->id == $repeat->profile_id) {
437 // TRANS: Client error displayed when trying to repeat an own notice.
438 throw new ClientException(_('You cannot repeat your own notice.'));
441 if ($repeat->scope != Notice::SITE_SCOPE &&
442 $repeat->scope != Notice::PUBLIC_SCOPE) {
443 // TRANS: Client error displayed when trying to repeat a non-public notice.
444 throw new ClientException(_('Cannot repeat a private notice.'), 403);
447 if (!$repeat->inScope($profile)) {
448 // The generic checks above should cover this, but let's be sure!
449 // TRANS: Client error displayed when trying to repeat a notice you cannot access.
450 throw new ClientException(_('Cannot repeat a notice you cannot read.'), 403);
453 if ($profile->hasRepeated($repeat)) {
454 // TRANS: Client error displayed when trying to repeat an already repeated notice.
455 throw new ClientException(_('You already repeated that notice.'));
458 $notice->repeat_of = $repeat_of;
460 $reply = self::getReplyTo($reply_to, $profile_id, $source, $final);
462 if (!empty($reply)) {
464 if (!$reply->inScope($profile)) {
465 // TRANS: Client error displayed when trying to reply to a notice a the target has no access to.
466 // TRANS: %1$s is a user nickname, %2$d is a notice ID (number).
467 throw new ClientException(sprintf(_('%1$s has no access to notice %2$d.'),
468 $profile->nickname, $reply->id), 403);
471 $notice->reply_to = $reply->id;
472 $notice->conversation = $reply->conversation;
474 // If the original is private to a group, and notice has no group specified,
475 // make it to the same group(s)
477 if (empty($groups) && ($reply->scope & Notice::GROUP_SCOPE)) {
479 $replyGroups = $reply->getGroups();
480 foreach ($replyGroups as $group) {
481 if ($profile->isMember($group)) {
482 $groups[] = $group->id;
491 if (!empty($lat) && !empty($lon)) {
496 if (!empty($location_ns) && !empty($location_id)) {
497 $notice->location_id = $location_id;
498 $notice->location_ns = $location_ns;
501 if (!empty($rendered)) {
502 $notice->rendered = $rendered;
504 $notice->rendered = common_render_content($final, $notice);
508 if (!empty($notice->repeat_of)) {
509 $notice->verb = ActivityVerb::SHARE;
510 $notice->object_type = ActivityObject::ACTIVITY;
512 $notice->verb = ActivityVerb::POST;
515 $notice->verb = $verb;
518 if (empty($object_type)) {
519 $notice->object_type = (empty($notice->reply_to)) ? ActivityObject::NOTE : ActivityObject::COMMENT;
521 $notice->object_type = $object_type;
524 if (is_null($scope)) { // 0 is a valid value
525 if (!empty($reply)) {
526 $notice->scope = $reply->scope;
528 $notice->scope = self::defaultScope();
531 $notice->scope = $scope;
534 // For private streams
537 $user = $profile->getUser();
539 if ($user->private_stream &&
540 ($notice->scope == Notice::PUBLIC_SCOPE ||
541 $notice->scope == Notice::SITE_SCOPE)) {
542 $notice->scope |= Notice::FOLLOWER_SCOPE;
544 } catch (NoSuchUserException $e) {
545 // Cannot handle private streams for remote profiles
548 // Force the scope for private groups
550 foreach ($groups as $groupId) {
551 $group = User_group::getKV('id', $groupId);
552 if (!empty($group)) {
553 if ($group->force_scope) {
554 $notice->scope |= Notice::GROUP_SCOPE;
560 if (Event::handle('StartNoticeSave', array(&$notice))) {
562 // XXX: some of these functions write to the DB
564 $id = $notice->insert();
567 common_log_db_error($notice, 'INSERT', __FILE__);
568 // TRANS: Server exception thrown when a notice cannot be saved.
569 throw new ServerException(_('Problem saving notice.'));
572 // Update ID-dependent columns: URI, conversation
574 $orig = clone($notice);
579 $notice->uri = common_notice_uri($notice);
583 // If it's not part of a conversation, it's
584 // the beginning of a new conversation.
586 if (empty($notice->conversation)) {
587 $conv = Conversation::create();
588 $notice->conversation = $conv->id;
593 if (!$notice->update($orig)) {
594 common_log_db_error($notice, 'UPDATE', __FILE__);
595 // TRANS: Server exception thrown when a notice cannot be updated.
596 throw new ServerException(_('Problem saving notice.'));
602 // Clear the cache for subscribed users, so they'll update at next request
603 // XXX: someone clever could prepend instead of clearing the cache
605 $notice->blowOnInsert();
607 // Save per-notice metadata...
609 if (isset($replies)) {
610 $notice->saveKnownReplies($replies);
612 $notice->saveReplies();
616 $notice->saveKnownTags($tags);
621 // Note: groups may save tags, so must be run after tags are saved
622 // to avoid errors on duplicates.
623 // Note: groups should always be set.
625 $notice->saveKnownGroups($groups);
628 $notice->saveKnownUrls($urls);
634 // Prepare inbox delivery, may be queued to background.
635 $notice->distribute();
641 function blowOnInsert($conversation = false)
643 $this->blowStream('profile:notice_ids:%d', $this->profile_id);
645 if ($this->isPublic()) {
646 $this->blowStream('public');
649 self::blow('notice:list-ids:conversation:%s', $this->conversation);
650 self::blow('conversation:notice_count:%d', $this->conversation);
652 if (!empty($this->repeat_of)) {
653 // XXX: we should probably only use one of these
654 $this->blowStream('notice:repeats:%d', $this->repeat_of);
655 self::blow('notice:list-ids:repeat_of:%d', $this->repeat_of);
658 $original = Notice::getKV('id', $this->repeat_of);
660 if (!empty($original)) {
661 $originalUser = User::getKV('id', $original->profile_id);
662 if (!empty($originalUser)) {
663 $this->blowStream('user:repeats_of_me:%d', $originalUser->id);
667 $profile = Profile::getKV($this->profile_id);
669 if (!empty($profile)) {
670 $profile->blowNoticeCount();
673 $ptags = $this->getProfileTags();
674 foreach ($ptags as $ptag) {
675 $ptag->blowNoticeStreamCache();
680 * Clear cache entries related to this notice at delete time.
681 * Necessary to avoid breaking paging on public, profile timelines.
683 function blowOnDelete()
685 $this->blowOnInsert();
687 self::blow('profile:notice_ids:%d;last', $this->profile_id);
689 if ($this->isPublic()) {
690 self::blow('public;last');
693 self::blow('fave:by_notice', $this->id);
695 if ($this->conversation) {
696 // In case we're the first, will need to calc a new root.
697 self::blow('notice:conversation_root:%d', $this->conversation);
700 $ptags = $this->getProfileTags();
701 foreach ($ptags as $ptag) {
702 $ptag->blowNoticeStreamCache(true);
706 function blowStream()
708 $c = self::memcache();
714 $args = func_get_args();
716 $format = array_shift($args);
718 $keyPart = vsprintf($format, $args);
720 $cacheKey = Cache::key($keyPart);
722 $c->delete($cacheKey);
724 // delete the "last" stream, too, if this notice is
725 // older than the top of that stream
727 $lastKey = $cacheKey.';last';
729 $lastStr = $c->get($lastKey);
731 if ($lastStr !== false) {
732 $window = explode(',', $lastStr);
733 $lastID = $window[0];
734 $lastNotice = Notice::getKV('id', $lastID);
735 if (empty($lastNotice) // just weird
736 || strtotime($lastNotice->created) >= strtotime($this->created)) {
737 $c->delete($lastKey);
742 /** save all urls in the notice to the db
744 * follow redirects and save all available file information
745 * (mimetype, date, size, oembed, etc.)
749 function saveUrls() {
750 if (common_config('attachments', 'process_links')) {
751 common_replace_urls_callback($this->content, array($this, 'saveUrl'), $this->id);
756 * Save the given URLs as related links/attachments to the db
758 * follow redirects and save all available file information
759 * (mimetype, date, size, oembed, etc.)
763 function saveKnownUrls($urls)
765 if (common_config('attachments', 'process_links')) {
766 // @fixme validation?
767 foreach (array_unique($urls) as $url) {
768 File::processNew($url, $this->id);
776 function saveUrl($url, $notice_id) {
777 File::processNew($url, $notice_id);
780 static function checkDupes($profile_id, $content) {
781 $profile = Profile::getKV($profile_id);
782 if (empty($profile)) {
785 $notice = $profile->getNotices(0, CachingNoticeStream::CACHE_WINDOW);
786 if (!empty($notice)) {
788 while ($notice->fetch()) {
789 if (time() - strtotime($notice->created) >= common_config('site', 'dupelimit')) {
791 } else if ($notice->content == $content) {
796 // If we get here, oldest item in cache window is not
797 // old enough for dupe limit; do direct check against DB
798 $notice = new Notice();
799 $notice->profile_id = $profile_id;
800 $notice->content = $content;
801 $threshold = common_sql_date(time() - common_config('site', 'dupelimit'));
802 $notice->whereAdd(sprintf("created > '%s'", $notice->escape($threshold)));
804 $cnt = $notice->count();
808 static function checkEditThrottle($profile_id) {
809 $profile = Profile::getKV($profile_id);
810 if (empty($profile)) {
813 // Get the Nth notice
814 $notice = $profile->getNotices(common_config('throttle', 'count') - 1, 1);
815 if ($notice && $notice->fetch()) {
816 // If the Nth notice was posted less than timespan seconds ago
817 if (time() - strtotime($notice->created) <= common_config('throttle', 'timespan')) {
822 // Either not N notices in the stream, OR the Nth was not posted within timespan seconds
826 protected $_attachments = -1;
828 function attachments() {
830 if ($this->_attachments != -1) {
831 return $this->_attachments;
834 $f2ps = File_to_post::listGet('post_id', array($this->id));
838 foreach ($f2ps[$this->id] as $f2p) {
839 $ids[] = $f2p->file_id;
842 $files = File::multiGet('id', $ids);
844 $this->_attachments = $files->fetchAll();
846 return $this->_attachments;
849 function _setAttachments($attachments)
851 $this->_attachments = $attachments;
854 function publicStream($offset=0, $limit=20, $since_id=0, $max_id=0)
856 $stream = new PublicNoticeStream();
857 return $stream->getNotices($offset, $limit, $since_id, $max_id);
861 function conversationStream($id, $offset=0, $limit=20, $since_id=0, $max_id=0)
863 $stream = new ConversationNoticeStream($id);
865 return $stream->getNotices($offset, $limit, $since_id, $max_id);
869 * Is this notice part of an active conversation?
871 * @return boolean true if other messages exist in the same
872 * conversation, false if this is the only one
874 function hasConversation()
876 if (!empty($this->conversation)) {
877 $conversation = Notice::conversationStream(
883 if ($conversation->N > 0) {
891 * Grab the earliest notice from this conversation.
893 * @return Notice or null
895 function conversationRoot($profile=-1)
897 // XXX: can this happen?
899 if (empty($this->conversation)) {
903 // Get the current profile if not specified
905 if (is_int($profile) && $profile == -1) {
906 $profile = Profile::current();
909 // If this notice is out of scope, no root for you!
911 if (!$this->inScope($profile)) {
915 // If this isn't a reply to anything, then it's its own
918 if (empty($this->reply_to)) {
922 if (is_null($profile)) {
923 $keypart = sprintf('notice:conversation_root:%d:null', $this->id);
925 $keypart = sprintf('notice:conversation_root:%d:%d',
930 $root = self::cacheGet($keypart);
932 if ($root !== false && $root->inScope($profile)) {
939 $parent = $last->getParent();
940 if ($parent->inScope($profile)) {
944 } catch (Exception $e) {
945 // Latest notice has no parent
947 // No parent, or parent out of scope
952 self::cacheSet($keypart, $root);
958 * Pull up a full list of local recipients who will be getting
959 * this notice in their inbox. Results will be cached, so don't
960 * change the input data wily-nilly!
962 * @param array $groups optional list of Group objects;
963 * if left empty, will be loaded from group_inbox records
964 * @param array $recipient optional list of reply profile ids
965 * if left empty, will be loaded from reply records
966 * @return array associating recipient user IDs with an inbox source constant
968 function whoGets(array $groups=null, array $recipients=null)
970 $c = self::memcache();
973 $ni = $c->get(Cache::key('notice:who_gets:'.$this->id));
979 if (is_null($groups)) {
980 $groups = $this->getGroups();
983 if (is_null($recipients)) {
984 $recipients = $this->getReplies();
987 $users = $this->getSubscribedUsers();
988 $ptags = $this->getProfileTags();
990 // FIXME: kind of ignoring 'transitional'...
991 // we'll probably stop supporting inboxless mode
996 // Give plugins a chance to add folks in at start...
997 if (Event::handle('StartNoticeWhoGets', array($this, &$ni))) {
999 foreach ($users as $id) {
1000 $ni[$id] = NOTICE_INBOX_SOURCE_SUB;
1003 foreach ($groups as $group) {
1004 $users = $group->getUserMembers();
1005 foreach ($users as $id) {
1006 if (!array_key_exists($id, $ni)) {
1007 $ni[$id] = NOTICE_INBOX_SOURCE_GROUP;
1012 foreach ($ptags as $ptag) {
1013 $users = $ptag->getUserSubscribers();
1014 foreach ($users as $id) {
1015 if (!array_key_exists($id, $ni)) {
1016 $ni[$id] = NOTICE_INBOX_SOURCE_PROFILE_TAG;
1021 foreach ($recipients as $recipient) {
1022 if (!array_key_exists($recipient, $ni)) {
1023 $ni[$recipient] = NOTICE_INBOX_SOURCE_REPLY;
1027 // Exclude any deleted, non-local, or blocking recipients.
1028 $profile = $this->getProfile();
1029 $originalProfile = null;
1030 if ($this->repeat_of) {
1031 // Check blocks against the original notice's poster as well.
1032 $original = Notice::getKV('id', $this->repeat_of);
1034 $originalProfile = $original->getProfile();
1038 foreach ($ni as $id => $source) {
1040 $user = User::getKV('id', $id);
1042 $user->hasBlocked($profile) ||
1043 ($originalProfile && $user->hasBlocked($originalProfile))) {
1046 } catch (UserNoProfileException $e) {
1047 // User doesn't have a profile; invalid; skip them.
1052 // Give plugins a chance to filter out...
1053 Event::handle('EndNoticeWhoGets', array($this, &$ni));
1057 // XXX: pack this data better
1058 $c->set(Cache::key('notice:who_gets:'.$this->id), $ni);
1065 * Adds this notice to the inboxes of each local user who should receive
1066 * it, based on author subscriptions, group memberships, and @-replies.
1068 * Warning: running a second time currently will make items appear
1069 * multiple times in users' inboxes.
1071 * @fixme make more robust against errors
1072 * @fixme break up massive deliveries to smaller background tasks
1074 * @param array $groups optional list of Group objects;
1075 * if left empty, will be loaded from group_inbox records
1076 * @param array $recipient optional list of reply profile ids
1077 * if left empty, will be loaded from reply records
1079 function addToInboxes(array $groups=null, array $recipients=null)
1081 $ni = $this->whoGets($groups, $recipients);
1083 $ids = array_keys($ni);
1085 // We remove the author (if they're a local user),
1086 // since we'll have already done this in distribute()
1088 $i = array_search($this->profile_id, $ids);
1096 Inbox::bulkInsert($this->id, $ids);
1101 function getSubscribedUsers()
1105 if(common_config('db','quote_identifiers'))
1106 $user_table = '"user"';
1107 else $user_table = 'user';
1111 'FROM '. $user_table .' JOIN subscription '.
1112 'ON '. $user_table .'.id = subscription.subscriber ' .
1113 'WHERE subscription.subscribed = %d ';
1115 $user->query(sprintf($qry, $this->profile_id));
1119 while ($user->fetch()) {
1128 function getProfileTags()
1130 $profile = $this->getProfile();
1131 $list = $profile->getOtherTags($profile);
1134 while($list->fetch()) {
1135 $ptags[] = clone($list);
1142 * Record this notice to the given group inboxes for delivery.
1143 * Overrides the regular parsing of !group markup.
1145 * @param string $group_ids
1146 * @fixme might prefer URIs as identifiers, as for replies?
1147 * best with generalizations on user_group to support
1148 * remote groups better.
1150 function saveKnownGroups($group_ids)
1152 if (!is_array($group_ids)) {
1153 // TRANS: Server exception thrown when no array is provided to the method saveKnownGroups().
1154 throw new ServerException(_('Bad type provided to saveKnownGroups.'));
1158 foreach (array_unique($group_ids) as $id) {
1159 $group = User_group::getKV('id', $id);
1161 common_log(LOG_ERR, "Local delivery to group id $id, $group->nickname");
1162 $result = $this->addToGroupInbox($group);
1164 common_log_db_error($gi, 'INSERT', __FILE__);
1167 if (common_config('group', 'addtag')) {
1168 // we automatically add a tag for every group name, too
1170 $tag = Notice_tag::pkeyGet(array('tag' => common_canonical_tag($group->nickname),
1171 'notice_id' => $this->id));
1173 if (is_null($tag)) {
1174 $this->saveTag($group->nickname);
1178 $groups[] = clone($group);
1180 common_log(LOG_ERR, "Local delivery to group id $id skipped, doesn't exist");
1188 * Parse !group delivery and record targets into group_inbox.
1189 * @return array of Group objects
1191 function saveGroups()
1193 // Don't save groups for repeats
1195 if (!empty($this->repeat_of)) {
1199 $profile = $this->getProfile();
1201 $groups = self::groupsFromText($this->content, $profile);
1203 /* Add them to the database */
1205 foreach ($groups as $group) {
1206 /* XXX: remote groups. */
1208 if (empty($group)) {
1213 if ($profile->isMember($group)) {
1215 $result = $this->addToGroupInbox($group);
1218 common_log_db_error($gi, 'INSERT', __FILE__);
1221 $groups[] = clone($group);
1228 function addToGroupInbox($group)
1230 $gi = Group_inbox::pkeyGet(array('group_id' => $group->id,
1231 'notice_id' => $this->id));
1235 $gi = new Group_inbox();
1237 $gi->group_id = $group->id;
1238 $gi->notice_id = $this->id;
1239 $gi->created = $this->created;
1241 $result = $gi->insert();
1244 common_log_db_error($gi, 'INSERT', __FILE__);
1245 // TRANS: Server exception thrown when an update for a group inbox fails.
1246 throw new ServerException(_('Problem saving group inbox.'));
1249 self::blow('user_group:notice_ids:%d', $gi->group_id);
1256 * Save reply records indicating that this notice needs to be
1257 * delivered to the local users with the given URIs.
1259 * Since this is expected to be used when saving foreign-sourced
1260 * messages, we won't deliver to any remote targets as that's the
1261 * source service's responsibility.
1263 * Mail notifications etc will be handled later.
1265 * @param array $uris Array of unique identifier URIs for recipients
1267 function saveKnownReplies(array $uris)
1273 $sender = Profile::getKV($this->profile_id);
1275 foreach (array_unique($uris) as $uri) {
1277 $profile = Profile::fromURI($uri);
1279 if (empty($profile)) {
1280 common_log(LOG_WARNING, "Unable to determine profile for URI '$uri'");
1284 if ($profile->hasBlocked($sender)) {
1285 common_log(LOG_INFO, "Not saving reply to profile {$profile->id} ($uri) from sender {$sender->id} because of a block.");
1289 $this->saveReply($profile->id);
1290 self::blow('reply:stream:%d', $profile->id);
1297 * Pull @-replies from this message's content in StatusNet markup format
1298 * and save reply records indicating that this message needs to be
1299 * delivered to those users.
1301 * Mail notifications to local profiles will be sent later.
1303 * @return array of integer profile IDs
1306 function saveReplies()
1308 // Don't save reply data for repeats
1310 if (!empty($this->repeat_of)) {
1314 $sender = Profile::getKV($this->profile_id);
1318 // If it's a reply, save for the replied-to author
1320 $parent = $this->getParent();
1321 $author = $parent->getProfile();
1322 if ($author instanceof Profile) {
1323 $this->saveReply($author->id);
1324 $replied[$author->id] = 1;
1325 self::blow('reply:stream:%d', $author->id);
1327 } catch (Exception $e) {
1328 // Not a reply, since it has no parent!
1331 // @todo ideally this parser information would only
1332 // be calculated once.
1334 $mentions = common_find_mentions($this->content, $this);
1336 // store replied only for first @ (what user/notice what the reply directed,
1337 // we assume first @ is it)
1339 foreach ($mentions as $mention) {
1341 foreach ($mention['mentioned'] as $mentioned) {
1343 // skip if they're already covered
1345 if (!empty($replied[$mentioned->id])) {
1349 // Don't save replies from blocked profile to local user
1351 $mentioned_user = User::getKV('id', $mentioned->id);
1352 if (!empty($mentioned_user) && $mentioned_user->hasBlocked($sender)) {
1356 $this->saveReply($mentioned->id);
1357 $replied[$mentioned->id] = 1;
1358 self::blow('reply:stream:%d', $mentioned->id);
1362 $recipientIds = array_keys($replied);
1364 return $recipientIds;
1367 function saveReply($profileId)
1369 $reply = new Reply();
1371 $reply->notice_id = $this->id;
1372 $reply->profile_id = $profileId;
1373 $reply->modified = $this->created;
1380 protected $_replies = -1;
1383 * Pull the complete list of @-reply targets for this notice.
1385 * @return array of integer profile ids
1387 function getReplies()
1389 if ($this->_replies != -1) {
1390 return $this->_replies;
1393 $replyMap = Reply::listGet('notice_id', array($this->id));
1397 foreach ($replyMap[$this->id] as $reply) {
1398 $ids[] = $reply->profile_id;
1401 $this->_replies = $ids;
1406 function _setReplies($replies)
1408 $this->_replies = $replies;
1412 * Pull the complete list of @-reply targets for this notice.
1414 * @return array of Profiles
1416 function getReplyProfiles()
1418 $ids = $this->getReplies();
1420 $profiles = Profile::multiGet('id', $ids);
1422 return $profiles->fetchAll();
1426 * Send e-mail notifications to local @-reply targets.
1428 * Replies must already have been saved; this is expected to be run
1429 * from the distrib queue handler.
1431 function sendReplyNotifications()
1433 // Don't send reply notifications for repeats
1435 if (!empty($this->repeat_of)) {
1439 $recipientIds = $this->getReplies();
1441 foreach ($recipientIds as $recipientId) {
1442 $user = User::getKV('id', $recipientId);
1443 if (!empty($user)) {
1444 mail_notify_attn($user, $this);
1450 * Pull list of groups this notice needs to be delivered to,
1451 * as previously recorded by saveGroups() or saveKnownGroups().
1453 * @return array of Group objects
1456 protected $_groups = -1;
1458 function getGroups()
1460 // Don't save groups for repeats
1462 if (!empty($this->repeat_of)) {
1466 if ($this->_groups != -1)
1468 return $this->_groups;
1471 $gis = Group_inbox::listGet('notice_id', array($this->id));
1475 foreach ($gis[$this->id] as $gi)
1477 $ids[] = $gi->group_id;
1480 $groups = User_group::multiGet('id', $ids);
1482 $this->_groups = $groups->fetchAll();
1484 return $this->_groups;
1487 function _setGroups($groups)
1489 $this->_groups = $groups;
1493 * Convert a notice into an activity for export.
1495 * @param User $cur Current user
1497 * @return Activity activity object representing this Notice.
1500 function asActivity($cur=null)
1502 $act = self::cacheGet(Cache::codeKey('notice:as-activity:'.$this->id));
1507 $act = new Activity();
1509 if (Event::handle('StartNoticeAsActivity', array($this, &$act))) {
1511 $act->id = $this->uri;
1512 $act->time = strtotime($this->created);
1513 $act->link = $this->bestUrl();
1514 $act->content = common_xml_safe_str($this->rendered);
1516 $profile = $this->getProfile();
1518 $act->actor = ActivityObject::fromProfile($profile);
1519 $act->actor->extra[] = $profile->profileInfo($cur);
1521 $act->verb = $this->verb;
1523 if ($this->repeat_of) {
1524 $repeated = Notice::getKV('id', $this->repeat_of);
1525 if (!empty($repeated)) {
1526 $act->objects[] = $repeated->asActivity($cur);
1529 $act->objects[] = ActivityObject::fromNotice($this);
1532 // XXX: should this be handled by default processing for object entry?
1536 $tags = $this->getTags();
1538 foreach ($tags as $tag) {
1539 $cat = new AtomCategory();
1542 $act->categories[] = $cat;
1546 // XXX: use Atom Media and/or File activity objects instead
1548 $attachments = $this->attachments();
1550 foreach ($attachments as $attachment) {
1551 // Save local attachments
1552 if (!empty($attachment->filename)) {
1553 $act->attachments[] = ActivityObject::fromFile($attachment);
1557 $ctx = new ActivityContext();
1559 if (!empty($this->reply_to)) {
1560 $reply = Notice::getKV('id', $this->reply_to);
1561 if (!empty($reply)) {
1562 $ctx->replyToID = $reply->uri;
1563 $ctx->replyToUrl = $reply->bestUrl();
1567 $ctx->location = $this->getLocation();
1571 if (!empty($this->conversation)) {
1572 $conv = Conversation::getKV('id', $this->conversation);
1573 if (!empty($conv)) {
1574 $ctx->conversation = $conv->uri;
1578 $reply_ids = $this->getReplies();
1580 foreach ($reply_ids as $id) {
1581 $rprofile = Profile::getKV('id', $id);
1582 if (!empty($rprofile)) {
1583 $ctx->attention[] = $rprofile->getUri();
1584 $ctx->attentionType[$rprofile->getUri()] = ActivityObject::PERSON;
1588 $groups = $this->getGroups();
1590 foreach ($groups as $group) {
1591 $ctx->attention[] = $group->getUri();
1592 $ctx->attentionType[$group->getUri()] = ActivityObject::GROUP;
1595 switch ($this->scope) {
1596 case Notice::PUBLIC_SCOPE:
1597 $ctx->attention[] = "http://activityschema.org/collection/public";
1598 $ctx->attentionType["http://activityschema.org/collection/public"] = ActivityObject::COLLECTION;
1600 case Notice::FOLLOWER_SCOPE:
1601 $surl = common_local_url("subscribers", array('nickname' => $profile->nickname));
1602 $ctx->attention[] = $surl;
1603 $ctx->attentionType[$surl] = ActivityObject::COLLECTION;
1607 $act->context = $ctx;
1609 $source = $this->getSource();
1612 $act->generator = ActivityObject::fromNoticeSource($source);
1617 $atom_feed = $profile->getAtomFeed();
1619 if (!empty($atom_feed)) {
1621 $act->source = new ActivitySource();
1623 // XXX: we should store the actual feed ID
1625 $act->source->id = $atom_feed;
1627 // XXX: we should store the actual feed title
1629 $act->source->title = $profile->getBestName();
1631 $act->source->links['alternate'] = $profile->profileurl;
1632 $act->source->links['self'] = $atom_feed;
1634 $act->source->icon = $profile->avatarUrl(AVATAR_PROFILE_SIZE);
1636 $notice = $profile->getCurrentNotice();
1638 if (!empty($notice)) {
1639 $act->source->updated = self::utcDate($notice->created);
1642 $user = User::getKV('id', $profile->id);
1644 if (!empty($user)) {
1645 $act->source->links['license'] = common_config('license', 'url');
1649 if ($this->isLocal()) {
1650 $act->selfLink = common_local_url('ApiStatusesShow', array('id' => $this->id,
1651 'format' => 'atom'));
1652 $act->editLink = $act->selfLink;
1655 Event::handle('EndNoticeAsActivity', array($this, &$act));
1658 self::cacheSet(Cache::codeKey('notice:as-activity:'.$this->id), $act);
1663 // This has gotten way too long. Needs to be sliced up into functional bits
1664 // or ideally exported to a utility class.
1666 function asAtomEntry($namespace=false,
1671 $act = $this->asActivity($cur);
1672 $act->extra[] = $this->noticeInfo($cur);
1673 return $act->asString($namespace, $author, $source);
1677 * Extra notice info for atom entries
1679 * Clients use some extra notice info in the atom stream.
1680 * This gives it to them.
1682 * @param User $cur Current user
1684 * @return array representation of <statusnet:notice_info> element
1687 function noticeInfo($cur)
1689 // local notice ID (useful to clients for ordering)
1691 $noticeInfoAttr = array('local_id' => $this->id);
1695 $ns = $this->getSource();
1698 $noticeInfoAttr['source'] = $ns->code;
1699 if (!empty($ns->url)) {
1700 $noticeInfoAttr['source_link'] = $ns->url;
1701 if (!empty($ns->name)) {
1702 $noticeInfoAttr['source'] = '<a href="'
1703 . htmlspecialchars($ns->url)
1704 . '" rel="nofollow">'
1705 . htmlspecialchars($ns->name)
1711 // favorite and repeated
1714 $cp = $cur->getProfile();
1715 $noticeInfoAttr['favorite'] = ($cp->hasFave($this)) ? "true" : "false";
1716 $noticeInfoAttr['repeated'] = ($cp->hasRepeated($this)) ? "true" : "false";
1719 if (!empty($this->repeat_of)) {
1720 $noticeInfoAttr['repeat_of'] = $this->repeat_of;
1723 return array('statusnet:notice_info', $noticeInfoAttr, null);
1727 * Returns an XML string fragment with a reference to a notice as an
1728 * Activity Streams noun object with the given element type.
1730 * Assumes that 'activity' namespace has been previously defined.
1732 * @param string $element one of 'subject', 'object', 'target'
1736 function asActivityNoun($element)
1738 $noun = ActivityObject::fromNotice($this);
1739 return $noun->asString('activity:' . $element);
1744 if (!empty($this->url)) {
1746 } else if (!empty($this->uri) && preg_match('/^https?:/', $this->uri)) {
1749 return common_local_url('shownotice',
1750 array('notice' => $this->id));
1756 * Determine which notice, if any, a new notice is in reply to.
1758 * For conversation tracking, we try to see where this notice fits
1759 * in the tree. Rough algorithm is:
1761 * if (reply_to is set and valid) {
1763 * } else if ((source not API or Web) and (content starts with "T NAME" or "@name ")) {
1764 * return ID of last notice by initial @name in content;
1767 * Note that all @nickname instances will still be used to save "reply" records,
1768 * so the notice shows up in the mentioned users' "replies" tab.
1770 * @param integer $reply_to ID passed in by Web or API
1771 * @param integer $profile_id ID of author
1772 * @param string $source Source tag, like 'web' or 'gwibber'
1773 * @param string $content Final notice content
1775 * @return integer ID of replied-to notice, or null for not a reply.
1778 static function getReplyTo($reply_to, $profile_id, $source, $content)
1780 static $lb = array('xmpp', 'mail', 'sms', 'omb');
1782 // If $reply_to is specified, we check that it exists, and then
1783 // return it if it does
1785 if (!empty($reply_to)) {
1786 $reply_notice = Notice::getKV('id', $reply_to);
1787 if (!empty($reply_notice)) {
1788 return $reply_notice;
1792 // If it's not a "low bandwidth" source (one where you can't set
1793 // a reply_to argument), we return. This is mostly web and API
1796 if (!in_array($source, $lb)) {
1800 // Is there an initial @ or T?
1802 if (preg_match('/^T ([A-Z0-9]{1,64}) /', $content, $match) ||
1803 preg_match('/^@([a-z0-9]{1,64})\s+/', $content, $match)) {
1804 $nickname = common_canonical_nickname($match[1]);
1809 // Figure out who that is.
1811 $sender = Profile::getKV('id', $profile_id);
1812 if (empty($sender)) {
1816 $recipient = common_relative_profile($sender, $nickname, common_sql_now());
1818 if (empty($recipient)) {
1822 // Get their last notice
1824 $last = $recipient->getCurrentNotice();
1826 if (!empty($last)) {
1833 static function maxContent()
1835 $contentlimit = common_config('notice', 'contentlimit');
1836 // null => use global limit (distinct from 0!)
1837 if (is_null($contentlimit)) {
1838 $contentlimit = common_config('site', 'textlimit');
1840 return $contentlimit;
1843 static function contentTooLong($content)
1845 $contentlimit = self::maxContent();
1846 return ($contentlimit > 0 && !empty($content) && (mb_strlen($content) > $contentlimit));
1849 function getLocation()
1853 if (!empty($this->location_id) && !empty($this->location_ns)) {
1854 $location = Location::fromId($this->location_id, $this->location_ns);
1857 if (is_null($location)) { // no ID, or Location::fromId() failed
1858 if (!empty($this->lat) && !empty($this->lon)) {
1859 $location = Location::fromLatLon($this->lat, $this->lon);
1867 * Convenience function for posting a repeat of an existing message.
1869 * @param int $repeater_id: profile ID of user doing the repeat
1870 * @param string $source: posting source key, eg 'web', 'api', etc
1873 * @throws Exception on failure or permission problems
1875 function repeat($repeater_id, $source)
1877 $author = Profile::getKV('id', $this->profile_id);
1879 // TRANS: Message used to repeat a notice. RT is the abbreviation of 'retweet'.
1880 // TRANS: %1$s is the repeated user's name, %2$s is the repeated notice.
1881 $content = sprintf(_('RT @%1$s %2$s'),
1885 $maxlen = common_config('site', 'textlimit');
1886 if ($maxlen > 0 && mb_strlen($content) > $maxlen) {
1887 // Web interface and current Twitter API clients will
1888 // pull the original notice's text, but some older
1889 // clients and RSS/Atom feeds will see this trimmed text.
1891 // Unfortunately this is likely to lose tags or URLs
1892 // at the end of long notices.
1893 $content = mb_substr($content, 0, $maxlen - 4) . ' ...';
1896 // Scope is same as this one's
1898 return self::saveNew($repeater_id,
1901 array('repeat_of' => $this->id,
1902 'scope' => $this->scope));
1905 // These are supposed to be in chron order!
1907 function repeatStream($limit=100)
1909 $cache = Cache::instance();
1911 if (empty($cache)) {
1912 $ids = $this->_repeatStreamDirect($limit);
1914 $idstr = $cache->get(Cache::key('notice:repeats:'.$this->id));
1915 if ($idstr !== false) {
1916 if (empty($idstr)) {
1919 $ids = explode(',', $idstr);
1922 $ids = $this->_repeatStreamDirect(100);
1923 $cache->set(Cache::key('notice:repeats:'.$this->id), implode(',', $ids));
1926 // We do a max of 100, so slice down to limit
1927 $ids = array_slice($ids, 0, $limit);
1931 return NoticeStream::getStreamByIds($ids);
1934 function _repeatStreamDirect($limit)
1936 $notice = new Notice();
1938 $notice->selectAdd(); // clears it
1939 $notice->selectAdd('id');
1941 $notice->repeat_of = $this->id;
1943 $notice->orderBy('created, id'); // NB: asc!
1945 if (!is_null($limit)) {
1946 $notice->limit(0, $limit);
1949 return $notice->fetchAll('id');
1952 function locationOptions($lat, $lon, $location_id, $location_ns, $profile = null)
1956 if (!empty($location_id) && !empty($location_ns)) {
1957 $options['location_id'] = $location_id;
1958 $options['location_ns'] = $location_ns;
1960 $location = Location::fromId($location_id, $location_ns);
1962 if (!empty($location)) {
1963 $options['lat'] = $location->lat;
1964 $options['lon'] = $location->lon;
1967 } else if (!empty($lat) && !empty($lon)) {
1968 $options['lat'] = $lat;
1969 $options['lon'] = $lon;
1971 $location = Location::fromLatLon($lat, $lon);
1973 if (!empty($location)) {
1974 $options['location_id'] = $location->location_id;
1975 $options['location_ns'] = $location->location_ns;
1977 } else if (!empty($profile)) {
1978 if (isset($profile->lat) && isset($profile->lon)) {
1979 $options['lat'] = $profile->lat;
1980 $options['lon'] = $profile->lon;
1983 if (isset($profile->location_id) && isset($profile->location_ns)) {
1984 $options['location_id'] = $profile->location_id;
1985 $options['location_ns'] = $profile->location_ns;
1992 function clearReplies()
1994 $replyNotice = new Notice();
1995 $replyNotice->reply_to = $this->id;
1997 //Null any notices that are replies to this notice
1999 if ($replyNotice->find()) {
2000 while ($replyNotice->fetch()) {
2001 $orig = clone($replyNotice);
2002 $replyNotice->reply_to = null;
2003 $replyNotice->update($orig);
2009 $reply = new Reply();
2010 $reply->notice_id = $this->id;
2012 if ($reply->find()) {
2013 while($reply->fetch()) {
2014 self::blow('reply:stream:%d', $reply->profile_id);
2022 function clearFiles()
2024 $f2p = new File_to_post();
2026 $f2p->post_id = $this->id;
2029 while ($f2p->fetch()) {
2033 // FIXME: decide whether to delete File objects
2034 // ...and related (actual) files
2037 function clearRepeats()
2039 $repeatNotice = new Notice();
2040 $repeatNotice->repeat_of = $this->id;
2042 //Null any notices that are repeats of this notice
2044 if ($repeatNotice->find()) {
2045 while ($repeatNotice->fetch()) {
2046 $orig = clone($repeatNotice);
2047 $repeatNotice->repeat_of = null;
2048 $repeatNotice->update($orig);
2053 function clearFaves()
2056 $fave->notice_id = $this->id;
2058 if ($fave->find()) {
2059 while ($fave->fetch()) {
2060 self::blow('fave:ids_by_user_own:%d', $fave->user_id);
2061 self::blow('fave:ids_by_user_own:%d;last', $fave->user_id);
2062 self::blow('fave:ids_by_user:%d', $fave->user_id);
2063 self::blow('fave:ids_by_user:%d;last', $fave->user_id);
2071 function clearTags()
2073 $tag = new Notice_tag();
2074 $tag->notice_id = $this->id;
2077 while ($tag->fetch()) {
2078 self::blow('profile:notice_ids_tagged:%d:%s', $this->profile_id, Cache::keyize($tag->tag));
2079 self::blow('profile:notice_ids_tagged:%d:%s;last', $this->profile_id, Cache::keyize($tag->tag));
2080 self::blow('notice_tag:notice_ids:%s', Cache::keyize($tag->tag));
2081 self::blow('notice_tag:notice_ids:%s;last', Cache::keyize($tag->tag));
2089 function clearGroupInboxes()
2091 $gi = new Group_inbox();
2093 $gi->notice_id = $this->id;
2096 while ($gi->fetch()) {
2097 self::blow('user_group:notice_ids:%d', $gi->group_id);
2105 function distribute()
2107 // We always insert for the author so they don't
2109 Event::handle('StartNoticeDistribute', array($this));
2111 $user = User::getKV('id', $this->profile_id);
2112 if (!empty($user)) {
2113 Inbox::insertNotice($user->id, $this->id);
2116 if (common_config('queue', 'inboxes')) {
2117 // If there's a failure, we want to _force_
2118 // distribution at this point.
2120 $qm = QueueManager::get();
2121 $qm->enqueue($this, 'distrib');
2122 } catch (Exception $e) {
2123 // If the exception isn't transient, this
2124 // may throw more exceptions as DQH does
2125 // its own enqueueing. So, we ignore them!
2127 $handler = new DistribQueueHandler();
2128 $handler->handle($this);
2129 } catch (Exception $e) {
2130 common_log(LOG_ERR, "emergency redistribution resulted in " . $e->getMessage());
2132 // Re-throw so somebody smarter can handle it.
2136 $handler = new DistribQueueHandler();
2137 $handler->handle($this);
2143 $result = parent::insert();
2146 // Profile::hasRepeated() abuses pkeyGet(), so we
2147 // have to clear manually
2148 if (!empty($this->repeat_of)) {
2149 $c = self::memcache();
2151 $ck = self::multicacheKey('Notice',
2152 array('profile_id' => $this->profile_id,
2153 'repeat_of' => $this->repeat_of));
2163 * Get the source of the notice
2165 * @return Notice_source $ns A notice source object. 'code' is the only attribute
2166 * guaranteed to be populated.
2168 function getSource()
2170 $ns = new Notice_source();
2171 if (!empty($this->source)) {
2172 switch ($this->source) {
2179 $ns->code = $this->source;
2182 $ns = Notice_source::getKV($this->source);
2184 $ns = new Notice_source();
2185 $ns->code = $this->source;
2186 $app = Oauth_application::getKV('name', $this->source);
2188 $ns->name = $app->name;
2189 $ns->url = $app->source_url;
2199 * Determine whether the notice was locally created
2201 * @return boolean locality
2204 public function isLocal()
2206 return ($this->is_local == Notice::LOCAL_PUBLIC ||
2207 $this->is_local == Notice::LOCAL_NONPUBLIC);
2211 * Get the list of hash tags saved with this notice.
2213 * @return array of strings
2215 public function getTags()
2219 $keypart = sprintf('notice:tags:%d', $this->id);
2221 $tagstr = self::cacheGet($keypart);
2223 if ($tagstr !== false) {
2224 $tags = explode(',', $tagstr);
2226 $tag = new Notice_tag();
2227 $tag->notice_id = $this->id;
2229 while ($tag->fetch()) {
2230 $tags[] = $tag->tag;
2233 self::cacheSet($keypart, implode(',', $tags));
2239 static private function utcDate($dt)
2241 $dateStr = date('d F Y H:i:s', strtotime($dt));
2242 $d = new DateTime($dateStr, new DateTimeZone('UTC'));
2243 return $d->format(DATE_W3C);
2247 * Look up the creation timestamp for a given notice ID, even
2248 * if it's been deleted.
2251 * @return mixed string recorded creation timestamp, or false if can't be found
2253 public static function getAsTimestamp($id)
2259 $notice = Notice::getKV('id', $id);
2261 return $notice->created;
2264 $deleted = Deleted_notice::getKV('id', $id);
2266 return $deleted->created;
2273 * Build an SQL 'where' fragment for timestamp-based sorting from a since_id
2274 * parameter, matching notices posted after the given one (exclusive).
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 whereSinceId($id, $idField='id', $createdField='created')
2285 $since = Notice::getAsTimestamp($id);
2287 return sprintf("($createdField = '%s' and $idField > %d) or ($createdField > '%s')", $since, $id, $since);
2293 * Build an SQL 'where' fragment for timestamp-based sorting from a since_id
2294 * parameter, matching notices posted after the given one (exclusive), 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 addWhereSinceId(DB_DataObject $obj, $id, $idField='id', $createdField='created')
2305 $since = self::whereSinceId($id, $idField, $createdField);
2307 $obj->whereAdd($since);
2312 * Build an SQL 'where' fragment for timestamp-based sorting from a max_id
2313 * parameter, matching notices posted before the given one (inclusive).
2315 * If the referenced notice can't be found, will return false.
2318 * @param string $idField
2319 * @param string $createdField
2320 * @return mixed string or false if no match
2322 public static function whereMaxId($id, $idField='id', $createdField='created')
2324 $max = Notice::getAsTimestamp($id);
2326 return sprintf("($createdField < '%s') or ($createdField = '%s' and $idField <= %d)", $max, $max, $id);
2332 * Build an SQL 'where' fragment for timestamp-based sorting from a max_id
2333 * parameter, matching notices posted before the given one (inclusive), and
2334 * if necessary add it to the data object's query.
2336 * @param DB_DataObject $obj
2338 * @param string $idField
2339 * @param string $createdField
2340 * @return mixed string or false if no match
2342 public static function addWhereMaxId(DB_DataObject $obj, $id, $idField='id', $createdField='created')
2344 $max = self::whereMaxId($id, $idField, $createdField);
2346 $obj->whereAdd($max);
2352 if (common_config('public', 'localonly')) {
2353 return ($this->is_local == Notice::LOCAL_PUBLIC);
2355 return (($this->is_local != Notice::LOCAL_NONPUBLIC) &&
2356 ($this->is_local != Notice::GATEWAY));
2361 * Check that the given profile is allowed to read, respond to, or otherwise
2362 * act on this notice.
2364 * The $scope member is a bitmask of scopes, representing a logical AND of the
2365 * scope requirement. So, 0x03 (Notice::ADDRESSEE_SCOPE | Notice::SITE_SCOPE) means
2366 * "only visible to people who are mentioned in the notice AND are users on this site."
2367 * Users on the site who are not mentioned in the notice will not be able to see the
2370 * @param Profile $profile The profile to check; pass null to check for public/unauthenticated users.
2372 * @return boolean whether the profile is in the notice's scope
2374 function inScope($profile)
2376 if (is_null($profile)) {
2377 $keypart = sprintf('notice:in-scope-for:%d:null', $this->id);
2379 $keypart = sprintf('notice:in-scope-for:%d:%d', $this->id, $profile->id);
2382 $result = self::cacheGet($keypart);
2384 if ($result === false) {
2386 if (Event::handle('StartNoticeInScope', array($this, $profile, &$bResult))) {
2387 $bResult = $this->_inScope($profile);
2388 Event::handle('EndNoticeInScope', array($this, $profile, &$bResult));
2390 $result = ($bResult) ? 1 : 0;
2391 self::cacheSet($keypart, $result, 0, 300);
2394 return ($result == 1) ? true : false;
2397 protected function _inScope($profile)
2399 if (!is_null($this->scope)) {
2400 $scope = $this->scope;
2402 $scope = self::defaultScope();
2405 // If there's no scope, anyone (even anon) is in scope.
2407 if ($scope == 0) { // Not private
2409 return !$this->isHiddenSpam($profile);
2411 } else { // Private, somehow
2413 // If there's scope, anon cannot be in scope
2415 if (empty($profile)) {
2419 // Author is always in scope
2421 if ($this->profile_id == $profile->id) {
2425 // Only for users on this site
2427 if (($scope & Notice::SITE_SCOPE) && !$profile->isLocal()) {
2431 // Only for users mentioned in the notice
2433 if ($scope & Notice::ADDRESSEE_SCOPE) {
2435 $repl = Reply::pkeyGet(array('notice_id' => $this->id,
2436 'profile_id' => $profile->id));
2443 // Only for members of the given group
2445 if ($scope & Notice::GROUP_SCOPE) {
2447 // XXX: just query for the single membership
2449 $groups = $this->getGroups();
2453 foreach ($groups as $group) {
2454 if ($profile->isMember($group)) {
2465 // Only for followers of the author
2469 if ($scope & Notice::FOLLOWER_SCOPE) {
2472 $author = $this->getProfile();
2473 } catch (Exception $e) {
2477 if (!Subscription::exists($profile, $author)) {
2482 return !$this->isHiddenSpam($profile);
2486 function isHiddenSpam($profile) {
2488 // Hide posts by silenced users from everyone but moderators.
2490 if (common_config('notice', 'hidespam')) {
2493 $author = $this->getProfile();
2494 } catch(Exception $e) {
2495 // If we can't get an author, keep it hidden.
2496 // XXX: technically not spam, but, whatever.
2500 if ($author->hasRole(Profile_role::SILENCED)) {
2501 if (empty($profile) || (($profile->id !== $author->id) && (!$profile->hasRight(Right::REVIEWSPAM)))) {
2510 static function groupsFromText($text, $profile)
2514 /* extract all !group */
2515 $count = preg_match_all('/(?:^|\s)!(' . Nickname::DISPLAY_FMT . ')/',
2523 foreach (array_unique($match[1]) as $nickname) {
2524 $group = User_group::getForNickname($nickname, $profile);
2525 if (!empty($group) && $profile->isMember($group)) {
2526 $groups[] = $group->id;
2533 protected $_parent = -1;
2535 public function getParent()
2537 if (empty($this->reply_to)) {
2538 // Should this also be NoResultException? I don't think so.
2539 throw new Exception('Notice has no parent');
2540 } elseif ($this->_parent === -1) { // local object cache
2541 $this->_parent = Notice::getKV('id', $this->reply_to);
2544 if (!($this->_parent instanceof Notice)) {
2545 throw new NoResultException($this->_parent);
2547 return $this->_parent;
2551 * Magic function called at serialize() time.
2553 * We use this to drop a couple process-specific references
2554 * from DB_DataObject which can cause trouble in future
2557 * @return array of variable names to include in serialization.
2562 $vars = parent::__sleep();
2563 $skip = array('_parent', '_profile', '_groups', '_attachments', '_faves', '_replies', '_repeats');
2564 return array_diff($vars, $skip);
2567 static function defaultScope()
2569 $scope = common_config('notice', 'defaultscope');
2570 if (is_null($scope)) {
2571 if (common_config('site', 'private')) {
2580 static function fillProfiles($notices)
2582 $map = self::getProfiles($notices);
2584 foreach ($notices as $notice) {
2585 if (array_key_exists($notice->profile_id, $map)) {
2586 $notice->_setProfile($map[$notice->profile_id]);
2590 return array_values($map);
2593 static function getProfiles(&$notices)
2596 foreach ($notices as $notice) {
2597 $ids[] = $notice->profile_id;
2600 $ids = array_unique($ids);
2602 return Profile::pivotGet('id', $ids);
2605 static function fillGroups(&$notices)
2607 $ids = self::_idsOf($notices);
2609 $gis = Group_inbox::listGet('notice_id', $ids);
2613 foreach ($gis as $id => $gi)
2617 $gids[] = $g->group_id;
2621 $gids = array_unique($gids);
2623 $group = User_group::pivotGet('id', $gids);
2625 foreach ($notices as $notice)
2628 $gi = $gis[$notice->id];
2629 foreach ($gi as $g) {
2630 $grps[] = $group[$g->group_id];
2632 $notice->_setGroups($grps);
2636 static function _idsOf(&$notices)
2639 foreach ($notices as $notice) {
2640 $ids[] = $notice->id;
2642 $ids = array_unique($ids);
2646 static function fillAttachments(&$notices)
2648 $ids = self::_idsOf($notices);
2650 $f2pMap = File_to_post::listGet('post_id', $ids);
2654 foreach ($f2pMap as $noticeId => $f2ps) {
2655 foreach ($f2ps as $f2p) {
2656 $fileIds[] = $f2p->file_id;
2660 $fileIds = array_unique($fileIds);
2662 $fileMap = File::pivotGet('id', $fileIds);
2664 foreach ($notices as $notice)
2667 $f2ps = $f2pMap[$notice->id];
2668 foreach ($f2ps as $f2p) {
2669 $files[] = $fileMap[$f2p->file_id];
2671 $notice->_setAttachments($files);
2678 * All faves of this notice
2680 * @return array Array of Fave objects
2685 if (isset($this->_faves) && is_array($this->_faves)) {
2686 return $this->_faves;
2688 $faveMap = Fave::listGet('notice_id', array($this->id));
2689 $this->_faves = $faveMap[$this->id];
2690 return $this->_faves;
2693 function _setFaves($faves)
2695 $this->_faves = $faves;
2698 static function fillFaves(&$notices)
2700 $ids = self::_idsOf($notices);
2701 $faveMap = Fave::listGet('notice_id', $ids);
2704 foreach ($faveMap as $id => $faves) {
2705 $cnt += count($faves);
2706 if (count($faves) > 0) {
2710 foreach ($notices as $notice) {
2711 $faves = $faveMap[$notice->id];
2712 $notice->_setFaves($faves);
2716 static function fillReplies(&$notices)
2718 $ids = self::_idsOf($notices);
2719 $replyMap = Reply::listGet('notice_id', $ids);
2720 foreach ($notices as $notice) {
2721 $replies = $replyMap[$notice->id];
2723 foreach ($replies as $reply) {
2724 $ids[] = $reply->profile_id;
2726 $notice->_setReplies($ids);
2730 protected $_repeats;
2732 function getRepeats()
2734 if (isset($this->_repeats) && is_array($this->_repeats)) {
2735 return $this->_repeats;
2737 $repeatMap = Notice::listGet('repeat_of', array($this->id));
2738 $this->_repeats = $repeatMap[$this->id];
2739 return $this->_repeats;
2742 function _setRepeats($repeats)
2744 $this->_repeats = $repeats;
2747 static function fillRepeats(&$notices)
2749 $ids = self::_idsOf($notices);
2750 $repeatMap = Notice::listGet('repeat_of', $ids);
2751 foreach ($notices as $notice) {
2752 $repeats = $repeatMap[$notice->id];
2753 $notice->_setRepeats($repeats);