3 * StatusNet - the distributed open-source microblogging tool
4 * Copyright (C) 2008-2011 StatusNet, Inc.
6 * This program is free software: you can redistribute it and/or modify
7 * it under the terms of the GNU Affero General Public License as published by
8 * the Free Software Foundation, either version 3 of the License, or
9 * (at your option) any later version.
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU Affero General Public License for more details.
16 * You should have received a copy of the GNU Affero General Public License
17 * along with this program. If not, see <http://www.gnu.org/licenses/>.
21 * @author Brenda Wallace <shiny@cpan.org>
22 * @author Christopher Vollick <psycotica0@gmail.com>
23 * @author CiaranG <ciaran@ciarang.com>
24 * @author Craig Andrews <candrews@integralblue.com>
25 * @author Evan Prodromou <evan@controlezvous.ca>
26 * @author Gina Haeussge <osd@foosel.net>
27 * @author Jeffery To <jeffery.to@gmail.com>
28 * @author Mike Cochrane <mikec@mikenz.geek.nz>
29 * @author Robin Millette <millette@controlyourself.ca>
30 * @author Sarven Capadisli <csarven@controlyourself.ca>
31 * @author Tom Adams <tom@holizz.com>
32 * @copyright 2009 Free Software Foundation, Inc http://www.fsf.org
33 * @license GNU Affero General Public License http://www.gnu.org/licenses/
36 if (!defined('STATUSNET') && !defined('LACONICA')) {
41 * Table Definition for notice
43 require_once INSTALLDIR.'/classes/Memcached_DataObject.php';
45 /* We keep 200 notices, the max number of notices available per API request,
46 * in the memcached cache. */
48 define('NOTICE_CACHE_WINDOW', CachingNoticeStream::CACHE_WINDOW);
50 define('MAX_BOXCARS', 128);
52 class Notice extends Managed_DataObject
55 /* the code below is auto generated do not remove the above tag */
57 public $__table = 'notice'; // table name
58 public $id; // int(4) primary_key not_null
59 public $profile_id; // int(4) multiple_key not_null
60 public $uri; // varchar(255) unique_key
61 public $content; // text
62 public $rendered; // text
63 public $url; // varchar(255)
64 public $created; // datetime multiple_key not_null default_0000-00-00%2000%3A00%3A00
65 public $modified; // timestamp not_null default_CURRENT_TIMESTAMP
66 public $reply_to; // int(4)
67 public $is_local; // int(4)
68 public $source; // varchar(32)
69 public $conversation; // int(4)
70 public $lat; // decimal(10,7)
71 public $lon; // decimal(10,7)
72 public $location_id; // int(4)
73 public $location_ns; // int(4)
74 public $repeat_of; // int(4)
75 public $verb; // varchar(255)
76 public $object_type; // varchar(255)
77 public $scope; // int(4)
79 /* the code above is auto generated do not remove the tag below */
82 public static function schemaDef()
86 'id' => array('type' => 'serial', 'not null' => true, 'description' => 'unique identifier'),
87 'profile_id' => array('type' => 'int', 'not null' => true, 'description' => 'who made the update'),
88 'uri' => array('type' => 'varchar', 'length' => 255, 'description' => 'universally unique identifier, usually a tag URI'),
89 'content' => array('type' => 'text', 'description' => 'update content', 'collate' => 'utf8_general_ci'),
90 'rendered' => array('type' => 'text', 'description' => 'HTML version of the content'),
91 'url' => array('type' => 'varchar', 'length' => 255, 'description' => 'URL of any attachment (image, video, bookmark, whatever)'),
92 'created' => array('type' => 'datetime', 'not null' => true, 'description' => 'date this record was created'),
93 'modified' => array('type' => 'timestamp', 'not null' => true, 'description' => 'date this record was modified'),
94 'reply_to' => array('type' => 'int', 'description' => 'notice replied to (usually a guess)'),
95 'is_local' => array('type' => 'int', 'size' => 'tiny', 'default' => 0, 'description' => 'notice was generated by a user'),
96 'source' => array('type' => 'varchar', 'length' => 32, 'description' => 'source of comment, like "web", "im", or "clientname"'),
97 'conversation' => array('type' => 'int', 'description' => 'id of root notice in this conversation'),
98 'lat' => array('type' => 'numeric', 'precision' => 10, 'scale' => 7, 'description' => 'latitude'),
99 'lon' => array('type' => 'numeric', 'precision' => 10, 'scale' => 7, 'description' => 'longitude'),
100 'location_id' => array('type' => 'int', 'description' => 'location id if possible'),
101 'location_ns' => array('type' => 'int', 'description' => 'namespace for location'),
102 'repeat_of' => array('type' => 'int', 'description' => 'notice this is a repeat of'),
103 'object_type' => array('type' => 'varchar', 'length' => 255, 'description' => 'URI representing activity streams object type', 'default' => 'http://activitystrea.ms/schema/1.0/note'),
104 'verb' => array('type' => 'varchar', 'length' => 255, 'description' => 'URI representing activity streams verb', 'default' => 'http://activitystrea.ms/schema/1.0/post'),
105 'scope' => array('type' => 'int',
106 'description' => 'bit map for distribution scope; 0 = everywhere; 1 = this server only; 2 = addressees; 4 = followers; null = default'),
108 'primary key' => array('id'),
109 'unique keys' => array(
110 'notice_uri_key' => array('uri'),
112 'foreign keys' => array(
113 'notice_profile_id_fkey' => array('profile', array('profile_id' => 'id')),
114 'notice_reply_to_fkey' => array('notice', array('reply_to' => 'id')),
115 'notice_conversation_fkey' => array('conversation', array('conversation' => 'id')), # note... used to refer to notice.id
116 'notice_repeat_of_fkey' => array('notice', array('repeat_of' => 'id')), # @fixme: what about repeats of deleted notices?
119 'notice_created_id_is_local_idx' => array('created', 'id', 'is_local'),
120 'notice_profile_id_idx' => array('profile_id', 'created', 'id'),
121 'notice_repeat_of_created_id_idx' => array('repeat_of', 'created', 'id'),
122 'notice_conversation_created_id_idx' => array('conversation', 'created', 'id'),
123 'notice_replyto_idx' => array('reply_to')
127 if (common_config('search', 'type') == 'fulltext') {
128 $def['fulltext indexes'] = array('content' => array('content'));
135 const LOCAL_PUBLIC = 1;
137 const LOCAL_NONPUBLIC = -1;
140 const PUBLIC_SCOPE = 0; // Useful fake constant
141 const SITE_SCOPE = 1;
142 const ADDRESSEE_SCOPE = 2;
143 const GROUP_SCOPE = 4;
144 const FOLLOWER_SCOPE = 8;
146 protected $_profile = -1;
148 function getProfile()
150 if (is_int($this->_profile) && $this->_profile == -1) {
151 $this->_setProfile(Profile::getKV('id', $this->profile_id));
153 if (empty($this->_profile)) {
154 // TRANS: Server exception thrown when a user profile for a notice cannot be found.
155 // TRANS: %1$d is a profile ID (number), %2$d is a notice ID (number).
156 throw new ServerException(sprintf(_('No such profile (%1$d) for notice (%2$d).'), $this->profile_id, $this->id));
160 return $this->_profile;
163 function _setProfile($profile)
165 $this->_profile = $profile;
170 // For auditing purposes, save a record that the notice
173 // @fixme we have some cases where things get re-run and so the
175 $deleted = Deleted_notice::getKV('id', $this->id);
178 $deleted = Deleted_notice::getKV('uri', $this->uri);
182 $deleted = new Deleted_notice();
184 $deleted->id = $this->id;
185 $deleted->profile_id = $this->profile_id;
186 $deleted->uri = $this->uri;
187 $deleted->created = $this->created;
188 $deleted->deleted = common_sql_now();
193 if (Event::handle('NoticeDeleteRelated', array($this))) {
195 // Clear related records
197 $this->clearReplies();
198 $this->clearRepeats();
201 $this->clearGroupInboxes();
204 // NOTE: we don't clear inboxes
205 // NOTE: we don't clear queue items
208 $result = parent::delete();
210 $this->blowOnDelete();
214 public function getUri()
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 (!($repeat instanceof Notice)) {
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)) {
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
531 $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;
538 } catch (NoSuchUserException $e) {
539 // Cannot handle private streams for remote profiles
542 // Force the scope for private groups
544 foreach ($groups as $groupId) {
545 $group = User_group::getKV('id', $groupId);
546 if (!empty($group)) {
547 if ($group->force_scope) {
548 $notice->scope |= Notice::GROUP_SCOPE;
554 if (Event::handle('StartNoticeSave', array(&$notice))) {
556 // XXX: some of these functions write to the DB
558 $id = $notice->insert();
561 common_log_db_error($notice, 'INSERT', __FILE__);
562 // TRANS: Server exception thrown when a notice cannot be saved.
563 throw new ServerException(_('Problem saving notice.'));
566 // Update ID-dependent columns: URI, conversation
568 $orig = clone($notice);
573 $notice->uri = common_notice_uri($notice);
577 // If it's not part of a conversation, it's
578 // the beginning of a new conversation.
580 if (empty($notice->conversation)) {
581 $conv = Conversation::create();
582 $notice->conversation = $conv->id;
587 if (!$notice->update($orig)) {
588 common_log_db_error($notice, 'UPDATE', __FILE__);
589 // TRANS: Server exception thrown when a notice cannot be updated.
590 throw new ServerException(_('Problem saving notice.'));
596 // Clear the cache for subscribed users, so they'll update at next request
597 // XXX: someone clever could prepend instead of clearing the cache
599 $notice->blowOnInsert();
601 // Save per-notice metadata...
603 if (isset($replies)) {
604 $notice->saveKnownReplies($replies);
606 $notice->saveReplies();
610 $notice->saveKnownTags($tags);
615 // Note: groups may save tags, so must be run after tags are saved
616 // to avoid errors on duplicates.
617 // Note: groups should always be set.
619 $notice->saveKnownGroups($groups);
622 $notice->saveKnownUrls($urls);
628 // Prepare inbox delivery, may be queued to background.
629 $notice->distribute();
635 function blowOnInsert($conversation = false)
637 $this->blowStream('profile:notice_ids:%d', $this->profile_id);
639 if ($this->isPublic()) {
640 $this->blowStream('public');
643 self::blow('notice:list-ids:conversation:%s', $this->conversation);
644 self::blow('conversation:notice_count:%d', $this->conversation);
646 if (!empty($this->repeat_of)) {
647 // XXX: we should probably only use one of these
648 $this->blowStream('notice:repeats:%d', $this->repeat_of);
649 self::blow('notice:list-ids:repeat_of:%d', $this->repeat_of);
652 $original = Notice::getKV('id', $this->repeat_of);
654 if (!empty($original)) {
655 $originalUser = User::getKV('id', $original->profile_id);
656 if (!empty($originalUser)) {
657 $this->blowStream('user:repeats_of_me:%d', $originalUser->id);
661 $profile = Profile::getKV($this->profile_id);
663 if (!empty($profile)) {
664 $profile->blowNoticeCount();
667 $ptags = $this->getProfileTags();
668 foreach ($ptags as $ptag) {
669 $ptag->blowNoticeStreamCache();
674 * Clear cache entries related to this notice at delete time.
675 * Necessary to avoid breaking paging on public, profile timelines.
677 function blowOnDelete()
679 $this->blowOnInsert();
681 self::blow('profile:notice_ids:%d;last', $this->profile_id);
683 if ($this->isPublic()) {
684 self::blow('public;last');
687 self::blow('fave:by_notice', $this->id);
689 if ($this->conversation) {
690 // In case we're the first, will need to calc a new root.
691 self::blow('notice:conversation_root:%d', $this->conversation);
694 $ptags = $this->getProfileTags();
695 foreach ($ptags as $ptag) {
696 $ptag->blowNoticeStreamCache(true);
700 function blowStream()
702 $c = self::memcache();
708 $args = func_get_args();
710 $format = array_shift($args);
712 $keyPart = vsprintf($format, $args);
714 $cacheKey = Cache::key($keyPart);
716 $c->delete($cacheKey);
718 // delete the "last" stream, too, if this notice is
719 // older than the top of that stream
721 $lastKey = $cacheKey.';last';
723 $lastStr = $c->get($lastKey);
725 if ($lastStr !== false) {
726 $window = explode(',', $lastStr);
727 $lastID = $window[0];
728 $lastNotice = Notice::getKV('id', $lastID);
729 if (empty($lastNotice) // just weird
730 || strtotime($lastNotice->created) >= strtotime($this->created)) {
731 $c->delete($lastKey);
736 /** save all urls in the notice to the db
738 * follow redirects and save all available file information
739 * (mimetype, date, size, oembed, etc.)
743 function saveUrls() {
744 if (common_config('attachments', 'process_links')) {
745 common_replace_urls_callback($this->content, array($this, 'saveUrl'), $this->id);
750 * Save the given URLs as related links/attachments to the db
752 * follow redirects and save all available file information
753 * (mimetype, date, size, oembed, etc.)
757 function saveKnownUrls($urls)
759 if (common_config('attachments', 'process_links')) {
760 // @fixme validation?
761 foreach (array_unique($urls) as $url) {
762 File::processNew($url, $this->id);
770 function saveUrl($url, $notice_id) {
771 File::processNew($url, $notice_id);
774 static function checkDupes($profile_id, $content) {
775 $profile = Profile::getKV($profile_id);
776 if (empty($profile)) {
779 $notice = $profile->getNotices(0, CachingNoticeStream::CACHE_WINDOW);
780 if (!empty($notice)) {
782 while ($notice->fetch()) {
783 if (time() - strtotime($notice->created) >= common_config('site', 'dupelimit')) {
785 } else if ($notice->content == $content) {
790 // If we get here, oldest item in cache window is not
791 // old enough for dupe limit; do direct check against DB
792 $notice = new Notice();
793 $notice->profile_id = $profile_id;
794 $notice->content = $content;
795 $threshold = common_sql_date(time() - common_config('site', 'dupelimit'));
796 $notice->whereAdd(sprintf("created > '%s'", $notice->escape($threshold)));
798 $cnt = $notice->count();
802 static function checkEditThrottle($profile_id) {
803 $profile = Profile::getKV($profile_id);
804 if (empty($profile)) {
807 // Get the Nth notice
808 $notice = $profile->getNotices(common_config('throttle', 'count') - 1, 1);
809 if ($notice && $notice->fetch()) {
810 // If the Nth notice was posted less than timespan seconds ago
811 if (time() - strtotime($notice->created) <= common_config('throttle', 'timespan')) {
816 // Either not N notices in the stream, OR the Nth was not posted within timespan seconds
820 protected $_attachments = -1;
822 function attachments() {
824 if ($this->_attachments != -1) {
825 return $this->_attachments;
828 $f2ps = File_to_post::listGet('post_id', array($this->id));
832 foreach ($f2ps[$this->id] as $f2p) {
833 $ids[] = $f2p->file_id;
836 $files = File::multiGet('id', $ids);
838 $this->_attachments = $files->fetchAll();
840 return $this->_attachments;
843 function _setAttachments($attachments)
845 $this->_attachments = $attachments;
848 function publicStream($offset=0, $limit=20, $since_id=0, $max_id=0)
850 $stream = new PublicNoticeStream();
851 return $stream->getNotices($offset, $limit, $since_id, $max_id);
855 function conversationStream($id, $offset=0, $limit=20, $since_id=0, $max_id=0)
857 $stream = new ConversationNoticeStream($id);
859 return $stream->getNotices($offset, $limit, $since_id, $max_id);
863 * Is this notice part of an active conversation?
865 * @return boolean true if other messages exist in the same
866 * conversation, false if this is the only one
868 function hasConversation()
870 if (!empty($this->conversation)) {
871 $conversation = Notice::conversationStream(
877 if ($conversation->N > 0) {
885 * Grab the earliest notice from this conversation.
887 * @return Notice or null
889 function conversationRoot($profile=-1)
891 // XXX: can this happen?
893 if (empty($this->conversation)) {
897 // Get the current profile if not specified
899 if (is_int($profile) && $profile == -1) {
900 $profile = Profile::current();
903 // If this notice is out of scope, no root for you!
905 if (!$this->inScope($profile)) {
909 // If this isn't a reply to anything, then it's its own
912 if (empty($this->reply_to)) {
916 if (is_null($profile)) {
917 $keypart = sprintf('notice:conversation_root:%d:null', $this->id);
919 $keypart = sprintf('notice:conversation_root:%d:%d',
924 $root = self::cacheGet($keypart);
926 if ($root !== false && $root->inScope($profile)) {
933 $parent = $last->getParent();
934 if ($parent->inScope($profile)) {
938 } catch (Exception $e) {
939 // Latest notice has no parent
941 // No parent, or parent out of scope
946 self::cacheSet($keypart, $root);
952 * Pull up a full list of local recipients who will be getting
953 * this notice in their inbox. Results will be cached, so don't
954 * change the input data wily-nilly!
956 * @param array $groups optional list of Group objects;
957 * if left empty, will be loaded from group_inbox records
958 * @param array $recipient optional list of reply profile ids
959 * if left empty, will be loaded from reply records
960 * @return array associating recipient user IDs with an inbox source constant
962 function whoGets(array $groups=null, array $recipients=null)
964 $c = self::memcache();
967 $ni = $c->get(Cache::key('notice:who_gets:'.$this->id));
973 if (is_null($groups)) {
974 $groups = $this->getGroups();
977 if (is_null($recipients)) {
978 $recipients = $this->getReplies();
981 $users = $this->getSubscribedUsers();
982 $ptags = $this->getProfileTags();
984 // FIXME: kind of ignoring 'transitional'...
985 // we'll probably stop supporting inboxless mode
990 // Give plugins a chance to add folks in at start...
991 if (Event::handle('StartNoticeWhoGets', array($this, &$ni))) {
993 foreach ($users as $id) {
994 $ni[$id] = NOTICE_INBOX_SOURCE_SUB;
997 foreach ($groups as $group) {
998 $users = $group->getUserMembers();
999 foreach ($users as $id) {
1000 if (!array_key_exists($id, $ni)) {
1001 $ni[$id] = NOTICE_INBOX_SOURCE_GROUP;
1006 foreach ($ptags as $ptag) {
1007 $users = $ptag->getUserSubscribers();
1008 foreach ($users as $id) {
1009 if (!array_key_exists($id, $ni)) {
1010 $ni[$id] = NOTICE_INBOX_SOURCE_PROFILE_TAG;
1015 foreach ($recipients as $recipient) {
1016 if (!array_key_exists($recipient, $ni)) {
1017 $ni[$recipient] = NOTICE_INBOX_SOURCE_REPLY;
1021 // Exclude any deleted, non-local, or blocking recipients.
1022 $profile = $this->getProfile();
1023 $originalProfile = null;
1024 if ($this->repeat_of) {
1025 // Check blocks against the original notice's poster as well.
1026 $original = Notice::getKV('id', $this->repeat_of);
1028 $originalProfile = $original->getProfile();
1032 foreach ($ni as $id => $source) {
1034 $user = User::getKV('id', $id);
1036 $user->hasBlocked($profile) ||
1037 ($originalProfile && $user->hasBlocked($originalProfile))) {
1040 } catch (UserNoProfileException $e) {
1041 // User doesn't have a profile; invalid; skip them.
1046 // Give plugins a chance to filter out...
1047 Event::handle('EndNoticeWhoGets', array($this, &$ni));
1051 // XXX: pack this data better
1052 $c->set(Cache::key('notice:who_gets:'.$this->id), $ni);
1059 * Adds this notice to the inboxes of each local user who should receive
1060 * it, based on author subscriptions, group memberships, and @-replies.
1062 * Warning: running a second time currently will make items appear
1063 * multiple times in users' inboxes.
1065 * @fixme make more robust against errors
1066 * @fixme break up massive deliveries to smaller background tasks
1068 * @param array $groups optional list of Group objects;
1069 * if left empty, will be loaded from group_inbox records
1070 * @param array $recipient optional list of reply profile ids
1071 * if left empty, will be loaded from reply records
1073 function addToInboxes(array $groups=null, array $recipients=null)
1075 $ni = $this->whoGets($groups, $recipients);
1077 $ids = array_keys($ni);
1079 // We remove the author (if they're a local user),
1080 // since we'll have already done this in distribute()
1082 $i = array_search($this->profile_id, $ids);
1090 Inbox::bulkInsert($this->id, $ids);
1095 function getSubscribedUsers()
1099 if(common_config('db','quote_identifiers'))
1100 $user_table = '"user"';
1101 else $user_table = 'user';
1105 'FROM '. $user_table .' JOIN subscription '.
1106 'ON '. $user_table .'.id = subscription.subscriber ' .
1107 'WHERE subscription.subscribed = %d ';
1109 $user->query(sprintf($qry, $this->profile_id));
1113 while ($user->fetch()) {
1122 function getProfileTags()
1124 $profile = $this->getProfile();
1125 $list = $profile->getOtherTags($profile);
1128 while($list->fetch()) {
1129 $ptags[] = clone($list);
1136 * Record this notice to the given group inboxes for delivery.
1137 * Overrides the regular parsing of !group markup.
1139 * @param string $group_ids
1140 * @fixme might prefer URIs as identifiers, as for replies?
1141 * best with generalizations on user_group to support
1142 * remote groups better.
1144 function saveKnownGroups($group_ids)
1146 if (!is_array($group_ids)) {
1147 // TRANS: Server exception thrown when no array is provided to the method saveKnownGroups().
1148 throw new ServerException(_('Bad type provided to saveKnownGroups.'));
1152 foreach (array_unique($group_ids) as $id) {
1153 $group = User_group::getKV('id', $id);
1155 common_log(LOG_ERR, "Local delivery to group id $id, $group->nickname");
1156 $result = $this->addToGroupInbox($group);
1158 common_log_db_error($gi, 'INSERT', __FILE__);
1161 if (common_config('group', 'addtag')) {
1162 // we automatically add a tag for every group name, too
1164 $tag = Notice_tag::pkeyGet(array('tag' => common_canonical_tag($group->nickname),
1165 'notice_id' => $this->id));
1167 if (is_null($tag)) {
1168 $this->saveTag($group->nickname);
1172 $groups[] = clone($group);
1174 common_log(LOG_ERR, "Local delivery to group id $id skipped, doesn't exist");
1182 * Parse !group delivery and record targets into group_inbox.
1183 * @return array of Group objects
1185 function saveGroups()
1187 // Don't save groups for repeats
1189 if (!empty($this->repeat_of)) {
1193 $profile = $this->getProfile();
1195 $groups = self::groupsFromText($this->content, $profile);
1197 /* Add them to the database */
1199 foreach ($groups as $group) {
1200 /* XXX: remote groups. */
1202 if (empty($group)) {
1207 if ($profile->isMember($group)) {
1209 $result = $this->addToGroupInbox($group);
1212 common_log_db_error($gi, 'INSERT', __FILE__);
1215 $groups[] = clone($group);
1222 function addToGroupInbox($group)
1224 $gi = Group_inbox::pkeyGet(array('group_id' => $group->id,
1225 'notice_id' => $this->id));
1229 $gi = new Group_inbox();
1231 $gi->group_id = $group->id;
1232 $gi->notice_id = $this->id;
1233 $gi->created = $this->created;
1235 $result = $gi->insert();
1238 common_log_db_error($gi, 'INSERT', __FILE__);
1239 // TRANS: Server exception thrown when an update for a group inbox fails.
1240 throw new ServerException(_('Problem saving group inbox.'));
1243 self::blow('user_group:notice_ids:%d', $gi->group_id);
1250 * Save reply records indicating that this notice needs to be
1251 * delivered to the local users with the given URIs.
1253 * Since this is expected to be used when saving foreign-sourced
1254 * messages, we won't deliver to any remote targets as that's the
1255 * source service's responsibility.
1257 * Mail notifications etc will be handled later.
1259 * @param array $uris Array of unique identifier URIs for recipients
1261 function saveKnownReplies(array $uris)
1267 $sender = Profile::getKV($this->profile_id);
1269 foreach (array_unique($uris) as $uri) {
1271 $profile = Profile::fromURI($uri);
1273 if (empty($profile)) {
1274 common_log(LOG_WARNING, "Unable to determine profile for URI '$uri'");
1278 if ($profile->hasBlocked($sender)) {
1279 common_log(LOG_INFO, "Not saving reply to profile {$profile->id} ($uri) from sender {$sender->id} because of a block.");
1283 $this->saveReply($profile->id);
1284 self::blow('reply:stream:%d', $profile->id);
1291 * Pull @-replies from this message's content in StatusNet markup format
1292 * and save reply records indicating that this message needs to be
1293 * delivered to those users.
1295 * Mail notifications to local profiles will be sent later.
1297 * @return array of integer profile IDs
1300 function saveReplies()
1302 // Don't save reply data for repeats
1304 if (!empty($this->repeat_of)) {
1308 $sender = Profile::getKV($this->profile_id);
1312 // If it's a reply, save for the replied-to author
1314 $author = $this->getParent()->getProfile();
1315 if ($author instanceof Profile) {
1316 $this->saveReply($author->id);
1317 $replied[$author->id] = 1;
1318 self::blow('reply:stream:%d', $author->id);
1320 } catch (Exception $e) {
1321 // Not a reply, since it has no parent!
1324 // @todo ideally this parser information would only
1325 // be calculated once.
1327 $mentions = common_find_mentions($this->content, $this);
1329 // store replied only for first @ (what user/notice what the reply directed,
1330 // we assume first @ is it)
1332 foreach ($mentions as $mention) {
1334 foreach ($mention['mentioned'] as $mentioned) {
1336 // skip if they're already covered
1338 if (!empty($replied[$mentioned->id])) {
1342 // Don't save replies from blocked profile to local user
1344 $mentioned_user = User::getKV('id', $mentioned->id);
1345 if (!empty($mentioned_user) && $mentioned_user->hasBlocked($sender)) {
1349 $this->saveReply($mentioned->id);
1350 $replied[$mentioned->id] = 1;
1351 self::blow('reply:stream:%d', $mentioned->id);
1355 $recipientIds = array_keys($replied);
1357 return $recipientIds;
1360 function saveReply($profileId)
1362 $reply = new Reply();
1364 $reply->notice_id = $this->id;
1365 $reply->profile_id = $profileId;
1366 $reply->modified = $this->created;
1373 protected $_replies = -1;
1376 * Pull the complete list of @-reply targets for this notice.
1378 * @return array of integer profile ids
1380 function getReplies()
1382 if ($this->_replies != -1) {
1383 return $this->_replies;
1386 $replyMap = Reply::listGet('notice_id', array($this->id));
1390 foreach ($replyMap[$this->id] as $reply) {
1391 $ids[] = $reply->profile_id;
1394 $this->_replies = $ids;
1399 function _setReplies($replies)
1401 $this->_replies = $replies;
1405 * Pull the complete list of @-reply targets for this notice.
1407 * @return array of Profiles
1409 function getReplyProfiles()
1411 $ids = $this->getReplies();
1413 $profiles = Profile::multiGet('id', $ids);
1415 return $profiles->fetchAll();
1419 * Send e-mail notifications to local @-reply targets.
1421 * Replies must already have been saved; this is expected to be run
1422 * from the distrib queue handler.
1424 function sendReplyNotifications()
1426 // Don't send reply notifications for repeats
1428 if (!empty($this->repeat_of)) {
1432 $recipientIds = $this->getReplies();
1434 foreach ($recipientIds as $recipientId) {
1435 $user = User::getKV('id', $recipientId);
1436 if (!empty($user)) {
1437 mail_notify_attn($user, $this);
1443 * Pull list of groups this notice needs to be delivered to,
1444 * as previously recorded by saveGroups() or saveKnownGroups().
1446 * @return array of Group objects
1449 protected $_groups = -1;
1451 function getGroups()
1453 // Don't save groups for repeats
1455 if (!empty($this->repeat_of)) {
1459 if ($this->_groups != -1)
1461 return $this->_groups;
1464 $gis = Group_inbox::listGet('notice_id', array($this->id));
1468 foreach ($gis[$this->id] as $gi)
1470 $ids[] = $gi->group_id;
1473 $groups = User_group::multiGet('id', $ids);
1475 $this->_groups = $groups->fetchAll();
1477 return $this->_groups;
1480 function _setGroups($groups)
1482 $this->_groups = $groups;
1486 * Convert a notice into an activity for export.
1488 * @param User $cur Current user
1490 * @return Activity activity object representing this Notice.
1493 function asActivity($cur=null)
1495 $act = self::cacheGet(Cache::codeKey('notice:as-activity:'.$this->id));
1500 $act = new Activity();
1502 if (Event::handle('StartNoticeAsActivity', array($this, &$act))) {
1504 $act->id = TagURI::mint("post:".$this->id);
1505 $act->time = strtotime($this->created);
1506 $act->content = common_xml_safe_str($this->rendered);
1508 $profile = $this->getProfile();
1510 $act->actor = ActivityObject::fromProfile($profile);
1511 $act->actor->extra[] = $profile->profileInfo($cur);
1513 $act->verb = $this->verb;
1515 if ($this->repeat_of) {
1516 $repeated = Notice::getKV('id', $this->repeat_of);
1517 if (!empty($repeated)) {
1518 $act->objects[] = $repeated->asActivity($cur);
1521 $act->objects[] = ActivityObject::fromNotice($this);
1524 // XXX: should this be handled by default processing for object entry?
1528 $tags = $this->getTags();
1530 foreach ($tags as $tag) {
1531 $cat = new AtomCategory();
1534 $act->categories[] = $cat;
1538 // XXX: use Atom Media and/or File activity objects instead
1540 $attachments = $this->attachments();
1542 foreach ($attachments as $attachment) {
1543 // Save local attachments
1544 if (!empty($attachment->filename)) {
1545 $act->attachments[] = ActivityObject::fromFile($attachment);
1549 $ctx = new ActivityContext();
1551 if (!empty($this->reply_to)) {
1552 $reply = Notice::getKV('id', $this->reply_to);
1553 if (!empty($reply)) {
1554 $ctx->replyToID = $reply->uri;
1555 $ctx->replyToUrl = $reply->bestUrl();
1559 $ctx->location = $this->getLocation();
1563 if (!empty($this->conversation)) {
1564 $conv = Conversation::getKV('id', $this->conversation);
1565 if (!empty($conv)) {
1566 $ctx->conversation = $conv->uri;
1570 $reply_ids = $this->getReplies();
1572 foreach ($reply_ids as $id) {
1573 $rprofile = Profile::getKV('id', $id);
1574 if (!empty($rprofile)) {
1575 $ctx->attention[] = $rprofile->getUri();
1576 $ctx->attentionType[$rprofile->getUri()] = ActivityObject::PERSON;
1580 $groups = $this->getGroups();
1582 foreach ($groups as $group) {
1583 $ctx->attention[] = $group->getUri();
1584 $ctx->attentionType[$group->getUri()] = ActivityObject::GROUP;
1587 switch ($this->scope) {
1588 case Notice::PUBLIC_SCOPE:
1589 $ctx->attention[] = "http://activityschema.org/collection/public";
1590 $ctx->attentionType["http://activityschema.org/collection/public"] = ActivityObject::COLLECTION;
1592 case Notice::FOLLOWER_SCOPE:
1593 $surl = common_local_url("subscribers", array('nickname' => $profile->nickname));
1594 $ctx->attention[] = $surl;
1595 $ctx->attentionType[$surl] = ActivityObject::COLLECTION;
1599 // XXX: deprecated; use ActivityVerb::SHARE instead
1603 if (!empty($this->repeat_of)) {
1604 $repeat = Notice::getKV('id', $this->repeat_of);
1605 if (!empty($repeat)) {
1606 $ctx->forwardID = $repeat->uri;
1607 $ctx->forwardUrl = $repeat->bestUrl();
1611 $act->context = $ctx;
1613 $source = $this->getSource();
1616 $act->generator = ActivityObject::fromNoticeSource($source);
1621 $atom_feed = $profile->getAtomFeed();
1623 if (!empty($atom_feed)) {
1625 $act->source = new ActivitySource();
1627 // XXX: we should store the actual feed ID
1629 $act->source->id = $atom_feed;
1631 // XXX: we should store the actual feed title
1633 $act->source->title = $profile->getBestName();
1635 $act->source->links['alternate'] = $profile->profileurl;
1636 $act->source->links['self'] = $atom_feed;
1638 $act->source->icon = $profile->avatarUrl(AVATAR_PROFILE_SIZE);
1640 $notice = $profile->getCurrentNotice();
1642 if (!empty($notice)) {
1643 $act->source->updated = self::utcDate($notice->created);
1646 $user = User::getKV('id', $profile->id);
1648 if (!empty($user)) {
1649 $act->source->links['license'] = common_config('license', 'url');
1653 if ($this->isLocal()) {
1654 $act->selfLink = common_local_url('ApiStatusesShow', array('id' => $this->id,
1655 'format' => 'atom'));
1656 $act->editLink = $act->selfLink;
1659 Event::handle('EndNoticeAsActivity', array($this, &$act));
1662 self::cacheSet(Cache::codeKey('notice:as-activity:'.$this->id), $act);
1667 // This has gotten way too long. Needs to be sliced up into functional bits
1668 // or ideally exported to a utility class.
1670 function asAtomEntry($namespace=false,
1675 $act = $this->asActivity($cur);
1676 $act->extra[] = $this->noticeInfo($cur);
1677 return $act->asString($namespace, $author, $source);
1681 * Extra notice info for atom entries
1683 * Clients use some extra notice info in the atom stream.
1684 * This gives it to them.
1686 * @param User $cur Current user
1688 * @return array representation of <statusnet:notice_info> element
1691 function noticeInfo($cur)
1693 // local notice ID (useful to clients for ordering)
1695 $noticeInfoAttr = array('local_id' => $this->id);
1699 $ns = $this->getSource();
1702 $noticeInfoAttr['source'] = $ns->code;
1703 if (!empty($ns->url)) {
1704 $noticeInfoAttr['source_link'] = $ns->url;
1705 if (!empty($ns->name)) {
1706 $noticeInfoAttr['source'] = '<a href="'
1707 . htmlspecialchars($ns->url)
1708 . '" rel="nofollow">'
1709 . htmlspecialchars($ns->name)
1715 // favorite and repeated
1718 $cp = $cur->getProfile();
1719 $noticeInfoAttr['favorite'] = ($cp->hasFave($this)) ? "true" : "false";
1720 $noticeInfoAttr['repeated'] = ($cp->hasRepeated($this)) ? "true" : "false";
1723 if (!empty($this->repeat_of)) {
1724 $noticeInfoAttr['repeat_of'] = $this->repeat_of;
1727 return array('statusnet:notice_info', $noticeInfoAttr, null);
1731 * Returns an XML string fragment with a reference to a notice as an
1732 * Activity Streams noun object with the given element type.
1734 * Assumes that 'activity' namespace has been previously defined.
1736 * @param string $element one of 'subject', 'object', 'target'
1740 function asActivityNoun($element)
1742 $noun = ActivityObject::fromNotice($this);
1743 return $noun->asString('activity:' . $element);
1748 if (!empty($this->url)) {
1750 } else if (!empty($this->uri) && preg_match('/^https?:/', $this->uri)) {
1753 return common_local_url('shownotice',
1754 array('notice' => $this->id));
1760 * Determine which notice, if any, a new notice is in reply to.
1762 * For conversation tracking, we try to see where this notice fits
1763 * in the tree. Rough algorithm is:
1765 * if (reply_to is set and valid) {
1767 * } else if ((source not API or Web) and (content starts with "T NAME" or "@name ")) {
1768 * return ID of last notice by initial @name in content;
1771 * Note that all @nickname instances will still be used to save "reply" records,
1772 * so the notice shows up in the mentioned users' "replies" tab.
1774 * @param integer $reply_to ID passed in by Web or API
1775 * @param integer $profile_id ID of author
1776 * @param string $source Source tag, like 'web' or 'gwibber'
1777 * @param string $content Final notice content
1779 * @return integer ID of replied-to notice, or null for not a reply.
1782 static function getReplyTo($reply_to, $profile_id, $source, $content)
1784 static $lb = array('xmpp', 'mail', 'sms', 'omb');
1786 // If $reply_to is specified, we check that it exists, and then
1787 // return it if it does
1789 if (!empty($reply_to)) {
1790 $reply_notice = Notice::getKV('id', $reply_to);
1791 if (!empty($reply_notice)) {
1792 return $reply_notice;
1796 // If it's not a "low bandwidth" source (one where you can't set
1797 // a reply_to argument), we return. This is mostly web and API
1800 if (!in_array($source, $lb)) {
1804 // Is there an initial @ or T?
1806 if (preg_match('/^T ([A-Z0-9]{1,64}) /', $content, $match) ||
1807 preg_match('/^@([a-z0-9]{1,64})\s+/', $content, $match)) {
1808 $nickname = common_canonical_nickname($match[1]);
1813 // Figure out who that is.
1815 $sender = Profile::getKV('id', $profile_id);
1816 if (empty($sender)) {
1820 $recipient = common_relative_profile($sender, $nickname, common_sql_now());
1822 if (empty($recipient)) {
1826 // Get their last notice
1828 $last = $recipient->getCurrentNotice();
1830 if (!empty($last)) {
1837 static function maxContent()
1839 $contentlimit = common_config('notice', 'contentlimit');
1840 // null => use global limit (distinct from 0!)
1841 if (is_null($contentlimit)) {
1842 $contentlimit = common_config('site', 'textlimit');
1844 return $contentlimit;
1847 static function contentTooLong($content)
1849 $contentlimit = self::maxContent();
1850 return ($contentlimit > 0 && !empty($content) && (mb_strlen($content) > $contentlimit));
1853 function getLocation()
1857 if (!empty($this->location_id) && !empty($this->location_ns)) {
1858 $location = Location::fromId($this->location_id, $this->location_ns);
1861 if (is_null($location)) { // no ID, or Location::fromId() failed
1862 if (!empty($this->lat) && !empty($this->lon)) {
1863 $location = Location::fromLatLon($this->lat, $this->lon);
1871 * Convenience function for posting a repeat of an existing message.
1873 * @param int $repeater_id: profile ID of user doing the repeat
1874 * @param string $source: posting source key, eg 'web', 'api', etc
1877 * @throws Exception on failure or permission problems
1879 function repeat($repeater_id, $source)
1881 $author = Profile::getKV('id', $this->profile_id);
1883 // TRANS: Message used to repeat a notice. RT is the abbreviation of 'retweet'.
1884 // TRANS: %1$s is the repeated user's name, %2$s is the repeated notice.
1885 $content = sprintf(_('RT @%1$s %2$s'),
1889 $maxlen = common_config('site', 'textlimit');
1890 if ($maxlen > 0 && mb_strlen($content) > $maxlen) {
1891 // Web interface and current Twitter API clients will
1892 // pull the original notice's text, but some older
1893 // clients and RSS/Atom feeds will see this trimmed text.
1895 // Unfortunately this is likely to lose tags or URLs
1896 // at the end of long notices.
1897 $content = mb_substr($content, 0, $maxlen - 4) . ' ...';
1900 // Scope is same as this one's
1902 return self::saveNew($repeater_id,
1905 array('repeat_of' => $this->id,
1906 'scope' => $this->scope));
1909 // These are supposed to be in chron order!
1911 function repeatStream($limit=100)
1913 $cache = Cache::instance();
1915 if (empty($cache)) {
1916 $ids = $this->_repeatStreamDirect($limit);
1918 $idstr = $cache->get(Cache::key('notice:repeats:'.$this->id));
1919 if ($idstr !== false) {
1920 if (empty($idstr)) {
1923 $ids = explode(',', $idstr);
1926 $ids = $this->_repeatStreamDirect(100);
1927 $cache->set(Cache::key('notice:repeats:'.$this->id), implode(',', $ids));
1930 // We do a max of 100, so slice down to limit
1931 $ids = array_slice($ids, 0, $limit);
1935 return NoticeStream::getStreamByIds($ids);
1938 function _repeatStreamDirect($limit)
1940 $notice = new Notice();
1942 $notice->selectAdd(); // clears it
1943 $notice->selectAdd('id');
1945 $notice->repeat_of = $this->id;
1947 $notice->orderBy('created, id'); // NB: asc!
1949 if (!is_null($limit)) {
1950 $notice->limit(0, $limit);
1953 return $notice->fetchAll('id');
1956 function locationOptions($lat, $lon, $location_id, $location_ns, $profile = null)
1960 if (!empty($location_id) && !empty($location_ns)) {
1961 $options['location_id'] = $location_id;
1962 $options['location_ns'] = $location_ns;
1964 $location = Location::fromId($location_id, $location_ns);
1966 if (!empty($location)) {
1967 $options['lat'] = $location->lat;
1968 $options['lon'] = $location->lon;
1971 } else if (!empty($lat) && !empty($lon)) {
1972 $options['lat'] = $lat;
1973 $options['lon'] = $lon;
1975 $location = Location::fromLatLon($lat, $lon);
1977 if (!empty($location)) {
1978 $options['location_id'] = $location->location_id;
1979 $options['location_ns'] = $location->location_ns;
1981 } else if (!empty($profile)) {
1982 if (isset($profile->lat) && isset($profile->lon)) {
1983 $options['lat'] = $profile->lat;
1984 $options['lon'] = $profile->lon;
1987 if (isset($profile->location_id) && isset($profile->location_ns)) {
1988 $options['location_id'] = $profile->location_id;
1989 $options['location_ns'] = $profile->location_ns;
1996 function clearReplies()
1998 $replyNotice = new Notice();
1999 $replyNotice->reply_to = $this->id;
2001 //Null any notices that are replies to this notice
2003 if ($replyNotice->find()) {
2004 while ($replyNotice->fetch()) {
2005 $orig = clone($replyNotice);
2006 $replyNotice->reply_to = null;
2007 $replyNotice->update($orig);
2013 $reply = new Reply();
2014 $reply->notice_id = $this->id;
2016 if ($reply->find()) {
2017 while($reply->fetch()) {
2018 self::blow('reply:stream:%d', $reply->profile_id);
2026 function clearFiles()
2028 $f2p = new File_to_post();
2030 $f2p->post_id = $this->id;
2033 while ($f2p->fetch()) {
2037 // FIXME: decide whether to delete File objects
2038 // ...and related (actual) files
2041 function clearRepeats()
2043 $repeatNotice = new Notice();
2044 $repeatNotice->repeat_of = $this->id;
2046 //Null any notices that are repeats of this notice
2048 if ($repeatNotice->find()) {
2049 while ($repeatNotice->fetch()) {
2050 $orig = clone($repeatNotice);
2051 $repeatNotice->repeat_of = null;
2052 $repeatNotice->update($orig);
2057 function clearFaves()
2060 $fave->notice_id = $this->id;
2062 if ($fave->find()) {
2063 while ($fave->fetch()) {
2064 self::blow('fave:ids_by_user_own:%d', $fave->user_id);
2065 self::blow('fave:ids_by_user_own:%d;last', $fave->user_id);
2066 self::blow('fave:ids_by_user:%d', $fave->user_id);
2067 self::blow('fave:ids_by_user:%d;last', $fave->user_id);
2075 function clearTags()
2077 $tag = new Notice_tag();
2078 $tag->notice_id = $this->id;
2081 while ($tag->fetch()) {
2082 self::blow('profile:notice_ids_tagged:%d:%s', $this->profile_id, Cache::keyize($tag->tag));
2083 self::blow('profile:notice_ids_tagged:%d:%s;last', $this->profile_id, Cache::keyize($tag->tag));
2084 self::blow('notice_tag:notice_ids:%s', Cache::keyize($tag->tag));
2085 self::blow('notice_tag:notice_ids:%s;last', Cache::keyize($tag->tag));
2093 function clearGroupInboxes()
2095 $gi = new Group_inbox();
2097 $gi->notice_id = $this->id;
2100 while ($gi->fetch()) {
2101 self::blow('user_group:notice_ids:%d', $gi->group_id);
2109 function distribute()
2111 // We always insert for the author so they don't
2113 Event::handle('StartNoticeDistribute', array($this));
2115 $user = User::getKV('id', $this->profile_id);
2116 if (!empty($user)) {
2117 Inbox::insertNotice($user->id, $this->id);
2120 if (common_config('queue', 'inboxes')) {
2121 // If there's a failure, we want to _force_
2122 // distribution at this point.
2124 $qm = QueueManager::get();
2125 $qm->enqueue($this, 'distrib');
2126 } catch (Exception $e) {
2127 // If the exception isn't transient, this
2128 // may throw more exceptions as DQH does
2129 // its own enqueueing. So, we ignore them!
2131 $handler = new DistribQueueHandler();
2132 $handler->handle($this);
2133 } catch (Exception $e) {
2134 common_log(LOG_ERR, "emergency redistribution resulted in " . $e->getMessage());
2136 // Re-throw so somebody smarter can handle it.
2140 $handler = new DistribQueueHandler();
2141 $handler->handle($this);
2147 $result = parent::insert();
2150 // Profile::hasRepeated() abuses pkeyGet(), so we
2151 // have to clear manually
2152 if (!empty($this->repeat_of)) {
2153 $c = self::memcache();
2155 $ck = self::multicacheKey('Notice',
2156 array('profile_id' => $this->profile_id,
2157 'repeat_of' => $this->repeat_of));
2167 * Get the source of the notice
2169 * @return Notice_source $ns A notice source object. 'code' is the only attribute
2170 * guaranteed to be populated.
2172 function getSource()
2174 $ns = new Notice_source();
2175 if (!empty($this->source)) {
2176 switch ($this->source) {
2183 $ns->code = $this->source;
2186 $ns = Notice_source::getKV($this->source);
2188 $ns = new Notice_source();
2189 $ns->code = $this->source;
2190 $app = Oauth_application::getKV('name', $this->source);
2192 $ns->name = $app->name;
2193 $ns->url = $app->source_url;
2203 * Determine whether the notice was locally created
2205 * @return boolean locality
2208 public function isLocal()
2210 return ($this->is_local == Notice::LOCAL_PUBLIC ||
2211 $this->is_local == Notice::LOCAL_NONPUBLIC);
2215 * Get the list of hash tags saved with this notice.
2217 * @return array of strings
2219 public function getTags()
2223 $keypart = sprintf('notice:tags:%d', $this->id);
2225 $tagstr = self::cacheGet($keypart);
2227 if ($tagstr !== false) {
2228 $tags = explode(',', $tagstr);
2230 $tag = new Notice_tag();
2231 $tag->notice_id = $this->id;
2233 while ($tag->fetch()) {
2234 $tags[] = $tag->tag;
2237 self::cacheSet($keypart, implode(',', $tags));
2243 static private function utcDate($dt)
2245 $dateStr = date('d F Y H:i:s', strtotime($dt));
2246 $d = new DateTime($dateStr, new DateTimeZone('UTC'));
2247 return $d->format(DATE_W3C);
2251 * Look up the creation timestamp for a given notice ID, even
2252 * if it's been deleted.
2255 * @return mixed string recorded creation timestamp, or false if can't be found
2257 public static function getAsTimestamp($id)
2263 $notice = Notice::getKV('id', $id);
2265 return $notice->created;
2268 $deleted = Deleted_notice::getKV('id', $id);
2270 return $deleted->created;
2277 * Build an SQL 'where' fragment for timestamp-based sorting from a since_id
2278 * parameter, matching notices posted after the given one (exclusive).
2280 * If the referenced notice can't be found, will return false.
2283 * @param string $idField
2284 * @param string $createdField
2285 * @return mixed string or false if no match
2287 public static function whereSinceId($id, $idField='id', $createdField='created')
2289 $since = Notice::getAsTimestamp($id);
2291 return sprintf("($createdField = '%s' and $idField > %d) or ($createdField > '%s')", $since, $id, $since);
2297 * Build an SQL 'where' fragment for timestamp-based sorting from a since_id
2298 * parameter, matching notices posted after the given one (exclusive), and
2299 * if necessary add it to the data object's query.
2301 * @param DB_DataObject $obj
2303 * @param string $idField
2304 * @param string $createdField
2305 * @return mixed string or false if no match
2307 public static function addWhereSinceId(DB_DataObject $obj, $id, $idField='id', $createdField='created')
2309 $since = self::whereSinceId($id, $idField, $createdField);
2311 $obj->whereAdd($since);
2316 * Build an SQL 'where' fragment for timestamp-based sorting from a max_id
2317 * parameter, matching notices posted before the given one (inclusive).
2319 * If the referenced notice can't be found, will return false.
2322 * @param string $idField
2323 * @param string $createdField
2324 * @return mixed string or false if no match
2326 public static function whereMaxId($id, $idField='id', $createdField='created')
2328 $max = Notice::getAsTimestamp($id);
2330 return sprintf("($createdField < '%s') or ($createdField = '%s' and $idField <= %d)", $max, $max, $id);
2336 * Build an SQL 'where' fragment for timestamp-based sorting from a max_id
2337 * parameter, matching notices posted before the given one (inclusive), and
2338 * if necessary add it to the data object's query.
2340 * @param DB_DataObject $obj
2342 * @param string $idField
2343 * @param string $createdField
2344 * @return mixed string or false if no match
2346 public static function addWhereMaxId(DB_DataObject $obj, $id, $idField='id', $createdField='created')
2348 $max = self::whereMaxId($id, $idField, $createdField);
2350 $obj->whereAdd($max);
2356 if (common_config('public', 'localonly')) {
2357 return ($this->is_local == Notice::LOCAL_PUBLIC);
2359 return (($this->is_local != Notice::LOCAL_NONPUBLIC) &&
2360 ($this->is_local != Notice::GATEWAY));
2365 * Check that the given profile is allowed to read, respond to, or otherwise
2366 * act on this notice.
2368 * The $scope member is a bitmask of scopes, representing a logical AND of the
2369 * scope requirement. So, 0x03 (Notice::ADDRESSEE_SCOPE | Notice::SITE_SCOPE) means
2370 * "only visible to people who are mentioned in the notice AND are users on this site."
2371 * Users on the site who are not mentioned in the notice will not be able to see the
2374 * @param Profile $profile The profile to check; pass null to check for public/unauthenticated users.
2376 * @return boolean whether the profile is in the notice's scope
2378 function inScope($profile)
2380 if (is_null($profile)) {
2381 $keypart = sprintf('notice:in-scope-for:%d:null', $this->id);
2383 $keypart = sprintf('notice:in-scope-for:%d:%d', $this->id, $profile->id);
2386 $result = self::cacheGet($keypart);
2388 if ($result === false) {
2390 if (Event::handle('StartNoticeInScope', array($this, $profile, &$bResult))) {
2391 $bResult = $this->_inScope($profile);
2392 Event::handle('EndNoticeInScope', array($this, $profile, &$bResult));
2394 $result = ($bResult) ? 1 : 0;
2395 self::cacheSet($keypart, $result, 0, 300);
2398 return ($result == 1) ? true : false;
2401 protected function _inScope($profile)
2403 if (!is_null($this->scope)) {
2404 $scope = $this->scope;
2406 $scope = self::defaultScope();
2409 // If there's no scope, anyone (even anon) is in scope.
2411 if ($scope == 0) { // Not private
2413 return !$this->isHiddenSpam($profile);
2415 } else { // Private, somehow
2417 // If there's scope, anon cannot be in scope
2419 if (empty($profile)) {
2423 // Author is always in scope
2425 if ($this->profile_id == $profile->id) {
2429 // Only for users on this site
2431 if (($scope & Notice::SITE_SCOPE) && !$profile->isLocal()) {
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 $_parent = -1;
2539 public function getParent()
2541 if (empty($this->reply_to)) {
2542 // Should this also be NoResultException? I don't think so.
2543 throw new Exception('Notice has no parent');
2544 } elseif ($this->_parent === -1) { // local object cache
2545 $this->_parent = Notice::getKV('id', $this->reply_to);
2548 if (!($this->_parent instanceof Notice)) {
2549 throw new NoResultException($this->_parent);
2551 return $this->_parent;
2555 * Magic function called at serialize() time.
2557 * We use this to drop a couple process-specific references
2558 * from DB_DataObject which can cause trouble in future
2561 * @return array of variable names to include in serialization.
2566 $vars = parent::__sleep();
2567 $skip = array('_parent', '_profile', '_groups', '_attachments', '_faves', '_replies', '_repeats');
2568 return array_diff($vars, $skip);
2571 static function defaultScope()
2573 $scope = common_config('notice', 'defaultscope');
2574 if (is_null($scope)) {
2575 if (common_config('site', 'private')) {
2584 static function fillProfiles($notices)
2586 $map = self::getProfiles($notices);
2588 foreach ($notices as $notice) {
2589 if (array_key_exists($notice->profile_id, $map)) {
2590 $notice->_setProfile($map[$notice->profile_id]);
2594 return array_values($map);
2597 static function getProfiles(&$notices)
2600 foreach ($notices as $notice) {
2601 $ids[] = $notice->profile_id;
2604 $ids = array_unique($ids);
2606 return Profile::pivotGet('id', $ids);
2609 static function fillGroups(&$notices)
2611 $ids = self::_idsOf($notices);
2613 $gis = Group_inbox::listGet('notice_id', $ids);
2617 foreach ($gis as $id => $gi)
2621 $gids[] = $g->group_id;
2625 $gids = array_unique($gids);
2627 $group = User_group::pivotGet('id', $gids);
2629 foreach ($notices as $notice)
2632 $gi = $gis[$notice->id];
2633 foreach ($gi as $g) {
2634 $grps[] = $group[$g->group_id];
2636 $notice->_setGroups($grps);
2640 static function _idsOf(&$notices)
2643 foreach ($notices as $notice) {
2644 $ids[] = $notice->id;
2646 $ids = array_unique($ids);
2650 static function fillAttachments(&$notices)
2652 $ids = self::_idsOf($notices);
2654 $f2pMap = File_to_post::listGet('post_id', $ids);
2658 foreach ($f2pMap as $noticeId => $f2ps) {
2659 foreach ($f2ps as $f2p) {
2660 $fileIds[] = $f2p->file_id;
2664 $fileIds = array_unique($fileIds);
2666 $fileMap = File::pivotGet('id', $fileIds);
2668 foreach ($notices as $notice)
2671 $f2ps = $f2pMap[$notice->id];
2672 foreach ($f2ps as $f2p) {
2673 $files[] = $fileMap[$f2p->file_id];
2675 $notice->_setAttachments($files);
2682 * All faves of this notice
2684 * @return array Array of Fave objects
2689 if (isset($this->_faves) && is_array($this->_faves)) {
2690 return $this->_faves;
2692 $faveMap = Fave::listGet('notice_id', array($this->id));
2693 $this->_faves = $faveMap[$this->id];
2694 return $this->_faves;
2697 function _setFaves($faves)
2699 $this->_faves = $faves;
2702 static function fillFaves(&$notices)
2704 $ids = self::_idsOf($notices);
2705 $faveMap = Fave::listGet('notice_id', $ids);
2708 foreach ($faveMap as $id => $faves) {
2709 $cnt += count($faves);
2710 if (count($faves) > 0) {
2714 foreach ($notices as $notice) {
2715 $faves = $faveMap[$notice->id];
2716 $notice->_setFaves($faves);
2720 static function fillReplies(&$notices)
2722 $ids = self::_idsOf($notices);
2723 $replyMap = Reply::listGet('notice_id', $ids);
2724 foreach ($notices as $notice) {
2725 $replies = $replyMap[$notice->id];
2727 foreach ($replies as $reply) {
2728 $ids[] = $reply->profile_id;
2730 $notice->_setReplies($ids);
2734 protected $_repeats;
2736 function getRepeats()
2738 if (isset($this->_repeats) && is_array($this->_repeats)) {
2739 return $this->_repeats;
2741 $repeatMap = Notice::listGet('repeat_of', array($this->id));
2742 $this->_repeats = $repeatMap[$this->id];
2743 return $this->_repeats;
2746 function _setRepeats($repeats)
2748 $this->_repeats = $repeats;
2751 static function fillRepeats(&$notices)
2753 $ids = self::_idsOf($notices);
2754 $repeatMap = Notice::listGet('repeat_of', $ids);
2755 foreach ($notices as $notice) {
2756 $repeats = $repeatMap[$notice->id];
2757 $notice->_setRepeats($repeats);