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 = array();
147 * Will always return a profile, if anything fails it will
148 * (through _setProfile) throw a NoProfileException.
150 public function getProfile()
152 if (!isset($this->_profile[$this->profile_id])) {
153 $this->_setProfile(Profile::getKV('id', $this->profile_id));
155 return $this->_profile[$this->profile_id];
158 public function _setProfile(Profile $profile=null)
160 if (!$profile instanceof Profile) {
161 throw new NoProfileException($this->profile_id);
163 $this->_profile[$this->profile_id] = $profile;
166 function delete($useWhere=false)
168 // For auditing purposes, save a record that the notice
171 // @fixme we have some cases where things get re-run and so the
173 $deleted = Deleted_notice::getKV('id', $this->id);
175 if (!$deleted instanceof Deleted_notice) {
176 $deleted = Deleted_notice::getKV('uri', $this->uri);
179 if (!$deleted instanceof Deleted_notice) {
180 $deleted = new Deleted_notice();
182 $deleted->id = $this->id;
183 $deleted->profile_id = $this->profile_id;
184 $deleted->uri = $this->uri;
185 $deleted->created = $this->created;
186 $deleted->deleted = common_sql_now();
191 if (Event::handle('NoticeDeleteRelated', array($this))) {
193 // Clear related records
195 $this->clearReplies();
196 $this->clearRepeats();
198 $this->clearGroupInboxes();
200 $this->clearAttentions();
202 // NOTE: we don't clear queue items
205 $result = parent::delete($useWhere);
207 $this->blowOnDelete();
211 public function getUri()
217 * @param $root boolean If true, link to just the conversation root.
219 * @return URL to conversation
221 public function getConversationUrl($anchor=true)
223 return Conversation::getUrlFromNotice($this, $anchor);
227 * Get the local representation URL of this notice.
229 public function getLocalUrl()
231 return common_local_url('shownotice', array('notice' => $this->id), null, null, false);
234 public function getTitle()
237 if (Event::handle('GetNoticeTitle', array($this, &$title))) {
238 // TRANS: Title of a notice posted without a title value.
239 // TRANS: %1$s is a user name, %2$s is the notice creation date/time.
240 $title = sprintf(_('%1$s\'s status on %2$s'),
241 $this->getProfile()->getFancyName(),
242 common_exact_date($this->created));
248 * Get the original representation URL of this notice.
250 public function getUrl()
252 // The risk is we start having empty urls and non-http uris...
253 // and we can't really handle any other protocol right now.
255 case common_valid_http_url($this->url): // should we allow non-http/https URLs?
257 case $this->isLocal():
258 // let's generate a valid link to our locally available notice on demand
259 return common_local_url('shownotice', array('notice' => $this->id), null, null, false);
260 case common_valid_http_url($this->uri):
263 common_debug('No URL available for notice: id='.$this->id);
264 throw new InvalidUrlException($this->url);
268 public function get_object_type($canonical=false) {
270 ? ActivityObject::canonicalType($this->object_type)
271 : $this->object_type;
274 public static function getByUri($uri)
276 $notice = new Notice();
278 if (!$notice->find(true)) {
279 throw new NoResultException($notice);
285 * Extract #hashtags from this notice's content and save them to the database.
289 /* extract all #hastags */
290 $count = preg_match_all('/(?:^|\s)#([\pL\pN_\-\.]{1,64})/u', strtolower($this->content), $match);
295 /* Add them to the database */
296 return $this->saveKnownTags($match[1]);
300 * Record the given set of hash tags in the db for this notice.
301 * Given tag strings will be normalized and checked for dupes.
303 function saveKnownTags($hashtags)
305 //turn each into their canonical tag
306 //this is needed to remove dupes before saving e.g. #hash.tag = #hashtag
307 for($i=0; $i<count($hashtags); $i++) {
308 /* elide characters we don't want in the tag */
309 $hashtags[$i] = common_canonical_tag($hashtags[$i]);
312 foreach(array_unique($hashtags) as $hashtag) {
313 $this->saveTag($hashtag);
314 self::blow('profile:notice_ids_tagged:%d:%s', $this->profile_id, $hashtag);
320 * Record a single hash tag as associated with this notice.
321 * Tag format and uniqueness must be validated by caller.
323 function saveTag($hashtag)
325 $tag = new Notice_tag();
326 $tag->notice_id = $this->id;
327 $tag->tag = $hashtag;
328 $tag->created = $this->created;
329 $id = $tag->insert();
332 // TRANS: Server exception. %s are the error details.
333 throw new ServerException(sprintf(_('Database error inserting hashtag: %s.'),
334 $last_error->message));
338 // if it's saved, blow its cache
339 $tag->blowCache(false);
343 * Save a new notice and push it out to subscribers' inboxes.
344 * Poster's permissions are checked before sending.
346 * @param int $profile_id Profile ID of the poster
347 * @param string $content source message text; links may be shortened
348 * per current user's preference
349 * @param string $source source key ('web', 'api', etc)
350 * @param array $options Associative array of optional properties:
351 * string 'created' timestamp of notice; defaults to now
352 * int 'is_local' source/gateway ID, one of:
353 * Notice::LOCAL_PUBLIC - Local, ok to appear in public timeline
354 * Notice::REMOTE - Sent from a remote service;
355 * hide from public timeline but show in
356 * local "and friends" timelines
357 * Notice::LOCAL_NONPUBLIC - Local, but hide from public timeline
358 * Notice::GATEWAY - From another non-OStatus service;
359 * will not appear in public views
360 * float 'lat' decimal latitude for geolocation
361 * float 'lon' decimal longitude for geolocation
362 * int 'location_id' geoname identifier
363 * int 'location_ns' geoname namespace to interpret location_id
364 * int 'reply_to'; notice ID this is a reply to
365 * int 'repeat_of'; notice ID this is a repeat of
366 * string 'uri' unique ID for notice; a unique tag uri (can be url or anything too)
367 * string 'url' permalink to notice; defaults to local notice URL
368 * string 'rendered' rendered HTML version of content
369 * array 'replies' list of profile URIs for reply delivery in
370 * place of extracting @-replies from content.
371 * array 'groups' list of group IDs to deliver to, in place of
372 * extracting ! tags from content
373 * array 'tags' list of hashtag strings to save with the notice
374 * in place of extracting # tags from content
375 * array 'urls' list of attached/referred URLs to save with the
376 * notice in place of extracting links from content
377 * boolean 'distribute' whether to distribute the notice, default true
378 * string 'object_type' URL of the associated object type (default ActivityObject::NOTE)
379 * string 'verb' URL of the associated verb (default ActivityVerb::POST)
380 * int 'scope' Scope bitmask; default to SITE_SCOPE on private sites, 0 otherwise
382 * @fixme tag override
385 * @throws ClientException
387 static function saveNew($profile_id, $content, $source, array $options=null) {
388 $defaults = array('uri' => null,
393 'distribute' => true,
394 'object_type' => null,
397 if (!empty($options) && is_array($options)) {
398 $options = array_merge($defaults, $options);
404 if (!isset($is_local)) {
405 $is_local = Notice::LOCAL_PUBLIC;
408 $profile = Profile::getKV('id', $profile_id);
409 if (!$profile instanceof Profile) {
410 // TRANS: Client exception thrown when trying to save a notice for an unknown user.
411 throw new ClientException(_('Problem saving notice. Unknown user.'));
414 $user = User::getKV('id', $profile_id);
415 if ($user instanceof User) {
416 // Use the local user's shortening preferences, if applicable.
417 $final = $user->shortenLinks($content);
419 $final = common_shorten_links($content);
422 if (Notice::contentTooLong($final)) {
423 // TRANS: Client exception thrown if a notice contains too many characters.
424 throw new ClientException(_('Problem saving notice. Too long.'));
427 if (common_config('throttle', 'enabled') && !Notice::checkEditThrottle($profile_id)) {
428 common_log(LOG_WARNING, 'Excessive posting by profile #' . $profile_id . '; throttled.');
429 // TRANS: Client exception thrown when a user tries to post too many notices in a given time frame.
430 throw new ClientException(_('Too many notices too fast; take a breather '.
431 'and post again in a few minutes.'));
434 if (common_config('site', 'dupelimit') > 0 && !Notice::checkDupes($profile_id, $final)) {
435 common_log(LOG_WARNING, 'Dupe posting by profile #' . $profile_id . '; throttled.');
436 // TRANS: Client exception thrown when a user tries to post too many duplicate notices in a given time frame.
437 throw new ClientException(_('Too many duplicate messages too quickly;'.
438 ' take a breather and post again in a few minutes.'));
441 if (!$profile->hasRight(Right::NEWNOTICE)) {
442 common_log(LOG_WARNING, "Attempted post from user disallowed to post: " . $profile->nickname);
444 // TRANS: Client exception thrown when a user tries to post while being banned.
445 throw new ClientException(_('You are banned from posting notices on this site.'), 403);
448 $notice = new Notice();
449 $notice->profile_id = $profile_id;
451 $autosource = common_config('public', 'autosource');
453 // Sandboxed are non-false, but not 1, either
455 if (!$profile->hasRight(Right::PUBLICNOTICE) ||
456 ($source && $autosource && in_array($source, $autosource))) {
457 $notice->is_local = Notice::LOCAL_NONPUBLIC;
459 $notice->is_local = $is_local;
462 if (!empty($created)) {
463 $notice->created = $created;
465 $notice->created = common_sql_now();
468 if (!$notice->isLocal()) {
469 // Only do these checks for non-local notices. Local notices will generate these values later.
470 if (!common_valid_http_url($url)) {
471 common_debug('Bad notice URL: ['.$url.'], URI: ['.$uri.']. Cannot link back to original! This is normal for shared notices etc.');
474 throw new ServerException('No URI for remote notice. Cannot accept that.');
478 $notice->content = $final;
480 $notice->source = $source;
484 // Get the groups here so we can figure out replies and such
485 if (!isset($groups)) {
486 $groups = User_group::idsFromText($notice->content, $profile);
491 // Handle repeat case
493 if (isset($repeat_of)) {
495 // Check for a private one
497 $repeat = Notice::getKV('id', $repeat_of);
499 if (!($repeat instanceof Notice)) {
500 // TRANS: Client exception thrown in notice when trying to repeat a missing or deleted notice.
501 throw new ClientException(_('Cannot repeat; original notice is missing or deleted.'));
504 if ($profile->id == $repeat->profile_id) {
505 // TRANS: Client error displayed when trying to repeat an own notice.
506 throw new ClientException(_('You cannot repeat your own notice.'));
509 if ($repeat->scope != Notice::SITE_SCOPE &&
510 $repeat->scope != Notice::PUBLIC_SCOPE) {
511 // TRANS: Client error displayed when trying to repeat a non-public notice.
512 throw new ClientException(_('Cannot repeat a private notice.'), 403);
515 if (!$repeat->inScope($profile)) {
516 // The generic checks above should cover this, but let's be sure!
517 // TRANS: Client error displayed when trying to repeat a notice you cannot access.
518 throw new ClientException(_('Cannot repeat a notice you cannot read.'), 403);
521 if ($profile->hasRepeated($repeat)) {
522 // TRANS: Client error displayed when trying to repeat an already repeated notice.
523 throw new ClientException(_('You already repeated that notice.'));
526 $notice->repeat_of = $repeat->id;
527 $notice->conversation = $repeat->conversation;
531 // If $reply_to is specified, we check that it exists, and then
532 // return it if it does
533 if (!empty($reply_to)) {
534 $reply = Notice::getKV('id', $reply_to);
535 } elseif (in_array($source, array('xmpp', 'mail', 'sms'))) {
536 // If the source lacks capability of sending the "reply_to"
537 // metadata, let's try to find an inline replyto-reference.
538 $reply = self::getInlineReplyTo($profile, $final);
541 if ($reply instanceof Notice) {
542 if (!$reply->inScope($profile)) {
543 // TRANS: Client error displayed when trying to reply to a notice a the target has no access to.
544 // TRANS: %1$s is a user nickname, %2$d is a notice ID (number).
545 throw new ClientException(sprintf(_('%1$s has no access to notice %2$d.'),
546 $profile->nickname, $reply->id), 403);
549 // If it's a repeat, the reply_to should be to the original
550 if (!empty($reply->repeat_of)) {
551 $notice->reply_to = $reply->repeat_of;
553 $notice->reply_to = $reply->id;
555 // But the conversation ought to be the same :)
556 $notice->conversation = $reply->conversation;
558 // If the original is private to a group, and notice has
559 // no group specified, make it to the same group(s)
561 if (empty($groups) && ($reply->scope & Notice::GROUP_SCOPE)) {
563 $replyGroups = $reply->getGroups();
564 foreach ($replyGroups as $group) {
565 if ($profile->isMember($group)) {
566 $groups[] = $group->id;
575 if (!empty($lat) && !empty($lon)) {
580 if (!empty($location_ns) && !empty($location_id)) {
581 $notice->location_id = $location_id;
582 $notice->location_ns = $location_ns;
585 if (!empty($rendered)) {
586 $notice->rendered = $rendered;
588 $notice->rendered = common_render_content($final, $notice);
592 if (!empty($notice->repeat_of)) {
593 $notice->verb = ActivityVerb::SHARE;
594 $notice->object_type = ActivityObject::ACTIVITY;
596 $notice->verb = ActivityVerb::POST;
599 $notice->verb = $verb;
602 if (empty($object_type)) {
603 $notice->object_type = (empty($notice->reply_to)) ? ActivityObject::NOTE : ActivityObject::COMMENT;
605 $notice->object_type = $object_type;
608 if (is_null($scope)) { // 0 is a valid value
609 if (!empty($reply)) {
610 $notice->scope = $reply->scope;
612 $notice->scope = self::defaultScope();
615 $notice->scope = $scope;
618 // For private streams
621 $user = $profile->getUser();
623 if ($user->private_stream &&
624 ($notice->scope == Notice::PUBLIC_SCOPE ||
625 $notice->scope == Notice::SITE_SCOPE)) {
626 $notice->scope |= Notice::FOLLOWER_SCOPE;
628 } catch (NoSuchUserException $e) {
629 // Cannot handle private streams for remote profiles
632 // Force the scope for private groups
634 foreach ($groups as $groupId) {
635 $group = User_group::getKV('id', $groupId);
636 if ($group instanceof User_group) {
637 if ($group->force_scope) {
638 $notice->scope |= Notice::GROUP_SCOPE;
644 if (Event::handle('StartNoticeSave', array(&$notice))) {
646 // XXX: some of these functions write to the DB
648 $id = $notice->insert();
651 common_log_db_error($notice, 'INSERT', __FILE__);
652 // TRANS: Server exception thrown when a notice cannot be saved.
653 throw new ServerException(_('Problem saving notice.'));
656 // Update ID-dependent columns: URI, conversation
658 $orig = clone($notice);
662 // We can only get here if it's a local notice, since remote notices
663 // should've bailed out earlier due to lacking a URI.
664 if (empty($notice->uri)) {
665 $notice->uri = sprintf('%s%s=%d:%s=%s',
667 'noticeId', $notice->id,
668 'objectType', $notice->get_object_type(true));
672 // If it's not part of a conversation, it's
673 // the beginning of a new conversation.
675 if (empty($notice->conversation)) {
676 $conv = Conversation::create($notice);
677 $notice->conversation = $conv->id;
682 if ($notice->update($orig) === false) {
683 common_log_db_error($notice, 'UPDATE', __FILE__);
684 // TRANS: Server exception thrown when a notice cannot be updated.
685 throw new ServerException(_('Problem saving notice.'));
691 // Clear the cache for subscribed users, so they'll update at next request
692 // XXX: someone clever could prepend instead of clearing the cache
694 $notice->blowOnInsert();
696 // Save per-notice metadata...
698 if (isset($replies)) {
699 $notice->saveKnownReplies($replies);
701 $notice->saveReplies();
705 $notice->saveKnownTags($tags);
710 // Note: groups may save tags, so must be run after tags are saved
711 // to avoid errors on duplicates.
712 // Note: groups should always be set.
714 $notice->saveKnownGroups($groups);
717 $notice->saveKnownUrls($urls);
723 // Prepare inbox delivery, may be queued to background.
724 $notice->distribute();
730 function blowOnInsert($conversation = false)
732 $this->blowStream('profile:notice_ids:%d', $this->profile_id);
734 if ($this->isPublic()) {
735 $this->blowStream('public');
738 self::blow('notice:list-ids:conversation:%s', $this->conversation);
739 self::blow('conversation:notice_count:%d', $this->conversation);
741 if (!empty($this->repeat_of)) {
742 // XXX: we should probably only use one of these
743 $this->blowStream('notice:repeats:%d', $this->repeat_of);
744 self::blow('notice:list-ids:repeat_of:%d', $this->repeat_of);
747 $original = Notice::getKV('id', $this->repeat_of);
749 if ($original instanceof Notice) {
750 $originalUser = User::getKV('id', $original->profile_id);
751 if ($originalUser instanceof User) {
752 $this->blowStream('user:repeats_of_me:%d', $originalUser->id);
756 $profile = Profile::getKV($this->profile_id);
758 if ($profile instanceof Profile) {
759 $profile->blowNoticeCount();
762 $ptags = $this->getProfileTags();
763 foreach ($ptags as $ptag) {
764 $ptag->blowNoticeStreamCache();
769 * Clear cache entries related to this notice at delete time.
770 * Necessary to avoid breaking paging on public, profile timelines.
772 function blowOnDelete()
774 $this->blowOnInsert();
776 self::blow('profile:notice_ids:%d;last', $this->profile_id);
778 if ($this->isPublic()) {
779 self::blow('public;last');
782 self::blow('fave:by_notice', $this->id);
784 if ($this->conversation) {
785 // In case we're the first, will need to calc a new root.
786 self::blow('notice:conversation_root:%d', $this->conversation);
789 $ptags = $this->getProfileTags();
790 foreach ($ptags as $ptag) {
791 $ptag->blowNoticeStreamCache(true);
795 function blowStream()
797 $c = self::memcache();
803 $args = func_get_args();
805 $format = array_shift($args);
807 $keyPart = vsprintf($format, $args);
809 $cacheKey = Cache::key($keyPart);
811 $c->delete($cacheKey);
813 // delete the "last" stream, too, if this notice is
814 // older than the top of that stream
816 $lastKey = $cacheKey.';last';
818 $lastStr = $c->get($lastKey);
820 if ($lastStr !== false) {
821 $window = explode(',', $lastStr);
822 $lastID = $window[0];
823 $lastNotice = Notice::getKV('id', $lastID);
824 if (!$lastNotice instanceof Notice // just weird
825 || strtotime($lastNotice->created) >= strtotime($this->created)) {
826 $c->delete($lastKey);
831 /** save all urls in the notice to the db
833 * follow redirects and save all available file information
834 * (mimetype, date, size, oembed, etc.)
838 function saveUrls() {
839 if (common_config('attachments', 'process_links')) {
840 common_replace_urls_callback($this->content, array($this, 'saveUrl'), $this->id);
845 * Save the given URLs as related links/attachments to the db
847 * follow redirects and save all available file information
848 * (mimetype, date, size, oembed, etc.)
852 function saveKnownUrls($urls)
854 if (common_config('attachments', 'process_links')) {
855 // @fixme validation?
856 foreach (array_unique($urls) as $url) {
858 File::processNew($url, $this->id);
859 } catch (ServerException $e) {
860 // Could not save URL. Log it?
869 function saveUrl($url, $notice_id) {
871 File::processNew($url, $notice_id);
872 } catch (ServerException $e) {
873 // Could not save URL. Log it?
877 static function checkDupes($profile_id, $content) {
878 $profile = Profile::getKV($profile_id);
879 if (!$profile instanceof Profile) {
882 $notice = $profile->getNotices(0, CachingNoticeStream::CACHE_WINDOW);
883 if (!empty($notice)) {
885 while ($notice->fetch()) {
886 if (time() - strtotime($notice->created) >= common_config('site', 'dupelimit')) {
888 } else if ($notice->content == $content) {
893 // If we get here, oldest item in cache window is not
894 // old enough for dupe limit; do direct check against DB
895 $notice = new Notice();
896 $notice->profile_id = $profile_id;
897 $notice->content = $content;
898 $threshold = common_sql_date(time() - common_config('site', 'dupelimit'));
899 $notice->whereAdd(sprintf("created > '%s'", $notice->escape($threshold)));
901 $cnt = $notice->count();
905 static function checkEditThrottle($profile_id) {
906 $profile = Profile::getKV($profile_id);
907 if (!$profile instanceof Profile) {
910 // Get the Nth notice
911 $notice = $profile->getNotices(common_config('throttle', 'count') - 1, 1);
912 if ($notice && $notice->fetch()) {
913 // If the Nth notice was posted less than timespan seconds ago
914 if (time() - strtotime($notice->created) <= common_config('throttle', 'timespan')) {
919 // Either not N notices in the stream, OR the Nth was not posted within timespan seconds
923 protected $_attachments = array();
925 function attachments() {
926 if (isset($this->_attachments[$this->id])) {
927 return $this->_attachments[$this->id];
930 $f2ps = File_to_post::listGet('post_id', array($this->id));
934 foreach ($f2ps[$this->id] as $f2p) {
935 $ids[] = $f2p->file_id;
938 $files = File::multiGet('id', $ids);
940 $this->_attachments[$this->id] = $files->fetchAll();
942 return $this->_attachments[$this->id];
945 function _setAttachments($attachments)
947 $this->_attachments[$this->id] = $attachments;
950 function publicStream($offset=0, $limit=20, $since_id=0, $max_id=0)
952 $stream = new PublicNoticeStream();
953 return $stream->getNotices($offset, $limit, $since_id, $max_id);
957 function conversationStream($id, $offset=0, $limit=20, $since_id=0, $max_id=0)
959 $stream = new ConversationNoticeStream($id);
961 return $stream->getNotices($offset, $limit, $since_id, $max_id);
965 * Is this notice part of an active conversation?
967 * @return boolean true if other messages exist in the same
968 * conversation, false if this is the only one
970 function hasConversation()
972 if (!empty($this->conversation)) {
973 $conversation = Notice::conversationStream(
979 if ($conversation->N > 0) {
987 * Grab the earliest notice from this conversation.
989 * @return Notice or null
991 function conversationRoot($profile=-1)
993 // XXX: can this happen?
995 if (empty($this->conversation)) {
999 // Get the current profile if not specified
1001 if (is_int($profile) && $profile == -1) {
1002 $profile = Profile::current();
1005 // If this notice is out of scope, no root for you!
1007 if (!$this->inScope($profile)) {
1011 // If this isn't a reply to anything, then it's its own
1014 if (empty($this->reply_to)) {
1018 if (is_null($profile)) {
1019 $keypart = sprintf('notice:conversation_root:%d:null', $this->id);
1021 $keypart = sprintf('notice:conversation_root:%d:%d',
1026 $root = self::cacheGet($keypart);
1028 if ($root !== false && $root->inScope($profile)) {
1035 $parent = $last->getParent();
1036 if ($parent->inScope($profile)) {
1040 } catch (Exception $e) {
1041 // Latest notice has no parent
1043 // No parent, or parent out of scope
1048 self::cacheSet($keypart, $root);
1054 * Pull up a full list of local recipients who will be getting
1055 * this notice in their inbox. Results will be cached, so don't
1056 * change the input data wily-nilly!
1058 * @param array $groups optional list of Group objects;
1059 * if left empty, will be loaded from group_inbox records
1060 * @param array $recipient optional list of reply profile ids
1061 * if left empty, will be loaded from reply records
1062 * @return array associating recipient user IDs with an inbox source constant
1064 function whoGets(array $groups=null, array $recipients=null)
1066 $c = self::memcache();
1069 $ni = $c->get(Cache::key('notice:who_gets:'.$this->id));
1070 if ($ni !== false) {
1075 if (is_null($recipients)) {
1076 $recipients = $this->getReplies();
1081 // Give plugins a chance to add folks in at start...
1082 if (Event::handle('StartNoticeWhoGets', array($this, &$ni))) {
1084 $users = $this->getSubscribedUsers();
1085 foreach ($users as $id) {
1086 $ni[$id] = NOTICE_INBOX_SOURCE_SUB;
1089 if (is_null($groups)) {
1090 $groups = $this->getGroups();
1092 foreach ($groups as $group) {
1093 $users = $group->getUserMembers();
1094 foreach ($users as $id) {
1095 if (!array_key_exists($id, $ni)) {
1096 $ni[$id] = NOTICE_INBOX_SOURCE_GROUP;
1101 $ptAtts = $this->getAttentionsFromProfileTags();
1102 foreach ($ptAtts as $key=>$val) {
1103 if (!array_key_exists($key, $ni)) {
1108 foreach ($recipients as $recipient) {
1109 if (!array_key_exists($recipient, $ni)) {
1110 $ni[$recipient] = NOTICE_INBOX_SOURCE_REPLY;
1114 // Exclude any deleted, non-local, or blocking recipients.
1115 $profile = $this->getProfile();
1116 $originalProfile = null;
1117 if ($this->repeat_of) {
1118 // Check blocks against the original notice's poster as well.
1119 $original = Notice::getKV('id', $this->repeat_of);
1120 if ($original instanceof Notice) {
1121 $originalProfile = $original->getProfile();
1125 foreach ($ni as $id => $source) {
1127 $user = User::getKV('id', $id);
1128 if (!$user instanceof User ||
1129 $user->hasBlocked($profile) ||
1130 ($originalProfile && $user->hasBlocked($originalProfile))) {
1133 } catch (UserNoProfileException $e) {
1134 // User doesn't have a profile; invalid; skip them.
1139 // Give plugins a chance to filter out...
1140 Event::handle('EndNoticeWhoGets', array($this, &$ni));
1144 // XXX: pack this data better
1145 $c->set(Cache::key('notice:who_gets:'.$this->id), $ni);
1151 function getSubscribedUsers()
1155 if(common_config('db','quote_identifiers'))
1156 $user_table = '"user"';
1157 else $user_table = 'user';
1161 'FROM '. $user_table .' JOIN subscription '.
1162 'ON '. $user_table .'.id = subscription.subscriber ' .
1163 'WHERE subscription.subscribed = %d ';
1165 $user->query(sprintf($qry, $this->profile_id));
1169 while ($user->fetch()) {
1178 function getProfileTags()
1180 $profile = $this->getProfile();
1181 $list = $profile->getOtherTags($profile);
1184 while($list->fetch()) {
1185 $ptags[] = clone($list);
1191 public function getAttentionsFromProfileTags()
1194 $ptags = $this->getProfileTags();
1195 foreach ($ptags as $ptag) {
1196 $users = $ptag->getUserSubscribers();
1197 foreach ($users as $id) {
1198 $ni[$id] = NOTICE_INBOX_SOURCE_PROFILE_TAG;
1205 * Record this notice to the given group inboxes for delivery.
1206 * Overrides the regular parsing of !group markup.
1208 * @param string $group_ids
1209 * @fixme might prefer URIs as identifiers, as for replies?
1210 * best with generalizations on user_group to support
1211 * remote groups better.
1213 function saveKnownGroups($group_ids)
1215 if (!is_array($group_ids)) {
1216 // TRANS: Server exception thrown when no array is provided to the method saveKnownGroups().
1217 throw new ServerException(_('Bad type provided to saveKnownGroups.'));
1221 foreach (array_unique($group_ids) as $id) {
1222 $group = User_group::getKV('id', $id);
1223 if ($group instanceof User_group) {
1224 common_log(LOG_ERR, "Local delivery to group id $id, $group->nickname");
1225 $result = $this->addToGroupInbox($group);
1227 common_log_db_error($gi, 'INSERT', __FILE__);
1230 if (common_config('group', 'addtag')) {
1231 // we automatically add a tag for every group name, too
1233 $tag = Notice_tag::pkeyGet(array('tag' => common_canonical_tag($group->nickname),
1234 'notice_id' => $this->id));
1236 if (is_null($tag)) {
1237 $this->saveTag($group->nickname);
1241 $groups[] = clone($group);
1243 common_log(LOG_ERR, "Local delivery to group id $id skipped, doesn't exist");
1250 function addToGroupInbox(User_group $group)
1252 $gi = Group_inbox::pkeyGet(array('group_id' => $group->id,
1253 'notice_id' => $this->id));
1255 if (!$gi instanceof Group_inbox) {
1257 $gi = new Group_inbox();
1259 $gi->group_id = $group->id;
1260 $gi->notice_id = $this->id;
1261 $gi->created = $this->created;
1263 $result = $gi->insert();
1266 common_log_db_error($gi, 'INSERT', __FILE__);
1267 // TRANS: Server exception thrown when an update for a group inbox fails.
1268 throw new ServerException(_('Problem saving group inbox.'));
1271 self::blow('user_group:notice_ids:%d', $gi->group_id);
1278 * Save reply records indicating that this notice needs to be
1279 * delivered to the local users with the given URIs.
1281 * Since this is expected to be used when saving foreign-sourced
1282 * messages, we won't deliver to any remote targets as that's the
1283 * source service's responsibility.
1285 * Mail notifications etc will be handled later.
1287 * @param array $uris Array of unique identifier URIs for recipients
1289 function saveKnownReplies(array $uris)
1295 $sender = Profile::getKV($this->profile_id);
1297 foreach (array_unique($uris) as $uri) {
1299 $profile = Profile::fromUri($uri);
1300 } catch (UnknownUriException $e) {
1301 common_log(LOG_WARNING, "Unable to determine profile for URI '$uri'");
1305 if ($profile->hasBlocked($sender)) {
1306 common_log(LOG_INFO, "Not saving reply to profile {$profile->id} ($uri) from sender {$sender->id} because of a block.");
1310 $this->saveReply($profile->id);
1311 self::blow('reply:stream:%d', $profile->id);
1318 * Pull @-replies from this message's content in StatusNet markup format
1319 * and save reply records indicating that this message needs to be
1320 * delivered to those users.
1322 * Mail notifications to local profiles will be sent later.
1324 * @return array of integer profile IDs
1327 function saveReplies()
1329 // Don't save reply data for repeats
1331 if (!empty($this->repeat_of)) {
1335 $sender = $this->getProfile();
1339 // If it's a reply, save for the replied-to author
1341 $parent = $this->getParent();
1342 $parentauthor = $parent->getProfile();
1343 $this->saveReply($parentauthor->id);
1344 $replied[$parentauthor->id] = 1;
1345 self::blow('reply:stream:%d', $parentauthor->id);
1346 } catch (Exception $e) {
1347 // Not a reply, since it has no parent!
1350 // @todo ideally this parser information would only
1351 // be calculated once.
1353 $mentions = common_find_mentions($this->content, $this);
1355 // store replied only for first @ (what user/notice what the reply directed,
1356 // we assume first @ is it)
1358 foreach ($mentions as $mention) {
1360 foreach ($mention['mentioned'] as $mentioned) {
1362 // skip if they're already covered
1364 if (!empty($replied[$mentioned->id])) {
1368 // Don't save replies from blocked profile to local user
1370 $mentioned_user = User::getKV('id', $mentioned->id);
1371 if ($mentioned_user instanceof User && $mentioned_user->hasBlocked($sender)) {
1375 $this->saveReply($mentioned->id);
1376 $replied[$mentioned->id] = 1;
1377 self::blow('reply:stream:%d', $mentioned->id);
1381 $recipientIds = array_keys($replied);
1383 return $recipientIds;
1386 function saveReply($profileId)
1388 $reply = new Reply();
1390 $reply->notice_id = $this->id;
1391 $reply->profile_id = $profileId;
1392 $reply->modified = $this->created;
1399 protected $_replies = array();
1402 * Pull the complete list of @-reply targets for this notice.
1404 * @return array of integer profile ids
1406 function getReplies()
1408 if (isset($this->_replies[$this->id])) {
1409 return $this->_replies[$this->id];
1412 $replyMap = Reply::listGet('notice_id', array($this->id));
1416 foreach ($replyMap[$this->id] as $reply) {
1417 $ids[] = $reply->profile_id;
1420 $this->_replies[$this->id] = $ids;
1425 function _setReplies($replies)
1427 $this->_replies[$this->id] = $replies;
1431 * Pull the complete list of @-reply targets for this notice.
1433 * @return array of Profiles
1435 function getReplyProfiles()
1437 $ids = $this->getReplies();
1439 $profiles = Profile::multiGet('id', $ids);
1441 return $profiles->fetchAll();
1445 * Send e-mail notifications to local @-reply targets.
1447 * Replies must already have been saved; this is expected to be run
1448 * from the distrib queue handler.
1450 function sendReplyNotifications()
1452 // Don't send reply notifications for repeats
1454 if (!empty($this->repeat_of)) {
1458 $recipientIds = $this->getReplies();
1460 foreach ($recipientIds as $recipientId) {
1461 $user = User::getKV('id', $recipientId);
1462 if ($user instanceof User) {
1463 mail_notify_attn($user, $this);
1469 * Pull list of groups this notice needs to be delivered to,
1470 * as previously recorded by saveKnownGroups().
1472 * @return array of Group objects
1475 protected $_groups = array();
1477 function getGroups()
1479 // Don't save groups for repeats
1481 if (!empty($this->repeat_of)) {
1485 if (isset($this->_groups[$this->id])) {
1486 return $this->_groups[$this->id];
1489 $gis = Group_inbox::listGet('notice_id', array($this->id));
1493 foreach ($gis[$this->id] as $gi)
1495 $ids[] = $gi->group_id;
1498 $groups = User_group::multiGet('id', $ids);
1500 $this->_groups[$this->id] = $groups->fetchAll();
1502 return $this->_groups[$this->id];
1505 function _setGroups($groups)
1507 $this->_groups[$this->id] = $groups;
1511 * Convert a notice into an activity for export.
1513 * @param User $cur Current user
1515 * @return Activity activity object representing this Notice.
1518 function asActivity($cur=null)
1520 $act = self::cacheGet(Cache::codeKey('notice:as-activity:'.$this->id));
1522 if ($act instanceof Activity) {
1525 $act = new Activity();
1527 if (Event::handle('StartNoticeAsActivity', array($this, &$act))) {
1529 $act->id = $this->uri;
1530 $act->time = strtotime($this->created);
1532 $act->link = $this->getUrl();
1533 } catch (InvalidUrlException $e) {
1534 // The notice is probably a share or similar, which don't
1535 // have a representational URL of their own.
1537 $act->content = common_xml_safe_str($this->rendered);
1539 $profile = $this->getProfile();
1541 $act->actor = ActivityObject::fromProfile($profile);
1542 $act->actor->extra[] = $profile->profileInfo($cur);
1544 $act->verb = $this->verb;
1546 if ($this->repeat_of) {
1547 $repeated = Notice::getKV('id', $this->repeat_of);
1548 if ($repeated instanceof Notice) {
1549 $act->objects[] = $repeated->asActivity($cur);
1552 $act->objects[] = ActivityObject::fromNotice($this);
1555 // XXX: should this be handled by default processing for object entry?
1559 $tags = $this->getTags();
1561 foreach ($tags as $tag) {
1562 $cat = new AtomCategory();
1565 $act->categories[] = $cat;
1569 // XXX: use Atom Media and/or File activity objects instead
1571 $attachments = $this->attachments();
1573 foreach ($attachments as $attachment) {
1574 // Save local attachments
1575 if (!empty($attachment->filename)) {
1576 $act->attachments[] = ActivityObject::fromFile($attachment);
1580 $ctx = new ActivityContext();
1583 $reply = $this->getParent();
1584 $ctx->replyToID = $reply->getUri();
1585 $ctx->replyToUrl = $reply->getUrl();
1586 } catch (Exception $e) {
1587 // This is not a reply to something
1590 $ctx->location = $this->getLocation();
1594 if (!empty($this->conversation)) {
1595 $conv = Conversation::getKV('id', $this->conversation);
1596 if ($conv instanceof Conversation) {
1597 $ctx->conversation = $conv->uri;
1601 $reply_ids = $this->getReplies();
1603 foreach ($reply_ids as $id) {
1604 $rprofile = Profile::getKV('id', $id);
1605 if ($rprofile instanceof Profile) {
1606 $ctx->attention[$rprofile->getUri()] = ActivityObject::PERSON;
1610 $groups = $this->getGroups();
1612 foreach ($groups as $group) {
1613 $ctx->attention[$group->getUri()] = ActivityObject::GROUP;
1616 switch ($this->scope) {
1617 case Notice::PUBLIC_SCOPE:
1618 $ctx->attention[ActivityContext::ATTN_PUBLIC] = ActivityObject::COLLECTION;
1620 case Notice::FOLLOWER_SCOPE:
1621 $surl = common_local_url("subscribers", array('nickname' => $profile->nickname));
1622 $ctx->attention[$surl] = ActivityObject::COLLECTION;
1626 $act->context = $ctx;
1628 $source = $this->getSource();
1630 if ($source instanceof Notice_source) {
1631 $act->generator = ActivityObject::fromNoticeSource($source);
1636 $atom_feed = $profile->getAtomFeed();
1638 if (!empty($atom_feed)) {
1640 $act->source = new ActivitySource();
1642 // XXX: we should store the actual feed ID
1644 $act->source->id = $atom_feed;
1646 // XXX: we should store the actual feed title
1648 $act->source->title = $profile->getBestName();
1650 $act->source->links['alternate'] = $profile->profileurl;
1651 $act->source->links['self'] = $atom_feed;
1653 $act->source->icon = $profile->avatarUrl(AVATAR_PROFILE_SIZE);
1655 $notice = $profile->getCurrentNotice();
1657 if ($notice instanceof Notice) {
1658 $act->source->updated = self::utcDate($notice->created);
1661 $user = User::getKV('id', $profile->id);
1663 if ($user instanceof User) {
1664 $act->source->links['license'] = common_config('license', 'url');
1668 if ($this->isLocal()) {
1669 $act->selfLink = common_local_url('ApiStatusesShow', array('id' => $this->id,
1670 'format' => 'atom'));
1671 $act->editLink = $act->selfLink;
1674 Event::handle('EndNoticeAsActivity', array($this, &$act));
1677 self::cacheSet(Cache::codeKey('notice:as-activity:'.$this->id), $act);
1682 // This has gotten way too long. Needs to be sliced up into functional bits
1683 // or ideally exported to a utility class.
1685 function asAtomEntry($namespace=false,
1690 $act = $this->asActivity($cur);
1691 $act->extra[] = $this->noticeInfo($cur);
1692 return $act->asString($namespace, $author, $source);
1696 * Extra notice info for atom entries
1698 * Clients use some extra notice info in the atom stream.
1699 * This gives it to them.
1701 * @param User $cur Current user
1703 * @return array representation of <statusnet:notice_info> element
1706 function noticeInfo($cur)
1708 // local notice ID (useful to clients for ordering)
1710 $noticeInfoAttr = array('local_id' => $this->id);
1714 $ns = $this->getSource();
1716 if ($ns instanceof Notice_source) {
1717 $noticeInfoAttr['source'] = $ns->code;
1718 if (!empty($ns->url)) {
1719 $noticeInfoAttr['source_link'] = $ns->url;
1720 if (!empty($ns->name)) {
1721 $noticeInfoAttr['source'] = '<a href="'
1722 . htmlspecialchars($ns->url)
1723 . '" rel="nofollow">'
1724 . htmlspecialchars($ns->name)
1730 // favorite and repeated
1734 $scoped = $cur->getProfile();
1735 $noticeInfoAttr['repeated'] = ($scoped->hasRepeated($this)) ? "true" : "false";
1738 if (!empty($this->repeat_of)) {
1739 $noticeInfoAttr['repeat_of'] = $this->repeat_of;
1742 Event::handle('StatusNetApiNoticeInfo', array($this, &$noticeInfoAttr, $scoped));
1744 return array('statusnet:notice_info', $noticeInfoAttr, null);
1748 * Returns an XML string fragment with a reference to a notice as an
1749 * Activity Streams noun object with the given element type.
1751 * Assumes that 'activity' namespace has been previously defined.
1753 * @param string $element one of 'subject', 'object', 'target'
1757 function asActivityNoun($element)
1759 $noun = ActivityObject::fromNotice($this);
1760 return $noun->asString('activity:' . $element);
1764 * Determine which notice, if any, a new notice is in reply to.
1766 * For conversation tracking, we try to see where this notice fits
1767 * in the tree. Beware that this may very well give false positives
1768 * and add replies to wrong threads (if there have been newer posts
1769 * by the same user as we're replying to).
1771 * @param Profile $sender Author profile
1772 * @param string $content Final notice content
1774 * @return integer ID of replied-to notice, or null for not a reply.
1777 static function getInlineReplyTo(Profile $sender, $content)
1779 // Is there an initial @ or T?
1780 if (preg_match('/^T ([A-Z0-9]{1,64}) /', $content, $match)
1781 || preg_match('/^@([a-z0-9]{1,64})\s+/', $content, $match)) {
1782 $nickname = common_canonical_nickname($match[1]);
1787 // Figure out who that is.
1788 $recipient = common_relative_profile($sender, $nickname, common_sql_now());
1790 if ($recipient instanceof Profile) {
1791 // Get their last notice
1792 $last = $recipient->getCurrentNotice();
1793 if ($last instanceof Notice) {
1796 // Maybe in the future we want to handle something else below
1797 // so don't return getCurrentNotice() immediately.
1803 static function maxContent()
1805 $contentlimit = common_config('notice', 'contentlimit');
1806 // null => use global limit (distinct from 0!)
1807 if (is_null($contentlimit)) {
1808 $contentlimit = common_config('site', 'textlimit');
1810 return $contentlimit;
1813 static function contentTooLong($content)
1815 $contentlimit = self::maxContent();
1816 return ($contentlimit > 0 && !empty($content) && (mb_strlen($content) > $contentlimit));
1819 function getLocation()
1823 if (!empty($this->location_id) && !empty($this->location_ns)) {
1824 $location = Location::fromId($this->location_id, $this->location_ns);
1827 if (is_null($location)) { // no ID, or Location::fromId() failed
1828 if (!empty($this->lat) && !empty($this->lon)) {
1829 $location = Location::fromLatLon($this->lat, $this->lon);
1837 * Convenience function for posting a repeat of an existing message.
1839 * @param Profile $repeater Profile which is doing the repeat
1840 * @param string $source: posting source key, eg 'web', 'api', etc
1843 * @throws Exception on failure or permission problems
1845 function repeat(Profile $repeater, $source)
1847 $author = $this->getProfile();
1849 // TRANS: Message used to repeat a notice. RT is the abbreviation of 'retweet'.
1850 // TRANS: %1$s is the repeated user's name, %2$s is the repeated notice.
1851 $content = sprintf(_('RT @%1$s %2$s'),
1852 $author->getNickname(),
1855 // Scope is same as this one's
1856 return self::saveNew($repeater->id,
1859 array('repeat_of' => $this->id,
1860 'scope' => $this->scope));
1863 // These are supposed to be in chron order!
1865 function repeatStream($limit=100)
1867 $cache = Cache::instance();
1869 if (empty($cache)) {
1870 $ids = $this->_repeatStreamDirect($limit);
1872 $idstr = $cache->get(Cache::key('notice:repeats:'.$this->id));
1873 if ($idstr !== false) {
1874 if (empty($idstr)) {
1877 $ids = explode(',', $idstr);
1880 $ids = $this->_repeatStreamDirect(100);
1881 $cache->set(Cache::key('notice:repeats:'.$this->id), implode(',', $ids));
1884 // We do a max of 100, so slice down to limit
1885 $ids = array_slice($ids, 0, $limit);
1889 return NoticeStream::getStreamByIds($ids);
1892 function _repeatStreamDirect($limit)
1894 $notice = new Notice();
1896 $notice->selectAdd(); // clears it
1897 $notice->selectAdd('id');
1899 $notice->repeat_of = $this->id;
1901 $notice->orderBy('created, id'); // NB: asc!
1903 if (!is_null($limit)) {
1904 $notice->limit(0, $limit);
1907 return $notice->fetchAll('id');
1910 function locationOptions($lat, $lon, $location_id, $location_ns, $profile = null)
1914 if (!empty($location_id) && !empty($location_ns)) {
1915 $options['location_id'] = $location_id;
1916 $options['location_ns'] = $location_ns;
1918 $location = Location::fromId($location_id, $location_ns);
1920 if ($location instanceof Location) {
1921 $options['lat'] = $location->lat;
1922 $options['lon'] = $location->lon;
1925 } else if (!empty($lat) && !empty($lon)) {
1926 $options['lat'] = $lat;
1927 $options['lon'] = $lon;
1929 $location = Location::fromLatLon($lat, $lon);
1931 if ($location instanceof Location) {
1932 $options['location_id'] = $location->location_id;
1933 $options['location_ns'] = $location->location_ns;
1935 } else if (!empty($profile)) {
1936 if (isset($profile->lat) && isset($profile->lon)) {
1937 $options['lat'] = $profile->lat;
1938 $options['lon'] = $profile->lon;
1941 if (isset($profile->location_id) && isset($profile->location_ns)) {
1942 $options['location_id'] = $profile->location_id;
1943 $options['location_ns'] = $profile->location_ns;
1950 function clearAttentions()
1952 $att = new Attention();
1953 $att->notice_id = $this->getID();
1956 while ($att->fetch()) {
1957 // Can't do delete() on the object directly since it won't remove all of it
1958 $other = clone($att);
1964 function clearReplies()
1966 $replyNotice = new Notice();
1967 $replyNotice->reply_to = $this->id;
1969 //Null any notices that are replies to this notice
1971 if ($replyNotice->find()) {
1972 while ($replyNotice->fetch()) {
1973 $orig = clone($replyNotice);
1974 $replyNotice->reply_to = null;
1975 $replyNotice->update($orig);
1981 $reply = new Reply();
1982 $reply->notice_id = $this->id;
1984 if ($reply->find()) {
1985 while($reply->fetch()) {
1986 self::blow('reply:stream:%d', $reply->profile_id);
1994 function clearFiles()
1996 $f2p = new File_to_post();
1998 $f2p->post_id = $this->id;
2001 while ($f2p->fetch()) {
2005 // FIXME: decide whether to delete File objects
2006 // ...and related (actual) files
2009 function clearRepeats()
2011 $repeatNotice = new Notice();
2012 $repeatNotice->repeat_of = $this->id;
2014 //Null any notices that are repeats of this notice
2016 if ($repeatNotice->find()) {
2017 while ($repeatNotice->fetch()) {
2018 $orig = clone($repeatNotice);
2019 $repeatNotice->repeat_of = null;
2020 $repeatNotice->update($orig);
2025 function clearTags()
2027 $tag = new Notice_tag();
2028 $tag->notice_id = $this->id;
2031 while ($tag->fetch()) {
2032 self::blow('profile:notice_ids_tagged:%d:%s', $this->profile_id, Cache::keyize($tag->tag));
2033 self::blow('profile:notice_ids_tagged:%d:%s;last', $this->profile_id, Cache::keyize($tag->tag));
2034 self::blow('notice_tag:notice_ids:%s', Cache::keyize($tag->tag));
2035 self::blow('notice_tag:notice_ids:%s;last', Cache::keyize($tag->tag));
2043 function clearGroupInboxes()
2045 $gi = new Group_inbox();
2047 $gi->notice_id = $this->id;
2050 while ($gi->fetch()) {
2051 self::blow('user_group:notice_ids:%d', $gi->group_id);
2059 function distribute()
2061 // We always insert for the author so they don't
2063 Event::handle('StartNoticeDistribute', array($this));
2065 // If there's a failure, we want to _force_
2066 // distribution at this point.
2068 $qm = QueueManager::get();
2069 $qm->enqueue($this, 'distrib');
2070 } catch (Exception $e) {
2071 // If the exception isn't transient, this
2072 // may throw more exceptions as DQH does
2073 // its own enqueueing. So, we ignore them!
2075 $handler = new DistribQueueHandler();
2076 $handler->handle($this);
2077 } catch (Exception $e) {
2078 common_log(LOG_ERR, "emergency redistribution resulted in " . $e->getMessage());
2080 // Re-throw so somebody smarter can handle it.
2087 $result = parent::insert();
2089 if ($result !== false) {
2090 // Profile::hasRepeated() abuses pkeyGet(), so we
2091 // have to clear manually
2092 if (!empty($this->repeat_of)) {
2093 $c = self::memcache();
2095 $ck = self::multicacheKey('Notice',
2096 array('profile_id' => $this->profile_id,
2097 'repeat_of' => $this->repeat_of));
2107 * Get the source of the notice
2109 * @return Notice_source $ns A notice source object. 'code' is the only attribute
2110 * guaranteed to be populated.
2112 function getSource()
2114 $ns = new Notice_source();
2115 if (!empty($this->source)) {
2116 switch ($this->source) {
2123 $ns->code = $this->source;
2126 $ns = Notice_source::getKV($this->source);
2128 $ns = new Notice_source();
2129 $ns->code = $this->source;
2130 $app = Oauth_application::getKV('name', $this->source);
2132 $ns->name = $app->name;
2133 $ns->url = $app->source_url;
2143 * Determine whether the notice was locally created
2145 * @return boolean locality
2148 public function isLocal()
2150 return ($this->is_local == Notice::LOCAL_PUBLIC ||
2151 $this->is_local == Notice::LOCAL_NONPUBLIC);
2155 * Get the list of hash tags saved with this notice.
2157 * @return array of strings
2159 public function getTags()
2163 $keypart = sprintf('notice:tags:%d', $this->id);
2165 $tagstr = self::cacheGet($keypart);
2167 if ($tagstr !== false) {
2168 $tags = explode(',', $tagstr);
2170 $tag = new Notice_tag();
2171 $tag->notice_id = $this->id;
2173 while ($tag->fetch()) {
2174 $tags[] = $tag->tag;
2177 self::cacheSet($keypart, implode(',', $tags));
2183 static private function utcDate($dt)
2185 $dateStr = date('d F Y H:i:s', strtotime($dt));
2186 $d = new DateTime($dateStr, new DateTimeZone('UTC'));
2187 return $d->format(DATE_W3C);
2191 * Look up the creation timestamp for a given notice ID, even
2192 * if it's been deleted.
2195 * @return mixed string recorded creation timestamp, or false if can't be found
2197 public static function getAsTimestamp($id)
2203 $notice = Notice::getKV('id', $id);
2205 return $notice->created;
2208 $deleted = Deleted_notice::getKV('id', $id);
2210 return $deleted->created;
2217 * Build an SQL 'where' fragment for timestamp-based sorting from a since_id
2218 * parameter, matching notices posted after the given one (exclusive).
2220 * If the referenced notice can't be found, will return false.
2223 * @param string $idField
2224 * @param string $createdField
2225 * @return mixed string or false if no match
2227 public static function whereSinceId($id, $idField='id', $createdField='created')
2229 $since = Notice::getAsTimestamp($id);
2231 return sprintf("($createdField = '%s' and $idField > %d) or ($createdField > '%s')", $since, $id, $since);
2237 * Build an SQL 'where' fragment for timestamp-based sorting from a since_id
2238 * parameter, matching notices posted after the given one (exclusive), and
2239 * if necessary add it to the data object's query.
2241 * @param DB_DataObject $obj
2243 * @param string $idField
2244 * @param string $createdField
2245 * @return mixed string or false if no match
2247 public static function addWhereSinceId(DB_DataObject $obj, $id, $idField='id', $createdField='created')
2249 $since = self::whereSinceId($id, $idField, $createdField);
2251 $obj->whereAdd($since);
2256 * Build an SQL 'where' fragment for timestamp-based sorting from a max_id
2257 * parameter, matching notices posted before the given one (inclusive).
2259 * If the referenced notice can't be found, will return false.
2262 * @param string $idField
2263 * @param string $createdField
2264 * @return mixed string or false if no match
2266 public static function whereMaxId($id, $idField='id', $createdField='created')
2268 $max = Notice::getAsTimestamp($id);
2270 return sprintf("($createdField < '%s') or ($createdField = '%s' and $idField <= %d)", $max, $max, $id);
2276 * Build an SQL 'where' fragment for timestamp-based sorting from a max_id
2277 * parameter, matching notices posted before the given one (inclusive), and
2278 * if necessary add it to the data object's query.
2280 * @param DB_DataObject $obj
2282 * @param string $idField
2283 * @param string $createdField
2284 * @return mixed string or false if no match
2286 public static function addWhereMaxId(DB_DataObject $obj, $id, $idField='id', $createdField='created')
2288 $max = self::whereMaxId($id, $idField, $createdField);
2290 $obj->whereAdd($max);
2296 if (common_config('public', 'localonly')) {
2297 return ($this->is_local == Notice::LOCAL_PUBLIC);
2299 return (($this->is_local != Notice::LOCAL_NONPUBLIC) &&
2300 ($this->is_local != Notice::GATEWAY));
2305 * Check that the given profile is allowed to read, respond to, or otherwise
2306 * act on this notice.
2308 * The $scope member is a bitmask of scopes, representing a logical AND of the
2309 * scope requirement. So, 0x03 (Notice::ADDRESSEE_SCOPE | Notice::SITE_SCOPE) means
2310 * "only visible to people who are mentioned in the notice AND are users on this site."
2311 * Users on the site who are not mentioned in the notice will not be able to see the
2314 * @param Profile $profile The profile to check; pass null to check for public/unauthenticated users.
2316 * @return boolean whether the profile is in the notice's scope
2318 function inScope($profile)
2320 if (is_null($profile)) {
2321 $keypart = sprintf('notice:in-scope-for:%d:null', $this->id);
2323 $keypart = sprintf('notice:in-scope-for:%d:%d', $this->id, $profile->id);
2326 $result = self::cacheGet($keypart);
2328 if ($result === false) {
2330 if (Event::handle('StartNoticeInScope', array($this, $profile, &$bResult))) {
2331 $bResult = $this->_inScope($profile);
2332 Event::handle('EndNoticeInScope', array($this, $profile, &$bResult));
2334 $result = ($bResult) ? 1 : 0;
2335 self::cacheSet($keypart, $result, 0, 300);
2338 return ($result == 1) ? true : false;
2341 protected function _inScope($profile)
2343 if (!is_null($this->scope)) {
2344 $scope = $this->scope;
2346 $scope = self::defaultScope();
2349 // If there's no scope, anyone (even anon) is in scope.
2351 if ($scope == 0) { // Not private
2353 return !$this->isHiddenSpam($profile);
2355 } else { // Private, somehow
2357 // If there's scope, anon cannot be in scope
2359 if (empty($profile)) {
2363 // Author is always in scope
2365 if ($this->profile_id == $profile->id) {
2369 // Only for users on this site
2371 if (($scope & Notice::SITE_SCOPE) && !$profile->isLocal()) {
2375 // Only for users mentioned in the notice
2377 if ($scope & Notice::ADDRESSEE_SCOPE) {
2379 $reply = Reply::pkeyGet(array('notice_id' => $this->id,
2380 'profile_id' => $profile->id));
2382 if (!$reply instanceof Reply) {
2387 // Only for members of the given group
2389 if ($scope & Notice::GROUP_SCOPE) {
2391 // XXX: just query for the single membership
2393 $groups = $this->getGroups();
2397 foreach ($groups as $group) {
2398 if ($profile->isMember($group)) {
2409 // Only for followers of the author
2413 if ($scope & Notice::FOLLOWER_SCOPE) {
2416 $author = $this->getProfile();
2417 } catch (Exception $e) {
2421 if (!Subscription::exists($profile, $author)) {
2426 return !$this->isHiddenSpam($profile);
2430 function isHiddenSpam($profile) {
2432 // Hide posts by silenced users from everyone but moderators.
2434 if (common_config('notice', 'hidespam')) {
2437 $author = $this->getProfile();
2438 } catch(Exception $e) {
2439 // If we can't get an author, keep it hidden.
2440 // XXX: technically not spam, but, whatever.
2444 if ($author->hasRole(Profile_role::SILENCED)) {
2445 if (!$profile instanceof Profile || (($profile->id !== $author->id) && (!$profile->hasRight(Right::REVIEWSPAM)))) {
2454 public function getParent()
2456 $parent = Notice::getKV('id', $this->reply_to);
2458 if (!$parent instanceof Notice) {
2459 throw new ServerException('Notice has no parent');
2466 * Magic function called at serialize() time.
2468 * We use this to drop a couple process-specific references
2469 * from DB_DataObject which can cause trouble in future
2472 * @return array of variable names to include in serialization.
2477 $vars = parent::__sleep();
2478 $skip = array('_profile', '_groups', '_attachments', '_faves', '_replies', '_repeats');
2479 return array_diff($vars, $skip);
2482 static function defaultScope()
2484 $scope = common_config('notice', 'defaultscope');
2485 if (is_null($scope)) {
2486 if (common_config('site', 'private')) {
2495 static function fillProfiles($notices)
2497 $map = self::getProfiles($notices);
2499 foreach ($notices as $entry=>$notice) {
2501 if (array_key_exists($notice->profile_id, $map)) {
2502 $notice->_setProfile($map[$notice->profile_id]);
2504 } catch (NoProfileException $e) {
2505 common_log(LOG_WARNING, "Failed to fill profile in Notice with non-existing entry for profile_id: {$e->profile_id}");
2506 unset($notices[$entry]);
2510 return array_values($map);
2513 static function getProfiles(&$notices)
2516 foreach ($notices as $notice) {
2517 $ids[] = $notice->profile_id;
2520 $ids = array_unique($ids);
2522 return Profile::pivotGet('id', $ids);
2525 static function fillGroups(&$notices)
2527 $ids = self::_idsOf($notices);
2529 $gis = Group_inbox::listGet('notice_id', $ids);
2533 foreach ($gis as $id => $gi)
2537 $gids[] = $g->group_id;
2541 $gids = array_unique($gids);
2543 $group = User_group::pivotGet('id', $gids);
2545 foreach ($notices as $notice)
2548 $gi = $gis[$notice->id];
2549 foreach ($gi as $g) {
2550 $grps[] = $group[$g->group_id];
2552 $notice->_setGroups($grps);
2556 static function _idsOf(array &$notices)
2559 foreach ($notices as $notice) {
2560 $ids[$notice->id] = true;
2562 return array_keys($ids);
2565 static function fillAttachments(&$notices)
2567 $ids = self::_idsOf($notices);
2569 $f2pMap = File_to_post::listGet('post_id', $ids);
2573 foreach ($f2pMap as $noticeId => $f2ps) {
2574 foreach ($f2ps as $f2p) {
2575 $fileIds[] = $f2p->file_id;
2579 $fileIds = array_unique($fileIds);
2581 $fileMap = File::pivotGet('id', $fileIds);
2583 foreach ($notices as $notice)
2586 $f2ps = $f2pMap[$notice->id];
2587 foreach ($f2ps as $f2p) {
2588 $files[] = $fileMap[$f2p->file_id];
2590 $notice->_setAttachments($files);
2594 static function fillReplies(&$notices)
2596 $ids = self::_idsOf($notices);
2597 $replyMap = Reply::listGet('notice_id', $ids);
2598 foreach ($notices as $notice) {
2599 $replies = $replyMap[$notice->id];
2601 foreach ($replies as $reply) {
2602 $ids[] = $reply->profile_id;
2604 $notice->_setReplies($ids);
2608 protected $_repeats = array();
2610 function getRepeats()
2612 if (isset($this->_repeats[$this->id])) {
2613 return $this->_repeats[$this->id];
2615 $repeatMap = Notice::listGet('repeat_of', array($this->id));
2616 $this->_repeats[$this->id] = $repeatMap[$this->id];
2617 return $this->_repeats[$this->id];
2620 function _setRepeats($repeats)
2622 $this->_repeats[$this->id] = $repeats;
2625 static function fillRepeats(&$notices)
2627 $ids = self::_idsOf($notices);
2628 $repeatMap = Notice::listGet('repeat_of', $ids);
2629 foreach ($notices as $notice) {
2630 $repeats = $repeatMap[$notice->id];
2631 $notice->_setRepeats($repeats);