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();
1581 $ctx->attentionType[$rprofile->getUri()] = ActivityObject::PERSON;
1585 $groups = $this->getGroups();
1587 foreach ($groups as $group) {
1588 $ctx->attention[] = $group->getUri();
1589 $ctx->attentionType[$group->getUri()] = ActivityObject::GROUP;
1592 switch ($this->scope) {
1593 case Notice::PUBLIC_SCOPE:
1594 $ctx->attention[] = "http://activityschema.org/collection/public";
1595 $ctx->attentionType["http://activityschema.org/collection/public"] = ActivityObject::COLLECTION;
1597 case Notice::FOLLOWER_SCOPE:
1598 $surl = common_local_url("subscribers", array('nickname' => $profile->nickname));
1599 $ctx->attention[] = $surl;
1600 $ctx->attentionType[$surl] = ActivityObject::COLLECTION;
1604 $act->context = $ctx;
1606 $source = $this->getSource();
1608 if ($source instanceof Notice_source) {
1609 $act->generator = ActivityObject::fromNoticeSource($source);
1614 $atom_feed = $profile->getAtomFeed();
1616 if (!empty($atom_feed)) {
1618 $act->source = new ActivitySource();
1620 // XXX: we should store the actual feed ID
1622 $act->source->id = $atom_feed;
1624 // XXX: we should store the actual feed title
1626 $act->source->title = $profile->getBestName();
1628 $act->source->links['alternate'] = $profile->profileurl;
1629 $act->source->links['self'] = $atom_feed;
1631 $act->source->icon = $profile->avatarUrl(AVATAR_PROFILE_SIZE);
1633 $notice = $profile->getCurrentNotice();
1635 if ($notice instanceof Notice) {
1636 $act->source->updated = self::utcDate($notice->created);
1639 $user = User::getKV('id', $profile->id);
1641 if ($user instanceof User) {
1642 $act->source->links['license'] = common_config('license', 'url');
1646 if ($this->isLocal()) {
1647 $act->selfLink = common_local_url('ApiStatusesShow', array('id' => $this->id,
1648 'format' => 'atom'));
1649 $act->editLink = $act->selfLink;
1652 Event::handle('EndNoticeAsActivity', array($this, &$act));
1655 self::cacheSet(Cache::codeKey('notice:as-activity:'.$this->id), $act);
1660 // This has gotten way too long. Needs to be sliced up into functional bits
1661 // or ideally exported to a utility class.
1663 function asAtomEntry($namespace=false,
1668 $act = $this->asActivity($cur);
1669 $act->extra[] = $this->noticeInfo($cur);
1670 return $act->asString($namespace, $author, $source);
1674 * Extra notice info for atom entries
1676 * Clients use some extra notice info in the atom stream.
1677 * This gives it to them.
1679 * @param User $cur Current user
1681 * @return array representation of <statusnet:notice_info> element
1684 function noticeInfo($cur)
1686 // local notice ID (useful to clients for ordering)
1688 $noticeInfoAttr = array('local_id' => $this->id);
1692 $ns = $this->getSource();
1694 if ($ns instanceof Notice_source) {
1695 $noticeInfoAttr['source'] = $ns->code;
1696 if (!empty($ns->url)) {
1697 $noticeInfoAttr['source_link'] = $ns->url;
1698 if (!empty($ns->name)) {
1699 $noticeInfoAttr['source'] = '<a href="'
1700 . htmlspecialchars($ns->url)
1701 . '" rel="nofollow">'
1702 . htmlspecialchars($ns->name)
1708 // favorite and repeated
1711 $cp = $cur->getProfile();
1712 $noticeInfoAttr['favorite'] = ($cp->hasFave($this)) ? "true" : "false";
1713 $noticeInfoAttr['repeated'] = ($cp->hasRepeated($this)) ? "true" : "false";
1716 if (!empty($this->repeat_of)) {
1717 $noticeInfoAttr['repeat_of'] = $this->repeat_of;
1720 return array('statusnet:notice_info', $noticeInfoAttr, null);
1724 * Returns an XML string fragment with a reference to a notice as an
1725 * Activity Streams noun object with the given element type.
1727 * Assumes that 'activity' namespace has been previously defined.
1729 * @param string $element one of 'subject', 'object', 'target'
1733 function asActivityNoun($element)
1735 $noun = ActivityObject::fromNotice($this);
1736 return $noun->asString('activity:' . $element);
1741 if (!empty($this->url)) {
1743 } else if (!empty($this->uri) && preg_match('/^https?:/', $this->uri)) {
1746 return common_local_url('shownotice',
1747 array('notice' => $this->id));
1753 * Determine which notice, if any, a new notice is in reply to.
1755 * For conversation tracking, we try to see where this notice fits
1756 * in the tree. Rough algorithm is:
1758 * if (reply_to is set and valid) {
1760 * } else if ((source not API or Web) and (content starts with "T NAME" or "@name ")) {
1761 * return ID of last notice by initial @name in content;
1764 * Note that all @nickname instances will still be used to save "reply" records,
1765 * so the notice shows up in the mentioned users' "replies" tab.
1767 * @param integer $reply_to ID passed in by Web or API
1768 * @param integer $profile_id ID of author
1769 * @param string $source Source tag, like 'web' or 'gwibber'
1770 * @param string $content Final notice content
1772 * @return integer ID of replied-to notice, or null for not a reply.
1775 static function getReplyTo($reply_to, $profile_id, $source, $content)
1777 static $lb = array('xmpp', 'mail', 'sms', 'omb');
1779 // If $reply_to is specified, we check that it exists, and then
1780 // return it if it does
1782 if (!empty($reply_to)) {
1783 $reply_notice = Notice::getKV('id', $reply_to);
1784 if ($reply_notice instanceof Notice) {
1785 return $reply_notice;
1789 // If it's not a "low bandwidth" source (one where you can't set
1790 // a reply_to argument), we return. This is mostly web and API
1793 if (!in_array($source, $lb)) {
1797 // Is there an initial @ or T?
1799 if (preg_match('/^T ([A-Z0-9]{1,64}) /', $content, $match) ||
1800 preg_match('/^@([a-z0-9]{1,64})\s+/', $content, $match)) {
1801 $nickname = common_canonical_nickname($match[1]);
1806 // Figure out who that is.
1808 $sender = Profile::getKV('id', $profile_id);
1809 if (!$sender instanceof Profile) {
1813 $recipient = common_relative_profile($sender, $nickname, common_sql_now());
1815 if (!$recipient instanceof Profile) {
1819 // Get their last notice
1821 $last = $recipient->getCurrentNotice();
1823 if ($last instanceof Notice) {
1830 static function maxContent()
1832 $contentlimit = common_config('notice', 'contentlimit');
1833 // null => use global limit (distinct from 0!)
1834 if (is_null($contentlimit)) {
1835 $contentlimit = common_config('site', 'textlimit');
1837 return $contentlimit;
1840 static function contentTooLong($content)
1842 $contentlimit = self::maxContent();
1843 return ($contentlimit > 0 && !empty($content) && (mb_strlen($content) > $contentlimit));
1846 function getLocation()
1850 if (!empty($this->location_id) && !empty($this->location_ns)) {
1851 $location = Location::fromId($this->location_id, $this->location_ns);
1854 if (is_null($location)) { // no ID, or Location::fromId() failed
1855 if (!empty($this->lat) && !empty($this->lon)) {
1856 $location = Location::fromLatLon($this->lat, $this->lon);
1864 * Convenience function for posting a repeat of an existing message.
1866 * @param int $repeater_id: profile ID of user doing the repeat
1867 * @param string $source: posting source key, eg 'web', 'api', etc
1870 * @throws Exception on failure or permission problems
1872 function repeat($repeater_id, $source)
1874 $author = Profile::getKV('id', $this->profile_id);
1876 // TRANS: Message used to repeat a notice. RT is the abbreviation of 'retweet'.
1877 // TRANS: %1$s is the repeated user's name, %2$s is the repeated notice.
1878 $content = sprintf(_('RT @%1$s %2$s'),
1882 $maxlen = common_config('site', 'textlimit');
1883 if ($maxlen > 0 && mb_strlen($content) > $maxlen) {
1884 // Web interface and current Twitter API clients will
1885 // pull the original notice's text, but some older
1886 // clients and RSS/Atom feeds will see this trimmed text.
1888 // Unfortunately this is likely to lose tags or URLs
1889 // at the end of long notices.
1890 $content = mb_substr($content, 0, $maxlen - 4) . ' ...';
1893 // Scope is same as this one's
1895 return self::saveNew($repeater_id,
1898 array('repeat_of' => $this->id,
1899 'scope' => $this->scope));
1902 // These are supposed to be in chron order!
1904 function repeatStream($limit=100)
1906 $cache = Cache::instance();
1908 if (empty($cache)) {
1909 $ids = $this->_repeatStreamDirect($limit);
1911 $idstr = $cache->get(Cache::key('notice:repeats:'.$this->id));
1912 if ($idstr !== false) {
1913 if (empty($idstr)) {
1916 $ids = explode(',', $idstr);
1919 $ids = $this->_repeatStreamDirect(100);
1920 $cache->set(Cache::key('notice:repeats:'.$this->id), implode(',', $ids));
1923 // We do a max of 100, so slice down to limit
1924 $ids = array_slice($ids, 0, $limit);
1928 return NoticeStream::getStreamByIds($ids);
1931 function _repeatStreamDirect($limit)
1933 $notice = new Notice();
1935 $notice->selectAdd(); // clears it
1936 $notice->selectAdd('id');
1938 $notice->repeat_of = $this->id;
1940 $notice->orderBy('created, id'); // NB: asc!
1942 if (!is_null($limit)) {
1943 $notice->limit(0, $limit);
1946 return $notice->fetchAll('id');
1949 function locationOptions($lat, $lon, $location_id, $location_ns, $profile = null)
1953 if (!empty($location_id) && !empty($location_ns)) {
1954 $options['location_id'] = $location_id;
1955 $options['location_ns'] = $location_ns;
1957 $location = Location::fromId($location_id, $location_ns);
1959 if ($location instanceof Location) {
1960 $options['lat'] = $location->lat;
1961 $options['lon'] = $location->lon;
1964 } else if (!empty($lat) && !empty($lon)) {
1965 $options['lat'] = $lat;
1966 $options['lon'] = $lon;
1968 $location = Location::fromLatLon($lat, $lon);
1970 if ($location instanceof Location) {
1971 $options['location_id'] = $location->location_id;
1972 $options['location_ns'] = $location->location_ns;
1974 } else if (!empty($profile)) {
1975 if (isset($profile->lat) && isset($profile->lon)) {
1976 $options['lat'] = $profile->lat;
1977 $options['lon'] = $profile->lon;
1980 if (isset($profile->location_id) && isset($profile->location_ns)) {
1981 $options['location_id'] = $profile->location_id;
1982 $options['location_ns'] = $profile->location_ns;
1989 function clearReplies()
1991 $replyNotice = new Notice();
1992 $replyNotice->reply_to = $this->id;
1994 //Null any notices that are replies to this notice
1996 if ($replyNotice->find()) {
1997 while ($replyNotice->fetch()) {
1998 $orig = clone($replyNotice);
1999 $replyNotice->reply_to = null;
2000 $replyNotice->update($orig);
2006 $reply = new Reply();
2007 $reply->notice_id = $this->id;
2009 if ($reply->find()) {
2010 while($reply->fetch()) {
2011 self::blow('reply:stream:%d', $reply->profile_id);
2019 function clearFiles()
2021 $f2p = new File_to_post();
2023 $f2p->post_id = $this->id;
2026 while ($f2p->fetch()) {
2030 // FIXME: decide whether to delete File objects
2031 // ...and related (actual) files
2034 function clearRepeats()
2036 $repeatNotice = new Notice();
2037 $repeatNotice->repeat_of = $this->id;
2039 //Null any notices that are repeats of this notice
2041 if ($repeatNotice->find()) {
2042 while ($repeatNotice->fetch()) {
2043 $orig = clone($repeatNotice);
2044 $repeatNotice->repeat_of = null;
2045 $repeatNotice->update($orig);
2050 function clearFaves()
2053 $fave->notice_id = $this->id;
2055 if ($fave->find()) {
2056 while ($fave->fetch()) {
2057 self::blow('fave:ids_by_user_own:%d', $fave->user_id);
2058 self::blow('fave:ids_by_user_own:%d;last', $fave->user_id);
2059 self::blow('fave:ids_by_user:%d', $fave->user_id);
2060 self::blow('fave:ids_by_user:%d;last', $fave->user_id);
2068 function clearTags()
2070 $tag = new Notice_tag();
2071 $tag->notice_id = $this->id;
2074 while ($tag->fetch()) {
2075 self::blow('profile:notice_ids_tagged:%d:%s', $this->profile_id, Cache::keyize($tag->tag));
2076 self::blow('profile:notice_ids_tagged:%d:%s;last', $this->profile_id, Cache::keyize($tag->tag));
2077 self::blow('notice_tag:notice_ids:%s', Cache::keyize($tag->tag));
2078 self::blow('notice_tag:notice_ids:%s;last', Cache::keyize($tag->tag));
2086 function clearGroupInboxes()
2088 $gi = new Group_inbox();
2090 $gi->notice_id = $this->id;
2093 while ($gi->fetch()) {
2094 self::blow('user_group:notice_ids:%d', $gi->group_id);
2102 function distribute()
2104 // We always insert for the author so they don't
2106 Event::handle('StartNoticeDistribute', array($this));
2108 $user = User::getKV('id', $this->profile_id);
2109 if ($user instanceof User) {
2110 Inbox::insertNotice($user->id, $this->id);
2113 if (common_config('queue', 'inboxes')) {
2114 // If there's a failure, we want to _force_
2115 // distribution at this point.
2117 $qm = QueueManager::get();
2118 $qm->enqueue($this, 'distrib');
2119 } catch (Exception $e) {
2120 // If the exception isn't transient, this
2121 // may throw more exceptions as DQH does
2122 // its own enqueueing. So, we ignore them!
2124 $handler = new DistribQueueHandler();
2125 $handler->handle($this);
2126 } catch (Exception $e) {
2127 common_log(LOG_ERR, "emergency redistribution resulted in " . $e->getMessage());
2129 // Re-throw so somebody smarter can handle it.
2133 $handler = new DistribQueueHandler();
2134 $handler->handle($this);
2140 $result = parent::insert();
2142 if ($result !== false) {
2143 // Profile::hasRepeated() abuses pkeyGet(), so we
2144 // have to clear manually
2145 if (!empty($this->repeat_of)) {
2146 $c = self::memcache();
2148 $ck = self::multicacheKey('Notice',
2149 array('profile_id' => $this->profile_id,
2150 'repeat_of' => $this->repeat_of));
2160 * Get the source of the notice
2162 * @return Notice_source $ns A notice source object. 'code' is the only attribute
2163 * guaranteed to be populated.
2165 function getSource()
2167 $ns = new Notice_source();
2168 if (!empty($this->source)) {
2169 switch ($this->source) {
2176 $ns->code = $this->source;
2179 $ns = Notice_source::getKV($this->source);
2181 $ns = new Notice_source();
2182 $ns->code = $this->source;
2183 $app = Oauth_application::getKV('name', $this->source);
2185 $ns->name = $app->name;
2186 $ns->url = $app->source_url;
2196 * Determine whether the notice was locally created
2198 * @return boolean locality
2201 public function isLocal()
2203 return ($this->is_local == Notice::LOCAL_PUBLIC ||
2204 $this->is_local == Notice::LOCAL_NONPUBLIC);
2208 * Get the list of hash tags saved with this notice.
2210 * @return array of strings
2212 public function getTags()
2216 $keypart = sprintf('notice:tags:%d', $this->id);
2218 $tagstr = self::cacheGet($keypart);
2220 if ($tagstr !== false) {
2221 $tags = explode(',', $tagstr);
2223 $tag = new Notice_tag();
2224 $tag->notice_id = $this->id;
2226 while ($tag->fetch()) {
2227 $tags[] = $tag->tag;
2230 self::cacheSet($keypart, implode(',', $tags));
2236 static private function utcDate($dt)
2238 $dateStr = date('d F Y H:i:s', strtotime($dt));
2239 $d = new DateTime($dateStr, new DateTimeZone('UTC'));
2240 return $d->format(DATE_W3C);
2244 * Look up the creation timestamp for a given notice ID, even
2245 * if it's been deleted.
2248 * @return mixed string recorded creation timestamp, or false if can't be found
2250 public static function getAsTimestamp($id)
2256 $notice = Notice::getKV('id', $id);
2258 return $notice->created;
2261 $deleted = Deleted_notice::getKV('id', $id);
2263 return $deleted->created;
2270 * Build an SQL 'where' fragment for timestamp-based sorting from a since_id
2271 * parameter, matching notices posted after the given one (exclusive).
2273 * If the referenced notice can't be found, will return false.
2276 * @param string $idField
2277 * @param string $createdField
2278 * @return mixed string or false if no match
2280 public static function whereSinceId($id, $idField='id', $createdField='created')
2282 $since = Notice::getAsTimestamp($id);
2284 return sprintf("($createdField = '%s' and $idField > %d) or ($createdField > '%s')", $since, $id, $since);
2290 * Build an SQL 'where' fragment for timestamp-based sorting from a since_id
2291 * parameter, matching notices posted after the given one (exclusive), and
2292 * if necessary add it to the data object's query.
2294 * @param DB_DataObject $obj
2296 * @param string $idField
2297 * @param string $createdField
2298 * @return mixed string or false if no match
2300 public static function addWhereSinceId(DB_DataObject $obj, $id, $idField='id', $createdField='created')
2302 $since = self::whereSinceId($id, $idField, $createdField);
2304 $obj->whereAdd($since);
2309 * Build an SQL 'where' fragment for timestamp-based sorting from a max_id
2310 * parameter, matching notices posted before the given one (inclusive).
2312 * If the referenced notice can't be found, will return false.
2315 * @param string $idField
2316 * @param string $createdField
2317 * @return mixed string or false if no match
2319 public static function whereMaxId($id, $idField='id', $createdField='created')
2321 $max = Notice::getAsTimestamp($id);
2323 return sprintf("($createdField < '%s') or ($createdField = '%s' and $idField <= %d)", $max, $max, $id);
2329 * Build an SQL 'where' fragment for timestamp-based sorting from a max_id
2330 * parameter, matching notices posted before the given one (inclusive), and
2331 * if necessary add it to the data object's query.
2333 * @param DB_DataObject $obj
2335 * @param string $idField
2336 * @param string $createdField
2337 * @return mixed string or false if no match
2339 public static function addWhereMaxId(DB_DataObject $obj, $id, $idField='id', $createdField='created')
2341 $max = self::whereMaxId($id, $idField, $createdField);
2343 $obj->whereAdd($max);
2349 if (common_config('public', 'localonly')) {
2350 return ($this->is_local == Notice::LOCAL_PUBLIC);
2352 return (($this->is_local != Notice::LOCAL_NONPUBLIC) &&
2353 ($this->is_local != Notice::GATEWAY));
2358 * Check that the given profile is allowed to read, respond to, or otherwise
2359 * act on this notice.
2361 * The $scope member is a bitmask of scopes, representing a logical AND of the
2362 * scope requirement. So, 0x03 (Notice::ADDRESSEE_SCOPE | Notice::SITE_SCOPE) means
2363 * "only visible to people who are mentioned in the notice AND are users on this site."
2364 * Users on the site who are not mentioned in the notice will not be able to see the
2367 * @param Profile $profile The profile to check; pass null to check for public/unauthenticated users.
2369 * @return boolean whether the profile is in the notice's scope
2371 function inScope($profile)
2373 if (is_null($profile)) {
2374 $keypart = sprintf('notice:in-scope-for:%d:null', $this->id);
2376 $keypart = sprintf('notice:in-scope-for:%d:%d', $this->id, $profile->id);
2379 $result = self::cacheGet($keypart);
2381 if ($result === false) {
2383 if (Event::handle('StartNoticeInScope', array($this, $profile, &$bResult))) {
2384 $bResult = $this->_inScope($profile);
2385 Event::handle('EndNoticeInScope', array($this, $profile, &$bResult));
2387 $result = ($bResult) ? 1 : 0;
2388 self::cacheSet($keypart, $result, 0, 300);
2391 return ($result == 1) ? true : false;
2394 protected function _inScope($profile)
2396 if (!is_null($this->scope)) {
2397 $scope = $this->scope;
2399 $scope = self::defaultScope();
2402 // If there's no scope, anyone (even anon) is in scope.
2404 if ($scope == 0) { // Not private
2406 return !$this->isHiddenSpam($profile);
2408 } else { // Private, somehow
2410 // If there's scope, anon cannot be in scope
2412 if (empty($profile)) {
2416 // Author is always in scope
2418 if ($this->profile_id == $profile->id) {
2422 // Only for users on this site
2424 if (($scope & Notice::SITE_SCOPE) && !$profile->isLocal()) {
2428 // Only for users mentioned in the notice
2430 if ($scope & Notice::ADDRESSEE_SCOPE) {
2432 $reply = Reply::pkeyGet(array('notice_id' => $this->id,
2433 'profile_id' => $profile->id));
2435 if (!$reply instanceof Reply) {
2440 // Only for members of the given group
2442 if ($scope & Notice::GROUP_SCOPE) {
2444 // XXX: just query for the single membership
2446 $groups = $this->getGroups();
2450 foreach ($groups as $group) {
2451 if ($profile->isMember($group)) {
2462 // Only for followers of the author
2466 if ($scope & Notice::FOLLOWER_SCOPE) {
2469 $author = $this->getProfile();
2470 } catch (Exception $e) {
2474 if (!Subscription::exists($profile, $author)) {
2479 return !$this->isHiddenSpam($profile);
2483 function isHiddenSpam($profile) {
2485 // Hide posts by silenced users from everyone but moderators.
2487 if (common_config('notice', 'hidespam')) {
2490 $author = $this->getProfile();
2491 } catch(Exception $e) {
2492 // If we can't get an author, keep it hidden.
2493 // XXX: technically not spam, but, whatever.
2497 if ($author->hasRole(Profile_role::SILENCED)) {
2498 if (!$profile instanceof Profile || (($profile->id !== $author->id) && (!$profile->hasRight(Right::REVIEWSPAM)))) {
2507 static function groupsFromText($text, $profile)
2511 /* extract all !group */
2512 $count = preg_match_all('/(?:^|\s)!(' . Nickname::DISPLAY_FMT . ')/',
2520 foreach (array_unique($match[1]) as $nickname) {
2521 $group = User_group::getForNickname($nickname, $profile);
2522 if ($group instanceof User_group && $profile->isMember($group)) {
2523 $groups[] = $group->id;
2530 public function getParent()
2532 $parent = Notice::getKV('id', $this->reply_to);
2534 if (!$parent instanceof Notice) {
2535 throw new ServerException('Notice has no parent');
2542 * Magic function called at serialize() time.
2544 * We use this to drop a couple process-specific references
2545 * from DB_DataObject which can cause trouble in future
2548 * @return array of variable names to include in serialization.
2553 $vars = parent::__sleep();
2554 $skip = array('_profile', '_groups', '_attachments', '_faves', '_replies', '_repeats');
2555 return array_diff($vars, $skip);
2558 static function defaultScope()
2560 $scope = common_config('notice', 'defaultscope');
2561 if (is_null($scope)) {
2562 if (common_config('site', 'private')) {
2571 static function fillProfiles($notices)
2573 $map = self::getProfiles($notices);
2575 foreach ($notices as $notice) {
2576 if (array_key_exists($notice->profile_id, $map)) {
2577 $notice->_setProfile($map[$notice->profile_id]);
2581 return array_values($map);
2584 static function getProfiles(&$notices)
2587 foreach ($notices as $notice) {
2588 $ids[] = $notice->profile_id;
2591 $ids = array_unique($ids);
2593 return Profile::pivotGet('id', $ids);
2596 static function fillGroups(&$notices)
2598 $ids = self::_idsOf($notices);
2600 $gis = Group_inbox::listGet('notice_id', $ids);
2604 foreach ($gis as $id => $gi)
2608 $gids[] = $g->group_id;
2612 $gids = array_unique($gids);
2614 $group = User_group::pivotGet('id', $gids);
2616 foreach ($notices as $notice)
2619 $gi = $gis[$notice->id];
2620 foreach ($gi as $g) {
2621 $grps[] = $group[$g->group_id];
2623 $notice->_setGroups($grps);
2627 static function _idsOf(&$notices)
2630 foreach ($notices as $notice) {
2631 $ids[] = $notice->id;
2633 $ids = array_unique($ids);
2637 static function fillAttachments(&$notices)
2639 $ids = self::_idsOf($notices);
2641 $f2pMap = File_to_post::listGet('post_id', $ids);
2645 foreach ($f2pMap as $noticeId => $f2ps) {
2646 foreach ($f2ps as $f2p) {
2647 $fileIds[] = $f2p->file_id;
2651 $fileIds = array_unique($fileIds);
2653 $fileMap = File::pivotGet('id', $fileIds);
2655 foreach ($notices as $notice)
2658 $f2ps = $f2pMap[$notice->id];
2659 foreach ($f2ps as $f2p) {
2660 $files[] = $fileMap[$f2p->file_id];
2662 $notice->_setAttachments($files);
2669 * All faves of this notice
2671 * @return array Array of Fave objects
2676 if (isset($this->_faves) && is_array($this->_faves)) {
2677 return $this->_faves;
2679 $faveMap = Fave::listGet('notice_id', array($this->id));
2680 $this->_faves = $faveMap[$this->id];
2681 return $this->_faves;
2684 function _setFaves($faves)
2686 $this->_faves = $faves;
2689 static function fillFaves(&$notices)
2691 $ids = self::_idsOf($notices);
2692 $faveMap = Fave::listGet('notice_id', $ids);
2695 foreach ($faveMap as $id => $faves) {
2696 $cnt += count($faves);
2697 if (count($faves) > 0) {
2701 foreach ($notices as $notice) {
2702 $faves = $faveMap[$notice->id];
2703 $notice->_setFaves($faves);
2707 static function fillReplies(&$notices)
2709 $ids = self::_idsOf($notices);
2710 $replyMap = Reply::listGet('notice_id', $ids);
2711 foreach ($notices as $notice) {
2712 $replies = $replyMap[$notice->id];
2714 foreach ($replies as $reply) {
2715 $ids[] = $reply->profile_id;
2717 $notice->_setReplies($ids);
2721 protected $_repeats;
2723 function getRepeats()
2725 if (isset($this->_repeats) && is_array($this->_repeats)) {
2726 return $this->_repeats;
2728 $repeatMap = Notice::listGet('repeat_of', array($this->id));
2729 $this->_repeats = $repeatMap[$this->id];
2730 return $this->_repeats;
2733 function _setRepeats($repeats)
2735 $this->_repeats = $repeats;
2738 static function fillRepeats(&$notices)
2740 $ids = self::_idsOf($notices);
2741 $repeatMap = Notice::listGet('repeat_of', $ids);
2742 foreach ($notices as $notice) {
2743 $repeats = $repeatMap[$notice->id];
2744 $notice->_setRepeats($repeats);