3 * StatusNet - the distributed open-source microblogging tool
4 * Copyright (C) 2008-2011 StatusNet, Inc.
6 * This program is free software: you can redistribute it and/or modify
7 * it under the terms of the GNU Affero General Public License as published by
8 * the Free Software Foundation, either version 3 of the License, or
9 * (at your option) any later version.
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU Affero General Public License for more details.
16 * You should have received a copy of the GNU Affero General Public License
17 * along with this program. If not, see <http://www.gnu.org/licenses/>.
21 * @author Brenda Wallace <shiny@cpan.org>
22 * @author Christopher Vollick <psycotica0@gmail.com>
23 * @author CiaranG <ciaran@ciarang.com>
24 * @author Craig Andrews <candrews@integralblue.com>
25 * @author Evan Prodromou <evan@controlezvous.ca>
26 * @author Gina Haeussge <osd@foosel.net>
27 * @author Jeffery To <jeffery.to@gmail.com>
28 * @author Mike Cochrane <mikec@mikenz.geek.nz>
29 * @author Robin Millette <millette@controlyourself.ca>
30 * @author Sarven Capadisli <csarven@controlyourself.ca>
31 * @author Tom Adams <tom@holizz.com>
32 * @copyright 2009 Free Software Foundation, Inc http://www.fsf.org
33 * @license GNU Affero General Public License http://www.gnu.org/licenses/
36 if (!defined('STATUSNET') && !defined('LACONICA')) {
41 * Table Definition for notice
43 require_once INSTALLDIR.'/classes/Memcached_DataObject.php';
45 /* We keep 200 notices, the max number of notices available per API request,
46 * in the memcached cache. */
48 define('NOTICE_CACHE_WINDOW', CachingNoticeStream::CACHE_WINDOW);
50 define('MAX_BOXCARS', 128);
52 class Notice extends Managed_DataObject
55 /* the code below is auto generated do not remove the above tag */
57 public $__table = 'notice'; // table name
58 public $id; // int(4) primary_key not_null
59 public $profile_id; // int(4) multiple_key not_null
60 public $uri; // varchar(255) unique_key
61 public $content; // text
62 public $rendered; // text
63 public $url; // varchar(255)
64 public $created; // datetime multiple_key not_null default_0000-00-00%2000%3A00%3A00
65 public $modified; // timestamp not_null default_CURRENT_TIMESTAMP
66 public $reply_to; // int(4)
67 public $is_local; // int(4)
68 public $source; // varchar(32)
69 public $conversation; // int(4)
70 public $lat; // decimal(10,7)
71 public $lon; // decimal(10,7)
72 public $location_id; // int(4)
73 public $location_ns; // int(4)
74 public $repeat_of; // int(4)
75 public $verb; // varchar(255)
76 public $object_type; // varchar(255)
77 public $scope; // int(4)
79 /* the code above is auto generated do not remove the tag below */
82 public static function schemaDef()
86 'id' => array('type' => 'serial', 'not null' => true, 'description' => 'unique identifier'),
87 'profile_id' => array('type' => 'int', 'not null' => true, 'description' => 'who made the update'),
88 'uri' => array('type' => 'varchar', 'length' => 255, 'description' => 'universally unique identifier, usually a tag URI'),
89 'content' => array('type' => 'text', 'description' => 'update content', 'collate' => 'utf8_general_ci'),
90 'rendered' => array('type' => 'text', 'description' => 'HTML version of the content'),
91 'url' => array('type' => 'varchar', 'length' => 255, 'description' => 'URL of any attachment (image, video, bookmark, whatever)'),
92 'created' => array('type' => 'datetime', 'not null' => true, 'description' => 'date this record was created'),
93 'modified' => array('type' => 'timestamp', 'not null' => true, 'description' => 'date this record was modified'),
94 'reply_to' => array('type' => 'int', 'description' => 'notice replied to (usually a guess)'),
95 'is_local' => array('type' => 'int', 'size' => 'tiny', 'default' => 0, 'description' => 'notice was generated by a user'),
96 'source' => array('type' => 'varchar', 'length' => 32, 'description' => 'source of comment, like "web", "im", or "clientname"'),
97 'conversation' => array('type' => 'int', 'description' => 'id of root notice in this conversation'),
98 'lat' => array('type' => 'numeric', 'precision' => 10, 'scale' => 7, 'description' => 'latitude'),
99 'lon' => array('type' => 'numeric', 'precision' => 10, 'scale' => 7, 'description' => 'longitude'),
100 'location_id' => array('type' => 'int', 'description' => 'location id if possible'),
101 'location_ns' => array('type' => 'int', 'description' => 'namespace for location'),
102 'repeat_of' => array('type' => 'int', 'description' => 'notice this is a repeat of'),
103 'object_type' => array('type' => 'varchar', 'length' => 255, 'description' => 'URI representing activity streams object type', 'default' => 'http://activitystrea.ms/schema/1.0/note'),
104 'verb' => array('type' => 'varchar', 'length' => 255, 'description' => 'URI representing activity streams verb', 'default' => 'http://activitystrea.ms/schema/1.0/post'),
105 'scope' => array('type' => 'int',
106 'description' => 'bit map for distribution scope; 0 = everywhere; 1 = this server only; 2 = addressees; 4 = followers; null = default'),
108 'primary key' => array('id'),
109 'unique keys' => array(
110 'notice_uri_key' => array('uri'),
112 'foreign keys' => array(
113 'notice_profile_id_fkey' => array('profile', array('profile_id' => 'id')),
114 'notice_reply_to_fkey' => array('notice', array('reply_to' => 'id')),
115 'notice_conversation_fkey' => array('conversation', array('conversation' => 'id')), # note... used to refer to notice.id
116 'notice_repeat_of_fkey' => array('notice', array('repeat_of' => 'id')), # @fixme: what about repeats of deleted notices?
119 'notice_created_id_is_local_idx' => array('created', 'id', 'is_local'),
120 'notice_profile_id_idx' => array('profile_id', 'created', 'id'),
121 'notice_repeat_of_created_id_idx' => array('repeat_of', 'created', 'id'),
122 'notice_conversation_created_id_idx' => array('conversation', 'created', 'id'),
123 'notice_replyto_idx' => array('reply_to')
127 if (common_config('search', 'type') == 'fulltext') {
128 $def['fulltext indexes'] = array('content' => array('content'));
134 function multiGet($kc, $kvs, $skipNulls=true)
136 return Memcached_DataObject::multiGet('Notice', $kc, $kvs, $skipNulls);
140 const LOCAL_PUBLIC = 1;
142 const LOCAL_NONPUBLIC = -1;
145 const PUBLIC_SCOPE = 0; // Useful fake constant
146 const SITE_SCOPE = 1;
147 const ADDRESSEE_SCOPE = 2;
148 const GROUP_SCOPE = 4;
149 const FOLLOWER_SCOPE = 8;
151 protected $_profile = -1;
153 function getProfile()
155 if (is_int($this->_profile) && $this->_profile == -1) {
156 $this->_setProfile(Profile::getKV('id', $this->profile_id));
158 if (empty($this->_profile)) {
159 // TRANS: Server exception thrown when a user profile for a notice cannot be found.
160 // TRANS: %1$d is a profile ID (number), %2$d is a notice ID (number).
161 throw new ServerException(sprintf(_('No such profile (%1$d) for notice (%2$d).'), $this->profile_id, $this->id));
165 return $this->_profile;
168 function _setProfile($profile)
170 $this->_profile = $profile;
175 // For auditing purposes, save a record that the notice
178 // @fixme we have some cases where things get re-run and so the
180 $deleted = Deleted_notice::getKV('id', $this->id);
183 $deleted = Deleted_notice::getKV('uri', $this->uri);
187 $deleted = new Deleted_notice();
189 $deleted->id = $this->id;
190 $deleted->profile_id = $this->profile_id;
191 $deleted->uri = $this->uri;
192 $deleted->created = $this->created;
193 $deleted->deleted = common_sql_now();
198 if (Event::handle('NoticeDeleteRelated', array($this))) {
200 // Clear related records
202 $this->clearReplies();
203 $this->clearRepeats();
206 $this->clearGroupInboxes();
209 // NOTE: we don't clear inboxes
210 // NOTE: we don't clear queue items
213 $result = parent::delete();
215 $this->blowOnDelete();
220 * Extract #hashtags from this notice's content and save them to the database.
224 /* extract all #hastags */
225 $count = preg_match_all('/(?:^|\s)#([\pL\pN_\-\.]{1,64})/u', strtolower($this->content), $match);
230 /* Add them to the database */
231 return $this->saveKnownTags($match[1]);
235 * Record the given set of hash tags in the db for this notice.
236 * Given tag strings will be normalized and checked for dupes.
238 function saveKnownTags($hashtags)
240 //turn each into their canonical tag
241 //this is needed to remove dupes before saving e.g. #hash.tag = #hashtag
242 for($i=0; $i<count($hashtags); $i++) {
243 /* elide characters we don't want in the tag */
244 $hashtags[$i] = common_canonical_tag($hashtags[$i]);
247 foreach(array_unique($hashtags) as $hashtag) {
248 $this->saveTag($hashtag);
249 self::blow('profile:notice_ids_tagged:%d:%s', $this->profile_id, $hashtag);
255 * Record a single hash tag as associated with this notice.
256 * Tag format and uniqueness must be validated by caller.
258 function saveTag($hashtag)
260 $tag = new Notice_tag();
261 $tag->notice_id = $this->id;
262 $tag->tag = $hashtag;
263 $tag->created = $this->created;
264 $id = $tag->insert();
267 // TRANS: Server exception. %s are the error details.
268 throw new ServerException(sprintf(_('Database error inserting hashtag: %s.'),
269 $last_error->message));
273 // if it's saved, blow its cache
274 $tag->blowCache(false);
278 * Save a new notice and push it out to subscribers' inboxes.
279 * Poster's permissions are checked before sending.
281 * @param int $profile_id Profile ID of the poster
282 * @param string $content source message text; links may be shortened
283 * per current user's preference
284 * @param string $source source key ('web', 'api', etc)
285 * @param array $options Associative array of optional properties:
286 * string 'created' timestamp of notice; defaults to now
287 * int 'is_local' source/gateway ID, one of:
288 * Notice::LOCAL_PUBLIC - Local, ok to appear in public timeline
289 * Notice::REMOTE - Sent from a remote service;
290 * hide from public timeline but show in
291 * local "and friends" timelines
292 * Notice::LOCAL_NONPUBLIC - Local, but hide from public timeline
293 * Notice::GATEWAY - From another non-OStatus service;
294 * will not appear in public views
295 * float 'lat' decimal latitude for geolocation
296 * float 'lon' decimal longitude for geolocation
297 * int 'location_id' geoname identifier
298 * int 'location_ns' geoname namespace to interpret location_id
299 * int 'reply_to'; notice ID this is a reply to
300 * int 'repeat_of'; notice ID this is a repeat of
301 * string 'uri' unique ID for notice; defaults to local notice URL
302 * string 'url' permalink to notice; defaults to local notice URL
303 * string 'rendered' rendered HTML version of content
304 * array 'replies' list of profile URIs for reply delivery in
305 * place of extracting @-replies from content.
306 * array 'groups' list of group IDs to deliver to, in place of
307 * extracting ! tags from content
308 * array 'tags' list of hashtag strings to save with the notice
309 * in place of extracting # tags from content
310 * array 'urls' list of attached/referred URLs to save with the
311 * notice in place of extracting links from content
312 * boolean 'distribute' whether to distribute the notice, default true
313 * string 'object_type' URL of the associated object type (default ActivityObject::NOTE)
314 * string 'verb' URL of the associated verb (default ActivityVerb::POST)
315 * int 'scope' Scope bitmask; default to SITE_SCOPE on private sites, 0 otherwise
317 * @fixme tag override
320 * @throws ClientException
322 static function saveNew($profile_id, $content, $source, array $options=null) {
323 $defaults = array('uri' => null,
328 'distribute' => true,
329 'object_type' => null,
332 if (!empty($options) && is_array($options)) {
333 $options = array_merge($defaults, $options);
339 if (!isset($is_local)) {
340 $is_local = Notice::LOCAL_PUBLIC;
343 $profile = Profile::getKV('id', $profile_id);
344 $user = User::getKV('id', $profile_id);
346 // Use the local user's shortening preferences, if applicable.
347 $final = $user->shortenLinks($content);
349 $final = common_shorten_links($content);
352 if (Notice::contentTooLong($final)) {
353 // TRANS: Client exception thrown if a notice contains too many characters.
354 throw new ClientException(_('Problem saving notice. Too long.'));
357 if (empty($profile)) {
358 // TRANS: Client exception thrown when trying to save a notice for an unknown user.
359 throw new ClientException(_('Problem saving notice. Unknown user.'));
362 if (common_config('throttle', 'enabled') && !Notice::checkEditThrottle($profile_id)) {
363 common_log(LOG_WARNING, 'Excessive posting by profile #' . $profile_id . '; throttled.');
364 // TRANS: Client exception thrown when a user tries to post too many notices in a given time frame.
365 throw new ClientException(_('Too many notices too fast; take a breather '.
366 'and post again in a few minutes.'));
369 if (common_config('site', 'dupelimit') > 0 && !Notice::checkDupes($profile_id, $final)) {
370 common_log(LOG_WARNING, 'Dupe posting by profile #' . $profile_id . '; throttled.');
371 // TRANS: Client exception thrown when a user tries to post too many duplicate notices in a given time frame.
372 throw new ClientException(_('Too many duplicate messages too quickly;'.
373 ' take a breather and post again in a few minutes.'));
376 if (!$profile->hasRight(Right::NEWNOTICE)) {
377 common_log(LOG_WARNING, "Attempted post from user disallowed to post: " . $profile->nickname);
379 // TRANS: Client exception thrown when a user tries to post while being banned.
380 throw new ClientException(_('You are banned from posting notices on this site.'), 403);
383 $notice = new Notice();
384 $notice->profile_id = $profile_id;
386 $autosource = common_config('public', 'autosource');
388 // Sandboxed are non-false, but not 1, either
390 if (!$profile->hasRight(Right::PUBLICNOTICE) ||
391 ($source && $autosource && in_array($source, $autosource))) {
392 $notice->is_local = Notice::LOCAL_NONPUBLIC;
394 $notice->is_local = $is_local;
397 if (!empty($created)) {
398 $notice->created = $created;
400 $notice->created = common_sql_now();
403 $notice->content = $final;
405 $notice->source = $source;
409 // Get the groups here so we can figure out replies and such
411 if (!isset($groups)) {
412 $groups = self::groupsFromText($notice->content, $profile);
417 // Handle repeat case
419 if (isset($repeat_of)) {
421 // Check for a private one
423 $repeat = Notice::getKV('id', $repeat_of);
425 if (empty($repeat)) {
426 // TRANS: Client exception thrown in notice when trying to repeat a missing or deleted notice.
427 throw new ClientException(_('Cannot repeat; original notice is missing or deleted.'));
430 if ($profile->id == $repeat->profile_id) {
431 // TRANS: Client error displayed when trying to repeat an own notice.
432 throw new ClientException(_('You cannot repeat your own notice.'));
435 if ($repeat->scope != Notice::SITE_SCOPE &&
436 $repeat->scope != Notice::PUBLIC_SCOPE) {
437 // TRANS: Client error displayed when trying to repeat a non-public notice.
438 throw new ClientException(_('Cannot repeat a private notice.'), 403);
441 if (!$repeat->inScope($profile)) {
442 // The generic checks above should cover this, but let's be sure!
443 // TRANS: Client error displayed when trying to repeat a notice you cannot access.
444 throw new ClientException(_('Cannot repeat a notice you cannot read.'), 403);
447 if ($profile->hasRepeated($repeat->id)) {
448 // TRANS: Client error displayed when trying to repeat an already repeated notice.
449 throw new ClientException(_('You already repeated that notice.'));
452 $notice->repeat_of = $repeat_of;
454 $reply = self::getReplyTo($reply_to, $profile_id, $source, $final);
456 if (!empty($reply)) {
458 if (!$reply->inScope($profile)) {
459 // TRANS: Client error displayed when trying to reply to a notice a the target has no access to.
460 // TRANS: %1$s is a user nickname, %2$d is a notice ID (number).
461 throw new ClientException(sprintf(_('%1$s has no access to notice %2$d.'),
462 $profile->nickname, $reply->id), 403);
465 $notice->reply_to = $reply->id;
466 $notice->conversation = $reply->conversation;
468 // If the original is private to a group, and notice has no group specified,
469 // make it to the same group(s)
471 if (empty($groups) && ($reply->scope | Notice::GROUP_SCOPE)) {
473 $replyGroups = $reply->getGroups();
474 foreach ($replyGroups as $group) {
475 if ($profile->isMember($group)) {
476 $groups[] = $group->id;
485 if (!empty($lat) && !empty($lon)) {
490 if (!empty($location_ns) && !empty($location_id)) {
491 $notice->location_id = $location_id;
492 $notice->location_ns = $location_ns;
495 if (!empty($rendered)) {
496 $notice->rendered = $rendered;
498 $notice->rendered = common_render_content($final, $notice);
502 if (!empty($notice->repeat_of)) {
503 $notice->verb = ActivityVerb::SHARE;
504 $notice->object_type = ActivityObject::ACTIVITY;
506 $notice->verb = ActivityVerb::POST;
509 $notice->verb = $verb;
512 if (empty($object_type)) {
513 $notice->object_type = (empty($notice->reply_to)) ? ActivityObject::NOTE : ActivityObject::COMMENT;
515 $notice->object_type = $object_type;
518 if (is_null($scope)) { // 0 is a valid value
519 if (!empty($reply)) {
520 $notice->scope = $reply->scope;
522 $notice->scope = self::defaultScope();
525 $notice->scope = $scope;
528 // For private streams
530 $user = $profile->getUser();
533 if ($user->private_stream &&
534 ($notice->scope == Notice::PUBLIC_SCOPE ||
535 $notice->scope == Notice::SITE_SCOPE)) {
536 $notice->scope |= Notice::FOLLOWER_SCOPE;
540 // Force the scope for private groups
542 foreach ($groups as $groupId) {
543 $group = User_group::getKV('id', $groupId);
544 if (!empty($group)) {
545 if ($group->force_scope) {
546 $notice->scope |= Notice::GROUP_SCOPE;
552 if (Event::handle('StartNoticeSave', array(&$notice))) {
554 // XXX: some of these functions write to the DB
556 $id = $notice->insert();
559 common_log_db_error($notice, 'INSERT', __FILE__);
560 // TRANS: Server exception thrown when a notice cannot be saved.
561 throw new ServerException(_('Problem saving notice.'));
564 // Update ID-dependent columns: URI, conversation
566 $orig = clone($notice);
571 $notice->uri = common_notice_uri($notice);
575 // If it's not part of a conversation, it's
576 // the beginning of a new conversation.
578 if (empty($notice->conversation)) {
579 $conv = Conversation::create();
580 $notice->conversation = $conv->id;
585 if (!$notice->update($orig)) {
586 common_log_db_error($notice, 'UPDATE', __FILE__);
587 // TRANS: Server exception thrown when a notice cannot be updated.
588 throw new ServerException(_('Problem saving notice.'));
594 // Clear the cache for subscribed users, so they'll update at next request
595 // XXX: someone clever could prepend instead of clearing the cache
597 $notice->blowOnInsert();
599 // Save per-notice metadata...
601 if (isset($replies)) {
602 $notice->saveKnownReplies($replies);
604 $notice->saveReplies();
608 $notice->saveKnownTags($tags);
613 // Note: groups may save tags, so must be run after tags are saved
614 // to avoid errors on duplicates.
615 // Note: groups should always be set.
617 $notice->saveKnownGroups($groups);
620 $notice->saveKnownUrls($urls);
626 // Prepare inbox delivery, may be queued to background.
627 $notice->distribute();
633 function blowOnInsert($conversation = false)
635 $this->blowStream('profile:notice_ids:%d', $this->profile_id);
637 if ($this->isPublic()) {
638 $this->blowStream('public');
641 self::blow('notice:list-ids:conversation:%s', $this->conversation);
642 self::blow('conversation:notice_count:%d', $this->conversation);
644 if (!empty($this->repeat_of)) {
645 // XXX: we should probably only use one of these
646 $this->blowStream('notice:repeats:%d', $this->repeat_of);
647 self::blow('notice:list-ids:repeat_of:%d', $this->repeat_of);
650 $original = Notice::getKV('id', $this->repeat_of);
652 if (!empty($original)) {
653 $originalUser = User::getKV('id', $original->profile_id);
654 if (!empty($originalUser)) {
655 $this->blowStream('user:repeats_of_me:%d', $originalUser->id);
659 $profile = Profile::getKV($this->profile_id);
661 if (!empty($profile)) {
662 $profile->blowNoticeCount();
665 $ptags = $this->getProfileTags();
666 foreach ($ptags as $ptag) {
667 $ptag->blowNoticeStreamCache();
672 * Clear cache entries related to this notice at delete time.
673 * Necessary to avoid breaking paging on public, profile timelines.
675 function blowOnDelete()
677 $this->blowOnInsert();
679 self::blow('profile:notice_ids:%d;last', $this->profile_id);
681 if ($this->isPublic()) {
682 self::blow('public;last');
685 self::blow('fave:by_notice', $this->id);
687 if ($this->conversation) {
688 // In case we're the first, will need to calc a new root.
689 self::blow('notice:conversation_root:%d', $this->conversation);
692 $ptags = $this->getProfileTags();
693 foreach ($ptags as $ptag) {
694 $ptag->blowNoticeStreamCache(true);
698 function blowStream()
700 $c = self::memcache();
706 $args = func_get_args();
708 $format = array_shift($args);
710 $keyPart = vsprintf($format, $args);
712 $cacheKey = Cache::key($keyPart);
714 $c->delete($cacheKey);
716 // delete the "last" stream, too, if this notice is
717 // older than the top of that stream
719 $lastKey = $cacheKey.';last';
721 $lastStr = $c->get($lastKey);
723 if ($lastStr !== false) {
724 $window = explode(',', $lastStr);
725 $lastID = $window[0];
726 $lastNotice = Notice::getKV('id', $lastID);
727 if (empty($lastNotice) // just weird
728 || strtotime($lastNotice->created) >= strtotime($this->created)) {
729 $c->delete($lastKey);
734 /** save all urls in the notice to the db
736 * follow redirects and save all available file information
737 * (mimetype, date, size, oembed, etc.)
741 function saveUrls() {
742 if (common_config('attachments', 'process_links')) {
743 common_replace_urls_callback($this->content, array($this, 'saveUrl'), $this->id);
748 * Save the given URLs as related links/attachments to the db
750 * follow redirects and save all available file information
751 * (mimetype, date, size, oembed, etc.)
755 function saveKnownUrls($urls)
757 if (common_config('attachments', 'process_links')) {
758 // @fixme validation?
759 foreach (array_unique($urls) as $url) {
760 File::processNew($url, $this->id);
768 function saveUrl($url, $notice_id) {
769 File::processNew($url, $notice_id);
772 static function checkDupes($profile_id, $content) {
773 $profile = Profile::getKV($profile_id);
774 if (empty($profile)) {
777 $notice = $profile->getNotices(0, CachingNoticeStream::CACHE_WINDOW);
778 if (!empty($notice)) {
780 while ($notice->fetch()) {
781 if (time() - strtotime($notice->created) >= common_config('site', 'dupelimit')) {
783 } else if ($notice->content == $content) {
788 // If we get here, oldest item in cache window is not
789 // old enough for dupe limit; do direct check against DB
790 $notice = new Notice();
791 $notice->profile_id = $profile_id;
792 $notice->content = $content;
793 $threshold = common_sql_date(time() - common_config('site', 'dupelimit'));
794 $notice->whereAdd(sprintf("created > '%s'", $notice->escape($threshold)));
796 $cnt = $notice->count();
800 static function checkEditThrottle($profile_id) {
801 $profile = Profile::getKV($profile_id);
802 if (empty($profile)) {
805 // Get the Nth notice
806 $notice = $profile->getNotices(common_config('throttle', 'count') - 1, 1);
807 if ($notice && $notice->fetch()) {
808 // If the Nth notice was posted less than timespan seconds ago
809 if (time() - strtotime($notice->created) <= common_config('throttle', 'timespan')) {
814 // Either not N notices in the stream, OR the Nth was not posted within timespan seconds
818 protected $_attachments = -1;
820 function attachments() {
822 if ($this->_attachments != -1) {
823 return $this->_attachments;
826 $f2ps = File_to_post::listGet('post_id', array($this->id));
830 foreach ($f2ps[$this->id] as $f2p) {
831 $ids[] = $f2p->file_id;
834 $files = Memcached_DataObject::multiGet('File', 'id', $ids);
836 $this->_attachments = $files->fetchAll();
838 return $this->_attachments;
841 function _setAttachments($attachments)
843 $this->_attachments = $attachments;
846 function publicStream($offset=0, $limit=20, $since_id=0, $max_id=0)
848 $stream = new PublicNoticeStream();
849 return $stream->getNotices($offset, $limit, $since_id, $max_id);
853 function conversationStream($id, $offset=0, $limit=20, $since_id=0, $max_id=0)
855 $stream = new ConversationNoticeStream($id);
857 return $stream->getNotices($offset, $limit, $since_id, $max_id);
861 * Is this notice part of an active conversation?
863 * @return boolean true if other messages exist in the same
864 * conversation, false if this is the only one
866 function hasConversation()
868 if (!empty($this->conversation)) {
869 $conversation = Notice::conversationStream(
875 if ($conversation->N > 0) {
883 * Grab the earliest notice from this conversation.
885 * @return Notice or null
887 function conversationRoot($profile=-1)
889 // XXX: can this happen?
891 if (empty($this->conversation)) {
895 // Get the current profile if not specified
897 if (is_int($profile) && $profile == -1) {
898 $profile = Profile::current();
901 // If this notice is out of scope, no root for you!
903 if (!$this->inScope($profile)) {
907 // If this isn't a reply to anything, then it's its own
910 if (empty($this->reply_to)) {
914 if (is_null($profile)) {
915 $keypart = sprintf('notice:conversation_root:%d:null', $this->id);
917 $keypart = sprintf('notice:conversation_root:%d:%d',
922 $root = self::cacheGet($keypart);
924 if ($root !== false && $root->inScope($profile)) {
930 $parent = $last->getOriginal();
931 if (!empty($parent) && $parent->inScope($profile)) {
938 } while (!empty($parent));
940 self::cacheSet($keypart, $root);
947 * Pull up a full list of local recipients who will be getting
948 * this notice in their inbox. Results will be cached, so don't
949 * change the input data wily-nilly!
951 * @param array $groups optional list of Group objects;
952 * if left empty, will be loaded from group_inbox records
953 * @param array $recipient optional list of reply profile ids
954 * if left empty, will be loaded from reply records
955 * @return array associating recipient user IDs with an inbox source constant
957 function whoGets(array $groups=null, array $recipients=null)
959 $c = self::memcache();
962 $ni = $c->get(Cache::key('notice:who_gets:'.$this->id));
968 if (is_null($groups)) {
969 $groups = $this->getGroups();
972 if (is_null($recipients)) {
973 $recipients = $this->getReplies();
976 $users = $this->getSubscribedUsers();
977 $ptags = $this->getProfileTags();
979 // FIXME: kind of ignoring 'transitional'...
980 // we'll probably stop supporting inboxless mode
985 // Give plugins a chance to add folks in at start...
986 if (Event::handle('StartNoticeWhoGets', array($this, &$ni))) {
988 foreach ($users as $id) {
989 $ni[$id] = NOTICE_INBOX_SOURCE_SUB;
992 foreach ($groups as $group) {
993 $users = $group->getUserMembers();
994 foreach ($users as $id) {
995 if (!array_key_exists($id, $ni)) {
996 $ni[$id] = NOTICE_INBOX_SOURCE_GROUP;
1001 foreach ($ptags as $ptag) {
1002 $users = $ptag->getUserSubscribers();
1003 foreach ($users as $id) {
1004 if (!array_key_exists($id, $ni)) {
1005 $ni[$id] = NOTICE_INBOX_SOURCE_PROFILE_TAG;
1010 foreach ($recipients as $recipient) {
1011 if (!array_key_exists($recipient, $ni)) {
1012 $ni[$recipient] = NOTICE_INBOX_SOURCE_REPLY;
1016 // Exclude any deleted, non-local, or blocking recipients.
1017 $profile = $this->getProfile();
1018 $originalProfile = null;
1019 if ($this->repeat_of) {
1020 // Check blocks against the original notice's poster as well.
1021 $original = Notice::getKV('id', $this->repeat_of);
1023 $originalProfile = $original->getProfile();
1027 foreach ($ni as $id => $source) {
1029 $user = User::getKV('id', $id);
1031 $user->hasBlocked($profile) ||
1032 ($originalProfile && $user->hasBlocked($originalProfile))) {
1035 } catch (UserNoProfileException $e) {
1036 // User doesn't have a profile; invalid; skip them.
1041 // Give plugins a chance to filter out...
1042 Event::handle('EndNoticeWhoGets', array($this, &$ni));
1046 // XXX: pack this data better
1047 $c->set(Cache::key('notice:who_gets:'.$this->id), $ni);
1054 * Adds this notice to the inboxes of each local user who should receive
1055 * it, based on author subscriptions, group memberships, and @-replies.
1057 * Warning: running a second time currently will make items appear
1058 * multiple times in users' inboxes.
1060 * @fixme make more robust against errors
1061 * @fixme break up massive deliveries to smaller background tasks
1063 * @param array $groups optional list of Group objects;
1064 * if left empty, will be loaded from group_inbox records
1065 * @param array $recipient optional list of reply profile ids
1066 * if left empty, will be loaded from reply records
1068 function addToInboxes(array $groups=null, array $recipients=null)
1070 $ni = $this->whoGets($groups, $recipients);
1072 $ids = array_keys($ni);
1074 // We remove the author (if they're a local user),
1075 // since we'll have already done this in distribute()
1077 $i = array_search($this->profile_id, $ids);
1085 Inbox::bulkInsert($this->id, $ids);
1090 function getSubscribedUsers()
1094 if(common_config('db','quote_identifiers'))
1095 $user_table = '"user"';
1096 else $user_table = 'user';
1100 'FROM '. $user_table .' JOIN subscription '.
1101 'ON '. $user_table .'.id = subscription.subscriber ' .
1102 'WHERE subscription.subscribed = %d ';
1104 $user->query(sprintf($qry, $this->profile_id));
1108 while ($user->fetch()) {
1117 function getProfileTags()
1119 $profile = $this->getProfile();
1120 $list = $profile->getOtherTags($profile);
1123 while($list->fetch()) {
1124 $ptags[] = clone($list);
1131 * Record this notice to the given group inboxes for delivery.
1132 * Overrides the regular parsing of !group markup.
1134 * @param string $group_ids
1135 * @fixme might prefer URIs as identifiers, as for replies?
1136 * best with generalizations on user_group to support
1137 * remote groups better.
1139 function saveKnownGroups($group_ids)
1141 if (!is_array($group_ids)) {
1142 // TRANS: Server exception thrown when no array is provided to the method saveKnownGroups().
1143 throw new ServerException(_('Bad type provided to saveKnownGroups.'));
1147 foreach (array_unique($group_ids) as $id) {
1148 $group = User_group::getKV('id', $id);
1150 common_log(LOG_ERR, "Local delivery to group id $id, $group->nickname");
1151 $result = $this->addToGroupInbox($group);
1153 common_log_db_error($gi, 'INSERT', __FILE__);
1156 if (common_config('group', 'addtag')) {
1157 // we automatically add a tag for every group name, too
1159 $tag = Notice_tag::pkeyGet(array('tag' => common_canonical_tag($group->nickname),
1160 'notice_id' => $this->id));
1162 if (is_null($tag)) {
1163 $this->saveTag($group->nickname);
1167 $groups[] = clone($group);
1169 common_log(LOG_ERR, "Local delivery to group id $id skipped, doesn't exist");
1177 * Parse !group delivery and record targets into group_inbox.
1178 * @return array of Group objects
1180 function saveGroups()
1182 // Don't save groups for repeats
1184 if (!empty($this->repeat_of)) {
1188 $profile = $this->getProfile();
1190 $groups = self::groupsFromText($this->content, $profile);
1192 /* Add them to the database */
1194 foreach ($groups as $group) {
1195 /* XXX: remote groups. */
1197 if (empty($group)) {
1202 if ($profile->isMember($group)) {
1204 $result = $this->addToGroupInbox($group);
1207 common_log_db_error($gi, 'INSERT', __FILE__);
1210 $groups[] = clone($group);
1217 function addToGroupInbox($group)
1219 $gi = Group_inbox::pkeyGet(array('group_id' => $group->id,
1220 'notice_id' => $this->id));
1224 $gi = new Group_inbox();
1226 $gi->group_id = $group->id;
1227 $gi->notice_id = $this->id;
1228 $gi->created = $this->created;
1230 $result = $gi->insert();
1233 common_log_db_error($gi, 'INSERT', __FILE__);
1234 // TRANS: Server exception thrown when an update for a group inbox fails.
1235 throw new ServerException(_('Problem saving group inbox.'));
1238 self::blow('user_group:notice_ids:%d', $gi->group_id);
1245 * Save reply records indicating that this notice needs to be
1246 * delivered to the local users with the given URIs.
1248 * Since this is expected to be used when saving foreign-sourced
1249 * messages, we won't deliver to any remote targets as that's the
1250 * source service's responsibility.
1252 * Mail notifications etc will be handled later.
1254 * @param array $uris Array of unique identifier URIs for recipients
1256 function saveKnownReplies(array $uris)
1262 $sender = Profile::getKV($this->profile_id);
1264 foreach (array_unique($uris) as $uri) {
1266 $profile = Profile::fromURI($uri);
1268 if (empty($profile)) {
1269 common_log(LOG_WARNING, "Unable to determine profile for URI '$uri'");
1273 if ($profile->hasBlocked($sender)) {
1274 common_log(LOG_INFO, "Not saving reply to profile {$profile->id} ($uri) from sender {$sender->id} because of a block.");
1278 $this->saveReply($profile->id);
1279 self::blow('reply:stream:%d', $profile->id);
1286 * Pull @-replies from this message's content in StatusNet markup format
1287 * and save reply records indicating that this message needs to be
1288 * delivered to those users.
1290 * Mail notifications to local profiles will be sent later.
1292 * @return array of integer profile IDs
1295 function saveReplies()
1297 // Don't save reply data for repeats
1299 if (!empty($this->repeat_of)) {
1303 $sender = Profile::getKV($this->profile_id);
1307 // If it's a reply, save for the replied-to author
1309 if (!empty($this->reply_to)) {
1310 $original = $this->getOriginal();
1311 if (!empty($original)) { // that'd be weird
1312 $author = $original->getProfile();
1313 if (!empty($author)) {
1314 $this->saveReply($author->id);
1315 $replied[$author->id] = 1;
1316 self::blow('reply:stream:%d', $author->id);
1321 // @todo ideally this parser information would only
1322 // be calculated once.
1324 $mentions = common_find_mentions($this->content, $this);
1326 // store replied only for first @ (what user/notice what the reply directed,
1327 // we assume first @ is it)
1329 foreach ($mentions as $mention) {
1331 foreach ($mention['mentioned'] as $mentioned) {
1333 // skip if they're already covered
1335 if (!empty($replied[$mentioned->id])) {
1339 // Don't save replies from blocked profile to local user
1341 $mentioned_user = User::getKV('id', $mentioned->id);
1342 if (!empty($mentioned_user) && $mentioned_user->hasBlocked($sender)) {
1346 $this->saveReply($mentioned->id);
1347 $replied[$mentioned->id] = 1;
1348 self::blow('reply:stream:%d', $mentioned->id);
1352 $recipientIds = array_keys($replied);
1354 return $recipientIds;
1357 function saveReply($profileId)
1359 $reply = new Reply();
1361 $reply->notice_id = $this->id;
1362 $reply->profile_id = $profileId;
1363 $reply->modified = $this->created;
1370 protected $_replies = -1;
1373 * Pull the complete list of @-reply targets for this notice.
1375 * @return array of integer profile ids
1377 function getReplies()
1379 if ($this->_replies != -1) {
1380 return $this->_replies;
1383 $replyMap = Reply::listGet('notice_id', array($this->id));
1387 foreach ($replyMap[$this->id] as $reply) {
1388 $ids[] = $reply->profile_id;
1391 $this->_replies = $ids;
1396 function _setReplies($replies)
1398 $this->_replies = $replies;
1402 * Pull the complete list of @-reply targets for this notice.
1404 * @return array of Profiles
1406 function getReplyProfiles()
1408 $ids = $this->getReplies();
1410 $profiles = Profile::multiGet('id', $ids);
1412 return $profiles->fetchAll();
1416 * Send e-mail notifications to local @-reply targets.
1418 * Replies must already have been saved; this is expected to be run
1419 * from the distrib queue handler.
1421 function sendReplyNotifications()
1423 // Don't send reply notifications for repeats
1425 if (!empty($this->repeat_of)) {
1429 $recipientIds = $this->getReplies();
1431 foreach ($recipientIds as $recipientId) {
1432 $user = User::getKV('id', $recipientId);
1433 if (!empty($user)) {
1434 mail_notify_attn($user, $this);
1440 * Pull list of groups this notice needs to be delivered to,
1441 * as previously recorded by saveGroups() or saveKnownGroups().
1443 * @return array of Group objects
1446 protected $_groups = -1;
1448 function getGroups()
1450 // Don't save groups for repeats
1452 if (!empty($this->repeat_of)) {
1456 if ($this->_groups != -1)
1458 return $this->_groups;
1461 $gis = Group_inbox::listGet('notice_id', array($this->id));
1465 foreach ($gis[$this->id] as $gi)
1467 $ids[] = $gi->group_id;
1470 $groups = User_group::multiGet('id', $ids);
1472 $this->_groups = $groups->fetchAll();
1474 return $this->_groups;
1477 function _setGroups($groups)
1479 $this->_groups = $groups;
1483 * Convert a notice into an activity for export.
1485 * @param User $cur Current user
1487 * @return Activity activity object representing this Notice.
1490 function asActivity($cur=null)
1492 $act = self::cacheGet(Cache::codeKey('notice:as-activity:'.$this->id));
1497 $act = new Activity();
1499 if (Event::handle('StartNoticeAsActivity', array($this, &$act))) {
1501 $act->id = TagURI::mint("post:".$this->id);
1502 $act->time = strtotime($this->created);
1503 $act->content = common_xml_safe_str($this->rendered);
1505 $profile = $this->getProfile();
1507 $act->actor = ActivityObject::fromProfile($profile);
1508 $act->actor->extra[] = $profile->profileInfo($cur);
1510 $act->verb = $this->verb;
1512 if ($this->repeat_of) {
1513 $repeated = Notice::getKV('id', $this->repeat_of);
1514 if (!empty($repeated)) {
1515 $act->objects[] = $repeated->asActivity($cur);
1518 $act->objects[] = ActivityObject::fromNotice($this);
1521 // XXX: should this be handled by default processing for object entry?
1525 $tags = $this->getTags();
1527 foreach ($tags as $tag) {
1528 $cat = new AtomCategory();
1531 $act->categories[] = $cat;
1535 // XXX: use Atom Media and/or File activity objects instead
1537 $attachments = $this->attachments();
1539 foreach ($attachments as $attachment) {
1540 // Save local attachments
1541 if (!empty($attachment->filename)) {
1542 $act->attachments[] = ActivityObject::fromFile($attachment);
1546 $ctx = new ActivityContext();
1548 if (!empty($this->reply_to)) {
1549 $reply = Notice::getKV('id', $this->reply_to);
1550 if (!empty($reply)) {
1551 $ctx->replyToID = $reply->uri;
1552 $ctx->replyToUrl = $reply->bestUrl();
1556 $ctx->location = $this->getLocation();
1560 if (!empty($this->conversation)) {
1561 $conv = Conversation::getKV('id', $this->conversation);
1562 if (!empty($conv)) {
1563 $ctx->conversation = $conv->uri;
1567 $reply_ids = $this->getReplies();
1569 foreach ($reply_ids as $id) {
1570 $rprofile = Profile::getKV('id', $id);
1571 if (!empty($rprofile)) {
1572 $ctx->attention[] = $rprofile->getUri();
1573 $ctx->attentionType[$rprofile->getUri()] = ActivityObject::PERSON;
1577 $groups = $this->getGroups();
1579 foreach ($groups as $group) {
1580 $ctx->attention[] = $group->getUri();
1581 $ctx->attentionType[$group->getUri()] = ActivityObject::GROUP;
1584 switch ($this->scope) {
1585 case Notice::PUBLIC_SCOPE:
1586 $ctx->attention[] = "http://activityschema.org/collection/public";
1587 $ctx->attentionType["http://activityschema.org/collection/public"] = ActivityObject::COLLECTION;
1589 case Notice::FOLLOWER_SCOPE:
1590 $surl = common_local_url("subscribers", array('nickname' => $profile->nickname));
1591 $ctx->attention[] = $surl;
1592 $ctx->attentionType[$surl] = ActivityObject::COLLECTION;
1596 // XXX: deprecated; use ActivityVerb::SHARE instead
1600 if (!empty($this->repeat_of)) {
1601 $repeat = Notice::getKV('id', $this->repeat_of);
1602 if (!empty($repeat)) {
1603 $ctx->forwardID = $repeat->uri;
1604 $ctx->forwardUrl = $repeat->bestUrl();
1608 $act->context = $ctx;
1610 $source = $this->getSource();
1613 $act->generator = ActivityObject::fromNoticeSource($source);
1618 $atom_feed = $profile->getAtomFeed();
1620 if (!empty($atom_feed)) {
1622 $act->source = new ActivitySource();
1624 // XXX: we should store the actual feed ID
1626 $act->source->id = $atom_feed;
1628 // XXX: we should store the actual feed title
1630 $act->source->title = $profile->getBestName();
1632 $act->source->links['alternate'] = $profile->profileurl;
1633 $act->source->links['self'] = $atom_feed;
1635 $act->source->icon = $profile->avatarUrl(AVATAR_PROFILE_SIZE);
1637 $notice = $profile->getCurrentNotice();
1639 if (!empty($notice)) {
1640 $act->source->updated = self::utcDate($notice->created);
1643 $user = User::getKV('id', $profile->id);
1645 if (!empty($user)) {
1646 $act->source->links['license'] = common_config('license', 'url');
1650 if ($this->isLocal()) {
1651 $act->selfLink = common_local_url('ApiStatusesShow', array('id' => $this->id,
1652 'format' => 'atom'));
1653 $act->editLink = $act->selfLink;
1656 Event::handle('EndNoticeAsActivity', array($this, &$act));
1659 self::cacheSet(Cache::codeKey('notice:as-activity:'.$this->id), $act);
1664 // This has gotten way too long. Needs to be sliced up into functional bits
1665 // or ideally exported to a utility class.
1667 function asAtomEntry($namespace=false,
1672 $act = $this->asActivity($cur);
1673 $act->extra[] = $this->noticeInfo($cur);
1674 return $act->asString($namespace, $author, $source);
1678 * Extra notice info for atom entries
1680 * Clients use some extra notice info in the atom stream.
1681 * This gives it to them.
1683 * @param User $cur Current user
1685 * @return array representation of <statusnet:notice_info> element
1688 function noticeInfo($cur)
1690 // local notice ID (useful to clients for ordering)
1692 $noticeInfoAttr = array('local_id' => $this->id);
1696 $ns = $this->getSource();
1699 $noticeInfoAttr['source'] = $ns->code;
1700 if (!empty($ns->url)) {
1701 $noticeInfoAttr['source_link'] = $ns->url;
1702 if (!empty($ns->name)) {
1703 $noticeInfoAttr['source'] = '<a href="'
1704 . htmlspecialchars($ns->url)
1705 . '" rel="nofollow">'
1706 . htmlspecialchars($ns->name)
1712 // favorite and repeated
1715 $noticeInfoAttr['favorite'] = ($cur->hasFave($this)) ? "true" : "false";
1716 $cp = $cur->getProfile();
1717 $noticeInfoAttr['repeated'] = ($cp->hasRepeated($this->id)) ? "true" : "false";
1720 if (!empty($this->repeat_of)) {
1721 $noticeInfoAttr['repeat_of'] = $this->repeat_of;
1724 return array('statusnet:notice_info', $noticeInfoAttr, null);
1728 * Returns an XML string fragment with a reference to a notice as an
1729 * Activity Streams noun object with the given element type.
1731 * Assumes that 'activity' namespace has been previously defined.
1733 * @param string $element one of 'subject', 'object', 'target'
1737 function asActivityNoun($element)
1739 $noun = ActivityObject::fromNotice($this);
1740 return $noun->asString('activity:' . $element);
1745 if (!empty($this->url)) {
1747 } else if (!empty($this->uri) && preg_match('/^https?:/', $this->uri)) {
1750 return common_local_url('shownotice',
1751 array('notice' => $this->id));
1757 * Determine which notice, if any, a new notice is in reply to.
1759 * For conversation tracking, we try to see where this notice fits
1760 * in the tree. Rough algorithm is:
1762 * if (reply_to is set and valid) {
1764 * } else if ((source not API or Web) and (content starts with "T NAME" or "@name ")) {
1765 * return ID of last notice by initial @name in content;
1768 * Note that all @nickname instances will still be used to save "reply" records,
1769 * so the notice shows up in the mentioned users' "replies" tab.
1771 * @param integer $reply_to ID passed in by Web or API
1772 * @param integer $profile_id ID of author
1773 * @param string $source Source tag, like 'web' or 'gwibber'
1774 * @param string $content Final notice content
1776 * @return integer ID of replied-to notice, or null for not a reply.
1779 static function getReplyTo($reply_to, $profile_id, $source, $content)
1781 static $lb = array('xmpp', 'mail', 'sms', 'omb');
1783 // If $reply_to is specified, we check that it exists, and then
1784 // return it if it does
1786 if (!empty($reply_to)) {
1787 $reply_notice = Notice::getKV('id', $reply_to);
1788 if (!empty($reply_notice)) {
1789 return $reply_notice;
1793 // If it's not a "low bandwidth" source (one where you can't set
1794 // a reply_to argument), we return. This is mostly web and API
1797 if (!in_array($source, $lb)) {
1801 // Is there an initial @ or T?
1803 if (preg_match('/^T ([A-Z0-9]{1,64}) /', $content, $match) ||
1804 preg_match('/^@([a-z0-9]{1,64})\s+/', $content, $match)) {
1805 $nickname = common_canonical_nickname($match[1]);
1810 // Figure out who that is.
1812 $sender = Profile::getKV('id', $profile_id);
1813 if (empty($sender)) {
1817 $recipient = common_relative_profile($sender, $nickname, common_sql_now());
1819 if (empty($recipient)) {
1823 // Get their last notice
1825 $last = $recipient->getCurrentNotice();
1827 if (!empty($last)) {
1834 static function maxContent()
1836 $contentlimit = common_config('notice', 'contentlimit');
1837 // null => use global limit (distinct from 0!)
1838 if (is_null($contentlimit)) {
1839 $contentlimit = common_config('site', 'textlimit');
1841 return $contentlimit;
1844 static function contentTooLong($content)
1846 $contentlimit = self::maxContent();
1847 return ($contentlimit > 0 && !empty($content) && (mb_strlen($content) > $contentlimit));
1850 function getLocation()
1854 if (!empty($this->location_id) && !empty($this->location_ns)) {
1855 $location = Location::fromId($this->location_id, $this->location_ns);
1858 if (is_null($location)) { // no ID, or Location::fromId() failed
1859 if (!empty($this->lat) && !empty($this->lon)) {
1860 $location = Location::fromLatLon($this->lat, $this->lon);
1868 * Convenience function for posting a repeat of an existing message.
1870 * @param int $repeater_id: profile ID of user doing the repeat
1871 * @param string $source: posting source key, eg 'web', 'api', etc
1874 * @throws Exception on failure or permission problems
1876 function repeat($repeater_id, $source)
1878 $author = Profile::getKV('id', $this->profile_id);
1880 // TRANS: Message used to repeat a notice. RT is the abbreviation of 'retweet'.
1881 // TRANS: %1$s is the repeated user's name, %2$s is the repeated notice.
1882 $content = sprintf(_('RT @%1$s %2$s'),
1886 $maxlen = common_config('site', 'textlimit');
1887 if ($maxlen > 0 && mb_strlen($content) > $maxlen) {
1888 // Web interface and current Twitter API clients will
1889 // pull the original notice's text, but some older
1890 // clients and RSS/Atom feeds will see this trimmed text.
1892 // Unfortunately this is likely to lose tags or URLs
1893 // at the end of long notices.
1894 $content = mb_substr($content, 0, $maxlen - 4) . ' ...';
1897 // Scope is same as this one's
1899 return self::saveNew($repeater_id,
1902 array('repeat_of' => $this->id,
1903 'scope' => $this->scope));
1906 // These are supposed to be in chron order!
1908 function repeatStream($limit=100)
1910 $cache = Cache::instance();
1912 if (empty($cache)) {
1913 $ids = $this->_repeatStreamDirect($limit);
1915 $idstr = $cache->get(Cache::key('notice:repeats:'.$this->id));
1916 if ($idstr !== false) {
1917 if (empty($idstr)) {
1920 $ids = explode(',', $idstr);
1923 $ids = $this->_repeatStreamDirect(100);
1924 $cache->set(Cache::key('notice:repeats:'.$this->id), implode(',', $ids));
1927 // We do a max of 100, so slice down to limit
1928 $ids = array_slice($ids, 0, $limit);
1932 return NoticeStream::getStreamByIds($ids);
1935 function _repeatStreamDirect($limit)
1937 $notice = new Notice();
1939 $notice->selectAdd(); // clears it
1940 $notice->selectAdd('id');
1942 $notice->repeat_of = $this->id;
1944 $notice->orderBy('created, id'); // NB: asc!
1946 if (!is_null($limit)) {
1947 $notice->limit(0, $limit);
1950 return $notice->fetchAll('id');
1953 function locationOptions($lat, $lon, $location_id, $location_ns, $profile = null)
1957 if (!empty($location_id) && !empty($location_ns)) {
1958 $options['location_id'] = $location_id;
1959 $options['location_ns'] = $location_ns;
1961 $location = Location::fromId($location_id, $location_ns);
1963 if (!empty($location)) {
1964 $options['lat'] = $location->lat;
1965 $options['lon'] = $location->lon;
1968 } else if (!empty($lat) && !empty($lon)) {
1969 $options['lat'] = $lat;
1970 $options['lon'] = $lon;
1972 $location = Location::fromLatLon($lat, $lon);
1974 if (!empty($location)) {
1975 $options['location_id'] = $location->location_id;
1976 $options['location_ns'] = $location->location_ns;
1978 } else if (!empty($profile)) {
1979 if (isset($profile->lat) && isset($profile->lon)) {
1980 $options['lat'] = $profile->lat;
1981 $options['lon'] = $profile->lon;
1984 if (isset($profile->location_id) && isset($profile->location_ns)) {
1985 $options['location_id'] = $profile->location_id;
1986 $options['location_ns'] = $profile->location_ns;
1993 function clearReplies()
1995 $replyNotice = new Notice();
1996 $replyNotice->reply_to = $this->id;
1998 //Null any notices that are replies to this notice
2000 if ($replyNotice->find()) {
2001 while ($replyNotice->fetch()) {
2002 $orig = clone($replyNotice);
2003 $replyNotice->reply_to = null;
2004 $replyNotice->update($orig);
2010 $reply = new Reply();
2011 $reply->notice_id = $this->id;
2013 if ($reply->find()) {
2014 while($reply->fetch()) {
2015 self::blow('reply:stream:%d', $reply->profile_id);
2023 function clearFiles()
2025 $f2p = new File_to_post();
2027 $f2p->post_id = $this->id;
2030 while ($f2p->fetch()) {
2034 // FIXME: decide whether to delete File objects
2035 // ...and related (actual) files
2038 function clearRepeats()
2040 $repeatNotice = new Notice();
2041 $repeatNotice->repeat_of = $this->id;
2043 //Null any notices that are repeats of this notice
2045 if ($repeatNotice->find()) {
2046 while ($repeatNotice->fetch()) {
2047 $orig = clone($repeatNotice);
2048 $repeatNotice->repeat_of = null;
2049 $repeatNotice->update($orig);
2054 function clearFaves()
2057 $fave->notice_id = $this->id;
2059 if ($fave->find()) {
2060 while ($fave->fetch()) {
2061 self::blow('fave:ids_by_user_own:%d', $fave->user_id);
2062 self::blow('fave:ids_by_user_own:%d;last', $fave->user_id);
2063 self::blow('fave:ids_by_user:%d', $fave->user_id);
2064 self::blow('fave:ids_by_user:%d;last', $fave->user_id);
2072 function clearTags()
2074 $tag = new Notice_tag();
2075 $tag->notice_id = $this->id;
2078 while ($tag->fetch()) {
2079 self::blow('profile:notice_ids_tagged:%d:%s', $this->profile_id, Cache::keyize($tag->tag));
2080 self::blow('profile:notice_ids_tagged:%d:%s;last', $this->profile_id, Cache::keyize($tag->tag));
2081 self::blow('notice_tag:notice_ids:%s', Cache::keyize($tag->tag));
2082 self::blow('notice_tag:notice_ids:%s;last', Cache::keyize($tag->tag));
2090 function clearGroupInboxes()
2092 $gi = new Group_inbox();
2094 $gi->notice_id = $this->id;
2097 while ($gi->fetch()) {
2098 self::blow('user_group:notice_ids:%d', $gi->group_id);
2106 function distribute()
2108 // We always insert for the author so they don't
2110 Event::handle('StartNoticeDistribute', array($this));
2112 $user = User::getKV('id', $this->profile_id);
2113 if (!empty($user)) {
2114 Inbox::insertNotice($user->id, $this->id);
2117 if (common_config('queue', 'inboxes')) {
2118 // If there's a failure, we want to _force_
2119 // distribution at this point.
2121 $qm = QueueManager::get();
2122 $qm->enqueue($this, 'distrib');
2123 } catch (Exception $e) {
2124 // If the exception isn't transient, this
2125 // may throw more exceptions as DQH does
2126 // its own enqueueing. So, we ignore them!
2128 $handler = new DistribQueueHandler();
2129 $handler->handle($this);
2130 } catch (Exception $e) {
2131 common_log(LOG_ERR, "emergency redistribution resulted in " . $e->getMessage());
2133 // Re-throw so somebody smarter can handle it.
2137 $handler = new DistribQueueHandler();
2138 $handler->handle($this);
2144 $result = parent::insert();
2147 // Profile::hasRepeated() abuses pkeyGet(), so we
2148 // have to clear manually
2149 if (!empty($this->repeat_of)) {
2150 $c = self::memcache();
2152 $ck = self::multicacheKey('Notice',
2153 array('profile_id' => $this->profile_id,
2154 'repeat_of' => $this->repeat_of));
2164 * Get the source of the notice
2166 * @return Notice_source $ns A notice source object. 'code' is the only attribute
2167 * guaranteed to be populated.
2169 function getSource()
2171 $ns = new Notice_source();
2172 if (!empty($this->source)) {
2173 switch ($this->source) {
2180 $ns->code = $this->source;
2183 $ns = Notice_source::getKV($this->source);
2185 $ns = new Notice_source();
2186 $ns->code = $this->source;
2187 $app = Oauth_application::getKV('name', $this->source);
2189 $ns->name = $app->name;
2190 $ns->url = $app->source_url;
2200 * Determine whether the notice was locally created
2202 * @return boolean locality
2205 public function isLocal()
2207 return ($this->is_local == Notice::LOCAL_PUBLIC ||
2208 $this->is_local == Notice::LOCAL_NONPUBLIC);
2212 * Get the list of hash tags saved with this notice.
2214 * @return array of strings
2216 public function getTags()
2220 $keypart = sprintf('notice:tags:%d', $this->id);
2222 $tagstr = self::cacheGet($keypart);
2224 if ($tagstr !== false) {
2225 $tags = explode(',', $tagstr);
2227 $tag = new Notice_tag();
2228 $tag->notice_id = $this->id;
2230 while ($tag->fetch()) {
2231 $tags[] = $tag->tag;
2234 self::cacheSet($keypart, implode(',', $tags));
2240 static private function utcDate($dt)
2242 $dateStr = date('d F Y H:i:s', strtotime($dt));
2243 $d = new DateTime($dateStr, new DateTimeZone('UTC'));
2244 return $d->format(DATE_W3C);
2248 * Look up the creation timestamp for a given notice ID, even
2249 * if it's been deleted.
2252 * @return mixed string recorded creation timestamp, or false if can't be found
2254 public static function getAsTimestamp($id)
2260 $notice = Notice::getKV('id', $id);
2262 return $notice->created;
2265 $deleted = Deleted_notice::getKV('id', $id);
2267 return $deleted->created;
2274 * Build an SQL 'where' fragment for timestamp-based sorting from a since_id
2275 * parameter, matching notices posted after the given one (exclusive).
2277 * If the referenced notice can't be found, will return false.
2280 * @param string $idField
2281 * @param string $createdField
2282 * @return mixed string or false if no match
2284 public static function whereSinceId($id, $idField='id', $createdField='created')
2286 $since = Notice::getAsTimestamp($id);
2288 return sprintf("($createdField = '%s' and $idField > %d) or ($createdField > '%s')", $since, $id, $since);
2294 * Build an SQL 'where' fragment for timestamp-based sorting from a since_id
2295 * parameter, matching notices posted after the given one (exclusive), and
2296 * if necessary add it to the data object's query.
2298 * @param DB_DataObject $obj
2300 * @param string $idField
2301 * @param string $createdField
2302 * @return mixed string or false if no match
2304 public static function addWhereSinceId(DB_DataObject $obj, $id, $idField='id', $createdField='created')
2306 $since = self::whereSinceId($id, $idField, $createdField);
2308 $obj->whereAdd($since);
2313 * Build an SQL 'where' fragment for timestamp-based sorting from a max_id
2314 * parameter, matching notices posted before the given one (inclusive).
2316 * If the referenced notice can't be found, will return false.
2319 * @param string $idField
2320 * @param string $createdField
2321 * @return mixed string or false if no match
2323 public static function whereMaxId($id, $idField='id', $createdField='created')
2325 $max = Notice::getAsTimestamp($id);
2327 return sprintf("($createdField < '%s') or ($createdField = '%s' and $idField <= %d)", $max, $max, $id);
2333 * Build an SQL 'where' fragment for timestamp-based sorting from a max_id
2334 * parameter, matching notices posted before the given one (inclusive), and
2335 * if necessary add it to the data object's query.
2337 * @param DB_DataObject $obj
2339 * @param string $idField
2340 * @param string $createdField
2341 * @return mixed string or false if no match
2343 public static function addWhereMaxId(DB_DataObject $obj, $id, $idField='id', $createdField='created')
2345 $max = self::whereMaxId($id, $idField, $createdField);
2347 $obj->whereAdd($max);
2353 if (common_config('public', 'localonly')) {
2354 return ($this->is_local == Notice::LOCAL_PUBLIC);
2356 return (($this->is_local != Notice::LOCAL_NONPUBLIC) &&
2357 ($this->is_local != Notice::GATEWAY));
2362 * Check that the given profile is allowed to read, respond to, or otherwise
2363 * act on this notice.
2365 * The $scope member is a bitmask of scopes, representing a logical AND of the
2366 * scope requirement. So, 0x03 (Notice::ADDRESSEE_SCOPE | Notice::SITE_SCOPE) means
2367 * "only visible to people who are mentioned in the notice AND are users on this site."
2368 * Users on the site who are not mentioned in the notice will not be able to see the
2371 * @param Profile $profile The profile to check; pass null to check for public/unauthenticated users.
2373 * @return boolean whether the profile is in the notice's scope
2375 function inScope($profile)
2377 if (is_null($profile)) {
2378 $keypart = sprintf('notice:in-scope-for:%d:null', $this->id);
2380 $keypart = sprintf('notice:in-scope-for:%d:%d', $this->id, $profile->id);
2383 $result = self::cacheGet($keypart);
2385 if ($result === false) {
2387 if (Event::handle('StartNoticeInScope', array($this, $profile, &$bResult))) {
2388 $bResult = $this->_inScope($profile);
2389 Event::handle('EndNoticeInScope', array($this, $profile, &$bResult));
2391 $result = ($bResult) ? 1 : 0;
2392 self::cacheSet($keypart, $result, 0, 300);
2395 return ($result == 1) ? true : false;
2398 protected function _inScope($profile)
2400 if (!is_null($this->scope)) {
2401 $scope = $this->scope;
2403 $scope = self::defaultScope();
2406 // If there's no scope, anyone (even anon) is in scope.
2408 if ($scope == 0) { // Not private
2410 return !$this->isHiddenSpam($profile);
2412 } else { // Private, somehow
2414 // If there's scope, anon cannot be in scope
2416 if (empty($profile)) {
2420 // Author is always in scope
2422 if ($this->profile_id == $profile->id) {
2426 // Only for users on this site
2428 if ($scope & Notice::SITE_SCOPE) {
2429 $user = $profile->getUser();
2435 // Only for users mentioned in the notice
2437 if ($scope & Notice::ADDRESSEE_SCOPE) {
2439 $repl = Reply::pkeyGet(array('notice_id' => $this->id,
2440 'profile_id' => $profile->id));
2447 // Only for members of the given group
2449 if ($scope & Notice::GROUP_SCOPE) {
2451 // XXX: just query for the single membership
2453 $groups = $this->getGroups();
2457 foreach ($groups as $group) {
2458 if ($profile->isMember($group)) {
2469 // Only for followers of the author
2473 if ($scope & Notice::FOLLOWER_SCOPE) {
2476 $author = $this->getProfile();
2477 } catch (Exception $e) {
2481 if (!Subscription::exists($profile, $author)) {
2486 return !$this->isHiddenSpam($profile);
2490 function isHiddenSpam($profile) {
2492 // Hide posts by silenced users from everyone but moderators.
2494 if (common_config('notice', 'hidespam')) {
2497 $author = $this->getProfile();
2498 } catch(Exception $e) {
2499 // If we can't get an author, keep it hidden.
2500 // XXX: technically not spam, but, whatever.
2504 if ($author->hasRole(Profile_role::SILENCED)) {
2505 if (empty($profile) || (($profile->id !== $author->id) && (!$profile->hasRight(Right::REVIEWSPAM)))) {
2514 static function groupsFromText($text, $profile)
2518 /* extract all !group */
2519 $count = preg_match_all('/(?:^|\s)!(' . Nickname::DISPLAY_FMT . ')/',
2527 foreach (array_unique($match[1]) as $nickname) {
2528 $group = User_group::getForNickname($nickname, $profile);
2529 if (!empty($group) && $profile->isMember($group)) {
2530 $groups[] = $group->id;
2537 protected $_original = -1;
2539 function getOriginal()
2541 if (is_int($this->_original) && $this->_original == -1) {
2542 if (empty($this->reply_to)) {
2543 $this->_original = null;
2545 $this->_original = Notice::getKV('id', $this->reply_to);
2548 return $this->_original;
2552 * Magic function called at serialize() time.
2554 * We use this to drop a couple process-specific references
2555 * from DB_DataObject which can cause trouble in future
2558 * @return array of variable names to include in serialization.
2563 $vars = parent::__sleep();
2564 $skip = array('_original', '_profile', '_groups', '_attachments', '_faves', '_replies', '_repeats');
2565 return array_diff($vars, $skip);
2568 static function defaultScope()
2570 $scope = common_config('notice', 'defaultscope');
2571 if (is_null($scope)) {
2572 if (common_config('site', 'private')) {
2581 static function fillProfiles($notices)
2583 $map = self::getProfiles($notices);
2585 foreach ($notices as $notice) {
2586 if (array_key_exists($notice->profile_id, $map)) {
2587 $notice->_setProfile($map[$notice->profile_id]);
2591 return array_values($map);
2594 static function getProfiles(&$notices)
2597 foreach ($notices as $notice) {
2598 $ids[] = $notice->profile_id;
2601 $ids = array_unique($ids);
2603 return Profile::pivotGet('id', $ids);
2606 static function fillGroups(&$notices)
2608 $ids = self::_idsOf($notices);
2610 $gis = Group_inbox::listGet('notice_id', $ids);
2614 foreach ($gis as $id => $gi)
2618 $gids[] = $g->group_id;
2622 $gids = array_unique($gids);
2624 $group = User_group::pivotGet('id', $gids);
2626 foreach ($notices as $notice)
2629 $gi = $gis[$notice->id];
2630 foreach ($gi as $g) {
2631 $grps[] = $group[$g->group_id];
2633 $notice->_setGroups($grps);
2637 static function _idsOf(&$notices)
2640 foreach ($notices as $notice) {
2641 $ids[] = $notice->id;
2643 $ids = array_unique($ids);
2647 static function fillAttachments(&$notices)
2649 $ids = self::_idsOf($notices);
2651 $f2pMap = File_to_post::listGet('post_id', $ids);
2655 foreach ($f2pMap as $noticeId => $f2ps) {
2656 foreach ($f2ps as $f2p) {
2657 $fileIds[] = $f2p->file_id;
2661 $fileIds = array_unique($fileIds);
2663 $fileMap = File::pivotGet('id', $fileIds);
2665 foreach ($notices as $notice)
2668 $f2ps = $f2pMap[$notice->id];
2669 foreach ($f2ps as $f2p) {
2670 $files[] = $fileMap[$f2p->file_id];
2672 $notice->_setAttachments($files);
2679 * All faves of this notice
2681 * @return array Array of Fave objects
2686 if (isset($this->_faves) && is_array($this->_faves)) {
2687 return $this->_faves;
2689 $faveMap = Fave::listGet('notice_id', array($this->id));
2690 $this->_faves = $faveMap[$this->id];
2691 return $this->_faves;
2694 function _setFaves($faves)
2696 $this->_faves = $faves;
2699 static function fillFaves(&$notices)
2701 $ids = self::_idsOf($notices);
2702 $faveMap = Fave::listGet('notice_id', $ids);
2705 foreach ($faveMap as $id => $faves) {
2706 $cnt += count($faves);
2707 if (count($faves) > 0) {
2711 foreach ($notices as $notice) {
2712 $faves = $faveMap[$notice->id];
2713 $notice->_setFaves($faves);
2717 static function fillReplies(&$notices)
2719 $ids = self::_idsOf($notices);
2720 $replyMap = Reply::listGet('notice_id', $ids);
2721 foreach ($notices as $notice) {
2722 $replies = $replyMap[$notice->id];
2724 foreach ($replies as $reply) {
2725 $ids[] = $reply->profile_id;
2727 $notice->_setReplies($ids);
2731 protected $_repeats;
2733 function getRepeats()
2735 if (isset($this->_repeats) && is_array($this->_repeats)) {
2736 return $this->_repeats;
2738 $repeatMap = Notice::listGet('repeat_of', array($this->id));
2739 $this->_repeats = $repeatMap[$this->id];
2740 return $this->_repeats;
2743 function _setRepeats($repeats)
2745 $this->_repeats = $repeats;
2748 static function fillRepeats(&$notices)
2750 $ids = self::_idsOf($notices);
2751 $repeatMap = Notice::listGet('repeat_of', $ids);
2752 foreach ($notices as $notice) {
2753 $repeats = $repeatMap[$notice->id];
2754 $notice->_setRepeats($repeats);