3 * StatusNet - the distributed open-source microblogging tool
4 * Copyright (C) 2008-2011 StatusNet, Inc.
6 * This program is free software: you can redistribute it and/or modify
7 * it under the terms of the GNU Affero General Public License as published by
8 * the Free Software Foundation, either version 3 of the License, or
9 * (at your option) any later version.
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU Affero General Public License for more details.
16 * You should have received a copy of the GNU Affero General Public License
17 * along with this program. If not, see <http://www.gnu.org/licenses/>.
21 * @author Brenda Wallace <shiny@cpan.org>
22 * @author Christopher Vollick <psycotica0@gmail.com>
23 * @author CiaranG <ciaran@ciarang.com>
24 * @author Craig Andrews <candrews@integralblue.com>
25 * @author Evan Prodromou <evan@controlezvous.ca>
26 * @author Gina Haeussge <osd@foosel.net>
27 * @author Jeffery To <jeffery.to@gmail.com>
28 * @author Mike Cochrane <mikec@mikenz.geek.nz>
29 * @author Robin Millette <millette@controlyourself.ca>
30 * @author Sarven Capadisli <csarven@controlyourself.ca>
31 * @author Tom Adams <tom@holizz.com>
32 * @author Mikael Nordfeldth <mmn@hethane.se>
33 * @copyright 2009 Free Software Foundation, Inc http://www.fsf.org
34 * @license GNU Affero General Public License http://www.gnu.org/licenses/
37 if (!defined('GNUSOCIAL')) { exit(1); }
40 * Table Definition for notice
43 /* We keep 200 notices, the max number of notices available per API request,
44 * in the memcached cache. */
46 define('NOTICE_CACHE_WINDOW', CachingNoticeStream::CACHE_WINDOW);
48 define('MAX_BOXCARS', 128);
50 class Notice extends Managed_DataObject
53 /* the code below is auto generated do not remove the above tag */
55 public $__table = 'notice'; // table name
56 public $id; // int(4) primary_key not_null
57 public $profile_id; // int(4) multiple_key not_null
58 public $uri; // varchar(255) unique_key
59 public $content; // text
60 public $rendered; // text
61 public $url; // varchar(255)
62 public $created; // datetime multiple_key not_null default_0000-00-00%2000%3A00%3A00
63 public $modified; // timestamp not_null default_CURRENT_TIMESTAMP
64 public $reply_to; // int(4)
65 public $is_local; // int(4)
66 public $source; // varchar(32)
67 public $conversation; // int(4)
68 public $lat; // decimal(10,7)
69 public $lon; // decimal(10,7)
70 public $location_id; // int(4)
71 public $location_ns; // int(4)
72 public $repeat_of; // int(4)
73 public $verb; // varchar(255)
74 public $object_type; // varchar(255)
75 public $scope; // int(4)
77 /* the code above is auto generated do not remove the tag below */
80 public static function schemaDef()
84 'id' => array('type' => 'serial', 'not null' => true, 'description' => 'unique identifier'),
85 'profile_id' => array('type' => 'int', 'not null' => true, 'description' => 'who made the update'),
86 'uri' => array('type' => 'varchar', 'length' => 255, 'description' => 'universally unique identifier, usually a tag URI'),
87 'content' => array('type' => 'text', 'description' => 'update content', 'collate' => 'utf8_general_ci'),
88 'rendered' => array('type' => 'text', 'description' => 'HTML version of the content'),
89 'url' => array('type' => 'varchar', 'length' => 255, 'description' => 'URL of any attachment (image, video, bookmark, whatever)'),
90 'created' => array('type' => 'datetime', 'not null' => true, 'description' => 'date this record was created'),
91 'modified' => array('type' => 'timestamp', 'not null' => true, 'description' => 'date this record was modified'),
92 'reply_to' => array('type' => 'int', 'description' => 'notice replied to (usually a guess)'),
93 'is_local' => array('type' => 'int', 'size' => 'tiny', 'default' => 0, 'description' => 'notice was generated by a user'),
94 'source' => array('type' => 'varchar', 'length' => 32, 'description' => 'source of comment, like "web", "im", or "clientname"'),
95 'conversation' => array('type' => 'int', 'description' => 'id of root notice in this conversation'),
96 'lat' => array('type' => 'numeric', 'precision' => 10, 'scale' => 7, 'description' => 'latitude'),
97 'lon' => array('type' => 'numeric', 'precision' => 10, 'scale' => 7, 'description' => 'longitude'),
98 'location_id' => array('type' => 'int', 'description' => 'location id if possible'),
99 'location_ns' => array('type' => 'int', 'description' => 'namespace for location'),
100 'repeat_of' => array('type' => 'int', 'description' => 'notice this is a repeat of'),
101 'object_type' => array('type' => 'varchar', 'length' => 255, 'description' => 'URI representing activity streams object type', 'default' => 'http://activitystrea.ms/schema/1.0/note'),
102 'verb' => array('type' => 'varchar', 'length' => 255, 'description' => 'URI representing activity streams verb', 'default' => 'http://activitystrea.ms/schema/1.0/post'),
103 'scope' => array('type' => 'int',
104 'description' => 'bit map for distribution scope; 0 = everywhere; 1 = this server only; 2 = addressees; 4 = followers; null = default'),
106 'primary key' => array('id'),
107 'unique keys' => array(
108 'notice_uri_key' => array('uri'),
110 'foreign keys' => array(
111 'notice_profile_id_fkey' => array('profile', array('profile_id' => 'id')),
112 'notice_reply_to_fkey' => array('notice', array('reply_to' => 'id')),
113 'notice_conversation_fkey' => array('conversation', array('conversation' => 'id')), # note... used to refer to notice.id
114 'notice_repeat_of_fkey' => array('notice', array('repeat_of' => 'id')), # @fixme: what about repeats of deleted notices?
117 'notice_created_id_is_local_idx' => array('created', 'id', 'is_local'),
118 'notice_profile_id_idx' => array('profile_id', 'created', 'id'),
119 'notice_repeat_of_created_id_idx' => array('repeat_of', 'created', 'id'),
120 'notice_conversation_created_id_idx' => array('conversation', 'created', 'id'),
121 'notice_replyto_idx' => array('reply_to')
125 if (common_config('search', 'type') == 'fulltext') {
126 $def['fulltext indexes'] = array('content' => array('content'));
133 const LOCAL_PUBLIC = 1;
135 const LOCAL_NONPUBLIC = -1;
138 const PUBLIC_SCOPE = 0; // Useful fake constant
139 const SITE_SCOPE = 1;
140 const ADDRESSEE_SCOPE = 2;
141 const GROUP_SCOPE = 4;
142 const FOLLOWER_SCOPE = 8;
144 protected $_profile = -1;
146 public function getProfile()
148 if ($this->_profile === -1) {
149 $this->_setProfile(Profile::getKV('id', $this->profile_id));
151 return $this->_profile;
154 public function _setProfile(Profile $profile=null)
156 if (!$profile instanceof Profile) {
157 throw new NoProfileException($this->profile_id);
159 $this->_profile = $profile;
162 function delete($useWhere=false)
164 // For auditing purposes, save a record that the notice
167 // @fixme we have some cases where things get re-run and so the
169 $deleted = Deleted_notice::getKV('id', $this->id);
171 if (!$deleted instanceof Deleted_notice) {
172 $deleted = Deleted_notice::getKV('uri', $this->uri);
175 if (!$deleted instanceof Deleted_notice) {
176 $deleted = new Deleted_notice();
178 $deleted->id = $this->id;
179 $deleted->profile_id = $this->profile_id;
180 $deleted->uri = $this->uri;
181 $deleted->created = $this->created;
182 $deleted->deleted = common_sql_now();
187 if (Event::handle('NoticeDeleteRelated', array($this))) {
189 // Clear related records
191 $this->clearReplies();
192 $this->clearRepeats();
195 $this->clearGroupInboxes();
197 $this->clearAttentions();
199 // NOTE: we don't clear queue items
202 $result = parent::delete($useWhere);
204 $this->blowOnDelete();
208 public function getUri()
213 public function getUrl()
215 // The risk is we start having empty urls and non-http uris...
216 // and we can't really handle any other protocol right now.
218 case common_valid_http_url($this->url): // should we allow non-http/https URLs?
220 case $this->isLocal():
221 // let's generate a valid link to our locally available notice on demand
222 return common_local_url('shownotice', array('notice' => $this->id), null, null, false);
223 case common_valid_http_url($this->uri):
226 common_debug('No URL available for notice: id='.$this->id);
227 throw new InvalidUrlException($this->url);
231 public function get_object_type($canonical=false) {
233 ? ActivityObject::canonicalType($this->object_type)
234 : $this->object_type;
237 public static function getByUri($uri)
239 $notice = new Notice();
241 if (!$notice->find(true)) {
242 throw new NoResultException($notice);
248 * Extract #hashtags from this notice's content and save them to the database.
252 /* extract all #hastags */
253 $count = preg_match_all('/(?:^|\s)#([\pL\pN_\-\.]{1,64})/u', strtolower($this->content), $match);
258 /* Add them to the database */
259 return $this->saveKnownTags($match[1]);
263 * Record the given set of hash tags in the db for this notice.
264 * Given tag strings will be normalized and checked for dupes.
266 function saveKnownTags($hashtags)
268 //turn each into their canonical tag
269 //this is needed to remove dupes before saving e.g. #hash.tag = #hashtag
270 for($i=0; $i<count($hashtags); $i++) {
271 /* elide characters we don't want in the tag */
272 $hashtags[$i] = common_canonical_tag($hashtags[$i]);
275 foreach(array_unique($hashtags) as $hashtag) {
276 $this->saveTag($hashtag);
277 self::blow('profile:notice_ids_tagged:%d:%s', $this->profile_id, $hashtag);
283 * Record a single hash tag as associated with this notice.
284 * Tag format and uniqueness must be validated by caller.
286 function saveTag($hashtag)
288 $tag = new Notice_tag();
289 $tag->notice_id = $this->id;
290 $tag->tag = $hashtag;
291 $tag->created = $this->created;
292 $id = $tag->insert();
295 // TRANS: Server exception. %s are the error details.
296 throw new ServerException(sprintf(_('Database error inserting hashtag: %s.'),
297 $last_error->message));
301 // if it's saved, blow its cache
302 $tag->blowCache(false);
306 * Save a new notice and push it out to subscribers' inboxes.
307 * Poster's permissions are checked before sending.
309 * @param int $profile_id Profile ID of the poster
310 * @param string $content source message text; links may be shortened
311 * per current user's preference
312 * @param string $source source key ('web', 'api', etc)
313 * @param array $options Associative array of optional properties:
314 * string 'created' timestamp of notice; defaults to now
315 * int 'is_local' source/gateway ID, one of:
316 * Notice::LOCAL_PUBLIC - Local, ok to appear in public timeline
317 * Notice::REMOTE - Sent from a remote service;
318 * hide from public timeline but show in
319 * local "and friends" timelines
320 * Notice::LOCAL_NONPUBLIC - Local, but hide from public timeline
321 * Notice::GATEWAY - From another non-OStatus service;
322 * will not appear in public views
323 * float 'lat' decimal latitude for geolocation
324 * float 'lon' decimal longitude for geolocation
325 * int 'location_id' geoname identifier
326 * int 'location_ns' geoname namespace to interpret location_id
327 * int 'reply_to'; notice ID this is a reply to
328 * int 'repeat_of'; notice ID this is a repeat of
329 * string 'uri' unique ID for notice; a unique tag uri (can be url or anything too)
330 * string 'url' permalink to notice; defaults to local notice URL
331 * string 'rendered' rendered HTML version of content
332 * array 'replies' list of profile URIs for reply delivery in
333 * place of extracting @-replies from content.
334 * array 'groups' list of group IDs to deliver to, in place of
335 * extracting ! tags from content
336 * array 'tags' list of hashtag strings to save with the notice
337 * in place of extracting # tags from content
338 * array 'urls' list of attached/referred URLs to save with the
339 * notice in place of extracting links from content
340 * boolean 'distribute' whether to distribute the notice, default true
341 * string 'object_type' URL of the associated object type (default ActivityObject::NOTE)
342 * string 'verb' URL of the associated verb (default ActivityVerb::POST)
343 * int 'scope' Scope bitmask; default to SITE_SCOPE on private sites, 0 otherwise
345 * @fixme tag override
348 * @throws ClientException
350 static function saveNew($profile_id, $content, $source, array $options=null) {
351 $defaults = array('uri' => null,
356 'distribute' => true,
357 'object_type' => null,
360 if (!empty($options) && is_array($options)) {
361 $options = array_merge($defaults, $options);
367 if (!isset($is_local)) {
368 $is_local = Notice::LOCAL_PUBLIC;
371 $profile = Profile::getKV('id', $profile_id);
372 if (!$profile instanceof Profile) {
373 // TRANS: Client exception thrown when trying to save a notice for an unknown user.
374 throw new ClientException(_('Problem saving notice. Unknown user.'));
377 $user = User::getKV('id', $profile_id);
378 if ($user instanceof User) {
379 // Use the local user's shortening preferences, if applicable.
380 $final = $user->shortenLinks($content);
382 $final = common_shorten_links($content);
385 if (Notice::contentTooLong($final)) {
386 // TRANS: Client exception thrown if a notice contains too many characters.
387 throw new ClientException(_('Problem saving notice. Too long.'));
390 if (common_config('throttle', 'enabled') && !Notice::checkEditThrottle($profile_id)) {
391 common_log(LOG_WARNING, 'Excessive posting by profile #' . $profile_id . '; throttled.');
392 // TRANS: Client exception thrown when a user tries to post too many notices in a given time frame.
393 throw new ClientException(_('Too many notices too fast; take a breather '.
394 'and post again in a few minutes.'));
397 if (common_config('site', 'dupelimit') > 0 && !Notice::checkDupes($profile_id, $final)) {
398 common_log(LOG_WARNING, 'Dupe posting by profile #' . $profile_id . '; throttled.');
399 // TRANS: Client exception thrown when a user tries to post too many duplicate notices in a given time frame.
400 throw new ClientException(_('Too many duplicate messages too quickly;'.
401 ' take a breather and post again in a few minutes.'));
404 if (!$profile->hasRight(Right::NEWNOTICE)) {
405 common_log(LOG_WARNING, "Attempted post from user disallowed to post: " . $profile->nickname);
407 // TRANS: Client exception thrown when a user tries to post while being banned.
408 throw new ClientException(_('You are banned from posting notices on this site.'), 403);
411 $notice = new Notice();
412 $notice->profile_id = $profile_id;
414 $autosource = common_config('public', 'autosource');
416 // Sandboxed are non-false, but not 1, either
418 if (!$profile->hasRight(Right::PUBLICNOTICE) ||
419 ($source && $autosource && in_array($source, $autosource))) {
420 $notice->is_local = Notice::LOCAL_NONPUBLIC;
422 $notice->is_local = $is_local;
425 if (!empty($created)) {
426 $notice->created = $created;
428 $notice->created = common_sql_now();
431 if (!$notice->isLocal()) {
432 // Only do these checks for non-local notices. Local notices will generate these values later.
433 if (!common_valid_http_url($url)) {
434 common_debug('Bad notice URL: ['.$url.'], URI: ['.$uri.']. Cannot link back to original! This is normal for shared notices etc.');
437 throw new ServerException('No URI for remote notice. Cannot accept that.');
441 $notice->content = $final;
443 $notice->source = $source;
447 // Get the groups here so we can figure out replies and such
448 if (!isset($groups)) {
449 $groups = User_group::idsFromText($notice->content, $profile);
454 // Handle repeat case
456 if (isset($repeat_of)) {
458 // Check for a private one
460 $repeat = Notice::getKV('id', $repeat_of);
462 if (!($repeat instanceof Notice)) {
463 // TRANS: Client exception thrown in notice when trying to repeat a missing or deleted notice.
464 throw new ClientException(_('Cannot repeat; original notice is missing or deleted.'));
467 if ($profile->id == $repeat->profile_id) {
468 // TRANS: Client error displayed when trying to repeat an own notice.
469 throw new ClientException(_('You cannot repeat your own notice.'));
472 if ($repeat->scope != Notice::SITE_SCOPE &&
473 $repeat->scope != Notice::PUBLIC_SCOPE) {
474 // TRANS: Client error displayed when trying to repeat a non-public notice.
475 throw new ClientException(_('Cannot repeat a private notice.'), 403);
478 if (!$repeat->inScope($profile)) {
479 // The generic checks above should cover this, but let's be sure!
480 // TRANS: Client error displayed when trying to repeat a notice you cannot access.
481 throw new ClientException(_('Cannot repeat a notice you cannot read.'), 403);
484 if ($profile->hasRepeated($repeat)) {
485 // TRANS: Client error displayed when trying to repeat an already repeated notice.
486 throw new ClientException(_('You already repeated that notice.'));
489 $notice->repeat_of = $repeat_of;
491 $reply = self::getReplyTo($reply_to, $profile_id, $source, $final);
493 if (!empty($reply)) {
495 if (!$reply->inScope($profile)) {
496 // TRANS: Client error displayed when trying to reply to a notice a the target has no access to.
497 // TRANS: %1$s is a user nickname, %2$d is a notice ID (number).
498 throw new ClientException(sprintf(_('%1$s has no access to notice %2$d.'),
499 $profile->nickname, $reply->id), 403);
502 $notice->reply_to = $reply->id;
503 $notice->conversation = $reply->conversation;
505 // If the original is private to a group, and notice has no group specified,
506 // make it to the same group(s)
508 if (empty($groups) && ($reply->scope & Notice::GROUP_SCOPE)) {
510 $replyGroups = $reply->getGroups();
511 foreach ($replyGroups as $group) {
512 if ($profile->isMember($group)) {
513 $groups[] = $group->id;
522 if (!empty($lat) && !empty($lon)) {
527 if (!empty($location_ns) && !empty($location_id)) {
528 $notice->location_id = $location_id;
529 $notice->location_ns = $location_ns;
532 if (!empty($rendered)) {
533 $notice->rendered = $rendered;
535 $notice->rendered = common_render_content($final, $notice);
539 if (!empty($notice->repeat_of)) {
540 $notice->verb = ActivityVerb::SHARE;
541 $notice->object_type = ActivityObject::ACTIVITY;
543 $notice->verb = ActivityVerb::POST;
546 $notice->verb = $verb;
549 if (empty($object_type)) {
550 $notice->object_type = (empty($notice->reply_to)) ? ActivityObject::NOTE : ActivityObject::COMMENT;
552 $notice->object_type = $object_type;
555 if (is_null($scope)) { // 0 is a valid value
556 if (!empty($reply)) {
557 $notice->scope = $reply->scope;
559 $notice->scope = self::defaultScope();
562 $notice->scope = $scope;
565 // For private streams
568 $user = $profile->getUser();
570 if ($user->private_stream &&
571 ($notice->scope == Notice::PUBLIC_SCOPE ||
572 $notice->scope == Notice::SITE_SCOPE)) {
573 $notice->scope |= Notice::FOLLOWER_SCOPE;
575 } catch (NoSuchUserException $e) {
576 // Cannot handle private streams for remote profiles
579 // Force the scope for private groups
581 foreach ($groups as $groupId) {
582 $group = User_group::getKV('id', $groupId);
583 if ($group instanceof User_group) {
584 if ($group->force_scope) {
585 $notice->scope |= Notice::GROUP_SCOPE;
591 if (Event::handle('StartNoticeSave', array(&$notice))) {
593 // XXX: some of these functions write to the DB
595 $id = $notice->insert();
598 common_log_db_error($notice, 'INSERT', __FILE__);
599 // TRANS: Server exception thrown when a notice cannot be saved.
600 throw new ServerException(_('Problem saving notice.'));
603 // Update ID-dependent columns: URI, conversation
605 $orig = clone($notice);
609 // We can only get here if it's a local notice, since remote notices
610 // should've bailed out earlier due to lacking a URI.
611 if (empty($notice->uri)) {
612 $notice->uri = sprintf('%s%s=%d:%s=%s',
614 'noticeId', $notice->id,
615 'objectType', $notice->get_object_type(true));
619 // If it's not part of a conversation, it's
620 // the beginning of a new conversation.
622 if (empty($notice->conversation)) {
623 $conv = Conversation::create($notice);
624 $notice->conversation = $conv->id;
629 if ($notice->update($orig) === false) {
630 common_log_db_error($notice, 'UPDATE', __FILE__);
631 // TRANS: Server exception thrown when a notice cannot be updated.
632 throw new ServerException(_('Problem saving notice.'));
638 // Clear the cache for subscribed users, so they'll update at next request
639 // XXX: someone clever could prepend instead of clearing the cache
641 $notice->blowOnInsert();
643 // Save per-notice metadata...
645 if (isset($replies)) {
646 $notice->saveKnownReplies($replies);
648 $notice->saveReplies();
652 $notice->saveKnownTags($tags);
657 // Note: groups may save tags, so must be run after tags are saved
658 // to avoid errors on duplicates.
659 // Note: groups should always be set.
661 $notice->saveKnownGroups($groups);
664 $notice->saveKnownUrls($urls);
670 // Prepare inbox delivery, may be queued to background.
671 $notice->distribute();
677 function blowOnInsert($conversation = false)
679 $this->blowStream('profile:notice_ids:%d', $this->profile_id);
681 if ($this->isPublic()) {
682 $this->blowStream('public');
685 self::blow('notice:list-ids:conversation:%s', $this->conversation);
686 self::blow('conversation:notice_count:%d', $this->conversation);
688 if (!empty($this->repeat_of)) {
689 // XXX: we should probably only use one of these
690 $this->blowStream('notice:repeats:%d', $this->repeat_of);
691 self::blow('notice:list-ids:repeat_of:%d', $this->repeat_of);
694 $original = Notice::getKV('id', $this->repeat_of);
696 if ($original instanceof Notice) {
697 $originalUser = User::getKV('id', $original->profile_id);
698 if ($originalUser instanceof User) {
699 $this->blowStream('user:repeats_of_me:%d', $originalUser->id);
703 $profile = Profile::getKV($this->profile_id);
705 if ($profile instanceof Profile) {
706 $profile->blowNoticeCount();
709 $ptags = $this->getProfileTags();
710 foreach ($ptags as $ptag) {
711 $ptag->blowNoticeStreamCache();
716 * Clear cache entries related to this notice at delete time.
717 * Necessary to avoid breaking paging on public, profile timelines.
719 function blowOnDelete()
721 $this->blowOnInsert();
723 self::blow('profile:notice_ids:%d;last', $this->profile_id);
725 if ($this->isPublic()) {
726 self::blow('public;last');
729 self::blow('fave:by_notice', $this->id);
731 if ($this->conversation) {
732 // In case we're the first, will need to calc a new root.
733 self::blow('notice:conversation_root:%d', $this->conversation);
736 $ptags = $this->getProfileTags();
737 foreach ($ptags as $ptag) {
738 $ptag->blowNoticeStreamCache(true);
742 function blowStream()
744 $c = self::memcache();
750 $args = func_get_args();
752 $format = array_shift($args);
754 $keyPart = vsprintf($format, $args);
756 $cacheKey = Cache::key($keyPart);
758 $c->delete($cacheKey);
760 // delete the "last" stream, too, if this notice is
761 // older than the top of that stream
763 $lastKey = $cacheKey.';last';
765 $lastStr = $c->get($lastKey);
767 if ($lastStr !== false) {
768 $window = explode(',', $lastStr);
769 $lastID = $window[0];
770 $lastNotice = Notice::getKV('id', $lastID);
771 if (!$lastNotice instanceof Notice // just weird
772 || strtotime($lastNotice->created) >= strtotime($this->created)) {
773 $c->delete($lastKey);
778 /** save all urls in the notice to the db
780 * follow redirects and save all available file information
781 * (mimetype, date, size, oembed, etc.)
785 function saveUrls() {
786 if (common_config('attachments', 'process_links')) {
787 common_replace_urls_callback($this->content, array($this, 'saveUrl'), $this->id);
792 * Save the given URLs as related links/attachments to the db
794 * follow redirects and save all available file information
795 * (mimetype, date, size, oembed, etc.)
799 function saveKnownUrls($urls)
801 if (common_config('attachments', 'process_links')) {
802 // @fixme validation?
803 foreach (array_unique($urls) as $url) {
804 File::processNew($url, $this->id);
812 function saveUrl($url, $notice_id) {
813 File::processNew($url, $notice_id);
816 static function checkDupes($profile_id, $content) {
817 $profile = Profile::getKV($profile_id);
818 if (!$profile instanceof Profile) {
821 $notice = $profile->getNotices(0, CachingNoticeStream::CACHE_WINDOW);
822 if (!empty($notice)) {
824 while ($notice->fetch()) {
825 if (time() - strtotime($notice->created) >= common_config('site', 'dupelimit')) {
827 } else if ($notice->content == $content) {
832 // If we get here, oldest item in cache window is not
833 // old enough for dupe limit; do direct check against DB
834 $notice = new Notice();
835 $notice->profile_id = $profile_id;
836 $notice->content = $content;
837 $threshold = common_sql_date(time() - common_config('site', 'dupelimit'));
838 $notice->whereAdd(sprintf("created > '%s'", $notice->escape($threshold)));
840 $cnt = $notice->count();
844 static function checkEditThrottle($profile_id) {
845 $profile = Profile::getKV($profile_id);
846 if (!$profile instanceof Profile) {
849 // Get the Nth notice
850 $notice = $profile->getNotices(common_config('throttle', 'count') - 1, 1);
851 if ($notice && $notice->fetch()) {
852 // If the Nth notice was posted less than timespan seconds ago
853 if (time() - strtotime($notice->created) <= common_config('throttle', 'timespan')) {
858 // Either not N notices in the stream, OR the Nth was not posted within timespan seconds
862 protected $_attachments = -1;
864 function attachments() {
866 if ($this->_attachments != -1) {
867 return $this->_attachments;
870 $f2ps = File_to_post::listGet('post_id', array($this->id));
874 foreach ($f2ps[$this->id] as $f2p) {
875 $ids[] = $f2p->file_id;
878 $files = File::multiGet('id', $ids);
880 $this->_attachments = $files->fetchAll();
882 return $this->_attachments;
885 function _setAttachments($attachments)
887 $this->_attachments = $attachments;
890 function publicStream($offset=0, $limit=20, $since_id=0, $max_id=0)
892 $stream = new PublicNoticeStream();
893 return $stream->getNotices($offset, $limit, $since_id, $max_id);
897 function conversationStream($id, $offset=0, $limit=20, $since_id=0, $max_id=0)
899 $stream = new ConversationNoticeStream($id);
901 return $stream->getNotices($offset, $limit, $since_id, $max_id);
905 * Is this notice part of an active conversation?
907 * @return boolean true if other messages exist in the same
908 * conversation, false if this is the only one
910 function hasConversation()
912 if (!empty($this->conversation)) {
913 $conversation = Notice::conversationStream(
919 if ($conversation->N > 0) {
927 * Grab the earliest notice from this conversation.
929 * @return Notice or null
931 function conversationRoot($profile=-1)
933 // XXX: can this happen?
935 if (empty($this->conversation)) {
939 // Get the current profile if not specified
941 if (is_int($profile) && $profile == -1) {
942 $profile = Profile::current();
945 // If this notice is out of scope, no root for you!
947 if (!$this->inScope($profile)) {
951 // If this isn't a reply to anything, then it's its own
954 if (empty($this->reply_to)) {
958 if (is_null($profile)) {
959 $keypart = sprintf('notice:conversation_root:%d:null', $this->id);
961 $keypart = sprintf('notice:conversation_root:%d:%d',
966 $root = self::cacheGet($keypart);
968 if ($root !== false && $root->inScope($profile)) {
975 $parent = $last->getParent();
976 if ($parent->inScope($profile)) {
980 } catch (Exception $e) {
981 // Latest notice has no parent
983 // No parent, or parent out of scope
988 self::cacheSet($keypart, $root);
994 * Pull up a full list of local recipients who will be getting
995 * this notice in their inbox. Results will be cached, so don't
996 * change the input data wily-nilly!
998 * @param array $groups optional list of Group objects;
999 * if left empty, will be loaded from group_inbox records
1000 * @param array $recipient optional list of reply profile ids
1001 * if left empty, will be loaded from reply records
1002 * @return array associating recipient user IDs with an inbox source constant
1004 function whoGets(array $groups=null, array $recipients=null)
1006 $c = self::memcache();
1009 $ni = $c->get(Cache::key('notice:who_gets:'.$this->id));
1010 if ($ni !== false) {
1015 if (is_null($recipients)) {
1016 $recipients = $this->getReplies();
1021 // Give plugins a chance to add folks in at start...
1022 if (Event::handle('StartNoticeWhoGets', array($this, &$ni))) {
1024 $users = $this->getSubscribedUsers();
1025 foreach ($users as $id) {
1026 $ni[$id] = NOTICE_INBOX_SOURCE_SUB;
1029 if (is_null($groups)) {
1030 $groups = $this->getGroups();
1032 foreach ($groups as $group) {
1033 $users = $group->getUserMembers();
1034 foreach ($users as $id) {
1035 if (!array_key_exists($id, $ni)) {
1036 $ni[$id] = NOTICE_INBOX_SOURCE_GROUP;
1041 $ptAtts = $this->getAttentionsFromProfileTags();
1042 foreach ($ptAtts as $key=>$val) {
1043 if (!array_key_exists($key, $ni)) {
1048 foreach ($recipients as $recipient) {
1049 if (!array_key_exists($recipient, $ni)) {
1050 $ni[$recipient] = NOTICE_INBOX_SOURCE_REPLY;
1054 // Exclude any deleted, non-local, or blocking recipients.
1055 $profile = $this->getProfile();
1056 $originalProfile = null;
1057 if ($this->repeat_of) {
1058 // Check blocks against the original notice's poster as well.
1059 $original = Notice::getKV('id', $this->repeat_of);
1060 if ($original instanceof Notice) {
1061 $originalProfile = $original->getProfile();
1065 foreach ($ni as $id => $source) {
1067 $user = User::getKV('id', $id);
1068 if (!$user instanceof User ||
1069 $user->hasBlocked($profile) ||
1070 ($originalProfile && $user->hasBlocked($originalProfile))) {
1073 } catch (UserNoProfileException $e) {
1074 // User doesn't have a profile; invalid; skip them.
1079 // Give plugins a chance to filter out...
1080 Event::handle('EndNoticeWhoGets', array($this, &$ni));
1084 // XXX: pack this data better
1085 $c->set(Cache::key('notice:who_gets:'.$this->id), $ni);
1091 function getSubscribedUsers()
1095 if(common_config('db','quote_identifiers'))
1096 $user_table = '"user"';
1097 else $user_table = 'user';
1101 'FROM '. $user_table .' JOIN subscription '.
1102 'ON '. $user_table .'.id = subscription.subscriber ' .
1103 'WHERE subscription.subscribed = %d ';
1105 $user->query(sprintf($qry, $this->profile_id));
1109 while ($user->fetch()) {
1118 function getProfileTags()
1120 $profile = $this->getProfile();
1121 $list = $profile->getOtherTags($profile);
1124 while($list->fetch()) {
1125 $ptags[] = clone($list);
1131 public function getAttentionsFromProfileTags()
1134 $ptags = $this->getProfileTags();
1135 foreach ($ptags as $ptag) {
1136 $users = $ptag->getUserSubscribers();
1137 foreach ($users as $id) {
1138 $ni[$id] = NOTICE_INBOX_SOURCE_PROFILE_TAG;
1145 * Record this notice to the given group inboxes for delivery.
1146 * Overrides the regular parsing of !group markup.
1148 * @param string $group_ids
1149 * @fixme might prefer URIs as identifiers, as for replies?
1150 * best with generalizations on user_group to support
1151 * remote groups better.
1153 function saveKnownGroups($group_ids)
1155 if (!is_array($group_ids)) {
1156 // TRANS: Server exception thrown when no array is provided to the method saveKnownGroups().
1157 throw new ServerException(_('Bad type provided to saveKnownGroups.'));
1161 foreach (array_unique($group_ids) as $id) {
1162 $group = User_group::getKV('id', $id);
1163 if ($group instanceof User_group) {
1164 common_log(LOG_ERR, "Local delivery to group id $id, $group->nickname");
1165 $result = $this->addToGroupInbox($group);
1167 common_log_db_error($gi, 'INSERT', __FILE__);
1170 if (common_config('group', 'addtag')) {
1171 // we automatically add a tag for every group name, too
1173 $tag = Notice_tag::pkeyGet(array('tag' => common_canonical_tag($group->nickname),
1174 'notice_id' => $this->id));
1176 if (is_null($tag)) {
1177 $this->saveTag($group->nickname);
1181 $groups[] = clone($group);
1183 common_log(LOG_ERR, "Local delivery to group id $id skipped, doesn't exist");
1190 function addToGroupInbox(User_group $group)
1192 $gi = Group_inbox::pkeyGet(array('group_id' => $group->id,
1193 'notice_id' => $this->id));
1195 if (!$gi instanceof Group_inbox) {
1197 $gi = new Group_inbox();
1199 $gi->group_id = $group->id;
1200 $gi->notice_id = $this->id;
1201 $gi->created = $this->created;
1203 $result = $gi->insert();
1206 common_log_db_error($gi, 'INSERT', __FILE__);
1207 // TRANS: Server exception thrown when an update for a group inbox fails.
1208 throw new ServerException(_('Problem saving group inbox.'));
1211 self::blow('user_group:notice_ids:%d', $gi->group_id);
1218 * Save reply records indicating that this notice needs to be
1219 * delivered to the local users with the given URIs.
1221 * Since this is expected to be used when saving foreign-sourced
1222 * messages, we won't deliver to any remote targets as that's the
1223 * source service's responsibility.
1225 * Mail notifications etc will be handled later.
1227 * @param array $uris Array of unique identifier URIs for recipients
1229 function saveKnownReplies(array $uris)
1235 $sender = Profile::getKV($this->profile_id);
1237 foreach (array_unique($uris) as $uri) {
1239 $profile = Profile::fromURI($uri);
1241 if (!$profile instanceof Profile) {
1242 common_log(LOG_WARNING, "Unable to determine profile for URI '$uri'");
1246 if ($profile->hasBlocked($sender)) {
1247 common_log(LOG_INFO, "Not saving reply to profile {$profile->id} ($uri) from sender {$sender->id} because of a block.");
1251 $this->saveReply($profile->id);
1252 self::blow('reply:stream:%d', $profile->id);
1259 * Pull @-replies from this message's content in StatusNet markup format
1260 * and save reply records indicating that this message needs to be
1261 * delivered to those users.
1263 * Mail notifications to local profiles will be sent later.
1265 * @return array of integer profile IDs
1268 function saveReplies()
1270 // Don't save reply data for repeats
1272 if (!empty($this->repeat_of)) {
1276 $sender = Profile::getKV($this->profile_id);
1280 // If it's a reply, save for the replied-to author
1282 $parent = $this->getParent();
1283 $author = $parent->getProfile();
1284 if ($author instanceof Profile) {
1285 $this->saveReply($author->id);
1286 $replied[$author->id] = 1;
1287 self::blow('reply:stream:%d', $author->id);
1289 } catch (Exception $e) {
1290 // Not a reply, since it has no parent!
1293 // @todo ideally this parser information would only
1294 // be calculated once.
1296 $mentions = common_find_mentions($this->content, $this);
1298 // store replied only for first @ (what user/notice what the reply directed,
1299 // we assume first @ is it)
1301 foreach ($mentions as $mention) {
1303 foreach ($mention['mentioned'] as $mentioned) {
1305 // skip if they're already covered
1307 if (!empty($replied[$mentioned->id])) {
1311 // Don't save replies from blocked profile to local user
1313 $mentioned_user = User::getKV('id', $mentioned->id);
1314 if ($mentioned_user instanceof User && $mentioned_user->hasBlocked($sender)) {
1318 $this->saveReply($mentioned->id);
1319 $replied[$mentioned->id] = 1;
1320 self::blow('reply:stream:%d', $mentioned->id);
1324 $recipientIds = array_keys($replied);
1326 return $recipientIds;
1329 function saveReply($profileId)
1331 $reply = new Reply();
1333 $reply->notice_id = $this->id;
1334 $reply->profile_id = $profileId;
1335 $reply->modified = $this->created;
1342 protected $_replies = -1;
1345 * Pull the complete list of @-reply targets for this notice.
1347 * @return array of integer profile ids
1349 function getReplies()
1351 if ($this->_replies != -1) {
1352 return $this->_replies;
1355 $replyMap = Reply::listGet('notice_id', array($this->id));
1359 foreach ($replyMap[$this->id] as $reply) {
1360 $ids[] = $reply->profile_id;
1363 $this->_replies = $ids;
1368 function _setReplies($replies)
1370 $this->_replies = $replies;
1374 * Pull the complete list of @-reply targets for this notice.
1376 * @return array of Profiles
1378 function getReplyProfiles()
1380 $ids = $this->getReplies();
1382 $profiles = Profile::multiGet('id', $ids);
1384 return $profiles->fetchAll();
1388 * Send e-mail notifications to local @-reply targets.
1390 * Replies must already have been saved; this is expected to be run
1391 * from the distrib queue handler.
1393 function sendReplyNotifications()
1395 // Don't send reply notifications for repeats
1397 if (!empty($this->repeat_of)) {
1401 $recipientIds = $this->getReplies();
1403 foreach ($recipientIds as $recipientId) {
1404 $user = User::getKV('id', $recipientId);
1405 if ($user instanceof User) {
1406 mail_notify_attn($user, $this);
1412 * Pull list of groups this notice needs to be delivered to,
1413 * as previously recorded by saveKnownGroups().
1415 * @return array of Group objects
1418 protected $_groups = -1;
1420 function getGroups()
1422 // Don't save groups for repeats
1424 if (!empty($this->repeat_of)) {
1428 if ($this->_groups != -1)
1430 return $this->_groups;
1433 $gis = Group_inbox::listGet('notice_id', array($this->id));
1437 foreach ($gis[$this->id] as $gi)
1439 $ids[] = $gi->group_id;
1442 $groups = User_group::multiGet('id', $ids);
1444 $this->_groups = $groups->fetchAll();
1446 return $this->_groups;
1449 function _setGroups($groups)
1451 $this->_groups = $groups;
1455 * Convert a notice into an activity for export.
1457 * @param User $cur Current user
1459 * @return Activity activity object representing this Notice.
1462 function asActivity($cur=null)
1464 $act = self::cacheGet(Cache::codeKey('notice:as-activity:'.$this->id));
1466 if ($act instanceof Activity) {
1469 $act = new Activity();
1471 if (Event::handle('StartNoticeAsActivity', array($this, &$act))) {
1473 $act->id = $this->uri;
1474 $act->time = strtotime($this->created);
1475 $act->link = $this->getUrl();
1476 $act->content = common_xml_safe_str($this->rendered);
1478 $profile = $this->getProfile();
1480 $act->actor = ActivityObject::fromProfile($profile);
1481 $act->actor->extra[] = $profile->profileInfo($cur);
1483 $act->verb = $this->verb;
1485 if ($this->repeat_of) {
1486 $repeated = Notice::getKV('id', $this->repeat_of);
1487 if ($repeated instanceof Notice) {
1488 $act->objects[] = $repeated->asActivity($cur);
1491 $act->objects[] = ActivityObject::fromNotice($this);
1494 // XXX: should this be handled by default processing for object entry?
1498 $tags = $this->getTags();
1500 foreach ($tags as $tag) {
1501 $cat = new AtomCategory();
1504 $act->categories[] = $cat;
1508 // XXX: use Atom Media and/or File activity objects instead
1510 $attachments = $this->attachments();
1512 foreach ($attachments as $attachment) {
1513 // Save local attachments
1514 if (!empty($attachment->filename)) {
1515 $act->attachments[] = ActivityObject::fromFile($attachment);
1519 $ctx = new ActivityContext();
1522 $reply = $this->getParent();
1523 $ctx->replyToID = $reply->getUri();
1524 $ctx->replyToUrl = $reply->getUrl();
1525 } catch (Exception $e) {
1526 // This is not a reply to something
1529 $ctx->location = $this->getLocation();
1533 if (!empty($this->conversation)) {
1534 $conv = Conversation::getKV('id', $this->conversation);
1535 if ($conv instanceof Conversation) {
1536 $ctx->conversation = $conv->uri;
1540 $reply_ids = $this->getReplies();
1542 foreach ($reply_ids as $id) {
1543 $rprofile = Profile::getKV('id', $id);
1544 if ($rprofile instanceof Profile) {
1545 $ctx->attention[$rprofile->getUri()] = ActivityObject::PERSON;
1549 $groups = $this->getGroups();
1551 foreach ($groups as $group) {
1552 $ctx->attention[$group->getUri()] = ActivityObject::GROUP;
1555 switch ($this->scope) {
1556 case Notice::PUBLIC_SCOPE:
1557 $ctx->attention[ActivityContext::ATTN_PUBLIC] = ActivityObject::COLLECTION;
1559 case Notice::FOLLOWER_SCOPE:
1560 $surl = common_local_url("subscribers", array('nickname' => $profile->nickname));
1561 $ctx->attention[$surl] = ActivityObject::COLLECTION;
1565 $act->context = $ctx;
1567 $source = $this->getSource();
1569 if ($source instanceof Notice_source) {
1570 $act->generator = ActivityObject::fromNoticeSource($source);
1575 $atom_feed = $profile->getAtomFeed();
1577 if (!empty($atom_feed)) {
1579 $act->source = new ActivitySource();
1581 // XXX: we should store the actual feed ID
1583 $act->source->id = $atom_feed;
1585 // XXX: we should store the actual feed title
1587 $act->source->title = $profile->getBestName();
1589 $act->source->links['alternate'] = $profile->profileurl;
1590 $act->source->links['self'] = $atom_feed;
1592 $act->source->icon = $profile->avatarUrl(AVATAR_PROFILE_SIZE);
1594 $notice = $profile->getCurrentNotice();
1596 if ($notice instanceof Notice) {
1597 $act->source->updated = self::utcDate($notice->created);
1600 $user = User::getKV('id', $profile->id);
1602 if ($user instanceof User) {
1603 $act->source->links['license'] = common_config('license', 'url');
1607 if ($this->isLocal()) {
1608 $act->selfLink = common_local_url('ApiStatusesShow', array('id' => $this->id,
1609 'format' => 'atom'));
1610 $act->editLink = $act->selfLink;
1613 Event::handle('EndNoticeAsActivity', array($this, &$act));
1616 self::cacheSet(Cache::codeKey('notice:as-activity:'.$this->id), $act);
1621 // This has gotten way too long. Needs to be sliced up into functional bits
1622 // or ideally exported to a utility class.
1624 function asAtomEntry($namespace=false,
1629 $act = $this->asActivity($cur);
1630 $act->extra[] = $this->noticeInfo($cur);
1631 return $act->asString($namespace, $author, $source);
1635 * Extra notice info for atom entries
1637 * Clients use some extra notice info in the atom stream.
1638 * This gives it to them.
1640 * @param User $cur Current user
1642 * @return array representation of <statusnet:notice_info> element
1645 function noticeInfo($cur)
1647 // local notice ID (useful to clients for ordering)
1649 $noticeInfoAttr = array('local_id' => $this->id);
1653 $ns = $this->getSource();
1655 if ($ns instanceof Notice_source) {
1656 $noticeInfoAttr['source'] = $ns->code;
1657 if (!empty($ns->url)) {
1658 $noticeInfoAttr['source_link'] = $ns->url;
1659 if (!empty($ns->name)) {
1660 $noticeInfoAttr['source'] = '<a href="'
1661 . htmlspecialchars($ns->url)
1662 . '" rel="nofollow">'
1663 . htmlspecialchars($ns->name)
1669 // favorite and repeated
1672 $cp = $cur->getProfile();
1673 $noticeInfoAttr['favorite'] = ($cp->hasFave($this)) ? "true" : "false";
1674 $noticeInfoAttr['repeated'] = ($cp->hasRepeated($this)) ? "true" : "false";
1677 if (!empty($this->repeat_of)) {
1678 $noticeInfoAttr['repeat_of'] = $this->repeat_of;
1681 return array('statusnet:notice_info', $noticeInfoAttr, null);
1685 * Returns an XML string fragment with a reference to a notice as an
1686 * Activity Streams noun object with the given element type.
1688 * Assumes that 'activity' namespace has been previously defined.
1690 * @param string $element one of 'subject', 'object', 'target'
1694 function asActivityNoun($element)
1696 $noun = ActivityObject::fromNotice($this);
1697 return $noun->asString('activity:' . $element);
1700 // FIXME: Replace all bestUrl with getUrl and do exception handling
1704 return $this->getUrl();
1705 } catch (InvalidUrlException $e) {
1706 return common_local_url('shownotice', array('notice' => $this->id));
1712 * Determine which notice, if any, a new notice is in reply to.
1714 * For conversation tracking, we try to see where this notice fits
1715 * in the tree. Rough algorithm is:
1717 * if (reply_to is set and valid) {
1719 * } else if ((source not API or Web) and (content starts with "T NAME" or "@name ")) {
1720 * return ID of last notice by initial @name in content;
1723 * Note that all @nickname instances will still be used to save "reply" records,
1724 * so the notice shows up in the mentioned users' "replies" tab.
1726 * @param integer $reply_to ID passed in by Web or API
1727 * @param integer $profile_id ID of author
1728 * @param string $source Source tag, like 'web' or 'gwibber'
1729 * @param string $content Final notice content
1731 * @return integer ID of replied-to notice, or null for not a reply.
1734 static function getReplyTo($reply_to, $profile_id, $source, $content)
1736 static $lb = array('xmpp', 'mail', 'sms', 'omb');
1738 // If $reply_to is specified, we check that it exists, and then
1739 // return it if it does
1741 if (!empty($reply_to)) {
1742 $reply_notice = Notice::getKV('id', $reply_to);
1743 if ($reply_notice instanceof Notice) {
1744 return $reply_notice;
1748 // If it's not a "low bandwidth" source (one where you can't set
1749 // a reply_to argument), we return. This is mostly web and API
1752 if (!in_array($source, $lb)) {
1756 // Is there an initial @ or T?
1758 if (preg_match('/^T ([A-Z0-9]{1,64}) /', $content, $match) ||
1759 preg_match('/^@([a-z0-9]{1,64})\s+/', $content, $match)) {
1760 $nickname = common_canonical_nickname($match[1]);
1765 // Figure out who that is.
1767 $sender = Profile::getKV('id', $profile_id);
1768 if (!$sender instanceof Profile) {
1772 $recipient = common_relative_profile($sender, $nickname, common_sql_now());
1774 if (!$recipient instanceof Profile) {
1778 // Get their last notice
1780 $last = $recipient->getCurrentNotice();
1782 if ($last instanceof Notice) {
1789 static function maxContent()
1791 $contentlimit = common_config('notice', 'contentlimit');
1792 // null => use global limit (distinct from 0!)
1793 if (is_null($contentlimit)) {
1794 $contentlimit = common_config('site', 'textlimit');
1796 return $contentlimit;
1799 static function contentTooLong($content)
1801 $contentlimit = self::maxContent();
1802 return ($contentlimit > 0 && !empty($content) && (mb_strlen($content) > $contentlimit));
1805 function getLocation()
1809 if (!empty($this->location_id) && !empty($this->location_ns)) {
1810 $location = Location::fromId($this->location_id, $this->location_ns);
1813 if (is_null($location)) { // no ID, or Location::fromId() failed
1814 if (!empty($this->lat) && !empty($this->lon)) {
1815 $location = Location::fromLatLon($this->lat, $this->lon);
1823 * Convenience function for posting a repeat of an existing message.
1825 * @param int $repeater_id: profile ID of user doing the repeat
1826 * @param string $source: posting source key, eg 'web', 'api', etc
1829 * @throws Exception on failure or permission problems
1831 function repeat($repeater_id, $source)
1833 $author = Profile::getKV('id', $this->profile_id);
1835 // TRANS: Message used to repeat a notice. RT is the abbreviation of 'retweet'.
1836 // TRANS: %1$s is the repeated user's name, %2$s is the repeated notice.
1837 $content = sprintf(_('RT @%1$s %2$s'),
1841 $maxlen = common_config('site', 'textlimit');
1842 if ($maxlen > 0 && mb_strlen($content) > $maxlen) {
1843 // Web interface and current Twitter API clients will
1844 // pull the original notice's text, but some older
1845 // clients and RSS/Atom feeds will see this trimmed text.
1847 // Unfortunately this is likely to lose tags or URLs
1848 // at the end of long notices.
1849 $content = mb_substr($content, 0, $maxlen - 4) . ' ...';
1852 // Scope is same as this one's
1854 return self::saveNew($repeater_id,
1857 array('repeat_of' => $this->id,
1858 'scope' => $this->scope));
1861 // These are supposed to be in chron order!
1863 function repeatStream($limit=100)
1865 $cache = Cache::instance();
1867 if (empty($cache)) {
1868 $ids = $this->_repeatStreamDirect($limit);
1870 $idstr = $cache->get(Cache::key('notice:repeats:'.$this->id));
1871 if ($idstr !== false) {
1872 if (empty($idstr)) {
1875 $ids = explode(',', $idstr);
1878 $ids = $this->_repeatStreamDirect(100);
1879 $cache->set(Cache::key('notice:repeats:'.$this->id), implode(',', $ids));
1882 // We do a max of 100, so slice down to limit
1883 $ids = array_slice($ids, 0, $limit);
1887 return NoticeStream::getStreamByIds($ids);
1890 function _repeatStreamDirect($limit)
1892 $notice = new Notice();
1894 $notice->selectAdd(); // clears it
1895 $notice->selectAdd('id');
1897 $notice->repeat_of = $this->id;
1899 $notice->orderBy('created, id'); // NB: asc!
1901 if (!is_null($limit)) {
1902 $notice->limit(0, $limit);
1905 return $notice->fetchAll('id');
1908 function locationOptions($lat, $lon, $location_id, $location_ns, $profile = null)
1912 if (!empty($location_id) && !empty($location_ns)) {
1913 $options['location_id'] = $location_id;
1914 $options['location_ns'] = $location_ns;
1916 $location = Location::fromId($location_id, $location_ns);
1918 if ($location instanceof Location) {
1919 $options['lat'] = $location->lat;
1920 $options['lon'] = $location->lon;
1923 } else if (!empty($lat) && !empty($lon)) {
1924 $options['lat'] = $lat;
1925 $options['lon'] = $lon;
1927 $location = Location::fromLatLon($lat, $lon);
1929 if ($location instanceof Location) {
1930 $options['location_id'] = $location->location_id;
1931 $options['location_ns'] = $location->location_ns;
1933 } else if (!empty($profile)) {
1934 if (isset($profile->lat) && isset($profile->lon)) {
1935 $options['lat'] = $profile->lat;
1936 $options['lon'] = $profile->lon;
1939 if (isset($profile->location_id) && isset($profile->location_ns)) {
1940 $options['location_id'] = $profile->location_id;
1941 $options['location_ns'] = $profile->location_ns;
1948 function clearAttentions()
1950 $att = new Attention();
1951 $att->notice_id = $this->getID();
1954 while ($att->fetch()) {
1955 // Can't do delete() on the object directly since it won't remove all of it
1956 $other = clone($att);
1962 function clearReplies()
1964 $replyNotice = new Notice();
1965 $replyNotice->reply_to = $this->id;
1967 //Null any notices that are replies to this notice
1969 if ($replyNotice->find()) {
1970 while ($replyNotice->fetch()) {
1971 $orig = clone($replyNotice);
1972 $replyNotice->reply_to = null;
1973 $replyNotice->update($orig);
1979 $reply = new Reply();
1980 $reply->notice_id = $this->id;
1982 if ($reply->find()) {
1983 while($reply->fetch()) {
1984 self::blow('reply:stream:%d', $reply->profile_id);
1992 function clearFiles()
1994 $f2p = new File_to_post();
1996 $f2p->post_id = $this->id;
1999 while ($f2p->fetch()) {
2003 // FIXME: decide whether to delete File objects
2004 // ...and related (actual) files
2007 function clearRepeats()
2009 $repeatNotice = new Notice();
2010 $repeatNotice->repeat_of = $this->id;
2012 //Null any notices that are repeats of this notice
2014 if ($repeatNotice->find()) {
2015 while ($repeatNotice->fetch()) {
2016 $orig = clone($repeatNotice);
2017 $repeatNotice->repeat_of = null;
2018 $repeatNotice->update($orig);
2023 function clearFaves()
2026 $fave->notice_id = $this->id;
2028 if ($fave->find()) {
2029 while ($fave->fetch()) {
2030 self::blow('fave:ids_by_user_own:%d', $fave->user_id);
2031 self::blow('fave:ids_by_user_own:%d;last', $fave->user_id);
2032 self::blow('fave:ids_by_user:%d', $fave->user_id);
2033 self::blow('fave:ids_by_user:%d;last', $fave->user_id);
2041 function clearTags()
2043 $tag = new Notice_tag();
2044 $tag->notice_id = $this->id;
2047 while ($tag->fetch()) {
2048 self::blow('profile:notice_ids_tagged:%d:%s', $this->profile_id, Cache::keyize($tag->tag));
2049 self::blow('profile:notice_ids_tagged:%d:%s;last', $this->profile_id, Cache::keyize($tag->tag));
2050 self::blow('notice_tag:notice_ids:%s', Cache::keyize($tag->tag));
2051 self::blow('notice_tag:notice_ids:%s;last', Cache::keyize($tag->tag));
2059 function clearGroupInboxes()
2061 $gi = new Group_inbox();
2063 $gi->notice_id = $this->id;
2066 while ($gi->fetch()) {
2067 self::blow('user_group:notice_ids:%d', $gi->group_id);
2075 function distribute()
2077 // We always insert for the author so they don't
2079 Event::handle('StartNoticeDistribute', array($this));
2081 // If there's a failure, we want to _force_
2082 // distribution at this point.
2084 $qm = QueueManager::get();
2085 $qm->enqueue($this, 'distrib');
2086 } catch (Exception $e) {
2087 // If the exception isn't transient, this
2088 // may throw more exceptions as DQH does
2089 // its own enqueueing. So, we ignore them!
2091 $handler = new DistribQueueHandler();
2092 $handler->handle($this);
2093 } catch (Exception $e) {
2094 common_log(LOG_ERR, "emergency redistribution resulted in " . $e->getMessage());
2096 // Re-throw so somebody smarter can handle it.
2103 $result = parent::insert();
2105 if ($result !== false) {
2106 // Profile::hasRepeated() abuses pkeyGet(), so we
2107 // have to clear manually
2108 if (!empty($this->repeat_of)) {
2109 $c = self::memcache();
2111 $ck = self::multicacheKey('Notice',
2112 array('profile_id' => $this->profile_id,
2113 'repeat_of' => $this->repeat_of));
2123 * Get the source of the notice
2125 * @return Notice_source $ns A notice source object. 'code' is the only attribute
2126 * guaranteed to be populated.
2128 function getSource()
2130 $ns = new Notice_source();
2131 if (!empty($this->source)) {
2132 switch ($this->source) {
2139 $ns->code = $this->source;
2142 $ns = Notice_source::getKV($this->source);
2144 $ns = new Notice_source();
2145 $ns->code = $this->source;
2146 $app = Oauth_application::getKV('name', $this->source);
2148 $ns->name = $app->name;
2149 $ns->url = $app->source_url;
2159 * Determine whether the notice was locally created
2161 * @return boolean locality
2164 public function isLocal()
2166 return ($this->is_local == Notice::LOCAL_PUBLIC ||
2167 $this->is_local == Notice::LOCAL_NONPUBLIC);
2171 * Get the list of hash tags saved with this notice.
2173 * @return array of strings
2175 public function getTags()
2179 $keypart = sprintf('notice:tags:%d', $this->id);
2181 $tagstr = self::cacheGet($keypart);
2183 if ($tagstr !== false) {
2184 $tags = explode(',', $tagstr);
2186 $tag = new Notice_tag();
2187 $tag->notice_id = $this->id;
2189 while ($tag->fetch()) {
2190 $tags[] = $tag->tag;
2193 self::cacheSet($keypart, implode(',', $tags));
2199 static private function utcDate($dt)
2201 $dateStr = date('d F Y H:i:s', strtotime($dt));
2202 $d = new DateTime($dateStr, new DateTimeZone('UTC'));
2203 return $d->format(DATE_W3C);
2207 * Look up the creation timestamp for a given notice ID, even
2208 * if it's been deleted.
2211 * @return mixed string recorded creation timestamp, or false if can't be found
2213 public static function getAsTimestamp($id)
2219 $notice = Notice::getKV('id', $id);
2221 return $notice->created;
2224 $deleted = Deleted_notice::getKV('id', $id);
2226 return $deleted->created;
2233 * Build an SQL 'where' fragment for timestamp-based sorting from a since_id
2234 * parameter, matching notices posted after the given one (exclusive).
2236 * If the referenced notice can't be found, will return false.
2239 * @param string $idField
2240 * @param string $createdField
2241 * @return mixed string or false if no match
2243 public static function whereSinceId($id, $idField='id', $createdField='created')
2245 $since = Notice::getAsTimestamp($id);
2247 return sprintf("($createdField = '%s' and $idField > %d) or ($createdField > '%s')", $since, $id, $since);
2253 * Build an SQL 'where' fragment for timestamp-based sorting from a since_id
2254 * parameter, matching notices posted after the given one (exclusive), and
2255 * if necessary add it to the data object's query.
2257 * @param DB_DataObject $obj
2259 * @param string $idField
2260 * @param string $createdField
2261 * @return mixed string or false if no match
2263 public static function addWhereSinceId(DB_DataObject $obj, $id, $idField='id', $createdField='created')
2265 $since = self::whereSinceId($id, $idField, $createdField);
2267 $obj->whereAdd($since);
2272 * Build an SQL 'where' fragment for timestamp-based sorting from a max_id
2273 * parameter, matching notices posted before the given one (inclusive).
2275 * If the referenced notice can't be found, will return false.
2278 * @param string $idField
2279 * @param string $createdField
2280 * @return mixed string or false if no match
2282 public static function whereMaxId($id, $idField='id', $createdField='created')
2284 $max = Notice::getAsTimestamp($id);
2286 return sprintf("($createdField < '%s') or ($createdField = '%s' and $idField <= %d)", $max, $max, $id);
2292 * Build an SQL 'where' fragment for timestamp-based sorting from a max_id
2293 * parameter, matching notices posted before the given one (inclusive), and
2294 * if necessary add it to the data object's query.
2296 * @param DB_DataObject $obj
2298 * @param string $idField
2299 * @param string $createdField
2300 * @return mixed string or false if no match
2302 public static function addWhereMaxId(DB_DataObject $obj, $id, $idField='id', $createdField='created')
2304 $max = self::whereMaxId($id, $idField, $createdField);
2306 $obj->whereAdd($max);
2312 if (common_config('public', 'localonly')) {
2313 return ($this->is_local == Notice::LOCAL_PUBLIC);
2315 return (($this->is_local != Notice::LOCAL_NONPUBLIC) &&
2316 ($this->is_local != Notice::GATEWAY));
2321 * Check that the given profile is allowed to read, respond to, or otherwise
2322 * act on this notice.
2324 * The $scope member is a bitmask of scopes, representing a logical AND of the
2325 * scope requirement. So, 0x03 (Notice::ADDRESSEE_SCOPE | Notice::SITE_SCOPE) means
2326 * "only visible to people who are mentioned in the notice AND are users on this site."
2327 * Users on the site who are not mentioned in the notice will not be able to see the
2330 * @param Profile $profile The profile to check; pass null to check for public/unauthenticated users.
2332 * @return boolean whether the profile is in the notice's scope
2334 function inScope($profile)
2336 if (is_null($profile)) {
2337 $keypart = sprintf('notice:in-scope-for:%d:null', $this->id);
2339 $keypart = sprintf('notice:in-scope-for:%d:%d', $this->id, $profile->id);
2342 $result = self::cacheGet($keypart);
2344 if ($result === false) {
2346 if (Event::handle('StartNoticeInScope', array($this, $profile, &$bResult))) {
2347 $bResult = $this->_inScope($profile);
2348 Event::handle('EndNoticeInScope', array($this, $profile, &$bResult));
2350 $result = ($bResult) ? 1 : 0;
2351 self::cacheSet($keypart, $result, 0, 300);
2354 return ($result == 1) ? true : false;
2357 protected function _inScope($profile)
2359 if (!is_null($this->scope)) {
2360 $scope = $this->scope;
2362 $scope = self::defaultScope();
2365 // If there's no scope, anyone (even anon) is in scope.
2367 if ($scope == 0) { // Not private
2369 return !$this->isHiddenSpam($profile);
2371 } else { // Private, somehow
2373 // If there's scope, anon cannot be in scope
2375 if (empty($profile)) {
2379 // Author is always in scope
2381 if ($this->profile_id == $profile->id) {
2385 // Only for users on this site
2387 if (($scope & Notice::SITE_SCOPE) && !$profile->isLocal()) {
2391 // Only for users mentioned in the notice
2393 if ($scope & Notice::ADDRESSEE_SCOPE) {
2395 $reply = Reply::pkeyGet(array('notice_id' => $this->id,
2396 'profile_id' => $profile->id));
2398 if (!$reply instanceof Reply) {
2403 // Only for members of the given group
2405 if ($scope & Notice::GROUP_SCOPE) {
2407 // XXX: just query for the single membership
2409 $groups = $this->getGroups();
2413 foreach ($groups as $group) {
2414 if ($profile->isMember($group)) {
2425 // Only for followers of the author
2429 if ($scope & Notice::FOLLOWER_SCOPE) {
2432 $author = $this->getProfile();
2433 } catch (Exception $e) {
2437 if (!Subscription::exists($profile, $author)) {
2442 return !$this->isHiddenSpam($profile);
2446 function isHiddenSpam($profile) {
2448 // Hide posts by silenced users from everyone but moderators.
2450 if (common_config('notice', 'hidespam')) {
2453 $author = $this->getProfile();
2454 } catch(Exception $e) {
2455 // If we can't get an author, keep it hidden.
2456 // XXX: technically not spam, but, whatever.
2460 if ($author->hasRole(Profile_role::SILENCED)) {
2461 if (!$profile instanceof Profile || (($profile->id !== $author->id) && (!$profile->hasRight(Right::REVIEWSPAM)))) {
2470 public function getParent()
2472 $parent = Notice::getKV('id', $this->reply_to);
2474 if (!$parent instanceof Notice) {
2475 throw new ServerException('Notice has no parent');
2482 * Magic function called at serialize() time.
2484 * We use this to drop a couple process-specific references
2485 * from DB_DataObject which can cause trouble in future
2488 * @return array of variable names to include in serialization.
2493 $vars = parent::__sleep();
2494 $skip = array('_profile', '_groups', '_attachments', '_faves', '_replies', '_repeats');
2495 return array_diff($vars, $skip);
2498 static function defaultScope()
2500 $scope = common_config('notice', 'defaultscope');
2501 if (is_null($scope)) {
2502 if (common_config('site', 'private')) {
2511 static function fillProfiles($notices)
2513 $map = self::getProfiles($notices);
2515 foreach ($notices as $entry=>$notice) {
2517 if (array_key_exists($notice->profile_id, $map)) {
2518 $notice->_setProfile($map[$notice->profile_id]);
2520 } catch (NoProfileException $e) {
2521 common_log(LOG_WARNING, "Failed to fill profile in Notice with non-existing entry for profile_id: {$e->id}");
2522 unset($notices[$entry]);
2526 return array_values($map);
2529 static function getProfiles(&$notices)
2532 foreach ($notices as $notice) {
2533 $ids[] = $notice->profile_id;
2536 $ids = array_unique($ids);
2538 return Profile::pivotGet('id', $ids);
2541 static function fillGroups(&$notices)
2543 $ids = self::_idsOf($notices);
2545 $gis = Group_inbox::listGet('notice_id', $ids);
2549 foreach ($gis as $id => $gi)
2553 $gids[] = $g->group_id;
2557 $gids = array_unique($gids);
2559 $group = User_group::pivotGet('id', $gids);
2561 foreach ($notices as $notice)
2564 $gi = $gis[$notice->id];
2565 foreach ($gi as $g) {
2566 $grps[] = $group[$g->group_id];
2568 $notice->_setGroups($grps);
2572 static function _idsOf(&$notices)
2575 foreach ($notices as $notice) {
2576 $ids[] = $notice->id;
2578 $ids = array_unique($ids);
2582 static function fillAttachments(&$notices)
2584 $ids = self::_idsOf($notices);
2586 $f2pMap = File_to_post::listGet('post_id', $ids);
2590 foreach ($f2pMap as $noticeId => $f2ps) {
2591 foreach ($f2ps as $f2p) {
2592 $fileIds[] = $f2p->file_id;
2596 $fileIds = array_unique($fileIds);
2598 $fileMap = File::pivotGet('id', $fileIds);
2600 foreach ($notices as $notice)
2603 $f2ps = $f2pMap[$notice->id];
2604 foreach ($f2ps as $f2p) {
2605 $files[] = $fileMap[$f2p->file_id];
2607 $notice->_setAttachments($files);
2614 * All faves of this notice
2616 * @return array Array of Fave objects
2621 if (isset($this->_faves) && is_array($this->_faves)) {
2622 return $this->_faves;
2624 $faveMap = Fave::listGet('notice_id', array($this->id));
2625 $this->_faves = $faveMap[$this->id];
2626 return $this->_faves;
2629 function _setFaves($faves)
2631 $this->_faves = $faves;
2634 static function fillFaves(&$notices)
2636 $ids = self::_idsOf($notices);
2637 $faveMap = Fave::listGet('notice_id', $ids);
2640 foreach ($faveMap as $id => $faves) {
2641 $cnt += count($faves);
2642 if (count($faves) > 0) {
2646 foreach ($notices as $notice) {
2647 $faves = $faveMap[$notice->id];
2648 $notice->_setFaves($faves);
2652 static function fillReplies(&$notices)
2654 $ids = self::_idsOf($notices);
2655 $replyMap = Reply::listGet('notice_id', $ids);
2656 foreach ($notices as $notice) {
2657 $replies = $replyMap[$notice->id];
2659 foreach ($replies as $reply) {
2660 $ids[] = $reply->profile_id;
2662 $notice->_setReplies($ids);
2666 protected $_repeats;
2668 function getRepeats()
2670 if (isset($this->_repeats) && is_array($this->_repeats)) {
2671 return $this->_repeats;
2673 $repeatMap = Notice::listGet('repeat_of', array($this->id));
2674 $this->_repeats = $repeatMap[$this->id];
2675 return $this->_repeats;
2678 function _setRepeats($repeats)
2680 $this->_repeats = $repeats;
2683 static function fillRepeats(&$notices)
2685 $ids = self::_idsOf($notices);
2686 $repeatMap = Notice::listGet('repeat_of', $ids);
2687 foreach ($notices as $notice) {
2688 $repeats = $repeatMap[$notice->id];
2689 $notice->_setRepeats($repeats);