3 * StatusNet - the distributed open-source microblogging tool
4 * Copyright (C) 2008-2011 StatusNet, Inc.
6 * This program is free software: you can redistribute it and/or modify
7 * it under the terms of the GNU Affero General Public License as published by
8 * the Free Software Foundation, either version 3 of the License, or
9 * (at your option) any later version.
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU Affero General Public License for more details.
16 * You should have received a copy of the GNU Affero General Public License
17 * along with this program. If not, see <http://www.gnu.org/licenses/>.
21 * @author Brenda Wallace <shiny@cpan.org>
22 * @author Christopher Vollick <psycotica0@gmail.com>
23 * @author CiaranG <ciaran@ciarang.com>
24 * @author Craig Andrews <candrews@integralblue.com>
25 * @author Evan Prodromou <evan@controlezvous.ca>
26 * @author Gina Haeussge <osd@foosel.net>
27 * @author Jeffery To <jeffery.to@gmail.com>
28 * @author Mike Cochrane <mikec@mikenz.geek.nz>
29 * @author Robin Millette <millette@controlyourself.ca>
30 * @author Sarven Capadisli <csarven@controlyourself.ca>
31 * @author Tom Adams <tom@holizz.com>
32 * @author Mikael Nordfeldth <mmn@hethane.se>
33 * @copyright 2009 Free Software Foundation, Inc http://www.fsf.org
34 * @license GNU Affero General Public License http://www.gnu.org/licenses/
37 if (!defined('STATUSNET') && !defined('LACONICA')) {
42 * Table Definition for notice
44 require_once INSTALLDIR.'/classes/Memcached_DataObject.php';
46 /* We keep 200 notices, the max number of notices available per API request,
47 * in the memcached cache. */
49 define('NOTICE_CACHE_WINDOW', CachingNoticeStream::CACHE_WINDOW);
51 define('MAX_BOXCARS', 128);
53 class Notice extends Managed_DataObject
56 /* the code below is auto generated do not remove the above tag */
58 public $__table = 'notice'; // table name
59 public $id; // int(4) primary_key not_null
60 public $profile_id; // int(4) multiple_key not_null
61 public $uri; // varchar(255) unique_key
62 public $content; // text
63 public $rendered; // text
64 public $url; // varchar(255)
65 public $created; // datetime multiple_key not_null default_0000-00-00%2000%3A00%3A00
66 public $modified; // timestamp not_null default_CURRENT_TIMESTAMP
67 public $reply_to; // int(4)
68 public $is_local; // int(4)
69 public $source; // varchar(32)
70 public $conversation; // int(4)
71 public $lat; // decimal(10,7)
72 public $lon; // decimal(10,7)
73 public $location_id; // int(4)
74 public $location_ns; // int(4)
75 public $repeat_of; // int(4)
76 public $verb; // varchar(255)
77 public $object_type; // varchar(255)
78 public $scope; // int(4)
80 /* the code above is auto generated do not remove the tag below */
83 public static function schemaDef()
87 'id' => array('type' => 'serial', 'not null' => true, 'description' => 'unique identifier'),
88 'profile_id' => array('type' => 'int', 'not null' => true, 'description' => 'who made the update'),
89 'uri' => array('type' => 'varchar', 'length' => 255, 'description' => 'universally unique identifier, usually a tag URI'),
90 'content' => array('type' => 'text', 'description' => 'update content', 'collate' => 'utf8_general_ci'),
91 'rendered' => array('type' => 'text', 'description' => 'HTML version of the content'),
92 'url' => array('type' => 'varchar', 'length' => 255, 'description' => 'URL of any attachment (image, video, bookmark, whatever)'),
93 'created' => array('type' => 'datetime', 'not null' => true, 'description' => 'date this record was created'),
94 'modified' => array('type' => 'timestamp', 'not null' => true, 'description' => 'date this record was modified'),
95 'reply_to' => array('type' => 'int', 'description' => 'notice replied to (usually a guess)'),
96 'is_local' => array('type' => 'int', 'size' => 'tiny', 'default' => 0, 'description' => 'notice was generated by a user'),
97 'source' => array('type' => 'varchar', 'length' => 32, 'description' => 'source of comment, like "web", "im", or "clientname"'),
98 'conversation' => array('type' => 'int', 'description' => 'id of root notice in this conversation'),
99 'lat' => array('type' => 'numeric', 'precision' => 10, 'scale' => 7, 'description' => 'latitude'),
100 'lon' => array('type' => 'numeric', 'precision' => 10, 'scale' => 7, 'description' => 'longitude'),
101 'location_id' => array('type' => 'int', 'description' => 'location id if possible'),
102 'location_ns' => array('type' => 'int', 'description' => 'namespace for location'),
103 'repeat_of' => array('type' => 'int', 'description' => 'notice this is a repeat of'),
104 'object_type' => array('type' => 'varchar', 'length' => 255, 'description' => 'URI representing activity streams object type', 'default' => 'http://activitystrea.ms/schema/1.0/note'),
105 'verb' => array('type' => 'varchar', 'length' => 255, 'description' => 'URI representing activity streams verb', 'default' => 'http://activitystrea.ms/schema/1.0/post'),
106 'scope' => array('type' => 'int',
107 'description' => 'bit map for distribution scope; 0 = everywhere; 1 = this server only; 2 = addressees; 4 = followers; null = default'),
109 'primary key' => array('id'),
110 'unique keys' => array(
111 'notice_uri_key' => array('uri'),
113 'foreign keys' => array(
114 'notice_profile_id_fkey' => array('profile', array('profile_id' => 'id')),
115 'notice_reply_to_fkey' => array('notice', array('reply_to' => 'id')),
116 'notice_conversation_fkey' => array('conversation', array('conversation' => 'id')), # note... used to refer to notice.id
117 'notice_repeat_of_fkey' => array('notice', array('repeat_of' => 'id')), # @fixme: what about repeats of deleted notices?
120 'notice_created_id_is_local_idx' => array('created', 'id', 'is_local'),
121 'notice_profile_id_idx' => array('profile_id', 'created', 'id'),
122 'notice_repeat_of_created_id_idx' => array('repeat_of', 'created', 'id'),
123 'notice_conversation_created_id_idx' => array('conversation', 'created', 'id'),
124 'notice_replyto_idx' => array('reply_to')
128 if (common_config('search', 'type') == 'fulltext') {
129 $def['fulltext indexes'] = array('content' => array('content'));
136 const LOCAL_PUBLIC = 1;
138 const LOCAL_NONPUBLIC = -1;
141 const PUBLIC_SCOPE = 0; // Useful fake constant
142 const SITE_SCOPE = 1;
143 const ADDRESSEE_SCOPE = 2;
144 const GROUP_SCOPE = 4;
145 const FOLLOWER_SCOPE = 8;
147 protected $_profile = -1;
149 public function getProfile()
151 if ($this->_profile === -1) {
152 $this->_setProfile(Profile::getKV('id', $this->profile_id));
154 if (!$this->_profile instanceof Profile) {
155 throw new NoProfileException($this->profile_id);
157 return $this->_profile;
160 function _setProfile(Profile $profile)
162 $this->_profile = $profile;
167 // For auditing purposes, save a record that the notice
170 // @fixme we have some cases where things get re-run and so the
172 $deleted = Deleted_notice::getKV('id', $this->id);
175 $deleted = Deleted_notice::getKV('uri', $this->uri);
179 $deleted = new Deleted_notice();
181 $deleted->id = $this->id;
182 $deleted->profile_id = $this->profile_id;
183 $deleted->uri = $this->uri;
184 $deleted->created = $this->created;
185 $deleted->deleted = common_sql_now();
190 if (Event::handle('NoticeDeleteRelated', array($this))) {
192 // Clear related records
194 $this->clearReplies();
195 $this->clearRepeats();
198 $this->clearGroupInboxes();
201 // NOTE: we don't clear inboxes
202 // NOTE: we don't clear queue items
205 $result = parent::delete();
207 $this->blowOnDelete();
211 public function getUri()
216 public function getUrl()
218 // The risk is we start having empty urls and non-http uris...
219 return $this->url ?: $this->uri;
223 * Extract #hashtags from this notice's content and save them to the database.
227 /* extract all #hastags */
228 $count = preg_match_all('/(?:^|\s)#([\pL\pN_\-\.]{1,64})/u', strtolower($this->content), $match);
233 /* Add them to the database */
234 return $this->saveKnownTags($match[1]);
238 * Record the given set of hash tags in the db for this notice.
239 * Given tag strings will be normalized and checked for dupes.
241 function saveKnownTags($hashtags)
243 //turn each into their canonical tag
244 //this is needed to remove dupes before saving e.g. #hash.tag = #hashtag
245 for($i=0; $i<count($hashtags); $i++) {
246 /* elide characters we don't want in the tag */
247 $hashtags[$i] = common_canonical_tag($hashtags[$i]);
250 foreach(array_unique($hashtags) as $hashtag) {
251 $this->saveTag($hashtag);
252 self::blow('profile:notice_ids_tagged:%d:%s', $this->profile_id, $hashtag);
258 * Record a single hash tag as associated with this notice.
259 * Tag format and uniqueness must be validated by caller.
261 function saveTag($hashtag)
263 $tag = new Notice_tag();
264 $tag->notice_id = $this->id;
265 $tag->tag = $hashtag;
266 $tag->created = $this->created;
267 $id = $tag->insert();
270 // TRANS: Server exception. %s are the error details.
271 throw new ServerException(sprintf(_('Database error inserting hashtag: %s.'),
272 $last_error->message));
276 // if it's saved, blow its cache
277 $tag->blowCache(false);
281 * Save a new notice and push it out to subscribers' inboxes.
282 * Poster's permissions are checked before sending.
284 * @param int $profile_id Profile ID of the poster
285 * @param string $content source message text; links may be shortened
286 * per current user's preference
287 * @param string $source source key ('web', 'api', etc)
288 * @param array $options Associative array of optional properties:
289 * string 'created' timestamp of notice; defaults to now
290 * int 'is_local' source/gateway ID, one of:
291 * Notice::LOCAL_PUBLIC - Local, ok to appear in public timeline
292 * Notice::REMOTE - Sent from a remote service;
293 * hide from public timeline but show in
294 * local "and friends" timelines
295 * Notice::LOCAL_NONPUBLIC - Local, but hide from public timeline
296 * Notice::GATEWAY - From another non-OStatus service;
297 * will not appear in public views
298 * float 'lat' decimal latitude for geolocation
299 * float 'lon' decimal longitude for geolocation
300 * int 'location_id' geoname identifier
301 * int 'location_ns' geoname namespace to interpret location_id
302 * int 'reply_to'; notice ID this is a reply to
303 * int 'repeat_of'; notice ID this is a repeat of
304 * string 'uri' unique ID for notice; defaults to local notice URL
305 * string 'url' permalink to notice; defaults to local notice URL
306 * string 'rendered' rendered HTML version of content
307 * array 'replies' list of profile URIs for reply delivery in
308 * place of extracting @-replies from content.
309 * array 'groups' list of group IDs to deliver to, in place of
310 * extracting ! tags from content
311 * array 'tags' list of hashtag strings to save with the notice
312 * in place of extracting # tags from content
313 * array 'urls' list of attached/referred URLs to save with the
314 * notice in place of extracting links from content
315 * boolean 'distribute' whether to distribute the notice, default true
316 * string 'object_type' URL of the associated object type (default ActivityObject::NOTE)
317 * string 'verb' URL of the associated verb (default ActivityVerb::POST)
318 * int 'scope' Scope bitmask; default to SITE_SCOPE on private sites, 0 otherwise
320 * @fixme tag override
323 * @throws ClientException
325 static function saveNew($profile_id, $content, $source, array $options=null) {
326 $defaults = array('uri' => null,
331 'distribute' => true,
332 'object_type' => null,
335 if (!empty($options) && is_array($options)) {
336 $options = array_merge($defaults, $options);
342 if (!isset($is_local)) {
343 $is_local = Notice::LOCAL_PUBLIC;
346 $profile = Profile::getKV('id', $profile_id);
347 if (!$profile instanceof Profile) {
348 // TRANS: Client exception thrown when trying to save a notice for an unknown user.
349 throw new ClientException(_('Problem saving notice. Unknown user.'));
352 $user = User::getKV('id', $profile_id);
353 if ($user instanceof User) {
354 // Use the local user's shortening preferences, if applicable.
355 $final = $user->shortenLinks($content);
357 $final = common_shorten_links($content);
360 if (Notice::contentTooLong($final)) {
361 // TRANS: Client exception thrown if a notice contains too many characters.
362 throw new ClientException(_('Problem saving notice. Too long.'));
365 if (common_config('throttle', 'enabled') && !Notice::checkEditThrottle($profile_id)) {
366 common_log(LOG_WARNING, 'Excessive posting by profile #' . $profile_id . '; throttled.');
367 // TRANS: Client exception thrown when a user tries to post too many notices in a given time frame.
368 throw new ClientException(_('Too many notices too fast; take a breather '.
369 'and post again in a few minutes.'));
372 if (common_config('site', 'dupelimit') > 0 && !Notice::checkDupes($profile_id, $final)) {
373 common_log(LOG_WARNING, 'Dupe posting by profile #' . $profile_id . '; throttled.');
374 // TRANS: Client exception thrown when a user tries to post too many duplicate notices in a given time frame.
375 throw new ClientException(_('Too many duplicate messages too quickly;'.
376 ' take a breather and post again in a few minutes.'));
379 if (!$profile->hasRight(Right::NEWNOTICE)) {
380 common_log(LOG_WARNING, "Attempted post from user disallowed to post: " . $profile->nickname);
382 // TRANS: Client exception thrown when a user tries to post while being banned.
383 throw new ClientException(_('You are banned from posting notices on this site.'), 403);
386 $notice = new Notice();
387 $notice->profile_id = $profile_id;
389 $autosource = common_config('public', 'autosource');
391 // Sandboxed are non-false, but not 1, either
393 if (!$profile->hasRight(Right::PUBLICNOTICE) ||
394 ($source && $autosource && in_array($source, $autosource))) {
395 $notice->is_local = Notice::LOCAL_NONPUBLIC;
397 $notice->is_local = $is_local;
400 if (!empty($created)) {
401 $notice->created = $created;
403 $notice->created = common_sql_now();
406 $notice->content = $final;
408 $notice->source = $source;
412 // Get the groups here so we can figure out replies and such
414 if (!isset($groups)) {
415 $groups = self::groupsFromText($notice->content, $profile);
420 // Handle repeat case
422 if (isset($repeat_of)) {
424 // Check for a private one
426 $repeat = Notice::getKV('id', $repeat_of);
428 if (!($repeat instanceof Notice)) {
429 // TRANS: Client exception thrown in notice when trying to repeat a missing or deleted notice.
430 throw new ClientException(_('Cannot repeat; original notice is missing or deleted.'));
433 if ($profile->id == $repeat->profile_id) {
434 // TRANS: Client error displayed when trying to repeat an own notice.
435 throw new ClientException(_('You cannot repeat your own notice.'));
438 if ($repeat->scope != Notice::SITE_SCOPE &&
439 $repeat->scope != Notice::PUBLIC_SCOPE) {
440 // TRANS: Client error displayed when trying to repeat a non-public notice.
441 throw new ClientException(_('Cannot repeat a private notice.'), 403);
444 if (!$repeat->inScope($profile)) {
445 // The generic checks above should cover this, but let's be sure!
446 // TRANS: Client error displayed when trying to repeat a notice you cannot access.
447 throw new ClientException(_('Cannot repeat a notice you cannot read.'), 403);
450 if ($profile->hasRepeated($repeat)) {
451 // TRANS: Client error displayed when trying to repeat an already repeated notice.
452 throw new ClientException(_('You already repeated that notice.'));
455 $notice->repeat_of = $repeat_of;
457 $reply = self::getReplyTo($reply_to, $profile_id, $source, $final);
459 if (!empty($reply)) {
461 if (!$reply->inScope($profile)) {
462 // TRANS: Client error displayed when trying to reply to a notice a the target has no access to.
463 // TRANS: %1$s is a user nickname, %2$d is a notice ID (number).
464 throw new ClientException(sprintf(_('%1$s has no access to notice %2$d.'),
465 $profile->nickname, $reply->id), 403);
468 $notice->reply_to = $reply->id;
469 $notice->conversation = $reply->conversation;
471 // If the original is private to a group, and notice has no group specified,
472 // make it to the same group(s)
474 if (empty($groups) && ($reply->scope & Notice::GROUP_SCOPE)) {
476 $replyGroups = $reply->getGroups();
477 foreach ($replyGroups as $group) {
478 if ($profile->isMember($group)) {
479 $groups[] = $group->id;
488 if (!empty($lat) && !empty($lon)) {
493 if (!empty($location_ns) && !empty($location_id)) {
494 $notice->location_id = $location_id;
495 $notice->location_ns = $location_ns;
498 if (!empty($rendered)) {
499 $notice->rendered = $rendered;
501 $notice->rendered = common_render_content($final, $notice);
505 if (!empty($notice->repeat_of)) {
506 $notice->verb = ActivityVerb::SHARE;
507 $notice->object_type = ActivityObject::ACTIVITY;
509 $notice->verb = ActivityVerb::POST;
512 $notice->verb = $verb;
515 if (empty($object_type)) {
516 $notice->object_type = (empty($notice->reply_to)) ? ActivityObject::NOTE : ActivityObject::COMMENT;
518 $notice->object_type = $object_type;
521 if (is_null($scope)) { // 0 is a valid value
522 if (!empty($reply)) {
523 $notice->scope = $reply->scope;
525 $notice->scope = self::defaultScope();
528 $notice->scope = $scope;
531 // For private streams
534 $user = $profile->getUser();
536 if ($user->private_stream &&
537 ($notice->scope == Notice::PUBLIC_SCOPE ||
538 $notice->scope == Notice::SITE_SCOPE)) {
539 $notice->scope |= Notice::FOLLOWER_SCOPE;
541 } catch (NoSuchUserException $e) {
542 // Cannot handle private streams for remote profiles
545 // Force the scope for private groups
547 foreach ($groups as $groupId) {
548 $group = User_group::getKV('id', $groupId);
549 if ($group instanceof User_group) {
550 if ($group->force_scope) {
551 $notice->scope |= Notice::GROUP_SCOPE;
557 if (Event::handle('StartNoticeSave', array(&$notice))) {
559 // XXX: some of these functions write to the DB
561 $id = $notice->insert();
564 common_log_db_error($notice, 'INSERT', __FILE__);
565 // TRANS: Server exception thrown when a notice cannot be saved.
566 throw new ServerException(_('Problem saving notice.'));
569 // Update ID-dependent columns: URI, conversation
571 $orig = clone($notice);
576 $notice->uri = common_notice_uri($notice);
580 // If it's not part of a conversation, it's
581 // the beginning of a new conversation.
583 if (empty($notice->conversation)) {
584 $conv = Conversation::create();
585 $notice->conversation = $conv->id;
590 if (!$notice->update($orig)) {
591 common_log_db_error($notice, 'UPDATE', __FILE__);
592 // TRANS: Server exception thrown when a notice cannot be updated.
593 throw new ServerException(_('Problem saving notice.'));
599 // Clear the cache for subscribed users, so they'll update at next request
600 // XXX: someone clever could prepend instead of clearing the cache
602 $notice->blowOnInsert();
604 // Save per-notice metadata...
606 if (isset($replies)) {
607 $notice->saveKnownReplies($replies);
609 $notice->saveReplies();
613 $notice->saveKnownTags($tags);
618 // Note: groups may save tags, so must be run after tags are saved
619 // to avoid errors on duplicates.
620 // Note: groups should always be set.
622 $notice->saveKnownGroups($groups);
625 $notice->saveKnownUrls($urls);
631 // Prepare inbox delivery, may be queued to background.
632 $notice->distribute();
638 function blowOnInsert($conversation = false)
640 $this->blowStream('profile:notice_ids:%d', $this->profile_id);
642 if ($this->isPublic()) {
643 $this->blowStream('public');
646 self::blow('notice:list-ids:conversation:%s', $this->conversation);
647 self::blow('conversation:notice_count:%d', $this->conversation);
649 if (!empty($this->repeat_of)) {
650 // XXX: we should probably only use one of these
651 $this->blowStream('notice:repeats:%d', $this->repeat_of);
652 self::blow('notice:list-ids:repeat_of:%d', $this->repeat_of);
655 $original = Notice::getKV('id', $this->repeat_of);
657 if ($original instanceof Notice) {
658 $originalUser = User::getKV('id', $original->profile_id);
659 if ($originalUser instanceof User) {
660 $this->blowStream('user:repeats_of_me:%d', $originalUser->id);
664 $profile = Profile::getKV($this->profile_id);
666 if ($profile instanceof Profile) {
667 $profile->blowNoticeCount();
670 $ptags = $this->getProfileTags();
671 foreach ($ptags as $ptag) {
672 $ptag->blowNoticeStreamCache();
677 * Clear cache entries related to this notice at delete time.
678 * Necessary to avoid breaking paging on public, profile timelines.
680 function blowOnDelete()
682 $this->blowOnInsert();
684 self::blow('profile:notice_ids:%d;last', $this->profile_id);
686 if ($this->isPublic()) {
687 self::blow('public;last');
690 self::blow('fave:by_notice', $this->id);
692 if ($this->conversation) {
693 // In case we're the first, will need to calc a new root.
694 self::blow('notice:conversation_root:%d', $this->conversation);
697 $ptags = $this->getProfileTags();
698 foreach ($ptags as $ptag) {
699 $ptag->blowNoticeStreamCache(true);
703 function blowStream()
705 $c = self::memcache();
711 $args = func_get_args();
713 $format = array_shift($args);
715 $keyPart = vsprintf($format, $args);
717 $cacheKey = Cache::key($keyPart);
719 $c->delete($cacheKey);
721 // delete the "last" stream, too, if this notice is
722 // older than the top of that stream
724 $lastKey = $cacheKey.';last';
726 $lastStr = $c->get($lastKey);
728 if ($lastStr !== false) {
729 $window = explode(',', $lastStr);
730 $lastID = $window[0];
731 $lastNotice = Notice::getKV('id', $lastID);
732 if (!$lastNotice instanceof Notice // just weird
733 || strtotime($lastNotice->created) >= strtotime($this->created)) {
734 $c->delete($lastKey);
739 /** save all urls in the notice to the db
741 * follow redirects and save all available file information
742 * (mimetype, date, size, oembed, etc.)
746 function saveUrls() {
747 if (common_config('attachments', 'process_links')) {
748 common_replace_urls_callback($this->content, array($this, 'saveUrl'), $this->id);
753 * Save the given URLs as related links/attachments to the db
755 * follow redirects and save all available file information
756 * (mimetype, date, size, oembed, etc.)
760 function saveKnownUrls($urls)
762 if (common_config('attachments', 'process_links')) {
763 // @fixme validation?
764 foreach (array_unique($urls) as $url) {
765 File::processNew($url, $this->id);
773 function saveUrl($url, $notice_id) {
774 File::processNew($url, $notice_id);
777 static function checkDupes($profile_id, $content) {
778 $profile = Profile::getKV($profile_id);
779 if (!$profile instanceof Profile) {
782 $notice = $profile->getNotices(0, CachingNoticeStream::CACHE_WINDOW);
783 if (!empty($notice)) {
785 while ($notice->fetch()) {
786 if (time() - strtotime($notice->created) >= common_config('site', 'dupelimit')) {
788 } else if ($notice->content == $content) {
793 // If we get here, oldest item in cache window is not
794 // old enough for dupe limit; do direct check against DB
795 $notice = new Notice();
796 $notice->profile_id = $profile_id;
797 $notice->content = $content;
798 $threshold = common_sql_date(time() - common_config('site', 'dupelimit'));
799 $notice->whereAdd(sprintf("created > '%s'", $notice->escape($threshold)));
801 $cnt = $notice->count();
805 static function checkEditThrottle($profile_id) {
806 $profile = Profile::getKV($profile_id);
807 if (!$profile instanceof Profile) {
810 // Get the Nth notice
811 $notice = $profile->getNotices(common_config('throttle', 'count') - 1, 1);
812 if ($notice && $notice->fetch()) {
813 // If the Nth notice was posted less than timespan seconds ago
814 if (time() - strtotime($notice->created) <= common_config('throttle', 'timespan')) {
819 // Either not N notices in the stream, OR the Nth was not posted within timespan seconds
823 protected $_attachments = -1;
825 function attachments() {
827 if ($this->_attachments != -1) {
828 return $this->_attachments;
831 $f2ps = File_to_post::listGet('post_id', array($this->id));
835 foreach ($f2ps[$this->id] as $f2p) {
836 $ids[] = $f2p->file_id;
839 $files = File::multiGet('id', $ids);
841 $this->_attachments = $files->fetchAll();
843 return $this->_attachments;
846 function _setAttachments($attachments)
848 $this->_attachments = $attachments;
851 function publicStream($offset=0, $limit=20, $since_id=0, $max_id=0)
853 $stream = new PublicNoticeStream();
854 return $stream->getNotices($offset, $limit, $since_id, $max_id);
858 function conversationStream($id, $offset=0, $limit=20, $since_id=0, $max_id=0)
860 $stream = new ConversationNoticeStream($id);
862 return $stream->getNotices($offset, $limit, $since_id, $max_id);
866 * Is this notice part of an active conversation?
868 * @return boolean true if other messages exist in the same
869 * conversation, false if this is the only one
871 function hasConversation()
873 if (!empty($this->conversation)) {
874 $conversation = Notice::conversationStream(
880 if ($conversation->N > 0) {
888 * Grab the earliest notice from this conversation.
890 * @return Notice or null
892 function conversationRoot($profile=-1)
894 // XXX: can this happen?
896 if (empty($this->conversation)) {
900 // Get the current profile if not specified
902 if (is_int($profile) && $profile == -1) {
903 $profile = Profile::current();
906 // If this notice is out of scope, no root for you!
908 if (!$this->inScope($profile)) {
912 // If this isn't a reply to anything, then it's its own
915 if (empty($this->reply_to)) {
919 if (is_null($profile)) {
920 $keypart = sprintf('notice:conversation_root:%d:null', $this->id);
922 $keypart = sprintf('notice:conversation_root:%d:%d',
927 $root = self::cacheGet($keypart);
929 if ($root !== false && $root->inScope($profile)) {
936 $parent = $last->getParent();
937 if ($parent->inScope($profile)) {
941 } catch (Exception $e) {
942 // Latest notice has no parent
944 // No parent, or parent out of scope
949 self::cacheSet($keypart, $root);
955 * Pull up a full list of local recipients who will be getting
956 * this notice in their inbox. Results will be cached, so don't
957 * change the input data wily-nilly!
959 * @param array $groups optional list of Group objects;
960 * if left empty, will be loaded from group_inbox records
961 * @param array $recipient optional list of reply profile ids
962 * if left empty, will be loaded from reply records
963 * @return array associating recipient user IDs with an inbox source constant
965 function whoGets(array $groups=null, array $recipients=null)
967 $c = self::memcache();
970 $ni = $c->get(Cache::key('notice:who_gets:'.$this->id));
976 if (is_null($groups)) {
977 $groups = $this->getGroups();
980 if (is_null($recipients)) {
981 $recipients = $this->getReplies();
984 $users = $this->getSubscribedUsers();
985 $ptags = $this->getProfileTags();
987 // FIXME: kind of ignoring 'transitional'...
988 // we'll probably stop supporting inboxless mode
993 // Give plugins a chance to add folks in at start...
994 if (Event::handle('StartNoticeWhoGets', array($this, &$ni))) {
996 foreach ($users as $id) {
997 $ni[$id] = NOTICE_INBOX_SOURCE_SUB;
1000 foreach ($groups as $group) {
1001 $users = $group->getUserMembers();
1002 foreach ($users as $id) {
1003 if (!array_key_exists($id, $ni)) {
1004 $ni[$id] = NOTICE_INBOX_SOURCE_GROUP;
1009 foreach ($ptags as $ptag) {
1010 $users = $ptag->getUserSubscribers();
1011 foreach ($users as $id) {
1012 if (!array_key_exists($id, $ni)) {
1013 $ni[$id] = NOTICE_INBOX_SOURCE_PROFILE_TAG;
1018 foreach ($recipients as $recipient) {
1019 if (!array_key_exists($recipient, $ni)) {
1020 $ni[$recipient] = NOTICE_INBOX_SOURCE_REPLY;
1024 // Exclude any deleted, non-local, or blocking recipients.
1025 $profile = $this->getProfile();
1026 $originalProfile = null;
1027 if ($this->repeat_of) {
1028 // Check blocks against the original notice's poster as well.
1029 $original = Notice::getKV('id', $this->repeat_of);
1030 if ($original instanceof Notice) {
1031 $originalProfile = $original->getProfile();
1035 foreach ($ni as $id => $source) {
1037 $user = User::getKV('id', $id);
1038 if (!$user instanceof User ||
1039 $user->hasBlocked($profile) ||
1040 ($originalProfile && $user->hasBlocked($originalProfile))) {
1043 } catch (UserNoProfileException $e) {
1044 // User doesn't have a profile; invalid; skip them.
1049 // Give plugins a chance to filter out...
1050 Event::handle('EndNoticeWhoGets', array($this, &$ni));
1054 // XXX: pack this data better
1055 $c->set(Cache::key('notice:who_gets:'.$this->id), $ni);
1062 * Adds this notice to the inboxes of each local user who should receive
1063 * it, based on author subscriptions, group memberships, and @-replies.
1065 * Warning: running a second time currently will make items appear
1066 * multiple times in users' inboxes.
1068 * @fixme make more robust against errors
1069 * @fixme break up massive deliveries to smaller background tasks
1071 * @param array $groups optional list of Group objects;
1072 * if left empty, will be loaded from group_inbox records
1073 * @param array $recipient optional list of reply profile ids
1074 * if left empty, will be loaded from reply records
1076 function addToInboxes(array $groups=null, array $recipients=null)
1078 $ni = $this->whoGets($groups, $recipients);
1080 $ids = array_keys($ni);
1082 // We remove the author (if they're a local user),
1083 // since we'll have already done this in distribute()
1085 $i = array_search($this->profile_id, $ids);
1093 Inbox::bulkInsert($this->id, $ids);
1098 function getSubscribedUsers()
1102 if(common_config('db','quote_identifiers'))
1103 $user_table = '"user"';
1104 else $user_table = 'user';
1108 'FROM '. $user_table .' JOIN subscription '.
1109 'ON '. $user_table .'.id = subscription.subscriber ' .
1110 'WHERE subscription.subscribed = %d ';
1112 $user->query(sprintf($qry, $this->profile_id));
1116 while ($user->fetch()) {
1125 function getProfileTags()
1127 $profile = $this->getProfile();
1128 $list = $profile->getOtherTags($profile);
1131 while($list->fetch()) {
1132 $ptags[] = clone($list);
1139 * Record this notice to the given group inboxes for delivery.
1140 * Overrides the regular parsing of !group markup.
1142 * @param string $group_ids
1143 * @fixme might prefer URIs as identifiers, as for replies?
1144 * best with generalizations on user_group to support
1145 * remote groups better.
1147 function saveKnownGroups($group_ids)
1149 if (!is_array($group_ids)) {
1150 // TRANS: Server exception thrown when no array is provided to the method saveKnownGroups().
1151 throw new ServerException(_('Bad type provided to saveKnownGroups.'));
1155 foreach (array_unique($group_ids) as $id) {
1156 $group = User_group::getKV('id', $id);
1158 common_log(LOG_ERR, "Local delivery to group id $id, $group->nickname");
1159 $result = $this->addToGroupInbox($group);
1161 common_log_db_error($gi, 'INSERT', __FILE__);
1164 if (common_config('group', 'addtag')) {
1165 // we automatically add a tag for every group name, too
1167 $tag = Notice_tag::pkeyGet(array('tag' => common_canonical_tag($group->nickname),
1168 'notice_id' => $this->id));
1170 if (is_null($tag)) {
1171 $this->saveTag($group->nickname);
1175 $groups[] = clone($group);
1177 common_log(LOG_ERR, "Local delivery to group id $id skipped, doesn't exist");
1185 * Parse !group delivery and record targets into group_inbox.
1186 * @return array of Group objects
1188 function saveGroups()
1190 // Don't save groups for repeats
1192 if (!empty($this->repeat_of)) {
1196 $profile = $this->getProfile();
1198 $groups = self::groupsFromText($this->content, $profile);
1200 /* Add them to the database */
1202 foreach ($groups as $group) {
1203 /* XXX: remote groups. */
1205 if (empty($group)) {
1210 if ($profile->isMember($group)) {
1212 $result = $this->addToGroupInbox($group);
1215 common_log_db_error($gi, 'INSERT', __FILE__);
1218 $groups[] = clone($group);
1225 function addToGroupInbox($group)
1227 $gi = Group_inbox::pkeyGet(array('group_id' => $group->id,
1228 'notice_id' => $this->id));
1230 if (!$gi instanceof Group_inbox) {
1232 $gi = new Group_inbox();
1234 $gi->group_id = $group->id;
1235 $gi->notice_id = $this->id;
1236 $gi->created = $this->created;
1238 $result = $gi->insert();
1241 common_log_db_error($gi, 'INSERT', __FILE__);
1242 // TRANS: Server exception thrown when an update for a group inbox fails.
1243 throw new ServerException(_('Problem saving group inbox.'));
1246 self::blow('user_group:notice_ids:%d', $gi->group_id);
1253 * Save reply records indicating that this notice needs to be
1254 * delivered to the local users with the given URIs.
1256 * Since this is expected to be used when saving foreign-sourced
1257 * messages, we won't deliver to any remote targets as that's the
1258 * source service's responsibility.
1260 * Mail notifications etc will be handled later.
1262 * @param array $uris Array of unique identifier URIs for recipients
1264 function saveKnownReplies(array $uris)
1270 $sender = Profile::getKV($this->profile_id);
1272 foreach (array_unique($uris) as $uri) {
1274 $profile = Profile::fromURI($uri);
1276 if (!$profile instanceof Profile) {
1277 common_log(LOG_WARNING, "Unable to determine profile for URI '$uri'");
1281 if ($profile->hasBlocked($sender)) {
1282 common_log(LOG_INFO, "Not saving reply to profile {$profile->id} ($uri) from sender {$sender->id} because of a block.");
1286 $this->saveReply($profile->id);
1287 self::blow('reply:stream:%d', $profile->id);
1294 * Pull @-replies from this message's content in StatusNet markup format
1295 * and save reply records indicating that this message needs to be
1296 * delivered to those users.
1298 * Mail notifications to local profiles will be sent later.
1300 * @return array of integer profile IDs
1303 function saveReplies()
1305 // Don't save reply data for repeats
1307 if (!empty($this->repeat_of)) {
1311 $sender = Profile::getKV($this->profile_id);
1315 // If it's a reply, save for the replied-to author
1317 $parent = $this->getParent();
1318 $author = $parent->getProfile();
1319 if ($author instanceof Profile) {
1320 $this->saveReply($author->id);
1321 $replied[$author->id] = 1;
1322 self::blow('reply:stream:%d', $author->id);
1324 } catch (Exception $e) {
1325 // Not a reply, since it has no parent!
1328 // @todo ideally this parser information would only
1329 // be calculated once.
1331 $mentions = common_find_mentions($this->content, $this);
1333 // store replied only for first @ (what user/notice what the reply directed,
1334 // we assume first @ is it)
1336 foreach ($mentions as $mention) {
1338 foreach ($mention['mentioned'] as $mentioned) {
1340 // skip if they're already covered
1342 if (!empty($replied[$mentioned->id])) {
1346 // Don't save replies from blocked profile to local user
1348 $mentioned_user = User::getKV('id', $mentioned->id);
1349 if ($mentioned_user instanceof User && $mentioned_user->hasBlocked($sender)) {
1353 $this->saveReply($mentioned->id);
1354 $replied[$mentioned->id] = 1;
1355 self::blow('reply:stream:%d', $mentioned->id);
1359 $recipientIds = array_keys($replied);
1361 return $recipientIds;
1364 function saveReply($profileId)
1366 $reply = new Reply();
1368 $reply->notice_id = $this->id;
1369 $reply->profile_id = $profileId;
1370 $reply->modified = $this->created;
1377 protected $_replies = -1;
1380 * Pull the complete list of @-reply targets for this notice.
1382 * @return array of integer profile ids
1384 function getReplies()
1386 if ($this->_replies != -1) {
1387 return $this->_replies;
1390 $replyMap = Reply::listGet('notice_id', array($this->id));
1394 foreach ($replyMap[$this->id] as $reply) {
1395 $ids[] = $reply->profile_id;
1398 $this->_replies = $ids;
1403 function _setReplies($replies)
1405 $this->_replies = $replies;
1409 * Pull the complete list of @-reply targets for this notice.
1411 * @return array of Profiles
1413 function getReplyProfiles()
1415 $ids = $this->getReplies();
1417 $profiles = Profile::multiGet('id', $ids);
1419 return $profiles->fetchAll();
1423 * Send e-mail notifications to local @-reply targets.
1425 * Replies must already have been saved; this is expected to be run
1426 * from the distrib queue handler.
1428 function sendReplyNotifications()
1430 // Don't send reply notifications for repeats
1432 if (!empty($this->repeat_of)) {
1436 $recipientIds = $this->getReplies();
1438 foreach ($recipientIds as $recipientId) {
1439 $user = User::getKV('id', $recipientId);
1440 if ($user instanceof User) {
1441 mail_notify_attn($user, $this);
1447 * Pull list of groups this notice needs to be delivered to,
1448 * as previously recorded by saveGroups() or saveKnownGroups().
1450 * @return array of Group objects
1453 protected $_groups = -1;
1455 function getGroups()
1457 // Don't save groups for repeats
1459 if (!empty($this->repeat_of)) {
1463 if ($this->_groups != -1)
1465 return $this->_groups;
1468 $gis = Group_inbox::listGet('notice_id', array($this->id));
1472 foreach ($gis[$this->id] as $gi)
1474 $ids[] = $gi->group_id;
1477 $groups = User_group::multiGet('id', $ids);
1479 $this->_groups = $groups->fetchAll();
1481 return $this->_groups;
1484 function _setGroups($groups)
1486 $this->_groups = $groups;
1490 * Convert a notice into an activity for export.
1492 * @param User $cur Current user
1494 * @return Activity activity object representing this Notice.
1497 function asActivity($cur=null)
1499 $act = self::cacheGet(Cache::codeKey('notice:as-activity:'.$this->id));
1501 if ($act instanceof Activity) {
1504 $act = new Activity();
1506 if (Event::handle('StartNoticeAsActivity', array($this, &$act))) {
1508 $act->id = $this->uri;
1509 $act->time = strtotime($this->created);
1510 $act->link = $this->bestUrl();
1511 $act->content = common_xml_safe_str($this->rendered);
1513 $profile = $this->getProfile();
1515 $act->actor = ActivityObject::fromProfile($profile);
1516 $act->actor->extra[] = $profile->profileInfo($cur);
1518 $act->verb = $this->verb;
1520 if ($this->repeat_of) {
1521 $repeated = Notice::getKV('id', $this->repeat_of);
1522 if ($repeated instanceof Notice) {
1523 $act->objects[] = $repeated->asActivity($cur);
1526 $act->objects[] = ActivityObject::fromNotice($this);
1529 // XXX: should this be handled by default processing for object entry?
1533 $tags = $this->getTags();
1535 foreach ($tags as $tag) {
1536 $cat = new AtomCategory();
1539 $act->categories[] = $cat;
1543 // XXX: use Atom Media and/or File activity objects instead
1545 $attachments = $this->attachments();
1547 foreach ($attachments as $attachment) {
1548 // Save local attachments
1549 if (!empty($attachment->filename)) {
1550 $act->attachments[] = ActivityObject::fromFile($attachment);
1554 $ctx = new ActivityContext();
1557 $reply = $this->getParent();
1558 $ctx->replyToID = $reply->uri;
1559 $ctx->replyToUrl = $reply->bestUrl();
1560 } catch (Exception $e) {
1561 // This is not a reply to something
1564 $ctx->location = $this->getLocation();
1568 if (!empty($this->conversation)) {
1569 $conv = Conversation::getKV('id', $this->conversation);
1570 if ($conv instanceof Conversation) {
1571 $ctx->conversation = $conv->uri;
1575 $reply_ids = $this->getReplies();
1577 foreach ($reply_ids as $id) {
1578 $rprofile = Profile::getKV('id', $id);
1579 if ($rprofile instanceof Profile) {
1580 $ctx->attention[$rprofile->getUri()] = ActivityObject::PERSON;
1584 $groups = $this->getGroups();
1586 foreach ($groups as $group) {
1587 $ctx->attention[$group->getUri()] = ActivityObject::GROUP;
1590 switch ($this->scope) {
1591 case Notice::PUBLIC_SCOPE:
1592 $ctx->attention[ActivityContext::ATTN_PUBLIC] = ActivityObject::COLLECTION;
1594 case Notice::FOLLOWER_SCOPE:
1595 $surl = common_local_url("subscribers", array('nickname' => $profile->nickname));
1596 $ctx->attention[$surl] = ActivityObject::COLLECTION;
1600 $act->context = $ctx;
1602 $source = $this->getSource();
1604 if ($source instanceof Notice_source) {
1605 $act->generator = ActivityObject::fromNoticeSource($source);
1610 $atom_feed = $profile->getAtomFeed();
1612 if (!empty($atom_feed)) {
1614 $act->source = new ActivitySource();
1616 // XXX: we should store the actual feed ID
1618 $act->source->id = $atom_feed;
1620 // XXX: we should store the actual feed title
1622 $act->source->title = $profile->getBestName();
1624 $act->source->links['alternate'] = $profile->profileurl;
1625 $act->source->links['self'] = $atom_feed;
1627 $act->source->icon = $profile->avatarUrl(AVATAR_PROFILE_SIZE);
1629 $notice = $profile->getCurrentNotice();
1631 if ($notice instanceof Notice) {
1632 $act->source->updated = self::utcDate($notice->created);
1635 $user = User::getKV('id', $profile->id);
1637 if ($user instanceof User) {
1638 $act->source->links['license'] = common_config('license', 'url');
1642 if ($this->isLocal()) {
1643 $act->selfLink = common_local_url('ApiStatusesShow', array('id' => $this->id,
1644 'format' => 'atom'));
1645 $act->editLink = $act->selfLink;
1648 Event::handle('EndNoticeAsActivity', array($this, &$act));
1651 self::cacheSet(Cache::codeKey('notice:as-activity:'.$this->id), $act);
1656 // This has gotten way too long. Needs to be sliced up into functional bits
1657 // or ideally exported to a utility class.
1659 function asAtomEntry($namespace=false,
1664 $act = $this->asActivity($cur);
1665 $act->extra[] = $this->noticeInfo($cur);
1666 return $act->asString($namespace, $author, $source);
1670 * Extra notice info for atom entries
1672 * Clients use some extra notice info in the atom stream.
1673 * This gives it to them.
1675 * @param User $cur Current user
1677 * @return array representation of <statusnet:notice_info> element
1680 function noticeInfo($cur)
1682 // local notice ID (useful to clients for ordering)
1684 $noticeInfoAttr = array('local_id' => $this->id);
1688 $ns = $this->getSource();
1690 if ($ns instanceof Notice_source) {
1691 $noticeInfoAttr['source'] = $ns->code;
1692 if (!empty($ns->url)) {
1693 $noticeInfoAttr['source_link'] = $ns->url;
1694 if (!empty($ns->name)) {
1695 $noticeInfoAttr['source'] = '<a href="'
1696 . htmlspecialchars($ns->url)
1697 . '" rel="nofollow">'
1698 . htmlspecialchars($ns->name)
1704 // favorite and repeated
1707 $cp = $cur->getProfile();
1708 $noticeInfoAttr['favorite'] = ($cp->hasFave($this)) ? "true" : "false";
1709 $noticeInfoAttr['repeated'] = ($cp->hasRepeated($this)) ? "true" : "false";
1712 if (!empty($this->repeat_of)) {
1713 $noticeInfoAttr['repeat_of'] = $this->repeat_of;
1716 return array('statusnet:notice_info', $noticeInfoAttr, null);
1720 * Returns an XML string fragment with a reference to a notice as an
1721 * Activity Streams noun object with the given element type.
1723 * Assumes that 'activity' namespace has been previously defined.
1725 * @param string $element one of 'subject', 'object', 'target'
1729 function asActivityNoun($element)
1731 $noun = ActivityObject::fromNotice($this);
1732 return $noun->asString('activity:' . $element);
1737 if (!empty($this->url)) {
1739 } else if (!empty($this->uri) && preg_match('/^https?:/', $this->uri)) {
1742 return common_local_url('shownotice',
1743 array('notice' => $this->id));
1749 * Determine which notice, if any, a new notice is in reply to.
1751 * For conversation tracking, we try to see where this notice fits
1752 * in the tree. Rough algorithm is:
1754 * if (reply_to is set and valid) {
1756 * } else if ((source not API or Web) and (content starts with "T NAME" or "@name ")) {
1757 * return ID of last notice by initial @name in content;
1760 * Note that all @nickname instances will still be used to save "reply" records,
1761 * so the notice shows up in the mentioned users' "replies" tab.
1763 * @param integer $reply_to ID passed in by Web or API
1764 * @param integer $profile_id ID of author
1765 * @param string $source Source tag, like 'web' or 'gwibber'
1766 * @param string $content Final notice content
1768 * @return integer ID of replied-to notice, or null for not a reply.
1771 static function getReplyTo($reply_to, $profile_id, $source, $content)
1773 static $lb = array('xmpp', 'mail', 'sms', 'omb');
1775 // If $reply_to is specified, we check that it exists, and then
1776 // return it if it does
1778 if (!empty($reply_to)) {
1779 $reply_notice = Notice::getKV('id', $reply_to);
1780 if ($reply_notice instanceof Notice) {
1781 return $reply_notice;
1785 // If it's not a "low bandwidth" source (one where you can't set
1786 // a reply_to argument), we return. This is mostly web and API
1789 if (!in_array($source, $lb)) {
1793 // Is there an initial @ or T?
1795 if (preg_match('/^T ([A-Z0-9]{1,64}) /', $content, $match) ||
1796 preg_match('/^@([a-z0-9]{1,64})\s+/', $content, $match)) {
1797 $nickname = common_canonical_nickname($match[1]);
1802 // Figure out who that is.
1804 $sender = Profile::getKV('id', $profile_id);
1805 if (!$sender instanceof Profile) {
1809 $recipient = common_relative_profile($sender, $nickname, common_sql_now());
1811 if (!$recipient instanceof Profile) {
1815 // Get their last notice
1817 $last = $recipient->getCurrentNotice();
1819 if ($last instanceof Notice) {
1826 static function maxContent()
1828 $contentlimit = common_config('notice', 'contentlimit');
1829 // null => use global limit (distinct from 0!)
1830 if (is_null($contentlimit)) {
1831 $contentlimit = common_config('site', 'textlimit');
1833 return $contentlimit;
1836 static function contentTooLong($content)
1838 $contentlimit = self::maxContent();
1839 return ($contentlimit > 0 && !empty($content) && (mb_strlen($content) > $contentlimit));
1842 function getLocation()
1846 if (!empty($this->location_id) && !empty($this->location_ns)) {
1847 $location = Location::fromId($this->location_id, $this->location_ns);
1850 if (is_null($location)) { // no ID, or Location::fromId() failed
1851 if (!empty($this->lat) && !empty($this->lon)) {
1852 $location = Location::fromLatLon($this->lat, $this->lon);
1860 * Convenience function for posting a repeat of an existing message.
1862 * @param int $repeater_id: profile ID of user doing the repeat
1863 * @param string $source: posting source key, eg 'web', 'api', etc
1866 * @throws Exception on failure or permission problems
1868 function repeat($repeater_id, $source)
1870 $author = Profile::getKV('id', $this->profile_id);
1872 // TRANS: Message used to repeat a notice. RT is the abbreviation of 'retweet'.
1873 // TRANS: %1$s is the repeated user's name, %2$s is the repeated notice.
1874 $content = sprintf(_('RT @%1$s %2$s'),
1878 $maxlen = common_config('site', 'textlimit');
1879 if ($maxlen > 0 && mb_strlen($content) > $maxlen) {
1880 // Web interface and current Twitter API clients will
1881 // pull the original notice's text, but some older
1882 // clients and RSS/Atom feeds will see this trimmed text.
1884 // Unfortunately this is likely to lose tags or URLs
1885 // at the end of long notices.
1886 $content = mb_substr($content, 0, $maxlen - 4) . ' ...';
1889 // Scope is same as this one's
1891 return self::saveNew($repeater_id,
1894 array('repeat_of' => $this->id,
1895 'scope' => $this->scope));
1898 // These are supposed to be in chron order!
1900 function repeatStream($limit=100)
1902 $cache = Cache::instance();
1904 if (empty($cache)) {
1905 $ids = $this->_repeatStreamDirect($limit);
1907 $idstr = $cache->get(Cache::key('notice:repeats:'.$this->id));
1908 if ($idstr !== false) {
1909 if (empty($idstr)) {
1912 $ids = explode(',', $idstr);
1915 $ids = $this->_repeatStreamDirect(100);
1916 $cache->set(Cache::key('notice:repeats:'.$this->id), implode(',', $ids));
1919 // We do a max of 100, so slice down to limit
1920 $ids = array_slice($ids, 0, $limit);
1924 return NoticeStream::getStreamByIds($ids);
1927 function _repeatStreamDirect($limit)
1929 $notice = new Notice();
1931 $notice->selectAdd(); // clears it
1932 $notice->selectAdd('id');
1934 $notice->repeat_of = $this->id;
1936 $notice->orderBy('created, id'); // NB: asc!
1938 if (!is_null($limit)) {
1939 $notice->limit(0, $limit);
1942 return $notice->fetchAll('id');
1945 function locationOptions($lat, $lon, $location_id, $location_ns, $profile = null)
1949 if (!empty($location_id) && !empty($location_ns)) {
1950 $options['location_id'] = $location_id;
1951 $options['location_ns'] = $location_ns;
1953 $location = Location::fromId($location_id, $location_ns);
1955 if ($location instanceof Location) {
1956 $options['lat'] = $location->lat;
1957 $options['lon'] = $location->lon;
1960 } else if (!empty($lat) && !empty($lon)) {
1961 $options['lat'] = $lat;
1962 $options['lon'] = $lon;
1964 $location = Location::fromLatLon($lat, $lon);
1966 if ($location instanceof Location) {
1967 $options['location_id'] = $location->location_id;
1968 $options['location_ns'] = $location->location_ns;
1970 } else if (!empty($profile)) {
1971 if (isset($profile->lat) && isset($profile->lon)) {
1972 $options['lat'] = $profile->lat;
1973 $options['lon'] = $profile->lon;
1976 if (isset($profile->location_id) && isset($profile->location_ns)) {
1977 $options['location_id'] = $profile->location_id;
1978 $options['location_ns'] = $profile->location_ns;
1985 function clearReplies()
1987 $replyNotice = new Notice();
1988 $replyNotice->reply_to = $this->id;
1990 //Null any notices that are replies to this notice
1992 if ($replyNotice->find()) {
1993 while ($replyNotice->fetch()) {
1994 $orig = clone($replyNotice);
1995 $replyNotice->reply_to = null;
1996 $replyNotice->update($orig);
2002 $reply = new Reply();
2003 $reply->notice_id = $this->id;
2005 if ($reply->find()) {
2006 while($reply->fetch()) {
2007 self::blow('reply:stream:%d', $reply->profile_id);
2015 function clearFiles()
2017 $f2p = new File_to_post();
2019 $f2p->post_id = $this->id;
2022 while ($f2p->fetch()) {
2026 // FIXME: decide whether to delete File objects
2027 // ...and related (actual) files
2030 function clearRepeats()
2032 $repeatNotice = new Notice();
2033 $repeatNotice->repeat_of = $this->id;
2035 //Null any notices that are repeats of this notice
2037 if ($repeatNotice->find()) {
2038 while ($repeatNotice->fetch()) {
2039 $orig = clone($repeatNotice);
2040 $repeatNotice->repeat_of = null;
2041 $repeatNotice->update($orig);
2046 function clearFaves()
2049 $fave->notice_id = $this->id;
2051 if ($fave->find()) {
2052 while ($fave->fetch()) {
2053 self::blow('fave:ids_by_user_own:%d', $fave->user_id);
2054 self::blow('fave:ids_by_user_own:%d;last', $fave->user_id);
2055 self::blow('fave:ids_by_user:%d', $fave->user_id);
2056 self::blow('fave:ids_by_user:%d;last', $fave->user_id);
2064 function clearTags()
2066 $tag = new Notice_tag();
2067 $tag->notice_id = $this->id;
2070 while ($tag->fetch()) {
2071 self::blow('profile:notice_ids_tagged:%d:%s', $this->profile_id, Cache::keyize($tag->tag));
2072 self::blow('profile:notice_ids_tagged:%d:%s;last', $this->profile_id, Cache::keyize($tag->tag));
2073 self::blow('notice_tag:notice_ids:%s', Cache::keyize($tag->tag));
2074 self::blow('notice_tag:notice_ids:%s;last', Cache::keyize($tag->tag));
2082 function clearGroupInboxes()
2084 $gi = new Group_inbox();
2086 $gi->notice_id = $this->id;
2089 while ($gi->fetch()) {
2090 self::blow('user_group:notice_ids:%d', $gi->group_id);
2098 function distribute()
2100 // We always insert for the author so they don't
2102 Event::handle('StartNoticeDistribute', array($this));
2104 $user = User::getKV('id', $this->profile_id);
2105 if ($user instanceof User) {
2106 Inbox::insertNotice($user->id, $this->id);
2109 if (common_config('queue', 'inboxes')) {
2110 // If there's a failure, we want to _force_
2111 // distribution at this point.
2113 $qm = QueueManager::get();
2114 $qm->enqueue($this, 'distrib');
2115 } catch (Exception $e) {
2116 // If the exception isn't transient, this
2117 // may throw more exceptions as DQH does
2118 // its own enqueueing. So, we ignore them!
2120 $handler = new DistribQueueHandler();
2121 $handler->handle($this);
2122 } catch (Exception $e) {
2123 common_log(LOG_ERR, "emergency redistribution resulted in " . $e->getMessage());
2125 // Re-throw so somebody smarter can handle it.
2129 $handler = new DistribQueueHandler();
2130 $handler->handle($this);
2136 $result = parent::insert();
2138 if ($result !== false) {
2139 // Profile::hasRepeated() abuses pkeyGet(), so we
2140 // have to clear manually
2141 if (!empty($this->repeat_of)) {
2142 $c = self::memcache();
2144 $ck = self::multicacheKey('Notice',
2145 array('profile_id' => $this->profile_id,
2146 'repeat_of' => $this->repeat_of));
2156 * Get the source of the notice
2158 * @return Notice_source $ns A notice source object. 'code' is the only attribute
2159 * guaranteed to be populated.
2161 function getSource()
2163 $ns = new Notice_source();
2164 if (!empty($this->source)) {
2165 switch ($this->source) {
2172 $ns->code = $this->source;
2175 $ns = Notice_source::getKV($this->source);
2177 $ns = new Notice_source();
2178 $ns->code = $this->source;
2179 $app = Oauth_application::getKV('name', $this->source);
2181 $ns->name = $app->name;
2182 $ns->url = $app->source_url;
2192 * Determine whether the notice was locally created
2194 * @return boolean locality
2197 public function isLocal()
2199 return ($this->is_local == Notice::LOCAL_PUBLIC ||
2200 $this->is_local == Notice::LOCAL_NONPUBLIC);
2204 * Get the list of hash tags saved with this notice.
2206 * @return array of strings
2208 public function getTags()
2212 $keypart = sprintf('notice:tags:%d', $this->id);
2214 $tagstr = self::cacheGet($keypart);
2216 if ($tagstr !== false) {
2217 $tags = explode(',', $tagstr);
2219 $tag = new Notice_tag();
2220 $tag->notice_id = $this->id;
2222 while ($tag->fetch()) {
2223 $tags[] = $tag->tag;
2226 self::cacheSet($keypart, implode(',', $tags));
2232 static private function utcDate($dt)
2234 $dateStr = date('d F Y H:i:s', strtotime($dt));
2235 $d = new DateTime($dateStr, new DateTimeZone('UTC'));
2236 return $d->format(DATE_W3C);
2240 * Look up the creation timestamp for a given notice ID, even
2241 * if it's been deleted.
2244 * @return mixed string recorded creation timestamp, or false if can't be found
2246 public static function getAsTimestamp($id)
2252 $notice = Notice::getKV('id', $id);
2254 return $notice->created;
2257 $deleted = Deleted_notice::getKV('id', $id);
2259 return $deleted->created;
2266 * Build an SQL 'where' fragment for timestamp-based sorting from a since_id
2267 * parameter, matching notices posted after the given one (exclusive).
2269 * If the referenced notice can't be found, will return false.
2272 * @param string $idField
2273 * @param string $createdField
2274 * @return mixed string or false if no match
2276 public static function whereSinceId($id, $idField='id', $createdField='created')
2278 $since = Notice::getAsTimestamp($id);
2280 return sprintf("($createdField = '%s' and $idField > %d) or ($createdField > '%s')", $since, $id, $since);
2286 * Build an SQL 'where' fragment for timestamp-based sorting from a since_id
2287 * parameter, matching notices posted after the given one (exclusive), and
2288 * if necessary add it to the data object's query.
2290 * @param DB_DataObject $obj
2292 * @param string $idField
2293 * @param string $createdField
2294 * @return mixed string or false if no match
2296 public static function addWhereSinceId(DB_DataObject $obj, $id, $idField='id', $createdField='created')
2298 $since = self::whereSinceId($id, $idField, $createdField);
2300 $obj->whereAdd($since);
2305 * Build an SQL 'where' fragment for timestamp-based sorting from a max_id
2306 * parameter, matching notices posted before the given one (inclusive).
2308 * If the referenced notice can't be found, will return false.
2311 * @param string $idField
2312 * @param string $createdField
2313 * @return mixed string or false if no match
2315 public static function whereMaxId($id, $idField='id', $createdField='created')
2317 $max = Notice::getAsTimestamp($id);
2319 return sprintf("($createdField < '%s') or ($createdField = '%s' and $idField <= %d)", $max, $max, $id);
2325 * Build an SQL 'where' fragment for timestamp-based sorting from a max_id
2326 * parameter, matching notices posted before the given one (inclusive), and
2327 * if necessary add it to the data object's query.
2329 * @param DB_DataObject $obj
2331 * @param string $idField
2332 * @param string $createdField
2333 * @return mixed string or false if no match
2335 public static function addWhereMaxId(DB_DataObject $obj, $id, $idField='id', $createdField='created')
2337 $max = self::whereMaxId($id, $idField, $createdField);
2339 $obj->whereAdd($max);
2345 if (common_config('public', 'localonly')) {
2346 return ($this->is_local == Notice::LOCAL_PUBLIC);
2348 return (($this->is_local != Notice::LOCAL_NONPUBLIC) &&
2349 ($this->is_local != Notice::GATEWAY));
2354 * Check that the given profile is allowed to read, respond to, or otherwise
2355 * act on this notice.
2357 * The $scope member is a bitmask of scopes, representing a logical AND of the
2358 * scope requirement. So, 0x03 (Notice::ADDRESSEE_SCOPE | Notice::SITE_SCOPE) means
2359 * "only visible to people who are mentioned in the notice AND are users on this site."
2360 * Users on the site who are not mentioned in the notice will not be able to see the
2363 * @param Profile $profile The profile to check; pass null to check for public/unauthenticated users.
2365 * @return boolean whether the profile is in the notice's scope
2367 function inScope($profile)
2369 if (is_null($profile)) {
2370 $keypart = sprintf('notice:in-scope-for:%d:null', $this->id);
2372 $keypart = sprintf('notice:in-scope-for:%d:%d', $this->id, $profile->id);
2375 $result = self::cacheGet($keypart);
2377 if ($result === false) {
2379 if (Event::handle('StartNoticeInScope', array($this, $profile, &$bResult))) {
2380 $bResult = $this->_inScope($profile);
2381 Event::handle('EndNoticeInScope', array($this, $profile, &$bResult));
2383 $result = ($bResult) ? 1 : 0;
2384 self::cacheSet($keypart, $result, 0, 300);
2387 return ($result == 1) ? true : false;
2390 protected function _inScope($profile)
2392 if (!is_null($this->scope)) {
2393 $scope = $this->scope;
2395 $scope = self::defaultScope();
2398 // If there's no scope, anyone (even anon) is in scope.
2400 if ($scope == 0) { // Not private
2402 return !$this->isHiddenSpam($profile);
2404 } else { // Private, somehow
2406 // If there's scope, anon cannot be in scope
2408 if (empty($profile)) {
2412 // Author is always in scope
2414 if ($this->profile_id == $profile->id) {
2418 // Only for users on this site
2420 if (($scope & Notice::SITE_SCOPE) && !$profile->isLocal()) {
2424 // Only for users mentioned in the notice
2426 if ($scope & Notice::ADDRESSEE_SCOPE) {
2428 $reply = Reply::pkeyGet(array('notice_id' => $this->id,
2429 'profile_id' => $profile->id));
2431 if (!$reply instanceof Reply) {
2436 // Only for members of the given group
2438 if ($scope & Notice::GROUP_SCOPE) {
2440 // XXX: just query for the single membership
2442 $groups = $this->getGroups();
2446 foreach ($groups as $group) {
2447 if ($profile->isMember($group)) {
2458 // Only for followers of the author
2462 if ($scope & Notice::FOLLOWER_SCOPE) {
2465 $author = $this->getProfile();
2466 } catch (Exception $e) {
2470 if (!Subscription::exists($profile, $author)) {
2475 return !$this->isHiddenSpam($profile);
2479 function isHiddenSpam($profile) {
2481 // Hide posts by silenced users from everyone but moderators.
2483 if (common_config('notice', 'hidespam')) {
2486 $author = $this->getProfile();
2487 } catch(Exception $e) {
2488 // If we can't get an author, keep it hidden.
2489 // XXX: technically not spam, but, whatever.
2493 if ($author->hasRole(Profile_role::SILENCED)) {
2494 if (!$profile instanceof Profile || (($profile->id !== $author->id) && (!$profile->hasRight(Right::REVIEWSPAM)))) {
2503 static function groupsFromText($text, $profile)
2507 /* extract all !group */
2508 $count = preg_match_all('/(?:^|\s)!(' . Nickname::DISPLAY_FMT . ')/',
2516 foreach (array_unique($match[1]) as $nickname) {
2517 $group = User_group::getForNickname($nickname, $profile);
2518 if ($group instanceof User_group && $profile->isMember($group)) {
2519 $groups[] = $group->id;
2526 public function getParent()
2528 $parent = Notice::getKV('id', $this->reply_to);
2530 if (!$parent instanceof Notice) {
2531 throw new ServerException('Notice has no parent');
2538 * Magic function called at serialize() time.
2540 * We use this to drop a couple process-specific references
2541 * from DB_DataObject which can cause trouble in future
2544 * @return array of variable names to include in serialization.
2549 $vars = parent::__sleep();
2550 $skip = array('_profile', '_groups', '_attachments', '_faves', '_replies', '_repeats');
2551 return array_diff($vars, $skip);
2554 static function defaultScope()
2556 $scope = common_config('notice', 'defaultscope');
2557 if (is_null($scope)) {
2558 if (common_config('site', 'private')) {
2567 static function fillProfiles($notices)
2569 $map = self::getProfiles($notices);
2571 foreach ($notices as $notice) {
2572 if (array_key_exists($notice->profile_id, $map)) {
2573 $notice->_setProfile($map[$notice->profile_id]);
2577 return array_values($map);
2580 static function getProfiles(&$notices)
2583 foreach ($notices as $notice) {
2584 $ids[] = $notice->profile_id;
2587 $ids = array_unique($ids);
2589 return Profile::pivotGet('id', $ids);
2592 static function fillGroups(&$notices)
2594 $ids = self::_idsOf($notices);
2596 $gis = Group_inbox::listGet('notice_id', $ids);
2600 foreach ($gis as $id => $gi)
2604 $gids[] = $g->group_id;
2608 $gids = array_unique($gids);
2610 $group = User_group::pivotGet('id', $gids);
2612 foreach ($notices as $notice)
2615 $gi = $gis[$notice->id];
2616 foreach ($gi as $g) {
2617 $grps[] = $group[$g->group_id];
2619 $notice->_setGroups($grps);
2623 static function _idsOf(&$notices)
2626 foreach ($notices as $notice) {
2627 $ids[] = $notice->id;
2629 $ids = array_unique($ids);
2633 static function fillAttachments(&$notices)
2635 $ids = self::_idsOf($notices);
2637 $f2pMap = File_to_post::listGet('post_id', $ids);
2641 foreach ($f2pMap as $noticeId => $f2ps) {
2642 foreach ($f2ps as $f2p) {
2643 $fileIds[] = $f2p->file_id;
2647 $fileIds = array_unique($fileIds);
2649 $fileMap = File::pivotGet('id', $fileIds);
2651 foreach ($notices as $notice)
2654 $f2ps = $f2pMap[$notice->id];
2655 foreach ($f2ps as $f2p) {
2656 $files[] = $fileMap[$f2p->file_id];
2658 $notice->_setAttachments($files);
2665 * All faves of this notice
2667 * @return array Array of Fave objects
2672 if (isset($this->_faves) && is_array($this->_faves)) {
2673 return $this->_faves;
2675 $faveMap = Fave::listGet('notice_id', array($this->id));
2676 $this->_faves = $faveMap[$this->id];
2677 return $this->_faves;
2680 function _setFaves($faves)
2682 $this->_faves = $faves;
2685 static function fillFaves(&$notices)
2687 $ids = self::_idsOf($notices);
2688 $faveMap = Fave::listGet('notice_id', $ids);
2691 foreach ($faveMap as $id => $faves) {
2692 $cnt += count($faves);
2693 if (count($faves) > 0) {
2697 foreach ($notices as $notice) {
2698 $faves = $faveMap[$notice->id];
2699 $notice->_setFaves($faves);
2703 static function fillReplies(&$notices)
2705 $ids = self::_idsOf($notices);
2706 $replyMap = Reply::listGet('notice_id', $ids);
2707 foreach ($notices as $notice) {
2708 $replies = $replyMap[$notice->id];
2710 foreach ($replies as $reply) {
2711 $ids[] = $reply->profile_id;
2713 $notice->_setReplies($ids);
2717 protected $_repeats;
2719 function getRepeats()
2721 if (isset($this->_repeats) && is_array($this->_repeats)) {
2722 return $this->_repeats;
2724 $repeatMap = Notice::listGet('repeat_of', array($this->id));
2725 $this->_repeats = $repeatMap[$this->id];
2726 return $this->_repeats;
2729 function _setRepeats($repeats)
2731 $this->_repeats = $repeats;
2734 static function fillRepeats(&$notices)
2736 $ids = self::_idsOf($notices);
2737 $repeatMap = Notice::listGet('repeat_of', $ids);
2738 foreach ($notices as $notice) {
2739 $repeats = $repeatMap[$notice->id];
2740 $notice->_setRepeats($repeats);