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 = TagURI::mint("post:".$this->id);
1512 $act->time = strtotime($this->created);
1513 $act->content = common_xml_safe_str($this->rendered);
1515 $profile = $this->getProfile();
1517 $act->actor = ActivityObject::fromProfile($profile);
1518 $act->actor->extra[] = $profile->profileInfo($cur);
1520 $act->verb = $this->verb;
1522 if ($this->repeat_of) {
1523 $repeated = Notice::getKV('id', $this->repeat_of);
1524 if (!empty($repeated)) {
1525 $act->objects[] = $repeated->asActivity($cur);
1528 $act->objects[] = ActivityObject::fromNotice($this);
1531 // XXX: should this be handled by default processing for object entry?
1535 $tags = $this->getTags();
1537 foreach ($tags as $tag) {
1538 $cat = new AtomCategory();
1541 $act->categories[] = $cat;
1545 // XXX: use Atom Media and/or File activity objects instead
1547 $attachments = $this->attachments();
1549 foreach ($attachments as $attachment) {
1550 // Save local attachments
1551 if (!empty($attachment->filename)) {
1552 $act->attachments[] = ActivityObject::fromFile($attachment);
1556 $ctx = new ActivityContext();
1558 if (!empty($this->reply_to)) {
1559 $reply = Notice::getKV('id', $this->reply_to);
1560 if (!empty($reply)) {
1561 $ctx->replyToID = $reply->uri;
1562 $ctx->replyToUrl = $reply->bestUrl();
1566 $ctx->location = $this->getLocation();
1570 if (!empty($this->conversation)) {
1571 $conv = Conversation::getKV('id', $this->conversation);
1572 if (!empty($conv)) {
1573 $ctx->conversation = $conv->uri;
1577 $reply_ids = $this->getReplies();
1579 foreach ($reply_ids as $id) {
1580 $rprofile = Profile::getKV('id', $id);
1581 if (!empty($rprofile)) {
1582 $ctx->attention[] = $rprofile->getUri();
1583 $ctx->attentionType[$rprofile->getUri()] = ActivityObject::PERSON;
1587 $groups = $this->getGroups();
1589 foreach ($groups as $group) {
1590 $ctx->attention[] = $group->getUri();
1591 $ctx->attentionType[$group->getUri()] = ActivityObject::GROUP;
1594 switch ($this->scope) {
1595 case Notice::PUBLIC_SCOPE:
1596 $ctx->attention[] = "http://activityschema.org/collection/public";
1597 $ctx->attentionType["http://activityschema.org/collection/public"] = ActivityObject::COLLECTION;
1599 case Notice::FOLLOWER_SCOPE:
1600 $surl = common_local_url("subscribers", array('nickname' => $profile->nickname));
1601 $ctx->attention[] = $surl;
1602 $ctx->attentionType[$surl] = ActivityObject::COLLECTION;
1606 // XXX: deprecated; use ActivityVerb::SHARE instead
1610 if (!empty($this->repeat_of)) {
1611 $repeat = Notice::getKV('id', $this->repeat_of);
1612 if (!empty($repeat)) {
1613 $ctx->forwardID = $repeat->uri;
1614 $ctx->forwardUrl = $repeat->bestUrl();
1618 $act->context = $ctx;
1620 $source = $this->getSource();
1623 $act->generator = ActivityObject::fromNoticeSource($source);
1628 $atom_feed = $profile->getAtomFeed();
1630 if (!empty($atom_feed)) {
1632 $act->source = new ActivitySource();
1634 // XXX: we should store the actual feed ID
1636 $act->source->id = $atom_feed;
1638 // XXX: we should store the actual feed title
1640 $act->source->title = $profile->getBestName();
1642 $act->source->links['alternate'] = $profile->profileurl;
1643 $act->source->links['self'] = $atom_feed;
1645 $act->source->icon = $profile->avatarUrl(AVATAR_PROFILE_SIZE);
1647 $notice = $profile->getCurrentNotice();
1649 if (!empty($notice)) {
1650 $act->source->updated = self::utcDate($notice->created);
1653 $user = User::getKV('id', $profile->id);
1655 if (!empty($user)) {
1656 $act->source->links['license'] = common_config('license', 'url');
1660 if ($this->isLocal()) {
1661 $act->selfLink = common_local_url('ApiStatusesShow', array('id' => $this->id,
1662 'format' => 'atom'));
1663 $act->editLink = $act->selfLink;
1666 Event::handle('EndNoticeAsActivity', array($this, &$act));
1669 self::cacheSet(Cache::codeKey('notice:as-activity:'.$this->id), $act);
1674 // This has gotten way too long. Needs to be sliced up into functional bits
1675 // or ideally exported to a utility class.
1677 function asAtomEntry($namespace=false,
1682 $act = $this->asActivity($cur);
1683 $act->extra[] = $this->noticeInfo($cur);
1684 return $act->asString($namespace, $author, $source);
1688 * Extra notice info for atom entries
1690 * Clients use some extra notice info in the atom stream.
1691 * This gives it to them.
1693 * @param User $cur Current user
1695 * @return array representation of <statusnet:notice_info> element
1698 function noticeInfo($cur)
1700 // local notice ID (useful to clients for ordering)
1702 $noticeInfoAttr = array('local_id' => $this->id);
1706 $ns = $this->getSource();
1709 $noticeInfoAttr['source'] = $ns->code;
1710 if (!empty($ns->url)) {
1711 $noticeInfoAttr['source_link'] = $ns->url;
1712 if (!empty($ns->name)) {
1713 $noticeInfoAttr['source'] = '<a href="'
1714 . htmlspecialchars($ns->url)
1715 . '" rel="nofollow">'
1716 . htmlspecialchars($ns->name)
1722 // favorite and repeated
1725 $cp = $cur->getProfile();
1726 $noticeInfoAttr['favorite'] = ($cp->hasFave($this)) ? "true" : "false";
1727 $noticeInfoAttr['repeated'] = ($cp->hasRepeated($this)) ? "true" : "false";
1730 if (!empty($this->repeat_of)) {
1731 $noticeInfoAttr['repeat_of'] = $this->repeat_of;
1734 return array('statusnet:notice_info', $noticeInfoAttr, null);
1738 * Returns an XML string fragment with a reference to a notice as an
1739 * Activity Streams noun object with the given element type.
1741 * Assumes that 'activity' namespace has been previously defined.
1743 * @param string $element one of 'subject', 'object', 'target'
1747 function asActivityNoun($element)
1749 $noun = ActivityObject::fromNotice($this);
1750 return $noun->asString('activity:' . $element);
1755 if (!empty($this->url)) {
1757 } else if (!empty($this->uri) && preg_match('/^https?:/', $this->uri)) {
1760 return common_local_url('shownotice',
1761 array('notice' => $this->id));
1767 * Determine which notice, if any, a new notice is in reply to.
1769 * For conversation tracking, we try to see where this notice fits
1770 * in the tree. Rough algorithm is:
1772 * if (reply_to is set and valid) {
1774 * } else if ((source not API or Web) and (content starts with "T NAME" or "@name ")) {
1775 * return ID of last notice by initial @name in content;
1778 * Note that all @nickname instances will still be used to save "reply" records,
1779 * so the notice shows up in the mentioned users' "replies" tab.
1781 * @param integer $reply_to ID passed in by Web or API
1782 * @param integer $profile_id ID of author
1783 * @param string $source Source tag, like 'web' or 'gwibber'
1784 * @param string $content Final notice content
1786 * @return integer ID of replied-to notice, or null for not a reply.
1789 static function getReplyTo($reply_to, $profile_id, $source, $content)
1791 static $lb = array('xmpp', 'mail', 'sms', 'omb');
1793 // If $reply_to is specified, we check that it exists, and then
1794 // return it if it does
1796 if (!empty($reply_to)) {
1797 $reply_notice = Notice::getKV('id', $reply_to);
1798 if (!empty($reply_notice)) {
1799 return $reply_notice;
1803 // If it's not a "low bandwidth" source (one where you can't set
1804 // a reply_to argument), we return. This is mostly web and API
1807 if (!in_array($source, $lb)) {
1811 // Is there an initial @ or T?
1813 if (preg_match('/^T ([A-Z0-9]{1,64}) /', $content, $match) ||
1814 preg_match('/^@([a-z0-9]{1,64})\s+/', $content, $match)) {
1815 $nickname = common_canonical_nickname($match[1]);
1820 // Figure out who that is.
1822 $sender = Profile::getKV('id', $profile_id);
1823 if (empty($sender)) {
1827 $recipient = common_relative_profile($sender, $nickname, common_sql_now());
1829 if (empty($recipient)) {
1833 // Get their last notice
1835 $last = $recipient->getCurrentNotice();
1837 if (!empty($last)) {
1844 static function maxContent()
1846 $contentlimit = common_config('notice', 'contentlimit');
1847 // null => use global limit (distinct from 0!)
1848 if (is_null($contentlimit)) {
1849 $contentlimit = common_config('site', 'textlimit');
1851 return $contentlimit;
1854 static function contentTooLong($content)
1856 $contentlimit = self::maxContent();
1857 return ($contentlimit > 0 && !empty($content) && (mb_strlen($content) > $contentlimit));
1860 function getLocation()
1864 if (!empty($this->location_id) && !empty($this->location_ns)) {
1865 $location = Location::fromId($this->location_id, $this->location_ns);
1868 if (is_null($location)) { // no ID, or Location::fromId() failed
1869 if (!empty($this->lat) && !empty($this->lon)) {
1870 $location = Location::fromLatLon($this->lat, $this->lon);
1878 * Convenience function for posting a repeat of an existing message.
1880 * @param int $repeater_id: profile ID of user doing the repeat
1881 * @param string $source: posting source key, eg 'web', 'api', etc
1884 * @throws Exception on failure or permission problems
1886 function repeat($repeater_id, $source)
1888 $author = Profile::getKV('id', $this->profile_id);
1890 // TRANS: Message used to repeat a notice. RT is the abbreviation of 'retweet'.
1891 // TRANS: %1$s is the repeated user's name, %2$s is the repeated notice.
1892 $content = sprintf(_('RT @%1$s %2$s'),
1896 $maxlen = common_config('site', 'textlimit');
1897 if ($maxlen > 0 && mb_strlen($content) > $maxlen) {
1898 // Web interface and current Twitter API clients will
1899 // pull the original notice's text, but some older
1900 // clients and RSS/Atom feeds will see this trimmed text.
1902 // Unfortunately this is likely to lose tags or URLs
1903 // at the end of long notices.
1904 $content = mb_substr($content, 0, $maxlen - 4) . ' ...';
1907 // Scope is same as this one's
1909 return self::saveNew($repeater_id,
1912 array('repeat_of' => $this->id,
1913 'scope' => $this->scope));
1916 // These are supposed to be in chron order!
1918 function repeatStream($limit=100)
1920 $cache = Cache::instance();
1922 if (empty($cache)) {
1923 $ids = $this->_repeatStreamDirect($limit);
1925 $idstr = $cache->get(Cache::key('notice:repeats:'.$this->id));
1926 if ($idstr !== false) {
1927 if (empty($idstr)) {
1930 $ids = explode(',', $idstr);
1933 $ids = $this->_repeatStreamDirect(100);
1934 $cache->set(Cache::key('notice:repeats:'.$this->id), implode(',', $ids));
1937 // We do a max of 100, so slice down to limit
1938 $ids = array_slice($ids, 0, $limit);
1942 return NoticeStream::getStreamByIds($ids);
1945 function _repeatStreamDirect($limit)
1947 $notice = new Notice();
1949 $notice->selectAdd(); // clears it
1950 $notice->selectAdd('id');
1952 $notice->repeat_of = $this->id;
1954 $notice->orderBy('created, id'); // NB: asc!
1956 if (!is_null($limit)) {
1957 $notice->limit(0, $limit);
1960 return $notice->fetchAll('id');
1963 function locationOptions($lat, $lon, $location_id, $location_ns, $profile = null)
1967 if (!empty($location_id) && !empty($location_ns)) {
1968 $options['location_id'] = $location_id;
1969 $options['location_ns'] = $location_ns;
1971 $location = Location::fromId($location_id, $location_ns);
1973 if (!empty($location)) {
1974 $options['lat'] = $location->lat;
1975 $options['lon'] = $location->lon;
1978 } else if (!empty($lat) && !empty($lon)) {
1979 $options['lat'] = $lat;
1980 $options['lon'] = $lon;
1982 $location = Location::fromLatLon($lat, $lon);
1984 if (!empty($location)) {
1985 $options['location_id'] = $location->location_id;
1986 $options['location_ns'] = $location->location_ns;
1988 } else if (!empty($profile)) {
1989 if (isset($profile->lat) && isset($profile->lon)) {
1990 $options['lat'] = $profile->lat;
1991 $options['lon'] = $profile->lon;
1994 if (isset($profile->location_id) && isset($profile->location_ns)) {
1995 $options['location_id'] = $profile->location_id;
1996 $options['location_ns'] = $profile->location_ns;
2003 function clearReplies()
2005 $replyNotice = new Notice();
2006 $replyNotice->reply_to = $this->id;
2008 //Null any notices that are replies to this notice
2010 if ($replyNotice->find()) {
2011 while ($replyNotice->fetch()) {
2012 $orig = clone($replyNotice);
2013 $replyNotice->reply_to = null;
2014 $replyNotice->update($orig);
2020 $reply = new Reply();
2021 $reply->notice_id = $this->id;
2023 if ($reply->find()) {
2024 while($reply->fetch()) {
2025 self::blow('reply:stream:%d', $reply->profile_id);
2033 function clearFiles()
2035 $f2p = new File_to_post();
2037 $f2p->post_id = $this->id;
2040 while ($f2p->fetch()) {
2044 // FIXME: decide whether to delete File objects
2045 // ...and related (actual) files
2048 function clearRepeats()
2050 $repeatNotice = new Notice();
2051 $repeatNotice->repeat_of = $this->id;
2053 //Null any notices that are repeats of this notice
2055 if ($repeatNotice->find()) {
2056 while ($repeatNotice->fetch()) {
2057 $orig = clone($repeatNotice);
2058 $repeatNotice->repeat_of = null;
2059 $repeatNotice->update($orig);
2064 function clearFaves()
2067 $fave->notice_id = $this->id;
2069 if ($fave->find()) {
2070 while ($fave->fetch()) {
2071 self::blow('fave:ids_by_user_own:%d', $fave->user_id);
2072 self::blow('fave:ids_by_user_own:%d;last', $fave->user_id);
2073 self::blow('fave:ids_by_user:%d', $fave->user_id);
2074 self::blow('fave:ids_by_user:%d;last', $fave->user_id);
2082 function clearTags()
2084 $tag = new Notice_tag();
2085 $tag->notice_id = $this->id;
2088 while ($tag->fetch()) {
2089 self::blow('profile:notice_ids_tagged:%d:%s', $this->profile_id, Cache::keyize($tag->tag));
2090 self::blow('profile:notice_ids_tagged:%d:%s;last', $this->profile_id, Cache::keyize($tag->tag));
2091 self::blow('notice_tag:notice_ids:%s', Cache::keyize($tag->tag));
2092 self::blow('notice_tag:notice_ids:%s;last', Cache::keyize($tag->tag));
2100 function clearGroupInboxes()
2102 $gi = new Group_inbox();
2104 $gi->notice_id = $this->id;
2107 while ($gi->fetch()) {
2108 self::blow('user_group:notice_ids:%d', $gi->group_id);
2116 function distribute()
2118 // We always insert for the author so they don't
2120 Event::handle('StartNoticeDistribute', array($this));
2122 $user = User::getKV('id', $this->profile_id);
2123 if (!empty($user)) {
2124 Inbox::insertNotice($user->id, $this->id);
2127 if (common_config('queue', 'inboxes')) {
2128 // If there's a failure, we want to _force_
2129 // distribution at this point.
2131 $qm = QueueManager::get();
2132 $qm->enqueue($this, 'distrib');
2133 } catch (Exception $e) {
2134 // If the exception isn't transient, this
2135 // may throw more exceptions as DQH does
2136 // its own enqueueing. So, we ignore them!
2138 $handler = new DistribQueueHandler();
2139 $handler->handle($this);
2140 } catch (Exception $e) {
2141 common_log(LOG_ERR, "emergency redistribution resulted in " . $e->getMessage());
2143 // Re-throw so somebody smarter can handle it.
2147 $handler = new DistribQueueHandler();
2148 $handler->handle($this);
2154 $result = parent::insert();
2157 // Profile::hasRepeated() abuses pkeyGet(), so we
2158 // have to clear manually
2159 if (!empty($this->repeat_of)) {
2160 $c = self::memcache();
2162 $ck = self::multicacheKey('Notice',
2163 array('profile_id' => $this->profile_id,
2164 'repeat_of' => $this->repeat_of));
2174 * Get the source of the notice
2176 * @return Notice_source $ns A notice source object. 'code' is the only attribute
2177 * guaranteed to be populated.
2179 function getSource()
2181 $ns = new Notice_source();
2182 if (!empty($this->source)) {
2183 switch ($this->source) {
2190 $ns->code = $this->source;
2193 $ns = Notice_source::getKV($this->source);
2195 $ns = new Notice_source();
2196 $ns->code = $this->source;
2197 $app = Oauth_application::getKV('name', $this->source);
2199 $ns->name = $app->name;
2200 $ns->url = $app->source_url;
2210 * Determine whether the notice was locally created
2212 * @return boolean locality
2215 public function isLocal()
2217 return ($this->is_local == Notice::LOCAL_PUBLIC ||
2218 $this->is_local == Notice::LOCAL_NONPUBLIC);
2222 * Get the list of hash tags saved with this notice.
2224 * @return array of strings
2226 public function getTags()
2230 $keypart = sprintf('notice:tags:%d', $this->id);
2232 $tagstr = self::cacheGet($keypart);
2234 if ($tagstr !== false) {
2235 $tags = explode(',', $tagstr);
2237 $tag = new Notice_tag();
2238 $tag->notice_id = $this->id;
2240 while ($tag->fetch()) {
2241 $tags[] = $tag->tag;
2244 self::cacheSet($keypart, implode(',', $tags));
2250 static private function utcDate($dt)
2252 $dateStr = date('d F Y H:i:s', strtotime($dt));
2253 $d = new DateTime($dateStr, new DateTimeZone('UTC'));
2254 return $d->format(DATE_W3C);
2258 * Look up the creation timestamp for a given notice ID, even
2259 * if it's been deleted.
2262 * @return mixed string recorded creation timestamp, or false if can't be found
2264 public static function getAsTimestamp($id)
2270 $notice = Notice::getKV('id', $id);
2272 return $notice->created;
2275 $deleted = Deleted_notice::getKV('id', $id);
2277 return $deleted->created;
2284 * Build an SQL 'where' fragment for timestamp-based sorting from a since_id
2285 * parameter, matching notices posted after the given one (exclusive).
2287 * If the referenced notice can't be found, will return false.
2290 * @param string $idField
2291 * @param string $createdField
2292 * @return mixed string or false if no match
2294 public static function whereSinceId($id, $idField='id', $createdField='created')
2296 $since = Notice::getAsTimestamp($id);
2298 return sprintf("($createdField = '%s' and $idField > %d) or ($createdField > '%s')", $since, $id, $since);
2304 * Build an SQL 'where' fragment for timestamp-based sorting from a since_id
2305 * parameter, matching notices posted after the given one (exclusive), and
2306 * if necessary add it to the data object's query.
2308 * @param DB_DataObject $obj
2310 * @param string $idField
2311 * @param string $createdField
2312 * @return mixed string or false if no match
2314 public static function addWhereSinceId(DB_DataObject $obj, $id, $idField='id', $createdField='created')
2316 $since = self::whereSinceId($id, $idField, $createdField);
2318 $obj->whereAdd($since);
2323 * Build an SQL 'where' fragment for timestamp-based sorting from a max_id
2324 * parameter, matching notices posted before the given one (inclusive).
2326 * If the referenced notice can't be found, will return false.
2329 * @param string $idField
2330 * @param string $createdField
2331 * @return mixed string or false if no match
2333 public static function whereMaxId($id, $idField='id', $createdField='created')
2335 $max = Notice::getAsTimestamp($id);
2337 return sprintf("($createdField < '%s') or ($createdField = '%s' and $idField <= %d)", $max, $max, $id);
2343 * Build an SQL 'where' fragment for timestamp-based sorting from a max_id
2344 * parameter, matching notices posted before the given one (inclusive), and
2345 * if necessary add it to the data object's query.
2347 * @param DB_DataObject $obj
2349 * @param string $idField
2350 * @param string $createdField
2351 * @return mixed string or false if no match
2353 public static function addWhereMaxId(DB_DataObject $obj, $id, $idField='id', $createdField='created')
2355 $max = self::whereMaxId($id, $idField, $createdField);
2357 $obj->whereAdd($max);
2363 if (common_config('public', 'localonly')) {
2364 return ($this->is_local == Notice::LOCAL_PUBLIC);
2366 return (($this->is_local != Notice::LOCAL_NONPUBLIC) &&
2367 ($this->is_local != Notice::GATEWAY));
2372 * Check that the given profile is allowed to read, respond to, or otherwise
2373 * act on this notice.
2375 * The $scope member is a bitmask of scopes, representing a logical AND of the
2376 * scope requirement. So, 0x03 (Notice::ADDRESSEE_SCOPE | Notice::SITE_SCOPE) means
2377 * "only visible to people who are mentioned in the notice AND are users on this site."
2378 * Users on the site who are not mentioned in the notice will not be able to see the
2381 * @param Profile $profile The profile to check; pass null to check for public/unauthenticated users.
2383 * @return boolean whether the profile is in the notice's scope
2385 function inScope($profile)
2387 if (is_null($profile)) {
2388 $keypart = sprintf('notice:in-scope-for:%d:null', $this->id);
2390 $keypart = sprintf('notice:in-scope-for:%d:%d', $this->id, $profile->id);
2393 $result = self::cacheGet($keypart);
2395 if ($result === false) {
2397 if (Event::handle('StartNoticeInScope', array($this, $profile, &$bResult))) {
2398 $bResult = $this->_inScope($profile);
2399 Event::handle('EndNoticeInScope', array($this, $profile, &$bResult));
2401 $result = ($bResult) ? 1 : 0;
2402 self::cacheSet($keypart, $result, 0, 300);
2405 return ($result == 1) ? true : false;
2408 protected function _inScope($profile)
2410 if (!is_null($this->scope)) {
2411 $scope = $this->scope;
2413 $scope = self::defaultScope();
2416 // If there's no scope, anyone (even anon) is in scope.
2418 if ($scope == 0) { // Not private
2420 return !$this->isHiddenSpam($profile);
2422 } else { // Private, somehow
2424 // If there's scope, anon cannot be in scope
2426 if (empty($profile)) {
2430 // Author is always in scope
2432 if ($this->profile_id == $profile->id) {
2436 // Only for users on this site
2438 if (($scope & Notice::SITE_SCOPE) && !$profile->isLocal()) {
2442 // Only for users mentioned in the notice
2444 if ($scope & Notice::ADDRESSEE_SCOPE) {
2446 $repl = Reply::pkeyGet(array('notice_id' => $this->id,
2447 'profile_id' => $profile->id));
2454 // Only for members of the given group
2456 if ($scope & Notice::GROUP_SCOPE) {
2458 // XXX: just query for the single membership
2460 $groups = $this->getGroups();
2464 foreach ($groups as $group) {
2465 if ($profile->isMember($group)) {
2476 // Only for followers of the author
2480 if ($scope & Notice::FOLLOWER_SCOPE) {
2483 $author = $this->getProfile();
2484 } catch (Exception $e) {
2488 if (!Subscription::exists($profile, $author)) {
2493 return !$this->isHiddenSpam($profile);
2497 function isHiddenSpam($profile) {
2499 // Hide posts by silenced users from everyone but moderators.
2501 if (common_config('notice', 'hidespam')) {
2504 $author = $this->getProfile();
2505 } catch(Exception $e) {
2506 // If we can't get an author, keep it hidden.
2507 // XXX: technically not spam, but, whatever.
2511 if ($author->hasRole(Profile_role::SILENCED)) {
2512 if (empty($profile) || (($profile->id !== $author->id) && (!$profile->hasRight(Right::REVIEWSPAM)))) {
2521 static function groupsFromText($text, $profile)
2525 /* extract all !group */
2526 $count = preg_match_all('/(?:^|\s)!(' . Nickname::DISPLAY_FMT . ')/',
2534 foreach (array_unique($match[1]) as $nickname) {
2535 $group = User_group::getForNickname($nickname, $profile);
2536 if (!empty($group) && $profile->isMember($group)) {
2537 $groups[] = $group->id;
2544 protected $_parent = -1;
2546 public function getParent()
2548 if (empty($this->reply_to)) {
2549 // Should this also be NoResultException? I don't think so.
2550 throw new Exception('Notice has no parent');
2551 } elseif ($this->_parent === -1) { // local object cache
2552 $this->_parent = Notice::getKV('id', $this->reply_to);
2555 if (!($this->_parent instanceof Notice)) {
2556 throw new NoResultException($this->_parent);
2558 return $this->_parent;
2562 * Magic function called at serialize() time.
2564 * We use this to drop a couple process-specific references
2565 * from DB_DataObject which can cause trouble in future
2568 * @return array of variable names to include in serialization.
2573 $vars = parent::__sleep();
2574 $skip = array('_parent', '_profile', '_groups', '_attachments', '_faves', '_replies', '_repeats');
2575 return array_diff($vars, $skip);
2578 static function defaultScope()
2580 $scope = common_config('notice', 'defaultscope');
2581 if (is_null($scope)) {
2582 if (common_config('site', 'private')) {
2591 static function fillProfiles($notices)
2593 $map = self::getProfiles($notices);
2595 foreach ($notices as $notice) {
2596 if (array_key_exists($notice->profile_id, $map)) {
2597 $notice->_setProfile($map[$notice->profile_id]);
2601 return array_values($map);
2604 static function getProfiles(&$notices)
2607 foreach ($notices as $notice) {
2608 $ids[] = $notice->profile_id;
2611 $ids = array_unique($ids);
2613 return Profile::pivotGet('id', $ids);
2616 static function fillGroups(&$notices)
2618 $ids = self::_idsOf($notices);
2620 $gis = Group_inbox::listGet('notice_id', $ids);
2624 foreach ($gis as $id => $gi)
2628 $gids[] = $g->group_id;
2632 $gids = array_unique($gids);
2634 $group = User_group::pivotGet('id', $gids);
2636 foreach ($notices as $notice)
2639 $gi = $gis[$notice->id];
2640 foreach ($gi as $g) {
2641 $grps[] = $group[$g->group_id];
2643 $notice->_setGroups($grps);
2647 static function _idsOf(&$notices)
2650 foreach ($notices as $notice) {
2651 $ids[] = $notice->id;
2653 $ids = array_unique($ids);
2657 static function fillAttachments(&$notices)
2659 $ids = self::_idsOf($notices);
2661 $f2pMap = File_to_post::listGet('post_id', $ids);
2665 foreach ($f2pMap as $noticeId => $f2ps) {
2666 foreach ($f2ps as $f2p) {
2667 $fileIds[] = $f2p->file_id;
2671 $fileIds = array_unique($fileIds);
2673 $fileMap = File::pivotGet('id', $fileIds);
2675 foreach ($notices as $notice)
2678 $f2ps = $f2pMap[$notice->id];
2679 foreach ($f2ps as $f2p) {
2680 $files[] = $fileMap[$f2p->file_id];
2682 $notice->_setAttachments($files);
2689 * All faves of this notice
2691 * @return array Array of Fave objects
2696 if (isset($this->_faves) && is_array($this->_faves)) {
2697 return $this->_faves;
2699 $faveMap = Fave::listGet('notice_id', array($this->id));
2700 $this->_faves = $faveMap[$this->id];
2701 return $this->_faves;
2704 function _setFaves($faves)
2706 $this->_faves = $faves;
2709 static function fillFaves(&$notices)
2711 $ids = self::_idsOf($notices);
2712 $faveMap = Fave::listGet('notice_id', $ids);
2715 foreach ($faveMap as $id => $faves) {
2716 $cnt += count($faves);
2717 if (count($faves) > 0) {
2721 foreach ($notices as $notice) {
2722 $faves = $faveMap[$notice->id];
2723 $notice->_setFaves($faves);
2727 static function fillReplies(&$notices)
2729 $ids = self::_idsOf($notices);
2730 $replyMap = Reply::listGet('notice_id', $ids);
2731 foreach ($notices as $notice) {
2732 $replies = $replyMap[$notice->id];
2734 foreach ($replies as $reply) {
2735 $ids[] = $reply->profile_id;
2737 $notice->_setReplies($ids);
2741 protected $_repeats;
2743 function getRepeats()
2745 if (isset($this->_repeats) && is_array($this->_repeats)) {
2746 return $this->_repeats;
2748 $repeatMap = Notice::listGet('repeat_of', array($this->id));
2749 $this->_repeats = $repeatMap[$this->id];
2750 return $this->_repeats;
2753 function _setRepeats($repeats)
2755 $this->_repeats = $repeats;
2758 static function fillRepeats(&$notices)
2760 $ids = self::_idsOf($notices);
2761 $repeatMap = Notice::listGet('repeat_of', $ids);
2762 foreach ($notices as $notice) {
2763 $repeats = $repeatMap[$notice->id];
2764 $notice->_setRepeats($repeats);