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 return $this->_profile;
154 public function _setProfile(Profile $profile=null)
156 if (!$profile instanceof Profile) {
157 throw new NoProfileException($this->profile_id);
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 static function getByUri($uri)
221 $notice = new Notice();
223 if (!$notice->find(true)) {
224 throw new NoResultException($notice);
230 * Extract #hashtags from this notice's content and save them to the database.
234 /* extract all #hastags */
235 $count = preg_match_all('/(?:^|\s)#([\pL\pN_\-\.]{1,64})/u', strtolower($this->content), $match);
240 /* Add them to the database */
241 return $this->saveKnownTags($match[1]);
245 * Record the given set of hash tags in the db for this notice.
246 * Given tag strings will be normalized and checked for dupes.
248 function saveKnownTags($hashtags)
250 //turn each into their canonical tag
251 //this is needed to remove dupes before saving e.g. #hash.tag = #hashtag
252 for($i=0; $i<count($hashtags); $i++) {
253 /* elide characters we don't want in the tag */
254 $hashtags[$i] = common_canonical_tag($hashtags[$i]);
257 foreach(array_unique($hashtags) as $hashtag) {
258 $this->saveTag($hashtag);
259 self::blow('profile:notice_ids_tagged:%d:%s', $this->profile_id, $hashtag);
265 * Record a single hash tag as associated with this notice.
266 * Tag format and uniqueness must be validated by caller.
268 function saveTag($hashtag)
270 $tag = new Notice_tag();
271 $tag->notice_id = $this->id;
272 $tag->tag = $hashtag;
273 $tag->created = $this->created;
274 $id = $tag->insert();
277 // TRANS: Server exception. %s are the error details.
278 throw new ServerException(sprintf(_('Database error inserting hashtag: %s.'),
279 $last_error->message));
283 // if it's saved, blow its cache
284 $tag->blowCache(false);
288 * Save a new notice and push it out to subscribers' inboxes.
289 * Poster's permissions are checked before sending.
291 * @param int $profile_id Profile ID of the poster
292 * @param string $content source message text; links may be shortened
293 * per current user's preference
294 * @param string $source source key ('web', 'api', etc)
295 * @param array $options Associative array of optional properties:
296 * string 'created' timestamp of notice; defaults to now
297 * int 'is_local' source/gateway ID, one of:
298 * Notice::LOCAL_PUBLIC - Local, ok to appear in public timeline
299 * Notice::REMOTE - Sent from a remote service;
300 * hide from public timeline but show in
301 * local "and friends" timelines
302 * Notice::LOCAL_NONPUBLIC - Local, but hide from public timeline
303 * Notice::GATEWAY - From another non-OStatus service;
304 * will not appear in public views
305 * float 'lat' decimal latitude for geolocation
306 * float 'lon' decimal longitude for geolocation
307 * int 'location_id' geoname identifier
308 * int 'location_ns' geoname namespace to interpret location_id
309 * int 'reply_to'; notice ID this is a reply to
310 * int 'repeat_of'; notice ID this is a repeat of
311 * string 'uri' unique ID for notice; defaults to local notice URL
312 * string 'url' permalink to notice; defaults to local notice URL
313 * string 'rendered' rendered HTML version of content
314 * array 'replies' list of profile URIs for reply delivery in
315 * place of extracting @-replies from content.
316 * array 'groups' list of group IDs to deliver to, in place of
317 * extracting ! tags from content
318 * array 'tags' list of hashtag strings to save with the notice
319 * in place of extracting # tags from content
320 * array 'urls' list of attached/referred URLs to save with the
321 * notice in place of extracting links from content
322 * boolean 'distribute' whether to distribute the notice, default true
323 * string 'object_type' URL of the associated object type (default ActivityObject::NOTE)
324 * string 'verb' URL of the associated verb (default ActivityVerb::POST)
325 * int 'scope' Scope bitmask; default to SITE_SCOPE on private sites, 0 otherwise
327 * @fixme tag override
330 * @throws ClientException
332 static function saveNew($profile_id, $content, $source, array $options=null) {
333 $defaults = array('uri' => null,
338 'distribute' => true,
339 'object_type' => null,
342 if (!empty($options) && is_array($options)) {
343 $options = array_merge($defaults, $options);
349 if (!isset($is_local)) {
350 $is_local = Notice::LOCAL_PUBLIC;
353 $profile = Profile::getKV('id', $profile_id);
354 if (!$profile instanceof Profile) {
355 // TRANS: Client exception thrown when trying to save a notice for an unknown user.
356 throw new ClientException(_('Problem saving notice. Unknown user.'));
359 $user = User::getKV('id', $profile_id);
360 if ($user instanceof User) {
361 // Use the local user's shortening preferences, if applicable.
362 $final = $user->shortenLinks($content);
364 $final = common_shorten_links($content);
367 if (Notice::contentTooLong($final)) {
368 // TRANS: Client exception thrown if a notice contains too many characters.
369 throw new ClientException(_('Problem saving notice. Too long.'));
372 if (common_config('throttle', 'enabled') && !Notice::checkEditThrottle($profile_id)) {
373 common_log(LOG_WARNING, 'Excessive posting by profile #' . $profile_id . '; throttled.');
374 // TRANS: Client exception thrown when a user tries to post too many notices in a given time frame.
375 throw new ClientException(_('Too many notices too fast; take a breather '.
376 'and post again in a few minutes.'));
379 if (common_config('site', 'dupelimit') > 0 && !Notice::checkDupes($profile_id, $final)) {
380 common_log(LOG_WARNING, 'Dupe posting by profile #' . $profile_id . '; throttled.');
381 // TRANS: Client exception thrown when a user tries to post too many duplicate notices in a given time frame.
382 throw new ClientException(_('Too many duplicate messages too quickly;'.
383 ' take a breather and post again in a few minutes.'));
386 if (!$profile->hasRight(Right::NEWNOTICE)) {
387 common_log(LOG_WARNING, "Attempted post from user disallowed to post: " . $profile->nickname);
389 // TRANS: Client exception thrown when a user tries to post while being banned.
390 throw new ClientException(_('You are banned from posting notices on this site.'), 403);
393 $notice = new Notice();
394 $notice->profile_id = $profile_id;
396 $autosource = common_config('public', 'autosource');
398 // Sandboxed are non-false, but not 1, either
400 if (!$profile->hasRight(Right::PUBLICNOTICE) ||
401 ($source && $autosource && in_array($source, $autosource))) {
402 $notice->is_local = Notice::LOCAL_NONPUBLIC;
404 $notice->is_local = $is_local;
407 if (!empty($created)) {
408 $notice->created = $created;
410 $notice->created = common_sql_now();
413 $notice->content = $final;
415 $notice->source = $source;
419 // Get the groups here so we can figure out replies and such
420 if (!isset($groups)) {
421 $groups = User_group::idsFromText($notice->content, $profile);
426 // Handle repeat case
428 if (isset($repeat_of)) {
430 // Check for a private one
432 $repeat = Notice::getKV('id', $repeat_of);
434 if (!($repeat instanceof Notice)) {
435 // TRANS: Client exception thrown in notice when trying to repeat a missing or deleted notice.
436 throw new ClientException(_('Cannot repeat; original notice is missing or deleted.'));
439 if ($profile->id == $repeat->profile_id) {
440 // TRANS: Client error displayed when trying to repeat an own notice.
441 throw new ClientException(_('You cannot repeat your own notice.'));
444 if ($repeat->scope != Notice::SITE_SCOPE &&
445 $repeat->scope != Notice::PUBLIC_SCOPE) {
446 // TRANS: Client error displayed when trying to repeat a non-public notice.
447 throw new ClientException(_('Cannot repeat a private notice.'), 403);
450 if (!$repeat->inScope($profile)) {
451 // The generic checks above should cover this, but let's be sure!
452 // TRANS: Client error displayed when trying to repeat a notice you cannot access.
453 throw new ClientException(_('Cannot repeat a notice you cannot read.'), 403);
456 if ($profile->hasRepeated($repeat)) {
457 // TRANS: Client error displayed when trying to repeat an already repeated notice.
458 throw new ClientException(_('You already repeated that notice.'));
461 $notice->repeat_of = $repeat_of;
463 $reply = self::getReplyTo($reply_to, $profile_id, $source, $final);
465 if (!empty($reply)) {
467 if (!$reply->inScope($profile)) {
468 // TRANS: Client error displayed when trying to reply to a notice a the target has no access to.
469 // TRANS: %1$s is a user nickname, %2$d is a notice ID (number).
470 throw new ClientException(sprintf(_('%1$s has no access to notice %2$d.'),
471 $profile->nickname, $reply->id), 403);
474 $notice->reply_to = $reply->id;
475 $notice->conversation = $reply->conversation;
477 // If the original is private to a group, and notice has no group specified,
478 // make it to the same group(s)
480 if (empty($groups) && ($reply->scope & Notice::GROUP_SCOPE)) {
482 $replyGroups = $reply->getGroups();
483 foreach ($replyGroups as $group) {
484 if ($profile->isMember($group)) {
485 $groups[] = $group->id;
494 if (!empty($lat) && !empty($lon)) {
499 if (!empty($location_ns) && !empty($location_id)) {
500 $notice->location_id = $location_id;
501 $notice->location_ns = $location_ns;
504 if (!empty($rendered)) {
505 $notice->rendered = $rendered;
507 $notice->rendered = common_render_content($final, $notice);
511 if (!empty($notice->repeat_of)) {
512 $notice->verb = ActivityVerb::SHARE;
513 $notice->object_type = ActivityObject::ACTIVITY;
515 $notice->verb = ActivityVerb::POST;
518 $notice->verb = $verb;
521 if (empty($object_type)) {
522 $notice->object_type = (empty($notice->reply_to)) ? ActivityObject::NOTE : ActivityObject::COMMENT;
524 $notice->object_type = $object_type;
527 if (is_null($scope)) { // 0 is a valid value
528 if (!empty($reply)) {
529 $notice->scope = $reply->scope;
531 $notice->scope = self::defaultScope();
534 $notice->scope = $scope;
537 // For private streams
540 $user = $profile->getUser();
542 if ($user->private_stream &&
543 ($notice->scope == Notice::PUBLIC_SCOPE ||
544 $notice->scope == Notice::SITE_SCOPE)) {
545 $notice->scope |= Notice::FOLLOWER_SCOPE;
547 } catch (NoSuchUserException $e) {
548 // Cannot handle private streams for remote profiles
551 // Force the scope for private groups
553 foreach ($groups as $groupId) {
554 $group = User_group::getKV('id', $groupId);
555 if ($group instanceof User_group) {
556 if ($group->force_scope) {
557 $notice->scope |= Notice::GROUP_SCOPE;
563 if (Event::handle('StartNoticeSave', array(&$notice))) {
565 // XXX: some of these functions write to the DB
567 $id = $notice->insert();
570 common_log_db_error($notice, 'INSERT', __FILE__);
571 // TRANS: Server exception thrown when a notice cannot be saved.
572 throw new ServerException(_('Problem saving notice.'));
575 // Update ID-dependent columns: URI, conversation
577 $orig = clone($notice);
582 $notice->uri = common_notice_uri($notice);
586 // If it's not part of a conversation, it's
587 // the beginning of a new conversation.
589 if (empty($notice->conversation)) {
590 $conv = Conversation::create($notice);
591 $notice->conversation = $conv->id;
596 if ($notice->update($orig) === false) {
597 common_log_db_error($notice, 'UPDATE', __FILE__);
598 // TRANS: Server exception thrown when a notice cannot be updated.
599 throw new ServerException(_('Problem saving notice.'));
605 // Clear the cache for subscribed users, so they'll update at next request
606 // XXX: someone clever could prepend instead of clearing the cache
608 $notice->blowOnInsert();
610 // Save per-notice metadata...
612 if (isset($replies)) {
613 $notice->saveKnownReplies($replies);
615 $notice->saveReplies();
619 $notice->saveKnownTags($tags);
624 // Note: groups may save tags, so must be run after tags are saved
625 // to avoid errors on duplicates.
626 // Note: groups should always be set.
628 $notice->saveKnownGroups($groups);
631 $notice->saveKnownUrls($urls);
637 // Prepare inbox delivery, may be queued to background.
638 $notice->distribute();
644 function blowOnInsert($conversation = false)
646 $this->blowStream('profile:notice_ids:%d', $this->profile_id);
648 if ($this->isPublic()) {
649 $this->blowStream('public');
652 self::blow('notice:list-ids:conversation:%s', $this->conversation);
653 self::blow('conversation:notice_count:%d', $this->conversation);
655 if (!empty($this->repeat_of)) {
656 // XXX: we should probably only use one of these
657 $this->blowStream('notice:repeats:%d', $this->repeat_of);
658 self::blow('notice:list-ids:repeat_of:%d', $this->repeat_of);
661 $original = Notice::getKV('id', $this->repeat_of);
663 if ($original instanceof Notice) {
664 $originalUser = User::getKV('id', $original->profile_id);
665 if ($originalUser instanceof User) {
666 $this->blowStream('user:repeats_of_me:%d', $originalUser->id);
670 $profile = Profile::getKV($this->profile_id);
672 if ($profile instanceof Profile) {
673 $profile->blowNoticeCount();
676 $ptags = $this->getProfileTags();
677 foreach ($ptags as $ptag) {
678 $ptag->blowNoticeStreamCache();
683 * Clear cache entries related to this notice at delete time.
684 * Necessary to avoid breaking paging on public, profile timelines.
686 function blowOnDelete()
688 $this->blowOnInsert();
690 self::blow('profile:notice_ids:%d;last', $this->profile_id);
692 if ($this->isPublic()) {
693 self::blow('public;last');
696 self::blow('fave:by_notice', $this->id);
698 if ($this->conversation) {
699 // In case we're the first, will need to calc a new root.
700 self::blow('notice:conversation_root:%d', $this->conversation);
703 $ptags = $this->getProfileTags();
704 foreach ($ptags as $ptag) {
705 $ptag->blowNoticeStreamCache(true);
709 function blowStream()
711 $c = self::memcache();
717 $args = func_get_args();
719 $format = array_shift($args);
721 $keyPart = vsprintf($format, $args);
723 $cacheKey = Cache::key($keyPart);
725 $c->delete($cacheKey);
727 // delete the "last" stream, too, if this notice is
728 // older than the top of that stream
730 $lastKey = $cacheKey.';last';
732 $lastStr = $c->get($lastKey);
734 if ($lastStr !== false) {
735 $window = explode(',', $lastStr);
736 $lastID = $window[0];
737 $lastNotice = Notice::getKV('id', $lastID);
738 if (!$lastNotice instanceof Notice // just weird
739 || strtotime($lastNotice->created) >= strtotime($this->created)) {
740 $c->delete($lastKey);
745 /** save all urls in the notice to the db
747 * follow redirects and save all available file information
748 * (mimetype, date, size, oembed, etc.)
752 function saveUrls() {
753 if (common_config('attachments', 'process_links')) {
754 common_replace_urls_callback($this->content, array($this, 'saveUrl'), $this->id);
759 * Save the given URLs as related links/attachments to the db
761 * follow redirects and save all available file information
762 * (mimetype, date, size, oembed, etc.)
766 function saveKnownUrls($urls)
768 if (common_config('attachments', 'process_links')) {
769 // @fixme validation?
770 foreach (array_unique($urls) as $url) {
771 File::processNew($url, $this->id);
779 function saveUrl($url, $notice_id) {
780 File::processNew($url, $notice_id);
783 static function checkDupes($profile_id, $content) {
784 $profile = Profile::getKV($profile_id);
785 if (!$profile instanceof Profile) {
788 $notice = $profile->getNotices(0, CachingNoticeStream::CACHE_WINDOW);
789 if (!empty($notice)) {
791 while ($notice->fetch()) {
792 if (time() - strtotime($notice->created) >= common_config('site', 'dupelimit')) {
794 } else if ($notice->content == $content) {
799 // If we get here, oldest item in cache window is not
800 // old enough for dupe limit; do direct check against DB
801 $notice = new Notice();
802 $notice->profile_id = $profile_id;
803 $notice->content = $content;
804 $threshold = common_sql_date(time() - common_config('site', 'dupelimit'));
805 $notice->whereAdd(sprintf("created > '%s'", $notice->escape($threshold)));
807 $cnt = $notice->count();
811 static function checkEditThrottle($profile_id) {
812 $profile = Profile::getKV($profile_id);
813 if (!$profile instanceof Profile) {
816 // Get the Nth notice
817 $notice = $profile->getNotices(common_config('throttle', 'count') - 1, 1);
818 if ($notice && $notice->fetch()) {
819 // If the Nth notice was posted less than timespan seconds ago
820 if (time() - strtotime($notice->created) <= common_config('throttle', 'timespan')) {
825 // Either not N notices in the stream, OR the Nth was not posted within timespan seconds
829 protected $_attachments = -1;
831 function attachments() {
833 if ($this->_attachments != -1) {
834 return $this->_attachments;
837 $f2ps = File_to_post::listGet('post_id', array($this->id));
841 foreach ($f2ps[$this->id] as $f2p) {
842 $ids[] = $f2p->file_id;
845 $files = File::multiGet('id', $ids);
847 $this->_attachments = $files->fetchAll();
849 return $this->_attachments;
852 function _setAttachments($attachments)
854 $this->_attachments = $attachments;
857 function publicStream($offset=0, $limit=20, $since_id=0, $max_id=0)
859 $stream = new PublicNoticeStream();
860 return $stream->getNotices($offset, $limit, $since_id, $max_id);
864 function conversationStream($id, $offset=0, $limit=20, $since_id=0, $max_id=0)
866 $stream = new ConversationNoticeStream($id);
868 return $stream->getNotices($offset, $limit, $since_id, $max_id);
872 * Is this notice part of an active conversation?
874 * @return boolean true if other messages exist in the same
875 * conversation, false if this is the only one
877 function hasConversation()
879 if (!empty($this->conversation)) {
880 $conversation = Notice::conversationStream(
886 if ($conversation->N > 0) {
894 * Grab the earliest notice from this conversation.
896 * @return Notice or null
898 function conversationRoot($profile=-1)
900 // XXX: can this happen?
902 if (empty($this->conversation)) {
906 // Get the current profile if not specified
908 if (is_int($profile) && $profile == -1) {
909 $profile = Profile::current();
912 // If this notice is out of scope, no root for you!
914 if (!$this->inScope($profile)) {
918 // If this isn't a reply to anything, then it's its own
921 if (empty($this->reply_to)) {
925 if (is_null($profile)) {
926 $keypart = sprintf('notice:conversation_root:%d:null', $this->id);
928 $keypart = sprintf('notice:conversation_root:%d:%d',
933 $root = self::cacheGet($keypart);
935 if ($root !== false && $root->inScope($profile)) {
942 $parent = $last->getParent();
943 if ($parent->inScope($profile)) {
947 } catch (Exception $e) {
948 // Latest notice has no parent
950 // No parent, or parent out of scope
955 self::cacheSet($keypart, $root);
961 * Pull up a full list of local recipients who will be getting
962 * this notice in their inbox. Results will be cached, so don't
963 * change the input data wily-nilly!
965 * @param array $groups optional list of Group objects;
966 * if left empty, will be loaded from group_inbox records
967 * @param array $recipient optional list of reply profile ids
968 * if left empty, will be loaded from reply records
969 * @return array associating recipient user IDs with an inbox source constant
971 function whoGets(array $groups=null, array $recipients=null)
973 $c = self::memcache();
976 $ni = $c->get(Cache::key('notice:who_gets:'.$this->id));
982 if (is_null($groups)) {
983 $groups = $this->getGroups();
986 if (is_null($recipients)) {
987 $recipients = $this->getReplies();
990 $users = $this->getSubscribedUsers();
991 $ptags = $this->getProfileTags();
993 // FIXME: kind of ignoring 'transitional'...
994 // we'll probably stop supporting inboxless mode
999 // Give plugins a chance to add folks in at start...
1000 if (Event::handle('StartNoticeWhoGets', array($this, &$ni))) {
1002 foreach ($users as $id) {
1003 $ni[$id] = NOTICE_INBOX_SOURCE_SUB;
1006 foreach ($groups as $group) {
1007 $users = $group->getUserMembers();
1008 foreach ($users as $id) {
1009 if (!array_key_exists($id, $ni)) {
1010 $ni[$id] = NOTICE_INBOX_SOURCE_GROUP;
1015 foreach ($ptags as $ptag) {
1016 $users = $ptag->getUserSubscribers();
1017 foreach ($users as $id) {
1018 if (!array_key_exists($id, $ni)) {
1019 $ni[$id] = NOTICE_INBOX_SOURCE_PROFILE_TAG;
1024 foreach ($recipients as $recipient) {
1025 if (!array_key_exists($recipient, $ni)) {
1026 $ni[$recipient] = NOTICE_INBOX_SOURCE_REPLY;
1030 // Exclude any deleted, non-local, or blocking recipients.
1031 $profile = $this->getProfile();
1032 $originalProfile = null;
1033 if ($this->repeat_of) {
1034 // Check blocks against the original notice's poster as well.
1035 $original = Notice::getKV('id', $this->repeat_of);
1036 if ($original instanceof Notice) {
1037 $originalProfile = $original->getProfile();
1041 foreach ($ni as $id => $source) {
1043 $user = User::getKV('id', $id);
1044 if (!$user instanceof User ||
1045 $user->hasBlocked($profile) ||
1046 ($originalProfile && $user->hasBlocked($originalProfile))) {
1049 } catch (UserNoProfileException $e) {
1050 // User doesn't have a profile; invalid; skip them.
1055 // Give plugins a chance to filter out...
1056 Event::handle('EndNoticeWhoGets', array($this, &$ni));
1060 // XXX: pack this data better
1061 $c->set(Cache::key('notice:who_gets:'.$this->id), $ni);
1068 * Adds this notice to the inboxes of each local user who should receive
1069 * it, based on author subscriptions, group memberships, and @-replies.
1071 * Warning: running a second time currently will make items appear
1072 * multiple times in users' inboxes.
1074 * @fixme make more robust against errors
1075 * @fixme break up massive deliveries to smaller background tasks
1077 * @param array $groups optional list of Group objects;
1078 * if left empty, will be loaded from group_inbox records
1079 * @param array $recipient optional list of reply profile ids
1080 * if left empty, will be loaded from reply records
1082 function addToInboxes(array $groups=null, array $recipients=null)
1084 $ni = $this->whoGets($groups, $recipients);
1086 $ids = array_keys($ni);
1089 Inbox::bulkInsert($this, $ids);
1094 function getSubscribedUsers()
1098 if(common_config('db','quote_identifiers'))
1099 $user_table = '"user"';
1100 else $user_table = 'user';
1104 'FROM '. $user_table .' JOIN subscription '.
1105 'ON '. $user_table .'.id = subscription.subscriber ' .
1106 'WHERE subscription.subscribed = %d ';
1108 $user->query(sprintf($qry, $this->profile_id));
1112 while ($user->fetch()) {
1121 function getProfileTags()
1123 $profile = $this->getProfile();
1124 $list = $profile->getOtherTags($profile);
1127 while($list->fetch()) {
1128 $ptags[] = clone($list);
1135 * Record this notice to the given group inboxes for delivery.
1136 * Overrides the regular parsing of !group markup.
1138 * @param string $group_ids
1139 * @fixme might prefer URIs as identifiers, as for replies?
1140 * best with generalizations on user_group to support
1141 * remote groups better.
1143 function saveKnownGroups($group_ids)
1145 if (!is_array($group_ids)) {
1146 // TRANS: Server exception thrown when no array is provided to the method saveKnownGroups().
1147 throw new ServerException(_('Bad type provided to saveKnownGroups.'));
1151 foreach (array_unique($group_ids) as $id) {
1152 $group = User_group::getKV('id', $id);
1153 if ($group instanceof User_group) {
1154 common_log(LOG_ERR, "Local delivery to group id $id, $group->nickname");
1155 $result = $this->addToGroupInbox($group);
1157 common_log_db_error($gi, 'INSERT', __FILE__);
1160 if (common_config('group', 'addtag')) {
1161 // we automatically add a tag for every group name, too
1163 $tag = Notice_tag::pkeyGet(array('tag' => common_canonical_tag($group->nickname),
1164 'notice_id' => $this->id));
1166 if (is_null($tag)) {
1167 $this->saveTag($group->nickname);
1171 $groups[] = clone($group);
1173 common_log(LOG_ERR, "Local delivery to group id $id skipped, doesn't exist");
1180 function addToGroupInbox(User_group $group)
1182 $gi = Group_inbox::pkeyGet(array('group_id' => $group->id,
1183 'notice_id' => $this->id));
1185 if (!$gi instanceof Group_inbox) {
1187 $gi = new Group_inbox();
1189 $gi->group_id = $group->id;
1190 $gi->notice_id = $this->id;
1191 $gi->created = $this->created;
1193 $result = $gi->insert();
1196 common_log_db_error($gi, 'INSERT', __FILE__);
1197 // TRANS: Server exception thrown when an update for a group inbox fails.
1198 throw new ServerException(_('Problem saving group inbox.'));
1201 self::blow('user_group:notice_ids:%d', $gi->group_id);
1208 * Save reply records indicating that this notice needs to be
1209 * delivered to the local users with the given URIs.
1211 * Since this is expected to be used when saving foreign-sourced
1212 * messages, we won't deliver to any remote targets as that's the
1213 * source service's responsibility.
1215 * Mail notifications etc will be handled later.
1217 * @param array $uris Array of unique identifier URIs for recipients
1219 function saveKnownReplies(array $uris)
1225 $sender = Profile::getKV($this->profile_id);
1227 foreach (array_unique($uris) as $uri) {
1229 $profile = Profile::fromURI($uri);
1231 if (!$profile instanceof Profile) {
1232 common_log(LOG_WARNING, "Unable to determine profile for URI '$uri'");
1236 if ($profile->hasBlocked($sender)) {
1237 common_log(LOG_INFO, "Not saving reply to profile {$profile->id} ($uri) from sender {$sender->id} because of a block.");
1241 $this->saveReply($profile->id);
1242 self::blow('reply:stream:%d', $profile->id);
1249 * Pull @-replies from this message's content in StatusNet markup format
1250 * and save reply records indicating that this message needs to be
1251 * delivered to those users.
1253 * Mail notifications to local profiles will be sent later.
1255 * @return array of integer profile IDs
1258 function saveReplies()
1260 // Don't save reply data for repeats
1262 if (!empty($this->repeat_of)) {
1266 $sender = Profile::getKV($this->profile_id);
1270 // If it's a reply, save for the replied-to author
1272 $parent = $this->getParent();
1273 $author = $parent->getProfile();
1274 if ($author instanceof Profile) {
1275 $this->saveReply($author->id);
1276 $replied[$author->id] = 1;
1277 self::blow('reply:stream:%d', $author->id);
1279 } catch (Exception $e) {
1280 // Not a reply, since it has no parent!
1283 // @todo ideally this parser information would only
1284 // be calculated once.
1286 $mentions = common_find_mentions($this->content, $this);
1288 // store replied only for first @ (what user/notice what the reply directed,
1289 // we assume first @ is it)
1291 foreach ($mentions as $mention) {
1293 foreach ($mention['mentioned'] as $mentioned) {
1295 // skip if they're already covered
1297 if (!empty($replied[$mentioned->id])) {
1301 // Don't save replies from blocked profile to local user
1303 $mentioned_user = User::getKV('id', $mentioned->id);
1304 if ($mentioned_user instanceof User && $mentioned_user->hasBlocked($sender)) {
1308 $this->saveReply($mentioned->id);
1309 $replied[$mentioned->id] = 1;
1310 self::blow('reply:stream:%d', $mentioned->id);
1314 $recipientIds = array_keys($replied);
1316 return $recipientIds;
1319 function saveReply($profileId)
1321 $reply = new Reply();
1323 $reply->notice_id = $this->id;
1324 $reply->profile_id = $profileId;
1325 $reply->modified = $this->created;
1332 protected $_replies = -1;
1335 * Pull the complete list of @-reply targets for this notice.
1337 * @return array of integer profile ids
1339 function getReplies()
1341 if ($this->_replies != -1) {
1342 return $this->_replies;
1345 $replyMap = Reply::listGet('notice_id', array($this->id));
1349 foreach ($replyMap[$this->id] as $reply) {
1350 $ids[] = $reply->profile_id;
1353 $this->_replies = $ids;
1358 function _setReplies($replies)
1360 $this->_replies = $replies;
1364 * Pull the complete list of @-reply targets for this notice.
1366 * @return array of Profiles
1368 function getReplyProfiles()
1370 $ids = $this->getReplies();
1372 $profiles = Profile::multiGet('id', $ids);
1374 return $profiles->fetchAll();
1378 * Send e-mail notifications to local @-reply targets.
1380 * Replies must already have been saved; this is expected to be run
1381 * from the distrib queue handler.
1383 function sendReplyNotifications()
1385 // Don't send reply notifications for repeats
1387 if (!empty($this->repeat_of)) {
1391 $recipientIds = $this->getReplies();
1393 foreach ($recipientIds as $recipientId) {
1394 $user = User::getKV('id', $recipientId);
1395 if ($user instanceof User) {
1396 mail_notify_attn($user, $this);
1402 * Pull list of groups this notice needs to be delivered to,
1403 * as previously recorded by saveKnownGroups().
1405 * @return array of Group objects
1408 protected $_groups = -1;
1410 function getGroups()
1412 // Don't save groups for repeats
1414 if (!empty($this->repeat_of)) {
1418 if ($this->_groups != -1)
1420 return $this->_groups;
1423 $gis = Group_inbox::listGet('notice_id', array($this->id));
1427 foreach ($gis[$this->id] as $gi)
1429 $ids[] = $gi->group_id;
1432 $groups = User_group::multiGet('id', $ids);
1434 $this->_groups = $groups->fetchAll();
1436 return $this->_groups;
1439 function _setGroups($groups)
1441 $this->_groups = $groups;
1445 * Convert a notice into an activity for export.
1447 * @param User $cur Current user
1449 * @return Activity activity object representing this Notice.
1452 function asActivity($cur=null)
1454 $act = self::cacheGet(Cache::codeKey('notice:as-activity:'.$this->id));
1456 if ($act instanceof Activity) {
1459 $act = new Activity();
1461 if (Event::handle('StartNoticeAsActivity', array($this, &$act))) {
1463 $act->id = $this->uri;
1464 $act->time = strtotime($this->created);
1465 $act->link = $this->bestUrl();
1466 $act->content = common_xml_safe_str($this->rendered);
1468 $profile = $this->getProfile();
1470 $act->actor = ActivityObject::fromProfile($profile);
1471 $act->actor->extra[] = $profile->profileInfo($cur);
1473 $act->verb = $this->verb;
1475 if ($this->repeat_of) {
1476 $repeated = Notice::getKV('id', $this->repeat_of);
1477 if ($repeated instanceof Notice) {
1478 $act->objects[] = $repeated->asActivity($cur);
1481 $act->objects[] = ActivityObject::fromNotice($this);
1484 // XXX: should this be handled by default processing for object entry?
1488 $tags = $this->getTags();
1490 foreach ($tags as $tag) {
1491 $cat = new AtomCategory();
1494 $act->categories[] = $cat;
1498 // XXX: use Atom Media and/or File activity objects instead
1500 $attachments = $this->attachments();
1502 foreach ($attachments as $attachment) {
1503 // Save local attachments
1504 if (!empty($attachment->filename)) {
1505 $act->attachments[] = ActivityObject::fromFile($attachment);
1509 $ctx = new ActivityContext();
1512 $reply = $this->getParent();
1513 $ctx->replyToID = $reply->uri;
1514 $ctx->replyToUrl = $reply->bestUrl();
1515 } catch (Exception $e) {
1516 // This is not a reply to something
1519 $ctx->location = $this->getLocation();
1523 if (!empty($this->conversation)) {
1524 $conv = Conversation::getKV('id', $this->conversation);
1525 if ($conv instanceof Conversation) {
1526 $ctx->conversation = $conv->uri;
1530 $reply_ids = $this->getReplies();
1532 foreach ($reply_ids as $id) {
1533 $rprofile = Profile::getKV('id', $id);
1534 if ($rprofile instanceof Profile) {
1535 $ctx->attention[$rprofile->getUri()] = ActivityObject::PERSON;
1539 $groups = $this->getGroups();
1541 foreach ($groups as $group) {
1542 $ctx->attention[$group->getUri()] = ActivityObject::GROUP;
1545 switch ($this->scope) {
1546 case Notice::PUBLIC_SCOPE:
1547 $ctx->attention[ActivityContext::ATTN_PUBLIC] = ActivityObject::COLLECTION;
1549 case Notice::FOLLOWER_SCOPE:
1550 $surl = common_local_url("subscribers", array('nickname' => $profile->nickname));
1551 $ctx->attention[$surl] = ActivityObject::COLLECTION;
1555 $act->context = $ctx;
1557 $source = $this->getSource();
1559 if ($source instanceof Notice_source) {
1560 $act->generator = ActivityObject::fromNoticeSource($source);
1565 $atom_feed = $profile->getAtomFeed();
1567 if (!empty($atom_feed)) {
1569 $act->source = new ActivitySource();
1571 // XXX: we should store the actual feed ID
1573 $act->source->id = $atom_feed;
1575 // XXX: we should store the actual feed title
1577 $act->source->title = $profile->getBestName();
1579 $act->source->links['alternate'] = $profile->profileurl;
1580 $act->source->links['self'] = $atom_feed;
1582 $act->source->icon = $profile->avatarUrl(AVATAR_PROFILE_SIZE);
1584 $notice = $profile->getCurrentNotice();
1586 if ($notice instanceof Notice) {
1587 $act->source->updated = self::utcDate($notice->created);
1590 $user = User::getKV('id', $profile->id);
1592 if ($user instanceof User) {
1593 $act->source->links['license'] = common_config('license', 'url');
1597 if ($this->isLocal()) {
1598 $act->selfLink = common_local_url('ApiStatusesShow', array('id' => $this->id,
1599 'format' => 'atom'));
1600 $act->editLink = $act->selfLink;
1603 Event::handle('EndNoticeAsActivity', array($this, &$act));
1606 self::cacheSet(Cache::codeKey('notice:as-activity:'.$this->id), $act);
1611 // This has gotten way too long. Needs to be sliced up into functional bits
1612 // or ideally exported to a utility class.
1614 function asAtomEntry($namespace=false,
1619 $act = $this->asActivity($cur);
1620 $act->extra[] = $this->noticeInfo($cur);
1621 return $act->asString($namespace, $author, $source);
1625 * Extra notice info for atom entries
1627 * Clients use some extra notice info in the atom stream.
1628 * This gives it to them.
1630 * @param User $cur Current user
1632 * @return array representation of <statusnet:notice_info> element
1635 function noticeInfo($cur)
1637 // local notice ID (useful to clients for ordering)
1639 $noticeInfoAttr = array('local_id' => $this->id);
1643 $ns = $this->getSource();
1645 if ($ns instanceof Notice_source) {
1646 $noticeInfoAttr['source'] = $ns->code;
1647 if (!empty($ns->url)) {
1648 $noticeInfoAttr['source_link'] = $ns->url;
1649 if (!empty($ns->name)) {
1650 $noticeInfoAttr['source'] = '<a href="'
1651 . htmlspecialchars($ns->url)
1652 . '" rel="nofollow">'
1653 . htmlspecialchars($ns->name)
1659 // favorite and repeated
1662 $cp = $cur->getProfile();
1663 $noticeInfoAttr['favorite'] = ($cp->hasFave($this)) ? "true" : "false";
1664 $noticeInfoAttr['repeated'] = ($cp->hasRepeated($this)) ? "true" : "false";
1667 if (!empty($this->repeat_of)) {
1668 $noticeInfoAttr['repeat_of'] = $this->repeat_of;
1671 return array('statusnet:notice_info', $noticeInfoAttr, null);
1675 * Returns an XML string fragment with a reference to a notice as an
1676 * Activity Streams noun object with the given element type.
1678 * Assumes that 'activity' namespace has been previously defined.
1680 * @param string $element one of 'subject', 'object', 'target'
1684 function asActivityNoun($element)
1686 $noun = ActivityObject::fromNotice($this);
1687 return $noun->asString('activity:' . $element);
1692 if (!empty($this->url)) {
1694 } else if (!empty($this->uri) && preg_match('/^https?:/', $this->uri)) {
1697 return common_local_url('shownotice',
1698 array('notice' => $this->id));
1704 * Determine which notice, if any, a new notice is in reply to.
1706 * For conversation tracking, we try to see where this notice fits
1707 * in the tree. Rough algorithm is:
1709 * if (reply_to is set and valid) {
1711 * } else if ((source not API or Web) and (content starts with "T NAME" or "@name ")) {
1712 * return ID of last notice by initial @name in content;
1715 * Note that all @nickname instances will still be used to save "reply" records,
1716 * so the notice shows up in the mentioned users' "replies" tab.
1718 * @param integer $reply_to ID passed in by Web or API
1719 * @param integer $profile_id ID of author
1720 * @param string $source Source tag, like 'web' or 'gwibber'
1721 * @param string $content Final notice content
1723 * @return integer ID of replied-to notice, or null for not a reply.
1726 static function getReplyTo($reply_to, $profile_id, $source, $content)
1728 static $lb = array('xmpp', 'mail', 'sms', 'omb');
1730 // If $reply_to is specified, we check that it exists, and then
1731 // return it if it does
1733 if (!empty($reply_to)) {
1734 $reply_notice = Notice::getKV('id', $reply_to);
1735 if ($reply_notice instanceof Notice) {
1736 return $reply_notice;
1740 // If it's not a "low bandwidth" source (one where you can't set
1741 // a reply_to argument), we return. This is mostly web and API
1744 if (!in_array($source, $lb)) {
1748 // Is there an initial @ or T?
1750 if (preg_match('/^T ([A-Z0-9]{1,64}) /', $content, $match) ||
1751 preg_match('/^@([a-z0-9]{1,64})\s+/', $content, $match)) {
1752 $nickname = common_canonical_nickname($match[1]);
1757 // Figure out who that is.
1759 $sender = Profile::getKV('id', $profile_id);
1760 if (!$sender instanceof Profile) {
1764 $recipient = common_relative_profile($sender, $nickname, common_sql_now());
1766 if (!$recipient instanceof Profile) {
1770 // Get their last notice
1772 $last = $recipient->getCurrentNotice();
1774 if ($last instanceof Notice) {
1781 static function maxContent()
1783 $contentlimit = common_config('notice', 'contentlimit');
1784 // null => use global limit (distinct from 0!)
1785 if (is_null($contentlimit)) {
1786 $contentlimit = common_config('site', 'textlimit');
1788 return $contentlimit;
1791 static function contentTooLong($content)
1793 $contentlimit = self::maxContent();
1794 return ($contentlimit > 0 && !empty($content) && (mb_strlen($content) > $contentlimit));
1797 function getLocation()
1801 if (!empty($this->location_id) && !empty($this->location_ns)) {
1802 $location = Location::fromId($this->location_id, $this->location_ns);
1805 if (is_null($location)) { // no ID, or Location::fromId() failed
1806 if (!empty($this->lat) && !empty($this->lon)) {
1807 $location = Location::fromLatLon($this->lat, $this->lon);
1815 * Convenience function for posting a repeat of an existing message.
1817 * @param int $repeater_id: profile ID of user doing the repeat
1818 * @param string $source: posting source key, eg 'web', 'api', etc
1821 * @throws Exception on failure or permission problems
1823 function repeat($repeater_id, $source)
1825 $author = Profile::getKV('id', $this->profile_id);
1827 // TRANS: Message used to repeat a notice. RT is the abbreviation of 'retweet'.
1828 // TRANS: %1$s is the repeated user's name, %2$s is the repeated notice.
1829 $content = sprintf(_('RT @%1$s %2$s'),
1833 $maxlen = common_config('site', 'textlimit');
1834 if ($maxlen > 0 && mb_strlen($content) > $maxlen) {
1835 // Web interface and current Twitter API clients will
1836 // pull the original notice's text, but some older
1837 // clients and RSS/Atom feeds will see this trimmed text.
1839 // Unfortunately this is likely to lose tags or URLs
1840 // at the end of long notices.
1841 $content = mb_substr($content, 0, $maxlen - 4) . ' ...';
1844 // Scope is same as this one's
1846 return self::saveNew($repeater_id,
1849 array('repeat_of' => $this->id,
1850 'scope' => $this->scope));
1853 // These are supposed to be in chron order!
1855 function repeatStream($limit=100)
1857 $cache = Cache::instance();
1859 if (empty($cache)) {
1860 $ids = $this->_repeatStreamDirect($limit);
1862 $idstr = $cache->get(Cache::key('notice:repeats:'.$this->id));
1863 if ($idstr !== false) {
1864 if (empty($idstr)) {
1867 $ids = explode(',', $idstr);
1870 $ids = $this->_repeatStreamDirect(100);
1871 $cache->set(Cache::key('notice:repeats:'.$this->id), implode(',', $ids));
1874 // We do a max of 100, so slice down to limit
1875 $ids = array_slice($ids, 0, $limit);
1879 return NoticeStream::getStreamByIds($ids);
1882 function _repeatStreamDirect($limit)
1884 $notice = new Notice();
1886 $notice->selectAdd(); // clears it
1887 $notice->selectAdd('id');
1889 $notice->repeat_of = $this->id;
1891 $notice->orderBy('created, id'); // NB: asc!
1893 if (!is_null($limit)) {
1894 $notice->limit(0, $limit);
1897 return $notice->fetchAll('id');
1900 function locationOptions($lat, $lon, $location_id, $location_ns, $profile = null)
1904 if (!empty($location_id) && !empty($location_ns)) {
1905 $options['location_id'] = $location_id;
1906 $options['location_ns'] = $location_ns;
1908 $location = Location::fromId($location_id, $location_ns);
1910 if ($location instanceof Location) {
1911 $options['lat'] = $location->lat;
1912 $options['lon'] = $location->lon;
1915 } else if (!empty($lat) && !empty($lon)) {
1916 $options['lat'] = $lat;
1917 $options['lon'] = $lon;
1919 $location = Location::fromLatLon($lat, $lon);
1921 if ($location instanceof Location) {
1922 $options['location_id'] = $location->location_id;
1923 $options['location_ns'] = $location->location_ns;
1925 } else if (!empty($profile)) {
1926 if (isset($profile->lat) && isset($profile->lon)) {
1927 $options['lat'] = $profile->lat;
1928 $options['lon'] = $profile->lon;
1931 if (isset($profile->location_id) && isset($profile->location_ns)) {
1932 $options['location_id'] = $profile->location_id;
1933 $options['location_ns'] = $profile->location_ns;
1940 function clearReplies()
1942 $replyNotice = new Notice();
1943 $replyNotice->reply_to = $this->id;
1945 //Null any notices that are replies to this notice
1947 if ($replyNotice->find()) {
1948 while ($replyNotice->fetch()) {
1949 $orig = clone($replyNotice);
1950 $replyNotice->reply_to = null;
1951 $replyNotice->update($orig);
1957 $reply = new Reply();
1958 $reply->notice_id = $this->id;
1960 if ($reply->find()) {
1961 while($reply->fetch()) {
1962 self::blow('reply:stream:%d', $reply->profile_id);
1970 function clearFiles()
1972 $f2p = new File_to_post();
1974 $f2p->post_id = $this->id;
1977 while ($f2p->fetch()) {
1981 // FIXME: decide whether to delete File objects
1982 // ...and related (actual) files
1985 function clearRepeats()
1987 $repeatNotice = new Notice();
1988 $repeatNotice->repeat_of = $this->id;
1990 //Null any notices that are repeats of this notice
1992 if ($repeatNotice->find()) {
1993 while ($repeatNotice->fetch()) {
1994 $orig = clone($repeatNotice);
1995 $repeatNotice->repeat_of = null;
1996 $repeatNotice->update($orig);
2001 function clearFaves()
2004 $fave->notice_id = $this->id;
2006 if ($fave->find()) {
2007 while ($fave->fetch()) {
2008 self::blow('fave:ids_by_user_own:%d', $fave->user_id);
2009 self::blow('fave:ids_by_user_own:%d;last', $fave->user_id);
2010 self::blow('fave:ids_by_user:%d', $fave->user_id);
2011 self::blow('fave:ids_by_user:%d;last', $fave->user_id);
2019 function clearTags()
2021 $tag = new Notice_tag();
2022 $tag->notice_id = $this->id;
2025 while ($tag->fetch()) {
2026 self::blow('profile:notice_ids_tagged:%d:%s', $this->profile_id, Cache::keyize($tag->tag));
2027 self::blow('profile:notice_ids_tagged:%d:%s;last', $this->profile_id, Cache::keyize($tag->tag));
2028 self::blow('notice_tag:notice_ids:%s', Cache::keyize($tag->tag));
2029 self::blow('notice_tag:notice_ids:%s;last', Cache::keyize($tag->tag));
2037 function clearGroupInboxes()
2039 $gi = new Group_inbox();
2041 $gi->notice_id = $this->id;
2044 while ($gi->fetch()) {
2045 self::blow('user_group:notice_ids:%d', $gi->group_id);
2053 function distribute()
2055 // We always insert for the author so they don't
2057 Event::handle('StartNoticeDistribute', array($this));
2059 // If there's a failure, we want to _force_
2060 // distribution at this point.
2062 $qm = QueueManager::get();
2063 $qm->enqueue($this, 'distrib');
2064 } catch (Exception $e) {
2065 // If the exception isn't transient, this
2066 // may throw more exceptions as DQH does
2067 // its own enqueueing. So, we ignore them!
2069 $handler = new DistribQueueHandler();
2070 $handler->handle($this);
2071 } catch (Exception $e) {
2072 common_log(LOG_ERR, "emergency redistribution resulted in " . $e->getMessage());
2074 // Re-throw so somebody smarter can handle it.
2081 $result = parent::insert();
2083 if ($result !== false) {
2084 // Profile::hasRepeated() abuses pkeyGet(), so we
2085 // have to clear manually
2086 if (!empty($this->repeat_of)) {
2087 $c = self::memcache();
2089 $ck = self::multicacheKey('Notice',
2090 array('profile_id' => $this->profile_id,
2091 'repeat_of' => $this->repeat_of));
2101 * Get the source of the notice
2103 * @return Notice_source $ns A notice source object. 'code' is the only attribute
2104 * guaranteed to be populated.
2106 function getSource()
2108 $ns = new Notice_source();
2109 if (!empty($this->source)) {
2110 switch ($this->source) {
2117 $ns->code = $this->source;
2120 $ns = Notice_source::getKV($this->source);
2122 $ns = new Notice_source();
2123 $ns->code = $this->source;
2124 $app = Oauth_application::getKV('name', $this->source);
2126 $ns->name = $app->name;
2127 $ns->url = $app->source_url;
2137 * Determine whether the notice was locally created
2139 * @return boolean locality
2142 public function isLocal()
2144 return ($this->is_local == Notice::LOCAL_PUBLIC ||
2145 $this->is_local == Notice::LOCAL_NONPUBLIC);
2149 * Get the list of hash tags saved with this notice.
2151 * @return array of strings
2153 public function getTags()
2157 $keypart = sprintf('notice:tags:%d', $this->id);
2159 $tagstr = self::cacheGet($keypart);
2161 if ($tagstr !== false) {
2162 $tags = explode(',', $tagstr);
2164 $tag = new Notice_tag();
2165 $tag->notice_id = $this->id;
2167 while ($tag->fetch()) {
2168 $tags[] = $tag->tag;
2171 self::cacheSet($keypart, implode(',', $tags));
2177 static private function utcDate($dt)
2179 $dateStr = date('d F Y H:i:s', strtotime($dt));
2180 $d = new DateTime($dateStr, new DateTimeZone('UTC'));
2181 return $d->format(DATE_W3C);
2185 * Look up the creation timestamp for a given notice ID, even
2186 * if it's been deleted.
2189 * @return mixed string recorded creation timestamp, or false if can't be found
2191 public static function getAsTimestamp($id)
2197 $notice = Notice::getKV('id', $id);
2199 return $notice->created;
2202 $deleted = Deleted_notice::getKV('id', $id);
2204 return $deleted->created;
2211 * Build an SQL 'where' fragment for timestamp-based sorting from a since_id
2212 * parameter, matching notices posted after the given one (exclusive).
2214 * If the referenced notice can't be found, will return false.
2217 * @param string $idField
2218 * @param string $createdField
2219 * @return mixed string or false if no match
2221 public static function whereSinceId($id, $idField='id', $createdField='created')
2223 $since = Notice::getAsTimestamp($id);
2225 return sprintf("($createdField = '%s' and $idField > %d) or ($createdField > '%s')", $since, $id, $since);
2231 * Build an SQL 'where' fragment for timestamp-based sorting from a since_id
2232 * parameter, matching notices posted after the given one (exclusive), and
2233 * if necessary add it to the data object's query.
2235 * @param DB_DataObject $obj
2237 * @param string $idField
2238 * @param string $createdField
2239 * @return mixed string or false if no match
2241 public static function addWhereSinceId(DB_DataObject $obj, $id, $idField='id', $createdField='created')
2243 $since = self::whereSinceId($id, $idField, $createdField);
2245 $obj->whereAdd($since);
2250 * Build an SQL 'where' fragment for timestamp-based sorting from a max_id
2251 * parameter, matching notices posted before the given one (inclusive).
2253 * If the referenced notice can't be found, will return false.
2256 * @param string $idField
2257 * @param string $createdField
2258 * @return mixed string or false if no match
2260 public static function whereMaxId($id, $idField='id', $createdField='created')
2262 $max = Notice::getAsTimestamp($id);
2264 return sprintf("($createdField < '%s') or ($createdField = '%s' and $idField <= %d)", $max, $max, $id);
2270 * Build an SQL 'where' fragment for timestamp-based sorting from a max_id
2271 * parameter, matching notices posted before the given one (inclusive), and
2272 * if necessary add it to the data object's query.
2274 * @param DB_DataObject $obj
2276 * @param string $idField
2277 * @param string $createdField
2278 * @return mixed string or false if no match
2280 public static function addWhereMaxId(DB_DataObject $obj, $id, $idField='id', $createdField='created')
2282 $max = self::whereMaxId($id, $idField, $createdField);
2284 $obj->whereAdd($max);
2290 if (common_config('public', 'localonly')) {
2291 return ($this->is_local == Notice::LOCAL_PUBLIC);
2293 return (($this->is_local != Notice::LOCAL_NONPUBLIC) &&
2294 ($this->is_local != Notice::GATEWAY));
2299 * Check that the given profile is allowed to read, respond to, or otherwise
2300 * act on this notice.
2302 * The $scope member is a bitmask of scopes, representing a logical AND of the
2303 * scope requirement. So, 0x03 (Notice::ADDRESSEE_SCOPE | Notice::SITE_SCOPE) means
2304 * "only visible to people who are mentioned in the notice AND are users on this site."
2305 * Users on the site who are not mentioned in the notice will not be able to see the
2308 * @param Profile $profile The profile to check; pass null to check for public/unauthenticated users.
2310 * @return boolean whether the profile is in the notice's scope
2312 function inScope($profile)
2314 if (is_null($profile)) {
2315 $keypart = sprintf('notice:in-scope-for:%d:null', $this->id);
2317 $keypart = sprintf('notice:in-scope-for:%d:%d', $this->id, $profile->id);
2320 $result = self::cacheGet($keypart);
2322 if ($result === false) {
2324 if (Event::handle('StartNoticeInScope', array($this, $profile, &$bResult))) {
2325 $bResult = $this->_inScope($profile);
2326 Event::handle('EndNoticeInScope', array($this, $profile, &$bResult));
2328 $result = ($bResult) ? 1 : 0;
2329 self::cacheSet($keypart, $result, 0, 300);
2332 return ($result == 1) ? true : false;
2335 protected function _inScope($profile)
2337 if (!is_null($this->scope)) {
2338 $scope = $this->scope;
2340 $scope = self::defaultScope();
2343 // If there's no scope, anyone (even anon) is in scope.
2345 if ($scope == 0) { // Not private
2347 return !$this->isHiddenSpam($profile);
2349 } else { // Private, somehow
2351 // If there's scope, anon cannot be in scope
2353 if (empty($profile)) {
2357 // Author is always in scope
2359 if ($this->profile_id == $profile->id) {
2363 // Only for users on this site
2365 if (($scope & Notice::SITE_SCOPE) && !$profile->isLocal()) {
2369 // Only for users mentioned in the notice
2371 if ($scope & Notice::ADDRESSEE_SCOPE) {
2373 $reply = Reply::pkeyGet(array('notice_id' => $this->id,
2374 'profile_id' => $profile->id));
2376 if (!$reply instanceof Reply) {
2381 // Only for members of the given group
2383 if ($scope & Notice::GROUP_SCOPE) {
2385 // XXX: just query for the single membership
2387 $groups = $this->getGroups();
2391 foreach ($groups as $group) {
2392 if ($profile->isMember($group)) {
2403 // Only for followers of the author
2407 if ($scope & Notice::FOLLOWER_SCOPE) {
2410 $author = $this->getProfile();
2411 } catch (Exception $e) {
2415 if (!Subscription::exists($profile, $author)) {
2420 return !$this->isHiddenSpam($profile);
2424 function isHiddenSpam($profile) {
2426 // Hide posts by silenced users from everyone but moderators.
2428 if (common_config('notice', 'hidespam')) {
2431 $author = $this->getProfile();
2432 } catch(Exception $e) {
2433 // If we can't get an author, keep it hidden.
2434 // XXX: technically not spam, but, whatever.
2438 if ($author->hasRole(Profile_role::SILENCED)) {
2439 if (!$profile instanceof Profile || (($profile->id !== $author->id) && (!$profile->hasRight(Right::REVIEWSPAM)))) {
2448 public function getParent()
2450 $parent = Notice::getKV('id', $this->reply_to);
2452 if (!$parent instanceof Notice) {
2453 throw new ServerException('Notice has no parent');
2460 * Magic function called at serialize() time.
2462 * We use this to drop a couple process-specific references
2463 * from DB_DataObject which can cause trouble in future
2466 * @return array of variable names to include in serialization.
2471 $vars = parent::__sleep();
2472 $skip = array('_profile', '_groups', '_attachments', '_faves', '_replies', '_repeats');
2473 return array_diff($vars, $skip);
2476 static function defaultScope()
2478 $scope = common_config('notice', 'defaultscope');
2479 if (is_null($scope)) {
2480 if (common_config('site', 'private')) {
2489 static function fillProfiles($notices)
2491 $map = self::getProfiles($notices);
2493 foreach ($notices as $entry=>$notice) {
2495 if (array_key_exists($notice->profile_id, $map)) {
2496 $notice->_setProfile($map[$notice->profile_id]);
2498 } catch (NoProfileException $e) {
2499 common_log(LOG_WARNING, "Failed to fill profile in Notice with non-existing entry for profile_id: {$e->id}");
2500 unset($notices[$entry]);
2504 return array_values($map);
2507 static function getProfiles(&$notices)
2510 foreach ($notices as $notice) {
2511 $ids[] = $notice->profile_id;
2514 $ids = array_unique($ids);
2516 return Profile::pivotGet('id', $ids);
2519 static function fillGroups(&$notices)
2521 $ids = self::_idsOf($notices);
2523 $gis = Group_inbox::listGet('notice_id', $ids);
2527 foreach ($gis as $id => $gi)
2531 $gids[] = $g->group_id;
2535 $gids = array_unique($gids);
2537 $group = User_group::pivotGet('id', $gids);
2539 foreach ($notices as $notice)
2542 $gi = $gis[$notice->id];
2543 foreach ($gi as $g) {
2544 $grps[] = $group[$g->group_id];
2546 $notice->_setGroups($grps);
2550 static function _idsOf(&$notices)
2553 foreach ($notices as $notice) {
2554 $ids[] = $notice->id;
2556 $ids = array_unique($ids);
2560 static function fillAttachments(&$notices)
2562 $ids = self::_idsOf($notices);
2564 $f2pMap = File_to_post::listGet('post_id', $ids);
2568 foreach ($f2pMap as $noticeId => $f2ps) {
2569 foreach ($f2ps as $f2p) {
2570 $fileIds[] = $f2p->file_id;
2574 $fileIds = array_unique($fileIds);
2576 $fileMap = File::pivotGet('id', $fileIds);
2578 foreach ($notices as $notice)
2581 $f2ps = $f2pMap[$notice->id];
2582 foreach ($f2ps as $f2p) {
2583 $files[] = $fileMap[$f2p->file_id];
2585 $notice->_setAttachments($files);
2592 * All faves of this notice
2594 * @return array Array of Fave objects
2599 if (isset($this->_faves) && is_array($this->_faves)) {
2600 return $this->_faves;
2602 $faveMap = Fave::listGet('notice_id', array($this->id));
2603 $this->_faves = $faveMap[$this->id];
2604 return $this->_faves;
2607 function _setFaves($faves)
2609 $this->_faves = $faves;
2612 static function fillFaves(&$notices)
2614 $ids = self::_idsOf($notices);
2615 $faveMap = Fave::listGet('notice_id', $ids);
2618 foreach ($faveMap as $id => $faves) {
2619 $cnt += count($faves);
2620 if (count($faves) > 0) {
2624 foreach ($notices as $notice) {
2625 $faves = $faveMap[$notice->id];
2626 $notice->_setFaves($faves);
2630 static function fillReplies(&$notices)
2632 $ids = self::_idsOf($notices);
2633 $replyMap = Reply::listGet('notice_id', $ids);
2634 foreach ($notices as $notice) {
2635 $replies = $replyMap[$notice->id];
2637 foreach ($replies as $reply) {
2638 $ids[] = $reply->profile_id;
2640 $notice->_setReplies($ids);
2644 protected $_repeats;
2646 function getRepeats()
2648 if (isset($this->_repeats) && is_array($this->_repeats)) {
2649 return $this->_repeats;
2651 $repeatMap = Notice::listGet('repeat_of', array($this->id));
2652 $this->_repeats = $repeatMap[$this->id];
2653 return $this->_repeats;
2656 function _setRepeats($repeats)
2658 $this->_repeats = $repeats;
2661 static function fillRepeats(&$notices)
2663 $ids = self::_idsOf($notices);
2664 $repeatMap = Notice::listGet('repeat_of', $ids);
2665 foreach ($notices as $notice) {
2666 $repeats = $repeatMap[$notice->id];
2667 $notice->_setRepeats($repeats);