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 * @copyright 2009 Free Software Foundation, Inc http://www.fsf.org
33 * @license GNU Affero General Public License http://www.gnu.org/licenses/
36 if (!defined('STATUSNET') && !defined('LACONICA')) {
41 * Table Definition for notice
43 require_once INSTALLDIR.'/classes/Memcached_DataObject.php';
45 /* We keep 200 notices, the max number of notices available per API request,
46 * in the memcached cache. */
48 define('NOTICE_CACHE_WINDOW', CachingNoticeStream::CACHE_WINDOW);
50 define('MAX_BOXCARS', 128);
52 class Notice extends Managed_DataObject
55 /* the code below is auto generated do not remove the above tag */
57 public $__table = 'notice'; // table name
58 public $id; // int(4) primary_key not_null
59 public $profile_id; // int(4) multiple_key not_null
60 public $uri; // varchar(255) unique_key
61 public $content; // text
62 public $rendered; // text
63 public $url; // varchar(255)
64 public $created; // datetime multiple_key not_null default_0000-00-00%2000%3A00%3A00
65 public $modified; // timestamp not_null default_CURRENT_TIMESTAMP
66 public $reply_to; // int(4)
67 public $is_local; // int(4)
68 public $source; // varchar(32)
69 public $conversation; // int(4)
70 public $lat; // decimal(10,7)
71 public $lon; // decimal(10,7)
72 public $location_id; // int(4)
73 public $location_ns; // int(4)
74 public $repeat_of; // int(4)
75 public $verb; // varchar(255)
76 public $object_type; // varchar(255)
77 public $scope; // int(4)
80 function staticGet($k,$v=NULL)
82 return Memcached_DataObject::staticGet('Notice',$k,$v);
85 /* the code above is auto generated do not remove the tag below */
88 public static function schemaDef()
92 'id' => array('type' => 'serial', 'not null' => true, 'description' => 'unique identifier'),
93 'profile_id' => array('type' => 'int', 'not null' => true, 'description' => 'who made the update'),
94 'uri' => array('type' => 'varchar', 'length' => 255, 'description' => 'universally unique identifier, usually a tag URI'),
95 'content' => array('type' => 'text', 'description' => 'update content'),
96 'rendered' => array('type' => 'text', 'description' => 'HTML version of the content'),
97 'url' => array('type' => 'varchar', 'length' => 255, 'description' => 'URL of any attachment (image, video, bookmark, whatever)'),
98 'created' => array('type' => 'datetime', 'not null' => true, 'description' => 'date this record was created'),
99 'modified' => array('type' => 'timestamp', 'not null' => true, 'description' => 'date this record was modified'),
100 'reply_to' => array('type' => 'int', 'description' => 'notice replied to (usually a guess)'),
101 'is_local' => array('type' => 'int', 'size' => 'tiny', 'default' => 0, 'description' => 'notice was generated by a user'),
102 'source' => array('type' => 'varchar', 'length' => 32, 'description' => 'source of comment, like "web", "im", or "clientname"'),
103 'conversation' => array('type' => 'int', 'description' => 'id of root notice in this conversation'),
104 'lat' => array('type' => 'numeric', 'precision' => 10, 'scale' => 7, 'description' => 'latitude'),
105 'lon' => array('type' => 'numeric', 'precision' => 10, 'scale' => 7, 'description' => 'longitude'),
106 'location_id' => array('type' => 'int', 'description' => 'location id if possible'),
107 'location_ns' => array('type' => 'int', 'description' => 'namespace for location'),
108 'repeat_of' => array('type' => 'int', 'description' => 'notice this is a repeat of'),
109 'object_type' => array('type' => 'varchar', 'length' => 255, 'description' => 'URI representing activity streams object type', 'default' => 'http://activitystrea.ms/schema/1.0/note'),
110 'scope' => array('type' => 'int',
112 'description' => 'bit map for distribution scope; 0 = everywhere; 1 = this server only; 2 = addressees; 4 = followers'),
114 'primary key' => array('id'),
115 'unique keys' => array(
116 'notice_uri_key' => array('uri'),
118 'foreign keys' => array(
119 'notice_profile_id_fkey' => array('profile', array('profile_id' => 'id')),
120 'notice_reply_to_fkey' => array('notice', array('reply_to' => 'id')),
121 'notice_conversation_fkey' => array('conversation', array('conversation' => 'id')), # note... used to refer to notice.id
122 'notice_repeat_of_fkey' => array('notice', array('repeat_of' => 'id')), # @fixme: what about repeats of deleted notices?
125 'notice_profile_id_idx' => array('profile_id', 'created', 'id'),
126 'notice_conversation_idx' => array('conversation'),
127 'notice_created_idx' => array('created'),
128 'notice_replyto_idx' => array('reply_to'),
129 'notice_repeatof_idx' => array('repeat_of'),
131 'fulltext indexes' => array(
132 'content' => array('content'),
137 function multiGet($kc, $kvs, $skipNulls=true)
139 return Memcached_DataObject::multiGet('Notice', $kc, $kvs, $skipNulls);
143 const LOCAL_PUBLIC = 1;
145 const LOCAL_NONPUBLIC = -1;
148 const PUBLIC_SCOPE = 0; // Useful fake constant
149 const SITE_SCOPE = 1;
150 const ADDRESSEE_SCOPE = 2;
151 const GROUP_SCOPE = 4;
152 const FOLLOWER_SCOPE = 8;
154 protected $_profile = -1;
156 function getProfile()
158 if (is_int($this->_profile) && $this->_profile == -1) {
159 $this->_setProfile(Profile::staticGet('id', $this->profile_id));
161 if (empty($this->_profile)) {
162 // TRANS: Server exception thrown when a user profile for a notice cannot be found.
163 // TRANS: %1$d is a profile ID (number), %2$d is a notice ID (number).
164 throw new ServerException(sprintf(_('No such profile (%1$d) for notice (%2$d).'), $this->profile_id, $this->id));
168 return $this->_profile;
171 function _setProfile($profile)
173 $this->_profile = $profile;
178 // For auditing purposes, save a record that the notice
181 // @fixme we have some cases where things get re-run and so the
183 $deleted = Deleted_notice::staticGet('id', $this->id);
186 $deleted = Deleted_notice::staticGet('uri', $this->uri);
190 $deleted = new Deleted_notice();
192 $deleted->id = $this->id;
193 $deleted->profile_id = $this->profile_id;
194 $deleted->uri = $this->uri;
195 $deleted->created = $this->created;
196 $deleted->deleted = common_sql_now();
201 if (Event::handle('NoticeDeleteRelated', array($this))) {
203 // Clear related records
205 $this->clearReplies();
206 $this->clearRepeats();
209 $this->clearGroupInboxes();
212 // NOTE: we don't clear inboxes
213 // NOTE: we don't clear queue items
216 $result = parent::delete();
218 $this->blowOnDelete();
223 * Extract #hashtags from this notice's content and save them to the database.
227 /* extract all #hastags */
228 $count = preg_match_all('/(?:^|\s)#([\pL\pN_\-\.]{1,64})/u', strtolower($this->content), $match);
233 /* Add them to the database */
234 return $this->saveKnownTags($match[1]);
238 * Record the given set of hash tags in the db for this notice.
239 * Given tag strings will be normalized and checked for dupes.
241 function saveKnownTags($hashtags)
243 //turn each into their canonical tag
244 //this is needed to remove dupes before saving e.g. #hash.tag = #hashtag
245 for($i=0; $i<count($hashtags); $i++) {
246 /* elide characters we don't want in the tag */
247 $hashtags[$i] = common_canonical_tag($hashtags[$i]);
250 foreach(array_unique($hashtags) as $hashtag) {
251 $this->saveTag($hashtag);
252 self::blow('profile:notice_ids_tagged:%d:%s', $this->profile_id, $hashtag);
258 * Record a single hash tag as associated with this notice.
259 * Tag format and uniqueness must be validated by caller.
261 function saveTag($hashtag)
263 $tag = new Notice_tag();
264 $tag->notice_id = $this->id;
265 $tag->tag = $hashtag;
266 $tag->created = $this->created;
267 $id = $tag->insert();
270 // TRANS: Server exception. %s are the error details.
271 throw new ServerException(sprintf(_('Database error inserting hashtag: %s.'),
272 $last_error->message));
276 // if it's saved, blow its cache
277 $tag->blowCache(false);
281 * Save a new notice and push it out to subscribers' inboxes.
282 * Poster's permissions are checked before sending.
284 * @param int $profile_id Profile ID of the poster
285 * @param string $content source message text; links may be shortened
286 * per current user's preference
287 * @param string $source source key ('web', 'api', etc)
288 * @param array $options Associative array of optional properties:
289 * string 'created' timestamp of notice; defaults to now
290 * int 'is_local' source/gateway ID, one of:
291 * Notice::LOCAL_PUBLIC - Local, ok to appear in public timeline
292 * Notice::REMOTE - Sent from a remote service;
293 * hide from public timeline but show in
294 * local "and friends" timelines
295 * Notice::LOCAL_NONPUBLIC - Local, but hide from public timeline
296 * Notice::GATEWAY - From another non-OStatus service;
297 * will not appear in public views
298 * float 'lat' decimal latitude for geolocation
299 * float 'lon' decimal longitude for geolocation
300 * int 'location_id' geoname identifier
301 * int 'location_ns' geoname namespace to interpret location_id
302 * int 'reply_to'; notice ID this is a reply to
303 * int 'repeat_of'; notice ID this is a repeat of
304 * string 'uri' unique ID for notice; defaults to local notice URL
305 * string 'url' permalink to notice; defaults to local notice URL
306 * string 'rendered' rendered HTML version of content
307 * array 'replies' list of profile URIs for reply delivery in
308 * place of extracting @-replies from content.
309 * array 'groups' list of group IDs to deliver to, in place of
310 * extracting ! tags from content
311 * array 'tags' list of hashtag strings to save with the notice
312 * in place of extracting # tags from content
313 * array 'urls' list of attached/referred URLs to save with the
314 * notice in place of extracting links from content
315 * boolean 'distribute' whether to distribute the notice, default true
316 * string 'object_type' URL of the associated object type (default ActivityObject::NOTE)
317 * string 'verb' URL of the associated verb (default ActivityVerb::POST)
318 * int 'scope' Scope bitmask; default to SITE_SCOPE on private sites, 0 otherwise
320 * @fixme tag override
323 * @throws ClientException
325 static function saveNew($profile_id, $content, $source, $options=null) {
326 $defaults = array('uri' => null,
331 'distribute' => true,
332 'object_type' => null,
335 if (!empty($options) && is_array($options)) {
336 $options = array_merge($defaults, $options);
342 if (!isset($is_local)) {
343 $is_local = Notice::LOCAL_PUBLIC;
346 $profile = Profile::staticGet('id', $profile_id);
347 $user = User::staticGet('id', $profile_id);
349 // Use the local user's shortening preferences, if applicable.
350 $final = $user->shortenLinks($content);
352 $final = common_shorten_links($content);
355 if (Notice::contentTooLong($final)) {
356 // TRANS: Client exception thrown if a notice contains too many characters.
357 throw new ClientException(_('Problem saving notice. Too long.'));
360 if (empty($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 if (common_config('throttle', 'enabled') && !Notice::checkEditThrottle($profile_id)) {
366 common_log(LOG_WARNING, 'Excessive posting by profile #' . $profile_id . '; throttled.');
367 // TRANS: Client exception thrown when a user tries to post too many notices in a given time frame.
368 throw new ClientException(_('Too many notices too fast; take a breather '.
369 'and post again in a few minutes.'));
372 if (common_config('site', 'dupelimit') > 0 && !Notice::checkDupes($profile_id, $final)) {
373 common_log(LOG_WARNING, 'Dupe posting by profile #' . $profile_id . '; throttled.');
374 // TRANS: Client exception thrown when a user tries to post too many duplicate notices in a given time frame.
375 throw new ClientException(_('Too many duplicate messages too quickly;'.
376 ' take a breather and post again in a few minutes.'));
379 if (!$profile->hasRight(Right::NEWNOTICE)) {
380 common_log(LOG_WARNING, "Attempted post from user disallowed to post: " . $profile->nickname);
382 // TRANS: Client exception thrown when a user tries to post while being banned.
383 throw new ClientException(_('You are banned from posting notices on this site.'), 403);
386 $notice = new Notice();
387 $notice->profile_id = $profile_id;
389 $autosource = common_config('public', 'autosource');
391 // Sandboxed are non-false, but not 1, either
393 if (!$profile->hasRight(Right::PUBLICNOTICE) ||
394 ($source && $autosource && in_array($source, $autosource))) {
395 $notice->is_local = Notice::LOCAL_NONPUBLIC;
397 $notice->is_local = $is_local;
400 if (!empty($created)) {
401 $notice->created = $created;
403 $notice->created = common_sql_now();
406 $notice->content = $final;
408 $notice->source = $source;
412 // Get the groups here so we can figure out replies and such
414 if (!isset($groups)) {
415 $groups = self::groupsFromText($notice->content, $profile);
420 // Handle repeat case
422 if (isset($repeat_of)) {
424 // Check for a private one
426 $repeat = Notice::staticGet('id', $repeat_of);
428 if (empty($repeat)) {
429 // TRANS: Client exception thrown in notice when trying to repeat a missing or deleted notice.
430 throw new ClientException(_('Cannot repeat; original notice is missing or deleted.'));
433 if ($profile->id == $repeat->profile_id) {
434 // TRANS: Client error displayed when trying to repeat an own notice.
435 throw new ClientException(_('You cannot repeat your own notice.'));
438 if ($repeat->scope != Notice::SITE_SCOPE &&
439 $repeat->scope != Notice::PUBLIC_SCOPE) {
440 // TRANS: Client error displayed when trying to repeat a non-public notice.
441 throw new ClientException(_('Cannot repeat a private notice.'), 403);
444 if (!$repeat->inScope($profile)) {
445 // The generic checks above should cover this, but let's be sure!
446 // TRANS: Client error displayed when trying to repeat a notice you cannot access.
447 throw new ClientException(_('Cannot repeat a notice you cannot read.'), 403);
450 if ($profile->hasRepeated($repeat->id)) {
451 // TRANS: Client error displayed when trying to repeat an already repeated notice.
452 throw new ClientException(_('You already repeated that notice.'));
455 $notice->repeat_of = $repeat_of;
457 $reply = self::getReplyTo($reply_to, $profile_id, $source, $final);
459 if (!empty($reply)) {
461 if (!$reply->inScope($profile)) {
462 // TRANS: Client error displayed when trying to reply to a notice a the target has no access to.
463 // TRANS: %1$s is a user nickname, %2$d is a notice ID (number).
464 throw new ClientException(sprintf(_('%1$s has no access to notice %2$d.'),
465 $profile->nickname, $reply->id), 403);
468 $notice->reply_to = $reply->id;
469 $notice->conversation = $reply->conversation;
471 // If the original is private to a group, and notice has no group specified,
472 // make it to the same group(s)
474 if (empty($groups) && ($reply->scope | Notice::GROUP_SCOPE)) {
476 $replyGroups = $reply->getGroups();
477 foreach ($replyGroups as $group) {
478 if ($profile->isMember($group)) {
479 $groups[] = $group->id;
488 if (!empty($lat) && !empty($lon)) {
493 if (!empty($location_ns) && !empty($location_id)) {
494 $notice->location_id = $location_id;
495 $notice->location_ns = $location_ns;
498 if (!empty($rendered)) {
499 $notice->rendered = $rendered;
501 $notice->rendered = common_render_content($final, $notice);
505 if (!empty($notice->repeat_of)) {
506 $notice->verb = ActivityVerb::SHARE;
507 $notice->object_type = ActivityVerb::ACTIVITY;
509 $notice->verb = ActivityVerb::POST;
512 $notice->verb = $verb;
515 if (empty($object_type)) {
516 $notice->object_type = (empty($notice->reply_to)) ? ActivityObject::NOTE : ActivityObject::COMMENT;
518 $notice->object_type = $object_type;
521 if (is_null($scope)) { // 0 is a valid value
522 if (!empty($reply)) {
523 $notice->scope = $reply->scope;
525 $notice->scope = self::defaultScope();
528 $notice->scope = $scope;
531 // For private streams
533 $user = $profile->getUser();
536 if ($user->private_stream &&
537 ($notice->scope == Notice::PUBLIC_SCOPE ||
538 $notice->scope == Notice::SITE_SCOPE)) {
539 $notice->scope |= Notice::FOLLOWER_SCOPE;
543 // Force the scope for private groups
545 foreach ($groups as $groupId) {
546 $group = User_group::staticGet('id', $groupId);
547 if (!empty($group)) {
548 if ($group->force_scope) {
549 $notice->scope |= Notice::GROUP_SCOPE;
555 if (Event::handle('StartNoticeSave', array(&$notice))) {
557 // XXX: some of these functions write to the DB
559 $id = $notice->insert();
562 common_log_db_error($notice, 'INSERT', __FILE__);
563 // TRANS: Server exception thrown when a notice cannot be saved.
564 throw new ServerException(_('Problem saving notice.'));
567 // Update ID-dependent columns: URI, conversation
569 $orig = clone($notice);
574 $notice->uri = common_notice_uri($notice);
578 // If it's not part of a conversation, it's
579 // the beginning of a new conversation.
581 if (empty($notice->conversation)) {
582 $conv = Conversation::create();
583 $notice->conversation = $conv->id;
588 if (!$notice->update($orig)) {
589 common_log_db_error($notice, 'UPDATE', __FILE__);
590 // TRANS: Server exception thrown when a notice cannot be updated.
591 throw new ServerException(_('Problem saving notice.'));
597 // Clear the cache for subscribed users, so they'll update at next request
598 // XXX: someone clever could prepend instead of clearing the cache
600 $notice->blowOnInsert();
602 // Save per-notice metadata...
604 if (isset($replies)) {
605 $notice->saveKnownReplies($replies);
607 $notice->saveReplies();
611 $notice->saveKnownTags($tags);
616 // Note: groups may save tags, so must be run after tags are saved
617 // to avoid errors on duplicates.
618 // Note: groups should always be set.
620 $notice->saveKnownGroups($groups);
623 $notice->saveKnownUrls($urls);
629 // Prepare inbox delivery, may be queued to background.
630 $notice->distribute();
636 function blowOnInsert($conversation = false)
638 $this->blowStream('profile:notice_ids:%d', $this->profile_id);
640 if ($this->isPublic()) {
641 $this->blowStream('public');
644 self::blow('notice:list-ids:conversation:%s', $this->conversation);
645 self::blow('conversation::notice_count:%d', $this->conversation);
647 if (!empty($this->repeat_of)) {
648 // XXX: we should probably only use one of these
649 $this->blowStream('notice:repeats:%d', $this->repeat_of);
650 self::blow('notice:list-ids:repeat_of:%d', $this->repeat_of);
653 $original = Notice::staticGet('id', $this->repeat_of);
655 if (!empty($original)) {
656 $originalUser = User::staticGet('id', $original->profile_id);
657 if (!empty($originalUser)) {
658 $this->blowStream('user:repeats_of_me:%d', $originalUser->id);
662 $profile = Profile::staticGet($this->profile_id);
664 if (!empty($profile)) {
665 $profile->blowNoticeCount();
668 $ptags = $this->getProfileTags();
669 foreach ($ptags as $ptag) {
670 $ptag->blowNoticeStreamCache();
675 * Clear cache entries related to this notice at delete time.
676 * Necessary to avoid breaking paging on public, profile timelines.
678 function blowOnDelete()
680 $this->blowOnInsert();
682 self::blow('profile:notice_ids:%d;last', $this->profile_id);
684 if ($this->isPublic()) {
685 self::blow('public;last');
688 self::blow('fave:by_notice', $this->id);
690 if ($this->conversation) {
691 // In case we're the first, will need to calc a new root.
692 self::blow('notice:conversation_root:%d', $this->conversation);
695 $ptags = $this->getProfileTags();
696 foreach ($ptags as $ptag) {
697 $ptag->blowNoticeStreamCache(true);
701 function blowStream()
703 $c = self::memcache();
709 $args = func_get_args();
711 $format = array_shift($args);
713 $keyPart = vsprintf($format, $args);
715 $cacheKey = Cache::key($keyPart);
717 $c->delete($cacheKey);
719 // delete the "last" stream, too, if this notice is
720 // older than the top of that stream
722 $lastKey = $cacheKey.';last';
724 $lastStr = $c->get($lastKey);
726 if ($lastStr !== false) {
727 $window = explode(',', $lastStr);
728 $lastID = $window[0];
729 $lastNotice = Notice::staticGet('id', $lastID);
730 if (empty($lastNotice) // just weird
731 || strtotime($lastNotice->created) >= strtotime($this->created)) {
732 $c->delete($lastKey);
737 /** save all urls in the notice to the db
739 * follow redirects and save all available file information
740 * (mimetype, date, size, oembed, etc.)
744 function saveUrls() {
745 if (common_config('attachments', 'process_links')) {
746 common_replace_urls_callback($this->content, array($this, 'saveUrl'), $this->id);
751 * Save the given URLs as related links/attachments to the db
753 * follow redirects and save all available file information
754 * (mimetype, date, size, oembed, etc.)
758 function saveKnownUrls($urls)
760 if (common_config('attachments', 'process_links')) {
761 // @fixme validation?
762 foreach (array_unique($urls) as $url) {
763 File::processNew($url, $this->id);
771 function saveUrl($url, $notice_id) {
772 File::processNew($url, $notice_id);
775 static function checkDupes($profile_id, $content) {
776 $profile = Profile::staticGet($profile_id);
777 if (empty($profile)) {
780 $notice = $profile->getNotices(0, CachingNoticeStream::CACHE_WINDOW);
781 if (!empty($notice)) {
783 while ($notice->fetch()) {
784 if (time() - strtotime($notice->created) >= common_config('site', 'dupelimit')) {
786 } else if ($notice->content == $content) {
791 // If we get here, oldest item in cache window is not
792 // old enough for dupe limit; do direct check against DB
793 $notice = new Notice();
794 $notice->profile_id = $profile_id;
795 $notice->content = $content;
796 $threshold = common_sql_date(time() - common_config('site', 'dupelimit'));
797 $notice->whereAdd(sprintf("created > '%s'", $notice->escape($threshold)));
799 $cnt = $notice->count();
803 static function checkEditThrottle($profile_id) {
804 $profile = Profile::staticGet($profile_id);
805 if (empty($profile)) {
808 // Get the Nth notice
809 $notice = $profile->getNotices(common_config('throttle', 'count') - 1, 1);
810 if ($notice && $notice->fetch()) {
811 // If the Nth notice was posted less than timespan seconds ago
812 if (time() - strtotime($notice->created) <= common_config('throttle', 'timespan')) {
817 // Either not N notices in the stream, OR the Nth was not posted within timespan seconds
821 protected $_attachments = -1;
823 function attachments() {
825 if ($this->_attachments != -1) {
826 return $this->_attachments;
829 $f2ps = Memcached_DataObject::listGet('File_to_post', 'post_id', array($this->id));
833 foreach ($f2ps[$this->id] as $f2p) {
834 $ids[] = $f2p->file_id;
837 $files = Memcached_DataObject::multiGet('File', 'id', $ids);
839 $this->_attachments = $files->fetchAll();
841 return $this->_attachments;
844 function _setAttachments($attachments)
846 $this->_attachments = $attachments;
849 function publicStream($offset=0, $limit=20, $since_id=0, $max_id=0)
851 $stream = new PublicNoticeStream();
852 return $stream->getNotices($offset, $limit, $since_id, $max_id);
856 function conversationStream($id, $offset=0, $limit=20, $since_id=0, $max_id=0)
858 $stream = new ConversationNoticeStream($id);
860 return $stream->getNotices($offset, $limit, $since_id, $max_id);
864 * Is this notice part of an active conversation?
866 * @return boolean true if other messages exist in the same
867 * conversation, false if this is the only one
869 function hasConversation()
871 if (!empty($this->conversation)) {
872 $conversation = Notice::conversationStream(
878 if ($conversation->N > 0) {
886 * Grab the earliest notice from this conversation.
888 * @return Notice or null
890 function conversationRoot($profile=-1)
892 // XXX: can this happen?
894 if (empty($this->conversation)) {
898 // Get the current profile if not specified
900 if (is_int($profile) && $profile == -1) {
901 $profile = Profile::current();
904 // If this notice is out of scope, no root for you!
906 if (!$this->inScope($profile)) {
910 // If this isn't a reply to anything, then it's its own
913 if (empty($this->reply_to)) {
917 if (is_null($profile)) {
918 $keypart = sprintf('notice:conversation_root:%d:null', $this->id);
920 $keypart = sprintf('notice:conversation_root:%d:%d',
925 $root = self::cacheGet($keypart);
927 if ($root !== false && $root->inScope($profile)) {
933 $parent = $last->getOriginal();
934 if (!empty($parent) && $parent->inScope($profile)) {
941 } while (!empty($parent));
943 self::cacheSet($keypart, $root);
950 * Pull up a full list of local recipients who will be getting
951 * this notice in their inbox. Results will be cached, so don't
952 * change the input data wily-nilly!
954 * @param array $groups optional list of Group objects;
955 * if left empty, will be loaded from group_inbox records
956 * @param array $recipient optional list of reply profile ids
957 * if left empty, will be loaded from reply records
958 * @return array associating recipient user IDs with an inbox source constant
960 function whoGets($groups=null, $recipients=null)
962 $c = self::memcache();
965 $ni = $c->get(Cache::key('notice:who_gets:'.$this->id));
971 if (is_null($groups)) {
972 $groups = $this->getGroups();
975 if (is_null($recipients)) {
976 $recipients = $this->getReplies();
979 $users = $this->getSubscribedUsers();
980 $ptags = $this->getProfileTags();
982 // FIXME: kind of ignoring 'transitional'...
983 // we'll probably stop supporting inboxless mode
988 // Give plugins a chance to add folks in at start...
989 if (Event::handle('StartNoticeWhoGets', array($this, &$ni))) {
991 foreach ($users as $id) {
992 $ni[$id] = NOTICE_INBOX_SOURCE_SUB;
995 foreach ($groups as $group) {
996 $users = $group->getUserMembers();
997 foreach ($users as $id) {
998 if (!array_key_exists($id, $ni)) {
999 $ni[$id] = NOTICE_INBOX_SOURCE_GROUP;
1004 foreach ($ptags as $ptag) {
1005 $users = $ptag->getUserSubscribers();
1006 foreach ($users as $id) {
1007 if (!array_key_exists($id, $ni)) {
1008 $user = User::staticGet('id', $id);
1009 if (!$user->hasBlocked($profile)) {
1010 $ni[$id] = NOTICE_INBOX_SOURCE_PROFILE_TAG;
1016 foreach ($recipients as $recipient) {
1017 if (!array_key_exists($recipient, $ni)) {
1018 $ni[$recipient] = NOTICE_INBOX_SOURCE_REPLY;
1021 // Exclude any deleted, non-local, or blocking recipients.
1022 $profile = $this->getProfile();
1023 $originalProfile = null;
1024 if ($this->repeat_of) {
1025 // Check blocks against the original notice's poster as well.
1026 $original = Notice::staticGet('id', $this->repeat_of);
1028 $originalProfile = $original->getProfile();
1031 foreach ($ni as $id => $source) {
1032 $user = User::staticGet('id', $id);
1033 if (empty($user) || $user->hasBlocked($profile) ||
1034 ($originalProfile && $user->hasBlocked($originalProfile))) {
1040 // Give plugins a chance to filter out...
1041 Event::handle('EndNoticeWhoGets', array($this, &$ni));
1045 // XXX: pack this data better
1046 $c->set(Cache::key('notice:who_gets:'.$this->id), $ni);
1053 * Adds this notice to the inboxes of each local user who should receive
1054 * it, based on author subscriptions, group memberships, and @-replies.
1056 * Warning: running a second time currently will make items appear
1057 * multiple times in users' inboxes.
1059 * @fixme make more robust against errors
1060 * @fixme break up massive deliveries to smaller background tasks
1062 * @param array $groups optional list of Group objects;
1063 * if left empty, will be loaded from group_inbox records
1064 * @param array $recipient optional list of reply profile ids
1065 * if left empty, will be loaded from reply records
1067 function addToInboxes($groups=null, $recipients=null)
1069 $ni = $this->whoGets($groups, $recipients);
1071 $ids = array_keys($ni);
1073 // We remove the author (if they're a local user),
1074 // since we'll have already done this in distribute()
1076 $i = array_search($this->profile_id, $ids);
1084 Inbox::bulkInsert($this->id, $ids);
1089 function getSubscribedUsers()
1093 if(common_config('db','quote_identifiers'))
1094 $user_table = '"user"';
1095 else $user_table = 'user';
1099 'FROM '. $user_table .' JOIN subscription '.
1100 'ON '. $user_table .'.id = subscription.subscriber ' .
1101 'WHERE subscription.subscribed = %d ';
1103 $user->query(sprintf($qry, $this->profile_id));
1107 while ($user->fetch()) {
1116 function getProfileTags()
1118 $profile = $this->getProfile();
1119 $list = $profile->getOtherTags($profile);
1122 while($list->fetch()) {
1123 $ptags[] = clone($list);
1130 * Record this notice to the given group inboxes for delivery.
1131 * Overrides the regular parsing of !group markup.
1133 * @param string $group_ids
1134 * @fixme might prefer URIs as identifiers, as for replies?
1135 * best with generalizations on user_group to support
1136 * remote groups better.
1138 function saveKnownGroups($group_ids)
1140 if (!is_array($group_ids)) {
1141 // TRANS: Server exception thrown when no array is provided to the method saveKnownGroups().
1142 throw new ServerException(_('Bad type provided to saveKnownGroups.'));
1146 foreach (array_unique($group_ids) as $id) {
1147 $group = User_group::staticGet('id', $id);
1149 common_log(LOG_ERR, "Local delivery to group id $id, $group->nickname");
1150 $result = $this->addToGroupInbox($group);
1152 common_log_db_error($gi, 'INSERT', __FILE__);
1155 if (common_config('group', 'addtag')) {
1156 // we automatically add a tag for every group name, too
1158 $tag = Notice_tag::pkeyGet(array('tag' => common_canonical_tag($group->nickname),
1159 'notice_id' => $this->id));
1161 if (is_null($tag)) {
1162 $this->saveTag($group->nickname);
1166 $groups[] = clone($group);
1168 common_log(LOG_ERR, "Local delivery to group id $id skipped, doesn't exist");
1176 * Parse !group delivery and record targets into group_inbox.
1177 * @return array of Group objects
1179 function saveGroups()
1181 // Don't save groups for repeats
1183 if (!empty($this->repeat_of)) {
1187 $profile = $this->getProfile();
1189 $groups = self::groupsFromText($this->content, $profile);
1191 /* Add them to the database */
1193 foreach ($groups as $group) {
1194 /* XXX: remote groups. */
1196 if (empty($group)) {
1201 if ($profile->isMember($group)) {
1203 $result = $this->addToGroupInbox($group);
1206 common_log_db_error($gi, 'INSERT', __FILE__);
1209 $groups[] = clone($group);
1216 function addToGroupInbox($group)
1218 $gi = Group_inbox::pkeyGet(array('group_id' => $group->id,
1219 'notice_id' => $this->id));
1223 $gi = new Group_inbox();
1225 $gi->group_id = $group->id;
1226 $gi->notice_id = $this->id;
1227 $gi->created = $this->created;
1229 $result = $gi->insert();
1232 common_log_db_error($gi, 'INSERT', __FILE__);
1233 // TRANS: Server exception thrown when an update for a group inbox fails.
1234 throw new ServerException(_('Problem saving group inbox.'));
1237 self::blow('user_group:notice_ids:%d', $gi->group_id);
1244 * Save reply records indicating that this notice needs to be
1245 * delivered to the local users with the given URIs.
1247 * Since this is expected to be used when saving foreign-sourced
1248 * messages, we won't deliver to any remote targets as that's the
1249 * source service's responsibility.
1251 * Mail notifications etc will be handled later.
1253 * @param array of unique identifier URIs for recipients
1255 function saveKnownReplies($uris)
1261 $sender = Profile::staticGet($this->profile_id);
1263 foreach (array_unique($uris) as $uri) {
1265 $profile = Profile::fromURI($uri);
1267 if (empty($profile)) {
1268 common_log(LOG_WARNING, "Unable to determine profile for URI '$uri'");
1272 if ($profile->hasBlocked($sender)) {
1273 common_log(LOG_INFO, "Not saving reply to profile {$profile->id} ($uri) from sender {$sender->id} because of a block.");
1277 $this->saveReply($profile->id);
1278 self::blow('reply:stream:%d', $profile->id);
1285 * Pull @-replies from this message's content in StatusNet markup format
1286 * and save reply records indicating that this message needs to be
1287 * delivered to those users.
1289 * Mail notifications to local profiles will be sent later.
1291 * @return array of integer profile IDs
1294 function saveReplies()
1296 // Don't save reply data for repeats
1298 if (!empty($this->repeat_of)) {
1302 $sender = Profile::staticGet($this->profile_id);
1306 // If it's a reply, save for the replied-to author
1308 if (!empty($this->reply_to)) {
1309 $original = $this->getOriginal();
1310 if (!empty($original)) { // that'd be weird
1311 $author = $original->getProfile();
1312 if (!empty($author)) {
1313 $this->saveReply($author->id);
1314 $replied[$author->id] = 1;
1315 self::blow('reply:stream:%d', $author->id);
1320 // @todo ideally this parser information would only
1321 // be calculated once.
1323 $mentions = common_find_mentions($this->content, $this);
1325 // store replied only for first @ (what user/notice what the reply directed,
1326 // we assume first @ is it)
1328 foreach ($mentions as $mention) {
1330 foreach ($mention['mentioned'] as $mentioned) {
1332 // skip if they're already covered
1334 if (!empty($replied[$mentioned->id])) {
1338 // Don't save replies from blocked profile to local user
1340 $mentioned_user = User::staticGet('id', $mentioned->id);
1341 if (!empty($mentioned_user) && $mentioned_user->hasBlocked($sender)) {
1345 $this->saveReply($mentioned->id);
1346 $replied[$mentioned->id] = 1;
1347 self::blow('reply:stream:%d', $mentioned->id);
1351 $recipientIds = array_keys($replied);
1353 return $recipientIds;
1356 function saveReply($profileId)
1358 $reply = new Reply();
1360 $reply->notice_id = $this->id;
1361 $reply->profile_id = $profileId;
1362 $reply->modified = $this->created;
1369 protected $_replies = -1;
1372 * Pull the complete list of @-reply targets for this notice.
1374 * @return array of integer profile ids
1376 function getReplies()
1378 if ($this->_replies != -1) {
1379 return $this->_replies;
1382 $replyMap = Memcached_DataObject::listGet('Reply', 'notice_id', array($this->id));
1386 foreach ($replyMap[$this->id] as $reply) {
1387 $ids[] = $reply->profile_id;
1390 $this->_replies = $ids;
1395 function _setReplies($replies)
1397 $this->_replies = $replies;
1401 * Pull the complete list of @-reply targets for this notice.
1403 * @return array of Profiles
1405 function getReplyProfiles()
1407 $ids = $this->getReplies();
1409 $profiles = Profile::multiGet('id', $ids);
1411 return $profiles->fetchAll();
1415 * Send e-mail notifications to local @-reply targets.
1417 * Replies must already have been saved; this is expected to be run
1418 * from the distrib queue handler.
1420 function sendReplyNotifications()
1422 // Don't send reply notifications for repeats
1424 if (!empty($this->repeat_of)) {
1428 $recipientIds = $this->getReplies();
1430 foreach ($recipientIds as $recipientId) {
1431 $user = User::staticGet('id', $recipientId);
1432 if (!empty($user)) {
1433 mail_notify_attn($user, $this);
1439 * Pull list of groups this notice needs to be delivered to,
1440 * as previously recorded by saveGroups() or saveKnownGroups().
1442 * @return array of Group objects
1445 protected $_groups = -1;
1447 function getGroups()
1449 // Don't save groups for repeats
1451 if (!empty($this->repeat_of)) {
1455 if ($this->_groups != -1)
1457 return $this->_groups;
1460 $gis = Memcached_DataObject::listGet('Group_inbox', 'notice_id', array($this->id));
1464 foreach ($gis[$this->id] as $gi)
1466 $ids[] = $gi->group_id;
1469 $groups = User_group::multiGet('id', $ids);
1471 $this->_groups = $groups->fetchAll();
1473 return $this->_groups;
1476 function _setGroups($groups)
1478 $this->_groups = $groups;
1482 * Convert a notice into an activity for export.
1484 * @param User $cur Current user
1486 * @return Activity activity object representing this Notice.
1489 function asActivity($cur)
1491 $act = self::cacheGet(Cache::codeKey('notice:as-activity:'.$this->id));
1496 $act = new Activity();
1498 if (Event::handle('StartNoticeAsActivity', array($this, &$act))) {
1500 $act->id = $this->uri;
1501 $act->time = strtotime($this->created);
1502 $act->link = $this->bestUrl();
1503 $act->content = common_xml_safe_str($this->rendered);
1504 $act->title = common_xml_safe_str($this->content);
1506 $profile = $this->getProfile();
1508 $act->actor = ActivityObject::fromProfile($profile);
1509 $act->actor->extra[] = $profile->profileInfo($cur);
1511 $act->verb = $this->verb;
1513 if ($this->repeat_of) {
1514 $repeated = Notice::staticGet('id', $this->repeat_of);
1515 $act->objects[] = $repeated->asActivity($cur);
1517 $act->objects[] = ActivityObject::fromNotice($this);
1520 // XXX: should this be handled by default processing for object entry?
1524 $tags = $this->getTags();
1526 foreach ($tags as $tag) {
1527 $cat = new AtomCategory();
1530 $act->categories[] = $cat;
1534 // XXX: use Atom Media and/or File activity objects instead
1536 $attachments = $this->attachments();
1538 foreach ($attachments as $attachment) {
1539 $enclosure = $attachment->getEnclosure();
1541 $act->enclosures[] = $enclosure;
1545 $ctx = new ActivityContext();
1547 if (!empty($this->reply_to)) {
1548 $reply = Notice::staticGet('id', $this->reply_to);
1549 if (!empty($reply)) {
1550 $ctx->replyToID = $reply->uri;
1551 $ctx->replyToUrl = $reply->bestUrl();
1555 $ctx->location = $this->getLocation();
1559 if (!empty($this->conversation)) {
1560 $conv = Conversation::staticGet('id', $this->conversation);
1561 if (!empty($conv)) {
1562 $ctx->conversation = $conv->uri;
1566 $reply_ids = $this->getReplies();
1568 foreach ($reply_ids as $id) {
1569 $rprofile = Profile::staticGet('id', $id);
1570 if (!empty($rprofile)) {
1571 $ctx->attention[] = $rprofile->getUri();
1575 $groups = $this->getGroups();
1577 foreach ($groups as $group) {
1578 $ctx->attention[] = $group->getUri();
1581 // XXX: deprecated; use ActivityVerb::SHARE instead
1585 if (!empty($this->repeat_of)) {
1586 $repeat = Notice::staticGet('id', $this->repeat_of);
1587 $ctx->forwardID = $repeat->uri;
1588 $ctx->forwardUrl = $repeat->bestUrl();
1591 $act->context = $ctx;
1595 $atom_feed = $profile->getAtomFeed();
1597 if (!empty($atom_feed)) {
1599 $act->source = new ActivitySource();
1601 // XXX: we should store the actual feed ID
1603 $act->source->id = $atom_feed;
1605 // XXX: we should store the actual feed title
1607 $act->source->title = $profile->getBestName();
1609 $act->source->links['alternate'] = $profile->profileurl;
1610 $act->source->links['self'] = $atom_feed;
1612 $act->source->icon = $profile->avatarUrl(AVATAR_PROFILE_SIZE);
1614 $notice = $profile->getCurrentNotice();
1616 if (!empty($notice)) {
1617 $act->source->updated = self::utcDate($notice->created);
1620 $user = User::staticGet('id', $profile->id);
1622 if (!empty($user)) {
1623 $act->source->links['license'] = common_config('license', 'url');
1627 if ($this->isLocal()) {
1628 $act->selfLink = common_local_url('ApiStatusesShow', array('id' => $this->id,
1629 'format' => 'atom'));
1630 $act->editLink = $act->selfLink;
1633 Event::handle('EndNoticeAsActivity', array($this, &$act));
1636 self::cacheSet(Cache::codeKey('notice:as-activity:'.$this->id), $act);
1641 // This has gotten way too long. Needs to be sliced up into functional bits
1642 // or ideally exported to a utility class.
1644 function asAtomEntry($namespace=false,
1649 $act = $this->asActivity($cur);
1650 $act->extra[] = $this->noticeInfo($cur);
1651 return $act->asString($namespace, $author, $source);
1655 * Extra notice info for atom entries
1657 * Clients use some extra notice info in the atom stream.
1658 * This gives it to them.
1660 * @param User $cur Current user
1662 * @return array representation of <statusnet:notice_info> element
1665 function noticeInfo($cur)
1667 // local notice ID (useful to clients for ordering)
1669 $noticeInfoAttr = array('local_id' => $this->id);
1673 $ns = $this->getSource();
1676 $noticeInfoAttr['source'] = $ns->code;
1677 if (!empty($ns->url)) {
1678 $noticeInfoAttr['source_link'] = $ns->url;
1679 if (!empty($ns->name)) {
1680 $noticeInfoAttr['source'] = '<a href="'
1681 . htmlspecialchars($ns->url)
1682 . '" rel="nofollow">'
1683 . htmlspecialchars($ns->name)
1689 // favorite and repeated
1692 $noticeInfoAttr['favorite'] = ($cur->hasFave($this)) ? "true" : "false";
1693 $cp = $cur->getProfile();
1694 $noticeInfoAttr['repeated'] = ($cp->hasRepeated($this->id)) ? "true" : "false";
1697 if (!empty($this->repeat_of)) {
1698 $noticeInfoAttr['repeat_of'] = $this->repeat_of;
1701 return array('statusnet:notice_info', $noticeInfoAttr, null);
1705 * Returns an XML string fragment with a reference to a notice as an
1706 * Activity Streams noun object with the given element type.
1708 * Assumes that 'activity' namespace has been previously defined.
1710 * @param string $element one of 'subject', 'object', 'target'
1714 function asActivityNoun($element)
1716 $noun = ActivityObject::fromNotice($this);
1717 return $noun->asString('activity:' . $element);
1722 if (!empty($this->url)) {
1724 } else if (!empty($this->uri) && preg_match('/^https?:/', $this->uri)) {
1727 return common_local_url('shownotice',
1728 array('notice' => $this->id));
1734 * Determine which notice, if any, a new notice is in reply to.
1736 * For conversation tracking, we try to see where this notice fits
1737 * in the tree. Rough algorithm is:
1739 * if (reply_to is set and valid) {
1741 * } else if ((source not API or Web) and (content starts with "T NAME" or "@name ")) {
1742 * return ID of last notice by initial @name in content;
1745 * Note that all @nickname instances will still be used to save "reply" records,
1746 * so the notice shows up in the mentioned users' "replies" tab.
1748 * @param integer $reply_to ID passed in by Web or API
1749 * @param integer $profile_id ID of author
1750 * @param string $source Source tag, like 'web' or 'gwibber'
1751 * @param string $content Final notice content
1753 * @return integer ID of replied-to notice, or null for not a reply.
1756 static function getReplyTo($reply_to, $profile_id, $source, $content)
1758 static $lb = array('xmpp', 'mail', 'sms', 'omb');
1760 // If $reply_to is specified, we check that it exists, and then
1761 // return it if it does
1763 if (!empty($reply_to)) {
1764 $reply_notice = Notice::staticGet('id', $reply_to);
1765 if (!empty($reply_notice)) {
1766 return $reply_notice;
1770 // If it's not a "low bandwidth" source (one where you can't set
1771 // a reply_to argument), we return. This is mostly web and API
1774 if (!in_array($source, $lb)) {
1778 // Is there an initial @ or T?
1780 if (preg_match('/^T ([A-Z0-9]{1,64}) /', $content, $match) ||
1781 preg_match('/^@([a-z0-9]{1,64})\s+/', $content, $match)) {
1782 $nickname = common_canonical_nickname($match[1]);
1787 // Figure out who that is.
1789 $sender = Profile::staticGet('id', $profile_id);
1790 if (empty($sender)) {
1794 $recipient = common_relative_profile($sender, $nickname, common_sql_now());
1796 if (empty($recipient)) {
1800 // Get their last notice
1802 $last = $recipient->getCurrentNotice();
1804 if (!empty($last)) {
1811 static function maxContent()
1813 $contentlimit = common_config('notice', 'contentlimit');
1814 // null => use global limit (distinct from 0!)
1815 if (is_null($contentlimit)) {
1816 $contentlimit = common_config('site', 'textlimit');
1818 return $contentlimit;
1821 static function contentTooLong($content)
1823 $contentlimit = self::maxContent();
1824 return ($contentlimit > 0 && !empty($content) && (mb_strlen($content) > $contentlimit));
1827 function getLocation()
1831 if (!empty($this->location_id) && !empty($this->location_ns)) {
1832 $location = Location::fromId($this->location_id, $this->location_ns);
1835 if (is_null($location)) { // no ID, or Location::fromId() failed
1836 if (!empty($this->lat) && !empty($this->lon)) {
1837 $location = Location::fromLatLon($this->lat, $this->lon);
1845 * Convenience function for posting a repeat of an existing message.
1847 * @param int $repeater_id: profile ID of user doing the repeat
1848 * @param string $source: posting source key, eg 'web', 'api', etc
1851 * @throws Exception on failure or permission problems
1853 function repeat($repeater_id, $source)
1855 $author = Profile::staticGet('id', $this->profile_id);
1857 // TRANS: Message used to repeat a notice. RT is the abbreviation of 'retweet'.
1858 // TRANS: %1$s is the repeated user's name, %2$s is the repeated notice.
1859 $content = sprintf(_('RT @%1$s %2$s'),
1863 $maxlen = common_config('site', 'textlimit');
1864 if ($maxlen > 0 && mb_strlen($content) > $maxlen) {
1865 // Web interface and current Twitter API clients will
1866 // pull the original notice's text, but some older
1867 // clients and RSS/Atom feeds will see this trimmed text.
1869 // Unfortunately this is likely to lose tags or URLs
1870 // at the end of long notices.
1871 $content = mb_substr($content, 0, $maxlen - 4) . ' ...';
1874 // Scope is same as this one's
1876 return self::saveNew($repeater_id,
1879 array('repeat_of' => $this->id,
1880 'scope' => $this->scope));
1883 // These are supposed to be in chron order!
1885 function repeatStream($limit=100)
1887 $cache = Cache::instance();
1889 if (empty($cache)) {
1890 $ids = $this->_repeatStreamDirect($limit);
1892 $idstr = $cache->get(Cache::key('notice:repeats:'.$this->id));
1893 if ($idstr !== false) {
1894 if (empty($idstr)) {
1897 $ids = explode(',', $idstr);
1900 $ids = $this->_repeatStreamDirect(100);
1901 $cache->set(Cache::key('notice:repeats:'.$this->id), implode(',', $ids));
1904 // We do a max of 100, so slice down to limit
1905 $ids = array_slice($ids, 0, $limit);
1909 return NoticeStream::getStreamByIds($ids);
1912 function _repeatStreamDirect($limit)
1914 $notice = new Notice();
1916 $notice->selectAdd(); // clears it
1917 $notice->selectAdd('id');
1919 $notice->repeat_of = $this->id;
1921 $notice->orderBy('created, id'); // NB: asc!
1923 if (!is_null($limit)) {
1924 $notice->limit(0, $limit);
1927 return $notice->fetchAll('id');
1930 function locationOptions($lat, $lon, $location_id, $location_ns, $profile = null)
1934 if (!empty($location_id) && !empty($location_ns)) {
1935 $options['location_id'] = $location_id;
1936 $options['location_ns'] = $location_ns;
1938 $location = Location::fromId($location_id, $location_ns);
1940 if (!empty($location)) {
1941 $options['lat'] = $location->lat;
1942 $options['lon'] = $location->lon;
1945 } else if (!empty($lat) && !empty($lon)) {
1946 $options['lat'] = $lat;
1947 $options['lon'] = $lon;
1949 $location = Location::fromLatLon($lat, $lon);
1951 if (!empty($location)) {
1952 $options['location_id'] = $location->location_id;
1953 $options['location_ns'] = $location->location_ns;
1955 } else if (!empty($profile)) {
1956 if (isset($profile->lat) && isset($profile->lon)) {
1957 $options['lat'] = $profile->lat;
1958 $options['lon'] = $profile->lon;
1961 if (isset($profile->location_id) && isset($profile->location_ns)) {
1962 $options['location_id'] = $profile->location_id;
1963 $options['location_ns'] = $profile->location_ns;
1970 function clearReplies()
1972 $replyNotice = new Notice();
1973 $replyNotice->reply_to = $this->id;
1975 //Null any notices that are replies to this notice
1977 if ($replyNotice->find()) {
1978 while ($replyNotice->fetch()) {
1979 $orig = clone($replyNotice);
1980 $replyNotice->reply_to = null;
1981 $replyNotice->update($orig);
1987 $reply = new Reply();
1988 $reply->notice_id = $this->id;
1990 if ($reply->find()) {
1991 while($reply->fetch()) {
1992 self::blow('reply:stream:%d', $reply->profile_id);
2000 function clearFiles()
2002 $f2p = new File_to_post();
2004 $f2p->post_id = $this->id;
2007 while ($f2p->fetch()) {
2011 // FIXME: decide whether to delete File objects
2012 // ...and related (actual) files
2015 function clearRepeats()
2017 $repeatNotice = new Notice();
2018 $repeatNotice->repeat_of = $this->id;
2020 //Null any notices that are repeats of this notice
2022 if ($repeatNotice->find()) {
2023 while ($repeatNotice->fetch()) {
2024 $orig = clone($repeatNotice);
2025 $repeatNotice->repeat_of = null;
2026 $repeatNotice->update($orig);
2031 function clearFaves()
2034 $fave->notice_id = $this->id;
2036 if ($fave->find()) {
2037 while ($fave->fetch()) {
2038 self::blow('fave:ids_by_user_own:%d', $fave->user_id);
2039 self::blow('fave:ids_by_user_own:%d;last', $fave->user_id);
2040 self::blow('fave:ids_by_user:%d', $fave->user_id);
2041 self::blow('fave:ids_by_user:%d;last', $fave->user_id);
2049 function clearTags()
2051 $tag = new Notice_tag();
2052 $tag->notice_id = $this->id;
2055 while ($tag->fetch()) {
2056 self::blow('profile:notice_ids_tagged:%d:%s', $this->profile_id, Cache::keyize($tag->tag));
2057 self::blow('profile:notice_ids_tagged:%d:%s;last', $this->profile_id, Cache::keyize($tag->tag));
2058 self::blow('notice_tag:notice_ids:%s', Cache::keyize($tag->tag));
2059 self::blow('notice_tag:notice_ids:%s;last', Cache::keyize($tag->tag));
2067 function clearGroupInboxes()
2069 $gi = new Group_inbox();
2071 $gi->notice_id = $this->id;
2074 while ($gi->fetch()) {
2075 self::blow('user_group:notice_ids:%d', $gi->group_id);
2083 function distribute()
2085 // We always insert for the author so they don't
2087 Event::handle('StartNoticeDistribute', array($this));
2089 $user = User::staticGet('id', $this->profile_id);
2090 if (!empty($user)) {
2091 Inbox::insertNotice($user->id, $this->id);
2094 if (common_config('queue', 'inboxes')) {
2095 // If there's a failure, we want to _force_
2096 // distribution at this point.
2098 $qm = QueueManager::get();
2099 $qm->enqueue($this, 'distrib');
2100 } catch (Exception $e) {
2101 // If the exception isn't transient, this
2102 // may throw more exceptions as DQH does
2103 // its own enqueueing. So, we ignore them!
2105 $handler = new DistribQueueHandler();
2106 $handler->handle($this);
2107 } catch (Exception $e) {
2108 common_log(LOG_ERR, "emergency redistribution resulted in " . $e->getMessage());
2110 // Re-throw so somebody smarter can handle it.
2114 $handler = new DistribQueueHandler();
2115 $handler->handle($this);
2121 $result = parent::insert();
2124 // Profile::hasRepeated() abuses pkeyGet(), so we
2125 // have to clear manually
2126 if (!empty($this->repeat_of)) {
2127 $c = self::memcache();
2129 $ck = self::multicacheKey('Notice',
2130 array('profile_id' => $this->profile_id,
2131 'repeat_of' => $this->repeat_of));
2141 * Get the source of the notice
2143 * @return Notice_source $ns A notice source object. 'code' is the only attribute
2144 * guaranteed to be populated.
2146 function getSource()
2148 $ns = new Notice_source();
2149 if (!empty($this->source)) {
2150 switch ($this->source) {
2157 $ns->code = $this->source;
2160 $ns = Notice_source::staticGet($this->source);
2162 $ns = new Notice_source();
2163 $ns->code = $this->source;
2164 $app = Oauth_application::staticGet('name', $this->source);
2166 $ns->name = $app->name;
2167 $ns->url = $app->source_url;
2177 * Determine whether the notice was locally created
2179 * @return boolean locality
2182 public function isLocal()
2184 return ($this->is_local == Notice::LOCAL_PUBLIC ||
2185 $this->is_local == Notice::LOCAL_NONPUBLIC);
2189 * Get the list of hash tags saved with this notice.
2191 * @return array of strings
2193 public function getTags()
2197 $keypart = sprintf('notice:tags:%d', $this->id);
2199 $tagstr = self::cacheGet($keypart);
2201 if ($tagstr !== false) {
2202 $tags = explode(',', $tagstr);
2204 $tag = new Notice_tag();
2205 $tag->notice_id = $this->id;
2207 while ($tag->fetch()) {
2208 $tags[] = $tag->tag;
2211 self::cacheSet($keypart, implode(',', $tags));
2217 static private function utcDate($dt)
2219 $dateStr = date('d F Y H:i:s', strtotime($dt));
2220 $d = new DateTime($dateStr, new DateTimeZone('UTC'));
2221 return $d->format(DATE_W3C);
2225 * Look up the creation timestamp for a given notice ID, even
2226 * if it's been deleted.
2229 * @return mixed string recorded creation timestamp, or false if can't be found
2231 public static function getAsTimestamp($id)
2237 $notice = Notice::staticGet('id', $id);
2239 return $notice->created;
2242 $deleted = Deleted_notice::staticGet('id', $id);
2244 return $deleted->created;
2251 * Build an SQL 'where' fragment for timestamp-based sorting from a since_id
2252 * parameter, matching notices posted after the given one (exclusive).
2254 * If the referenced notice can't be found, will return false.
2257 * @param string $idField
2258 * @param string $createdField
2259 * @return mixed string or false if no match
2261 public static function whereSinceId($id, $idField='id', $createdField='created')
2263 $since = Notice::getAsTimestamp($id);
2265 return sprintf("($createdField = '%s' and $idField > %d) or ($createdField > '%s')", $since, $id, $since);
2271 * Build an SQL 'where' fragment for timestamp-based sorting from a since_id
2272 * parameter, matching notices posted after the given one (exclusive), and
2273 * if necessary add it to the data object's query.
2275 * @param DB_DataObject $obj
2277 * @param string $idField
2278 * @param string $createdField
2279 * @return mixed string or false if no match
2281 public static function addWhereSinceId(DB_DataObject $obj, $id, $idField='id', $createdField='created')
2283 $since = self::whereSinceId($id, $idField, $createdField);
2285 $obj->whereAdd($since);
2290 * Build an SQL 'where' fragment for timestamp-based sorting from a max_id
2291 * parameter, matching notices posted before the given one (inclusive).
2293 * If the referenced notice can't be found, will return false.
2296 * @param string $idField
2297 * @param string $createdField
2298 * @return mixed string or false if no match
2300 public static function whereMaxId($id, $idField='id', $createdField='created')
2302 $max = Notice::getAsTimestamp($id);
2304 return sprintf("($createdField < '%s') or ($createdField = '%s' and $idField <= %d)", $max, $max, $id);
2310 * Build an SQL 'where' fragment for timestamp-based sorting from a max_id
2311 * parameter, matching notices posted before the given one (inclusive), and
2312 * if necessary add it to the data object's query.
2314 * @param DB_DataObject $obj
2316 * @param string $idField
2317 * @param string $createdField
2318 * @return mixed string or false if no match
2320 public static function addWhereMaxId(DB_DataObject $obj, $id, $idField='id', $createdField='created')
2322 $max = self::whereMaxId($id, $idField, $createdField);
2324 $obj->whereAdd($max);
2330 if (common_config('public', 'localonly')) {
2331 return ($this->is_local == Notice::LOCAL_PUBLIC);
2333 return (($this->is_local != Notice::LOCAL_NONPUBLIC) &&
2334 ($this->is_local != Notice::GATEWAY));
2339 * Check that the given profile is allowed to read, respond to, or otherwise
2340 * act on this notice.
2342 * The $scope member is a bitmask of scopes, representing a logical AND of the
2343 * scope requirement. So, 0x03 (Notice::ADDRESSEE_SCOPE | Notice::SITE_SCOPE) means
2344 * "only visible to people who are mentioned in the notice AND are users on this site."
2345 * Users on the site who are not mentioned in the notice will not be able to see the
2348 * @param Profile $profile The profile to check; pass null to check for public/unauthenticated users.
2350 * @return boolean whether the profile is in the notice's scope
2352 function inScope($profile)
2354 if (is_null($profile)) {
2355 $keypart = sprintf('notice:in-scope-for:%d:null', $this->id);
2357 $keypart = sprintf('notice:in-scope-for:%d:%d', $this->id, $profile->id);
2360 $result = self::cacheGet($keypart);
2362 if ($result === false) {
2363 $bResult = $this->_inScope($profile);
2364 $result = ($bResult) ? 1 : 0;
2365 self::cacheSet($keypart, $result, 0, 300);
2368 return ($result == 1) ? true : false;
2371 protected function _inScope($profile)
2373 // If there's no scope, anyone (even anon) is in scope.
2375 if ($this->scope == 0) {
2379 // If there's scope, anon cannot be in scope
2381 if (empty($profile)) {
2385 // Author is always in scope
2387 if ($this->profile_id == $profile->id) {
2391 // Only for users on this site
2393 if ($this->scope & Notice::SITE_SCOPE) {
2394 $user = $profile->getUser();
2400 // Only for users mentioned in the notice
2402 if ($this->scope & Notice::ADDRESSEE_SCOPE) {
2404 $repl = Reply::pkeyGet(array('notice_id' => $this->id,
2405 'profile_id' => $profile->id));
2412 // Only for members of the given group
2414 if ($this->scope & Notice::GROUP_SCOPE) {
2416 // XXX: just query for the single membership
2418 $groups = $this->getGroups();
2422 foreach ($groups as $group) {
2423 if ($profile->isMember($group)) {
2434 // Only for followers of the author
2436 if ($this->scope & Notice::FOLLOWER_SCOPE) {
2437 $author = $this->getProfile();
2438 if (!Subscription::exists($profile, $author)) {
2446 static function groupsFromText($text, $profile)
2450 /* extract all !group */
2451 $count = preg_match_all('/(?:^|\s)!(' . Nickname::DISPLAY_FMT . ')/',
2459 foreach (array_unique($match[1]) as $nickname) {
2460 $group = User_group::getForNickname($nickname, $profile);
2461 if (!empty($group) && $profile->isMember($group)) {
2462 $groups[] = $group->id;
2469 protected $_original = -1;
2471 function getOriginal()
2473 if (is_int($this->_original) && $this->_original == -1) {
2474 if (empty($this->reply_to)) {
2475 $this->_original = null;
2477 $this->_original = Notice::staticGet('id', $this->reply_to);
2480 return $this->_original;
2484 * Magic function called at serialize() time.
2486 * We use this to drop a couple process-specific references
2487 * from DB_DataObject which can cause trouble in future
2490 * @return array of variable names to include in serialization.
2495 $vars = parent::__sleep();
2496 $skip = array('_original', '_profile', '_groups', '_attachments', '_faves', '_replies', '_repeats');
2497 return array_diff($vars, $skip);
2500 static function defaultScope()
2502 $scope = common_config('notice', 'defaultscope');
2503 if (is_null($scope)) {
2504 if (common_config('site', 'private')) {
2513 static function fillProfiles($notices)
2515 $map = self::getProfiles($notices);
2517 foreach ($notices as $notice) {
2518 if (array_key_exists($notice->profile_id, $map)) {
2519 $notice->_setProfile($map[$notice->profile_id]);
2523 return array_values($map);
2526 static function getProfiles(&$notices)
2529 foreach ($notices as $notice) {
2530 $ids[] = $notice->profile_id;
2533 $ids = array_unique($ids);
2535 return Memcached_DataObject::pivotGet('Profile', 'id', $ids);
2538 static function fillGroups(&$notices)
2540 $ids = self::_idsOf($notices);
2542 $gis = Memcached_DataObject::listGet('Group_inbox', 'notice_id', $ids);
2546 foreach ($gis as $id => $gi)
2550 $gids[] = $g->group_id;
2554 $gids = array_unique($gids);
2556 $group = Memcached_DataObject::pivotGet('User_group', 'id', $gids);
2558 foreach ($notices as $notice)
2561 $gi = $gis[$notice->id];
2562 foreach ($gi as $g) {
2563 $grps[] = $group[$g->group_id];
2565 $notice->_setGroups($grps);
2569 static function _idsOf(&$notices)
2572 foreach ($notices as $notice) {
2573 $ids[] = $notice->id;
2575 $ids = array_unique($ids);
2579 static function fillAttachments(&$notices)
2581 $ids = self::_idsOf($notices);
2583 $f2pMap = Memcached_DataObject::listGet('File_to_post', 'post_id', $ids);
2587 foreach ($f2pMap as $noticeId => $f2ps) {
2588 foreach ($f2ps as $f2p) {
2589 $fileIds[] = $f2p->file_id;
2593 $fileIds = array_unique($fileIds);
2595 $fileMap = Memcached_DataObject::pivotGet('File', 'id', $fileIds);
2597 foreach ($notices as $notice)
2600 $f2ps = $f2pMap[$notice->id];
2601 foreach ($f2ps as $f2p) {
2602 $files[] = $fileMap[$f2p->file_id];
2604 $notice->_setAttachments($files);
2611 * All faves of this notice
2613 * @return array Array of Fave objects
2618 if (isset($this->_faves) && is_array($this->_faves)) {
2619 return $this->_faves;
2621 $faveMap = Memcached_DataObject::listGet('Fave', 'notice_id', array($this->id));
2622 $this->_faves = $faveMap[$this->id];
2623 return $this->_faves;
2626 function _setFaves(&$faves)
2628 $this->_faves = $faves;
2631 static function fillFaves(&$notices)
2633 $ids = self::_idsOf($notices);
2634 $faveMap = Memcached_DataObject::listGet('Fave', 'notice_id', $ids);
2637 foreach ($faveMap as $id => $faves) {
2638 $cnt += count($faves);
2639 if (count($faves) > 0) {
2643 foreach ($notices as $notice) {
2644 $notice->_setFaves($faveMap[$notice->id]);
2648 static function fillReplies(&$notices)
2650 $ids = self::_idsOf($notices);
2651 $replyMap = Memcached_DataObject::listGet('Reply', 'notice_id', $ids);
2652 foreach ($notices as $notice) {
2653 $replies = $replyMap[$notice->id];
2655 foreach ($replies as $reply) {
2656 $ids[] = $reply->profile_id;
2658 $notice->_setReplies($ids);
2662 protected $_repeats;
2664 function getRepeats()
2666 if (isset($this->_repeats) && is_array($this->_repeats)) {
2667 return $this->_repeats;
2669 $repeatMap = Memcached_DataObject::listGet('Notice', 'repeat_of', array($this->id));
2670 $this->_repeats = $repeatMap[$this->id];
2671 return $this->_repeats;
2674 function _setRepeats(&$repeats)
2676 $this->_repeats = $repeats;
2679 static function fillRepeats(&$notices)
2681 $ids = self::_idsOf($notices);
2682 $repeatMap = Memcached_DataObject::listGet('Notice', 'repeat_of', $ids);
2683 foreach ($notices as $notice) {
2684 $notice->_setRepeats($repeatMap[$notice->id]);