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 return $this->url ?: $this->uri;
219 public function get_object_type($canonical=false) {
221 ? ActivityObject::canonicalType($this->object_type)
222 : $this->object_type;
225 public static function getByUri($uri)
227 $notice = new Notice();
229 if (!$notice->find(true)) {
230 throw new NoResultException($notice);
236 * Extract #hashtags from this notice's content and save them to the database.
240 /* extract all #hastags */
241 $count = preg_match_all('/(?:^|\s)#([\pL\pN_\-\.]{1,64})/u', strtolower($this->content), $match);
246 /* Add them to the database */
247 return $this->saveKnownTags($match[1]);
251 * Record the given set of hash tags in the db for this notice.
252 * Given tag strings will be normalized and checked for dupes.
254 function saveKnownTags($hashtags)
256 //turn each into their canonical tag
257 //this is needed to remove dupes before saving e.g. #hash.tag = #hashtag
258 for($i=0; $i<count($hashtags); $i++) {
259 /* elide characters we don't want in the tag */
260 $hashtags[$i] = common_canonical_tag($hashtags[$i]);
263 foreach(array_unique($hashtags) as $hashtag) {
264 $this->saveTag($hashtag);
265 self::blow('profile:notice_ids_tagged:%d:%s', $this->profile_id, $hashtag);
271 * Record a single hash tag as associated with this notice.
272 * Tag format and uniqueness must be validated by caller.
274 function saveTag($hashtag)
276 $tag = new Notice_tag();
277 $tag->notice_id = $this->id;
278 $tag->tag = $hashtag;
279 $tag->created = $this->created;
280 $id = $tag->insert();
283 // TRANS: Server exception. %s are the error details.
284 throw new ServerException(sprintf(_('Database error inserting hashtag: %s.'),
285 $last_error->message));
289 // if it's saved, blow its cache
290 $tag->blowCache(false);
294 * Save a new notice and push it out to subscribers' inboxes.
295 * Poster's permissions are checked before sending.
297 * @param int $profile_id Profile ID of the poster
298 * @param string $content source message text; links may be shortened
299 * per current user's preference
300 * @param string $source source key ('web', 'api', etc)
301 * @param array $options Associative array of optional properties:
302 * string 'created' timestamp of notice; defaults to now
303 * int 'is_local' source/gateway ID, one of:
304 * Notice::LOCAL_PUBLIC - Local, ok to appear in public timeline
305 * Notice::REMOTE - Sent from a remote service;
306 * hide from public timeline but show in
307 * local "and friends" timelines
308 * Notice::LOCAL_NONPUBLIC - Local, but hide from public timeline
309 * Notice::GATEWAY - From another non-OStatus service;
310 * will not appear in public views
311 * float 'lat' decimal latitude for geolocation
312 * float 'lon' decimal longitude for geolocation
313 * int 'location_id' geoname identifier
314 * int 'location_ns' geoname namespace to interpret location_id
315 * int 'reply_to'; notice ID this is a reply to
316 * int 'repeat_of'; notice ID this is a repeat of
317 * string 'uri' unique ID for notice; a unique tag uri (can be url or anything too)
318 * string 'url' permalink to notice; defaults to local notice URL
319 * string 'rendered' rendered HTML version of content
320 * array 'replies' list of profile URIs for reply delivery in
321 * place of extracting @-replies from content.
322 * array 'groups' list of group IDs to deliver to, in place of
323 * extracting ! tags from content
324 * array 'tags' list of hashtag strings to save with the notice
325 * in place of extracting # tags from content
326 * array 'urls' list of attached/referred URLs to save with the
327 * notice in place of extracting links from content
328 * boolean 'distribute' whether to distribute the notice, default true
329 * string 'object_type' URL of the associated object type (default ActivityObject::NOTE)
330 * string 'verb' URL of the associated verb (default ActivityVerb::POST)
331 * int 'scope' Scope bitmask; default to SITE_SCOPE on private sites, 0 otherwise
333 * @fixme tag override
336 * @throws ClientException
338 static function saveNew($profile_id, $content, $source, array $options=null) {
339 $defaults = array('uri' => null,
344 'distribute' => true,
345 'object_type' => null,
348 if (!empty($options) && is_array($options)) {
349 $options = array_merge($defaults, $options);
355 if (!isset($is_local)) {
356 $is_local = Notice::LOCAL_PUBLIC;
359 $profile = Profile::getKV('id', $profile_id);
360 if (!$profile instanceof Profile) {
361 // TRANS: Client exception thrown when trying to save a notice for an unknown user.
362 throw new ClientException(_('Problem saving notice. Unknown user.'));
365 $user = User::getKV('id', $profile_id);
366 if ($user instanceof User) {
367 // Use the local user's shortening preferences, if applicable.
368 $final = $user->shortenLinks($content);
370 $final = common_shorten_links($content);
373 if (Notice::contentTooLong($final)) {
374 // TRANS: Client exception thrown if a notice contains too many characters.
375 throw new ClientException(_('Problem saving notice. Too long.'));
378 if (common_config('throttle', 'enabled') && !Notice::checkEditThrottle($profile_id)) {
379 common_log(LOG_WARNING, 'Excessive posting by profile #' . $profile_id . '; throttled.');
380 // TRANS: Client exception thrown when a user tries to post too many notices in a given time frame.
381 throw new ClientException(_('Too many notices too fast; take a breather '.
382 'and post again in a few minutes.'));
385 if (common_config('site', 'dupelimit') > 0 && !Notice::checkDupes($profile_id, $final)) {
386 common_log(LOG_WARNING, 'Dupe posting by profile #' . $profile_id . '; throttled.');
387 // TRANS: Client exception thrown when a user tries to post too many duplicate notices in a given time frame.
388 throw new ClientException(_('Too many duplicate messages too quickly;'.
389 ' take a breather and post again in a few minutes.'));
392 if (!$profile->hasRight(Right::NEWNOTICE)) {
393 common_log(LOG_WARNING, "Attempted post from user disallowed to post: " . $profile->nickname);
395 // TRANS: Client exception thrown when a user tries to post while being banned.
396 throw new ClientException(_('You are banned from posting notices on this site.'), 403);
399 $notice = new Notice();
400 $notice->profile_id = $profile_id;
402 $autosource = common_config('public', 'autosource');
404 // Sandboxed are non-false, but not 1, either
406 if (!$profile->hasRight(Right::PUBLICNOTICE) ||
407 ($source && $autosource && in_array($source, $autosource))) {
408 $notice->is_local = Notice::LOCAL_NONPUBLIC;
410 $notice->is_local = $is_local;
413 if (!empty($created)) {
414 $notice->created = $created;
416 $notice->created = common_sql_now();
419 $notice->content = $final;
421 $notice->source = $source;
425 // Get the groups here so we can figure out replies and such
426 if (!isset($groups)) {
427 $groups = User_group::idsFromText($notice->content, $profile);
432 // Handle repeat case
434 if (isset($repeat_of)) {
436 // Check for a private one
438 $repeat = Notice::getKV('id', $repeat_of);
440 if (!($repeat instanceof Notice)) {
441 // TRANS: Client exception thrown in notice when trying to repeat a missing or deleted notice.
442 throw new ClientException(_('Cannot repeat; original notice is missing or deleted.'));
445 if ($profile->id == $repeat->profile_id) {
446 // TRANS: Client error displayed when trying to repeat an own notice.
447 throw new ClientException(_('You cannot repeat your own notice.'));
450 if ($repeat->scope != Notice::SITE_SCOPE &&
451 $repeat->scope != Notice::PUBLIC_SCOPE) {
452 // TRANS: Client error displayed when trying to repeat a non-public notice.
453 throw new ClientException(_('Cannot repeat a private notice.'), 403);
456 if (!$repeat->inScope($profile)) {
457 // The generic checks above should cover this, but let's be sure!
458 // TRANS: Client error displayed when trying to repeat a notice you cannot access.
459 throw new ClientException(_('Cannot repeat a notice you cannot read.'), 403);
462 if ($profile->hasRepeated($repeat)) {
463 // TRANS: Client error displayed when trying to repeat an already repeated notice.
464 throw new ClientException(_('You already repeated that notice.'));
467 $notice->repeat_of = $repeat_of;
469 $reply = self::getReplyTo($reply_to, $profile_id, $source, $final);
471 if (!empty($reply)) {
473 if (!$reply->inScope($profile)) {
474 // TRANS: Client error displayed when trying to reply to a notice a the target has no access to.
475 // TRANS: %1$s is a user nickname, %2$d is a notice ID (number).
476 throw new ClientException(sprintf(_('%1$s has no access to notice %2$d.'),
477 $profile->nickname, $reply->id), 403);
480 $notice->reply_to = $reply->id;
481 $notice->conversation = $reply->conversation;
483 // If the original is private to a group, and notice has no group specified,
484 // make it to the same group(s)
486 if (empty($groups) && ($reply->scope & Notice::GROUP_SCOPE)) {
488 $replyGroups = $reply->getGroups();
489 foreach ($replyGroups as $group) {
490 if ($profile->isMember($group)) {
491 $groups[] = $group->id;
500 if (!empty($lat) && !empty($lon)) {
505 if (!empty($location_ns) && !empty($location_id)) {
506 $notice->location_id = $location_id;
507 $notice->location_ns = $location_ns;
510 if (!empty($rendered)) {
511 $notice->rendered = $rendered;
513 $notice->rendered = common_render_content($final, $notice);
517 if (!empty($notice->repeat_of)) {
518 $notice->verb = ActivityVerb::SHARE;
519 $notice->object_type = ActivityObject::ACTIVITY;
521 $notice->verb = ActivityVerb::POST;
524 $notice->verb = $verb;
527 if (empty($object_type)) {
528 $notice->object_type = (empty($notice->reply_to)) ? ActivityObject::NOTE : ActivityObject::COMMENT;
530 $notice->object_type = $object_type;
533 if (is_null($scope)) { // 0 is a valid value
534 if (!empty($reply)) {
535 $notice->scope = $reply->scope;
537 $notice->scope = self::defaultScope();
540 $notice->scope = $scope;
543 // For private streams
546 $user = $profile->getUser();
548 if ($user->private_stream &&
549 ($notice->scope == Notice::PUBLIC_SCOPE ||
550 $notice->scope == Notice::SITE_SCOPE)) {
551 $notice->scope |= Notice::FOLLOWER_SCOPE;
553 } catch (NoSuchUserException $e) {
554 // Cannot handle private streams for remote profiles
557 // Force the scope for private groups
559 foreach ($groups as $groupId) {
560 $group = User_group::getKV('id', $groupId);
561 if ($group instanceof User_group) {
562 if ($group->force_scope) {
563 $notice->scope |= Notice::GROUP_SCOPE;
569 if (Event::handle('StartNoticeSave', array(&$notice))) {
571 // XXX: some of these functions write to the DB
573 $id = $notice->insert();
576 common_log_db_error($notice, 'INSERT', __FILE__);
577 // TRANS: Server exception thrown when a notice cannot be saved.
578 throw new ServerException(_('Problem saving notice.'));
581 // Update ID-dependent columns: URI, conversation
583 $orig = clone($notice);
588 $notice->uri = sprintf('%s:%s=%d:%s=%s',
590 'noticeId', $notice->id,
591 'objectType', $notice->get_object_type(true));
595 // If it's not part of a conversation, it's
596 // the beginning of a new conversation.
598 if (empty($notice->conversation)) {
599 $conv = Conversation::create($notice);
600 $notice->conversation = $conv->id;
605 if ($notice->update($orig) === false) {
606 common_log_db_error($notice, 'UPDATE', __FILE__);
607 // TRANS: Server exception thrown when a notice cannot be updated.
608 throw new ServerException(_('Problem saving notice.'));
614 // Clear the cache for subscribed users, so they'll update at next request
615 // XXX: someone clever could prepend instead of clearing the cache
617 $notice->blowOnInsert();
619 // Save per-notice metadata...
621 if (isset($replies)) {
622 $notice->saveKnownReplies($replies);
624 $notice->saveReplies();
628 $notice->saveKnownTags($tags);
633 // Note: groups may save tags, so must be run after tags are saved
634 // to avoid errors on duplicates.
635 // Note: groups should always be set.
637 $notice->saveKnownGroups($groups);
640 $notice->saveKnownUrls($urls);
646 // Prepare inbox delivery, may be queued to background.
647 $notice->distribute();
653 function blowOnInsert($conversation = false)
655 $this->blowStream('profile:notice_ids:%d', $this->profile_id);
657 if ($this->isPublic()) {
658 $this->blowStream('public');
661 self::blow('notice:list-ids:conversation:%s', $this->conversation);
662 self::blow('conversation:notice_count:%d', $this->conversation);
664 if (!empty($this->repeat_of)) {
665 // XXX: we should probably only use one of these
666 $this->blowStream('notice:repeats:%d', $this->repeat_of);
667 self::blow('notice:list-ids:repeat_of:%d', $this->repeat_of);
670 $original = Notice::getKV('id', $this->repeat_of);
672 if ($original instanceof Notice) {
673 $originalUser = User::getKV('id', $original->profile_id);
674 if ($originalUser instanceof User) {
675 $this->blowStream('user:repeats_of_me:%d', $originalUser->id);
679 $profile = Profile::getKV($this->profile_id);
681 if ($profile instanceof Profile) {
682 $profile->blowNoticeCount();
685 $ptags = $this->getProfileTags();
686 foreach ($ptags as $ptag) {
687 $ptag->blowNoticeStreamCache();
692 * Clear cache entries related to this notice at delete time.
693 * Necessary to avoid breaking paging on public, profile timelines.
695 function blowOnDelete()
697 $this->blowOnInsert();
699 self::blow('profile:notice_ids:%d;last', $this->profile_id);
701 if ($this->isPublic()) {
702 self::blow('public;last');
705 self::blow('fave:by_notice', $this->id);
707 if ($this->conversation) {
708 // In case we're the first, will need to calc a new root.
709 self::blow('notice:conversation_root:%d', $this->conversation);
712 $ptags = $this->getProfileTags();
713 foreach ($ptags as $ptag) {
714 $ptag->blowNoticeStreamCache(true);
718 function blowStream()
720 $c = self::memcache();
726 $args = func_get_args();
728 $format = array_shift($args);
730 $keyPart = vsprintf($format, $args);
732 $cacheKey = Cache::key($keyPart);
734 $c->delete($cacheKey);
736 // delete the "last" stream, too, if this notice is
737 // older than the top of that stream
739 $lastKey = $cacheKey.';last';
741 $lastStr = $c->get($lastKey);
743 if ($lastStr !== false) {
744 $window = explode(',', $lastStr);
745 $lastID = $window[0];
746 $lastNotice = Notice::getKV('id', $lastID);
747 if (!$lastNotice instanceof Notice // just weird
748 || strtotime($lastNotice->created) >= strtotime($this->created)) {
749 $c->delete($lastKey);
754 /** save all urls in the notice to the db
756 * follow redirects and save all available file information
757 * (mimetype, date, size, oembed, etc.)
761 function saveUrls() {
762 if (common_config('attachments', 'process_links')) {
763 common_replace_urls_callback($this->content, array($this, 'saveUrl'), $this->id);
768 * Save the given URLs as related links/attachments to the db
770 * follow redirects and save all available file information
771 * (mimetype, date, size, oembed, etc.)
775 function saveKnownUrls($urls)
777 if (common_config('attachments', 'process_links')) {
778 // @fixme validation?
779 foreach (array_unique($urls) as $url) {
780 File::processNew($url, $this->id);
788 function saveUrl($url, $notice_id) {
789 File::processNew($url, $notice_id);
792 static function checkDupes($profile_id, $content) {
793 $profile = Profile::getKV($profile_id);
794 if (!$profile instanceof Profile) {
797 $notice = $profile->getNotices(0, CachingNoticeStream::CACHE_WINDOW);
798 if (!empty($notice)) {
800 while ($notice->fetch()) {
801 if (time() - strtotime($notice->created) >= common_config('site', 'dupelimit')) {
803 } else if ($notice->content == $content) {
808 // If we get here, oldest item in cache window is not
809 // old enough for dupe limit; do direct check against DB
810 $notice = new Notice();
811 $notice->profile_id = $profile_id;
812 $notice->content = $content;
813 $threshold = common_sql_date(time() - common_config('site', 'dupelimit'));
814 $notice->whereAdd(sprintf("created > '%s'", $notice->escape($threshold)));
816 $cnt = $notice->count();
820 static function checkEditThrottle($profile_id) {
821 $profile = Profile::getKV($profile_id);
822 if (!$profile instanceof Profile) {
825 // Get the Nth notice
826 $notice = $profile->getNotices(common_config('throttle', 'count') - 1, 1);
827 if ($notice && $notice->fetch()) {
828 // If the Nth notice was posted less than timespan seconds ago
829 if (time() - strtotime($notice->created) <= common_config('throttle', 'timespan')) {
834 // Either not N notices in the stream, OR the Nth was not posted within timespan seconds
838 protected $_attachments = -1;
840 function attachments() {
842 if ($this->_attachments != -1) {
843 return $this->_attachments;
846 $f2ps = File_to_post::listGet('post_id', array($this->id));
850 foreach ($f2ps[$this->id] as $f2p) {
851 $ids[] = $f2p->file_id;
854 $files = File::multiGet('id', $ids);
856 $this->_attachments = $files->fetchAll();
858 return $this->_attachments;
861 function _setAttachments($attachments)
863 $this->_attachments = $attachments;
866 function publicStream($offset=0, $limit=20, $since_id=0, $max_id=0)
868 $stream = new PublicNoticeStream();
869 return $stream->getNotices($offset, $limit, $since_id, $max_id);
873 function conversationStream($id, $offset=0, $limit=20, $since_id=0, $max_id=0)
875 $stream = new ConversationNoticeStream($id);
877 return $stream->getNotices($offset, $limit, $since_id, $max_id);
881 * Is this notice part of an active conversation?
883 * @return boolean true if other messages exist in the same
884 * conversation, false if this is the only one
886 function hasConversation()
888 if (!empty($this->conversation)) {
889 $conversation = Notice::conversationStream(
895 if ($conversation->N > 0) {
903 * Grab the earliest notice from this conversation.
905 * @return Notice or null
907 function conversationRoot($profile=-1)
909 // XXX: can this happen?
911 if (empty($this->conversation)) {
915 // Get the current profile if not specified
917 if (is_int($profile) && $profile == -1) {
918 $profile = Profile::current();
921 // If this notice is out of scope, no root for you!
923 if (!$this->inScope($profile)) {
927 // If this isn't a reply to anything, then it's its own
930 if (empty($this->reply_to)) {
934 if (is_null($profile)) {
935 $keypart = sprintf('notice:conversation_root:%d:null', $this->id);
937 $keypart = sprintf('notice:conversation_root:%d:%d',
942 $root = self::cacheGet($keypart);
944 if ($root !== false && $root->inScope($profile)) {
951 $parent = $last->getParent();
952 if ($parent->inScope($profile)) {
956 } catch (Exception $e) {
957 // Latest notice has no parent
959 // No parent, or parent out of scope
964 self::cacheSet($keypart, $root);
970 * Pull up a full list of local recipients who will be getting
971 * this notice in their inbox. Results will be cached, so don't
972 * change the input data wily-nilly!
974 * @param array $groups optional list of Group objects;
975 * if left empty, will be loaded from group_inbox records
976 * @param array $recipient optional list of reply profile ids
977 * if left empty, will be loaded from reply records
978 * @return array associating recipient user IDs with an inbox source constant
980 function whoGets(array $groups=null, array $recipients=null)
982 $c = self::memcache();
985 $ni = $c->get(Cache::key('notice:who_gets:'.$this->id));
991 if (is_null($recipients)) {
992 $recipients = $this->getReplies();
997 // Give plugins a chance to add folks in at start...
998 if (Event::handle('StartNoticeWhoGets', array($this, &$ni))) {
1000 $users = $this->getSubscribedUsers();
1001 foreach ($users as $id) {
1002 $ni[$id] = NOTICE_INBOX_SOURCE_SUB;
1005 if (is_null($groups)) {
1006 $groups = $this->getGroups();
1008 foreach ($groups as $group) {
1009 $users = $group->getUserMembers();
1010 foreach ($users as $id) {
1011 if (!array_key_exists($id, $ni)) {
1012 $ni[$id] = NOTICE_INBOX_SOURCE_GROUP;
1017 $ptAtts = $this->getAttentionsFromProfileTags();
1018 foreach ($ptAtts as $key=>$val) {
1019 if (!array_key_exists($key, $ni)) {
1024 foreach ($recipients as $recipient) {
1025 if (!array_key_exists($recipient, $ni)) {
1026 $ni[$recipient] = NOTICE_INBOX_SOURCE_REPLY;
1030 // Exclude any deleted, non-local, or blocking recipients.
1031 $profile = $this->getProfile();
1032 $originalProfile = null;
1033 if ($this->repeat_of) {
1034 // Check blocks against the original notice's poster as well.
1035 $original = Notice::getKV('id', $this->repeat_of);
1036 if ($original instanceof Notice) {
1037 $originalProfile = $original->getProfile();
1041 foreach ($ni as $id => $source) {
1043 $user = User::getKV('id', $id);
1044 if (!$user instanceof User ||
1045 $user->hasBlocked($profile) ||
1046 ($originalProfile && $user->hasBlocked($originalProfile))) {
1049 } catch (UserNoProfileException $e) {
1050 // User doesn't have a profile; invalid; skip them.
1055 // Give plugins a chance to filter out...
1056 Event::handle('EndNoticeWhoGets', array($this, &$ni));
1060 // XXX: pack this data better
1061 $c->set(Cache::key('notice:who_gets:'.$this->id), $ni);
1067 function getSubscribedUsers()
1071 if(common_config('db','quote_identifiers'))
1072 $user_table = '"user"';
1073 else $user_table = 'user';
1077 'FROM '. $user_table .' JOIN subscription '.
1078 'ON '. $user_table .'.id = subscription.subscriber ' .
1079 'WHERE subscription.subscribed = %d ';
1081 $user->query(sprintf($qry, $this->profile_id));
1085 while ($user->fetch()) {
1094 function getProfileTags()
1096 $profile = $this->getProfile();
1097 $list = $profile->getOtherTags($profile);
1100 while($list->fetch()) {
1101 $ptags[] = clone($list);
1107 public function getAttentionsFromProfileTags()
1110 $ptags = $this->getProfileTags();
1111 foreach ($ptags as $ptag) {
1112 $users = $ptag->getUserSubscribers();
1113 foreach ($users as $id) {
1114 $ni[$id] = NOTICE_INBOX_SOURCE_PROFILE_TAG;
1121 * Record this notice to the given group inboxes for delivery.
1122 * Overrides the regular parsing of !group markup.
1124 * @param string $group_ids
1125 * @fixme might prefer URIs as identifiers, as for replies?
1126 * best with generalizations on user_group to support
1127 * remote groups better.
1129 function saveKnownGroups($group_ids)
1131 if (!is_array($group_ids)) {
1132 // TRANS: Server exception thrown when no array is provided to the method saveKnownGroups().
1133 throw new ServerException(_('Bad type provided to saveKnownGroups.'));
1137 foreach (array_unique($group_ids) as $id) {
1138 $group = User_group::getKV('id', $id);
1139 if ($group instanceof User_group) {
1140 common_log(LOG_ERR, "Local delivery to group id $id, $group->nickname");
1141 $result = $this->addToGroupInbox($group);
1143 common_log_db_error($gi, 'INSERT', __FILE__);
1146 if (common_config('group', 'addtag')) {
1147 // we automatically add a tag for every group name, too
1149 $tag = Notice_tag::pkeyGet(array('tag' => common_canonical_tag($group->nickname),
1150 'notice_id' => $this->id));
1152 if (is_null($tag)) {
1153 $this->saveTag($group->nickname);
1157 $groups[] = clone($group);
1159 common_log(LOG_ERR, "Local delivery to group id $id skipped, doesn't exist");
1166 function addToGroupInbox(User_group $group)
1168 $gi = Group_inbox::pkeyGet(array('group_id' => $group->id,
1169 'notice_id' => $this->id));
1171 if (!$gi instanceof Group_inbox) {
1173 $gi = new Group_inbox();
1175 $gi->group_id = $group->id;
1176 $gi->notice_id = $this->id;
1177 $gi->created = $this->created;
1179 $result = $gi->insert();
1182 common_log_db_error($gi, 'INSERT', __FILE__);
1183 // TRANS: Server exception thrown when an update for a group inbox fails.
1184 throw new ServerException(_('Problem saving group inbox.'));
1187 self::blow('user_group:notice_ids:%d', $gi->group_id);
1194 * Save reply records indicating that this notice needs to be
1195 * delivered to the local users with the given URIs.
1197 * Since this is expected to be used when saving foreign-sourced
1198 * messages, we won't deliver to any remote targets as that's the
1199 * source service's responsibility.
1201 * Mail notifications etc will be handled later.
1203 * @param array $uris Array of unique identifier URIs for recipients
1205 function saveKnownReplies(array $uris)
1211 $sender = Profile::getKV($this->profile_id);
1213 foreach (array_unique($uris) as $uri) {
1215 $profile = Profile::fromURI($uri);
1217 if (!$profile instanceof Profile) {
1218 common_log(LOG_WARNING, "Unable to determine profile for URI '$uri'");
1222 if ($profile->hasBlocked($sender)) {
1223 common_log(LOG_INFO, "Not saving reply to profile {$profile->id} ($uri) from sender {$sender->id} because of a block.");
1227 $this->saveReply($profile->id);
1228 self::blow('reply:stream:%d', $profile->id);
1235 * Pull @-replies from this message's content in StatusNet markup format
1236 * and save reply records indicating that this message needs to be
1237 * delivered to those users.
1239 * Mail notifications to local profiles will be sent later.
1241 * @return array of integer profile IDs
1244 function saveReplies()
1246 // Don't save reply data for repeats
1248 if (!empty($this->repeat_of)) {
1252 $sender = Profile::getKV($this->profile_id);
1256 // If it's a reply, save for the replied-to author
1258 $parent = $this->getParent();
1259 $author = $parent->getProfile();
1260 if ($author instanceof Profile) {
1261 $this->saveReply($author->id);
1262 $replied[$author->id] = 1;
1263 self::blow('reply:stream:%d', $author->id);
1265 } catch (Exception $e) {
1266 // Not a reply, since it has no parent!
1269 // @todo ideally this parser information would only
1270 // be calculated once.
1272 $mentions = common_find_mentions($this->content, $this);
1274 // store replied only for first @ (what user/notice what the reply directed,
1275 // we assume first @ is it)
1277 foreach ($mentions as $mention) {
1279 foreach ($mention['mentioned'] as $mentioned) {
1281 // skip if they're already covered
1283 if (!empty($replied[$mentioned->id])) {
1287 // Don't save replies from blocked profile to local user
1289 $mentioned_user = User::getKV('id', $mentioned->id);
1290 if ($mentioned_user instanceof User && $mentioned_user->hasBlocked($sender)) {
1294 $this->saveReply($mentioned->id);
1295 $replied[$mentioned->id] = 1;
1296 self::blow('reply:stream:%d', $mentioned->id);
1300 $recipientIds = array_keys($replied);
1302 return $recipientIds;
1305 function saveReply($profileId)
1307 $reply = new Reply();
1309 $reply->notice_id = $this->id;
1310 $reply->profile_id = $profileId;
1311 $reply->modified = $this->created;
1318 protected $_replies = -1;
1321 * Pull the complete list of @-reply targets for this notice.
1323 * @return array of integer profile ids
1325 function getReplies()
1327 if ($this->_replies != -1) {
1328 return $this->_replies;
1331 $replyMap = Reply::listGet('notice_id', array($this->id));
1335 foreach ($replyMap[$this->id] as $reply) {
1336 $ids[] = $reply->profile_id;
1339 $this->_replies = $ids;
1344 function _setReplies($replies)
1346 $this->_replies = $replies;
1350 * Pull the complete list of @-reply targets for this notice.
1352 * @return array of Profiles
1354 function getReplyProfiles()
1356 $ids = $this->getReplies();
1358 $profiles = Profile::multiGet('id', $ids);
1360 return $profiles->fetchAll();
1364 * Send e-mail notifications to local @-reply targets.
1366 * Replies must already have been saved; this is expected to be run
1367 * from the distrib queue handler.
1369 function sendReplyNotifications()
1371 // Don't send reply notifications for repeats
1373 if (!empty($this->repeat_of)) {
1377 $recipientIds = $this->getReplies();
1379 foreach ($recipientIds as $recipientId) {
1380 $user = User::getKV('id', $recipientId);
1381 if ($user instanceof User) {
1382 mail_notify_attn($user, $this);
1388 * Pull list of groups this notice needs to be delivered to,
1389 * as previously recorded by saveKnownGroups().
1391 * @return array of Group objects
1394 protected $_groups = -1;
1396 function getGroups()
1398 // Don't save groups for repeats
1400 if (!empty($this->repeat_of)) {
1404 if ($this->_groups != -1)
1406 return $this->_groups;
1409 $gis = Group_inbox::listGet('notice_id', array($this->id));
1413 foreach ($gis[$this->id] as $gi)
1415 $ids[] = $gi->group_id;
1418 $groups = User_group::multiGet('id', $ids);
1420 $this->_groups = $groups->fetchAll();
1422 return $this->_groups;
1425 function _setGroups($groups)
1427 $this->_groups = $groups;
1431 * Convert a notice into an activity for export.
1433 * @param User $cur Current user
1435 * @return Activity activity object representing this Notice.
1438 function asActivity($cur=null)
1440 $act = self::cacheGet(Cache::codeKey('notice:as-activity:'.$this->id));
1442 if ($act instanceof Activity) {
1445 $act = new Activity();
1447 if (Event::handle('StartNoticeAsActivity', array($this, &$act))) {
1449 $act->id = $this->uri;
1450 $act->time = strtotime($this->created);
1451 $act->link = $this->bestUrl();
1452 $act->content = common_xml_safe_str($this->rendered);
1454 $profile = $this->getProfile();
1456 $act->actor = ActivityObject::fromProfile($profile);
1457 $act->actor->extra[] = $profile->profileInfo($cur);
1459 $act->verb = $this->verb;
1461 if ($this->repeat_of) {
1462 $repeated = Notice::getKV('id', $this->repeat_of);
1463 if ($repeated instanceof Notice) {
1464 $act->objects[] = $repeated->asActivity($cur);
1467 $act->objects[] = ActivityObject::fromNotice($this);
1470 // XXX: should this be handled by default processing for object entry?
1474 $tags = $this->getTags();
1476 foreach ($tags as $tag) {
1477 $cat = new AtomCategory();
1480 $act->categories[] = $cat;
1484 // XXX: use Atom Media and/or File activity objects instead
1486 $attachments = $this->attachments();
1488 foreach ($attachments as $attachment) {
1489 // Save local attachments
1490 if (!empty($attachment->filename)) {
1491 $act->attachments[] = ActivityObject::fromFile($attachment);
1495 $ctx = new ActivityContext();
1498 $reply = $this->getParent();
1499 $ctx->replyToID = $reply->uri;
1500 $ctx->replyToUrl = $reply->bestUrl();
1501 } catch (Exception $e) {
1502 // This is not a reply to something
1505 $ctx->location = $this->getLocation();
1509 if (!empty($this->conversation)) {
1510 $conv = Conversation::getKV('id', $this->conversation);
1511 if ($conv instanceof Conversation) {
1512 $ctx->conversation = $conv->uri;
1516 $reply_ids = $this->getReplies();
1518 foreach ($reply_ids as $id) {
1519 $rprofile = Profile::getKV('id', $id);
1520 if ($rprofile instanceof Profile) {
1521 $ctx->attention[$rprofile->getUri()] = ActivityObject::PERSON;
1525 $groups = $this->getGroups();
1527 foreach ($groups as $group) {
1528 $ctx->attention[$group->getUri()] = ActivityObject::GROUP;
1531 switch ($this->scope) {
1532 case Notice::PUBLIC_SCOPE:
1533 $ctx->attention[ActivityContext::ATTN_PUBLIC] = ActivityObject::COLLECTION;
1535 case Notice::FOLLOWER_SCOPE:
1536 $surl = common_local_url("subscribers", array('nickname' => $profile->nickname));
1537 $ctx->attention[$surl] = ActivityObject::COLLECTION;
1541 $act->context = $ctx;
1543 $source = $this->getSource();
1545 if ($source instanceof Notice_source) {
1546 $act->generator = ActivityObject::fromNoticeSource($source);
1551 $atom_feed = $profile->getAtomFeed();
1553 if (!empty($atom_feed)) {
1555 $act->source = new ActivitySource();
1557 // XXX: we should store the actual feed ID
1559 $act->source->id = $atom_feed;
1561 // XXX: we should store the actual feed title
1563 $act->source->title = $profile->getBestName();
1565 $act->source->links['alternate'] = $profile->profileurl;
1566 $act->source->links['self'] = $atom_feed;
1568 $act->source->icon = $profile->avatarUrl(AVATAR_PROFILE_SIZE);
1570 $notice = $profile->getCurrentNotice();
1572 if ($notice instanceof Notice) {
1573 $act->source->updated = self::utcDate($notice->created);
1576 $user = User::getKV('id', $profile->id);
1578 if ($user instanceof User) {
1579 $act->source->links['license'] = common_config('license', 'url');
1583 if ($this->isLocal()) {
1584 $act->selfLink = common_local_url('ApiStatusesShow', array('id' => $this->id,
1585 'format' => 'atom'));
1586 $act->editLink = $act->selfLink;
1589 Event::handle('EndNoticeAsActivity', array($this, &$act));
1592 self::cacheSet(Cache::codeKey('notice:as-activity:'.$this->id), $act);
1597 // This has gotten way too long. Needs to be sliced up into functional bits
1598 // or ideally exported to a utility class.
1600 function asAtomEntry($namespace=false,
1605 $act = $this->asActivity($cur);
1606 $act->extra[] = $this->noticeInfo($cur);
1607 return $act->asString($namespace, $author, $source);
1611 * Extra notice info for atom entries
1613 * Clients use some extra notice info in the atom stream.
1614 * This gives it to them.
1616 * @param User $cur Current user
1618 * @return array representation of <statusnet:notice_info> element
1621 function noticeInfo($cur)
1623 // local notice ID (useful to clients for ordering)
1625 $noticeInfoAttr = array('local_id' => $this->id);
1629 $ns = $this->getSource();
1631 if ($ns instanceof Notice_source) {
1632 $noticeInfoAttr['source'] = $ns->code;
1633 if (!empty($ns->url)) {
1634 $noticeInfoAttr['source_link'] = $ns->url;
1635 if (!empty($ns->name)) {
1636 $noticeInfoAttr['source'] = '<a href="'
1637 . htmlspecialchars($ns->url)
1638 . '" rel="nofollow">'
1639 . htmlspecialchars($ns->name)
1645 // favorite and repeated
1648 $cp = $cur->getProfile();
1649 $noticeInfoAttr['favorite'] = ($cp->hasFave($this)) ? "true" : "false";
1650 $noticeInfoAttr['repeated'] = ($cp->hasRepeated($this)) ? "true" : "false";
1653 if (!empty($this->repeat_of)) {
1654 $noticeInfoAttr['repeat_of'] = $this->repeat_of;
1657 return array('statusnet:notice_info', $noticeInfoAttr, null);
1661 * Returns an XML string fragment with a reference to a notice as an
1662 * Activity Streams noun object with the given element type.
1664 * Assumes that 'activity' namespace has been previously defined.
1666 * @param string $element one of 'subject', 'object', 'target'
1670 function asActivityNoun($element)
1672 $noun = ActivityObject::fromNotice($this);
1673 return $noun->asString('activity:' . $element);
1678 if (!empty($this->url)) {
1680 } else if (!empty($this->uri) && preg_match('/^https?:/', $this->uri)) {
1683 return common_local_url('shownotice',
1684 array('notice' => $this->id));
1690 * Determine which notice, if any, a new notice is in reply to.
1692 * For conversation tracking, we try to see where this notice fits
1693 * in the tree. Rough algorithm is:
1695 * if (reply_to is set and valid) {
1697 * } else if ((source not API or Web) and (content starts with "T NAME" or "@name ")) {
1698 * return ID of last notice by initial @name in content;
1701 * Note that all @nickname instances will still be used to save "reply" records,
1702 * so the notice shows up in the mentioned users' "replies" tab.
1704 * @param integer $reply_to ID passed in by Web or API
1705 * @param integer $profile_id ID of author
1706 * @param string $source Source tag, like 'web' or 'gwibber'
1707 * @param string $content Final notice content
1709 * @return integer ID of replied-to notice, or null for not a reply.
1712 static function getReplyTo($reply_to, $profile_id, $source, $content)
1714 static $lb = array('xmpp', 'mail', 'sms', 'omb');
1716 // If $reply_to is specified, we check that it exists, and then
1717 // return it if it does
1719 if (!empty($reply_to)) {
1720 $reply_notice = Notice::getKV('id', $reply_to);
1721 if ($reply_notice instanceof Notice) {
1722 return $reply_notice;
1726 // If it's not a "low bandwidth" source (one where you can't set
1727 // a reply_to argument), we return. This is mostly web and API
1730 if (!in_array($source, $lb)) {
1734 // Is there an initial @ or T?
1736 if (preg_match('/^T ([A-Z0-9]{1,64}) /', $content, $match) ||
1737 preg_match('/^@([a-z0-9]{1,64})\s+/', $content, $match)) {
1738 $nickname = common_canonical_nickname($match[1]);
1743 // Figure out who that is.
1745 $sender = Profile::getKV('id', $profile_id);
1746 if (!$sender instanceof Profile) {
1750 $recipient = common_relative_profile($sender, $nickname, common_sql_now());
1752 if (!$recipient instanceof Profile) {
1756 // Get their last notice
1758 $last = $recipient->getCurrentNotice();
1760 if ($last instanceof Notice) {
1767 static function maxContent()
1769 $contentlimit = common_config('notice', 'contentlimit');
1770 // null => use global limit (distinct from 0!)
1771 if (is_null($contentlimit)) {
1772 $contentlimit = common_config('site', 'textlimit');
1774 return $contentlimit;
1777 static function contentTooLong($content)
1779 $contentlimit = self::maxContent();
1780 return ($contentlimit > 0 && !empty($content) && (mb_strlen($content) > $contentlimit));
1783 function getLocation()
1787 if (!empty($this->location_id) && !empty($this->location_ns)) {
1788 $location = Location::fromId($this->location_id, $this->location_ns);
1791 if (is_null($location)) { // no ID, or Location::fromId() failed
1792 if (!empty($this->lat) && !empty($this->lon)) {
1793 $location = Location::fromLatLon($this->lat, $this->lon);
1801 * Convenience function for posting a repeat of an existing message.
1803 * @param int $repeater_id: profile ID of user doing the repeat
1804 * @param string $source: posting source key, eg 'web', 'api', etc
1807 * @throws Exception on failure or permission problems
1809 function repeat($repeater_id, $source)
1811 $author = Profile::getKV('id', $this->profile_id);
1813 // TRANS: Message used to repeat a notice. RT is the abbreviation of 'retweet'.
1814 // TRANS: %1$s is the repeated user's name, %2$s is the repeated notice.
1815 $content = sprintf(_('RT @%1$s %2$s'),
1819 $maxlen = common_config('site', 'textlimit');
1820 if ($maxlen > 0 && mb_strlen($content) > $maxlen) {
1821 // Web interface and current Twitter API clients will
1822 // pull the original notice's text, but some older
1823 // clients and RSS/Atom feeds will see this trimmed text.
1825 // Unfortunately this is likely to lose tags or URLs
1826 // at the end of long notices.
1827 $content = mb_substr($content, 0, $maxlen - 4) . ' ...';
1830 // Scope is same as this one's
1832 return self::saveNew($repeater_id,
1835 array('repeat_of' => $this->id,
1836 'scope' => $this->scope));
1839 // These are supposed to be in chron order!
1841 function repeatStream($limit=100)
1843 $cache = Cache::instance();
1845 if (empty($cache)) {
1846 $ids = $this->_repeatStreamDirect($limit);
1848 $idstr = $cache->get(Cache::key('notice:repeats:'.$this->id));
1849 if ($idstr !== false) {
1850 if (empty($idstr)) {
1853 $ids = explode(',', $idstr);
1856 $ids = $this->_repeatStreamDirect(100);
1857 $cache->set(Cache::key('notice:repeats:'.$this->id), implode(',', $ids));
1860 // We do a max of 100, so slice down to limit
1861 $ids = array_slice($ids, 0, $limit);
1865 return NoticeStream::getStreamByIds($ids);
1868 function _repeatStreamDirect($limit)
1870 $notice = new Notice();
1872 $notice->selectAdd(); // clears it
1873 $notice->selectAdd('id');
1875 $notice->repeat_of = $this->id;
1877 $notice->orderBy('created, id'); // NB: asc!
1879 if (!is_null($limit)) {
1880 $notice->limit(0, $limit);
1883 return $notice->fetchAll('id');
1886 function locationOptions($lat, $lon, $location_id, $location_ns, $profile = null)
1890 if (!empty($location_id) && !empty($location_ns)) {
1891 $options['location_id'] = $location_id;
1892 $options['location_ns'] = $location_ns;
1894 $location = Location::fromId($location_id, $location_ns);
1896 if ($location instanceof Location) {
1897 $options['lat'] = $location->lat;
1898 $options['lon'] = $location->lon;
1901 } else if (!empty($lat) && !empty($lon)) {
1902 $options['lat'] = $lat;
1903 $options['lon'] = $lon;
1905 $location = Location::fromLatLon($lat, $lon);
1907 if ($location instanceof Location) {
1908 $options['location_id'] = $location->location_id;
1909 $options['location_ns'] = $location->location_ns;
1911 } else if (!empty($profile)) {
1912 if (isset($profile->lat) && isset($profile->lon)) {
1913 $options['lat'] = $profile->lat;
1914 $options['lon'] = $profile->lon;
1917 if (isset($profile->location_id) && isset($profile->location_ns)) {
1918 $options['location_id'] = $profile->location_id;
1919 $options['location_ns'] = $profile->location_ns;
1926 function clearAttentions()
1928 $att = new Attention();
1929 $att->notice_id = $this->getID();
1932 while ($att->fetch()) {
1933 // Can't do delete() on the object directly since it won't remove all of it
1934 $other = clone($att);
1940 function clearReplies()
1942 $replyNotice = new Notice();
1943 $replyNotice->reply_to = $this->id;
1945 //Null any notices that are replies to this notice
1947 if ($replyNotice->find()) {
1948 while ($replyNotice->fetch()) {
1949 $orig = clone($replyNotice);
1950 $replyNotice->reply_to = null;
1951 $replyNotice->update($orig);
1957 $reply = new Reply();
1958 $reply->notice_id = $this->id;
1960 if ($reply->find()) {
1961 while($reply->fetch()) {
1962 self::blow('reply:stream:%d', $reply->profile_id);
1970 function clearFiles()
1972 $f2p = new File_to_post();
1974 $f2p->post_id = $this->id;
1977 while ($f2p->fetch()) {
1981 // FIXME: decide whether to delete File objects
1982 // ...and related (actual) files
1985 function clearRepeats()
1987 $repeatNotice = new Notice();
1988 $repeatNotice->repeat_of = $this->id;
1990 //Null any notices that are repeats of this notice
1992 if ($repeatNotice->find()) {
1993 while ($repeatNotice->fetch()) {
1994 $orig = clone($repeatNotice);
1995 $repeatNotice->repeat_of = null;
1996 $repeatNotice->update($orig);
2001 function clearFaves()
2004 $fave->notice_id = $this->id;
2006 if ($fave->find()) {
2007 while ($fave->fetch()) {
2008 self::blow('fave:ids_by_user_own:%d', $fave->user_id);
2009 self::blow('fave:ids_by_user_own:%d;last', $fave->user_id);
2010 self::blow('fave:ids_by_user:%d', $fave->user_id);
2011 self::blow('fave:ids_by_user:%d;last', $fave->user_id);
2019 function clearTags()
2021 $tag = new Notice_tag();
2022 $tag->notice_id = $this->id;
2025 while ($tag->fetch()) {
2026 self::blow('profile:notice_ids_tagged:%d:%s', $this->profile_id, Cache::keyize($tag->tag));
2027 self::blow('profile:notice_ids_tagged:%d:%s;last', $this->profile_id, Cache::keyize($tag->tag));
2028 self::blow('notice_tag:notice_ids:%s', Cache::keyize($tag->tag));
2029 self::blow('notice_tag:notice_ids:%s;last', Cache::keyize($tag->tag));
2037 function clearGroupInboxes()
2039 $gi = new Group_inbox();
2041 $gi->notice_id = $this->id;
2044 while ($gi->fetch()) {
2045 self::blow('user_group:notice_ids:%d', $gi->group_id);
2053 function distribute()
2055 // We always insert for the author so they don't
2057 Event::handle('StartNoticeDistribute', array($this));
2059 // If there's a failure, we want to _force_
2060 // distribution at this point.
2062 $qm = QueueManager::get();
2063 $qm->enqueue($this, 'distrib');
2064 } catch (Exception $e) {
2065 // If the exception isn't transient, this
2066 // may throw more exceptions as DQH does
2067 // its own enqueueing. So, we ignore them!
2069 $handler = new DistribQueueHandler();
2070 $handler->handle($this);
2071 } catch (Exception $e) {
2072 common_log(LOG_ERR, "emergency redistribution resulted in " . $e->getMessage());
2074 // Re-throw so somebody smarter can handle it.
2081 $result = parent::insert();
2083 if ($result !== false) {
2084 // Profile::hasRepeated() abuses pkeyGet(), so we
2085 // have to clear manually
2086 if (!empty($this->repeat_of)) {
2087 $c = self::memcache();
2089 $ck = self::multicacheKey('Notice',
2090 array('profile_id' => $this->profile_id,
2091 'repeat_of' => $this->repeat_of));
2101 * Get the source of the notice
2103 * @return Notice_source $ns A notice source object. 'code' is the only attribute
2104 * guaranteed to be populated.
2106 function getSource()
2108 $ns = new Notice_source();
2109 if (!empty($this->source)) {
2110 switch ($this->source) {
2117 $ns->code = $this->source;
2120 $ns = Notice_source::getKV($this->source);
2122 $ns = new Notice_source();
2123 $ns->code = $this->source;
2124 $app = Oauth_application::getKV('name', $this->source);
2126 $ns->name = $app->name;
2127 $ns->url = $app->source_url;
2137 * Determine whether the notice was locally created
2139 * @return boolean locality
2142 public function isLocal()
2144 return ($this->is_local == Notice::LOCAL_PUBLIC ||
2145 $this->is_local == Notice::LOCAL_NONPUBLIC);
2149 * Get the list of hash tags saved with this notice.
2151 * @return array of strings
2153 public function getTags()
2157 $keypart = sprintf('notice:tags:%d', $this->id);
2159 $tagstr = self::cacheGet($keypart);
2161 if ($tagstr !== false) {
2162 $tags = explode(',', $tagstr);
2164 $tag = new Notice_tag();
2165 $tag->notice_id = $this->id;
2167 while ($tag->fetch()) {
2168 $tags[] = $tag->tag;
2171 self::cacheSet($keypart, implode(',', $tags));
2177 static private function utcDate($dt)
2179 $dateStr = date('d F Y H:i:s', strtotime($dt));
2180 $d = new DateTime($dateStr, new DateTimeZone('UTC'));
2181 return $d->format(DATE_W3C);
2185 * Look up the creation timestamp for a given notice ID, even
2186 * if it's been deleted.
2189 * @return mixed string recorded creation timestamp, or false if can't be found
2191 public static function getAsTimestamp($id)
2197 $notice = Notice::getKV('id', $id);
2199 return $notice->created;
2202 $deleted = Deleted_notice::getKV('id', $id);
2204 return $deleted->created;
2211 * Build an SQL 'where' fragment for timestamp-based sorting from a since_id
2212 * parameter, matching notices posted after the given one (exclusive).
2214 * If the referenced notice can't be found, will return false.
2217 * @param string $idField
2218 * @param string $createdField
2219 * @return mixed string or false if no match
2221 public static function whereSinceId($id, $idField='id', $createdField='created')
2223 $since = Notice::getAsTimestamp($id);
2225 return sprintf("($createdField = '%s' and $idField > %d) or ($createdField > '%s')", $since, $id, $since);
2231 * Build an SQL 'where' fragment for timestamp-based sorting from a since_id
2232 * parameter, matching notices posted after the given one (exclusive), and
2233 * if necessary add it to the data object's query.
2235 * @param DB_DataObject $obj
2237 * @param string $idField
2238 * @param string $createdField
2239 * @return mixed string or false if no match
2241 public static function addWhereSinceId(DB_DataObject $obj, $id, $idField='id', $createdField='created')
2243 $since = self::whereSinceId($id, $idField, $createdField);
2245 $obj->whereAdd($since);
2250 * Build an SQL 'where' fragment for timestamp-based sorting from a max_id
2251 * parameter, matching notices posted before the given one (inclusive).
2253 * If the referenced notice can't be found, will return false.
2256 * @param string $idField
2257 * @param string $createdField
2258 * @return mixed string or false if no match
2260 public static function whereMaxId($id, $idField='id', $createdField='created')
2262 $max = Notice::getAsTimestamp($id);
2264 return sprintf("($createdField < '%s') or ($createdField = '%s' and $idField <= %d)", $max, $max, $id);
2270 * Build an SQL 'where' fragment for timestamp-based sorting from a max_id
2271 * parameter, matching notices posted before the given one (inclusive), and
2272 * if necessary add it to the data object's query.
2274 * @param DB_DataObject $obj
2276 * @param string $idField
2277 * @param string $createdField
2278 * @return mixed string or false if no match
2280 public static function addWhereMaxId(DB_DataObject $obj, $id, $idField='id', $createdField='created')
2282 $max = self::whereMaxId($id, $idField, $createdField);
2284 $obj->whereAdd($max);
2290 if (common_config('public', 'localonly')) {
2291 return ($this->is_local == Notice::LOCAL_PUBLIC);
2293 return (($this->is_local != Notice::LOCAL_NONPUBLIC) &&
2294 ($this->is_local != Notice::GATEWAY));
2299 * Check that the given profile is allowed to read, respond to, or otherwise
2300 * act on this notice.
2302 * The $scope member is a bitmask of scopes, representing a logical AND of the
2303 * scope requirement. So, 0x03 (Notice::ADDRESSEE_SCOPE | Notice::SITE_SCOPE) means
2304 * "only visible to people who are mentioned in the notice AND are users on this site."
2305 * Users on the site who are not mentioned in the notice will not be able to see the
2308 * @param Profile $profile The profile to check; pass null to check for public/unauthenticated users.
2310 * @return boolean whether the profile is in the notice's scope
2312 function inScope($profile)
2314 if (is_null($profile)) {
2315 $keypart = sprintf('notice:in-scope-for:%d:null', $this->id);
2317 $keypart = sprintf('notice:in-scope-for:%d:%d', $this->id, $profile->id);
2320 $result = self::cacheGet($keypart);
2322 if ($result === false) {
2324 if (Event::handle('StartNoticeInScope', array($this, $profile, &$bResult))) {
2325 $bResult = $this->_inScope($profile);
2326 Event::handle('EndNoticeInScope', array($this, $profile, &$bResult));
2328 $result = ($bResult) ? 1 : 0;
2329 self::cacheSet($keypart, $result, 0, 300);
2332 return ($result == 1) ? true : false;
2335 protected function _inScope($profile)
2337 if (!is_null($this->scope)) {
2338 $scope = $this->scope;
2340 $scope = self::defaultScope();
2343 // If there's no scope, anyone (even anon) is in scope.
2345 if ($scope == 0) { // Not private
2347 return !$this->isHiddenSpam($profile);
2349 } else { // Private, somehow
2351 // If there's scope, anon cannot be in scope
2353 if (empty($profile)) {
2357 // Author is always in scope
2359 if ($this->profile_id == $profile->id) {
2363 // Only for users on this site
2365 if (($scope & Notice::SITE_SCOPE) && !$profile->isLocal()) {
2369 // Only for users mentioned in the notice
2371 if ($scope & Notice::ADDRESSEE_SCOPE) {
2373 $reply = Reply::pkeyGet(array('notice_id' => $this->id,
2374 'profile_id' => $profile->id));
2376 if (!$reply instanceof Reply) {
2381 // Only for members of the given group
2383 if ($scope & Notice::GROUP_SCOPE) {
2385 // XXX: just query for the single membership
2387 $groups = $this->getGroups();
2391 foreach ($groups as $group) {
2392 if ($profile->isMember($group)) {
2403 // Only for followers of the author
2407 if ($scope & Notice::FOLLOWER_SCOPE) {
2410 $author = $this->getProfile();
2411 } catch (Exception $e) {
2415 if (!Subscription::exists($profile, $author)) {
2420 return !$this->isHiddenSpam($profile);
2424 function isHiddenSpam($profile) {
2426 // Hide posts by silenced users from everyone but moderators.
2428 if (common_config('notice', 'hidespam')) {
2431 $author = $this->getProfile();
2432 } catch(Exception $e) {
2433 // If we can't get an author, keep it hidden.
2434 // XXX: technically not spam, but, whatever.
2438 if ($author->hasRole(Profile_role::SILENCED)) {
2439 if (!$profile instanceof Profile || (($profile->id !== $author->id) && (!$profile->hasRight(Right::REVIEWSPAM)))) {
2448 public function getParent()
2450 $parent = Notice::getKV('id', $this->reply_to);
2452 if (!$parent instanceof Notice) {
2453 throw new ServerException('Notice has no parent');
2460 * Magic function called at serialize() time.
2462 * We use this to drop a couple process-specific references
2463 * from DB_DataObject which can cause trouble in future
2466 * @return array of variable names to include in serialization.
2471 $vars = parent::__sleep();
2472 $skip = array('_profile', '_groups', '_attachments', '_faves', '_replies', '_repeats');
2473 return array_diff($vars, $skip);
2476 static function defaultScope()
2478 $scope = common_config('notice', 'defaultscope');
2479 if (is_null($scope)) {
2480 if (common_config('site', 'private')) {
2489 static function fillProfiles($notices)
2491 $map = self::getProfiles($notices);
2493 foreach ($notices as $entry=>$notice) {
2495 if (array_key_exists($notice->profile_id, $map)) {
2496 $notice->_setProfile($map[$notice->profile_id]);
2498 } catch (NoProfileException $e) {
2499 common_log(LOG_WARNING, "Failed to fill profile in Notice with non-existing entry for profile_id: {$e->id}");
2500 unset($notices[$entry]);
2504 return array_values($map);
2507 static function getProfiles(&$notices)
2510 foreach ($notices as $notice) {
2511 $ids[] = $notice->profile_id;
2514 $ids = array_unique($ids);
2516 return Profile::pivotGet('id', $ids);
2519 static function fillGroups(&$notices)
2521 $ids = self::_idsOf($notices);
2523 $gis = Group_inbox::listGet('notice_id', $ids);
2527 foreach ($gis as $id => $gi)
2531 $gids[] = $g->group_id;
2535 $gids = array_unique($gids);
2537 $group = User_group::pivotGet('id', $gids);
2539 foreach ($notices as $notice)
2542 $gi = $gis[$notice->id];
2543 foreach ($gi as $g) {
2544 $grps[] = $group[$g->group_id];
2546 $notice->_setGroups($grps);
2550 static function _idsOf(&$notices)
2553 foreach ($notices as $notice) {
2554 $ids[] = $notice->id;
2556 $ids = array_unique($ids);
2560 static function fillAttachments(&$notices)
2562 $ids = self::_idsOf($notices);
2564 $f2pMap = File_to_post::listGet('post_id', $ids);
2568 foreach ($f2pMap as $noticeId => $f2ps) {
2569 foreach ($f2ps as $f2p) {
2570 $fileIds[] = $f2p->file_id;
2574 $fileIds = array_unique($fileIds);
2576 $fileMap = File::pivotGet('id', $fileIds);
2578 foreach ($notices as $notice)
2581 $f2ps = $f2pMap[$notice->id];
2582 foreach ($f2ps as $f2p) {
2583 $files[] = $fileMap[$f2p->file_id];
2585 $notice->_setAttachments($files);
2592 * All faves of this notice
2594 * @return array Array of Fave objects
2599 if (isset($this->_faves) && is_array($this->_faves)) {
2600 return $this->_faves;
2602 $faveMap = Fave::listGet('notice_id', array($this->id));
2603 $this->_faves = $faveMap[$this->id];
2604 return $this->_faves;
2607 function _setFaves($faves)
2609 $this->_faves = $faves;
2612 static function fillFaves(&$notices)
2614 $ids = self::_idsOf($notices);
2615 $faveMap = Fave::listGet('notice_id', $ids);
2618 foreach ($faveMap as $id => $faves) {
2619 $cnt += count($faves);
2620 if (count($faves) > 0) {
2624 foreach ($notices as $notice) {
2625 $faves = $faveMap[$notice->id];
2626 $notice->_setFaves($faves);
2630 static function fillReplies(&$notices)
2632 $ids = self::_idsOf($notices);
2633 $replyMap = Reply::listGet('notice_id', $ids);
2634 foreach ($notices as $notice) {
2635 $replies = $replyMap[$notice->id];
2637 foreach ($replies as $reply) {
2638 $ids[] = $reply->profile_id;
2640 $notice->_setReplies($ids);
2644 protected $_repeats;
2646 function getRepeats()
2648 if (isset($this->_repeats) && is_array($this->_repeats)) {
2649 return $this->_repeats;
2651 $repeatMap = Notice::listGet('repeat_of', array($this->id));
2652 $this->_repeats = $repeatMap[$this->id];
2653 return $this->_repeats;
2656 function _setRepeats($repeats)
2658 $this->_repeats = $repeats;
2661 static function fillRepeats(&$notices)
2663 $ids = self::_idsOf($notices);
2664 $repeatMap = Notice::listGet('repeat_of', $ids);
2665 foreach ($notices as $notice) {
2666 $repeats = $repeatMap[$notice->id];
2667 $notice->_setRepeats($repeats);