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->id;
511 $notice->conversation = $repeat->conversation;
515 // If $reply_to is specified, we check that it exists, and then
516 // return it if it does
517 if (!empty($reply_to)) {
518 $reply = Notice::getKV('id', $reply_to);
519 } elseif (in_array($source, array('xmpp', 'mail', 'sms'))) {
520 // If the source lacks capability of sending the "reply_to"
521 // metadata, let's try to find an inline replyto-reference.
522 $reply = self::getInlineReplyTo($profile, $final);
525 if ($reply instanceof Notice) {
526 if (!$reply->inScope($profile)) {
527 // TRANS: Client error displayed when trying to reply to a notice a the target has no access to.
528 // TRANS: %1$s is a user nickname, %2$d is a notice ID (number).
529 throw new ClientException(sprintf(_('%1$s has no access to notice %2$d.'),
530 $profile->nickname, $reply->id), 403);
533 // If it's a repeat, the reply_to should be to the original
534 if (!empty($reply->repeat_of)) {
535 $notice->reply_to = $reply->repeat_of;
537 $notice->reply_to = $reply->id;
539 // But the conversation ought to be the same :)
540 $notice->conversation = $reply->conversation;
542 // If the original is private to a group, and notice has
543 // no group specified, make it to the same group(s)
545 if (empty($groups) && ($reply->scope & Notice::GROUP_SCOPE)) {
547 $replyGroups = $reply->getGroups();
548 foreach ($replyGroups as $group) {
549 if ($profile->isMember($group)) {
550 $groups[] = $group->id;
559 if (!empty($lat) && !empty($lon)) {
564 if (!empty($location_ns) && !empty($location_id)) {
565 $notice->location_id = $location_id;
566 $notice->location_ns = $location_ns;
569 if (!empty($rendered)) {
570 $notice->rendered = $rendered;
572 $notice->rendered = common_render_content($final, $notice);
576 if (!empty($notice->repeat_of)) {
577 $notice->verb = ActivityVerb::SHARE;
578 $notice->object_type = ActivityObject::ACTIVITY;
580 $notice->verb = ActivityVerb::POST;
583 $notice->verb = $verb;
586 if (empty($object_type)) {
587 $notice->object_type = (empty($notice->reply_to)) ? ActivityObject::NOTE : ActivityObject::COMMENT;
589 $notice->object_type = $object_type;
592 if (is_null($scope)) { // 0 is a valid value
593 if (!empty($reply)) {
594 $notice->scope = $reply->scope;
596 $notice->scope = self::defaultScope();
599 $notice->scope = $scope;
602 // For private streams
605 $user = $profile->getUser();
607 if ($user->private_stream &&
608 ($notice->scope == Notice::PUBLIC_SCOPE ||
609 $notice->scope == Notice::SITE_SCOPE)) {
610 $notice->scope |= Notice::FOLLOWER_SCOPE;
612 } catch (NoSuchUserException $e) {
613 // Cannot handle private streams for remote profiles
616 // Force the scope for private groups
618 foreach ($groups as $groupId) {
619 $group = User_group::getKV('id', $groupId);
620 if ($group instanceof User_group) {
621 if ($group->force_scope) {
622 $notice->scope |= Notice::GROUP_SCOPE;
628 if (Event::handle('StartNoticeSave', array(&$notice))) {
630 // XXX: some of these functions write to the DB
632 $id = $notice->insert();
635 common_log_db_error($notice, 'INSERT', __FILE__);
636 // TRANS: Server exception thrown when a notice cannot be saved.
637 throw new ServerException(_('Problem saving notice.'));
640 // Update ID-dependent columns: URI, conversation
642 $orig = clone($notice);
646 // We can only get here if it's a local notice, since remote notices
647 // should've bailed out earlier due to lacking a URI.
648 if (empty($notice->uri)) {
649 $notice->uri = sprintf('%s%s=%d:%s=%s',
651 'noticeId', $notice->id,
652 'objectType', $notice->get_object_type(true));
656 // If it's not part of a conversation, it's
657 // the beginning of a new conversation.
659 if (empty($notice->conversation)) {
660 $conv = Conversation::create($notice);
661 $notice->conversation = $conv->id;
666 if ($notice->update($orig) === false) {
667 common_log_db_error($notice, 'UPDATE', __FILE__);
668 // TRANS: Server exception thrown when a notice cannot be updated.
669 throw new ServerException(_('Problem saving notice.'));
675 // Clear the cache for subscribed users, so they'll update at next request
676 // XXX: someone clever could prepend instead of clearing the cache
678 $notice->blowOnInsert();
680 // Save per-notice metadata...
682 if (isset($replies)) {
683 $notice->saveKnownReplies($replies);
685 $notice->saveReplies();
689 $notice->saveKnownTags($tags);
694 // Note: groups may save tags, so must be run after tags are saved
695 // to avoid errors on duplicates.
696 // Note: groups should always be set.
698 $notice->saveKnownGroups($groups);
701 $notice->saveKnownUrls($urls);
707 // Prepare inbox delivery, may be queued to background.
708 $notice->distribute();
714 function blowOnInsert($conversation = false)
716 $this->blowStream('profile:notice_ids:%d', $this->profile_id);
718 if ($this->isPublic()) {
719 $this->blowStream('public');
722 self::blow('notice:list-ids:conversation:%s', $this->conversation);
723 self::blow('conversation:notice_count:%d', $this->conversation);
725 if (!empty($this->repeat_of)) {
726 // XXX: we should probably only use one of these
727 $this->blowStream('notice:repeats:%d', $this->repeat_of);
728 self::blow('notice:list-ids:repeat_of:%d', $this->repeat_of);
731 $original = Notice::getKV('id', $this->repeat_of);
733 if ($original instanceof Notice) {
734 $originalUser = User::getKV('id', $original->profile_id);
735 if ($originalUser instanceof User) {
736 $this->blowStream('user:repeats_of_me:%d', $originalUser->id);
740 $profile = Profile::getKV($this->profile_id);
742 if ($profile instanceof Profile) {
743 $profile->blowNoticeCount();
746 $ptags = $this->getProfileTags();
747 foreach ($ptags as $ptag) {
748 $ptag->blowNoticeStreamCache();
753 * Clear cache entries related to this notice at delete time.
754 * Necessary to avoid breaking paging on public, profile timelines.
756 function blowOnDelete()
758 $this->blowOnInsert();
760 self::blow('profile:notice_ids:%d;last', $this->profile_id);
762 if ($this->isPublic()) {
763 self::blow('public;last');
766 self::blow('fave:by_notice', $this->id);
768 if ($this->conversation) {
769 // In case we're the first, will need to calc a new root.
770 self::blow('notice:conversation_root:%d', $this->conversation);
773 $ptags = $this->getProfileTags();
774 foreach ($ptags as $ptag) {
775 $ptag->blowNoticeStreamCache(true);
779 function blowStream()
781 $c = self::memcache();
787 $args = func_get_args();
789 $format = array_shift($args);
791 $keyPart = vsprintf($format, $args);
793 $cacheKey = Cache::key($keyPart);
795 $c->delete($cacheKey);
797 // delete the "last" stream, too, if this notice is
798 // older than the top of that stream
800 $lastKey = $cacheKey.';last';
802 $lastStr = $c->get($lastKey);
804 if ($lastStr !== false) {
805 $window = explode(',', $lastStr);
806 $lastID = $window[0];
807 $lastNotice = Notice::getKV('id', $lastID);
808 if (!$lastNotice instanceof Notice // just weird
809 || strtotime($lastNotice->created) >= strtotime($this->created)) {
810 $c->delete($lastKey);
815 /** save all urls in the notice to the db
817 * follow redirects and save all available file information
818 * (mimetype, date, size, oembed, etc.)
822 function saveUrls() {
823 if (common_config('attachments', 'process_links')) {
824 common_replace_urls_callback($this->content, array($this, 'saveUrl'), $this->id);
829 * Save the given URLs as related links/attachments to the db
831 * follow redirects and save all available file information
832 * (mimetype, date, size, oembed, etc.)
836 function saveKnownUrls($urls)
838 if (common_config('attachments', 'process_links')) {
839 // @fixme validation?
840 foreach (array_unique($urls) as $url) {
842 File::processNew($url, $this->id);
843 } catch (ServerException $e) {
844 // Could not save URL. Log it?
853 function saveUrl($url, $notice_id) {
855 File::processNew($url, $notice_id);
856 } catch (ServerException $e) {
857 // Could not save URL. Log it?
861 static function checkDupes($profile_id, $content) {
862 $profile = Profile::getKV($profile_id);
863 if (!$profile instanceof Profile) {
866 $notice = $profile->getNotices(0, CachingNoticeStream::CACHE_WINDOW);
867 if (!empty($notice)) {
869 while ($notice->fetch()) {
870 if (time() - strtotime($notice->created) >= common_config('site', 'dupelimit')) {
872 } else if ($notice->content == $content) {
877 // If we get here, oldest item in cache window is not
878 // old enough for dupe limit; do direct check against DB
879 $notice = new Notice();
880 $notice->profile_id = $profile_id;
881 $notice->content = $content;
882 $threshold = common_sql_date(time() - common_config('site', 'dupelimit'));
883 $notice->whereAdd(sprintf("created > '%s'", $notice->escape($threshold)));
885 $cnt = $notice->count();
889 static function checkEditThrottle($profile_id) {
890 $profile = Profile::getKV($profile_id);
891 if (!$profile instanceof Profile) {
894 // Get the Nth notice
895 $notice = $profile->getNotices(common_config('throttle', 'count') - 1, 1);
896 if ($notice && $notice->fetch()) {
897 // If the Nth notice was posted less than timespan seconds ago
898 if (time() - strtotime($notice->created) <= common_config('throttle', 'timespan')) {
903 // Either not N notices in the stream, OR the Nth was not posted within timespan seconds
907 protected $_attachments = -1;
909 function attachments() {
911 if ($this->_attachments != -1) {
912 return $this->_attachments;
915 $f2ps = File_to_post::listGet('post_id', array($this->id));
919 foreach ($f2ps[$this->id] as $f2p) {
920 $ids[] = $f2p->file_id;
923 $files = File::multiGet('id', $ids);
925 $this->_attachments = $files->fetchAll();
927 return $this->_attachments;
930 function _setAttachments($attachments)
932 $this->_attachments = $attachments;
935 function publicStream($offset=0, $limit=20, $since_id=0, $max_id=0)
937 $stream = new PublicNoticeStream();
938 return $stream->getNotices($offset, $limit, $since_id, $max_id);
942 function conversationStream($id, $offset=0, $limit=20, $since_id=0, $max_id=0)
944 $stream = new ConversationNoticeStream($id);
946 return $stream->getNotices($offset, $limit, $since_id, $max_id);
950 * Is this notice part of an active conversation?
952 * @return boolean true if other messages exist in the same
953 * conversation, false if this is the only one
955 function hasConversation()
957 if (!empty($this->conversation)) {
958 $conversation = Notice::conversationStream(
964 if ($conversation->N > 0) {
972 * Grab the earliest notice from this conversation.
974 * @return Notice or null
976 function conversationRoot($profile=-1)
978 // XXX: can this happen?
980 if (empty($this->conversation)) {
984 // Get the current profile if not specified
986 if (is_int($profile) && $profile == -1) {
987 $profile = Profile::current();
990 // If this notice is out of scope, no root for you!
992 if (!$this->inScope($profile)) {
996 // If this isn't a reply to anything, then it's its own
999 if (empty($this->reply_to)) {
1003 if (is_null($profile)) {
1004 $keypart = sprintf('notice:conversation_root:%d:null', $this->id);
1006 $keypart = sprintf('notice:conversation_root:%d:%d',
1011 $root = self::cacheGet($keypart);
1013 if ($root !== false && $root->inScope($profile)) {
1020 $parent = $last->getParent();
1021 if ($parent->inScope($profile)) {
1025 } catch (Exception $e) {
1026 // Latest notice has no parent
1028 // No parent, or parent out of scope
1033 self::cacheSet($keypart, $root);
1039 * Pull up a full list of local recipients who will be getting
1040 * this notice in their inbox. Results will be cached, so don't
1041 * change the input data wily-nilly!
1043 * @param array $groups optional list of Group objects;
1044 * if left empty, will be loaded from group_inbox records
1045 * @param array $recipient optional list of reply profile ids
1046 * if left empty, will be loaded from reply records
1047 * @return array associating recipient user IDs with an inbox source constant
1049 function whoGets(array $groups=null, array $recipients=null)
1051 $c = self::memcache();
1054 $ni = $c->get(Cache::key('notice:who_gets:'.$this->id));
1055 if ($ni !== false) {
1060 if (is_null($recipients)) {
1061 $recipients = $this->getReplies();
1066 // Give plugins a chance to add folks in at start...
1067 if (Event::handle('StartNoticeWhoGets', array($this, &$ni))) {
1069 $users = $this->getSubscribedUsers();
1070 foreach ($users as $id) {
1071 $ni[$id] = NOTICE_INBOX_SOURCE_SUB;
1074 if (is_null($groups)) {
1075 $groups = $this->getGroups();
1077 foreach ($groups as $group) {
1078 $users = $group->getUserMembers();
1079 foreach ($users as $id) {
1080 if (!array_key_exists($id, $ni)) {
1081 $ni[$id] = NOTICE_INBOX_SOURCE_GROUP;
1086 $ptAtts = $this->getAttentionsFromProfileTags();
1087 foreach ($ptAtts as $key=>$val) {
1088 if (!array_key_exists($key, $ni)) {
1093 foreach ($recipients as $recipient) {
1094 if (!array_key_exists($recipient, $ni)) {
1095 $ni[$recipient] = NOTICE_INBOX_SOURCE_REPLY;
1099 // Exclude any deleted, non-local, or blocking recipients.
1100 $profile = $this->getProfile();
1101 $originalProfile = null;
1102 if ($this->repeat_of) {
1103 // Check blocks against the original notice's poster as well.
1104 $original = Notice::getKV('id', $this->repeat_of);
1105 if ($original instanceof Notice) {
1106 $originalProfile = $original->getProfile();
1110 foreach ($ni as $id => $source) {
1112 $user = User::getKV('id', $id);
1113 if (!$user instanceof User ||
1114 $user->hasBlocked($profile) ||
1115 ($originalProfile && $user->hasBlocked($originalProfile))) {
1118 } catch (UserNoProfileException $e) {
1119 // User doesn't have a profile; invalid; skip them.
1124 // Give plugins a chance to filter out...
1125 Event::handle('EndNoticeWhoGets', array($this, &$ni));
1129 // XXX: pack this data better
1130 $c->set(Cache::key('notice:who_gets:'.$this->id), $ni);
1136 function getSubscribedUsers()
1140 if(common_config('db','quote_identifiers'))
1141 $user_table = '"user"';
1142 else $user_table = 'user';
1146 'FROM '. $user_table .' JOIN subscription '.
1147 'ON '. $user_table .'.id = subscription.subscriber ' .
1148 'WHERE subscription.subscribed = %d ';
1150 $user->query(sprintf($qry, $this->profile_id));
1154 while ($user->fetch()) {
1163 function getProfileTags()
1165 $profile = $this->getProfile();
1166 $list = $profile->getOtherTags($profile);
1169 while($list->fetch()) {
1170 $ptags[] = clone($list);
1176 public function getAttentionsFromProfileTags()
1179 $ptags = $this->getProfileTags();
1180 foreach ($ptags as $ptag) {
1181 $users = $ptag->getUserSubscribers();
1182 foreach ($users as $id) {
1183 $ni[$id] = NOTICE_INBOX_SOURCE_PROFILE_TAG;
1190 * Record this notice to the given group inboxes for delivery.
1191 * Overrides the regular parsing of !group markup.
1193 * @param string $group_ids
1194 * @fixme might prefer URIs as identifiers, as for replies?
1195 * best with generalizations on user_group to support
1196 * remote groups better.
1198 function saveKnownGroups($group_ids)
1200 if (!is_array($group_ids)) {
1201 // TRANS: Server exception thrown when no array is provided to the method saveKnownGroups().
1202 throw new ServerException(_('Bad type provided to saveKnownGroups.'));
1206 foreach (array_unique($group_ids) as $id) {
1207 $group = User_group::getKV('id', $id);
1208 if ($group instanceof User_group) {
1209 common_log(LOG_ERR, "Local delivery to group id $id, $group->nickname");
1210 $result = $this->addToGroupInbox($group);
1212 common_log_db_error($gi, 'INSERT', __FILE__);
1215 if (common_config('group', 'addtag')) {
1216 // we automatically add a tag for every group name, too
1218 $tag = Notice_tag::pkeyGet(array('tag' => common_canonical_tag($group->nickname),
1219 'notice_id' => $this->id));
1221 if (is_null($tag)) {
1222 $this->saveTag($group->nickname);
1226 $groups[] = clone($group);
1228 common_log(LOG_ERR, "Local delivery to group id $id skipped, doesn't exist");
1235 function addToGroupInbox(User_group $group)
1237 $gi = Group_inbox::pkeyGet(array('group_id' => $group->id,
1238 'notice_id' => $this->id));
1240 if (!$gi instanceof Group_inbox) {
1242 $gi = new Group_inbox();
1244 $gi->group_id = $group->id;
1245 $gi->notice_id = $this->id;
1246 $gi->created = $this->created;
1248 $result = $gi->insert();
1251 common_log_db_error($gi, 'INSERT', __FILE__);
1252 // TRANS: Server exception thrown when an update for a group inbox fails.
1253 throw new ServerException(_('Problem saving group inbox.'));
1256 self::blow('user_group:notice_ids:%d', $gi->group_id);
1263 * Save reply records indicating that this notice needs to be
1264 * delivered to the local users with the given URIs.
1266 * Since this is expected to be used when saving foreign-sourced
1267 * messages, we won't deliver to any remote targets as that's the
1268 * source service's responsibility.
1270 * Mail notifications etc will be handled later.
1272 * @param array $uris Array of unique identifier URIs for recipients
1274 function saveKnownReplies(array $uris)
1280 $sender = Profile::getKV($this->profile_id);
1282 foreach (array_unique($uris) as $uri) {
1284 $profile = Profile::fromUri($uri);
1285 } catch (UnknownUriException $e) {
1286 common_log(LOG_WARNING, "Unable to determine profile for URI '$uri'");
1290 if ($profile->hasBlocked($sender)) {
1291 common_log(LOG_INFO, "Not saving reply to profile {$profile->id} ($uri) from sender {$sender->id} because of a block.");
1295 $this->saveReply($profile->id);
1296 self::blow('reply:stream:%d', $profile->id);
1303 * Pull @-replies from this message's content in StatusNet markup format
1304 * and save reply records indicating that this message needs to be
1305 * delivered to those users.
1307 * Mail notifications to local profiles will be sent later.
1309 * @return array of integer profile IDs
1312 function saveReplies()
1314 // Don't save reply data for repeats
1316 if (!empty($this->repeat_of)) {
1320 $sender = Profile::getKV($this->profile_id);
1324 // If it's a reply, save for the replied-to author
1326 $parent = $this->getParent();
1327 $author = $parent->getProfile();
1328 if ($author instanceof Profile) {
1329 $this->saveReply($author->id);
1330 $replied[$author->id] = 1;
1331 self::blow('reply:stream:%d', $author->id);
1333 } catch (Exception $e) {
1334 // Not a reply, since it has no parent!
1337 // @todo ideally this parser information would only
1338 // be calculated once.
1340 $mentions = common_find_mentions($this->content, $this);
1342 // store replied only for first @ (what user/notice what the reply directed,
1343 // we assume first @ is it)
1345 foreach ($mentions as $mention) {
1347 foreach ($mention['mentioned'] as $mentioned) {
1349 // skip if they're already covered
1351 if (!empty($replied[$mentioned->id])) {
1355 // Don't save replies from blocked profile to local user
1357 $mentioned_user = User::getKV('id', $mentioned->id);
1358 if ($mentioned_user instanceof User && $mentioned_user->hasBlocked($sender)) {
1362 $this->saveReply($mentioned->id);
1363 $replied[$mentioned->id] = 1;
1364 self::blow('reply:stream:%d', $mentioned->id);
1368 $recipientIds = array_keys($replied);
1370 return $recipientIds;
1373 function saveReply($profileId)
1375 $reply = new Reply();
1377 $reply->notice_id = $this->id;
1378 $reply->profile_id = $profileId;
1379 $reply->modified = $this->created;
1386 protected $_replies = -1;
1389 * Pull the complete list of @-reply targets for this notice.
1391 * @return array of integer profile ids
1393 function getReplies()
1395 if ($this->_replies != -1) {
1396 return $this->_replies;
1399 $replyMap = Reply::listGet('notice_id', array($this->id));
1403 foreach ($replyMap[$this->id] as $reply) {
1404 $ids[] = $reply->profile_id;
1407 $this->_replies = $ids;
1412 function _setReplies($replies)
1414 $this->_replies = $replies;
1418 * Pull the complete list of @-reply targets for this notice.
1420 * @return array of Profiles
1422 function getReplyProfiles()
1424 $ids = $this->getReplies();
1426 $profiles = Profile::multiGet('id', $ids);
1428 return $profiles->fetchAll();
1432 * Send e-mail notifications to local @-reply targets.
1434 * Replies must already have been saved; this is expected to be run
1435 * from the distrib queue handler.
1437 function sendReplyNotifications()
1439 // Don't send reply notifications for repeats
1441 if (!empty($this->repeat_of)) {
1445 $recipientIds = $this->getReplies();
1447 foreach ($recipientIds as $recipientId) {
1448 $user = User::getKV('id', $recipientId);
1449 if ($user instanceof User) {
1450 mail_notify_attn($user, $this);
1456 * Pull list of groups this notice needs to be delivered to,
1457 * as previously recorded by saveKnownGroups().
1459 * @return array of Group objects
1462 protected $_groups = -1;
1464 function getGroups()
1466 // Don't save groups for repeats
1468 if (!empty($this->repeat_of)) {
1472 if ($this->_groups != -1)
1474 return $this->_groups;
1477 $gis = Group_inbox::listGet('notice_id', array($this->id));
1481 foreach ($gis[$this->id] as $gi)
1483 $ids[] = $gi->group_id;
1486 $groups = User_group::multiGet('id', $ids);
1488 $this->_groups = $groups->fetchAll();
1490 return $this->_groups;
1493 function _setGroups($groups)
1495 $this->_groups = $groups;
1499 * Convert a notice into an activity for export.
1501 * @param User $cur Current user
1503 * @return Activity activity object representing this Notice.
1506 function asActivity($cur=null)
1508 $act = self::cacheGet(Cache::codeKey('notice:as-activity:'.$this->id));
1510 if ($act instanceof Activity) {
1513 $act = new Activity();
1515 if (Event::handle('StartNoticeAsActivity', array($this, &$act))) {
1517 $act->id = $this->uri;
1518 $act->time = strtotime($this->created);
1520 $act->link = $this->getUrl();
1521 } catch (InvalidUrlException $e) {
1522 // The notice is probably a share or similar, which don't
1523 // have a representational URL of their own.
1525 $act->content = common_xml_safe_str($this->rendered);
1527 $profile = $this->getProfile();
1529 $act->actor = ActivityObject::fromProfile($profile);
1530 $act->actor->extra[] = $profile->profileInfo($cur);
1532 $act->verb = $this->verb;
1534 if ($this->repeat_of) {
1535 $repeated = Notice::getKV('id', $this->repeat_of);
1536 if ($repeated instanceof Notice) {
1537 $act->objects[] = $repeated->asActivity($cur);
1540 $act->objects[] = ActivityObject::fromNotice($this);
1543 // XXX: should this be handled by default processing for object entry?
1547 $tags = $this->getTags();
1549 foreach ($tags as $tag) {
1550 $cat = new AtomCategory();
1553 $act->categories[] = $cat;
1557 // XXX: use Atom Media and/or File activity objects instead
1559 $attachments = $this->attachments();
1561 foreach ($attachments as $attachment) {
1562 // Save local attachments
1563 if (!empty($attachment->filename)) {
1564 $act->attachments[] = ActivityObject::fromFile($attachment);
1568 $ctx = new ActivityContext();
1571 $reply = $this->getParent();
1572 $ctx->replyToID = $reply->getUri();
1573 $ctx->replyToUrl = $reply->getUrl();
1574 } catch (Exception $e) {
1575 // This is not a reply to something
1578 $ctx->location = $this->getLocation();
1582 if (!empty($this->conversation)) {
1583 $conv = Conversation::getKV('id', $this->conversation);
1584 if ($conv instanceof Conversation) {
1585 $ctx->conversation = $conv->uri;
1589 $reply_ids = $this->getReplies();
1591 foreach ($reply_ids as $id) {
1592 $rprofile = Profile::getKV('id', $id);
1593 if ($rprofile instanceof Profile) {
1594 $ctx->attention[$rprofile->getUri()] = ActivityObject::PERSON;
1598 $groups = $this->getGroups();
1600 foreach ($groups as $group) {
1601 $ctx->attention[$group->getUri()] = ActivityObject::GROUP;
1604 switch ($this->scope) {
1605 case Notice::PUBLIC_SCOPE:
1606 $ctx->attention[ActivityContext::ATTN_PUBLIC] = ActivityObject::COLLECTION;
1608 case Notice::FOLLOWER_SCOPE:
1609 $surl = common_local_url("subscribers", array('nickname' => $profile->nickname));
1610 $ctx->attention[$surl] = ActivityObject::COLLECTION;
1614 $act->context = $ctx;
1616 $source = $this->getSource();
1618 if ($source instanceof Notice_source) {
1619 $act->generator = ActivityObject::fromNoticeSource($source);
1624 $atom_feed = $profile->getAtomFeed();
1626 if (!empty($atom_feed)) {
1628 $act->source = new ActivitySource();
1630 // XXX: we should store the actual feed ID
1632 $act->source->id = $atom_feed;
1634 // XXX: we should store the actual feed title
1636 $act->source->title = $profile->getBestName();
1638 $act->source->links['alternate'] = $profile->profileurl;
1639 $act->source->links['self'] = $atom_feed;
1641 $act->source->icon = $profile->avatarUrl(AVATAR_PROFILE_SIZE);
1643 $notice = $profile->getCurrentNotice();
1645 if ($notice instanceof Notice) {
1646 $act->source->updated = self::utcDate($notice->created);
1649 $user = User::getKV('id', $profile->id);
1651 if ($user instanceof User) {
1652 $act->source->links['license'] = common_config('license', 'url');
1656 if ($this->isLocal()) {
1657 $act->selfLink = common_local_url('ApiStatusesShow', array('id' => $this->id,
1658 'format' => 'atom'));
1659 $act->editLink = $act->selfLink;
1662 Event::handle('EndNoticeAsActivity', array($this, &$act));
1665 self::cacheSet(Cache::codeKey('notice:as-activity:'.$this->id), $act);
1670 // This has gotten way too long. Needs to be sliced up into functional bits
1671 // or ideally exported to a utility class.
1673 function asAtomEntry($namespace=false,
1678 $act = $this->asActivity($cur);
1679 $act->extra[] = $this->noticeInfo($cur);
1680 return $act->asString($namespace, $author, $source);
1684 * Extra notice info for atom entries
1686 * Clients use some extra notice info in the atom stream.
1687 * This gives it to them.
1689 * @param User $cur Current user
1691 * @return array representation of <statusnet:notice_info> element
1694 function noticeInfo($cur)
1696 // local notice ID (useful to clients for ordering)
1698 $noticeInfoAttr = array('local_id' => $this->id);
1702 $ns = $this->getSource();
1704 if ($ns instanceof Notice_source) {
1705 $noticeInfoAttr['source'] = $ns->code;
1706 if (!empty($ns->url)) {
1707 $noticeInfoAttr['source_link'] = $ns->url;
1708 if (!empty($ns->name)) {
1709 $noticeInfoAttr['source'] = '<a href="'
1710 . htmlspecialchars($ns->url)
1711 . '" rel="nofollow">'
1712 . htmlspecialchars($ns->name)
1718 // favorite and repeated
1721 $cp = $cur->getProfile();
1722 $noticeInfoAttr['favorite'] = ($cp->hasFave($this)) ? "true" : "false";
1723 $noticeInfoAttr['repeated'] = ($cp->hasRepeated($this)) ? "true" : "false";
1726 if (!empty($this->repeat_of)) {
1727 $noticeInfoAttr['repeat_of'] = $this->repeat_of;
1730 return array('statusnet:notice_info', $noticeInfoAttr, null);
1734 * Returns an XML string fragment with a reference to a notice as an
1735 * Activity Streams noun object with the given element type.
1737 * Assumes that 'activity' namespace has been previously defined.
1739 * @param string $element one of 'subject', 'object', 'target'
1743 function asActivityNoun($element)
1745 $noun = ActivityObject::fromNotice($this);
1746 return $noun->asString('activity:' . $element);
1750 * Determine which notice, if any, a new notice is in reply to.
1752 * For conversation tracking, we try to see where this notice fits
1753 * in the tree. Beware that this may very well give false positives
1754 * and add replies to wrong threads (if there have been newer posts
1755 * by the same user as we're replying to).
1757 * @param Profile $sender Author profile
1758 * @param string $content Final notice content
1760 * @return integer ID of replied-to notice, or null for not a reply.
1763 static function getInlineReplyTo(Profile $sender, $content)
1765 // Is there an initial @ or T?
1766 if (preg_match('/^T ([A-Z0-9]{1,64}) /', $content, $match)
1767 || preg_match('/^@([a-z0-9]{1,64})\s+/', $content, $match)) {
1768 $nickname = common_canonical_nickname($match[1]);
1773 // Figure out who that is.
1774 $recipient = common_relative_profile($sender, $nickname, common_sql_now());
1776 if ($recipient instanceof Profile) {
1777 // Get their last notice
1778 $last = $recipient->getCurrentNotice();
1779 if ($last instanceof Notice) {
1782 // Maybe in the future we want to handle something else below
1783 // so don't return getCurrentNotice() immediately.
1789 static function maxContent()
1791 $contentlimit = common_config('notice', 'contentlimit');
1792 // null => use global limit (distinct from 0!)
1793 if (is_null($contentlimit)) {
1794 $contentlimit = common_config('site', 'textlimit');
1796 return $contentlimit;
1799 static function contentTooLong($content)
1801 $contentlimit = self::maxContent();
1802 return ($contentlimit > 0 && !empty($content) && (mb_strlen($content) > $contentlimit));
1805 function getLocation()
1809 if (!empty($this->location_id) && !empty($this->location_ns)) {
1810 $location = Location::fromId($this->location_id, $this->location_ns);
1813 if (is_null($location)) { // no ID, or Location::fromId() failed
1814 if (!empty($this->lat) && !empty($this->lon)) {
1815 $location = Location::fromLatLon($this->lat, $this->lon);
1823 * Convenience function for posting a repeat of an existing message.
1825 * @param Profile $repeater Profile which is doing the repeat
1826 * @param string $source: posting source key, eg 'web', 'api', etc
1829 * @throws Exception on failure or permission problems
1831 function repeat(Profile $repeater, $source)
1833 $author = $this->getProfile();
1835 // TRANS: Message used to repeat a notice. RT is the abbreviation of 'retweet'.
1836 // TRANS: %1$s is the repeated user's name, %2$s is the repeated notice.
1837 $content = sprintf(_('RT @%1$s %2$s'),
1838 $author->getNickname(),
1841 // Scope is same as this one's
1842 return self::saveNew($repeater->id,
1845 array('repeat_of' => $this->id,
1846 'scope' => $this->scope));
1849 // These are supposed to be in chron order!
1851 function repeatStream($limit=100)
1853 $cache = Cache::instance();
1855 if (empty($cache)) {
1856 $ids = $this->_repeatStreamDirect($limit);
1858 $idstr = $cache->get(Cache::key('notice:repeats:'.$this->id));
1859 if ($idstr !== false) {
1860 if (empty($idstr)) {
1863 $ids = explode(',', $idstr);
1866 $ids = $this->_repeatStreamDirect(100);
1867 $cache->set(Cache::key('notice:repeats:'.$this->id), implode(',', $ids));
1870 // We do a max of 100, so slice down to limit
1871 $ids = array_slice($ids, 0, $limit);
1875 return NoticeStream::getStreamByIds($ids);
1878 function _repeatStreamDirect($limit)
1880 $notice = new Notice();
1882 $notice->selectAdd(); // clears it
1883 $notice->selectAdd('id');
1885 $notice->repeat_of = $this->id;
1887 $notice->orderBy('created, id'); // NB: asc!
1889 if (!is_null($limit)) {
1890 $notice->limit(0, $limit);
1893 return $notice->fetchAll('id');
1896 function locationOptions($lat, $lon, $location_id, $location_ns, $profile = null)
1900 if (!empty($location_id) && !empty($location_ns)) {
1901 $options['location_id'] = $location_id;
1902 $options['location_ns'] = $location_ns;
1904 $location = Location::fromId($location_id, $location_ns);
1906 if ($location instanceof Location) {
1907 $options['lat'] = $location->lat;
1908 $options['lon'] = $location->lon;
1911 } else if (!empty($lat) && !empty($lon)) {
1912 $options['lat'] = $lat;
1913 $options['lon'] = $lon;
1915 $location = Location::fromLatLon($lat, $lon);
1917 if ($location instanceof Location) {
1918 $options['location_id'] = $location->location_id;
1919 $options['location_ns'] = $location->location_ns;
1921 } else if (!empty($profile)) {
1922 if (isset($profile->lat) && isset($profile->lon)) {
1923 $options['lat'] = $profile->lat;
1924 $options['lon'] = $profile->lon;
1927 if (isset($profile->location_id) && isset($profile->location_ns)) {
1928 $options['location_id'] = $profile->location_id;
1929 $options['location_ns'] = $profile->location_ns;
1936 function clearAttentions()
1938 $att = new Attention();
1939 $att->notice_id = $this->getID();
1942 while ($att->fetch()) {
1943 // Can't do delete() on the object directly since it won't remove all of it
1944 $other = clone($att);
1950 function clearReplies()
1952 $replyNotice = new Notice();
1953 $replyNotice->reply_to = $this->id;
1955 //Null any notices that are replies to this notice
1957 if ($replyNotice->find()) {
1958 while ($replyNotice->fetch()) {
1959 $orig = clone($replyNotice);
1960 $replyNotice->reply_to = null;
1961 $replyNotice->update($orig);
1967 $reply = new Reply();
1968 $reply->notice_id = $this->id;
1970 if ($reply->find()) {
1971 while($reply->fetch()) {
1972 self::blow('reply:stream:%d', $reply->profile_id);
1980 function clearFiles()
1982 $f2p = new File_to_post();
1984 $f2p->post_id = $this->id;
1987 while ($f2p->fetch()) {
1991 // FIXME: decide whether to delete File objects
1992 // ...and related (actual) files
1995 function clearRepeats()
1997 $repeatNotice = new Notice();
1998 $repeatNotice->repeat_of = $this->id;
2000 //Null any notices that are repeats of this notice
2002 if ($repeatNotice->find()) {
2003 while ($repeatNotice->fetch()) {
2004 $orig = clone($repeatNotice);
2005 $repeatNotice->repeat_of = null;
2006 $repeatNotice->update($orig);
2011 function clearFaves()
2014 $fave->notice_id = $this->id;
2016 if ($fave->find()) {
2017 while ($fave->fetch()) {
2018 self::blow('fave:ids_by_user_own:%d', $fave->user_id);
2019 self::blow('fave:ids_by_user_own:%d;last', $fave->user_id);
2020 self::blow('fave:ids_by_user:%d', $fave->user_id);
2021 self::blow('fave:ids_by_user:%d;last', $fave->user_id);
2029 function clearTags()
2031 $tag = new Notice_tag();
2032 $tag->notice_id = $this->id;
2035 while ($tag->fetch()) {
2036 self::blow('profile:notice_ids_tagged:%d:%s', $this->profile_id, Cache::keyize($tag->tag));
2037 self::blow('profile:notice_ids_tagged:%d:%s;last', $this->profile_id, Cache::keyize($tag->tag));
2038 self::blow('notice_tag:notice_ids:%s', Cache::keyize($tag->tag));
2039 self::blow('notice_tag:notice_ids:%s;last', Cache::keyize($tag->tag));
2047 function clearGroupInboxes()
2049 $gi = new Group_inbox();
2051 $gi->notice_id = $this->id;
2054 while ($gi->fetch()) {
2055 self::blow('user_group:notice_ids:%d', $gi->group_id);
2063 function distribute()
2065 // We always insert for the author so they don't
2067 Event::handle('StartNoticeDistribute', array($this));
2069 // If there's a failure, we want to _force_
2070 // distribution at this point.
2072 $qm = QueueManager::get();
2073 $qm->enqueue($this, 'distrib');
2074 } catch (Exception $e) {
2075 // If the exception isn't transient, this
2076 // may throw more exceptions as DQH does
2077 // its own enqueueing. So, we ignore them!
2079 $handler = new DistribQueueHandler();
2080 $handler->handle($this);
2081 } catch (Exception $e) {
2082 common_log(LOG_ERR, "emergency redistribution resulted in " . $e->getMessage());
2084 // Re-throw so somebody smarter can handle it.
2091 $result = parent::insert();
2093 if ($result !== false) {
2094 // Profile::hasRepeated() abuses pkeyGet(), so we
2095 // have to clear manually
2096 if (!empty($this->repeat_of)) {
2097 $c = self::memcache();
2099 $ck = self::multicacheKey('Notice',
2100 array('profile_id' => $this->profile_id,
2101 'repeat_of' => $this->repeat_of));
2111 * Get the source of the notice
2113 * @return Notice_source $ns A notice source object. 'code' is the only attribute
2114 * guaranteed to be populated.
2116 function getSource()
2118 $ns = new Notice_source();
2119 if (!empty($this->source)) {
2120 switch ($this->source) {
2127 $ns->code = $this->source;
2130 $ns = Notice_source::getKV($this->source);
2132 $ns = new Notice_source();
2133 $ns->code = $this->source;
2134 $app = Oauth_application::getKV('name', $this->source);
2136 $ns->name = $app->name;
2137 $ns->url = $app->source_url;
2147 * Determine whether the notice was locally created
2149 * @return boolean locality
2152 public function isLocal()
2154 return ($this->is_local == Notice::LOCAL_PUBLIC ||
2155 $this->is_local == Notice::LOCAL_NONPUBLIC);
2159 * Get the list of hash tags saved with this notice.
2161 * @return array of strings
2163 public function getTags()
2167 $keypart = sprintf('notice:tags:%d', $this->id);
2169 $tagstr = self::cacheGet($keypart);
2171 if ($tagstr !== false) {
2172 $tags = explode(',', $tagstr);
2174 $tag = new Notice_tag();
2175 $tag->notice_id = $this->id;
2177 while ($tag->fetch()) {
2178 $tags[] = $tag->tag;
2181 self::cacheSet($keypart, implode(',', $tags));
2187 static private function utcDate($dt)
2189 $dateStr = date('d F Y H:i:s', strtotime($dt));
2190 $d = new DateTime($dateStr, new DateTimeZone('UTC'));
2191 return $d->format(DATE_W3C);
2195 * Look up the creation timestamp for a given notice ID, even
2196 * if it's been deleted.
2199 * @return mixed string recorded creation timestamp, or false if can't be found
2201 public static function getAsTimestamp($id)
2207 $notice = Notice::getKV('id', $id);
2209 return $notice->created;
2212 $deleted = Deleted_notice::getKV('id', $id);
2214 return $deleted->created;
2221 * Build an SQL 'where' fragment for timestamp-based sorting from a since_id
2222 * parameter, matching notices posted after the given one (exclusive).
2224 * If the referenced notice can't be found, will return false.
2227 * @param string $idField
2228 * @param string $createdField
2229 * @return mixed string or false if no match
2231 public static function whereSinceId($id, $idField='id', $createdField='created')
2233 $since = Notice::getAsTimestamp($id);
2235 return sprintf("($createdField = '%s' and $idField > %d) or ($createdField > '%s')", $since, $id, $since);
2241 * Build an SQL 'where' fragment for timestamp-based sorting from a since_id
2242 * parameter, matching notices posted after the given one (exclusive), and
2243 * if necessary add it to the data object's query.
2245 * @param DB_DataObject $obj
2247 * @param string $idField
2248 * @param string $createdField
2249 * @return mixed string or false if no match
2251 public static function addWhereSinceId(DB_DataObject $obj, $id, $idField='id', $createdField='created')
2253 $since = self::whereSinceId($id, $idField, $createdField);
2255 $obj->whereAdd($since);
2260 * Build an SQL 'where' fragment for timestamp-based sorting from a max_id
2261 * parameter, matching notices posted before the given one (inclusive).
2263 * If the referenced notice can't be found, will return false.
2266 * @param string $idField
2267 * @param string $createdField
2268 * @return mixed string or false if no match
2270 public static function whereMaxId($id, $idField='id', $createdField='created')
2272 $max = Notice::getAsTimestamp($id);
2274 return sprintf("($createdField < '%s') or ($createdField = '%s' and $idField <= %d)", $max, $max, $id);
2280 * Build an SQL 'where' fragment for timestamp-based sorting from a max_id
2281 * parameter, matching notices posted before the given one (inclusive), and
2282 * if necessary add it to the data object's query.
2284 * @param DB_DataObject $obj
2286 * @param string $idField
2287 * @param string $createdField
2288 * @return mixed string or false if no match
2290 public static function addWhereMaxId(DB_DataObject $obj, $id, $idField='id', $createdField='created')
2292 $max = self::whereMaxId($id, $idField, $createdField);
2294 $obj->whereAdd($max);
2300 if (common_config('public', 'localonly')) {
2301 return ($this->is_local == Notice::LOCAL_PUBLIC);
2303 return (($this->is_local != Notice::LOCAL_NONPUBLIC) &&
2304 ($this->is_local != Notice::GATEWAY));
2309 * Check that the given profile is allowed to read, respond to, or otherwise
2310 * act on this notice.
2312 * The $scope member is a bitmask of scopes, representing a logical AND of the
2313 * scope requirement. So, 0x03 (Notice::ADDRESSEE_SCOPE | Notice::SITE_SCOPE) means
2314 * "only visible to people who are mentioned in the notice AND are users on this site."
2315 * Users on the site who are not mentioned in the notice will not be able to see the
2318 * @param Profile $profile The profile to check; pass null to check for public/unauthenticated users.
2320 * @return boolean whether the profile is in the notice's scope
2322 function inScope($profile)
2324 if (is_null($profile)) {
2325 $keypart = sprintf('notice:in-scope-for:%d:null', $this->id);
2327 $keypart = sprintf('notice:in-scope-for:%d:%d', $this->id, $profile->id);
2330 $result = self::cacheGet($keypart);
2332 if ($result === false) {
2334 if (Event::handle('StartNoticeInScope', array($this, $profile, &$bResult))) {
2335 $bResult = $this->_inScope($profile);
2336 Event::handle('EndNoticeInScope', array($this, $profile, &$bResult));
2338 $result = ($bResult) ? 1 : 0;
2339 self::cacheSet($keypart, $result, 0, 300);
2342 return ($result == 1) ? true : false;
2345 protected function _inScope($profile)
2347 if (!is_null($this->scope)) {
2348 $scope = $this->scope;
2350 $scope = self::defaultScope();
2353 // If there's no scope, anyone (even anon) is in scope.
2355 if ($scope == 0) { // Not private
2357 return !$this->isHiddenSpam($profile);
2359 } else { // Private, somehow
2361 // If there's scope, anon cannot be in scope
2363 if (empty($profile)) {
2367 // Author is always in scope
2369 if ($this->profile_id == $profile->id) {
2373 // Only for users on this site
2375 if (($scope & Notice::SITE_SCOPE) && !$profile->isLocal()) {
2379 // Only for users mentioned in the notice
2381 if ($scope & Notice::ADDRESSEE_SCOPE) {
2383 $reply = Reply::pkeyGet(array('notice_id' => $this->id,
2384 'profile_id' => $profile->id));
2386 if (!$reply instanceof Reply) {
2391 // Only for members of the given group
2393 if ($scope & Notice::GROUP_SCOPE) {
2395 // XXX: just query for the single membership
2397 $groups = $this->getGroups();
2401 foreach ($groups as $group) {
2402 if ($profile->isMember($group)) {
2413 // Only for followers of the author
2417 if ($scope & Notice::FOLLOWER_SCOPE) {
2420 $author = $this->getProfile();
2421 } catch (Exception $e) {
2425 if (!Subscription::exists($profile, $author)) {
2430 return !$this->isHiddenSpam($profile);
2434 function isHiddenSpam($profile) {
2436 // Hide posts by silenced users from everyone but moderators.
2438 if (common_config('notice', 'hidespam')) {
2441 $author = $this->getProfile();
2442 } catch(Exception $e) {
2443 // If we can't get an author, keep it hidden.
2444 // XXX: technically not spam, but, whatever.
2448 if ($author->hasRole(Profile_role::SILENCED)) {
2449 if (!$profile instanceof Profile || (($profile->id !== $author->id) && (!$profile->hasRight(Right::REVIEWSPAM)))) {
2458 public function getParent()
2460 $parent = Notice::getKV('id', $this->reply_to);
2462 if (!$parent instanceof Notice) {
2463 throw new ServerException('Notice has no parent');
2470 * Magic function called at serialize() time.
2472 * We use this to drop a couple process-specific references
2473 * from DB_DataObject which can cause trouble in future
2476 * @return array of variable names to include in serialization.
2481 $vars = parent::__sleep();
2482 $skip = array('_profile', '_groups', '_attachments', '_faves', '_replies', '_repeats');
2483 return array_diff($vars, $skip);
2486 static function defaultScope()
2488 $scope = common_config('notice', 'defaultscope');
2489 if (is_null($scope)) {
2490 if (common_config('site', 'private')) {
2499 static function fillProfiles($notices)
2501 $map = self::getProfiles($notices);
2503 foreach ($notices as $entry=>$notice) {
2505 if (array_key_exists($notice->profile_id, $map)) {
2506 $notice->_setProfile($map[$notice->profile_id]);
2508 } catch (NoProfileException $e) {
2509 common_log(LOG_WARNING, "Failed to fill profile in Notice with non-existing entry for profile_id: {$e->profile_id}");
2510 unset($notices[$entry]);
2514 return array_values($map);
2517 static function getProfiles(&$notices)
2520 foreach ($notices as $notice) {
2521 $ids[] = $notice->profile_id;
2524 $ids = array_unique($ids);
2526 return Profile::pivotGet('id', $ids);
2529 static function fillGroups(&$notices)
2531 $ids = self::_idsOf($notices);
2533 $gis = Group_inbox::listGet('notice_id', $ids);
2537 foreach ($gis as $id => $gi)
2541 $gids[] = $g->group_id;
2545 $gids = array_unique($gids);
2547 $group = User_group::pivotGet('id', $gids);
2549 foreach ($notices as $notice)
2552 $gi = $gis[$notice->id];
2553 foreach ($gi as $g) {
2554 $grps[] = $group[$g->group_id];
2556 $notice->_setGroups($grps);
2560 static function _idsOf(&$notices)
2563 foreach ($notices as $notice) {
2564 $ids[] = $notice->id;
2566 $ids = array_unique($ids);
2570 static function fillAttachments(&$notices)
2572 $ids = self::_idsOf($notices);
2574 $f2pMap = File_to_post::listGet('post_id', $ids);
2578 foreach ($f2pMap as $noticeId => $f2ps) {
2579 foreach ($f2ps as $f2p) {
2580 $fileIds[] = $f2p->file_id;
2584 $fileIds = array_unique($fileIds);
2586 $fileMap = File::pivotGet('id', $fileIds);
2588 foreach ($notices as $notice)
2591 $f2ps = $f2pMap[$notice->id];
2592 foreach ($f2ps as $f2p) {
2593 $files[] = $fileMap[$f2p->file_id];
2595 $notice->_setAttachments($files);
2602 * All faves of this notice
2604 * @return array Array of Fave objects
2609 if (isset($this->_faves) && is_array($this->_faves)) {
2610 return $this->_faves;
2612 $faveMap = Fave::listGet('notice_id', array($this->id));
2613 $this->_faves = $faveMap[$this->id];
2614 return $this->_faves;
2617 function _setFaves($faves)
2619 $this->_faves = $faves;
2622 static function fillFaves(&$notices)
2624 $ids = self::_idsOf($notices);
2625 $faveMap = Fave::listGet('notice_id', $ids);
2628 foreach ($faveMap as $id => $faves) {
2629 $cnt += count($faves);
2630 if (count($faves) > 0) {
2634 foreach ($notices as $notice) {
2635 $faves = $faveMap[$notice->id];
2636 $notice->_setFaves($faves);
2640 static function fillReplies(&$notices)
2642 $ids = self::_idsOf($notices);
2643 $replyMap = Reply::listGet('notice_id', $ids);
2644 foreach ($notices as $notice) {
2645 $replies = $replyMap[$notice->id];
2647 foreach ($replies as $reply) {
2648 $ids[] = $reply->profile_id;
2650 $notice->_setReplies($ids);
2654 protected $_repeats;
2656 function getRepeats()
2658 if (isset($this->_repeats) && is_array($this->_repeats)) {
2659 return $this->_repeats;
2661 $repeatMap = Notice::listGet('repeat_of', array($this->id));
2662 $this->_repeats = $repeatMap[$this->id];
2663 return $this->_repeats;
2666 function _setRepeats($repeats)
2668 $this->_repeats = $repeats;
2671 static function fillRepeats(&$notices)
2673 $ids = self::_idsOf($notices);
2674 $repeatMap = Notice::listGet('repeat_of', $ids);
2675 foreach ($notices as $notice) {
2676 $repeats = $repeatMap[$notice->id];
2677 $notice->_setRepeats($repeats);