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();
146 public function getProfile()
148 if (!isset($this->_profile[$this->profile_id])) {
149 $this->_setProfile(Profile::getKV('id', $this->profile_id));
151 return $this->_profile[$this->profile_id];
154 public function _setProfile(Profile $profile=null)
156 if (!$profile instanceof Profile) {
157 throw new NoProfileException($this->profile_id);
159 $this->_profile[$this->profile_id] = $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();
197 $this->clearAttentions();
199 // NOTE: we don't clear queue items
202 $result = parent::delete($useWhere);
204 $this->blowOnDelete();
208 public function getUri()
214 * @param $root boolean If true, link to just the conversation root.
216 * @return URL to conversation
218 public function getConversationUrl($anchor=true)
220 return Conversation::getUrlFromNotice($this, $anchor);
224 * Get the local representation URL of this notice.
226 public function getLocalUrl()
228 return common_local_url('shownotice', array('notice' => $this->id), null, null, false);
232 * Get the original representation URL of this notice.
234 public function getUrl()
236 // The risk is we start having empty urls and non-http uris...
237 // and we can't really handle any other protocol right now.
239 case common_valid_http_url($this->url): // should we allow non-http/https URLs?
241 case $this->isLocal():
242 // let's generate a valid link to our locally available notice on demand
243 return common_local_url('shownotice', array('notice' => $this->id), null, null, false);
244 case common_valid_http_url($this->uri):
247 common_debug('No URL available for notice: id='.$this->id);
248 throw new InvalidUrlException($this->url);
252 public function get_object_type($canonical=false) {
254 ? ActivityObject::canonicalType($this->object_type)
255 : $this->object_type;
258 public static function getByUri($uri)
260 $notice = new Notice();
262 if (!$notice->find(true)) {
263 throw new NoResultException($notice);
269 * Extract #hashtags from this notice's content and save them to the database.
273 /* extract all #hastags */
274 $count = preg_match_all('/(?:^|\s)#([\pL\pN_\-\.]{1,64})/u', strtolower($this->content), $match);
279 /* Add them to the database */
280 return $this->saveKnownTags($match[1]);
284 * Record the given set of hash tags in the db for this notice.
285 * Given tag strings will be normalized and checked for dupes.
287 function saveKnownTags($hashtags)
289 //turn each into their canonical tag
290 //this is needed to remove dupes before saving e.g. #hash.tag = #hashtag
291 for($i=0; $i<count($hashtags); $i++) {
292 /* elide characters we don't want in the tag */
293 $hashtags[$i] = common_canonical_tag($hashtags[$i]);
296 foreach(array_unique($hashtags) as $hashtag) {
297 $this->saveTag($hashtag);
298 self::blow('profile:notice_ids_tagged:%d:%s', $this->profile_id, $hashtag);
304 * Record a single hash tag as associated with this notice.
305 * Tag format and uniqueness must be validated by caller.
307 function saveTag($hashtag)
309 $tag = new Notice_tag();
310 $tag->notice_id = $this->id;
311 $tag->tag = $hashtag;
312 $tag->created = $this->created;
313 $id = $tag->insert();
316 // TRANS: Server exception. %s are the error details.
317 throw new ServerException(sprintf(_('Database error inserting hashtag: %s.'),
318 $last_error->message));
322 // if it's saved, blow its cache
323 $tag->blowCache(false);
327 * Save a new notice and push it out to subscribers' inboxes.
328 * Poster's permissions are checked before sending.
330 * @param int $profile_id Profile ID of the poster
331 * @param string $content source message text; links may be shortened
332 * per current user's preference
333 * @param string $source source key ('web', 'api', etc)
334 * @param array $options Associative array of optional properties:
335 * string 'created' timestamp of notice; defaults to now
336 * int 'is_local' source/gateway ID, one of:
337 * Notice::LOCAL_PUBLIC - Local, ok to appear in public timeline
338 * Notice::REMOTE - Sent from a remote service;
339 * hide from public timeline but show in
340 * local "and friends" timelines
341 * Notice::LOCAL_NONPUBLIC - Local, but hide from public timeline
342 * Notice::GATEWAY - From another non-OStatus service;
343 * will not appear in public views
344 * float 'lat' decimal latitude for geolocation
345 * float 'lon' decimal longitude for geolocation
346 * int 'location_id' geoname identifier
347 * int 'location_ns' geoname namespace to interpret location_id
348 * int 'reply_to'; notice ID this is a reply to
349 * int 'repeat_of'; notice ID this is a repeat of
350 * string 'uri' unique ID for notice; a unique tag uri (can be url or anything too)
351 * string 'url' permalink to notice; defaults to local notice URL
352 * string 'rendered' rendered HTML version of content
353 * array 'replies' list of profile URIs for reply delivery in
354 * place of extracting @-replies from content.
355 * array 'groups' list of group IDs to deliver to, in place of
356 * extracting ! tags from content
357 * array 'tags' list of hashtag strings to save with the notice
358 * in place of extracting # tags from content
359 * array 'urls' list of attached/referred URLs to save with the
360 * notice in place of extracting links from content
361 * boolean 'distribute' whether to distribute the notice, default true
362 * string 'object_type' URL of the associated object type (default ActivityObject::NOTE)
363 * string 'verb' URL of the associated verb (default ActivityVerb::POST)
364 * int 'scope' Scope bitmask; default to SITE_SCOPE on private sites, 0 otherwise
366 * @fixme tag override
369 * @throws ClientException
371 static function saveNew($profile_id, $content, $source, array $options=null) {
372 $defaults = array('uri' => null,
377 'distribute' => true,
378 'object_type' => null,
381 if (!empty($options) && is_array($options)) {
382 $options = array_merge($defaults, $options);
388 if (!isset($is_local)) {
389 $is_local = Notice::LOCAL_PUBLIC;
392 $profile = Profile::getKV('id', $profile_id);
393 if (!$profile instanceof Profile) {
394 // TRANS: Client exception thrown when trying to save a notice for an unknown user.
395 throw new ClientException(_('Problem saving notice. Unknown user.'));
398 $user = User::getKV('id', $profile_id);
399 if ($user instanceof User) {
400 // Use the local user's shortening preferences, if applicable.
401 $final = $user->shortenLinks($content);
403 $final = common_shorten_links($content);
406 if (Notice::contentTooLong($final)) {
407 // TRANS: Client exception thrown if a notice contains too many characters.
408 throw new ClientException(_('Problem saving notice. Too long.'));
411 if (common_config('throttle', 'enabled') && !Notice::checkEditThrottle($profile_id)) {
412 common_log(LOG_WARNING, 'Excessive posting by profile #' . $profile_id . '; throttled.');
413 // TRANS: Client exception thrown when a user tries to post too many notices in a given time frame.
414 throw new ClientException(_('Too many notices too fast; take a breather '.
415 'and post again in a few minutes.'));
418 if (common_config('site', 'dupelimit') > 0 && !Notice::checkDupes($profile_id, $final)) {
419 common_log(LOG_WARNING, 'Dupe posting by profile #' . $profile_id . '; throttled.');
420 // TRANS: Client exception thrown when a user tries to post too many duplicate notices in a given time frame.
421 throw new ClientException(_('Too many duplicate messages too quickly;'.
422 ' take a breather and post again in a few minutes.'));
425 if (!$profile->hasRight(Right::NEWNOTICE)) {
426 common_log(LOG_WARNING, "Attempted post from user disallowed to post: " . $profile->nickname);
428 // TRANS: Client exception thrown when a user tries to post while being banned.
429 throw new ClientException(_('You are banned from posting notices on this site.'), 403);
432 $notice = new Notice();
433 $notice->profile_id = $profile_id;
435 $autosource = common_config('public', 'autosource');
437 // Sandboxed are non-false, but not 1, either
439 if (!$profile->hasRight(Right::PUBLICNOTICE) ||
440 ($source && $autosource && in_array($source, $autosource))) {
441 $notice->is_local = Notice::LOCAL_NONPUBLIC;
443 $notice->is_local = $is_local;
446 if (!empty($created)) {
447 $notice->created = $created;
449 $notice->created = common_sql_now();
452 if (!$notice->isLocal()) {
453 // Only do these checks for non-local notices. Local notices will generate these values later.
454 if (!common_valid_http_url($url)) {
455 common_debug('Bad notice URL: ['.$url.'], URI: ['.$uri.']. Cannot link back to original! This is normal for shared notices etc.');
458 throw new ServerException('No URI for remote notice. Cannot accept that.');
462 $notice->content = $final;
464 $notice->source = $source;
468 // Get the groups here so we can figure out replies and such
469 if (!isset($groups)) {
470 $groups = User_group::idsFromText($notice->content, $profile);
475 // Handle repeat case
477 if (isset($repeat_of)) {
479 // Check for a private one
481 $repeat = Notice::getKV('id', $repeat_of);
483 if (!($repeat instanceof Notice)) {
484 // TRANS: Client exception thrown in notice when trying to repeat a missing or deleted notice.
485 throw new ClientException(_('Cannot repeat; original notice is missing or deleted.'));
488 if ($profile->id == $repeat->profile_id) {
489 // TRANS: Client error displayed when trying to repeat an own notice.
490 throw new ClientException(_('You cannot repeat your own notice.'));
493 if ($repeat->scope != Notice::SITE_SCOPE &&
494 $repeat->scope != Notice::PUBLIC_SCOPE) {
495 // TRANS: Client error displayed when trying to repeat a non-public notice.
496 throw new ClientException(_('Cannot repeat a private notice.'), 403);
499 if (!$repeat->inScope($profile)) {
500 // The generic checks above should cover this, but let's be sure!
501 // TRANS: Client error displayed when trying to repeat a notice you cannot access.
502 throw new ClientException(_('Cannot repeat a notice you cannot read.'), 403);
505 if ($profile->hasRepeated($repeat)) {
506 // TRANS: Client error displayed when trying to repeat an already repeated notice.
507 throw new ClientException(_('You already repeated that notice.'));
510 $notice->repeat_of = $repeat_of;
514 // If $reply_to is specified, we check that it exists, and then
515 // return it if it does
516 if (!empty($reply_to)) {
517 $reply = Notice::getKV('id', $reply_to);
518 } elseif (in_array($source, array('xmpp', 'mail', 'sms'))) {
519 // If the source lacks capability of sending the "reply_to"
520 // metadata, let's try to find an inline replyto-reference.
521 $reply = self::getInlineReplyTo($profile, $final);
524 if ($reply instanceof Notice) {
525 if (!$reply->inScope($profile)) {
526 // TRANS: Client error displayed when trying to reply to a notice a the target has no access to.
527 // TRANS: %1$s is a user nickname, %2$d is a notice ID (number).
528 throw new ClientException(sprintf(_('%1$s has no access to notice %2$d.'),
529 $profile->nickname, $reply->id), 403);
532 $notice->reply_to = $reply->id;
533 $notice->conversation = $reply->conversation;
535 // If the original is private to a group, and notice has
536 // no group specified, make it to the same group(s)
538 if (empty($groups) && ($reply->scope & Notice::GROUP_SCOPE)) {
540 $replyGroups = $reply->getGroups();
541 foreach ($replyGroups as $group) {
542 if ($profile->isMember($group)) {
543 $groups[] = $group->id;
552 if (!empty($lat) && !empty($lon)) {
557 if (!empty($location_ns) && !empty($location_id)) {
558 $notice->location_id = $location_id;
559 $notice->location_ns = $location_ns;
562 if (!empty($rendered)) {
563 $notice->rendered = $rendered;
565 $notice->rendered = common_render_content($final, $notice);
569 if (!empty($notice->repeat_of)) {
570 $notice->verb = ActivityVerb::SHARE;
571 $notice->object_type = ActivityObject::ACTIVITY;
573 $notice->verb = ActivityVerb::POST;
576 $notice->verb = $verb;
579 if (empty($object_type)) {
580 $notice->object_type = (empty($notice->reply_to)) ? ActivityObject::NOTE : ActivityObject::COMMENT;
582 $notice->object_type = $object_type;
585 if (is_null($scope)) { // 0 is a valid value
586 if (!empty($reply)) {
587 $notice->scope = $reply->scope;
589 $notice->scope = self::defaultScope();
592 $notice->scope = $scope;
595 // For private streams
598 $user = $profile->getUser();
600 if ($user->private_stream &&
601 ($notice->scope == Notice::PUBLIC_SCOPE ||
602 $notice->scope == Notice::SITE_SCOPE)) {
603 $notice->scope |= Notice::FOLLOWER_SCOPE;
605 } catch (NoSuchUserException $e) {
606 // Cannot handle private streams for remote profiles
609 // Force the scope for private groups
611 foreach ($groups as $groupId) {
612 $group = User_group::getKV('id', $groupId);
613 if ($group instanceof User_group) {
614 if ($group->force_scope) {
615 $notice->scope |= Notice::GROUP_SCOPE;
621 if (Event::handle('StartNoticeSave', array(&$notice))) {
623 // XXX: some of these functions write to the DB
625 $id = $notice->insert();
628 common_log_db_error($notice, 'INSERT', __FILE__);
629 // TRANS: Server exception thrown when a notice cannot be saved.
630 throw new ServerException(_('Problem saving notice.'));
633 // Update ID-dependent columns: URI, conversation
635 $orig = clone($notice);
639 // We can only get here if it's a local notice, since remote notices
640 // should've bailed out earlier due to lacking a URI.
641 if (empty($notice->uri)) {
642 $notice->uri = sprintf('%s%s=%d:%s=%s',
644 'noticeId', $notice->id,
645 'objectType', $notice->get_object_type(true));
649 // If it's not part of a conversation, it's
650 // the beginning of a new conversation.
652 if (empty($notice->conversation)) {
653 $conv = Conversation::create($notice);
654 $notice->conversation = $conv->id;
659 if ($notice->update($orig) === false) {
660 common_log_db_error($notice, 'UPDATE', __FILE__);
661 // TRANS: Server exception thrown when a notice cannot be updated.
662 throw new ServerException(_('Problem saving notice.'));
668 // Clear the cache for subscribed users, so they'll update at next request
669 // XXX: someone clever could prepend instead of clearing the cache
671 $notice->blowOnInsert();
673 // Save per-notice metadata...
675 if (isset($replies)) {
676 $notice->saveKnownReplies($replies);
678 $notice->saveReplies();
682 $notice->saveKnownTags($tags);
687 // Note: groups may save tags, so must be run after tags are saved
688 // to avoid errors on duplicates.
689 // Note: groups should always be set.
691 $notice->saveKnownGroups($groups);
694 $notice->saveKnownUrls($urls);
700 // Prepare inbox delivery, may be queued to background.
701 $notice->distribute();
707 function blowOnInsert($conversation = false)
709 $this->blowStream('profile:notice_ids:%d', $this->profile_id);
711 if ($this->isPublic()) {
712 $this->blowStream('public');
715 self::blow('notice:list-ids:conversation:%s', $this->conversation);
716 self::blow('conversation:notice_count:%d', $this->conversation);
718 if (!empty($this->repeat_of)) {
719 // XXX: we should probably only use one of these
720 $this->blowStream('notice:repeats:%d', $this->repeat_of);
721 self::blow('notice:list-ids:repeat_of:%d', $this->repeat_of);
724 $original = Notice::getKV('id', $this->repeat_of);
726 if ($original instanceof Notice) {
727 $originalUser = User::getKV('id', $original->profile_id);
728 if ($originalUser instanceof User) {
729 $this->blowStream('user:repeats_of_me:%d', $originalUser->id);
733 $profile = Profile::getKV($this->profile_id);
735 if ($profile instanceof Profile) {
736 $profile->blowNoticeCount();
739 $ptags = $this->getProfileTags();
740 foreach ($ptags as $ptag) {
741 $ptag->blowNoticeStreamCache();
746 * Clear cache entries related to this notice at delete time.
747 * Necessary to avoid breaking paging on public, profile timelines.
749 function blowOnDelete()
751 $this->blowOnInsert();
753 self::blow('profile:notice_ids:%d;last', $this->profile_id);
755 if ($this->isPublic()) {
756 self::blow('public;last');
759 self::blow('fave:by_notice', $this->id);
761 if ($this->conversation) {
762 // In case we're the first, will need to calc a new root.
763 self::blow('notice:conversation_root:%d', $this->conversation);
766 $ptags = $this->getProfileTags();
767 foreach ($ptags as $ptag) {
768 $ptag->blowNoticeStreamCache(true);
772 function blowStream()
774 $c = self::memcache();
780 $args = func_get_args();
782 $format = array_shift($args);
784 $keyPart = vsprintf($format, $args);
786 $cacheKey = Cache::key($keyPart);
788 $c->delete($cacheKey);
790 // delete the "last" stream, too, if this notice is
791 // older than the top of that stream
793 $lastKey = $cacheKey.';last';
795 $lastStr = $c->get($lastKey);
797 if ($lastStr !== false) {
798 $window = explode(',', $lastStr);
799 $lastID = $window[0];
800 $lastNotice = Notice::getKV('id', $lastID);
801 if (!$lastNotice instanceof Notice // just weird
802 || strtotime($lastNotice->created) >= strtotime($this->created)) {
803 $c->delete($lastKey);
808 /** save all urls in the notice to the db
810 * follow redirects and save all available file information
811 * (mimetype, date, size, oembed, etc.)
815 function saveUrls() {
816 if (common_config('attachments', 'process_links')) {
817 common_replace_urls_callback($this->content, array($this, 'saveUrl'), $this->id);
822 * Save the given URLs as related links/attachments to the db
824 * follow redirects and save all available file information
825 * (mimetype, date, size, oembed, etc.)
829 function saveKnownUrls($urls)
831 if (common_config('attachments', 'process_links')) {
832 // @fixme validation?
833 foreach (array_unique($urls) as $url) {
835 File::processNew($url, $this->id);
836 } catch (ServerException $e) {
837 // Could not save URL. Log it?
846 function saveUrl($url, $notice_id) {
848 File::processNew($url, $notice_id);
849 } catch (ServerException $e) {
850 // Could not save URL. Log it?
854 static function checkDupes($profile_id, $content) {
855 $profile = Profile::getKV($profile_id);
856 if (!$profile instanceof Profile) {
859 $notice = $profile->getNotices(0, CachingNoticeStream::CACHE_WINDOW);
860 if (!empty($notice)) {
862 while ($notice->fetch()) {
863 if (time() - strtotime($notice->created) >= common_config('site', 'dupelimit')) {
865 } else if ($notice->content == $content) {
870 // If we get here, oldest item in cache window is not
871 // old enough for dupe limit; do direct check against DB
872 $notice = new Notice();
873 $notice->profile_id = $profile_id;
874 $notice->content = $content;
875 $threshold = common_sql_date(time() - common_config('site', 'dupelimit'));
876 $notice->whereAdd(sprintf("created > '%s'", $notice->escape($threshold)));
878 $cnt = $notice->count();
882 static function checkEditThrottle($profile_id) {
883 $profile = Profile::getKV($profile_id);
884 if (!$profile instanceof Profile) {
887 // Get the Nth notice
888 $notice = $profile->getNotices(common_config('throttle', 'count') - 1, 1);
889 if ($notice && $notice->fetch()) {
890 // If the Nth notice was posted less than timespan seconds ago
891 if (time() - strtotime($notice->created) <= common_config('throttle', 'timespan')) {
896 // Either not N notices in the stream, OR the Nth was not posted within timespan seconds
900 protected $_attachments = -1;
902 function attachments() {
904 if ($this->_attachments != -1) {
905 return $this->_attachments;
908 $f2ps = File_to_post::listGet('post_id', array($this->id));
912 foreach ($f2ps[$this->id] as $f2p) {
913 $ids[] = $f2p->file_id;
916 $files = File::multiGet('id', $ids);
918 $this->_attachments = $files->fetchAll();
920 return $this->_attachments;
923 function _setAttachments($attachments)
925 $this->_attachments = $attachments;
928 function publicStream($offset=0, $limit=20, $since_id=0, $max_id=0)
930 $stream = new PublicNoticeStream();
931 return $stream->getNotices($offset, $limit, $since_id, $max_id);
935 function conversationStream($id, $offset=0, $limit=20, $since_id=0, $max_id=0)
937 $stream = new ConversationNoticeStream($id);
939 return $stream->getNotices($offset, $limit, $since_id, $max_id);
943 * Is this notice part of an active conversation?
945 * @return boolean true if other messages exist in the same
946 * conversation, false if this is the only one
948 function hasConversation()
950 if (!empty($this->conversation)) {
951 $conversation = Notice::conversationStream(
957 if ($conversation->N > 0) {
965 * Grab the earliest notice from this conversation.
967 * @return Notice or null
969 function conversationRoot($profile=-1)
971 // XXX: can this happen?
973 if (empty($this->conversation)) {
977 // Get the current profile if not specified
979 if (is_int($profile) && $profile == -1) {
980 $profile = Profile::current();
983 // If this notice is out of scope, no root for you!
985 if (!$this->inScope($profile)) {
989 // If this isn't a reply to anything, then it's its own
992 if (empty($this->reply_to)) {
996 if (is_null($profile)) {
997 $keypart = sprintf('notice:conversation_root:%d:null', $this->id);
999 $keypart = sprintf('notice:conversation_root:%d:%d',
1004 $root = self::cacheGet($keypart);
1006 if ($root !== false && $root->inScope($profile)) {
1013 $parent = $last->getParent();
1014 if ($parent->inScope($profile)) {
1018 } catch (Exception $e) {
1019 // Latest notice has no parent
1021 // No parent, or parent out of scope
1026 self::cacheSet($keypart, $root);
1032 * Pull up a full list of local recipients who will be getting
1033 * this notice in their inbox. Results will be cached, so don't
1034 * change the input data wily-nilly!
1036 * @param array $groups optional list of Group objects;
1037 * if left empty, will be loaded from group_inbox records
1038 * @param array $recipient optional list of reply profile ids
1039 * if left empty, will be loaded from reply records
1040 * @return array associating recipient user IDs with an inbox source constant
1042 function whoGets(array $groups=null, array $recipients=null)
1044 $c = self::memcache();
1047 $ni = $c->get(Cache::key('notice:who_gets:'.$this->id));
1048 if ($ni !== false) {
1053 if (is_null($recipients)) {
1054 $recipients = $this->getReplies();
1059 // Give plugins a chance to add folks in at start...
1060 if (Event::handle('StartNoticeWhoGets', array($this, &$ni))) {
1062 $users = $this->getSubscribedUsers();
1063 foreach ($users as $id) {
1064 $ni[$id] = NOTICE_INBOX_SOURCE_SUB;
1067 if (is_null($groups)) {
1068 $groups = $this->getGroups();
1070 foreach ($groups as $group) {
1071 $users = $group->getUserMembers();
1072 foreach ($users as $id) {
1073 if (!array_key_exists($id, $ni)) {
1074 $ni[$id] = NOTICE_INBOX_SOURCE_GROUP;
1079 $ptAtts = $this->getAttentionsFromProfileTags();
1080 foreach ($ptAtts as $key=>$val) {
1081 if (!array_key_exists($key, $ni)) {
1086 foreach ($recipients as $recipient) {
1087 if (!array_key_exists($recipient, $ni)) {
1088 $ni[$recipient] = NOTICE_INBOX_SOURCE_REPLY;
1092 // Exclude any deleted, non-local, or blocking recipients.
1093 $profile = $this->getProfile();
1094 $originalProfile = null;
1095 if ($this->repeat_of) {
1096 // Check blocks against the original notice's poster as well.
1097 $original = Notice::getKV('id', $this->repeat_of);
1098 if ($original instanceof Notice) {
1099 $originalProfile = $original->getProfile();
1103 foreach ($ni as $id => $source) {
1105 $user = User::getKV('id', $id);
1106 if (!$user instanceof User ||
1107 $user->hasBlocked($profile) ||
1108 ($originalProfile && $user->hasBlocked($originalProfile))) {
1111 } catch (UserNoProfileException $e) {
1112 // User doesn't have a profile; invalid; skip them.
1117 // Give plugins a chance to filter out...
1118 Event::handle('EndNoticeWhoGets', array($this, &$ni));
1122 // XXX: pack this data better
1123 $c->set(Cache::key('notice:who_gets:'.$this->id), $ni);
1129 function getSubscribedUsers()
1133 if(common_config('db','quote_identifiers'))
1134 $user_table = '"user"';
1135 else $user_table = 'user';
1139 'FROM '. $user_table .' JOIN subscription '.
1140 'ON '. $user_table .'.id = subscription.subscriber ' .
1141 'WHERE subscription.subscribed = %d ';
1143 $user->query(sprintf($qry, $this->profile_id));
1147 while ($user->fetch()) {
1156 function getProfileTags()
1158 $profile = $this->getProfile();
1159 $list = $profile->getOtherTags($profile);
1162 while($list->fetch()) {
1163 $ptags[] = clone($list);
1169 public function getAttentionsFromProfileTags()
1172 $ptags = $this->getProfileTags();
1173 foreach ($ptags as $ptag) {
1174 $users = $ptag->getUserSubscribers();
1175 foreach ($users as $id) {
1176 $ni[$id] = NOTICE_INBOX_SOURCE_PROFILE_TAG;
1183 * Record this notice to the given group inboxes for delivery.
1184 * Overrides the regular parsing of !group markup.
1186 * @param string $group_ids
1187 * @fixme might prefer URIs as identifiers, as for replies?
1188 * best with generalizations on user_group to support
1189 * remote groups better.
1191 function saveKnownGroups($group_ids)
1193 if (!is_array($group_ids)) {
1194 // TRANS: Server exception thrown when no array is provided to the method saveKnownGroups().
1195 throw new ServerException(_('Bad type provided to saveKnownGroups.'));
1199 foreach (array_unique($group_ids) as $id) {
1200 $group = User_group::getKV('id', $id);
1201 if ($group instanceof User_group) {
1202 common_log(LOG_ERR, "Local delivery to group id $id, $group->nickname");
1203 $result = $this->addToGroupInbox($group);
1205 common_log_db_error($gi, 'INSERT', __FILE__);
1208 if (common_config('group', 'addtag')) {
1209 // we automatically add a tag for every group name, too
1211 $tag = Notice_tag::pkeyGet(array('tag' => common_canonical_tag($group->nickname),
1212 'notice_id' => $this->id));
1214 if (is_null($tag)) {
1215 $this->saveTag($group->nickname);
1219 $groups[] = clone($group);
1221 common_log(LOG_ERR, "Local delivery to group id $id skipped, doesn't exist");
1228 function addToGroupInbox(User_group $group)
1230 $gi = Group_inbox::pkeyGet(array('group_id' => $group->id,
1231 'notice_id' => $this->id));
1233 if (!$gi instanceof Group_inbox) {
1235 $gi = new Group_inbox();
1237 $gi->group_id = $group->id;
1238 $gi->notice_id = $this->id;
1239 $gi->created = $this->created;
1241 $result = $gi->insert();
1244 common_log_db_error($gi, 'INSERT', __FILE__);
1245 // TRANS: Server exception thrown when an update for a group inbox fails.
1246 throw new ServerException(_('Problem saving group inbox.'));
1249 self::blow('user_group:notice_ids:%d', $gi->group_id);
1256 * Save reply records indicating that this notice needs to be
1257 * delivered to the local users with the given URIs.
1259 * Since this is expected to be used when saving foreign-sourced
1260 * messages, we won't deliver to any remote targets as that's the
1261 * source service's responsibility.
1263 * Mail notifications etc will be handled later.
1265 * @param array $uris Array of unique identifier URIs for recipients
1267 function saveKnownReplies(array $uris)
1273 $sender = Profile::getKV($this->profile_id);
1275 foreach (array_unique($uris) as $uri) {
1277 $profile = Profile::fromUri($uri);
1278 } catch (UnknownUriException $e) {
1279 common_log(LOG_WARNING, "Unable to determine profile for URI '$uri'");
1283 if ($profile->hasBlocked($sender)) {
1284 common_log(LOG_INFO, "Not saving reply to profile {$profile->id} ($uri) from sender {$sender->id} because of a block.");
1288 $this->saveReply($profile->id);
1289 self::blow('reply:stream:%d', $profile->id);
1296 * Pull @-replies from this message's content in StatusNet markup format
1297 * and save reply records indicating that this message needs to be
1298 * delivered to those users.
1300 * Mail notifications to local profiles will be sent later.
1302 * @return array of integer profile IDs
1305 function saveReplies()
1307 // Don't save reply data for repeats
1309 if (!empty($this->repeat_of)) {
1313 $sender = Profile::getKV($this->profile_id);
1317 // If it's a reply, save for the replied-to author
1319 $parent = $this->getParent();
1320 $author = $parent->getProfile();
1321 if ($author instanceof Profile) {
1322 $this->saveReply($author->id);
1323 $replied[$author->id] = 1;
1324 self::blow('reply:stream:%d', $author->id);
1326 } catch (Exception $e) {
1327 // Not a reply, since it has no parent!
1330 // @todo ideally this parser information would only
1331 // be calculated once.
1333 $mentions = common_find_mentions($this->content, $this);
1335 // store replied only for first @ (what user/notice what the reply directed,
1336 // we assume first @ is it)
1338 foreach ($mentions as $mention) {
1340 foreach ($mention['mentioned'] as $mentioned) {
1342 // skip if they're already covered
1344 if (!empty($replied[$mentioned->id])) {
1348 // Don't save replies from blocked profile to local user
1350 $mentioned_user = User::getKV('id', $mentioned->id);
1351 if ($mentioned_user instanceof User && $mentioned_user->hasBlocked($sender)) {
1355 $this->saveReply($mentioned->id);
1356 $replied[$mentioned->id] = 1;
1357 self::blow('reply:stream:%d', $mentioned->id);
1361 $recipientIds = array_keys($replied);
1363 return $recipientIds;
1366 function saveReply($profileId)
1368 $reply = new Reply();
1370 $reply->notice_id = $this->id;
1371 $reply->profile_id = $profileId;
1372 $reply->modified = $this->created;
1379 protected $_replies = -1;
1382 * Pull the complete list of @-reply targets for this notice.
1384 * @return array of integer profile ids
1386 function getReplies()
1388 if ($this->_replies != -1) {
1389 return $this->_replies;
1392 $replyMap = Reply::listGet('notice_id', array($this->id));
1396 foreach ($replyMap[$this->id] as $reply) {
1397 $ids[] = $reply->profile_id;
1400 $this->_replies = $ids;
1405 function _setReplies($replies)
1407 $this->_replies = $replies;
1411 * Pull the complete list of @-reply targets for this notice.
1413 * @return array of Profiles
1415 function getReplyProfiles()
1417 $ids = $this->getReplies();
1419 $profiles = Profile::multiGet('id', $ids);
1421 return $profiles->fetchAll();
1425 * Send e-mail notifications to local @-reply targets.
1427 * Replies must already have been saved; this is expected to be run
1428 * from the distrib queue handler.
1430 function sendReplyNotifications()
1432 // Don't send reply notifications for repeats
1434 if (!empty($this->repeat_of)) {
1438 $recipientIds = $this->getReplies();
1440 foreach ($recipientIds as $recipientId) {
1441 $user = User::getKV('id', $recipientId);
1442 if ($user instanceof User) {
1443 mail_notify_attn($user, $this);
1449 * Pull list of groups this notice needs to be delivered to,
1450 * as previously recorded by saveKnownGroups().
1452 * @return array of Group objects
1455 protected $_groups = -1;
1457 function getGroups()
1459 // Don't save groups for repeats
1461 if (!empty($this->repeat_of)) {
1465 if ($this->_groups != -1)
1467 return $this->_groups;
1470 $gis = Group_inbox::listGet('notice_id', array($this->id));
1474 foreach ($gis[$this->id] as $gi)
1476 $ids[] = $gi->group_id;
1479 $groups = User_group::multiGet('id', $ids);
1481 $this->_groups = $groups->fetchAll();
1483 return $this->_groups;
1486 function _setGroups($groups)
1488 $this->_groups = $groups;
1492 * Convert a notice into an activity for export.
1494 * @param User $cur Current user
1496 * @return Activity activity object representing this Notice.
1499 function asActivity($cur=null)
1501 $act = self::cacheGet(Cache::codeKey('notice:as-activity:'.$this->id));
1503 if ($act instanceof Activity) {
1506 $act = new Activity();
1508 if (Event::handle('StartNoticeAsActivity', array($this, &$act))) {
1510 $act->id = $this->uri;
1511 $act->time = strtotime($this->created);
1513 $act->link = $this->getUrl();
1514 } catch (InvalidUrlException $e) {
1515 // The notice is probably a share or similar, which don't
1516 // have a representational URL of their own.
1518 $act->content = common_xml_safe_str($this->rendered);
1520 $profile = $this->getProfile();
1522 $act->actor = ActivityObject::fromProfile($profile);
1523 $act->actor->extra[] = $profile->profileInfo($cur);
1525 $act->verb = $this->verb;
1527 if ($this->repeat_of) {
1528 $repeated = Notice::getKV('id', $this->repeat_of);
1529 if ($repeated instanceof Notice) {
1530 $act->objects[] = $repeated->asActivity($cur);
1533 $act->objects[] = ActivityObject::fromNotice($this);
1536 // XXX: should this be handled by default processing for object entry?
1540 $tags = $this->getTags();
1542 foreach ($tags as $tag) {
1543 $cat = new AtomCategory();
1546 $act->categories[] = $cat;
1550 // XXX: use Atom Media and/or File activity objects instead
1552 $attachments = $this->attachments();
1554 foreach ($attachments as $attachment) {
1555 // Save local attachments
1556 if (!empty($attachment->filename)) {
1557 $act->attachments[] = ActivityObject::fromFile($attachment);
1561 $ctx = new ActivityContext();
1564 $reply = $this->getParent();
1565 $ctx->replyToID = $reply->getUri();
1566 $ctx->replyToUrl = $reply->getUrl();
1567 } catch (Exception $e) {
1568 // This is not a reply to something
1571 $ctx->location = $this->getLocation();
1575 if (!empty($this->conversation)) {
1576 $conv = Conversation::getKV('id', $this->conversation);
1577 if ($conv instanceof Conversation) {
1578 $ctx->conversation = $conv->uri;
1582 $reply_ids = $this->getReplies();
1584 foreach ($reply_ids as $id) {
1585 $rprofile = Profile::getKV('id', $id);
1586 if ($rprofile instanceof Profile) {
1587 $ctx->attention[$rprofile->getUri()] = ActivityObject::PERSON;
1591 $groups = $this->getGroups();
1593 foreach ($groups as $group) {
1594 $ctx->attention[$group->getUri()] = ActivityObject::GROUP;
1597 switch ($this->scope) {
1598 case Notice::PUBLIC_SCOPE:
1599 $ctx->attention[ActivityContext::ATTN_PUBLIC] = ActivityObject::COLLECTION;
1601 case Notice::FOLLOWER_SCOPE:
1602 $surl = common_local_url("subscribers", array('nickname' => $profile->nickname));
1603 $ctx->attention[$surl] = ActivityObject::COLLECTION;
1607 $act->context = $ctx;
1609 $source = $this->getSource();
1611 if ($source instanceof Notice_source) {
1612 $act->generator = ActivityObject::fromNoticeSource($source);
1617 $atom_feed = $profile->getAtomFeed();
1619 if (!empty($atom_feed)) {
1621 $act->source = new ActivitySource();
1623 // XXX: we should store the actual feed ID
1625 $act->source->id = $atom_feed;
1627 // XXX: we should store the actual feed title
1629 $act->source->title = $profile->getBestName();
1631 $act->source->links['alternate'] = $profile->profileurl;
1632 $act->source->links['self'] = $atom_feed;
1634 $act->source->icon = $profile->avatarUrl(AVATAR_PROFILE_SIZE);
1636 $notice = $profile->getCurrentNotice();
1638 if ($notice instanceof Notice) {
1639 $act->source->updated = self::utcDate($notice->created);
1642 $user = User::getKV('id', $profile->id);
1644 if ($user instanceof User) {
1645 $act->source->links['license'] = common_config('license', 'url');
1649 if ($this->isLocal()) {
1650 $act->selfLink = common_local_url('ApiStatusesShow', array('id' => $this->id,
1651 'format' => 'atom'));
1652 $act->editLink = $act->selfLink;
1655 Event::handle('EndNoticeAsActivity', array($this, &$act));
1658 self::cacheSet(Cache::codeKey('notice:as-activity:'.$this->id), $act);
1663 // This has gotten way too long. Needs to be sliced up into functional bits
1664 // or ideally exported to a utility class.
1666 function asAtomEntry($namespace=false,
1671 $act = $this->asActivity($cur);
1672 $act->extra[] = $this->noticeInfo($cur);
1673 return $act->asString($namespace, $author, $source);
1677 * Extra notice info for atom entries
1679 * Clients use some extra notice info in the atom stream.
1680 * This gives it to them.
1682 * @param User $cur Current user
1684 * @return array representation of <statusnet:notice_info> element
1687 function noticeInfo($cur)
1689 // local notice ID (useful to clients for ordering)
1691 $noticeInfoAttr = array('local_id' => $this->id);
1695 $ns = $this->getSource();
1697 if ($ns instanceof Notice_source) {
1698 $noticeInfoAttr['source'] = $ns->code;
1699 if (!empty($ns->url)) {
1700 $noticeInfoAttr['source_link'] = $ns->url;
1701 if (!empty($ns->name)) {
1702 $noticeInfoAttr['source'] = '<a href="'
1703 . htmlspecialchars($ns->url)
1704 . '" rel="nofollow">'
1705 . htmlspecialchars($ns->name)
1711 // favorite and repeated
1714 $cp = $cur->getProfile();
1715 $noticeInfoAttr['favorite'] = ($cp->hasFave($this)) ? "true" : "false";
1716 $noticeInfoAttr['repeated'] = ($cp->hasRepeated($this)) ? "true" : "false";
1719 if (!empty($this->repeat_of)) {
1720 $noticeInfoAttr['repeat_of'] = $this->repeat_of;
1723 return array('statusnet:notice_info', $noticeInfoAttr, null);
1727 * Returns an XML string fragment with a reference to a notice as an
1728 * Activity Streams noun object with the given element type.
1730 * Assumes that 'activity' namespace has been previously defined.
1732 * @param string $element one of 'subject', 'object', 'target'
1736 function asActivityNoun($element)
1738 $noun = ActivityObject::fromNotice($this);
1739 return $noun->asString('activity:' . $element);
1743 * Determine which notice, if any, a new notice is in reply to.
1745 * For conversation tracking, we try to see where this notice fits
1746 * in the tree. Beware that this may very well give false positives
1747 * and add replies to wrong threads (if there have been newer posts
1748 * by the same user as we're replying to).
1750 * @param Profile $sender Author profile
1751 * @param string $content Final notice content
1753 * @return integer ID of replied-to notice, or null for not a reply.
1756 static function getInlineReplyTo(Profile $sender, $content)
1758 // Is there an initial @ or T?
1759 if (preg_match('/^T ([A-Z0-9]{1,64}) /', $content, $match)
1760 || preg_match('/^@([a-z0-9]{1,64})\s+/', $content, $match)) {
1761 $nickname = common_canonical_nickname($match[1]);
1766 // Figure out who that is.
1767 $recipient = common_relative_profile($sender, $nickname, common_sql_now());
1769 if ($recipient instanceof Profile) {
1770 // Get their last notice
1771 $last = $recipient->getCurrentNotice();
1772 if ($last instanceof Notice) {
1775 // Maybe in the future we want to handle something else below
1776 // so don't return getCurrentNotice() immediately.
1782 static function maxContent()
1784 $contentlimit = common_config('notice', 'contentlimit');
1785 // null => use global limit (distinct from 0!)
1786 if (is_null($contentlimit)) {
1787 $contentlimit = common_config('site', 'textlimit');
1789 return $contentlimit;
1792 static function contentTooLong($content)
1794 $contentlimit = self::maxContent();
1795 return ($contentlimit > 0 && !empty($content) && (mb_strlen($content) > $contentlimit));
1798 function getLocation()
1802 if (!empty($this->location_id) && !empty($this->location_ns)) {
1803 $location = Location::fromId($this->location_id, $this->location_ns);
1806 if (is_null($location)) { // no ID, or Location::fromId() failed
1807 if (!empty($this->lat) && !empty($this->lon)) {
1808 $location = Location::fromLatLon($this->lat, $this->lon);
1816 * Convenience function for posting a repeat of an existing message.
1818 * @param Profile $repeater Profile which is doing the repeat
1819 * @param string $source: posting source key, eg 'web', 'api', etc
1822 * @throws Exception on failure or permission problems
1824 function repeat(Profile $repeater, $source)
1826 $author = $this->getProfile();
1828 // TRANS: Message used to repeat a notice. RT is the abbreviation of 'retweet'.
1829 // TRANS: %1$s is the repeated user's name, %2$s is the repeated notice.
1830 $content = sprintf(_('RT @%1$s %2$s'),
1831 $author->getNickname(),
1834 // Scope is same as this one's
1835 return self::saveNew($repeater->id,
1838 array('repeat_of' => $this->id,
1839 'scope' => $this->scope));
1842 // These are supposed to be in chron order!
1844 function repeatStream($limit=100)
1846 $cache = Cache::instance();
1848 if (empty($cache)) {
1849 $ids = $this->_repeatStreamDirect($limit);
1851 $idstr = $cache->get(Cache::key('notice:repeats:'.$this->id));
1852 if ($idstr !== false) {
1853 if (empty($idstr)) {
1856 $ids = explode(',', $idstr);
1859 $ids = $this->_repeatStreamDirect(100);
1860 $cache->set(Cache::key('notice:repeats:'.$this->id), implode(',', $ids));
1863 // We do a max of 100, so slice down to limit
1864 $ids = array_slice($ids, 0, $limit);
1868 return NoticeStream::getStreamByIds($ids);
1871 function _repeatStreamDirect($limit)
1873 $notice = new Notice();
1875 $notice->selectAdd(); // clears it
1876 $notice->selectAdd('id');
1878 $notice->repeat_of = $this->id;
1880 $notice->orderBy('created, id'); // NB: asc!
1882 if (!is_null($limit)) {
1883 $notice->limit(0, $limit);
1886 return $notice->fetchAll('id');
1889 function locationOptions($lat, $lon, $location_id, $location_ns, $profile = null)
1893 if (!empty($location_id) && !empty($location_ns)) {
1894 $options['location_id'] = $location_id;
1895 $options['location_ns'] = $location_ns;
1897 $location = Location::fromId($location_id, $location_ns);
1899 if ($location instanceof Location) {
1900 $options['lat'] = $location->lat;
1901 $options['lon'] = $location->lon;
1904 } else if (!empty($lat) && !empty($lon)) {
1905 $options['lat'] = $lat;
1906 $options['lon'] = $lon;
1908 $location = Location::fromLatLon($lat, $lon);
1910 if ($location instanceof Location) {
1911 $options['location_id'] = $location->location_id;
1912 $options['location_ns'] = $location->location_ns;
1914 } else if (!empty($profile)) {
1915 if (isset($profile->lat) && isset($profile->lon)) {
1916 $options['lat'] = $profile->lat;
1917 $options['lon'] = $profile->lon;
1920 if (isset($profile->location_id) && isset($profile->location_ns)) {
1921 $options['location_id'] = $profile->location_id;
1922 $options['location_ns'] = $profile->location_ns;
1929 function clearAttentions()
1931 $att = new Attention();
1932 $att->notice_id = $this->getID();
1935 while ($att->fetch()) {
1936 // Can't do delete() on the object directly since it won't remove all of it
1937 $other = clone($att);
1943 function clearReplies()
1945 $replyNotice = new Notice();
1946 $replyNotice->reply_to = $this->id;
1948 //Null any notices that are replies to this notice
1950 if ($replyNotice->find()) {
1951 while ($replyNotice->fetch()) {
1952 $orig = clone($replyNotice);
1953 $replyNotice->reply_to = null;
1954 $replyNotice->update($orig);
1960 $reply = new Reply();
1961 $reply->notice_id = $this->id;
1963 if ($reply->find()) {
1964 while($reply->fetch()) {
1965 self::blow('reply:stream:%d', $reply->profile_id);
1973 function clearFiles()
1975 $f2p = new File_to_post();
1977 $f2p->post_id = $this->id;
1980 while ($f2p->fetch()) {
1984 // FIXME: decide whether to delete File objects
1985 // ...and related (actual) files
1988 function clearRepeats()
1990 $repeatNotice = new Notice();
1991 $repeatNotice->repeat_of = $this->id;
1993 //Null any notices that are repeats of this notice
1995 if ($repeatNotice->find()) {
1996 while ($repeatNotice->fetch()) {
1997 $orig = clone($repeatNotice);
1998 $repeatNotice->repeat_of = null;
1999 $repeatNotice->update($orig);
2004 function clearFaves()
2007 $fave->notice_id = $this->id;
2009 if ($fave->find()) {
2010 while ($fave->fetch()) {
2011 self::blow('fave:ids_by_user_own:%d', $fave->user_id);
2012 self::blow('fave:ids_by_user_own:%d;last', $fave->user_id);
2013 self::blow('fave:ids_by_user:%d', $fave->user_id);
2014 self::blow('fave:ids_by_user:%d;last', $fave->user_id);
2022 function clearTags()
2024 $tag = new Notice_tag();
2025 $tag->notice_id = $this->id;
2028 while ($tag->fetch()) {
2029 self::blow('profile:notice_ids_tagged:%d:%s', $this->profile_id, Cache::keyize($tag->tag));
2030 self::blow('profile:notice_ids_tagged:%d:%s;last', $this->profile_id, Cache::keyize($tag->tag));
2031 self::blow('notice_tag:notice_ids:%s', Cache::keyize($tag->tag));
2032 self::blow('notice_tag:notice_ids:%s;last', Cache::keyize($tag->tag));
2040 function clearGroupInboxes()
2042 $gi = new Group_inbox();
2044 $gi->notice_id = $this->id;
2047 while ($gi->fetch()) {
2048 self::blow('user_group:notice_ids:%d', $gi->group_id);
2056 function distribute()
2058 // We always insert for the author so they don't
2060 Event::handle('StartNoticeDistribute', array($this));
2062 // If there's a failure, we want to _force_
2063 // distribution at this point.
2065 $qm = QueueManager::get();
2066 $qm->enqueue($this, 'distrib');
2067 } catch (Exception $e) {
2068 // If the exception isn't transient, this
2069 // may throw more exceptions as DQH does
2070 // its own enqueueing. So, we ignore them!
2072 $handler = new DistribQueueHandler();
2073 $handler->handle($this);
2074 } catch (Exception $e) {
2075 common_log(LOG_ERR, "emergency redistribution resulted in " . $e->getMessage());
2077 // Re-throw so somebody smarter can handle it.
2084 $result = parent::insert();
2086 if ($result !== false) {
2087 // Profile::hasRepeated() abuses pkeyGet(), so we
2088 // have to clear manually
2089 if (!empty($this->repeat_of)) {
2090 $c = self::memcache();
2092 $ck = self::multicacheKey('Notice',
2093 array('profile_id' => $this->profile_id,
2094 'repeat_of' => $this->repeat_of));
2104 * Get the source of the notice
2106 * @return Notice_source $ns A notice source object. 'code' is the only attribute
2107 * guaranteed to be populated.
2109 function getSource()
2111 $ns = new Notice_source();
2112 if (!empty($this->source)) {
2113 switch ($this->source) {
2120 $ns->code = $this->source;
2123 $ns = Notice_source::getKV($this->source);
2125 $ns = new Notice_source();
2126 $ns->code = $this->source;
2127 $app = Oauth_application::getKV('name', $this->source);
2129 $ns->name = $app->name;
2130 $ns->url = $app->source_url;
2140 * Determine whether the notice was locally created
2142 * @return boolean locality
2145 public function isLocal()
2147 return ($this->is_local == Notice::LOCAL_PUBLIC ||
2148 $this->is_local == Notice::LOCAL_NONPUBLIC);
2152 * Get the list of hash tags saved with this notice.
2154 * @return array of strings
2156 public function getTags()
2160 $keypart = sprintf('notice:tags:%d', $this->id);
2162 $tagstr = self::cacheGet($keypart);
2164 if ($tagstr !== false) {
2165 $tags = explode(',', $tagstr);
2167 $tag = new Notice_tag();
2168 $tag->notice_id = $this->id;
2170 while ($tag->fetch()) {
2171 $tags[] = $tag->tag;
2174 self::cacheSet($keypart, implode(',', $tags));
2180 static private function utcDate($dt)
2182 $dateStr = date('d F Y H:i:s', strtotime($dt));
2183 $d = new DateTime($dateStr, new DateTimeZone('UTC'));
2184 return $d->format(DATE_W3C);
2188 * Look up the creation timestamp for a given notice ID, even
2189 * if it's been deleted.
2192 * @return mixed string recorded creation timestamp, or false if can't be found
2194 public static function getAsTimestamp($id)
2200 $notice = Notice::getKV('id', $id);
2202 return $notice->created;
2205 $deleted = Deleted_notice::getKV('id', $id);
2207 return $deleted->created;
2214 * Build an SQL 'where' fragment for timestamp-based sorting from a since_id
2215 * parameter, matching notices posted after the given one (exclusive).
2217 * If the referenced notice can't be found, will return false.
2220 * @param string $idField
2221 * @param string $createdField
2222 * @return mixed string or false if no match
2224 public static function whereSinceId($id, $idField='id', $createdField='created')
2226 $since = Notice::getAsTimestamp($id);
2228 return sprintf("($createdField = '%s' and $idField > %d) or ($createdField > '%s')", $since, $id, $since);
2234 * Build an SQL 'where' fragment for timestamp-based sorting from a since_id
2235 * parameter, matching notices posted after the given one (exclusive), and
2236 * if necessary add it to the data object's query.
2238 * @param DB_DataObject $obj
2240 * @param string $idField
2241 * @param string $createdField
2242 * @return mixed string or false if no match
2244 public static function addWhereSinceId(DB_DataObject $obj, $id, $idField='id', $createdField='created')
2246 $since = self::whereSinceId($id, $idField, $createdField);
2248 $obj->whereAdd($since);
2253 * Build an SQL 'where' fragment for timestamp-based sorting from a max_id
2254 * parameter, matching notices posted before the given one (inclusive).
2256 * If the referenced notice can't be found, will return false.
2259 * @param string $idField
2260 * @param string $createdField
2261 * @return mixed string or false if no match
2263 public static function whereMaxId($id, $idField='id', $createdField='created')
2265 $max = Notice::getAsTimestamp($id);
2267 return sprintf("($createdField < '%s') or ($createdField = '%s' and $idField <= %d)", $max, $max, $id);
2273 * Build an SQL 'where' fragment for timestamp-based sorting from a max_id
2274 * parameter, matching notices posted before the given one (inclusive), and
2275 * if necessary add it to the data object's query.
2277 * @param DB_DataObject $obj
2279 * @param string $idField
2280 * @param string $createdField
2281 * @return mixed string or false if no match
2283 public static function addWhereMaxId(DB_DataObject $obj, $id, $idField='id', $createdField='created')
2285 $max = self::whereMaxId($id, $idField, $createdField);
2287 $obj->whereAdd($max);
2293 if (common_config('public', 'localonly')) {
2294 return ($this->is_local == Notice::LOCAL_PUBLIC);
2296 return (($this->is_local != Notice::LOCAL_NONPUBLIC) &&
2297 ($this->is_local != Notice::GATEWAY));
2302 * Check that the given profile is allowed to read, respond to, or otherwise
2303 * act on this notice.
2305 * The $scope member is a bitmask of scopes, representing a logical AND of the
2306 * scope requirement. So, 0x03 (Notice::ADDRESSEE_SCOPE | Notice::SITE_SCOPE) means
2307 * "only visible to people who are mentioned in the notice AND are users on this site."
2308 * Users on the site who are not mentioned in the notice will not be able to see the
2311 * @param Profile $profile The profile to check; pass null to check for public/unauthenticated users.
2313 * @return boolean whether the profile is in the notice's scope
2315 function inScope($profile)
2317 if (is_null($profile)) {
2318 $keypart = sprintf('notice:in-scope-for:%d:null', $this->id);
2320 $keypart = sprintf('notice:in-scope-for:%d:%d', $this->id, $profile->id);
2323 $result = self::cacheGet($keypart);
2325 if ($result === false) {
2327 if (Event::handle('StartNoticeInScope', array($this, $profile, &$bResult))) {
2328 $bResult = $this->_inScope($profile);
2329 Event::handle('EndNoticeInScope', array($this, $profile, &$bResult));
2331 $result = ($bResult) ? 1 : 0;
2332 self::cacheSet($keypart, $result, 0, 300);
2335 return ($result == 1) ? true : false;
2338 protected function _inScope($profile)
2340 if (!is_null($this->scope)) {
2341 $scope = $this->scope;
2343 $scope = self::defaultScope();
2346 // If there's no scope, anyone (even anon) is in scope.
2348 if ($scope == 0) { // Not private
2350 return !$this->isHiddenSpam($profile);
2352 } else { // Private, somehow
2354 // If there's scope, anon cannot be in scope
2356 if (empty($profile)) {
2360 // Author is always in scope
2362 if ($this->profile_id == $profile->id) {
2366 // Only for users on this site
2368 if (($scope & Notice::SITE_SCOPE) && !$profile->isLocal()) {
2372 // Only for users mentioned in the notice
2374 if ($scope & Notice::ADDRESSEE_SCOPE) {
2376 $reply = Reply::pkeyGet(array('notice_id' => $this->id,
2377 'profile_id' => $profile->id));
2379 if (!$reply instanceof Reply) {
2384 // Only for members of the given group
2386 if ($scope & Notice::GROUP_SCOPE) {
2388 // XXX: just query for the single membership
2390 $groups = $this->getGroups();
2394 foreach ($groups as $group) {
2395 if ($profile->isMember($group)) {
2406 // Only for followers of the author
2410 if ($scope & Notice::FOLLOWER_SCOPE) {
2413 $author = $this->getProfile();
2414 } catch (Exception $e) {
2418 if (!Subscription::exists($profile, $author)) {
2423 return !$this->isHiddenSpam($profile);
2427 function isHiddenSpam($profile) {
2429 // Hide posts by silenced users from everyone but moderators.
2431 if (common_config('notice', 'hidespam')) {
2434 $author = $this->getProfile();
2435 } catch(Exception $e) {
2436 // If we can't get an author, keep it hidden.
2437 // XXX: technically not spam, but, whatever.
2441 if ($author->hasRole(Profile_role::SILENCED)) {
2442 if (!$profile instanceof Profile || (($profile->id !== $author->id) && (!$profile->hasRight(Right::REVIEWSPAM)))) {
2451 public function getParent()
2453 $parent = Notice::getKV('id', $this->reply_to);
2455 if (!$parent instanceof Notice) {
2456 throw new ServerException('Notice has no parent');
2463 * Magic function called at serialize() time.
2465 * We use this to drop a couple process-specific references
2466 * from DB_DataObject which can cause trouble in future
2469 * @return array of variable names to include in serialization.
2474 $vars = parent::__sleep();
2475 $skip = array('_profile', '_groups', '_attachments', '_faves', '_replies', '_repeats');
2476 return array_diff($vars, $skip);
2479 static function defaultScope()
2481 $scope = common_config('notice', 'defaultscope');
2482 if (is_null($scope)) {
2483 if (common_config('site', 'private')) {
2492 static function fillProfiles($notices)
2494 $map = self::getProfiles($notices);
2496 foreach ($notices as $entry=>$notice) {
2498 if (array_key_exists($notice->profile_id, $map)) {
2499 $notice->_setProfile($map[$notice->profile_id]);
2501 } catch (NoProfileException $e) {
2502 common_log(LOG_WARNING, "Failed to fill profile in Notice with non-existing entry for profile_id: {$e->profile_id}");
2503 unset($notices[$entry]);
2507 return array_values($map);
2510 static function getProfiles(&$notices)
2513 foreach ($notices as $notice) {
2514 $ids[] = $notice->profile_id;
2517 $ids = array_unique($ids);
2519 return Profile::pivotGet('id', $ids);
2522 static function fillGroups(&$notices)
2524 $ids = self::_idsOf($notices);
2526 $gis = Group_inbox::listGet('notice_id', $ids);
2530 foreach ($gis as $id => $gi)
2534 $gids[] = $g->group_id;
2538 $gids = array_unique($gids);
2540 $group = User_group::pivotGet('id', $gids);
2542 foreach ($notices as $notice)
2545 $gi = $gis[$notice->id];
2546 foreach ($gi as $g) {
2547 $grps[] = $group[$g->group_id];
2549 $notice->_setGroups($grps);
2553 static function _idsOf(&$notices)
2556 foreach ($notices as $notice) {
2557 $ids[] = $notice->id;
2559 $ids = array_unique($ids);
2563 static function fillAttachments(&$notices)
2565 $ids = self::_idsOf($notices);
2567 $f2pMap = File_to_post::listGet('post_id', $ids);
2571 foreach ($f2pMap as $noticeId => $f2ps) {
2572 foreach ($f2ps as $f2p) {
2573 $fileIds[] = $f2p->file_id;
2577 $fileIds = array_unique($fileIds);
2579 $fileMap = File::pivotGet('id', $fileIds);
2581 foreach ($notices as $notice)
2584 $f2ps = $f2pMap[$notice->id];
2585 foreach ($f2ps as $f2p) {
2586 $files[] = $fileMap[$f2p->file_id];
2588 $notice->_setAttachments($files);
2595 * All faves of this notice
2597 * @return array Array of Fave objects
2602 if (isset($this->_faves) && is_array($this->_faves)) {
2603 return $this->_faves;
2605 $faveMap = Fave::listGet('notice_id', array($this->id));
2606 $this->_faves = $faveMap[$this->id];
2607 return $this->_faves;
2610 function _setFaves($faves)
2612 $this->_faves = $faves;
2615 static function fillFaves(&$notices)
2617 $ids = self::_idsOf($notices);
2618 $faveMap = Fave::listGet('notice_id', $ids);
2621 foreach ($faveMap as $id => $faves) {
2622 $cnt += count($faves);
2623 if (count($faves) > 0) {
2627 foreach ($notices as $notice) {
2628 $faves = $faveMap[$notice->id];
2629 $notice->_setFaves($faves);
2633 static function fillReplies(&$notices)
2635 $ids = self::_idsOf($notices);
2636 $replyMap = Reply::listGet('notice_id', $ids);
2637 foreach ($notices as $notice) {
2638 $replies = $replyMap[$notice->id];
2640 foreach ($replies as $reply) {
2641 $ids[] = $reply->profile_id;
2643 $notice->_setReplies($ids);
2647 protected $_repeats;
2649 function getRepeats()
2651 if (isset($this->_repeats) && is_array($this->_repeats)) {
2652 return $this->_repeats;
2654 $repeatMap = Notice::listGet('repeat_of', array($this->id));
2655 $this->_repeats = $repeatMap[$this->id];
2656 return $this->_repeats;
2659 function _setRepeats($repeats)
2661 $this->_repeats = $repeats;
2664 static function fillRepeats(&$notices)
2666 $ids = self::_idsOf($notices);
2667 $repeatMap = Notice::listGet('repeat_of', $ids);
2668 foreach ($notices as $notice) {
2669 $repeats = $repeatMap[$notice->id];
2670 $notice->_setRepeats($repeats);