3 * StatusNet - the distributed open-source microblogging tool
4 * Copyright (C) 2008-2011 StatusNet, Inc.
6 * This program is free software: you can redistribute it and/or modify
7 * it under the terms of the GNU Affero General Public License as published by
8 * the Free Software Foundation, either version 3 of the License, or
9 * (at your option) any later version.
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU Affero General Public License for more details.
16 * You should have received a copy of the GNU Affero General Public License
17 * along with this program. If not, see <http://www.gnu.org/licenses/>.
21 * @author Brenda Wallace <shiny@cpan.org>
22 * @author Christopher Vollick <psycotica0@gmail.com>
23 * @author CiaranG <ciaran@ciarang.com>
24 * @author Craig Andrews <candrews@integralblue.com>
25 * @author Evan Prodromou <evan@controlezvous.ca>
26 * @author Gina Haeussge <osd@foosel.net>
27 * @author Jeffery To <jeffery.to@gmail.com>
28 * @author Mike Cochrane <mikec@mikenz.geek.nz>
29 * @author Robin Millette <millette@controlyourself.ca>
30 * @author Sarven Capadisli <csarven@controlyourself.ca>
31 * @author Tom Adams <tom@holizz.com>
32 * @author Mikael Nordfeldth <mmn@hethane.se>
33 * @copyright 2009 Free Software Foundation, Inc http://www.fsf.org
34 * @license GNU Affero General Public License http://www.gnu.org/licenses/
37 if (!defined('GNUSOCIAL')) { exit(1); }
40 * Table Definition for notice
43 /* We keep 200 notices, the max number of notices available per API request,
44 * in the memcached cache. */
46 define('NOTICE_CACHE_WINDOW', CachingNoticeStream::CACHE_WINDOW);
48 define('MAX_BOXCARS', 128);
50 class Notice extends Managed_DataObject
53 /* the code below is auto generated do not remove the above tag */
55 public $__table = 'notice'; // table name
56 public $id; // int(4) primary_key not_null
57 public $profile_id; // int(4) multiple_key not_null
58 public $uri; // varchar(255) unique_key
59 public $content; // text
60 public $rendered; // text
61 public $url; // varchar(255)
62 public $created; // datetime multiple_key not_null default_0000-00-00%2000%3A00%3A00
63 public $modified; // timestamp not_null default_CURRENT_TIMESTAMP
64 public $reply_to; // int(4)
65 public $is_local; // int(4)
66 public $source; // varchar(32)
67 public $conversation; // int(4)
68 public $lat; // decimal(10,7)
69 public $lon; // decimal(10,7)
70 public $location_id; // int(4)
71 public $location_ns; // int(4)
72 public $repeat_of; // int(4)
73 public $verb; // varchar(255)
74 public $object_type; // varchar(255)
75 public $scope; // int(4)
77 /* the code above is auto generated do not remove the tag below */
80 public static function schemaDef()
84 'id' => array('type' => 'serial', 'not null' => true, 'description' => 'unique identifier'),
85 'profile_id' => array('type' => 'int', 'not null' => true, 'description' => 'who made the update'),
86 'uri' => array('type' => 'varchar', 'length' => 255, 'description' => 'universally unique identifier, usually a tag URI'),
87 'content' => array('type' => 'text', 'description' => 'update content', 'collate' => 'utf8_general_ci'),
88 'rendered' => array('type' => 'text', 'description' => 'HTML version of the content'),
89 'url' => array('type' => 'varchar', 'length' => 255, 'description' => 'URL of any attachment (image, video, bookmark, whatever)'),
90 'created' => array('type' => 'datetime', 'not null' => true, 'description' => 'date this record was created'),
91 'modified' => array('type' => 'timestamp', 'not null' => true, 'description' => 'date this record was modified'),
92 'reply_to' => array('type' => 'int', 'description' => 'notice replied to (usually a guess)'),
93 'is_local' => array('type' => 'int', 'size' => 'tiny', 'default' => 0, 'description' => 'notice was generated by a user'),
94 'source' => array('type' => 'varchar', 'length' => 32, 'description' => 'source of comment, like "web", "im", or "clientname"'),
95 'conversation' => array('type' => 'int', 'description' => 'id of root notice in this conversation'),
96 'lat' => array('type' => 'numeric', 'precision' => 10, 'scale' => 7, 'description' => 'latitude'),
97 'lon' => array('type' => 'numeric', 'precision' => 10, 'scale' => 7, 'description' => 'longitude'),
98 'location_id' => array('type' => 'int', 'description' => 'location id if possible'),
99 'location_ns' => array('type' => 'int', 'description' => 'namespace for location'),
100 'repeat_of' => array('type' => 'int', 'description' => 'notice this is a repeat of'),
101 'object_type' => array('type' => 'varchar', 'length' => 255, 'description' => 'URI representing activity streams object type', 'default' => 'http://activitystrea.ms/schema/1.0/note'),
102 'verb' => array('type' => 'varchar', 'length' => 255, 'description' => 'URI representing activity streams verb', 'default' => 'http://activitystrea.ms/schema/1.0/post'),
103 'scope' => array('type' => 'int',
104 'description' => 'bit map for distribution scope; 0 = everywhere; 1 = this server only; 2 = addressees; 4 = followers; null = default'),
106 'primary key' => array('id'),
107 'unique keys' => array(
108 'notice_uri_key' => array('uri'),
110 'foreign keys' => array(
111 'notice_profile_id_fkey' => array('profile', array('profile_id' => 'id')),
112 'notice_reply_to_fkey' => array('notice', array('reply_to' => 'id')),
113 'notice_conversation_fkey' => array('conversation', array('conversation' => 'id')), # note... used to refer to notice.id
114 'notice_repeat_of_fkey' => array('notice', array('repeat_of' => 'id')), # @fixme: what about repeats of deleted notices?
117 'notice_created_id_is_local_idx' => array('created', 'id', 'is_local'),
118 'notice_profile_id_idx' => array('profile_id', 'created', 'id'),
119 'notice_repeat_of_created_id_idx' => array('repeat_of', 'created', 'id'),
120 'notice_conversation_created_id_idx' => array('conversation', 'created', 'id'),
121 'notice_replyto_idx' => array('reply_to')
125 if (common_config('search', 'type') == 'fulltext') {
126 $def['fulltext indexes'] = array('content' => array('content'));
133 const LOCAL_PUBLIC = 1;
135 const LOCAL_NONPUBLIC = -1;
138 const PUBLIC_SCOPE = 0; // Useful fake constant
139 const SITE_SCOPE = 1;
140 const ADDRESSEE_SCOPE = 2;
141 const GROUP_SCOPE = 4;
142 const FOLLOWER_SCOPE = 8;
144 protected $_profile = -1;
146 public function getProfile()
148 if ($this->_profile === -1) {
149 $this->_setProfile(Profile::getKV('id', $this->profile_id));
151 if (!$this->_profile instanceof Profile) {
152 throw new NoProfileException($this->profile_id);
154 return $this->_profile;
157 function _setProfile(Profile $profile)
159 $this->_profile = $profile;
162 function delete($useWhere=false)
164 // For auditing purposes, save a record that the notice
167 // @fixme we have some cases where things get re-run and so the
169 $deleted = Deleted_notice::getKV('id', $this->id);
171 if (!$deleted instanceof Deleted_notice) {
172 $deleted = Deleted_notice::getKV('uri', $this->uri);
175 if (!$deleted instanceof Deleted_notice) {
176 $deleted = new Deleted_notice();
178 $deleted->id = $this->id;
179 $deleted->profile_id = $this->profile_id;
180 $deleted->uri = $this->uri;
181 $deleted->created = $this->created;
182 $deleted->deleted = common_sql_now();
187 if (Event::handle('NoticeDeleteRelated', array($this))) {
189 // Clear related records
191 $this->clearReplies();
192 $this->clearRepeats();
195 $this->clearGroupInboxes();
198 // NOTE: we don't clear inboxes
199 // NOTE: we don't clear queue items
202 $result = parent::delete($useWhere);
204 $this->blowOnDelete();
208 public function getUri()
213 public function getUrl()
215 // The risk is we start having empty urls and non-http uris...
216 return $this->url ?: $this->uri;
219 public function getByUri($uri)
221 return Notice::getKV('uri', $uri);
225 * Extract #hashtags from this notice's content and save them to the database.
229 /* extract all #hastags */
230 $count = preg_match_all('/(?:^|\s)#([\pL\pN_\-\.]{1,64})/u', strtolower($this->content), $match);
235 /* Add them to the database */
236 return $this->saveKnownTags($match[1]);
240 * Record the given set of hash tags in the db for this notice.
241 * Given tag strings will be normalized and checked for dupes.
243 function saveKnownTags($hashtags)
245 //turn each into their canonical tag
246 //this is needed to remove dupes before saving e.g. #hash.tag = #hashtag
247 for($i=0; $i<count($hashtags); $i++) {
248 /* elide characters we don't want in the tag */
249 $hashtags[$i] = common_canonical_tag($hashtags[$i]);
252 foreach(array_unique($hashtags) as $hashtag) {
253 $this->saveTag($hashtag);
254 self::blow('profile:notice_ids_tagged:%d:%s', $this->profile_id, $hashtag);
260 * Record a single hash tag as associated with this notice.
261 * Tag format and uniqueness must be validated by caller.
263 function saveTag($hashtag)
265 $tag = new Notice_tag();
266 $tag->notice_id = $this->id;
267 $tag->tag = $hashtag;
268 $tag->created = $this->created;
269 $id = $tag->insert();
272 // TRANS: Server exception. %s are the error details.
273 throw new ServerException(sprintf(_('Database error inserting hashtag: %s.'),
274 $last_error->message));
278 // if it's saved, blow its cache
279 $tag->blowCache(false);
283 * Save a new notice and push it out to subscribers' inboxes.
284 * Poster's permissions are checked before sending.
286 * @param int $profile_id Profile ID of the poster
287 * @param string $content source message text; links may be shortened
288 * per current user's preference
289 * @param string $source source key ('web', 'api', etc)
290 * @param array $options Associative array of optional properties:
291 * string 'created' timestamp of notice; defaults to now
292 * int 'is_local' source/gateway ID, one of:
293 * Notice::LOCAL_PUBLIC - Local, ok to appear in public timeline
294 * Notice::REMOTE - Sent from a remote service;
295 * hide from public timeline but show in
296 * local "and friends" timelines
297 * Notice::LOCAL_NONPUBLIC - Local, but hide from public timeline
298 * Notice::GATEWAY - From another non-OStatus service;
299 * will not appear in public views
300 * float 'lat' decimal latitude for geolocation
301 * float 'lon' decimal longitude for geolocation
302 * int 'location_id' geoname identifier
303 * int 'location_ns' geoname namespace to interpret location_id
304 * int 'reply_to'; notice ID this is a reply to
305 * int 'repeat_of'; notice ID this is a repeat of
306 * string 'uri' unique ID for notice; defaults to local notice URL
307 * string 'url' permalink to notice; defaults to local notice URL
308 * string 'rendered' rendered HTML version of content
309 * array 'replies' list of profile URIs for reply delivery in
310 * place of extracting @-replies from content.
311 * array 'groups' list of group IDs to deliver to, in place of
312 * extracting ! tags from content
313 * array 'tags' list of hashtag strings to save with the notice
314 * in place of extracting # tags from content
315 * array 'urls' list of attached/referred URLs to save with the
316 * notice in place of extracting links from content
317 * boolean 'distribute' whether to distribute the notice, default true
318 * string 'object_type' URL of the associated object type (default ActivityObject::NOTE)
319 * string 'verb' URL of the associated verb (default ActivityVerb::POST)
320 * int 'scope' Scope bitmask; default to SITE_SCOPE on private sites, 0 otherwise
322 * @fixme tag override
325 * @throws ClientException
327 static function saveNew($profile_id, $content, $source, array $options=null) {
328 $defaults = array('uri' => null,
333 'distribute' => true,
334 'object_type' => null,
337 if (!empty($options) && is_array($options)) {
338 $options = array_merge($defaults, $options);
344 if (!isset($is_local)) {
345 $is_local = Notice::LOCAL_PUBLIC;
348 $profile = Profile::getKV('id', $profile_id);
349 if (!$profile instanceof Profile) {
350 // TRANS: Client exception thrown when trying to save a notice for an unknown user.
351 throw new ClientException(_('Problem saving notice. Unknown user.'));
354 $user = User::getKV('id', $profile_id);
355 if ($user instanceof User) {
356 // Use the local user's shortening preferences, if applicable.
357 $final = $user->shortenLinks($content);
359 $final = common_shorten_links($content);
362 if (Notice::contentTooLong($final)) {
363 // TRANS: Client exception thrown if a notice contains too many characters.
364 throw new ClientException(_('Problem saving notice. Too long.'));
367 if (common_config('throttle', 'enabled') && !Notice::checkEditThrottle($profile_id)) {
368 common_log(LOG_WARNING, 'Excessive posting by profile #' . $profile_id . '; throttled.');
369 // TRANS: Client exception thrown when a user tries to post too many notices in a given time frame.
370 throw new ClientException(_('Too many notices too fast; take a breather '.
371 'and post again in a few minutes.'));
374 if (common_config('site', 'dupelimit') > 0 && !Notice::checkDupes($profile_id, $final)) {
375 common_log(LOG_WARNING, 'Dupe posting by profile #' . $profile_id . '; throttled.');
376 // TRANS: Client exception thrown when a user tries to post too many duplicate notices in a given time frame.
377 throw new ClientException(_('Too many duplicate messages too quickly;'.
378 ' take a breather and post again in a few minutes.'));
381 if (!$profile->hasRight(Right::NEWNOTICE)) {
382 common_log(LOG_WARNING, "Attempted post from user disallowed to post: " . $profile->nickname);
384 // TRANS: Client exception thrown when a user tries to post while being banned.
385 throw new ClientException(_('You are banned from posting notices on this site.'), 403);
388 $notice = new Notice();
389 $notice->profile_id = $profile_id;
391 $autosource = common_config('public', 'autosource');
393 // Sandboxed are non-false, but not 1, either
395 if (!$profile->hasRight(Right::PUBLICNOTICE) ||
396 ($source && $autosource && in_array($source, $autosource))) {
397 $notice->is_local = Notice::LOCAL_NONPUBLIC;
399 $notice->is_local = $is_local;
402 if (!empty($created)) {
403 $notice->created = $created;
405 $notice->created = common_sql_now();
408 $notice->content = $final;
410 $notice->source = $source;
414 // Get the groups here so we can figure out replies and such
415 if (!isset($groups)) {
416 $groups = User_group::idsFromText($notice->content, $profile);
421 // Handle repeat case
423 if (isset($repeat_of)) {
425 // Check for a private one
427 $repeat = Notice::getKV('id', $repeat_of);
429 if (!($repeat instanceof Notice)) {
430 // TRANS: Client exception thrown in notice when trying to repeat a missing or deleted notice.
431 throw new ClientException(_('Cannot repeat; original notice is missing or deleted.'));
434 if ($profile->id == $repeat->profile_id) {
435 // TRANS: Client error displayed when trying to repeat an own notice.
436 throw new ClientException(_('You cannot repeat your own notice.'));
439 if ($repeat->scope != Notice::SITE_SCOPE &&
440 $repeat->scope != Notice::PUBLIC_SCOPE) {
441 // TRANS: Client error displayed when trying to repeat a non-public notice.
442 throw new ClientException(_('Cannot repeat a private notice.'), 403);
445 if (!$repeat->inScope($profile)) {
446 // The generic checks above should cover this, but let's be sure!
447 // TRANS: Client error displayed when trying to repeat a notice you cannot access.
448 throw new ClientException(_('Cannot repeat a notice you cannot read.'), 403);
451 if ($profile->hasRepeated($repeat)) {
452 // TRANS: Client error displayed when trying to repeat an already repeated notice.
453 throw new ClientException(_('You already repeated that notice.'));
456 $notice->repeat_of = $repeat_of;
458 $reply = self::getReplyTo($reply_to, $profile_id, $source, $final);
460 if (!empty($reply)) {
462 if (!$reply->inScope($profile)) {
463 // TRANS: Client error displayed when trying to reply to a notice a the target has no access to.
464 // TRANS: %1$s is a user nickname, %2$d is a notice ID (number).
465 throw new ClientException(sprintf(_('%1$s has no access to notice %2$d.'),
466 $profile->nickname, $reply->id), 403);
469 $notice->reply_to = $reply->id;
470 $notice->conversation = $reply->conversation;
472 // If the original is private to a group, and notice has no group specified,
473 // make it to the same group(s)
475 if (empty($groups) && ($reply->scope & Notice::GROUP_SCOPE)) {
477 $replyGroups = $reply->getGroups();
478 foreach ($replyGroups as $group) {
479 if ($profile->isMember($group)) {
480 $groups[] = $group->id;
489 if (!empty($lat) && !empty($lon)) {
494 if (!empty($location_ns) && !empty($location_id)) {
495 $notice->location_id = $location_id;
496 $notice->location_ns = $location_ns;
499 if (!empty($rendered)) {
500 $notice->rendered = $rendered;
502 $notice->rendered = common_render_content($final, $notice);
506 if (!empty($notice->repeat_of)) {
507 $notice->verb = ActivityVerb::SHARE;
508 $notice->object_type = ActivityObject::ACTIVITY;
510 $notice->verb = ActivityVerb::POST;
513 $notice->verb = $verb;
516 if (empty($object_type)) {
517 $notice->object_type = (empty($notice->reply_to)) ? ActivityObject::NOTE : ActivityObject::COMMENT;
519 $notice->object_type = $object_type;
522 if (is_null($scope)) { // 0 is a valid value
523 if (!empty($reply)) {
524 $notice->scope = $reply->scope;
526 $notice->scope = self::defaultScope();
529 $notice->scope = $scope;
532 // For private streams
535 $user = $profile->getUser();
537 if ($user->private_stream &&
538 ($notice->scope == Notice::PUBLIC_SCOPE ||
539 $notice->scope == Notice::SITE_SCOPE)) {
540 $notice->scope |= Notice::FOLLOWER_SCOPE;
542 } catch (NoSuchUserException $e) {
543 // Cannot handle private streams for remote profiles
546 // Force the scope for private groups
548 foreach ($groups as $groupId) {
549 $group = User_group::getKV('id', $groupId);
550 if ($group instanceof User_group) {
551 if ($group->force_scope) {
552 $notice->scope |= Notice::GROUP_SCOPE;
558 if (Event::handle('StartNoticeSave', array(&$notice))) {
560 // XXX: some of these functions write to the DB
562 $id = $notice->insert();
565 common_log_db_error($notice, 'INSERT', __FILE__);
566 // TRANS: Server exception thrown when a notice cannot be saved.
567 throw new ServerException(_('Problem saving notice.'));
570 // Update ID-dependent columns: URI, conversation
572 $orig = clone($notice);
577 $notice->uri = common_notice_uri($notice);
581 // If it's not part of a conversation, it's
582 // the beginning of a new conversation.
584 if (empty($notice->conversation)) {
585 $conv = Conversation::create();
586 $notice->conversation = $conv->id;
591 if (!$notice->update($orig)) {
592 common_log_db_error($notice, 'UPDATE', __FILE__);
593 // TRANS: Server exception thrown when a notice cannot be updated.
594 throw new ServerException(_('Problem saving notice.'));
600 // Clear the cache for subscribed users, so they'll update at next request
601 // XXX: someone clever could prepend instead of clearing the cache
603 $notice->blowOnInsert();
605 // Save per-notice metadata...
607 if (isset($replies)) {
608 $notice->saveKnownReplies($replies);
610 $notice->saveReplies();
614 $notice->saveKnownTags($tags);
619 // Note: groups may save tags, so must be run after tags are saved
620 // to avoid errors on duplicates.
621 // Note: groups should always be set.
623 $notice->saveKnownGroups($groups);
626 $notice->saveKnownUrls($urls);
632 // Prepare inbox delivery, may be queued to background.
633 $notice->distribute();
639 function blowOnInsert($conversation = false)
641 $this->blowStream('profile:notice_ids:%d', $this->profile_id);
643 if ($this->isPublic()) {
644 $this->blowStream('public');
647 self::blow('notice:list-ids:conversation:%s', $this->conversation);
648 self::blow('conversation:notice_count:%d', $this->conversation);
650 if (!empty($this->repeat_of)) {
651 // XXX: we should probably only use one of these
652 $this->blowStream('notice:repeats:%d', $this->repeat_of);
653 self::blow('notice:list-ids:repeat_of:%d', $this->repeat_of);
656 $original = Notice::getKV('id', $this->repeat_of);
658 if ($original instanceof Notice) {
659 $originalUser = User::getKV('id', $original->profile_id);
660 if ($originalUser instanceof User) {
661 $this->blowStream('user:repeats_of_me:%d', $originalUser->id);
665 $profile = Profile::getKV($this->profile_id);
667 if ($profile instanceof Profile) {
668 $profile->blowNoticeCount();
671 $ptags = $this->getProfileTags();
672 foreach ($ptags as $ptag) {
673 $ptag->blowNoticeStreamCache();
678 * Clear cache entries related to this notice at delete time.
679 * Necessary to avoid breaking paging on public, profile timelines.
681 function blowOnDelete()
683 $this->blowOnInsert();
685 self::blow('profile:notice_ids:%d;last', $this->profile_id);
687 if ($this->isPublic()) {
688 self::blow('public;last');
691 self::blow('fave:by_notice', $this->id);
693 if ($this->conversation) {
694 // In case we're the first, will need to calc a new root.
695 self::blow('notice:conversation_root:%d', $this->conversation);
698 $ptags = $this->getProfileTags();
699 foreach ($ptags as $ptag) {
700 $ptag->blowNoticeStreamCache(true);
704 function blowStream()
706 $c = self::memcache();
712 $args = func_get_args();
714 $format = array_shift($args);
716 $keyPart = vsprintf($format, $args);
718 $cacheKey = Cache::key($keyPart);
720 $c->delete($cacheKey);
722 // delete the "last" stream, too, if this notice is
723 // older than the top of that stream
725 $lastKey = $cacheKey.';last';
727 $lastStr = $c->get($lastKey);
729 if ($lastStr !== false) {
730 $window = explode(',', $lastStr);
731 $lastID = $window[0];
732 $lastNotice = Notice::getKV('id', $lastID);
733 if (!$lastNotice instanceof Notice // just weird
734 || strtotime($lastNotice->created) >= strtotime($this->created)) {
735 $c->delete($lastKey);
740 /** save all urls in the notice to the db
742 * follow redirects and save all available file information
743 * (mimetype, date, size, oembed, etc.)
747 function saveUrls() {
748 if (common_config('attachments', 'process_links')) {
749 common_replace_urls_callback($this->content, array($this, 'saveUrl'), $this->id);
754 * Save the given URLs as related links/attachments to the db
756 * follow redirects and save all available file information
757 * (mimetype, date, size, oembed, etc.)
761 function saveKnownUrls($urls)
763 if (common_config('attachments', 'process_links')) {
764 // @fixme validation?
765 foreach (array_unique($urls) as $url) {
766 File::processNew($url, $this->id);
774 function saveUrl($url, $notice_id) {
775 File::processNew($url, $notice_id);
778 static function checkDupes($profile_id, $content) {
779 $profile = Profile::getKV($profile_id);
780 if (!$profile instanceof Profile) {
783 $notice = $profile->getNotices(0, CachingNoticeStream::CACHE_WINDOW);
784 if (!empty($notice)) {
786 while ($notice->fetch()) {
787 if (time() - strtotime($notice->created) >= common_config('site', 'dupelimit')) {
789 } else if ($notice->content == $content) {
794 // If we get here, oldest item in cache window is not
795 // old enough for dupe limit; do direct check against DB
796 $notice = new Notice();
797 $notice->profile_id = $profile_id;
798 $notice->content = $content;
799 $threshold = common_sql_date(time() - common_config('site', 'dupelimit'));
800 $notice->whereAdd(sprintf("created > '%s'", $notice->escape($threshold)));
802 $cnt = $notice->count();
806 static function checkEditThrottle($profile_id) {
807 $profile = Profile::getKV($profile_id);
808 if (!$profile instanceof Profile) {
811 // Get the Nth notice
812 $notice = $profile->getNotices(common_config('throttle', 'count') - 1, 1);
813 if ($notice && $notice->fetch()) {
814 // If the Nth notice was posted less than timespan seconds ago
815 if (time() - strtotime($notice->created) <= common_config('throttle', 'timespan')) {
820 // Either not N notices in the stream, OR the Nth was not posted within timespan seconds
824 protected $_attachments = -1;
826 function attachments() {
828 if ($this->_attachments != -1) {
829 return $this->_attachments;
832 $f2ps = File_to_post::listGet('post_id', array($this->id));
836 foreach ($f2ps[$this->id] as $f2p) {
837 $ids[] = $f2p->file_id;
840 $files = File::multiGet('id', $ids);
842 $this->_attachments = $files->fetchAll();
844 return $this->_attachments;
847 function _setAttachments($attachments)
849 $this->_attachments = $attachments;
852 function publicStream($offset=0, $limit=20, $since_id=0, $max_id=0)
854 $stream = new PublicNoticeStream();
855 return $stream->getNotices($offset, $limit, $since_id, $max_id);
859 function conversationStream($id, $offset=0, $limit=20, $since_id=0, $max_id=0)
861 $stream = new ConversationNoticeStream($id);
863 return $stream->getNotices($offset, $limit, $since_id, $max_id);
867 * Is this notice part of an active conversation?
869 * @return boolean true if other messages exist in the same
870 * conversation, false if this is the only one
872 function hasConversation()
874 if (!empty($this->conversation)) {
875 $conversation = Notice::conversationStream(
881 if ($conversation->N > 0) {
889 * Grab the earliest notice from this conversation.
891 * @return Notice or null
893 function conversationRoot($profile=-1)
895 // XXX: can this happen?
897 if (empty($this->conversation)) {
901 // Get the current profile if not specified
903 if (is_int($profile) && $profile == -1) {
904 $profile = Profile::current();
907 // If this notice is out of scope, no root for you!
909 if (!$this->inScope($profile)) {
913 // If this isn't a reply to anything, then it's its own
916 if (empty($this->reply_to)) {
920 if (is_null($profile)) {
921 $keypart = sprintf('notice:conversation_root:%d:null', $this->id);
923 $keypart = sprintf('notice:conversation_root:%d:%d',
928 $root = self::cacheGet($keypart);
930 if ($root !== false && $root->inScope($profile)) {
937 $parent = $last->getParent();
938 if ($parent->inScope($profile)) {
942 } catch (Exception $e) {
943 // Latest notice has no parent
945 // No parent, or parent out of scope
950 self::cacheSet($keypart, $root);
956 * Pull up a full list of local recipients who will be getting
957 * this notice in their inbox. Results will be cached, so don't
958 * change the input data wily-nilly!
960 * @param array $groups optional list of Group objects;
961 * if left empty, will be loaded from group_inbox records
962 * @param array $recipient optional list of reply profile ids
963 * if left empty, will be loaded from reply records
964 * @return array associating recipient user IDs with an inbox source constant
966 function whoGets(array $groups=null, array $recipients=null)
968 $c = self::memcache();
971 $ni = $c->get(Cache::key('notice:who_gets:'.$this->id));
977 if (is_null($groups)) {
978 $groups = $this->getGroups();
981 if (is_null($recipients)) {
982 $recipients = $this->getReplies();
985 $users = $this->getSubscribedUsers();
986 $ptags = $this->getProfileTags();
988 // FIXME: kind of ignoring 'transitional'...
989 // we'll probably stop supporting inboxless mode
994 // Give plugins a chance to add folks in at start...
995 if (Event::handle('StartNoticeWhoGets', array($this, &$ni))) {
997 foreach ($users as $id) {
998 $ni[$id] = NOTICE_INBOX_SOURCE_SUB;
1001 foreach ($groups as $group) {
1002 $users = $group->getUserMembers();
1003 foreach ($users as $id) {
1004 if (!array_key_exists($id, $ni)) {
1005 $ni[$id] = NOTICE_INBOX_SOURCE_GROUP;
1010 foreach ($ptags as $ptag) {
1011 $users = $ptag->getUserSubscribers();
1012 foreach ($users as $id) {
1013 if (!array_key_exists($id, $ni)) {
1014 $ni[$id] = NOTICE_INBOX_SOURCE_PROFILE_TAG;
1019 foreach ($recipients as $recipient) {
1020 if (!array_key_exists($recipient, $ni)) {
1021 $ni[$recipient] = NOTICE_INBOX_SOURCE_REPLY;
1025 // Exclude any deleted, non-local, or blocking recipients.
1026 $profile = $this->getProfile();
1027 $originalProfile = null;
1028 if ($this->repeat_of) {
1029 // Check blocks against the original notice's poster as well.
1030 $original = Notice::getKV('id', $this->repeat_of);
1031 if ($original instanceof Notice) {
1032 $originalProfile = $original->getProfile();
1036 foreach ($ni as $id => $source) {
1038 $user = User::getKV('id', $id);
1039 if (!$user instanceof User ||
1040 $user->hasBlocked($profile) ||
1041 ($originalProfile && $user->hasBlocked($originalProfile))) {
1044 } catch (UserNoProfileException $e) {
1045 // User doesn't have a profile; invalid; skip them.
1050 // Give plugins a chance to filter out...
1051 Event::handle('EndNoticeWhoGets', array($this, &$ni));
1055 // XXX: pack this data better
1056 $c->set(Cache::key('notice:who_gets:'.$this->id), $ni);
1063 * Adds this notice to the inboxes of each local user who should receive
1064 * it, based on author subscriptions, group memberships, and @-replies.
1066 * Warning: running a second time currently will make items appear
1067 * multiple times in users' inboxes.
1069 * @fixme make more robust against errors
1070 * @fixme break up massive deliveries to smaller background tasks
1072 * @param array $groups optional list of Group objects;
1073 * if left empty, will be loaded from group_inbox records
1074 * @param array $recipient optional list of reply profile ids
1075 * if left empty, will be loaded from reply records
1077 function addToInboxes(array $groups=null, array $recipients=null)
1079 $ni = $this->whoGets($groups, $recipients);
1081 $ids = array_keys($ni);
1083 // We remove the author (if they're a local user),
1084 // since we'll have already done this in distribute()
1086 $i = array_search($this->profile_id, $ids);
1094 Inbox::bulkInsert($this, $ids);
1099 function getSubscribedUsers()
1103 if(common_config('db','quote_identifiers'))
1104 $user_table = '"user"';
1105 else $user_table = 'user';
1109 'FROM '. $user_table .' JOIN subscription '.
1110 'ON '. $user_table .'.id = subscription.subscriber ' .
1111 'WHERE subscription.subscribed = %d ';
1113 $user->query(sprintf($qry, $this->profile_id));
1117 while ($user->fetch()) {
1126 function getProfileTags()
1128 $profile = $this->getProfile();
1129 $list = $profile->getOtherTags($profile);
1132 while($list->fetch()) {
1133 $ptags[] = clone($list);
1140 * Record this notice to the given group inboxes for delivery.
1141 * Overrides the regular parsing of !group markup.
1143 * @param string $group_ids
1144 * @fixme might prefer URIs as identifiers, as for replies?
1145 * best with generalizations on user_group to support
1146 * remote groups better.
1148 function saveKnownGroups($group_ids)
1150 if (!is_array($group_ids)) {
1151 // TRANS: Server exception thrown when no array is provided to the method saveKnownGroups().
1152 throw new ServerException(_('Bad type provided to saveKnownGroups.'));
1156 foreach (array_unique($group_ids) as $id) {
1157 $group = User_group::getKV('id', $id);
1158 if ($group instanceof User_group) {
1159 common_log(LOG_ERR, "Local delivery to group id $id, $group->nickname");
1160 $result = $this->addToGroupInbox($group);
1162 common_log_db_error($gi, 'INSERT', __FILE__);
1165 if (common_config('group', 'addtag')) {
1166 // we automatically add a tag for every group name, too
1168 $tag = Notice_tag::pkeyGet(array('tag' => common_canonical_tag($group->nickname),
1169 'notice_id' => $this->id));
1171 if (is_null($tag)) {
1172 $this->saveTag($group->nickname);
1176 $groups[] = clone($group);
1178 common_log(LOG_ERR, "Local delivery to group id $id skipped, doesn't exist");
1185 function addToGroupInbox(User_group $group)
1187 $gi = Group_inbox::pkeyGet(array('group_id' => $group->id,
1188 'notice_id' => $this->id));
1190 if (!$gi instanceof Group_inbox) {
1192 $gi = new Group_inbox();
1194 $gi->group_id = $group->id;
1195 $gi->notice_id = $this->id;
1196 $gi->created = $this->created;
1198 $result = $gi->insert();
1201 common_log_db_error($gi, 'INSERT', __FILE__);
1202 // TRANS: Server exception thrown when an update for a group inbox fails.
1203 throw new ServerException(_('Problem saving group inbox.'));
1206 self::blow('user_group:notice_ids:%d', $gi->group_id);
1213 * Save reply records indicating that this notice needs to be
1214 * delivered to the local users with the given URIs.
1216 * Since this is expected to be used when saving foreign-sourced
1217 * messages, we won't deliver to any remote targets as that's the
1218 * source service's responsibility.
1220 * Mail notifications etc will be handled later.
1222 * @param array $uris Array of unique identifier URIs for recipients
1224 function saveKnownReplies(array $uris)
1230 $sender = Profile::getKV($this->profile_id);
1232 foreach (array_unique($uris) as $uri) {
1234 $profile = Profile::fromURI($uri);
1236 if (!$profile instanceof Profile) {
1237 common_log(LOG_WARNING, "Unable to determine profile for URI '$uri'");
1241 if ($profile->hasBlocked($sender)) {
1242 common_log(LOG_INFO, "Not saving reply to profile {$profile->id} ($uri) from sender {$sender->id} because of a block.");
1246 $this->saveReply($profile->id);
1247 self::blow('reply:stream:%d', $profile->id);
1254 * Pull @-replies from this message's content in StatusNet markup format
1255 * and save reply records indicating that this message needs to be
1256 * delivered to those users.
1258 * Mail notifications to local profiles will be sent later.
1260 * @return array of integer profile IDs
1263 function saveReplies()
1265 // Don't save reply data for repeats
1267 if (!empty($this->repeat_of)) {
1271 $sender = Profile::getKV($this->profile_id);
1275 // If it's a reply, save for the replied-to author
1277 $parent = $this->getParent();
1278 $author = $parent->getProfile();
1279 if ($author instanceof Profile) {
1280 $this->saveReply($author->id);
1281 $replied[$author->id] = 1;
1282 self::blow('reply:stream:%d', $author->id);
1284 } catch (Exception $e) {
1285 // Not a reply, since it has no parent!
1288 // @todo ideally this parser information would only
1289 // be calculated once.
1291 $mentions = common_find_mentions($this->content, $this);
1293 // store replied only for first @ (what user/notice what the reply directed,
1294 // we assume first @ is it)
1296 foreach ($mentions as $mention) {
1298 foreach ($mention['mentioned'] as $mentioned) {
1300 // skip if they're already covered
1302 if (!empty($replied[$mentioned->id])) {
1306 // Don't save replies from blocked profile to local user
1308 $mentioned_user = User::getKV('id', $mentioned->id);
1309 if ($mentioned_user instanceof User && $mentioned_user->hasBlocked($sender)) {
1313 $this->saveReply($mentioned->id);
1314 $replied[$mentioned->id] = 1;
1315 self::blow('reply:stream:%d', $mentioned->id);
1319 $recipientIds = array_keys($replied);
1321 return $recipientIds;
1324 function saveReply($profileId)
1326 $reply = new Reply();
1328 $reply->notice_id = $this->id;
1329 $reply->profile_id = $profileId;
1330 $reply->modified = $this->created;
1337 protected $_replies = -1;
1340 * Pull the complete list of @-reply targets for this notice.
1342 * @return array of integer profile ids
1344 function getReplies()
1346 if ($this->_replies != -1) {
1347 return $this->_replies;
1350 $replyMap = Reply::listGet('notice_id', array($this->id));
1354 foreach ($replyMap[$this->id] as $reply) {
1355 $ids[] = $reply->profile_id;
1358 $this->_replies = $ids;
1363 function _setReplies($replies)
1365 $this->_replies = $replies;
1369 * Pull the complete list of @-reply targets for this notice.
1371 * @return array of Profiles
1373 function getReplyProfiles()
1375 $ids = $this->getReplies();
1377 $profiles = Profile::multiGet('id', $ids);
1379 return $profiles->fetchAll();
1383 * Send e-mail notifications to local @-reply targets.
1385 * Replies must already have been saved; this is expected to be run
1386 * from the distrib queue handler.
1388 function sendReplyNotifications()
1390 // Don't send reply notifications for repeats
1392 if (!empty($this->repeat_of)) {
1396 $recipientIds = $this->getReplies();
1398 foreach ($recipientIds as $recipientId) {
1399 $user = User::getKV('id', $recipientId);
1400 if ($user instanceof User) {
1401 mail_notify_attn($user, $this);
1407 * Pull list of groups this notice needs to be delivered to,
1408 * as previously recorded by saveKnownGroups().
1410 * @return array of Group objects
1413 protected $_groups = -1;
1415 function getGroups()
1417 // Don't save groups for repeats
1419 if (!empty($this->repeat_of)) {
1423 if ($this->_groups != -1)
1425 return $this->_groups;
1428 $gis = Group_inbox::listGet('notice_id', array($this->id));
1432 foreach ($gis[$this->id] as $gi)
1434 $ids[] = $gi->group_id;
1437 $groups = User_group::multiGet('id', $ids);
1439 $this->_groups = $groups->fetchAll();
1441 return $this->_groups;
1444 function _setGroups($groups)
1446 $this->_groups = $groups;
1450 * Convert a notice into an activity for export.
1452 * @param User $cur Current user
1454 * @return Activity activity object representing this Notice.
1457 function asActivity($cur=null)
1459 $act = self::cacheGet(Cache::codeKey('notice:as-activity:'.$this->id));
1461 if ($act instanceof Activity) {
1464 $act = new Activity();
1466 if (Event::handle('StartNoticeAsActivity', array($this, &$act))) {
1468 $act->id = $this->uri;
1469 $act->time = strtotime($this->created);
1470 $act->link = $this->bestUrl();
1471 $act->content = common_xml_safe_str($this->rendered);
1473 $profile = $this->getProfile();
1475 $act->actor = ActivityObject::fromProfile($profile);
1476 $act->actor->extra[] = $profile->profileInfo($cur);
1478 $act->verb = $this->verb;
1480 if ($this->repeat_of) {
1481 $repeated = Notice::getKV('id', $this->repeat_of);
1482 if ($repeated instanceof Notice) {
1483 $act->objects[] = $repeated->asActivity($cur);
1486 $act->objects[] = ActivityObject::fromNotice($this);
1489 // XXX: should this be handled by default processing for object entry?
1493 $tags = $this->getTags();
1495 foreach ($tags as $tag) {
1496 $cat = new AtomCategory();
1499 $act->categories[] = $cat;
1503 // XXX: use Atom Media and/or File activity objects instead
1505 $attachments = $this->attachments();
1507 foreach ($attachments as $attachment) {
1508 // Save local attachments
1509 if (!empty($attachment->filename)) {
1510 $act->attachments[] = ActivityObject::fromFile($attachment);
1514 $ctx = new ActivityContext();
1517 $reply = $this->getParent();
1518 $ctx->replyToID = $reply->uri;
1519 $ctx->replyToUrl = $reply->bestUrl();
1520 } catch (Exception $e) {
1521 // This is not a reply to something
1524 $ctx->location = $this->getLocation();
1528 if (!empty($this->conversation)) {
1529 $conv = Conversation::getKV('id', $this->conversation);
1530 if ($conv instanceof Conversation) {
1531 $ctx->conversation = $conv->uri;
1535 $reply_ids = $this->getReplies();
1537 foreach ($reply_ids as $id) {
1538 $rprofile = Profile::getKV('id', $id);
1539 if ($rprofile instanceof Profile) {
1540 $ctx->attention[$rprofile->getUri()] = ActivityObject::PERSON;
1544 $groups = $this->getGroups();
1546 foreach ($groups as $group) {
1547 $ctx->attention[$group->getUri()] = ActivityObject::GROUP;
1550 switch ($this->scope) {
1551 case Notice::PUBLIC_SCOPE:
1552 $ctx->attention[ActivityContext::ATTN_PUBLIC] = ActivityObject::COLLECTION;
1554 case Notice::FOLLOWER_SCOPE:
1555 $surl = common_local_url("subscribers", array('nickname' => $profile->nickname));
1556 $ctx->attention[$surl] = ActivityObject::COLLECTION;
1560 $act->context = $ctx;
1562 $source = $this->getSource();
1564 if ($source instanceof Notice_source) {
1565 $act->generator = ActivityObject::fromNoticeSource($source);
1570 $atom_feed = $profile->getAtomFeed();
1572 if (!empty($atom_feed)) {
1574 $act->source = new ActivitySource();
1576 // XXX: we should store the actual feed ID
1578 $act->source->id = $atom_feed;
1580 // XXX: we should store the actual feed title
1582 $act->source->title = $profile->getBestName();
1584 $act->source->links['alternate'] = $profile->profileurl;
1585 $act->source->links['self'] = $atom_feed;
1587 $act->source->icon = $profile->avatarUrl(AVATAR_PROFILE_SIZE);
1589 $notice = $profile->getCurrentNotice();
1591 if ($notice instanceof Notice) {
1592 $act->source->updated = self::utcDate($notice->created);
1595 $user = User::getKV('id', $profile->id);
1597 if ($user instanceof User) {
1598 $act->source->links['license'] = common_config('license', 'url');
1602 if ($this->isLocal()) {
1603 $act->selfLink = common_local_url('ApiStatusesShow', array('id' => $this->id,
1604 'format' => 'atom'));
1605 $act->editLink = $act->selfLink;
1608 Event::handle('EndNoticeAsActivity', array($this, &$act));
1611 self::cacheSet(Cache::codeKey('notice:as-activity:'.$this->id), $act);
1616 // This has gotten way too long. Needs to be sliced up into functional bits
1617 // or ideally exported to a utility class.
1619 function asAtomEntry($namespace=false,
1624 $act = $this->asActivity($cur);
1625 $act->extra[] = $this->noticeInfo($cur);
1626 return $act->asString($namespace, $author, $source);
1630 * Extra notice info for atom entries
1632 * Clients use some extra notice info in the atom stream.
1633 * This gives it to them.
1635 * @param User $cur Current user
1637 * @return array representation of <statusnet:notice_info> element
1640 function noticeInfo($cur)
1642 // local notice ID (useful to clients for ordering)
1644 $noticeInfoAttr = array('local_id' => $this->id);
1648 $ns = $this->getSource();
1650 if ($ns instanceof Notice_source) {
1651 $noticeInfoAttr['source'] = $ns->code;
1652 if (!empty($ns->url)) {
1653 $noticeInfoAttr['source_link'] = $ns->url;
1654 if (!empty($ns->name)) {
1655 $noticeInfoAttr['source'] = '<a href="'
1656 . htmlspecialchars($ns->url)
1657 . '" rel="nofollow">'
1658 . htmlspecialchars($ns->name)
1664 // favorite and repeated
1667 $cp = $cur->getProfile();
1668 $noticeInfoAttr['favorite'] = ($cp->hasFave($this)) ? "true" : "false";
1669 $noticeInfoAttr['repeated'] = ($cp->hasRepeated($this)) ? "true" : "false";
1672 if (!empty($this->repeat_of)) {
1673 $noticeInfoAttr['repeat_of'] = $this->repeat_of;
1676 return array('statusnet:notice_info', $noticeInfoAttr, null);
1680 * Returns an XML string fragment with a reference to a notice as an
1681 * Activity Streams noun object with the given element type.
1683 * Assumes that 'activity' namespace has been previously defined.
1685 * @param string $element one of 'subject', 'object', 'target'
1689 function asActivityNoun($element)
1691 $noun = ActivityObject::fromNotice($this);
1692 return $noun->asString('activity:' . $element);
1697 if (!empty($this->url)) {
1699 } else if (!empty($this->uri) && preg_match('/^https?:/', $this->uri)) {
1702 return common_local_url('shownotice',
1703 array('notice' => $this->id));
1709 * Determine which notice, if any, a new notice is in reply to.
1711 * For conversation tracking, we try to see where this notice fits
1712 * in the tree. Rough algorithm is:
1714 * if (reply_to is set and valid) {
1716 * } else if ((source not API or Web) and (content starts with "T NAME" or "@name ")) {
1717 * return ID of last notice by initial @name in content;
1720 * Note that all @nickname instances will still be used to save "reply" records,
1721 * so the notice shows up in the mentioned users' "replies" tab.
1723 * @param integer $reply_to ID passed in by Web or API
1724 * @param integer $profile_id ID of author
1725 * @param string $source Source tag, like 'web' or 'gwibber'
1726 * @param string $content Final notice content
1728 * @return integer ID of replied-to notice, or null for not a reply.
1731 static function getReplyTo($reply_to, $profile_id, $source, $content)
1733 static $lb = array('xmpp', 'mail', 'sms', 'omb');
1735 // If $reply_to is specified, we check that it exists, and then
1736 // return it if it does
1738 if (!empty($reply_to)) {
1739 $reply_notice = Notice::getKV('id', $reply_to);
1740 if ($reply_notice instanceof Notice) {
1741 return $reply_notice;
1745 // If it's not a "low bandwidth" source (one where you can't set
1746 // a reply_to argument), we return. This is mostly web and API
1749 if (!in_array($source, $lb)) {
1753 // Is there an initial @ or T?
1755 if (preg_match('/^T ([A-Z0-9]{1,64}) /', $content, $match) ||
1756 preg_match('/^@([a-z0-9]{1,64})\s+/', $content, $match)) {
1757 $nickname = common_canonical_nickname($match[1]);
1762 // Figure out who that is.
1764 $sender = Profile::getKV('id', $profile_id);
1765 if (!$sender instanceof Profile) {
1769 $recipient = common_relative_profile($sender, $nickname, common_sql_now());
1771 if (!$recipient instanceof Profile) {
1775 // Get their last notice
1777 $last = $recipient->getCurrentNotice();
1779 if ($last instanceof Notice) {
1786 static function maxContent()
1788 $contentlimit = common_config('notice', 'contentlimit');
1789 // null => use global limit (distinct from 0!)
1790 if (is_null($contentlimit)) {
1791 $contentlimit = common_config('site', 'textlimit');
1793 return $contentlimit;
1796 static function contentTooLong($content)
1798 $contentlimit = self::maxContent();
1799 return ($contentlimit > 0 && !empty($content) && (mb_strlen($content) > $contentlimit));
1802 function getLocation()
1806 if (!empty($this->location_id) && !empty($this->location_ns)) {
1807 $location = Location::fromId($this->location_id, $this->location_ns);
1810 if (is_null($location)) { // no ID, or Location::fromId() failed
1811 if (!empty($this->lat) && !empty($this->lon)) {
1812 $location = Location::fromLatLon($this->lat, $this->lon);
1820 * Convenience function for posting a repeat of an existing message.
1822 * @param int $repeater_id: profile ID of user doing the repeat
1823 * @param string $source: posting source key, eg 'web', 'api', etc
1826 * @throws Exception on failure or permission problems
1828 function repeat($repeater_id, $source)
1830 $author = Profile::getKV('id', $this->profile_id);
1832 // TRANS: Message used to repeat a notice. RT is the abbreviation of 'retweet'.
1833 // TRANS: %1$s is the repeated user's name, %2$s is the repeated notice.
1834 $content = sprintf(_('RT @%1$s %2$s'),
1838 $maxlen = common_config('site', 'textlimit');
1839 if ($maxlen > 0 && mb_strlen($content) > $maxlen) {
1840 // Web interface and current Twitter API clients will
1841 // pull the original notice's text, but some older
1842 // clients and RSS/Atom feeds will see this trimmed text.
1844 // Unfortunately this is likely to lose tags or URLs
1845 // at the end of long notices.
1846 $content = mb_substr($content, 0, $maxlen - 4) . ' ...';
1849 // Scope is same as this one's
1851 return self::saveNew($repeater_id,
1854 array('repeat_of' => $this->id,
1855 'scope' => $this->scope));
1858 // These are supposed to be in chron order!
1860 function repeatStream($limit=100)
1862 $cache = Cache::instance();
1864 if (empty($cache)) {
1865 $ids = $this->_repeatStreamDirect($limit);
1867 $idstr = $cache->get(Cache::key('notice:repeats:'.$this->id));
1868 if ($idstr !== false) {
1869 if (empty($idstr)) {
1872 $ids = explode(',', $idstr);
1875 $ids = $this->_repeatStreamDirect(100);
1876 $cache->set(Cache::key('notice:repeats:'.$this->id), implode(',', $ids));
1879 // We do a max of 100, so slice down to limit
1880 $ids = array_slice($ids, 0, $limit);
1884 return NoticeStream::getStreamByIds($ids);
1887 function _repeatStreamDirect($limit)
1889 $notice = new Notice();
1891 $notice->selectAdd(); // clears it
1892 $notice->selectAdd('id');
1894 $notice->repeat_of = $this->id;
1896 $notice->orderBy('created, id'); // NB: asc!
1898 if (!is_null($limit)) {
1899 $notice->limit(0, $limit);
1902 return $notice->fetchAll('id');
1905 function locationOptions($lat, $lon, $location_id, $location_ns, $profile = null)
1909 if (!empty($location_id) && !empty($location_ns)) {
1910 $options['location_id'] = $location_id;
1911 $options['location_ns'] = $location_ns;
1913 $location = Location::fromId($location_id, $location_ns);
1915 if ($location instanceof Location) {
1916 $options['lat'] = $location->lat;
1917 $options['lon'] = $location->lon;
1920 } else if (!empty($lat) && !empty($lon)) {
1921 $options['lat'] = $lat;
1922 $options['lon'] = $lon;
1924 $location = Location::fromLatLon($lat, $lon);
1926 if ($location instanceof Location) {
1927 $options['location_id'] = $location->location_id;
1928 $options['location_ns'] = $location->location_ns;
1930 } else if (!empty($profile)) {
1931 if (isset($profile->lat) && isset($profile->lon)) {
1932 $options['lat'] = $profile->lat;
1933 $options['lon'] = $profile->lon;
1936 if (isset($profile->location_id) && isset($profile->location_ns)) {
1937 $options['location_id'] = $profile->location_id;
1938 $options['location_ns'] = $profile->location_ns;
1945 function clearReplies()
1947 $replyNotice = new Notice();
1948 $replyNotice->reply_to = $this->id;
1950 //Null any notices that are replies to this notice
1952 if ($replyNotice->find()) {
1953 while ($replyNotice->fetch()) {
1954 $orig = clone($replyNotice);
1955 $replyNotice->reply_to = null;
1956 $replyNotice->update($orig);
1962 $reply = new Reply();
1963 $reply->notice_id = $this->id;
1965 if ($reply->find()) {
1966 while($reply->fetch()) {
1967 self::blow('reply:stream:%d', $reply->profile_id);
1975 function clearFiles()
1977 $f2p = new File_to_post();
1979 $f2p->post_id = $this->id;
1982 while ($f2p->fetch()) {
1986 // FIXME: decide whether to delete File objects
1987 // ...and related (actual) files
1990 function clearRepeats()
1992 $repeatNotice = new Notice();
1993 $repeatNotice->repeat_of = $this->id;
1995 //Null any notices that are repeats of this notice
1997 if ($repeatNotice->find()) {
1998 while ($repeatNotice->fetch()) {
1999 $orig = clone($repeatNotice);
2000 $repeatNotice->repeat_of = null;
2001 $repeatNotice->update($orig);
2006 function clearFaves()
2009 $fave->notice_id = $this->id;
2011 if ($fave->find()) {
2012 while ($fave->fetch()) {
2013 self::blow('fave:ids_by_user_own:%d', $fave->user_id);
2014 self::blow('fave:ids_by_user_own:%d;last', $fave->user_id);
2015 self::blow('fave:ids_by_user:%d', $fave->user_id);
2016 self::blow('fave:ids_by_user:%d;last', $fave->user_id);
2024 function clearTags()
2026 $tag = new Notice_tag();
2027 $tag->notice_id = $this->id;
2030 while ($tag->fetch()) {
2031 self::blow('profile:notice_ids_tagged:%d:%s', $this->profile_id, Cache::keyize($tag->tag));
2032 self::blow('profile:notice_ids_tagged:%d:%s;last', $this->profile_id, Cache::keyize($tag->tag));
2033 self::blow('notice_tag:notice_ids:%s', Cache::keyize($tag->tag));
2034 self::blow('notice_tag:notice_ids:%s;last', Cache::keyize($tag->tag));
2042 function clearGroupInboxes()
2044 $gi = new Group_inbox();
2046 $gi->notice_id = $this->id;
2049 while ($gi->fetch()) {
2050 self::blow('user_group:notice_ids:%d', $gi->group_id);
2058 function distribute()
2060 // We always insert for the author so they don't
2062 Event::handle('StartNoticeDistribute', array($this));
2064 $user = User::getKV('id', $this->profile_id);
2065 if ($user instanceof User) {
2066 Inbox::insertNotice($this, $user->id);
2069 if (common_config('queue', 'inboxes')) {
2070 // If there's a failure, we want to _force_
2071 // distribution at this point.
2073 $qm = QueueManager::get();
2074 $qm->enqueue($this, 'distrib');
2075 } catch (Exception $e) {
2076 // If the exception isn't transient, this
2077 // may throw more exceptions as DQH does
2078 // its own enqueueing. So, we ignore them!
2080 $handler = new DistribQueueHandler();
2081 $handler->handle($this);
2082 } catch (Exception $e) {
2083 common_log(LOG_ERR, "emergency redistribution resulted in " . $e->getMessage());
2085 // Re-throw so somebody smarter can handle it.
2089 $handler = new DistribQueueHandler();
2090 $handler->handle($this);
2096 $result = parent::insert();
2098 if ($result !== false) {
2099 // Profile::hasRepeated() abuses pkeyGet(), so we
2100 // have to clear manually
2101 if (!empty($this->repeat_of)) {
2102 $c = self::memcache();
2104 $ck = self::multicacheKey('Notice',
2105 array('profile_id' => $this->profile_id,
2106 'repeat_of' => $this->repeat_of));
2116 * Get the source of the notice
2118 * @return Notice_source $ns A notice source object. 'code' is the only attribute
2119 * guaranteed to be populated.
2121 function getSource()
2123 $ns = new Notice_source();
2124 if (!empty($this->source)) {
2125 switch ($this->source) {
2132 $ns->code = $this->source;
2135 $ns = Notice_source::getKV($this->source);
2137 $ns = new Notice_source();
2138 $ns->code = $this->source;
2139 $app = Oauth_application::getKV('name', $this->source);
2141 $ns->name = $app->name;
2142 $ns->url = $app->source_url;
2152 * Determine whether the notice was locally created
2154 * @return boolean locality
2157 public function isLocal()
2159 return ($this->is_local == Notice::LOCAL_PUBLIC ||
2160 $this->is_local == Notice::LOCAL_NONPUBLIC);
2164 * Get the list of hash tags saved with this notice.
2166 * @return array of strings
2168 public function getTags()
2172 $keypart = sprintf('notice:tags:%d', $this->id);
2174 $tagstr = self::cacheGet($keypart);
2176 if ($tagstr !== false) {
2177 $tags = explode(',', $tagstr);
2179 $tag = new Notice_tag();
2180 $tag->notice_id = $this->id;
2182 while ($tag->fetch()) {
2183 $tags[] = $tag->tag;
2186 self::cacheSet($keypart, implode(',', $tags));
2192 static private function utcDate($dt)
2194 $dateStr = date('d F Y H:i:s', strtotime($dt));
2195 $d = new DateTime($dateStr, new DateTimeZone('UTC'));
2196 return $d->format(DATE_W3C);
2200 * Look up the creation timestamp for a given notice ID, even
2201 * if it's been deleted.
2204 * @return mixed string recorded creation timestamp, or false if can't be found
2206 public static function getAsTimestamp($id)
2212 $notice = Notice::getKV('id', $id);
2214 return $notice->created;
2217 $deleted = Deleted_notice::getKV('id', $id);
2219 return $deleted->created;
2226 * Build an SQL 'where' fragment for timestamp-based sorting from a since_id
2227 * parameter, matching notices posted after the given one (exclusive).
2229 * If the referenced notice can't be found, will return false.
2232 * @param string $idField
2233 * @param string $createdField
2234 * @return mixed string or false if no match
2236 public static function whereSinceId($id, $idField='id', $createdField='created')
2238 $since = Notice::getAsTimestamp($id);
2240 return sprintf("($createdField = '%s' and $idField > %d) or ($createdField > '%s')", $since, $id, $since);
2246 * Build an SQL 'where' fragment for timestamp-based sorting from a since_id
2247 * parameter, matching notices posted after the given one (exclusive), and
2248 * if necessary add it to the data object's query.
2250 * @param DB_DataObject $obj
2252 * @param string $idField
2253 * @param string $createdField
2254 * @return mixed string or false if no match
2256 public static function addWhereSinceId(DB_DataObject $obj, $id, $idField='id', $createdField='created')
2258 $since = self::whereSinceId($id, $idField, $createdField);
2260 $obj->whereAdd($since);
2265 * Build an SQL 'where' fragment for timestamp-based sorting from a max_id
2266 * parameter, matching notices posted before the given one (inclusive).
2268 * If the referenced notice can't be found, will return false.
2271 * @param string $idField
2272 * @param string $createdField
2273 * @return mixed string or false if no match
2275 public static function whereMaxId($id, $idField='id', $createdField='created')
2277 $max = Notice::getAsTimestamp($id);
2279 return sprintf("($createdField < '%s') or ($createdField = '%s' and $idField <= %d)", $max, $max, $id);
2285 * Build an SQL 'where' fragment for timestamp-based sorting from a max_id
2286 * parameter, matching notices posted before the given one (inclusive), and
2287 * if necessary add it to the data object's query.
2289 * @param DB_DataObject $obj
2291 * @param string $idField
2292 * @param string $createdField
2293 * @return mixed string or false if no match
2295 public static function addWhereMaxId(DB_DataObject $obj, $id, $idField='id', $createdField='created')
2297 $max = self::whereMaxId($id, $idField, $createdField);
2299 $obj->whereAdd($max);
2305 if (common_config('public', 'localonly')) {
2306 return ($this->is_local == Notice::LOCAL_PUBLIC);
2308 return (($this->is_local != Notice::LOCAL_NONPUBLIC) &&
2309 ($this->is_local != Notice::GATEWAY));
2314 * Check that the given profile is allowed to read, respond to, or otherwise
2315 * act on this notice.
2317 * The $scope member is a bitmask of scopes, representing a logical AND of the
2318 * scope requirement. So, 0x03 (Notice::ADDRESSEE_SCOPE | Notice::SITE_SCOPE) means
2319 * "only visible to people who are mentioned in the notice AND are users on this site."
2320 * Users on the site who are not mentioned in the notice will not be able to see the
2323 * @param Profile $profile The profile to check; pass null to check for public/unauthenticated users.
2325 * @return boolean whether the profile is in the notice's scope
2327 function inScope($profile)
2329 if (is_null($profile)) {
2330 $keypart = sprintf('notice:in-scope-for:%d:null', $this->id);
2332 $keypart = sprintf('notice:in-scope-for:%d:%d', $this->id, $profile->id);
2335 $result = self::cacheGet($keypart);
2337 if ($result === false) {
2339 if (Event::handle('StartNoticeInScope', array($this, $profile, &$bResult))) {
2340 $bResult = $this->_inScope($profile);
2341 Event::handle('EndNoticeInScope', array($this, $profile, &$bResult));
2343 $result = ($bResult) ? 1 : 0;
2344 self::cacheSet($keypart, $result, 0, 300);
2347 return ($result == 1) ? true : false;
2350 protected function _inScope($profile)
2352 if (!is_null($this->scope)) {
2353 $scope = $this->scope;
2355 $scope = self::defaultScope();
2358 // If there's no scope, anyone (even anon) is in scope.
2360 if ($scope == 0) { // Not private
2362 return !$this->isHiddenSpam($profile);
2364 } else { // Private, somehow
2366 // If there's scope, anon cannot be in scope
2368 if (empty($profile)) {
2372 // Author is always in scope
2374 if ($this->profile_id == $profile->id) {
2378 // Only for users on this site
2380 if (($scope & Notice::SITE_SCOPE) && !$profile->isLocal()) {
2384 // Only for users mentioned in the notice
2386 if ($scope & Notice::ADDRESSEE_SCOPE) {
2388 $reply = Reply::pkeyGet(array('notice_id' => $this->id,
2389 'profile_id' => $profile->id));
2391 if (!$reply instanceof Reply) {
2396 // Only for members of the given group
2398 if ($scope & Notice::GROUP_SCOPE) {
2400 // XXX: just query for the single membership
2402 $groups = $this->getGroups();
2406 foreach ($groups as $group) {
2407 if ($profile->isMember($group)) {
2418 // Only for followers of the author
2422 if ($scope & Notice::FOLLOWER_SCOPE) {
2425 $author = $this->getProfile();
2426 } catch (Exception $e) {
2430 if (!Subscription::exists($profile, $author)) {
2435 return !$this->isHiddenSpam($profile);
2439 function isHiddenSpam($profile) {
2441 // Hide posts by silenced users from everyone but moderators.
2443 if (common_config('notice', 'hidespam')) {
2446 $author = $this->getProfile();
2447 } catch(Exception $e) {
2448 // If we can't get an author, keep it hidden.
2449 // XXX: technically not spam, but, whatever.
2453 if ($author->hasRole(Profile_role::SILENCED)) {
2454 if (!$profile instanceof Profile || (($profile->id !== $author->id) && (!$profile->hasRight(Right::REVIEWSPAM)))) {
2463 public function getParent()
2465 $parent = Notice::getKV('id', $this->reply_to);
2467 if (!$parent instanceof Notice) {
2468 throw new ServerException('Notice has no parent');
2475 * Magic function called at serialize() time.
2477 * We use this to drop a couple process-specific references
2478 * from DB_DataObject which can cause trouble in future
2481 * @return array of variable names to include in serialization.
2486 $vars = parent::__sleep();
2487 $skip = array('_profile', '_groups', '_attachments', '_faves', '_replies', '_repeats');
2488 return array_diff($vars, $skip);
2491 static function defaultScope()
2493 $scope = common_config('notice', 'defaultscope');
2494 if (is_null($scope)) {
2495 if (common_config('site', 'private')) {
2504 static function fillProfiles($notices)
2506 $map = self::getProfiles($notices);
2508 foreach ($notices as $notice) {
2509 if (array_key_exists($notice->profile_id, $map)) {
2510 $notice->_setProfile($map[$notice->profile_id]);
2514 return array_values($map);
2517 static function getProfiles(&$notices)
2520 foreach ($notices as $notice) {
2521 $ids[] = $notice->profile_id;
2524 $ids = array_unique($ids);
2526 return Profile::pivotGet('id', $ids);
2529 static function fillGroups(&$notices)
2531 $ids = self::_idsOf($notices);
2533 $gis = Group_inbox::listGet('notice_id', $ids);
2537 foreach ($gis as $id => $gi)
2541 $gids[] = $g->group_id;
2545 $gids = array_unique($gids);
2547 $group = User_group::pivotGet('id', $gids);
2549 foreach ($notices as $notice)
2552 $gi = $gis[$notice->id];
2553 foreach ($gi as $g) {
2554 $grps[] = $group[$g->group_id];
2556 $notice->_setGroups($grps);
2560 static function _idsOf(&$notices)
2563 foreach ($notices as $notice) {
2564 $ids[] = $notice->id;
2566 $ids = array_unique($ids);
2570 static function fillAttachments(&$notices)
2572 $ids = self::_idsOf($notices);
2574 $f2pMap = File_to_post::listGet('post_id', $ids);
2578 foreach ($f2pMap as $noticeId => $f2ps) {
2579 foreach ($f2ps as $f2p) {
2580 $fileIds[] = $f2p->file_id;
2584 $fileIds = array_unique($fileIds);
2586 $fileMap = File::pivotGet('id', $fileIds);
2588 foreach ($notices as $notice)
2591 $f2ps = $f2pMap[$notice->id];
2592 foreach ($f2ps as $f2p) {
2593 $files[] = $fileMap[$f2p->file_id];
2595 $notice->_setAttachments($files);
2602 * All faves of this notice
2604 * @return array Array of Fave objects
2609 if (isset($this->_faves) && is_array($this->_faves)) {
2610 return $this->_faves;
2612 $faveMap = Fave::listGet('notice_id', array($this->id));
2613 $this->_faves = $faveMap[$this->id];
2614 return $this->_faves;
2617 function _setFaves($faves)
2619 $this->_faves = $faves;
2622 static function fillFaves(&$notices)
2624 $ids = self::_idsOf($notices);
2625 $faveMap = Fave::listGet('notice_id', $ids);
2628 foreach ($faveMap as $id => $faves) {
2629 $cnt += count($faves);
2630 if (count($faves) > 0) {
2634 foreach ($notices as $notice) {
2635 $faves = $faveMap[$notice->id];
2636 $notice->_setFaves($faves);
2640 static function fillReplies(&$notices)
2642 $ids = self::_idsOf($notices);
2643 $replyMap = Reply::listGet('notice_id', $ids);
2644 foreach ($notices as $notice) {
2645 $replies = $replyMap[$notice->id];
2647 foreach ($replies as $reply) {
2648 $ids[] = $reply->profile_id;
2650 $notice->_setReplies($ids);
2654 protected $_repeats;
2656 function getRepeats()
2658 if (isset($this->_repeats) && is_array($this->_repeats)) {
2659 return $this->_repeats;
2661 $repeatMap = Notice::listGet('repeat_of', array($this->id));
2662 $this->_repeats = $repeatMap[$this->id];
2663 return $this->_repeats;
2666 function _setRepeats($repeats)
2668 $this->_repeats = $repeats;
2671 static function fillRepeats(&$notices)
2673 $ids = self::_idsOf($notices);
2674 $repeatMap = Notice::listGet('repeat_of', $ids);
2675 foreach ($notices as $notice) {
2676 $repeats = $repeatMap[$notice->id];
2677 $notice->_setRepeats($repeats);