3 * StatusNet - the distributed open-source microblogging tool
4 * Copyright (C) 2008-2011 StatusNet, Inc.
6 * This program is free software: you can redistribute it and/or modify
7 * it under the terms of the GNU Affero General Public License as published by
8 * the Free Software Foundation, either version 3 of the License, or
9 * (at your option) any later version.
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU Affero General Public License for more details.
16 * You should have received a copy of the GNU Affero General Public License
17 * along with this program. If not, see <http://www.gnu.org/licenses/>.
21 * @author Brenda Wallace <shiny@cpan.org>
22 * @author Christopher Vollick <psycotica0@gmail.com>
23 * @author CiaranG <ciaran@ciarang.com>
24 * @author Craig Andrews <candrews@integralblue.com>
25 * @author Evan Prodromou <evan@controlezvous.ca>
26 * @author Gina Haeussge <osd@foosel.net>
27 * @author Jeffery To <jeffery.to@gmail.com>
28 * @author Mike Cochrane <mikec@mikenz.geek.nz>
29 * @author Robin Millette <millette@controlyourself.ca>
30 * @author Sarven Capadisli <csarven@controlyourself.ca>
31 * @author Tom Adams <tom@holizz.com>
32 * @author Mikael Nordfeldth <mmn@hethane.se>
33 * @copyright 2009 Free Software Foundation, Inc http://www.fsf.org
34 * @license GNU Affero General Public License http://www.gnu.org/licenses/
37 if (!defined('GNUSOCIAL')) { exit(1); }
40 * Table Definition for notice
43 /* We keep 200 notices, the max number of notices available per API request,
44 * in the memcached cache. */
46 define('NOTICE_CACHE_WINDOW', CachingNoticeStream::CACHE_WINDOW);
48 define('MAX_BOXCARS', 128);
50 class Notice extends Managed_DataObject
53 /* the code below is auto generated do not remove the above tag */
55 public $__table = 'notice'; // table name
56 public $id; // int(4) primary_key not_null
57 public $profile_id; // int(4) multiple_key not_null
58 public $uri; // varchar(255) unique_key
59 public $content; // text
60 public $rendered; // text
61 public $url; // varchar(255)
62 public $created; // datetime multiple_key not_null default_0000-00-00%2000%3A00%3A00
63 public $modified; // timestamp not_null default_CURRENT_TIMESTAMP
64 public $reply_to; // int(4)
65 public $is_local; // int(4)
66 public $source; // varchar(32)
67 public $conversation; // int(4)
68 public $lat; // decimal(10,7)
69 public $lon; // decimal(10,7)
70 public $location_id; // int(4)
71 public $location_ns; // int(4)
72 public $repeat_of; // int(4)
73 public $verb; // varchar(255)
74 public $object_type; // varchar(255)
75 public $scope; // int(4)
77 /* the code above is auto generated do not remove the tag below */
80 public static function schemaDef()
84 'id' => array('type' => 'serial', 'not null' => true, 'description' => 'unique identifier'),
85 'profile_id' => array('type' => 'int', 'not null' => true, 'description' => 'who made the update'),
86 'uri' => array('type' => 'varchar', 'length' => 255, 'description' => 'universally unique identifier, usually a tag URI'),
87 'content' => array('type' => 'text', 'description' => 'update content', 'collate' => 'utf8_general_ci'),
88 'rendered' => array('type' => 'text', 'description' => 'HTML version of the content'),
89 'url' => array('type' => 'varchar', 'length' => 255, 'description' => 'URL of any attachment (image, video, bookmark, whatever)'),
90 'created' => array('type' => 'datetime', 'not null' => true, 'description' => 'date this record was created'),
91 'modified' => array('type' => 'timestamp', 'not null' => true, 'description' => 'date this record was modified'),
92 'reply_to' => array('type' => 'int', 'description' => 'notice replied to (usually a guess)'),
93 'is_local' => array('type' => 'int', 'size' => 'tiny', 'default' => 0, 'description' => 'notice was generated by a user'),
94 'source' => array('type' => 'varchar', 'length' => 32, 'description' => 'source of comment, like "web", "im", or "clientname"'),
95 'conversation' => array('type' => 'int', 'description' => 'id of root notice in this conversation'),
96 'lat' => array('type' => 'numeric', 'precision' => 10, 'scale' => 7, 'description' => 'latitude'),
97 'lon' => array('type' => 'numeric', 'precision' => 10, 'scale' => 7, 'description' => 'longitude'),
98 'location_id' => array('type' => 'int', 'description' => 'location id if possible'),
99 'location_ns' => array('type' => 'int', 'description' => 'namespace for location'),
100 'repeat_of' => array('type' => 'int', 'description' => 'notice this is a repeat of'),
101 'object_type' => array('type' => 'varchar', 'length' => 255, 'description' => 'URI representing activity streams object type', 'default' => 'http://activitystrea.ms/schema/1.0/note'),
102 'verb' => array('type' => 'varchar', 'length' => 255, 'description' => 'URI representing activity streams verb', 'default' => 'http://activitystrea.ms/schema/1.0/post'),
103 'scope' => array('type' => 'int',
104 'description' => 'bit map for distribution scope; 0 = everywhere; 1 = this server only; 2 = addressees; 4 = followers; null = default'),
106 'primary key' => array('id'),
107 'unique keys' => array(
108 'notice_uri_key' => array('uri'),
110 'foreign keys' => array(
111 'notice_profile_id_fkey' => array('profile', array('profile_id' => 'id')),
112 'notice_reply_to_fkey' => array('notice', array('reply_to' => 'id')),
113 'notice_conversation_fkey' => array('conversation', array('conversation' => 'id')), # note... used to refer to notice.id
114 'notice_repeat_of_fkey' => array('notice', array('repeat_of' => 'id')), # @fixme: what about repeats of deleted notices?
117 'notice_created_id_is_local_idx' => array('created', 'id', 'is_local'),
118 'notice_profile_id_idx' => array('profile_id', 'created', 'id'),
119 'notice_repeat_of_created_id_idx' => array('repeat_of', 'created', 'id'),
120 'notice_conversation_created_id_idx' => array('conversation', 'created', 'id'),
121 'notice_replyto_idx' => array('reply_to')
125 if (common_config('search', 'type') == 'fulltext') {
126 $def['fulltext indexes'] = array('content' => array('content'));
133 const LOCAL_PUBLIC = 1;
135 const LOCAL_NONPUBLIC = -1;
138 const PUBLIC_SCOPE = 0; // Useful fake constant
139 const SITE_SCOPE = 1;
140 const ADDRESSEE_SCOPE = 2;
141 const GROUP_SCOPE = 4;
142 const FOLLOWER_SCOPE = 8;
144 protected $_profile = -1;
146 public function getProfile()
148 if ($this->_profile === -1) {
149 $this->_setProfile(Profile::getKV('id', $this->profile_id));
151 return $this->_profile;
154 public function _setProfile(Profile $profile=null)
156 if (!$profile instanceof Profile) {
157 throw new NoProfileException($this->profile_id);
159 $this->_profile = $profile;
162 function delete($useWhere=false)
164 // For auditing purposes, save a record that the notice
167 // @fixme we have some cases where things get re-run and so the
169 $deleted = Deleted_notice::getKV('id', $this->id);
171 if (!$deleted instanceof Deleted_notice) {
172 $deleted = Deleted_notice::getKV('uri', $this->uri);
175 if (!$deleted instanceof Deleted_notice) {
176 $deleted = new Deleted_notice();
178 $deleted->id = $this->id;
179 $deleted->profile_id = $this->profile_id;
180 $deleted->uri = $this->uri;
181 $deleted->created = $this->created;
182 $deleted->deleted = common_sql_now();
187 if (Event::handle('NoticeDeleteRelated', array($this))) {
189 // Clear related records
191 $this->clearReplies();
192 $this->clearRepeats();
195 $this->clearGroupInboxes();
197 $this->clearAttentions();
199 // NOTE: we don't clear queue items
202 $result = parent::delete($useWhere);
204 $this->blowOnDelete();
208 public function getUri()
213 public function getUrl()
215 // The risk is we start having empty urls and non-http uris...
216 // and we can't really handle any other protocol right now.
218 case common_valid_http_url($this->url):
220 case common_valid_http_url($this->uri):
223 throw new ServerException('No URL available for notice.');
227 public function get_object_type($canonical=false) {
229 ? ActivityObject::canonicalType($this->object_type)
230 : $this->object_type;
233 public static function getByUri($uri)
235 $notice = new Notice();
237 if (!$notice->find(true)) {
238 throw new NoResultException($notice);
244 * Extract #hashtags from this notice's content and save them to the database.
248 /* extract all #hastags */
249 $count = preg_match_all('/(?:^|\s)#([\pL\pN_\-\.]{1,64})/u', strtolower($this->content), $match);
254 /* Add them to the database */
255 return $this->saveKnownTags($match[1]);
259 * Record the given set of hash tags in the db for this notice.
260 * Given tag strings will be normalized and checked for dupes.
262 function saveKnownTags($hashtags)
264 //turn each into their canonical tag
265 //this is needed to remove dupes before saving e.g. #hash.tag = #hashtag
266 for($i=0; $i<count($hashtags); $i++) {
267 /* elide characters we don't want in the tag */
268 $hashtags[$i] = common_canonical_tag($hashtags[$i]);
271 foreach(array_unique($hashtags) as $hashtag) {
272 $this->saveTag($hashtag);
273 self::blow('profile:notice_ids_tagged:%d:%s', $this->profile_id, $hashtag);
279 * Record a single hash tag as associated with this notice.
280 * Tag format and uniqueness must be validated by caller.
282 function saveTag($hashtag)
284 $tag = new Notice_tag();
285 $tag->notice_id = $this->id;
286 $tag->tag = $hashtag;
287 $tag->created = $this->created;
288 $id = $tag->insert();
291 // TRANS: Server exception. %s are the error details.
292 throw new ServerException(sprintf(_('Database error inserting hashtag: %s.'),
293 $last_error->message));
297 // if it's saved, blow its cache
298 $tag->blowCache(false);
302 * Save a new notice and push it out to subscribers' inboxes.
303 * Poster's permissions are checked before sending.
305 * @param int $profile_id Profile ID of the poster
306 * @param string $content source message text; links may be shortened
307 * per current user's preference
308 * @param string $source source key ('web', 'api', etc)
309 * @param array $options Associative array of optional properties:
310 * string 'created' timestamp of notice; defaults to now
311 * int 'is_local' source/gateway ID, one of:
312 * Notice::LOCAL_PUBLIC - Local, ok to appear in public timeline
313 * Notice::REMOTE - Sent from a remote service;
314 * hide from public timeline but show in
315 * local "and friends" timelines
316 * Notice::LOCAL_NONPUBLIC - Local, but hide from public timeline
317 * Notice::GATEWAY - From another non-OStatus service;
318 * will not appear in public views
319 * float 'lat' decimal latitude for geolocation
320 * float 'lon' decimal longitude for geolocation
321 * int 'location_id' geoname identifier
322 * int 'location_ns' geoname namespace to interpret location_id
323 * int 'reply_to'; notice ID this is a reply to
324 * int 'repeat_of'; notice ID this is a repeat of
325 * string 'uri' unique ID for notice; a unique tag uri (can be url or anything too)
326 * string 'url' permalink to notice; defaults to local notice URL
327 * string 'rendered' rendered HTML version of content
328 * array 'replies' list of profile URIs for reply delivery in
329 * place of extracting @-replies from content.
330 * array 'groups' list of group IDs to deliver to, in place of
331 * extracting ! tags from content
332 * array 'tags' list of hashtag strings to save with the notice
333 * in place of extracting # tags from content
334 * array 'urls' list of attached/referred URLs to save with the
335 * notice in place of extracting links from content
336 * boolean 'distribute' whether to distribute the notice, default true
337 * string 'object_type' URL of the associated object type (default ActivityObject::NOTE)
338 * string 'verb' URL of the associated verb (default ActivityVerb::POST)
339 * int 'scope' Scope bitmask; default to SITE_SCOPE on private sites, 0 otherwise
341 * @fixme tag override
344 * @throws ClientException
346 static function saveNew($profile_id, $content, $source, array $options=null) {
347 $defaults = array('uri' => null,
352 'distribute' => true,
353 'object_type' => null,
356 if (!empty($options) && is_array($options)) {
357 $options = array_merge($defaults, $options);
363 if (!isset($is_local)) {
364 $is_local = Notice::LOCAL_PUBLIC;
367 $profile = Profile::getKV('id', $profile_id);
368 if (!$profile instanceof Profile) {
369 // TRANS: Client exception thrown when trying to save a notice for an unknown user.
370 throw new ClientException(_('Problem saving notice. Unknown user.'));
373 $user = User::getKV('id', $profile_id);
374 if ($user instanceof User) {
375 // Use the local user's shortening preferences, if applicable.
376 $final = $user->shortenLinks($content);
378 $final = common_shorten_links($content);
381 if (Notice::contentTooLong($final)) {
382 // TRANS: Client exception thrown if a notice contains too many characters.
383 throw new ClientException(_('Problem saving notice. Too long.'));
386 if (common_config('throttle', 'enabled') && !Notice::checkEditThrottle($profile_id)) {
387 common_log(LOG_WARNING, 'Excessive posting by profile #' . $profile_id . '; throttled.');
388 // TRANS: Client exception thrown when a user tries to post too many notices in a given time frame.
389 throw new ClientException(_('Too many notices too fast; take a breather '.
390 'and post again in a few minutes.'));
393 if (common_config('site', 'dupelimit') > 0 && !Notice::checkDupes($profile_id, $final)) {
394 common_log(LOG_WARNING, 'Dupe posting by profile #' . $profile_id . '; throttled.');
395 // TRANS: Client exception thrown when a user tries to post too many duplicate notices in a given time frame.
396 throw new ClientException(_('Too many duplicate messages too quickly;'.
397 ' take a breather and post again in a few minutes.'));
400 if (!$profile->hasRight(Right::NEWNOTICE)) {
401 common_log(LOG_WARNING, "Attempted post from user disallowed to post: " . $profile->nickname);
403 // TRANS: Client exception thrown when a user tries to post while being banned.
404 throw new ClientException(_('You are banned from posting notices on this site.'), 403);
407 $notice = new Notice();
408 $notice->profile_id = $profile_id;
410 $autosource = common_config('public', 'autosource');
412 // Sandboxed are non-false, but not 1, either
414 if (!$profile->hasRight(Right::PUBLICNOTICE) ||
415 ($source && $autosource && in_array($source, $autosource))) {
416 $notice->is_local = Notice::LOCAL_NONPUBLIC;
418 $notice->is_local = $is_local;
421 if (!empty($created)) {
422 $notice->created = $created;
424 $notice->created = common_sql_now();
427 $notice->content = $final;
429 $notice->source = $source;
433 // Get the groups here so we can figure out replies and such
434 if (!isset($groups)) {
435 $groups = User_group::idsFromText($notice->content, $profile);
440 // Handle repeat case
442 if (isset($repeat_of)) {
444 // Check for a private one
446 $repeat = Notice::getKV('id', $repeat_of);
448 if (!($repeat instanceof Notice)) {
449 // TRANS: Client exception thrown in notice when trying to repeat a missing or deleted notice.
450 throw new ClientException(_('Cannot repeat; original notice is missing or deleted.'));
453 if ($profile->id == $repeat->profile_id) {
454 // TRANS: Client error displayed when trying to repeat an own notice.
455 throw new ClientException(_('You cannot repeat your own notice.'));
458 if ($repeat->scope != Notice::SITE_SCOPE &&
459 $repeat->scope != Notice::PUBLIC_SCOPE) {
460 // TRANS: Client error displayed when trying to repeat a non-public notice.
461 throw new ClientException(_('Cannot repeat a private notice.'), 403);
464 if (!$repeat->inScope($profile)) {
465 // The generic checks above should cover this, but let's be sure!
466 // TRANS: Client error displayed when trying to repeat a notice you cannot access.
467 throw new ClientException(_('Cannot repeat a notice you cannot read.'), 403);
470 if ($profile->hasRepeated($repeat)) {
471 // TRANS: Client error displayed when trying to repeat an already repeated notice.
472 throw new ClientException(_('You already repeated that notice.'));
475 $notice->repeat_of = $repeat_of;
477 $reply = self::getReplyTo($reply_to, $profile_id, $source, $final);
479 if (!empty($reply)) {
481 if (!$reply->inScope($profile)) {
482 // TRANS: Client error displayed when trying to reply to a notice a the target has no access to.
483 // TRANS: %1$s is a user nickname, %2$d is a notice ID (number).
484 throw new ClientException(sprintf(_('%1$s has no access to notice %2$d.'),
485 $profile->nickname, $reply->id), 403);
488 $notice->reply_to = $reply->id;
489 $notice->conversation = $reply->conversation;
491 // If the original is private to a group, and notice has no group specified,
492 // make it to the same group(s)
494 if (empty($groups) && ($reply->scope & Notice::GROUP_SCOPE)) {
496 $replyGroups = $reply->getGroups();
497 foreach ($replyGroups as $group) {
498 if ($profile->isMember($group)) {
499 $groups[] = $group->id;
508 if (!empty($lat) && !empty($lon)) {
513 if (!empty($location_ns) && !empty($location_id)) {
514 $notice->location_id = $location_id;
515 $notice->location_ns = $location_ns;
518 if (!empty($rendered)) {
519 $notice->rendered = $rendered;
521 $notice->rendered = common_render_content($final, $notice);
525 if (!empty($notice->repeat_of)) {
526 $notice->verb = ActivityVerb::SHARE;
527 $notice->object_type = ActivityObject::ACTIVITY;
529 $notice->verb = ActivityVerb::POST;
532 $notice->verb = $verb;
535 if (empty($object_type)) {
536 $notice->object_type = (empty($notice->reply_to)) ? ActivityObject::NOTE : ActivityObject::COMMENT;
538 $notice->object_type = $object_type;
541 if (is_null($scope)) { // 0 is a valid value
542 if (!empty($reply)) {
543 $notice->scope = $reply->scope;
545 $notice->scope = self::defaultScope();
548 $notice->scope = $scope;
551 // For private streams
554 $user = $profile->getUser();
556 if ($user->private_stream &&
557 ($notice->scope == Notice::PUBLIC_SCOPE ||
558 $notice->scope == Notice::SITE_SCOPE)) {
559 $notice->scope |= Notice::FOLLOWER_SCOPE;
561 } catch (NoSuchUserException $e) {
562 // Cannot handle private streams for remote profiles
565 // Force the scope for private groups
567 foreach ($groups as $groupId) {
568 $group = User_group::getKV('id', $groupId);
569 if ($group instanceof User_group) {
570 if ($group->force_scope) {
571 $notice->scope |= Notice::GROUP_SCOPE;
577 if (Event::handle('StartNoticeSave', array(&$notice))) {
579 // XXX: some of these functions write to the DB
581 $id = $notice->insert();
584 common_log_db_error($notice, 'INSERT', __FILE__);
585 // TRANS: Server exception thrown when a notice cannot be saved.
586 throw new ServerException(_('Problem saving notice.'));
589 // Update ID-dependent columns: URI, conversation
591 $orig = clone($notice);
596 $notice->uri = sprintf('%s:%s=%d:%s=%s',
598 'noticeId', $notice->id,
599 'objectType', $notice->get_object_type(true));
603 // If it's not part of a conversation, it's
604 // the beginning of a new conversation.
606 if (empty($notice->conversation)) {
607 $conv = Conversation::create($notice);
608 $notice->conversation = $conv->id;
613 if ($notice->update($orig) === false) {
614 common_log_db_error($notice, 'UPDATE', __FILE__);
615 // TRANS: Server exception thrown when a notice cannot be updated.
616 throw new ServerException(_('Problem saving notice.'));
622 // Clear the cache for subscribed users, so they'll update at next request
623 // XXX: someone clever could prepend instead of clearing the cache
625 $notice->blowOnInsert();
627 // Save per-notice metadata...
629 if (isset($replies)) {
630 $notice->saveKnownReplies($replies);
632 $notice->saveReplies();
636 $notice->saveKnownTags($tags);
641 // Note: groups may save tags, so must be run after tags are saved
642 // to avoid errors on duplicates.
643 // Note: groups should always be set.
645 $notice->saveKnownGroups($groups);
648 $notice->saveKnownUrls($urls);
654 // Prepare inbox delivery, may be queued to background.
655 $notice->distribute();
661 function blowOnInsert($conversation = false)
663 $this->blowStream('profile:notice_ids:%d', $this->profile_id);
665 if ($this->isPublic()) {
666 $this->blowStream('public');
669 self::blow('notice:list-ids:conversation:%s', $this->conversation);
670 self::blow('conversation:notice_count:%d', $this->conversation);
672 if (!empty($this->repeat_of)) {
673 // XXX: we should probably only use one of these
674 $this->blowStream('notice:repeats:%d', $this->repeat_of);
675 self::blow('notice:list-ids:repeat_of:%d', $this->repeat_of);
678 $original = Notice::getKV('id', $this->repeat_of);
680 if ($original instanceof Notice) {
681 $originalUser = User::getKV('id', $original->profile_id);
682 if ($originalUser instanceof User) {
683 $this->blowStream('user:repeats_of_me:%d', $originalUser->id);
687 $profile = Profile::getKV($this->profile_id);
689 if ($profile instanceof Profile) {
690 $profile->blowNoticeCount();
693 $ptags = $this->getProfileTags();
694 foreach ($ptags as $ptag) {
695 $ptag->blowNoticeStreamCache();
700 * Clear cache entries related to this notice at delete time.
701 * Necessary to avoid breaking paging on public, profile timelines.
703 function blowOnDelete()
705 $this->blowOnInsert();
707 self::blow('profile:notice_ids:%d;last', $this->profile_id);
709 if ($this->isPublic()) {
710 self::blow('public;last');
713 self::blow('fave:by_notice', $this->id);
715 if ($this->conversation) {
716 // In case we're the first, will need to calc a new root.
717 self::blow('notice:conversation_root:%d', $this->conversation);
720 $ptags = $this->getProfileTags();
721 foreach ($ptags as $ptag) {
722 $ptag->blowNoticeStreamCache(true);
726 function blowStream()
728 $c = self::memcache();
734 $args = func_get_args();
736 $format = array_shift($args);
738 $keyPart = vsprintf($format, $args);
740 $cacheKey = Cache::key($keyPart);
742 $c->delete($cacheKey);
744 // delete the "last" stream, too, if this notice is
745 // older than the top of that stream
747 $lastKey = $cacheKey.';last';
749 $lastStr = $c->get($lastKey);
751 if ($lastStr !== false) {
752 $window = explode(',', $lastStr);
753 $lastID = $window[0];
754 $lastNotice = Notice::getKV('id', $lastID);
755 if (!$lastNotice instanceof Notice // just weird
756 || strtotime($lastNotice->created) >= strtotime($this->created)) {
757 $c->delete($lastKey);
762 /** save all urls in the notice to the db
764 * follow redirects and save all available file information
765 * (mimetype, date, size, oembed, etc.)
769 function saveUrls() {
770 if (common_config('attachments', 'process_links')) {
771 common_replace_urls_callback($this->content, array($this, 'saveUrl'), $this->id);
776 * Save the given URLs as related links/attachments to the db
778 * follow redirects and save all available file information
779 * (mimetype, date, size, oembed, etc.)
783 function saveKnownUrls($urls)
785 if (common_config('attachments', 'process_links')) {
786 // @fixme validation?
787 foreach (array_unique($urls) as $url) {
788 File::processNew($url, $this->id);
796 function saveUrl($url, $notice_id) {
797 File::processNew($url, $notice_id);
800 static function checkDupes($profile_id, $content) {
801 $profile = Profile::getKV($profile_id);
802 if (!$profile instanceof Profile) {
805 $notice = $profile->getNotices(0, CachingNoticeStream::CACHE_WINDOW);
806 if (!empty($notice)) {
808 while ($notice->fetch()) {
809 if (time() - strtotime($notice->created) >= common_config('site', 'dupelimit')) {
811 } else if ($notice->content == $content) {
816 // If we get here, oldest item in cache window is not
817 // old enough for dupe limit; do direct check against DB
818 $notice = new Notice();
819 $notice->profile_id = $profile_id;
820 $notice->content = $content;
821 $threshold = common_sql_date(time() - common_config('site', 'dupelimit'));
822 $notice->whereAdd(sprintf("created > '%s'", $notice->escape($threshold)));
824 $cnt = $notice->count();
828 static function checkEditThrottle($profile_id) {
829 $profile = Profile::getKV($profile_id);
830 if (!$profile instanceof Profile) {
833 // Get the Nth notice
834 $notice = $profile->getNotices(common_config('throttle', 'count') - 1, 1);
835 if ($notice && $notice->fetch()) {
836 // If the Nth notice was posted less than timespan seconds ago
837 if (time() - strtotime($notice->created) <= common_config('throttle', 'timespan')) {
842 // Either not N notices in the stream, OR the Nth was not posted within timespan seconds
846 protected $_attachments = -1;
848 function attachments() {
850 if ($this->_attachments != -1) {
851 return $this->_attachments;
854 $f2ps = File_to_post::listGet('post_id', array($this->id));
858 foreach ($f2ps[$this->id] as $f2p) {
859 $ids[] = $f2p->file_id;
862 $files = File::multiGet('id', $ids);
864 $this->_attachments = $files->fetchAll();
866 return $this->_attachments;
869 function _setAttachments($attachments)
871 $this->_attachments = $attachments;
874 function publicStream($offset=0, $limit=20, $since_id=0, $max_id=0)
876 $stream = new PublicNoticeStream();
877 return $stream->getNotices($offset, $limit, $since_id, $max_id);
881 function conversationStream($id, $offset=0, $limit=20, $since_id=0, $max_id=0)
883 $stream = new ConversationNoticeStream($id);
885 return $stream->getNotices($offset, $limit, $since_id, $max_id);
889 * Is this notice part of an active conversation?
891 * @return boolean true if other messages exist in the same
892 * conversation, false if this is the only one
894 function hasConversation()
896 if (!empty($this->conversation)) {
897 $conversation = Notice::conversationStream(
903 if ($conversation->N > 0) {
911 * Grab the earliest notice from this conversation.
913 * @return Notice or null
915 function conversationRoot($profile=-1)
917 // XXX: can this happen?
919 if (empty($this->conversation)) {
923 // Get the current profile if not specified
925 if (is_int($profile) && $profile == -1) {
926 $profile = Profile::current();
929 // If this notice is out of scope, no root for you!
931 if (!$this->inScope($profile)) {
935 // If this isn't a reply to anything, then it's its own
938 if (empty($this->reply_to)) {
942 if (is_null($profile)) {
943 $keypart = sprintf('notice:conversation_root:%d:null', $this->id);
945 $keypart = sprintf('notice:conversation_root:%d:%d',
950 $root = self::cacheGet($keypart);
952 if ($root !== false && $root->inScope($profile)) {
959 $parent = $last->getParent();
960 if ($parent->inScope($profile)) {
964 } catch (Exception $e) {
965 // Latest notice has no parent
967 // No parent, or parent out of scope
972 self::cacheSet($keypart, $root);
978 * Pull up a full list of local recipients who will be getting
979 * this notice in their inbox. Results will be cached, so don't
980 * change the input data wily-nilly!
982 * @param array $groups optional list of Group objects;
983 * if left empty, will be loaded from group_inbox records
984 * @param array $recipient optional list of reply profile ids
985 * if left empty, will be loaded from reply records
986 * @return array associating recipient user IDs with an inbox source constant
988 function whoGets(array $groups=null, array $recipients=null)
990 $c = self::memcache();
993 $ni = $c->get(Cache::key('notice:who_gets:'.$this->id));
999 if (is_null($recipients)) {
1000 $recipients = $this->getReplies();
1005 // Give plugins a chance to add folks in at start...
1006 if (Event::handle('StartNoticeWhoGets', array($this, &$ni))) {
1008 $users = $this->getSubscribedUsers();
1009 foreach ($users as $id) {
1010 $ni[$id] = NOTICE_INBOX_SOURCE_SUB;
1013 if (is_null($groups)) {
1014 $groups = $this->getGroups();
1016 foreach ($groups as $group) {
1017 $users = $group->getUserMembers();
1018 foreach ($users as $id) {
1019 if (!array_key_exists($id, $ni)) {
1020 $ni[$id] = NOTICE_INBOX_SOURCE_GROUP;
1025 $ptAtts = $this->getAttentionsFromProfileTags();
1026 foreach ($ptAtts as $key=>$val) {
1027 if (!array_key_exists($key, $ni)) {
1032 foreach ($recipients as $recipient) {
1033 if (!array_key_exists($recipient, $ni)) {
1034 $ni[$recipient] = NOTICE_INBOX_SOURCE_REPLY;
1038 // Exclude any deleted, non-local, or blocking recipients.
1039 $profile = $this->getProfile();
1040 $originalProfile = null;
1041 if ($this->repeat_of) {
1042 // Check blocks against the original notice's poster as well.
1043 $original = Notice::getKV('id', $this->repeat_of);
1044 if ($original instanceof Notice) {
1045 $originalProfile = $original->getProfile();
1049 foreach ($ni as $id => $source) {
1051 $user = User::getKV('id', $id);
1052 if (!$user instanceof User ||
1053 $user->hasBlocked($profile) ||
1054 ($originalProfile && $user->hasBlocked($originalProfile))) {
1057 } catch (UserNoProfileException $e) {
1058 // User doesn't have a profile; invalid; skip them.
1063 // Give plugins a chance to filter out...
1064 Event::handle('EndNoticeWhoGets', array($this, &$ni));
1068 // XXX: pack this data better
1069 $c->set(Cache::key('notice:who_gets:'.$this->id), $ni);
1075 function getSubscribedUsers()
1079 if(common_config('db','quote_identifiers'))
1080 $user_table = '"user"';
1081 else $user_table = 'user';
1085 'FROM '. $user_table .' JOIN subscription '.
1086 'ON '. $user_table .'.id = subscription.subscriber ' .
1087 'WHERE subscription.subscribed = %d ';
1089 $user->query(sprintf($qry, $this->profile_id));
1093 while ($user->fetch()) {
1102 function getProfileTags()
1104 $profile = $this->getProfile();
1105 $list = $profile->getOtherTags($profile);
1108 while($list->fetch()) {
1109 $ptags[] = clone($list);
1115 public function getAttentionsFromProfileTags()
1118 $ptags = $this->getProfileTags();
1119 foreach ($ptags as $ptag) {
1120 $users = $ptag->getUserSubscribers();
1121 foreach ($users as $id) {
1122 $ni[$id] = NOTICE_INBOX_SOURCE_PROFILE_TAG;
1129 * Record this notice to the given group inboxes for delivery.
1130 * Overrides the regular parsing of !group markup.
1132 * @param string $group_ids
1133 * @fixme might prefer URIs as identifiers, as for replies?
1134 * best with generalizations on user_group to support
1135 * remote groups better.
1137 function saveKnownGroups($group_ids)
1139 if (!is_array($group_ids)) {
1140 // TRANS: Server exception thrown when no array is provided to the method saveKnownGroups().
1141 throw new ServerException(_('Bad type provided to saveKnownGroups.'));
1145 foreach (array_unique($group_ids) as $id) {
1146 $group = User_group::getKV('id', $id);
1147 if ($group instanceof User_group) {
1148 common_log(LOG_ERR, "Local delivery to group id $id, $group->nickname");
1149 $result = $this->addToGroupInbox($group);
1151 common_log_db_error($gi, 'INSERT', __FILE__);
1154 if (common_config('group', 'addtag')) {
1155 // we automatically add a tag for every group name, too
1157 $tag = Notice_tag::pkeyGet(array('tag' => common_canonical_tag($group->nickname),
1158 'notice_id' => $this->id));
1160 if (is_null($tag)) {
1161 $this->saveTag($group->nickname);
1165 $groups[] = clone($group);
1167 common_log(LOG_ERR, "Local delivery to group id $id skipped, doesn't exist");
1174 function addToGroupInbox(User_group $group)
1176 $gi = Group_inbox::pkeyGet(array('group_id' => $group->id,
1177 'notice_id' => $this->id));
1179 if (!$gi instanceof Group_inbox) {
1181 $gi = new Group_inbox();
1183 $gi->group_id = $group->id;
1184 $gi->notice_id = $this->id;
1185 $gi->created = $this->created;
1187 $result = $gi->insert();
1190 common_log_db_error($gi, 'INSERT', __FILE__);
1191 // TRANS: Server exception thrown when an update for a group inbox fails.
1192 throw new ServerException(_('Problem saving group inbox.'));
1195 self::blow('user_group:notice_ids:%d', $gi->group_id);
1202 * Save reply records indicating that this notice needs to be
1203 * delivered to the local users with the given URIs.
1205 * Since this is expected to be used when saving foreign-sourced
1206 * messages, we won't deliver to any remote targets as that's the
1207 * source service's responsibility.
1209 * Mail notifications etc will be handled later.
1211 * @param array $uris Array of unique identifier URIs for recipients
1213 function saveKnownReplies(array $uris)
1219 $sender = Profile::getKV($this->profile_id);
1221 foreach (array_unique($uris) as $uri) {
1223 $profile = Profile::fromURI($uri);
1225 if (!$profile instanceof Profile) {
1226 common_log(LOG_WARNING, "Unable to determine profile for URI '$uri'");
1230 if ($profile->hasBlocked($sender)) {
1231 common_log(LOG_INFO, "Not saving reply to profile {$profile->id} ($uri) from sender {$sender->id} because of a block.");
1235 $this->saveReply($profile->id);
1236 self::blow('reply:stream:%d', $profile->id);
1243 * Pull @-replies from this message's content in StatusNet markup format
1244 * and save reply records indicating that this message needs to be
1245 * delivered to those users.
1247 * Mail notifications to local profiles will be sent later.
1249 * @return array of integer profile IDs
1252 function saveReplies()
1254 // Don't save reply data for repeats
1256 if (!empty($this->repeat_of)) {
1260 $sender = Profile::getKV($this->profile_id);
1264 // If it's a reply, save for the replied-to author
1266 $parent = $this->getParent();
1267 $author = $parent->getProfile();
1268 if ($author instanceof Profile) {
1269 $this->saveReply($author->id);
1270 $replied[$author->id] = 1;
1271 self::blow('reply:stream:%d', $author->id);
1273 } catch (Exception $e) {
1274 // Not a reply, since it has no parent!
1277 // @todo ideally this parser information would only
1278 // be calculated once.
1280 $mentions = common_find_mentions($this->content, $this);
1282 // store replied only for first @ (what user/notice what the reply directed,
1283 // we assume first @ is it)
1285 foreach ($mentions as $mention) {
1287 foreach ($mention['mentioned'] as $mentioned) {
1289 // skip if they're already covered
1291 if (!empty($replied[$mentioned->id])) {
1295 // Don't save replies from blocked profile to local user
1297 $mentioned_user = User::getKV('id', $mentioned->id);
1298 if ($mentioned_user instanceof User && $mentioned_user->hasBlocked($sender)) {
1302 $this->saveReply($mentioned->id);
1303 $replied[$mentioned->id] = 1;
1304 self::blow('reply:stream:%d', $mentioned->id);
1308 $recipientIds = array_keys($replied);
1310 return $recipientIds;
1313 function saveReply($profileId)
1315 $reply = new Reply();
1317 $reply->notice_id = $this->id;
1318 $reply->profile_id = $profileId;
1319 $reply->modified = $this->created;
1326 protected $_replies = -1;
1329 * Pull the complete list of @-reply targets for this notice.
1331 * @return array of integer profile ids
1333 function getReplies()
1335 if ($this->_replies != -1) {
1336 return $this->_replies;
1339 $replyMap = Reply::listGet('notice_id', array($this->id));
1343 foreach ($replyMap[$this->id] as $reply) {
1344 $ids[] = $reply->profile_id;
1347 $this->_replies = $ids;
1352 function _setReplies($replies)
1354 $this->_replies = $replies;
1358 * Pull the complete list of @-reply targets for this notice.
1360 * @return array of Profiles
1362 function getReplyProfiles()
1364 $ids = $this->getReplies();
1366 $profiles = Profile::multiGet('id', $ids);
1368 return $profiles->fetchAll();
1372 * Send e-mail notifications to local @-reply targets.
1374 * Replies must already have been saved; this is expected to be run
1375 * from the distrib queue handler.
1377 function sendReplyNotifications()
1379 // Don't send reply notifications for repeats
1381 if (!empty($this->repeat_of)) {
1385 $recipientIds = $this->getReplies();
1387 foreach ($recipientIds as $recipientId) {
1388 $user = User::getKV('id', $recipientId);
1389 if ($user instanceof User) {
1390 mail_notify_attn($user, $this);
1396 * Pull list of groups this notice needs to be delivered to,
1397 * as previously recorded by saveKnownGroups().
1399 * @return array of Group objects
1402 protected $_groups = -1;
1404 function getGroups()
1406 // Don't save groups for repeats
1408 if (!empty($this->repeat_of)) {
1412 if ($this->_groups != -1)
1414 return $this->_groups;
1417 $gis = Group_inbox::listGet('notice_id', array($this->id));
1421 foreach ($gis[$this->id] as $gi)
1423 $ids[] = $gi->group_id;
1426 $groups = User_group::multiGet('id', $ids);
1428 $this->_groups = $groups->fetchAll();
1430 return $this->_groups;
1433 function _setGroups($groups)
1435 $this->_groups = $groups;
1439 * Convert a notice into an activity for export.
1441 * @param User $cur Current user
1443 * @return Activity activity object representing this Notice.
1446 function asActivity($cur=null)
1448 $act = self::cacheGet(Cache::codeKey('notice:as-activity:'.$this->id));
1450 if ($act instanceof Activity) {
1453 $act = new Activity();
1455 if (Event::handle('StartNoticeAsActivity', array($this, &$act))) {
1457 $act->id = $this->uri;
1458 $act->time = strtotime($this->created);
1459 $act->link = $this->bestUrl();
1460 $act->content = common_xml_safe_str($this->rendered);
1462 $profile = $this->getProfile();
1464 $act->actor = ActivityObject::fromProfile($profile);
1465 $act->actor->extra[] = $profile->profileInfo($cur);
1467 $act->verb = $this->verb;
1469 if ($this->repeat_of) {
1470 $repeated = Notice::getKV('id', $this->repeat_of);
1471 if ($repeated instanceof Notice) {
1472 $act->objects[] = $repeated->asActivity($cur);
1475 $act->objects[] = ActivityObject::fromNotice($this);
1478 // XXX: should this be handled by default processing for object entry?
1482 $tags = $this->getTags();
1484 foreach ($tags as $tag) {
1485 $cat = new AtomCategory();
1488 $act->categories[] = $cat;
1492 // XXX: use Atom Media and/or File activity objects instead
1494 $attachments = $this->attachments();
1496 foreach ($attachments as $attachment) {
1497 // Save local attachments
1498 if (!empty($attachment->filename)) {
1499 $act->attachments[] = ActivityObject::fromFile($attachment);
1503 $ctx = new ActivityContext();
1506 $reply = $this->getParent();
1507 $ctx->replyToID = $reply->uri;
1508 $ctx->replyToUrl = $reply->bestUrl();
1509 } catch (Exception $e) {
1510 // This is not a reply to something
1513 $ctx->location = $this->getLocation();
1517 if (!empty($this->conversation)) {
1518 $conv = Conversation::getKV('id', $this->conversation);
1519 if ($conv instanceof Conversation) {
1520 $ctx->conversation = $conv->uri;
1524 $reply_ids = $this->getReplies();
1526 foreach ($reply_ids as $id) {
1527 $rprofile = Profile::getKV('id', $id);
1528 if ($rprofile instanceof Profile) {
1529 $ctx->attention[$rprofile->getUri()] = ActivityObject::PERSON;
1533 $groups = $this->getGroups();
1535 foreach ($groups as $group) {
1536 $ctx->attention[$group->getUri()] = ActivityObject::GROUP;
1539 switch ($this->scope) {
1540 case Notice::PUBLIC_SCOPE:
1541 $ctx->attention[ActivityContext::ATTN_PUBLIC] = ActivityObject::COLLECTION;
1543 case Notice::FOLLOWER_SCOPE:
1544 $surl = common_local_url("subscribers", array('nickname' => $profile->nickname));
1545 $ctx->attention[$surl] = ActivityObject::COLLECTION;
1549 $act->context = $ctx;
1551 $source = $this->getSource();
1553 if ($source instanceof Notice_source) {
1554 $act->generator = ActivityObject::fromNoticeSource($source);
1559 $atom_feed = $profile->getAtomFeed();
1561 if (!empty($atom_feed)) {
1563 $act->source = new ActivitySource();
1565 // XXX: we should store the actual feed ID
1567 $act->source->id = $atom_feed;
1569 // XXX: we should store the actual feed title
1571 $act->source->title = $profile->getBestName();
1573 $act->source->links['alternate'] = $profile->profileurl;
1574 $act->source->links['self'] = $atom_feed;
1576 $act->source->icon = $profile->avatarUrl(AVATAR_PROFILE_SIZE);
1578 $notice = $profile->getCurrentNotice();
1580 if ($notice instanceof Notice) {
1581 $act->source->updated = self::utcDate($notice->created);
1584 $user = User::getKV('id', $profile->id);
1586 if ($user instanceof User) {
1587 $act->source->links['license'] = common_config('license', 'url');
1591 if ($this->isLocal()) {
1592 $act->selfLink = common_local_url('ApiStatusesShow', array('id' => $this->id,
1593 'format' => 'atom'));
1594 $act->editLink = $act->selfLink;
1597 Event::handle('EndNoticeAsActivity', array($this, &$act));
1600 self::cacheSet(Cache::codeKey('notice:as-activity:'.$this->id), $act);
1605 // This has gotten way too long. Needs to be sliced up into functional bits
1606 // or ideally exported to a utility class.
1608 function asAtomEntry($namespace=false,
1613 $act = $this->asActivity($cur);
1614 $act->extra[] = $this->noticeInfo($cur);
1615 return $act->asString($namespace, $author, $source);
1619 * Extra notice info for atom entries
1621 * Clients use some extra notice info in the atom stream.
1622 * This gives it to them.
1624 * @param User $cur Current user
1626 * @return array representation of <statusnet:notice_info> element
1629 function noticeInfo($cur)
1631 // local notice ID (useful to clients for ordering)
1633 $noticeInfoAttr = array('local_id' => $this->id);
1637 $ns = $this->getSource();
1639 if ($ns instanceof Notice_source) {
1640 $noticeInfoAttr['source'] = $ns->code;
1641 if (!empty($ns->url)) {
1642 $noticeInfoAttr['source_link'] = $ns->url;
1643 if (!empty($ns->name)) {
1644 $noticeInfoAttr['source'] = '<a href="'
1645 . htmlspecialchars($ns->url)
1646 . '" rel="nofollow">'
1647 . htmlspecialchars($ns->name)
1653 // favorite and repeated
1656 $cp = $cur->getProfile();
1657 $noticeInfoAttr['favorite'] = ($cp->hasFave($this)) ? "true" : "false";
1658 $noticeInfoAttr['repeated'] = ($cp->hasRepeated($this)) ? "true" : "false";
1661 if (!empty($this->repeat_of)) {
1662 $noticeInfoAttr['repeat_of'] = $this->repeat_of;
1665 return array('statusnet:notice_info', $noticeInfoAttr, null);
1669 * Returns an XML string fragment with a reference to a notice as an
1670 * Activity Streams noun object with the given element type.
1672 * Assumes that 'activity' namespace has been previously defined.
1674 * @param string $element one of 'subject', 'object', 'target'
1678 function asActivityNoun($element)
1680 $noun = ActivityObject::fromNotice($this);
1681 return $noun->asString('activity:' . $element);
1686 if (!empty($this->url)) {
1688 } else if (!empty($this->uri) && preg_match('/^https?:/', $this->uri)) {
1691 return common_local_url('shownotice',
1692 array('notice' => $this->id));
1698 * Determine which notice, if any, a new notice is in reply to.
1700 * For conversation tracking, we try to see where this notice fits
1701 * in the tree. Rough algorithm is:
1703 * if (reply_to is set and valid) {
1705 * } else if ((source not API or Web) and (content starts with "T NAME" or "@name ")) {
1706 * return ID of last notice by initial @name in content;
1709 * Note that all @nickname instances will still be used to save "reply" records,
1710 * so the notice shows up in the mentioned users' "replies" tab.
1712 * @param integer $reply_to ID passed in by Web or API
1713 * @param integer $profile_id ID of author
1714 * @param string $source Source tag, like 'web' or 'gwibber'
1715 * @param string $content Final notice content
1717 * @return integer ID of replied-to notice, or null for not a reply.
1720 static function getReplyTo($reply_to, $profile_id, $source, $content)
1722 static $lb = array('xmpp', 'mail', 'sms', 'omb');
1724 // If $reply_to is specified, we check that it exists, and then
1725 // return it if it does
1727 if (!empty($reply_to)) {
1728 $reply_notice = Notice::getKV('id', $reply_to);
1729 if ($reply_notice instanceof Notice) {
1730 return $reply_notice;
1734 // If it's not a "low bandwidth" source (one where you can't set
1735 // a reply_to argument), we return. This is mostly web and API
1738 if (!in_array($source, $lb)) {
1742 // Is there an initial @ or T?
1744 if (preg_match('/^T ([A-Z0-9]{1,64}) /', $content, $match) ||
1745 preg_match('/^@([a-z0-9]{1,64})\s+/', $content, $match)) {
1746 $nickname = common_canonical_nickname($match[1]);
1751 // Figure out who that is.
1753 $sender = Profile::getKV('id', $profile_id);
1754 if (!$sender instanceof Profile) {
1758 $recipient = common_relative_profile($sender, $nickname, common_sql_now());
1760 if (!$recipient instanceof Profile) {
1764 // Get their last notice
1766 $last = $recipient->getCurrentNotice();
1768 if ($last instanceof Notice) {
1775 static function maxContent()
1777 $contentlimit = common_config('notice', 'contentlimit');
1778 // null => use global limit (distinct from 0!)
1779 if (is_null($contentlimit)) {
1780 $contentlimit = common_config('site', 'textlimit');
1782 return $contentlimit;
1785 static function contentTooLong($content)
1787 $contentlimit = self::maxContent();
1788 return ($contentlimit > 0 && !empty($content) && (mb_strlen($content) > $contentlimit));
1791 function getLocation()
1795 if (!empty($this->location_id) && !empty($this->location_ns)) {
1796 $location = Location::fromId($this->location_id, $this->location_ns);
1799 if (is_null($location)) { // no ID, or Location::fromId() failed
1800 if (!empty($this->lat) && !empty($this->lon)) {
1801 $location = Location::fromLatLon($this->lat, $this->lon);
1809 * Convenience function for posting a repeat of an existing message.
1811 * @param int $repeater_id: profile ID of user doing the repeat
1812 * @param string $source: posting source key, eg 'web', 'api', etc
1815 * @throws Exception on failure or permission problems
1817 function repeat($repeater_id, $source)
1819 $author = Profile::getKV('id', $this->profile_id);
1821 // TRANS: Message used to repeat a notice. RT is the abbreviation of 'retweet'.
1822 // TRANS: %1$s is the repeated user's name, %2$s is the repeated notice.
1823 $content = sprintf(_('RT @%1$s %2$s'),
1827 $maxlen = common_config('site', 'textlimit');
1828 if ($maxlen > 0 && mb_strlen($content) > $maxlen) {
1829 // Web interface and current Twitter API clients will
1830 // pull the original notice's text, but some older
1831 // clients and RSS/Atom feeds will see this trimmed text.
1833 // Unfortunately this is likely to lose tags or URLs
1834 // at the end of long notices.
1835 $content = mb_substr($content, 0, $maxlen - 4) . ' ...';
1838 // Scope is same as this one's
1840 return self::saveNew($repeater_id,
1843 array('repeat_of' => $this->id,
1844 'scope' => $this->scope));
1847 // These are supposed to be in chron order!
1849 function repeatStream($limit=100)
1851 $cache = Cache::instance();
1853 if (empty($cache)) {
1854 $ids = $this->_repeatStreamDirect($limit);
1856 $idstr = $cache->get(Cache::key('notice:repeats:'.$this->id));
1857 if ($idstr !== false) {
1858 if (empty($idstr)) {
1861 $ids = explode(',', $idstr);
1864 $ids = $this->_repeatStreamDirect(100);
1865 $cache->set(Cache::key('notice:repeats:'.$this->id), implode(',', $ids));
1868 // We do a max of 100, so slice down to limit
1869 $ids = array_slice($ids, 0, $limit);
1873 return NoticeStream::getStreamByIds($ids);
1876 function _repeatStreamDirect($limit)
1878 $notice = new Notice();
1880 $notice->selectAdd(); // clears it
1881 $notice->selectAdd('id');
1883 $notice->repeat_of = $this->id;
1885 $notice->orderBy('created, id'); // NB: asc!
1887 if (!is_null($limit)) {
1888 $notice->limit(0, $limit);
1891 return $notice->fetchAll('id');
1894 function locationOptions($lat, $lon, $location_id, $location_ns, $profile = null)
1898 if (!empty($location_id) && !empty($location_ns)) {
1899 $options['location_id'] = $location_id;
1900 $options['location_ns'] = $location_ns;
1902 $location = Location::fromId($location_id, $location_ns);
1904 if ($location instanceof Location) {
1905 $options['lat'] = $location->lat;
1906 $options['lon'] = $location->lon;
1909 } else if (!empty($lat) && !empty($lon)) {
1910 $options['lat'] = $lat;
1911 $options['lon'] = $lon;
1913 $location = Location::fromLatLon($lat, $lon);
1915 if ($location instanceof Location) {
1916 $options['location_id'] = $location->location_id;
1917 $options['location_ns'] = $location->location_ns;
1919 } else if (!empty($profile)) {
1920 if (isset($profile->lat) && isset($profile->lon)) {
1921 $options['lat'] = $profile->lat;
1922 $options['lon'] = $profile->lon;
1925 if (isset($profile->location_id) && isset($profile->location_ns)) {
1926 $options['location_id'] = $profile->location_id;
1927 $options['location_ns'] = $profile->location_ns;
1934 function clearAttentions()
1936 $att = new Attention();
1937 $att->notice_id = $this->getID();
1940 while ($att->fetch()) {
1941 // Can't do delete() on the object directly since it won't remove all of it
1942 $other = clone($att);
1948 function clearReplies()
1950 $replyNotice = new Notice();
1951 $replyNotice->reply_to = $this->id;
1953 //Null any notices that are replies to this notice
1955 if ($replyNotice->find()) {
1956 while ($replyNotice->fetch()) {
1957 $orig = clone($replyNotice);
1958 $replyNotice->reply_to = null;
1959 $replyNotice->update($orig);
1965 $reply = new Reply();
1966 $reply->notice_id = $this->id;
1968 if ($reply->find()) {
1969 while($reply->fetch()) {
1970 self::blow('reply:stream:%d', $reply->profile_id);
1978 function clearFiles()
1980 $f2p = new File_to_post();
1982 $f2p->post_id = $this->id;
1985 while ($f2p->fetch()) {
1989 // FIXME: decide whether to delete File objects
1990 // ...and related (actual) files
1993 function clearRepeats()
1995 $repeatNotice = new Notice();
1996 $repeatNotice->repeat_of = $this->id;
1998 //Null any notices that are repeats of this notice
2000 if ($repeatNotice->find()) {
2001 while ($repeatNotice->fetch()) {
2002 $orig = clone($repeatNotice);
2003 $repeatNotice->repeat_of = null;
2004 $repeatNotice->update($orig);
2009 function clearFaves()
2012 $fave->notice_id = $this->id;
2014 if ($fave->find()) {
2015 while ($fave->fetch()) {
2016 self::blow('fave:ids_by_user_own:%d', $fave->user_id);
2017 self::blow('fave:ids_by_user_own:%d;last', $fave->user_id);
2018 self::blow('fave:ids_by_user:%d', $fave->user_id);
2019 self::blow('fave:ids_by_user:%d;last', $fave->user_id);
2027 function clearTags()
2029 $tag = new Notice_tag();
2030 $tag->notice_id = $this->id;
2033 while ($tag->fetch()) {
2034 self::blow('profile:notice_ids_tagged:%d:%s', $this->profile_id, Cache::keyize($tag->tag));
2035 self::blow('profile:notice_ids_tagged:%d:%s;last', $this->profile_id, Cache::keyize($tag->tag));
2036 self::blow('notice_tag:notice_ids:%s', Cache::keyize($tag->tag));
2037 self::blow('notice_tag:notice_ids:%s;last', Cache::keyize($tag->tag));
2045 function clearGroupInboxes()
2047 $gi = new Group_inbox();
2049 $gi->notice_id = $this->id;
2052 while ($gi->fetch()) {
2053 self::blow('user_group:notice_ids:%d', $gi->group_id);
2061 function distribute()
2063 // We always insert for the author so they don't
2065 Event::handle('StartNoticeDistribute', array($this));
2067 // If there's a failure, we want to _force_
2068 // distribution at this point.
2070 $qm = QueueManager::get();
2071 $qm->enqueue($this, 'distrib');
2072 } catch (Exception $e) {
2073 // If the exception isn't transient, this
2074 // may throw more exceptions as DQH does
2075 // its own enqueueing. So, we ignore them!
2077 $handler = new DistribQueueHandler();
2078 $handler->handle($this);
2079 } catch (Exception $e) {
2080 common_log(LOG_ERR, "emergency redistribution resulted in " . $e->getMessage());
2082 // Re-throw so somebody smarter can handle it.
2089 $result = parent::insert();
2091 if ($result !== false) {
2092 // Profile::hasRepeated() abuses pkeyGet(), so we
2093 // have to clear manually
2094 if (!empty($this->repeat_of)) {
2095 $c = self::memcache();
2097 $ck = self::multicacheKey('Notice',
2098 array('profile_id' => $this->profile_id,
2099 'repeat_of' => $this->repeat_of));
2109 * Get the source of the notice
2111 * @return Notice_source $ns A notice source object. 'code' is the only attribute
2112 * guaranteed to be populated.
2114 function getSource()
2116 $ns = new Notice_source();
2117 if (!empty($this->source)) {
2118 switch ($this->source) {
2125 $ns->code = $this->source;
2128 $ns = Notice_source::getKV($this->source);
2130 $ns = new Notice_source();
2131 $ns->code = $this->source;
2132 $app = Oauth_application::getKV('name', $this->source);
2134 $ns->name = $app->name;
2135 $ns->url = $app->source_url;
2145 * Determine whether the notice was locally created
2147 * @return boolean locality
2150 public function isLocal()
2152 return ($this->is_local == Notice::LOCAL_PUBLIC ||
2153 $this->is_local == Notice::LOCAL_NONPUBLIC);
2157 * Get the list of hash tags saved with this notice.
2159 * @return array of strings
2161 public function getTags()
2165 $keypart = sprintf('notice:tags:%d', $this->id);
2167 $tagstr = self::cacheGet($keypart);
2169 if ($tagstr !== false) {
2170 $tags = explode(',', $tagstr);
2172 $tag = new Notice_tag();
2173 $tag->notice_id = $this->id;
2175 while ($tag->fetch()) {
2176 $tags[] = $tag->tag;
2179 self::cacheSet($keypart, implode(',', $tags));
2185 static private function utcDate($dt)
2187 $dateStr = date('d F Y H:i:s', strtotime($dt));
2188 $d = new DateTime($dateStr, new DateTimeZone('UTC'));
2189 return $d->format(DATE_W3C);
2193 * Look up the creation timestamp for a given notice ID, even
2194 * if it's been deleted.
2197 * @return mixed string recorded creation timestamp, or false if can't be found
2199 public static function getAsTimestamp($id)
2205 $notice = Notice::getKV('id', $id);
2207 return $notice->created;
2210 $deleted = Deleted_notice::getKV('id', $id);
2212 return $deleted->created;
2219 * Build an SQL 'where' fragment for timestamp-based sorting from a since_id
2220 * parameter, matching notices posted after the given one (exclusive).
2222 * If the referenced notice can't be found, will return false.
2225 * @param string $idField
2226 * @param string $createdField
2227 * @return mixed string or false if no match
2229 public static function whereSinceId($id, $idField='id', $createdField='created')
2231 $since = Notice::getAsTimestamp($id);
2233 return sprintf("($createdField = '%s' and $idField > %d) or ($createdField > '%s')", $since, $id, $since);
2239 * Build an SQL 'where' fragment for timestamp-based sorting from a since_id
2240 * parameter, matching notices posted after the given one (exclusive), and
2241 * if necessary add it to the data object's query.
2243 * @param DB_DataObject $obj
2245 * @param string $idField
2246 * @param string $createdField
2247 * @return mixed string or false if no match
2249 public static function addWhereSinceId(DB_DataObject $obj, $id, $idField='id', $createdField='created')
2251 $since = self::whereSinceId($id, $idField, $createdField);
2253 $obj->whereAdd($since);
2258 * Build an SQL 'where' fragment for timestamp-based sorting from a max_id
2259 * parameter, matching notices posted before the given one (inclusive).
2261 * If the referenced notice can't be found, will return false.
2264 * @param string $idField
2265 * @param string $createdField
2266 * @return mixed string or false if no match
2268 public static function whereMaxId($id, $idField='id', $createdField='created')
2270 $max = Notice::getAsTimestamp($id);
2272 return sprintf("($createdField < '%s') or ($createdField = '%s' and $idField <= %d)", $max, $max, $id);
2278 * Build an SQL 'where' fragment for timestamp-based sorting from a max_id
2279 * parameter, matching notices posted before the given one (inclusive), and
2280 * if necessary add it to the data object's query.
2282 * @param DB_DataObject $obj
2284 * @param string $idField
2285 * @param string $createdField
2286 * @return mixed string or false if no match
2288 public static function addWhereMaxId(DB_DataObject $obj, $id, $idField='id', $createdField='created')
2290 $max = self::whereMaxId($id, $idField, $createdField);
2292 $obj->whereAdd($max);
2298 if (common_config('public', 'localonly')) {
2299 return ($this->is_local == Notice::LOCAL_PUBLIC);
2301 return (($this->is_local != Notice::LOCAL_NONPUBLIC) &&
2302 ($this->is_local != Notice::GATEWAY));
2307 * Check that the given profile is allowed to read, respond to, or otherwise
2308 * act on this notice.
2310 * The $scope member is a bitmask of scopes, representing a logical AND of the
2311 * scope requirement. So, 0x03 (Notice::ADDRESSEE_SCOPE | Notice::SITE_SCOPE) means
2312 * "only visible to people who are mentioned in the notice AND are users on this site."
2313 * Users on the site who are not mentioned in the notice will not be able to see the
2316 * @param Profile $profile The profile to check; pass null to check for public/unauthenticated users.
2318 * @return boolean whether the profile is in the notice's scope
2320 function inScope($profile)
2322 if (is_null($profile)) {
2323 $keypart = sprintf('notice:in-scope-for:%d:null', $this->id);
2325 $keypart = sprintf('notice:in-scope-for:%d:%d', $this->id, $profile->id);
2328 $result = self::cacheGet($keypart);
2330 if ($result === false) {
2332 if (Event::handle('StartNoticeInScope', array($this, $profile, &$bResult))) {
2333 $bResult = $this->_inScope($profile);
2334 Event::handle('EndNoticeInScope', array($this, $profile, &$bResult));
2336 $result = ($bResult) ? 1 : 0;
2337 self::cacheSet($keypart, $result, 0, 300);
2340 return ($result == 1) ? true : false;
2343 protected function _inScope($profile)
2345 if (!is_null($this->scope)) {
2346 $scope = $this->scope;
2348 $scope = self::defaultScope();
2351 // If there's no scope, anyone (even anon) is in scope.
2353 if ($scope == 0) { // Not private
2355 return !$this->isHiddenSpam($profile);
2357 } else { // Private, somehow
2359 // If there's scope, anon cannot be in scope
2361 if (empty($profile)) {
2365 // Author is always in scope
2367 if ($this->profile_id == $profile->id) {
2371 // Only for users on this site
2373 if (($scope & Notice::SITE_SCOPE) && !$profile->isLocal()) {
2377 // Only for users mentioned in the notice
2379 if ($scope & Notice::ADDRESSEE_SCOPE) {
2381 $reply = Reply::pkeyGet(array('notice_id' => $this->id,
2382 'profile_id' => $profile->id));
2384 if (!$reply instanceof Reply) {
2389 // Only for members of the given group
2391 if ($scope & Notice::GROUP_SCOPE) {
2393 // XXX: just query for the single membership
2395 $groups = $this->getGroups();
2399 foreach ($groups as $group) {
2400 if ($profile->isMember($group)) {
2411 // Only for followers of the author
2415 if ($scope & Notice::FOLLOWER_SCOPE) {
2418 $author = $this->getProfile();
2419 } catch (Exception $e) {
2423 if (!Subscription::exists($profile, $author)) {
2428 return !$this->isHiddenSpam($profile);
2432 function isHiddenSpam($profile) {
2434 // Hide posts by silenced users from everyone but moderators.
2436 if (common_config('notice', 'hidespam')) {
2439 $author = $this->getProfile();
2440 } catch(Exception $e) {
2441 // If we can't get an author, keep it hidden.
2442 // XXX: technically not spam, but, whatever.
2446 if ($author->hasRole(Profile_role::SILENCED)) {
2447 if (!$profile instanceof Profile || (($profile->id !== $author->id) && (!$profile->hasRight(Right::REVIEWSPAM)))) {
2456 public function getParent()
2458 $parent = Notice::getKV('id', $this->reply_to);
2460 if (!$parent instanceof Notice) {
2461 throw new ServerException('Notice has no parent');
2468 * Magic function called at serialize() time.
2470 * We use this to drop a couple process-specific references
2471 * from DB_DataObject which can cause trouble in future
2474 * @return array of variable names to include in serialization.
2479 $vars = parent::__sleep();
2480 $skip = array('_profile', '_groups', '_attachments', '_faves', '_replies', '_repeats');
2481 return array_diff($vars, $skip);
2484 static function defaultScope()
2486 $scope = common_config('notice', 'defaultscope');
2487 if (is_null($scope)) {
2488 if (common_config('site', 'private')) {
2497 static function fillProfiles($notices)
2499 $map = self::getProfiles($notices);
2501 foreach ($notices as $entry=>$notice) {
2503 if (array_key_exists($notice->profile_id, $map)) {
2504 $notice->_setProfile($map[$notice->profile_id]);
2506 } catch (NoProfileException $e) {
2507 common_log(LOG_WARNING, "Failed to fill profile in Notice with non-existing entry for profile_id: {$e->id}");
2508 unset($notices[$entry]);
2512 return array_values($map);
2515 static function getProfiles(&$notices)
2518 foreach ($notices as $notice) {
2519 $ids[] = $notice->profile_id;
2522 $ids = array_unique($ids);
2524 return Profile::pivotGet('id', $ids);
2527 static function fillGroups(&$notices)
2529 $ids = self::_idsOf($notices);
2531 $gis = Group_inbox::listGet('notice_id', $ids);
2535 foreach ($gis as $id => $gi)
2539 $gids[] = $g->group_id;
2543 $gids = array_unique($gids);
2545 $group = User_group::pivotGet('id', $gids);
2547 foreach ($notices as $notice)
2550 $gi = $gis[$notice->id];
2551 foreach ($gi as $g) {
2552 $grps[] = $group[$g->group_id];
2554 $notice->_setGroups($grps);
2558 static function _idsOf(&$notices)
2561 foreach ($notices as $notice) {
2562 $ids[] = $notice->id;
2564 $ids = array_unique($ids);
2568 static function fillAttachments(&$notices)
2570 $ids = self::_idsOf($notices);
2572 $f2pMap = File_to_post::listGet('post_id', $ids);
2576 foreach ($f2pMap as $noticeId => $f2ps) {
2577 foreach ($f2ps as $f2p) {
2578 $fileIds[] = $f2p->file_id;
2582 $fileIds = array_unique($fileIds);
2584 $fileMap = File::pivotGet('id', $fileIds);
2586 foreach ($notices as $notice)
2589 $f2ps = $f2pMap[$notice->id];
2590 foreach ($f2ps as $f2p) {
2591 $files[] = $fileMap[$f2p->file_id];
2593 $notice->_setAttachments($files);
2600 * All faves of this notice
2602 * @return array Array of Fave objects
2607 if (isset($this->_faves) && is_array($this->_faves)) {
2608 return $this->_faves;
2610 $faveMap = Fave::listGet('notice_id', array($this->id));
2611 $this->_faves = $faveMap[$this->id];
2612 return $this->_faves;
2615 function _setFaves($faves)
2617 $this->_faves = $faves;
2620 static function fillFaves(&$notices)
2622 $ids = self::_idsOf($notices);
2623 $faveMap = Fave::listGet('notice_id', $ids);
2626 foreach ($faveMap as $id => $faves) {
2627 $cnt += count($faves);
2628 if (count($faves) > 0) {
2632 foreach ($notices as $notice) {
2633 $faves = $faveMap[$notice->id];
2634 $notice->_setFaves($faves);
2638 static function fillReplies(&$notices)
2640 $ids = self::_idsOf($notices);
2641 $replyMap = Reply::listGet('notice_id', $ids);
2642 foreach ($notices as $notice) {
2643 $replies = $replyMap[$notice->id];
2645 foreach ($replies as $reply) {
2646 $ids[] = $reply->profile_id;
2648 $notice->_setReplies($ids);
2652 protected $_repeats;
2654 function getRepeats()
2656 if (isset($this->_repeats) && is_array($this->_repeats)) {
2657 return $this->_repeats;
2659 $repeatMap = Notice::listGet('repeat_of', array($this->id));
2660 $this->_repeats = $repeatMap[$this->id];
2661 return $this->_repeats;
2664 function _setRepeats($repeats)
2666 $this->_repeats = $repeats;
2669 static function fillRepeats(&$notices)
2671 $ids = self::_idsOf($notices);
2672 $repeatMap = Notice::listGet('repeat_of', $ids);
2673 foreach ($notices as $notice) {
2674 $repeats = $repeatMap[$notice->id];
2675 $notice->_setRepeats($repeats);