3 * StatusNet - the distributed open-source microblogging tool
4 * Copyright (C) 2008-2011 StatusNet, Inc.
6 * This program is free software: you can redistribute it and/or modify
7 * it under the terms of the GNU Affero General Public License as published by
8 * the Free Software Foundation, either version 3 of the License, or
9 * (at your option) any later version.
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU Affero General Public License for more details.
16 * You should have received a copy of the GNU Affero General Public License
17 * along with this program. If not, see <http://www.gnu.org/licenses/>.
21 * @author Brenda Wallace <shiny@cpan.org>
22 * @author Christopher Vollick <psycotica0@gmail.com>
23 * @author CiaranG <ciaran@ciarang.com>
24 * @author Craig Andrews <candrews@integralblue.com>
25 * @author Evan Prodromou <evan@controlezvous.ca>
26 * @author Gina Haeussge <osd@foosel.net>
27 * @author Jeffery To <jeffery.to@gmail.com>
28 * @author Mike Cochrane <mikec@mikenz.geek.nz>
29 * @author Robin Millette <millette@controlyourself.ca>
30 * @author Sarven Capadisli <csarven@controlyourself.ca>
31 * @author Tom Adams <tom@holizz.com>
32 * @author Mikael Nordfeldth <mmn@hethane.se>
33 * @copyright 2009 Free Software Foundation, Inc http://www.fsf.org
34 * @license GNU Affero General Public License http://www.gnu.org/licenses/
37 if (!defined('GNUSOCIAL')) { exit(1); }
40 * Table Definition for notice
43 /* We keep 200 notices, the max number of notices available per API request,
44 * in the memcached cache. */
46 define('NOTICE_CACHE_WINDOW', CachingNoticeStream::CACHE_WINDOW);
48 define('MAX_BOXCARS', 128);
50 class Notice extends Managed_DataObject
53 /* the code below is auto generated do not remove the above tag */
55 public $__table = 'notice'; // table name
56 public $id; // int(4) primary_key not_null
57 public $profile_id; // int(4) multiple_key not_null
58 public $uri; // varchar(255) unique_key
59 public $content; // text
60 public $rendered; // text
61 public $url; // varchar(255)
62 public $created; // datetime multiple_key not_null default_0000-00-00%2000%3A00%3A00
63 public $modified; // timestamp not_null default_CURRENT_TIMESTAMP
64 public $reply_to; // int(4)
65 public $is_local; // int(4)
66 public $source; // varchar(32)
67 public $conversation; // int(4)
68 public $lat; // decimal(10,7)
69 public $lon; // decimal(10,7)
70 public $location_id; // int(4)
71 public $location_ns; // int(4)
72 public $repeat_of; // int(4)
73 public $verb; // varchar(255)
74 public $object_type; // varchar(255)
75 public $scope; // int(4)
77 /* the code above is auto generated do not remove the tag below */
80 public static function schemaDef()
84 'id' => array('type' => 'serial', 'not null' => true, 'description' => 'unique identifier'),
85 'profile_id' => array('type' => 'int', 'not null' => true, 'description' => 'who made the update'),
86 'uri' => array('type' => 'varchar', 'length' => 255, 'description' => 'universally unique identifier, usually a tag URI'),
87 'content' => array('type' => 'text', 'description' => 'update content', 'collate' => 'utf8_general_ci'),
88 'rendered' => array('type' => 'text', 'description' => 'HTML version of the content'),
89 'url' => array('type' => 'varchar', 'length' => 255, 'description' => 'URL of any attachment (image, video, bookmark, whatever)'),
90 'created' => array('type' => 'datetime', 'not null' => true, 'description' => 'date this record was created'),
91 'modified' => array('type' => 'timestamp', 'not null' => true, 'description' => 'date this record was modified'),
92 'reply_to' => array('type' => 'int', 'description' => 'notice replied to (usually a guess)'),
93 'is_local' => array('type' => 'int', 'size' => 'tiny', 'default' => 0, 'description' => 'notice was generated by a user'),
94 'source' => array('type' => 'varchar', 'length' => 32, 'description' => 'source of comment, like "web", "im", or "clientname"'),
95 'conversation' => array('type' => 'int', 'description' => 'id of root notice in this conversation'),
96 'lat' => array('type' => 'numeric', 'precision' => 10, 'scale' => 7, 'description' => 'latitude'),
97 'lon' => array('type' => 'numeric', 'precision' => 10, 'scale' => 7, 'description' => 'longitude'),
98 'location_id' => array('type' => 'int', 'description' => 'location id if possible'),
99 'location_ns' => array('type' => 'int', 'description' => 'namespace for location'),
100 'repeat_of' => array('type' => 'int', 'description' => 'notice this is a repeat of'),
101 'object_type' => array('type' => 'varchar', 'length' => 255, 'description' => 'URI representing activity streams object type', 'default' => 'http://activitystrea.ms/schema/1.0/note'),
102 'verb' => array('type' => 'varchar', 'length' => 255, 'description' => 'URI representing activity streams verb', 'default' => 'http://activitystrea.ms/schema/1.0/post'),
103 'scope' => array('type' => 'int',
104 'description' => 'bit map for distribution scope; 0 = everywhere; 1 = this server only; 2 = addressees; 4 = followers; null = default'),
106 'primary key' => array('id'),
107 'unique keys' => array(
108 'notice_uri_key' => array('uri'),
110 'foreign keys' => array(
111 'notice_profile_id_fkey' => array('profile', array('profile_id' => 'id')),
112 'notice_reply_to_fkey' => array('notice', array('reply_to' => 'id')),
113 'notice_conversation_fkey' => array('conversation', array('conversation' => 'id')), # note... used to refer to notice.id
114 'notice_repeat_of_fkey' => array('notice', array('repeat_of' => 'id')), # @fixme: what about repeats of deleted notices?
117 'notice_created_id_is_local_idx' => array('created', 'id', 'is_local'),
118 'notice_profile_id_idx' => array('profile_id', 'created', 'id'),
119 'notice_repeat_of_created_id_idx' => array('repeat_of', 'created', 'id'),
120 'notice_conversation_created_id_idx' => array('conversation', 'created', 'id'),
121 'notice_replyto_idx' => array('reply_to')
125 if (common_config('search', 'type') == 'fulltext') {
126 $def['fulltext indexes'] = array('content' => array('content'));
133 const LOCAL_PUBLIC = 1;
135 const LOCAL_NONPUBLIC = -1;
138 const PUBLIC_SCOPE = 0; // Useful fake constant
139 const SITE_SCOPE = 1;
140 const ADDRESSEE_SCOPE = 2;
141 const GROUP_SCOPE = 4;
142 const FOLLOWER_SCOPE = 8;
144 protected $_profile = -1;
146 public function getProfile()
148 if ($this->_profile === -1) {
149 $this->_setProfile(Profile::getKV('id', $this->profile_id));
151 return $this->_profile;
154 public function _setProfile(Profile $profile=null)
156 if (!$profile instanceof Profile) {
157 throw new NoProfileException($this->profile_id);
159 $this->_profile = $profile;
162 function delete($useWhere=false)
164 // For auditing purposes, save a record that the notice
167 // @fixme we have some cases where things get re-run and so the
169 $deleted = Deleted_notice::getKV('id', $this->id);
171 if (!$deleted instanceof Deleted_notice) {
172 $deleted = Deleted_notice::getKV('uri', $this->uri);
175 if (!$deleted instanceof Deleted_notice) {
176 $deleted = new Deleted_notice();
178 $deleted->id = $this->id;
179 $deleted->profile_id = $this->profile_id;
180 $deleted->uri = $this->uri;
181 $deleted->created = $this->created;
182 $deleted->deleted = common_sql_now();
187 if (Event::handle('NoticeDeleteRelated', array($this))) {
189 // Clear related records
191 $this->clearReplies();
192 $this->clearRepeats();
195 $this->clearGroupInboxes();
197 $this->clearAttentions();
199 // NOTE: we don't clear queue items
202 $result = parent::delete($useWhere);
204 $this->blowOnDelete();
208 public function getUri()
213 public function getUrl()
215 // The risk is we start having empty urls and non-http uris...
216 // and we can't really handle any other protocol right now.
218 case common_valid_http_url($this->url):
220 case common_valid_http_url($this->uri):
223 throw new ServerException('No URL available for notice.');
227 public function get_object_type($canonical=false) {
229 ? ActivityObject::canonicalType($this->object_type)
230 : $this->object_type;
233 public static function getByUri($uri)
235 $notice = new Notice();
237 if (!$notice->find(true)) {
238 throw new NoResultException($notice);
244 * Extract #hashtags from this notice's content and save them to the database.
248 /* extract all #hastags */
249 $count = preg_match_all('/(?:^|\s)#([\pL\pN_\-\.]{1,64})/u', strtolower($this->content), $match);
254 /* Add them to the database */
255 return $this->saveKnownTags($match[1]);
259 * Record the given set of hash tags in the db for this notice.
260 * Given tag strings will be normalized and checked for dupes.
262 function saveKnownTags($hashtags)
264 //turn each into their canonical tag
265 //this is needed to remove dupes before saving e.g. #hash.tag = #hashtag
266 for($i=0; $i<count($hashtags); $i++) {
267 /* elide characters we don't want in the tag */
268 $hashtags[$i] = common_canonical_tag($hashtags[$i]);
271 foreach(array_unique($hashtags) as $hashtag) {
272 $this->saveTag($hashtag);
273 self::blow('profile:notice_ids_tagged:%d:%s', $this->profile_id, $hashtag);
279 * Record a single hash tag as associated with this notice.
280 * Tag format and uniqueness must be validated by caller.
282 function saveTag($hashtag)
284 $tag = new Notice_tag();
285 $tag->notice_id = $this->id;
286 $tag->tag = $hashtag;
287 $tag->created = $this->created;
288 $id = $tag->insert();
291 // TRANS: Server exception. %s are the error details.
292 throw new ServerException(sprintf(_('Database error inserting hashtag: %s.'),
293 $last_error->message));
297 // if it's saved, blow its cache
298 $tag->blowCache(false);
302 * Save a new notice and push it out to subscribers' inboxes.
303 * Poster's permissions are checked before sending.
305 * @param int $profile_id Profile ID of the poster
306 * @param string $content source message text; links may be shortened
307 * per current user's preference
308 * @param string $source source key ('web', 'api', etc)
309 * @param array $options Associative array of optional properties:
310 * string 'created' timestamp of notice; defaults to now
311 * int 'is_local' source/gateway ID, one of:
312 * Notice::LOCAL_PUBLIC - Local, ok to appear in public timeline
313 * Notice::REMOTE - Sent from a remote service;
314 * hide from public timeline but show in
315 * local "and friends" timelines
316 * Notice::LOCAL_NONPUBLIC - Local, but hide from public timeline
317 * Notice::GATEWAY - From another non-OStatus service;
318 * will not appear in public views
319 * float 'lat' decimal latitude for geolocation
320 * float 'lon' decimal longitude for geolocation
321 * int 'location_id' geoname identifier
322 * int 'location_ns' geoname namespace to interpret location_id
323 * int 'reply_to'; notice ID this is a reply to
324 * int 'repeat_of'; notice ID this is a repeat of
325 * string 'uri' unique ID for notice; a unique tag uri (can be url or anything too)
326 * string 'url' permalink to notice; defaults to local notice URL
327 * string 'rendered' rendered HTML version of content
328 * array 'replies' list of profile URIs for reply delivery in
329 * place of extracting @-replies from content.
330 * array 'groups' list of group IDs to deliver to, in place of
331 * extracting ! tags from content
332 * array 'tags' list of hashtag strings to save with the notice
333 * in place of extracting # tags from content
334 * array 'urls' list of attached/referred URLs to save with the
335 * notice in place of extracting links from content
336 * boolean 'distribute' whether to distribute the notice, default true
337 * string 'object_type' URL of the associated object type (default ActivityObject::NOTE)
338 * string 'verb' URL of the associated verb (default ActivityVerb::POST)
339 * int 'scope' Scope bitmask; default to SITE_SCOPE on private sites, 0 otherwise
341 * @fixme tag override
344 * @throws ClientException
346 static function saveNew($profile_id, $content, $source, array $options=null) {
347 $defaults = array('uri' => null,
352 'distribute' => true,
353 'object_type' => null,
356 if (!empty($options) && is_array($options)) {
357 $options = array_merge($defaults, $options);
363 if (!isset($is_local)) {
364 $is_local = Notice::LOCAL_PUBLIC;
367 $profile = Profile::getKV('id', $profile_id);
368 if (!$profile instanceof Profile) {
369 // TRANS: Client exception thrown when trying to save a notice for an unknown user.
370 throw new ClientException(_('Problem saving notice. Unknown user.'));
373 $user = User::getKV('id', $profile_id);
374 if ($user instanceof User) {
375 // Use the local user's shortening preferences, if applicable.
376 $final = $user->shortenLinks($content);
378 $final = common_shorten_links($content);
381 if (Notice::contentTooLong($final)) {
382 // TRANS: Client exception thrown if a notice contains too many characters.
383 throw new ClientException(_('Problem saving notice. Too long.'));
386 if (common_config('throttle', 'enabled') && !Notice::checkEditThrottle($profile_id)) {
387 common_log(LOG_WARNING, 'Excessive posting by profile #' . $profile_id . '; throttled.');
388 // TRANS: Client exception thrown when a user tries to post too many notices in a given time frame.
389 throw new ClientException(_('Too many notices too fast; take a breather '.
390 'and post again in a few minutes.'));
393 if (common_config('site', 'dupelimit') > 0 && !Notice::checkDupes($profile_id, $final)) {
394 common_log(LOG_WARNING, 'Dupe posting by profile #' . $profile_id . '; throttled.');
395 // TRANS: Client exception thrown when a user tries to post too many duplicate notices in a given time frame.
396 throw new ClientException(_('Too many duplicate messages too quickly;'.
397 ' take a breather and post again in a few minutes.'));
400 if (!$profile->hasRight(Right::NEWNOTICE)) {
401 common_log(LOG_WARNING, "Attempted post from user disallowed to post: " . $profile->nickname);
403 // TRANS: Client exception thrown when a user tries to post while being banned.
404 throw new ClientException(_('You are banned from posting notices on this site.'), 403);
407 $notice = new Notice();
408 $notice->profile_id = $profile_id;
410 $autosource = common_config('public', 'autosource');
412 // Sandboxed are non-false, but not 1, either
414 if (!$profile->hasRight(Right::PUBLICNOTICE) ||
415 ($source && $autosource && in_array($source, $autosource))) {
416 $notice->is_local = Notice::LOCAL_NONPUBLIC;
418 $notice->is_local = $is_local;
421 if (!empty($created)) {
422 $notice->created = $created;
424 $notice->created = common_sql_now();
427 if (!$notice->isLocal()) {
428 // Only do these checks for non-local notices. Local notices will generate these values later.
429 if (!common_valid_http_url($url)) {
430 common_debug('Bad notice URL: ['.$url.'] Cannot link back to original!');
433 throw new ServerException('No URI for remote notice. Cannot accept that.');
437 $notice->content = $final;
439 $notice->source = $source;
443 // Get the groups here so we can figure out replies and such
444 if (!isset($groups)) {
445 $groups = User_group::idsFromText($notice->content, $profile);
450 // Handle repeat case
452 if (isset($repeat_of)) {
454 // Check for a private one
456 $repeat = Notice::getKV('id', $repeat_of);
458 if (!($repeat instanceof Notice)) {
459 // TRANS: Client exception thrown in notice when trying to repeat a missing or deleted notice.
460 throw new ClientException(_('Cannot repeat; original notice is missing or deleted.'));
463 if ($profile->id == $repeat->profile_id) {
464 // TRANS: Client error displayed when trying to repeat an own notice.
465 throw new ClientException(_('You cannot repeat your own notice.'));
468 if ($repeat->scope != Notice::SITE_SCOPE &&
469 $repeat->scope != Notice::PUBLIC_SCOPE) {
470 // TRANS: Client error displayed when trying to repeat a non-public notice.
471 throw new ClientException(_('Cannot repeat a private notice.'), 403);
474 if (!$repeat->inScope($profile)) {
475 // The generic checks above should cover this, but let's be sure!
476 // TRANS: Client error displayed when trying to repeat a notice you cannot access.
477 throw new ClientException(_('Cannot repeat a notice you cannot read.'), 403);
480 if ($profile->hasRepeated($repeat)) {
481 // TRANS: Client error displayed when trying to repeat an already repeated notice.
482 throw new ClientException(_('You already repeated that notice.'));
485 $notice->repeat_of = $repeat_of;
487 $reply = self::getReplyTo($reply_to, $profile_id, $source, $final);
489 if (!empty($reply)) {
491 if (!$reply->inScope($profile)) {
492 // TRANS: Client error displayed when trying to reply to a notice a the target has no access to.
493 // TRANS: %1$s is a user nickname, %2$d is a notice ID (number).
494 throw new ClientException(sprintf(_('%1$s has no access to notice %2$d.'),
495 $profile->nickname, $reply->id), 403);
498 $notice->reply_to = $reply->id;
499 $notice->conversation = $reply->conversation;
501 // If the original is private to a group, and notice has no group specified,
502 // make it to the same group(s)
504 if (empty($groups) && ($reply->scope & Notice::GROUP_SCOPE)) {
506 $replyGroups = $reply->getGroups();
507 foreach ($replyGroups as $group) {
508 if ($profile->isMember($group)) {
509 $groups[] = $group->id;
518 if (!empty($lat) && !empty($lon)) {
523 if (!empty($location_ns) && !empty($location_id)) {
524 $notice->location_id = $location_id;
525 $notice->location_ns = $location_ns;
528 if (!empty($rendered)) {
529 $notice->rendered = $rendered;
531 $notice->rendered = common_render_content($final, $notice);
535 if (!empty($notice->repeat_of)) {
536 $notice->verb = ActivityVerb::SHARE;
537 $notice->object_type = ActivityObject::ACTIVITY;
539 $notice->verb = ActivityVerb::POST;
542 $notice->verb = $verb;
545 if (empty($object_type)) {
546 $notice->object_type = (empty($notice->reply_to)) ? ActivityObject::NOTE : ActivityObject::COMMENT;
548 $notice->object_type = $object_type;
551 if (is_null($scope)) { // 0 is a valid value
552 if (!empty($reply)) {
553 $notice->scope = $reply->scope;
555 $notice->scope = self::defaultScope();
558 $notice->scope = $scope;
561 // For private streams
564 $user = $profile->getUser();
566 if ($user->private_stream &&
567 ($notice->scope == Notice::PUBLIC_SCOPE ||
568 $notice->scope == Notice::SITE_SCOPE)) {
569 $notice->scope |= Notice::FOLLOWER_SCOPE;
571 } catch (NoSuchUserException $e) {
572 // Cannot handle private streams for remote profiles
575 // Force the scope for private groups
577 foreach ($groups as $groupId) {
578 $group = User_group::getKV('id', $groupId);
579 if ($group instanceof User_group) {
580 if ($group->force_scope) {
581 $notice->scope |= Notice::GROUP_SCOPE;
587 if (Event::handle('StartNoticeSave', array(&$notice))) {
589 // XXX: some of these functions write to the DB
591 $id = $notice->insert();
594 common_log_db_error($notice, 'INSERT', __FILE__);
595 // TRANS: Server exception thrown when a notice cannot be saved.
596 throw new ServerException(_('Problem saving notice.'));
599 // Update ID-dependent columns: URI, conversation
601 $orig = clone($notice);
606 $notice->uri = sprintf('%s%s=%d:%s=%s',
608 'noticeId', $notice->id,
609 'objectType', $notice->get_object_type(true));
614 $notice->url = common_local_url('shownotice', array('notice' => $notice->id), null, null, false);
618 // If it's not part of a conversation, it's
619 // the beginning of a new conversation.
621 if (empty($notice->conversation)) {
622 $conv = Conversation::create($notice);
623 $notice->conversation = $conv->id;
628 if ($notice->update($orig) === false) {
629 common_log_db_error($notice, 'UPDATE', __FILE__);
630 // TRANS: Server exception thrown when a notice cannot be updated.
631 throw new ServerException(_('Problem saving notice.'));
637 // Clear the cache for subscribed users, so they'll update at next request
638 // XXX: someone clever could prepend instead of clearing the cache
640 $notice->blowOnInsert();
642 // Save per-notice metadata...
644 if (isset($replies)) {
645 $notice->saveKnownReplies($replies);
647 $notice->saveReplies();
651 $notice->saveKnownTags($tags);
656 // Note: groups may save tags, so must be run after tags are saved
657 // to avoid errors on duplicates.
658 // Note: groups should always be set.
660 $notice->saveKnownGroups($groups);
663 $notice->saveKnownUrls($urls);
669 // Prepare inbox delivery, may be queued to background.
670 $notice->distribute();
676 function blowOnInsert($conversation = false)
678 $this->blowStream('profile:notice_ids:%d', $this->profile_id);
680 if ($this->isPublic()) {
681 $this->blowStream('public');
684 self::blow('notice:list-ids:conversation:%s', $this->conversation);
685 self::blow('conversation:notice_count:%d', $this->conversation);
687 if (!empty($this->repeat_of)) {
688 // XXX: we should probably only use one of these
689 $this->blowStream('notice:repeats:%d', $this->repeat_of);
690 self::blow('notice:list-ids:repeat_of:%d', $this->repeat_of);
693 $original = Notice::getKV('id', $this->repeat_of);
695 if ($original instanceof Notice) {
696 $originalUser = User::getKV('id', $original->profile_id);
697 if ($originalUser instanceof User) {
698 $this->blowStream('user:repeats_of_me:%d', $originalUser->id);
702 $profile = Profile::getKV($this->profile_id);
704 if ($profile instanceof Profile) {
705 $profile->blowNoticeCount();
708 $ptags = $this->getProfileTags();
709 foreach ($ptags as $ptag) {
710 $ptag->blowNoticeStreamCache();
715 * Clear cache entries related to this notice at delete time.
716 * Necessary to avoid breaking paging on public, profile timelines.
718 function blowOnDelete()
720 $this->blowOnInsert();
722 self::blow('profile:notice_ids:%d;last', $this->profile_id);
724 if ($this->isPublic()) {
725 self::blow('public;last');
728 self::blow('fave:by_notice', $this->id);
730 if ($this->conversation) {
731 // In case we're the first, will need to calc a new root.
732 self::blow('notice:conversation_root:%d', $this->conversation);
735 $ptags = $this->getProfileTags();
736 foreach ($ptags as $ptag) {
737 $ptag->blowNoticeStreamCache(true);
741 function blowStream()
743 $c = self::memcache();
749 $args = func_get_args();
751 $format = array_shift($args);
753 $keyPart = vsprintf($format, $args);
755 $cacheKey = Cache::key($keyPart);
757 $c->delete($cacheKey);
759 // delete the "last" stream, too, if this notice is
760 // older than the top of that stream
762 $lastKey = $cacheKey.';last';
764 $lastStr = $c->get($lastKey);
766 if ($lastStr !== false) {
767 $window = explode(',', $lastStr);
768 $lastID = $window[0];
769 $lastNotice = Notice::getKV('id', $lastID);
770 if (!$lastNotice instanceof Notice // just weird
771 || strtotime($lastNotice->created) >= strtotime($this->created)) {
772 $c->delete($lastKey);
777 /** save all urls in the notice to the db
779 * follow redirects and save all available file information
780 * (mimetype, date, size, oembed, etc.)
784 function saveUrls() {
785 if (common_config('attachments', 'process_links')) {
786 common_replace_urls_callback($this->content, array($this, 'saveUrl'), $this->id);
791 * Save the given URLs as related links/attachments to the db
793 * follow redirects and save all available file information
794 * (mimetype, date, size, oembed, etc.)
798 function saveKnownUrls($urls)
800 if (common_config('attachments', 'process_links')) {
801 // @fixme validation?
802 foreach (array_unique($urls) as $url) {
803 File::processNew($url, $this->id);
811 function saveUrl($url, $notice_id) {
812 File::processNew($url, $notice_id);
815 static function checkDupes($profile_id, $content) {
816 $profile = Profile::getKV($profile_id);
817 if (!$profile instanceof Profile) {
820 $notice = $profile->getNotices(0, CachingNoticeStream::CACHE_WINDOW);
821 if (!empty($notice)) {
823 while ($notice->fetch()) {
824 if (time() - strtotime($notice->created) >= common_config('site', 'dupelimit')) {
826 } else if ($notice->content == $content) {
831 // If we get here, oldest item in cache window is not
832 // old enough for dupe limit; do direct check against DB
833 $notice = new Notice();
834 $notice->profile_id = $profile_id;
835 $notice->content = $content;
836 $threshold = common_sql_date(time() - common_config('site', 'dupelimit'));
837 $notice->whereAdd(sprintf("created > '%s'", $notice->escape($threshold)));
839 $cnt = $notice->count();
843 static function checkEditThrottle($profile_id) {
844 $profile = Profile::getKV($profile_id);
845 if (!$profile instanceof Profile) {
848 // Get the Nth notice
849 $notice = $profile->getNotices(common_config('throttle', 'count') - 1, 1);
850 if ($notice && $notice->fetch()) {
851 // If the Nth notice was posted less than timespan seconds ago
852 if (time() - strtotime($notice->created) <= common_config('throttle', 'timespan')) {
857 // Either not N notices in the stream, OR the Nth was not posted within timespan seconds
861 protected $_attachments = -1;
863 function attachments() {
865 if ($this->_attachments != -1) {
866 return $this->_attachments;
869 $f2ps = File_to_post::listGet('post_id', array($this->id));
873 foreach ($f2ps[$this->id] as $f2p) {
874 $ids[] = $f2p->file_id;
877 $files = File::multiGet('id', $ids);
879 $this->_attachments = $files->fetchAll();
881 return $this->_attachments;
884 function _setAttachments($attachments)
886 $this->_attachments = $attachments;
889 function publicStream($offset=0, $limit=20, $since_id=0, $max_id=0)
891 $stream = new PublicNoticeStream();
892 return $stream->getNotices($offset, $limit, $since_id, $max_id);
896 function conversationStream($id, $offset=0, $limit=20, $since_id=0, $max_id=0)
898 $stream = new ConversationNoticeStream($id);
900 return $stream->getNotices($offset, $limit, $since_id, $max_id);
904 * Is this notice part of an active conversation?
906 * @return boolean true if other messages exist in the same
907 * conversation, false if this is the only one
909 function hasConversation()
911 if (!empty($this->conversation)) {
912 $conversation = Notice::conversationStream(
918 if ($conversation->N > 0) {
926 * Grab the earliest notice from this conversation.
928 * @return Notice or null
930 function conversationRoot($profile=-1)
932 // XXX: can this happen?
934 if (empty($this->conversation)) {
938 // Get the current profile if not specified
940 if (is_int($profile) && $profile == -1) {
941 $profile = Profile::current();
944 // If this notice is out of scope, no root for you!
946 if (!$this->inScope($profile)) {
950 // If this isn't a reply to anything, then it's its own
953 if (empty($this->reply_to)) {
957 if (is_null($profile)) {
958 $keypart = sprintf('notice:conversation_root:%d:null', $this->id);
960 $keypart = sprintf('notice:conversation_root:%d:%d',
965 $root = self::cacheGet($keypart);
967 if ($root !== false && $root->inScope($profile)) {
974 $parent = $last->getParent();
975 if ($parent->inScope($profile)) {
979 } catch (Exception $e) {
980 // Latest notice has no parent
982 // No parent, or parent out of scope
987 self::cacheSet($keypart, $root);
993 * Pull up a full list of local recipients who will be getting
994 * this notice in their inbox. Results will be cached, so don't
995 * change the input data wily-nilly!
997 * @param array $groups optional list of Group objects;
998 * if left empty, will be loaded from group_inbox records
999 * @param array $recipient optional list of reply profile ids
1000 * if left empty, will be loaded from reply records
1001 * @return array associating recipient user IDs with an inbox source constant
1003 function whoGets(array $groups=null, array $recipients=null)
1005 $c = self::memcache();
1008 $ni = $c->get(Cache::key('notice:who_gets:'.$this->id));
1009 if ($ni !== false) {
1014 if (is_null($recipients)) {
1015 $recipients = $this->getReplies();
1020 // Give plugins a chance to add folks in at start...
1021 if (Event::handle('StartNoticeWhoGets', array($this, &$ni))) {
1023 $users = $this->getSubscribedUsers();
1024 foreach ($users as $id) {
1025 $ni[$id] = NOTICE_INBOX_SOURCE_SUB;
1028 if (is_null($groups)) {
1029 $groups = $this->getGroups();
1031 foreach ($groups as $group) {
1032 $users = $group->getUserMembers();
1033 foreach ($users as $id) {
1034 if (!array_key_exists($id, $ni)) {
1035 $ni[$id] = NOTICE_INBOX_SOURCE_GROUP;
1040 $ptAtts = $this->getAttentionsFromProfileTags();
1041 foreach ($ptAtts as $key=>$val) {
1042 if (!array_key_exists($key, $ni)) {
1047 foreach ($recipients as $recipient) {
1048 if (!array_key_exists($recipient, $ni)) {
1049 $ni[$recipient] = NOTICE_INBOX_SOURCE_REPLY;
1053 // Exclude any deleted, non-local, or blocking recipients.
1054 $profile = $this->getProfile();
1055 $originalProfile = null;
1056 if ($this->repeat_of) {
1057 // Check blocks against the original notice's poster as well.
1058 $original = Notice::getKV('id', $this->repeat_of);
1059 if ($original instanceof Notice) {
1060 $originalProfile = $original->getProfile();
1064 foreach ($ni as $id => $source) {
1066 $user = User::getKV('id', $id);
1067 if (!$user instanceof User ||
1068 $user->hasBlocked($profile) ||
1069 ($originalProfile && $user->hasBlocked($originalProfile))) {
1072 } catch (UserNoProfileException $e) {
1073 // User doesn't have a profile; invalid; skip them.
1078 // Give plugins a chance to filter out...
1079 Event::handle('EndNoticeWhoGets', array($this, &$ni));
1083 // XXX: pack this data better
1084 $c->set(Cache::key('notice:who_gets:'.$this->id), $ni);
1090 function getSubscribedUsers()
1094 if(common_config('db','quote_identifiers'))
1095 $user_table = '"user"';
1096 else $user_table = 'user';
1100 'FROM '. $user_table .' JOIN subscription '.
1101 'ON '. $user_table .'.id = subscription.subscriber ' .
1102 'WHERE subscription.subscribed = %d ';
1104 $user->query(sprintf($qry, $this->profile_id));
1108 while ($user->fetch()) {
1117 function getProfileTags()
1119 $profile = $this->getProfile();
1120 $list = $profile->getOtherTags($profile);
1123 while($list->fetch()) {
1124 $ptags[] = clone($list);
1130 public function getAttentionsFromProfileTags()
1133 $ptags = $this->getProfileTags();
1134 foreach ($ptags as $ptag) {
1135 $users = $ptag->getUserSubscribers();
1136 foreach ($users as $id) {
1137 $ni[$id] = NOTICE_INBOX_SOURCE_PROFILE_TAG;
1144 * Record this notice to the given group inboxes for delivery.
1145 * Overrides the regular parsing of !group markup.
1147 * @param string $group_ids
1148 * @fixme might prefer URIs as identifiers, as for replies?
1149 * best with generalizations on user_group to support
1150 * remote groups better.
1152 function saveKnownGroups($group_ids)
1154 if (!is_array($group_ids)) {
1155 // TRANS: Server exception thrown when no array is provided to the method saveKnownGroups().
1156 throw new ServerException(_('Bad type provided to saveKnownGroups.'));
1160 foreach (array_unique($group_ids) as $id) {
1161 $group = User_group::getKV('id', $id);
1162 if ($group instanceof User_group) {
1163 common_log(LOG_ERR, "Local delivery to group id $id, $group->nickname");
1164 $result = $this->addToGroupInbox($group);
1166 common_log_db_error($gi, 'INSERT', __FILE__);
1169 if (common_config('group', 'addtag')) {
1170 // we automatically add a tag for every group name, too
1172 $tag = Notice_tag::pkeyGet(array('tag' => common_canonical_tag($group->nickname),
1173 'notice_id' => $this->id));
1175 if (is_null($tag)) {
1176 $this->saveTag($group->nickname);
1180 $groups[] = clone($group);
1182 common_log(LOG_ERR, "Local delivery to group id $id skipped, doesn't exist");
1189 function addToGroupInbox(User_group $group)
1191 $gi = Group_inbox::pkeyGet(array('group_id' => $group->id,
1192 'notice_id' => $this->id));
1194 if (!$gi instanceof Group_inbox) {
1196 $gi = new Group_inbox();
1198 $gi->group_id = $group->id;
1199 $gi->notice_id = $this->id;
1200 $gi->created = $this->created;
1202 $result = $gi->insert();
1205 common_log_db_error($gi, 'INSERT', __FILE__);
1206 // TRANS: Server exception thrown when an update for a group inbox fails.
1207 throw new ServerException(_('Problem saving group inbox.'));
1210 self::blow('user_group:notice_ids:%d', $gi->group_id);
1217 * Save reply records indicating that this notice needs to be
1218 * delivered to the local users with the given URIs.
1220 * Since this is expected to be used when saving foreign-sourced
1221 * messages, we won't deliver to any remote targets as that's the
1222 * source service's responsibility.
1224 * Mail notifications etc will be handled later.
1226 * @param array $uris Array of unique identifier URIs for recipients
1228 function saveKnownReplies(array $uris)
1234 $sender = Profile::getKV($this->profile_id);
1236 foreach (array_unique($uris) as $uri) {
1238 $profile = Profile::fromURI($uri);
1240 if (!$profile instanceof Profile) {
1241 common_log(LOG_WARNING, "Unable to determine profile for URI '$uri'");
1245 if ($profile->hasBlocked($sender)) {
1246 common_log(LOG_INFO, "Not saving reply to profile {$profile->id} ($uri) from sender {$sender->id} because of a block.");
1250 $this->saveReply($profile->id);
1251 self::blow('reply:stream:%d', $profile->id);
1258 * Pull @-replies from this message's content in StatusNet markup format
1259 * and save reply records indicating that this message needs to be
1260 * delivered to those users.
1262 * Mail notifications to local profiles will be sent later.
1264 * @return array of integer profile IDs
1267 function saveReplies()
1269 // Don't save reply data for repeats
1271 if (!empty($this->repeat_of)) {
1275 $sender = Profile::getKV($this->profile_id);
1279 // If it's a reply, save for the replied-to author
1281 $parent = $this->getParent();
1282 $author = $parent->getProfile();
1283 if ($author instanceof Profile) {
1284 $this->saveReply($author->id);
1285 $replied[$author->id] = 1;
1286 self::blow('reply:stream:%d', $author->id);
1288 } catch (Exception $e) {
1289 // Not a reply, since it has no parent!
1292 // @todo ideally this parser information would only
1293 // be calculated once.
1295 $mentions = common_find_mentions($this->content, $this);
1297 // store replied only for first @ (what user/notice what the reply directed,
1298 // we assume first @ is it)
1300 foreach ($mentions as $mention) {
1302 foreach ($mention['mentioned'] as $mentioned) {
1304 // skip if they're already covered
1306 if (!empty($replied[$mentioned->id])) {
1310 // Don't save replies from blocked profile to local user
1312 $mentioned_user = User::getKV('id', $mentioned->id);
1313 if ($mentioned_user instanceof User && $mentioned_user->hasBlocked($sender)) {
1317 $this->saveReply($mentioned->id);
1318 $replied[$mentioned->id] = 1;
1319 self::blow('reply:stream:%d', $mentioned->id);
1323 $recipientIds = array_keys($replied);
1325 return $recipientIds;
1328 function saveReply($profileId)
1330 $reply = new Reply();
1332 $reply->notice_id = $this->id;
1333 $reply->profile_id = $profileId;
1334 $reply->modified = $this->created;
1341 protected $_replies = -1;
1344 * Pull the complete list of @-reply targets for this notice.
1346 * @return array of integer profile ids
1348 function getReplies()
1350 if ($this->_replies != -1) {
1351 return $this->_replies;
1354 $replyMap = Reply::listGet('notice_id', array($this->id));
1358 foreach ($replyMap[$this->id] as $reply) {
1359 $ids[] = $reply->profile_id;
1362 $this->_replies = $ids;
1367 function _setReplies($replies)
1369 $this->_replies = $replies;
1373 * Pull the complete list of @-reply targets for this notice.
1375 * @return array of Profiles
1377 function getReplyProfiles()
1379 $ids = $this->getReplies();
1381 $profiles = Profile::multiGet('id', $ids);
1383 return $profiles->fetchAll();
1387 * Send e-mail notifications to local @-reply targets.
1389 * Replies must already have been saved; this is expected to be run
1390 * from the distrib queue handler.
1392 function sendReplyNotifications()
1394 // Don't send reply notifications for repeats
1396 if (!empty($this->repeat_of)) {
1400 $recipientIds = $this->getReplies();
1402 foreach ($recipientIds as $recipientId) {
1403 $user = User::getKV('id', $recipientId);
1404 if ($user instanceof User) {
1405 mail_notify_attn($user, $this);
1411 * Pull list of groups this notice needs to be delivered to,
1412 * as previously recorded by saveKnownGroups().
1414 * @return array of Group objects
1417 protected $_groups = -1;
1419 function getGroups()
1421 // Don't save groups for repeats
1423 if (!empty($this->repeat_of)) {
1427 if ($this->_groups != -1)
1429 return $this->_groups;
1432 $gis = Group_inbox::listGet('notice_id', array($this->id));
1436 foreach ($gis[$this->id] as $gi)
1438 $ids[] = $gi->group_id;
1441 $groups = User_group::multiGet('id', $ids);
1443 $this->_groups = $groups->fetchAll();
1445 return $this->_groups;
1448 function _setGroups($groups)
1450 $this->_groups = $groups;
1454 * Convert a notice into an activity for export.
1456 * @param User $cur Current user
1458 * @return Activity activity object representing this Notice.
1461 function asActivity($cur=null)
1463 $act = self::cacheGet(Cache::codeKey('notice:as-activity:'.$this->id));
1465 if ($act instanceof Activity) {
1468 $act = new Activity();
1470 if (Event::handle('StartNoticeAsActivity', array($this, &$act))) {
1472 $act->id = $this->uri;
1473 $act->time = strtotime($this->created);
1474 $act->link = $this->bestUrl();
1475 $act->content = common_xml_safe_str($this->rendered);
1477 $profile = $this->getProfile();
1479 $act->actor = ActivityObject::fromProfile($profile);
1480 $act->actor->extra[] = $profile->profileInfo($cur);
1482 $act->verb = $this->verb;
1484 if ($this->repeat_of) {
1485 $repeated = Notice::getKV('id', $this->repeat_of);
1486 if ($repeated instanceof Notice) {
1487 $act->objects[] = $repeated->asActivity($cur);
1490 $act->objects[] = ActivityObject::fromNotice($this);
1493 // XXX: should this be handled by default processing for object entry?
1497 $tags = $this->getTags();
1499 foreach ($tags as $tag) {
1500 $cat = new AtomCategory();
1503 $act->categories[] = $cat;
1507 // XXX: use Atom Media and/or File activity objects instead
1509 $attachments = $this->attachments();
1511 foreach ($attachments as $attachment) {
1512 // Save local attachments
1513 if (!empty($attachment->filename)) {
1514 $act->attachments[] = ActivityObject::fromFile($attachment);
1518 $ctx = new ActivityContext();
1521 $reply = $this->getParent();
1522 $ctx->replyToID = $reply->uri;
1523 $ctx->replyToUrl = $reply->bestUrl();
1524 } catch (Exception $e) {
1525 // This is not a reply to something
1528 $ctx->location = $this->getLocation();
1532 if (!empty($this->conversation)) {
1533 $conv = Conversation::getKV('id', $this->conversation);
1534 if ($conv instanceof Conversation) {
1535 $ctx->conversation = $conv->uri;
1539 $reply_ids = $this->getReplies();
1541 foreach ($reply_ids as $id) {
1542 $rprofile = Profile::getKV('id', $id);
1543 if ($rprofile instanceof Profile) {
1544 $ctx->attention[$rprofile->getUri()] = ActivityObject::PERSON;
1548 $groups = $this->getGroups();
1550 foreach ($groups as $group) {
1551 $ctx->attention[$group->getUri()] = ActivityObject::GROUP;
1554 switch ($this->scope) {
1555 case Notice::PUBLIC_SCOPE:
1556 $ctx->attention[ActivityContext::ATTN_PUBLIC] = ActivityObject::COLLECTION;
1558 case Notice::FOLLOWER_SCOPE:
1559 $surl = common_local_url("subscribers", array('nickname' => $profile->nickname));
1560 $ctx->attention[$surl] = ActivityObject::COLLECTION;
1564 $act->context = $ctx;
1566 $source = $this->getSource();
1568 if ($source instanceof Notice_source) {
1569 $act->generator = ActivityObject::fromNoticeSource($source);
1574 $atom_feed = $profile->getAtomFeed();
1576 if (!empty($atom_feed)) {
1578 $act->source = new ActivitySource();
1580 // XXX: we should store the actual feed ID
1582 $act->source->id = $atom_feed;
1584 // XXX: we should store the actual feed title
1586 $act->source->title = $profile->getBestName();
1588 $act->source->links['alternate'] = $profile->profileurl;
1589 $act->source->links['self'] = $atom_feed;
1591 $act->source->icon = $profile->avatarUrl(AVATAR_PROFILE_SIZE);
1593 $notice = $profile->getCurrentNotice();
1595 if ($notice instanceof Notice) {
1596 $act->source->updated = self::utcDate($notice->created);
1599 $user = User::getKV('id', $profile->id);
1601 if ($user instanceof User) {
1602 $act->source->links['license'] = common_config('license', 'url');
1606 if ($this->isLocal()) {
1607 $act->selfLink = common_local_url('ApiStatusesShow', array('id' => $this->id,
1608 'format' => 'atom'));
1609 $act->editLink = $act->selfLink;
1612 Event::handle('EndNoticeAsActivity', array($this, &$act));
1615 self::cacheSet(Cache::codeKey('notice:as-activity:'.$this->id), $act);
1620 // This has gotten way too long. Needs to be sliced up into functional bits
1621 // or ideally exported to a utility class.
1623 function asAtomEntry($namespace=false,
1628 $act = $this->asActivity($cur);
1629 $act->extra[] = $this->noticeInfo($cur);
1630 return $act->asString($namespace, $author, $source);
1634 * Extra notice info for atom entries
1636 * Clients use some extra notice info in the atom stream.
1637 * This gives it to them.
1639 * @param User $cur Current user
1641 * @return array representation of <statusnet:notice_info> element
1644 function noticeInfo($cur)
1646 // local notice ID (useful to clients for ordering)
1648 $noticeInfoAttr = array('local_id' => $this->id);
1652 $ns = $this->getSource();
1654 if ($ns instanceof Notice_source) {
1655 $noticeInfoAttr['source'] = $ns->code;
1656 if (!empty($ns->url)) {
1657 $noticeInfoAttr['source_link'] = $ns->url;
1658 if (!empty($ns->name)) {
1659 $noticeInfoAttr['source'] = '<a href="'
1660 . htmlspecialchars($ns->url)
1661 . '" rel="nofollow">'
1662 . htmlspecialchars($ns->name)
1668 // favorite and repeated
1671 $cp = $cur->getProfile();
1672 $noticeInfoAttr['favorite'] = ($cp->hasFave($this)) ? "true" : "false";
1673 $noticeInfoAttr['repeated'] = ($cp->hasRepeated($this)) ? "true" : "false";
1676 if (!empty($this->repeat_of)) {
1677 $noticeInfoAttr['repeat_of'] = $this->repeat_of;
1680 return array('statusnet:notice_info', $noticeInfoAttr, null);
1684 * Returns an XML string fragment with a reference to a notice as an
1685 * Activity Streams noun object with the given element type.
1687 * Assumes that 'activity' namespace has been previously defined.
1689 * @param string $element one of 'subject', 'object', 'target'
1693 function asActivityNoun($element)
1695 $noun = ActivityObject::fromNotice($this);
1696 return $noun->asString('activity:' . $element);
1701 if (!empty($this->url)) {
1703 } else if (!empty($this->uri) && preg_match('/^https?:/', $this->uri)) {
1706 return common_local_url('shownotice',
1707 array('notice' => $this->id));
1713 * Determine which notice, if any, a new notice is in reply to.
1715 * For conversation tracking, we try to see where this notice fits
1716 * in the tree. Rough algorithm is:
1718 * if (reply_to is set and valid) {
1720 * } else if ((source not API or Web) and (content starts with "T NAME" or "@name ")) {
1721 * return ID of last notice by initial @name in content;
1724 * Note that all @nickname instances will still be used to save "reply" records,
1725 * so the notice shows up in the mentioned users' "replies" tab.
1727 * @param integer $reply_to ID passed in by Web or API
1728 * @param integer $profile_id ID of author
1729 * @param string $source Source tag, like 'web' or 'gwibber'
1730 * @param string $content Final notice content
1732 * @return integer ID of replied-to notice, or null for not a reply.
1735 static function getReplyTo($reply_to, $profile_id, $source, $content)
1737 static $lb = array('xmpp', 'mail', 'sms', 'omb');
1739 // If $reply_to is specified, we check that it exists, and then
1740 // return it if it does
1742 if (!empty($reply_to)) {
1743 $reply_notice = Notice::getKV('id', $reply_to);
1744 if ($reply_notice instanceof Notice) {
1745 return $reply_notice;
1749 // If it's not a "low bandwidth" source (one where you can't set
1750 // a reply_to argument), we return. This is mostly web and API
1753 if (!in_array($source, $lb)) {
1757 // Is there an initial @ or T?
1759 if (preg_match('/^T ([A-Z0-9]{1,64}) /', $content, $match) ||
1760 preg_match('/^@([a-z0-9]{1,64})\s+/', $content, $match)) {
1761 $nickname = common_canonical_nickname($match[1]);
1766 // Figure out who that is.
1768 $sender = Profile::getKV('id', $profile_id);
1769 if (!$sender instanceof Profile) {
1773 $recipient = common_relative_profile($sender, $nickname, common_sql_now());
1775 if (!$recipient instanceof Profile) {
1779 // Get their last notice
1781 $last = $recipient->getCurrentNotice();
1783 if ($last instanceof Notice) {
1790 static function maxContent()
1792 $contentlimit = common_config('notice', 'contentlimit');
1793 // null => use global limit (distinct from 0!)
1794 if (is_null($contentlimit)) {
1795 $contentlimit = common_config('site', 'textlimit');
1797 return $contentlimit;
1800 static function contentTooLong($content)
1802 $contentlimit = self::maxContent();
1803 return ($contentlimit > 0 && !empty($content) && (mb_strlen($content) > $contentlimit));
1806 function getLocation()
1810 if (!empty($this->location_id) && !empty($this->location_ns)) {
1811 $location = Location::fromId($this->location_id, $this->location_ns);
1814 if (is_null($location)) { // no ID, or Location::fromId() failed
1815 if (!empty($this->lat) && !empty($this->lon)) {
1816 $location = Location::fromLatLon($this->lat, $this->lon);
1824 * Convenience function for posting a repeat of an existing message.
1826 * @param int $repeater_id: profile ID of user doing the repeat
1827 * @param string $source: posting source key, eg 'web', 'api', etc
1830 * @throws Exception on failure or permission problems
1832 function repeat($repeater_id, $source)
1834 $author = Profile::getKV('id', $this->profile_id);
1836 // TRANS: Message used to repeat a notice. RT is the abbreviation of 'retweet'.
1837 // TRANS: %1$s is the repeated user's name, %2$s is the repeated notice.
1838 $content = sprintf(_('RT @%1$s %2$s'),
1842 $maxlen = common_config('site', 'textlimit');
1843 if ($maxlen > 0 && mb_strlen($content) > $maxlen) {
1844 // Web interface and current Twitter API clients will
1845 // pull the original notice's text, but some older
1846 // clients and RSS/Atom feeds will see this trimmed text.
1848 // Unfortunately this is likely to lose tags or URLs
1849 // at the end of long notices.
1850 $content = mb_substr($content, 0, $maxlen - 4) . ' ...';
1853 // Scope is same as this one's
1855 return self::saveNew($repeater_id,
1858 array('repeat_of' => $this->id,
1859 'scope' => $this->scope));
1862 // These are supposed to be in chron order!
1864 function repeatStream($limit=100)
1866 $cache = Cache::instance();
1868 if (empty($cache)) {
1869 $ids = $this->_repeatStreamDirect($limit);
1871 $idstr = $cache->get(Cache::key('notice:repeats:'.$this->id));
1872 if ($idstr !== false) {
1873 if (empty($idstr)) {
1876 $ids = explode(',', $idstr);
1879 $ids = $this->_repeatStreamDirect(100);
1880 $cache->set(Cache::key('notice:repeats:'.$this->id), implode(',', $ids));
1883 // We do a max of 100, so slice down to limit
1884 $ids = array_slice($ids, 0, $limit);
1888 return NoticeStream::getStreamByIds($ids);
1891 function _repeatStreamDirect($limit)
1893 $notice = new Notice();
1895 $notice->selectAdd(); // clears it
1896 $notice->selectAdd('id');
1898 $notice->repeat_of = $this->id;
1900 $notice->orderBy('created, id'); // NB: asc!
1902 if (!is_null($limit)) {
1903 $notice->limit(0, $limit);
1906 return $notice->fetchAll('id');
1909 function locationOptions($lat, $lon, $location_id, $location_ns, $profile = null)
1913 if (!empty($location_id) && !empty($location_ns)) {
1914 $options['location_id'] = $location_id;
1915 $options['location_ns'] = $location_ns;
1917 $location = Location::fromId($location_id, $location_ns);
1919 if ($location instanceof Location) {
1920 $options['lat'] = $location->lat;
1921 $options['lon'] = $location->lon;
1924 } else if (!empty($lat) && !empty($lon)) {
1925 $options['lat'] = $lat;
1926 $options['lon'] = $lon;
1928 $location = Location::fromLatLon($lat, $lon);
1930 if ($location instanceof Location) {
1931 $options['location_id'] = $location->location_id;
1932 $options['location_ns'] = $location->location_ns;
1934 } else if (!empty($profile)) {
1935 if (isset($profile->lat) && isset($profile->lon)) {
1936 $options['lat'] = $profile->lat;
1937 $options['lon'] = $profile->lon;
1940 if (isset($profile->location_id) && isset($profile->location_ns)) {
1941 $options['location_id'] = $profile->location_id;
1942 $options['location_ns'] = $profile->location_ns;
1949 function clearAttentions()
1951 $att = new Attention();
1952 $att->notice_id = $this->getID();
1955 while ($att->fetch()) {
1956 // Can't do delete() on the object directly since it won't remove all of it
1957 $other = clone($att);
1963 function clearReplies()
1965 $replyNotice = new Notice();
1966 $replyNotice->reply_to = $this->id;
1968 //Null any notices that are replies to this notice
1970 if ($replyNotice->find()) {
1971 while ($replyNotice->fetch()) {
1972 $orig = clone($replyNotice);
1973 $replyNotice->reply_to = null;
1974 $replyNotice->update($orig);
1980 $reply = new Reply();
1981 $reply->notice_id = $this->id;
1983 if ($reply->find()) {
1984 while($reply->fetch()) {
1985 self::blow('reply:stream:%d', $reply->profile_id);
1993 function clearFiles()
1995 $f2p = new File_to_post();
1997 $f2p->post_id = $this->id;
2000 while ($f2p->fetch()) {
2004 // FIXME: decide whether to delete File objects
2005 // ...and related (actual) files
2008 function clearRepeats()
2010 $repeatNotice = new Notice();
2011 $repeatNotice->repeat_of = $this->id;
2013 //Null any notices that are repeats of this notice
2015 if ($repeatNotice->find()) {
2016 while ($repeatNotice->fetch()) {
2017 $orig = clone($repeatNotice);
2018 $repeatNotice->repeat_of = null;
2019 $repeatNotice->update($orig);
2024 function clearFaves()
2027 $fave->notice_id = $this->id;
2029 if ($fave->find()) {
2030 while ($fave->fetch()) {
2031 self::blow('fave:ids_by_user_own:%d', $fave->user_id);
2032 self::blow('fave:ids_by_user_own:%d;last', $fave->user_id);
2033 self::blow('fave:ids_by_user:%d', $fave->user_id);
2034 self::blow('fave:ids_by_user:%d;last', $fave->user_id);
2042 function clearTags()
2044 $tag = new Notice_tag();
2045 $tag->notice_id = $this->id;
2048 while ($tag->fetch()) {
2049 self::blow('profile:notice_ids_tagged:%d:%s', $this->profile_id, Cache::keyize($tag->tag));
2050 self::blow('profile:notice_ids_tagged:%d:%s;last', $this->profile_id, Cache::keyize($tag->tag));
2051 self::blow('notice_tag:notice_ids:%s', Cache::keyize($tag->tag));
2052 self::blow('notice_tag:notice_ids:%s;last', Cache::keyize($tag->tag));
2060 function clearGroupInboxes()
2062 $gi = new Group_inbox();
2064 $gi->notice_id = $this->id;
2067 while ($gi->fetch()) {
2068 self::blow('user_group:notice_ids:%d', $gi->group_id);
2076 function distribute()
2078 // We always insert for the author so they don't
2080 Event::handle('StartNoticeDistribute', array($this));
2082 // If there's a failure, we want to _force_
2083 // distribution at this point.
2085 $qm = QueueManager::get();
2086 $qm->enqueue($this, 'distrib');
2087 } catch (Exception $e) {
2088 // If the exception isn't transient, this
2089 // may throw more exceptions as DQH does
2090 // its own enqueueing. So, we ignore them!
2092 $handler = new DistribQueueHandler();
2093 $handler->handle($this);
2094 } catch (Exception $e) {
2095 common_log(LOG_ERR, "emergency redistribution resulted in " . $e->getMessage());
2097 // Re-throw so somebody smarter can handle it.
2104 $result = parent::insert();
2106 if ($result !== false) {
2107 // Profile::hasRepeated() abuses pkeyGet(), so we
2108 // have to clear manually
2109 if (!empty($this->repeat_of)) {
2110 $c = self::memcache();
2112 $ck = self::multicacheKey('Notice',
2113 array('profile_id' => $this->profile_id,
2114 'repeat_of' => $this->repeat_of));
2124 * Get the source of the notice
2126 * @return Notice_source $ns A notice source object. 'code' is the only attribute
2127 * guaranteed to be populated.
2129 function getSource()
2131 $ns = new Notice_source();
2132 if (!empty($this->source)) {
2133 switch ($this->source) {
2140 $ns->code = $this->source;
2143 $ns = Notice_source::getKV($this->source);
2145 $ns = new Notice_source();
2146 $ns->code = $this->source;
2147 $app = Oauth_application::getKV('name', $this->source);
2149 $ns->name = $app->name;
2150 $ns->url = $app->source_url;
2160 * Determine whether the notice was locally created
2162 * @return boolean locality
2165 public function isLocal()
2167 return ($this->is_local == Notice::LOCAL_PUBLIC ||
2168 $this->is_local == Notice::LOCAL_NONPUBLIC);
2172 * Get the list of hash tags saved with this notice.
2174 * @return array of strings
2176 public function getTags()
2180 $keypart = sprintf('notice:tags:%d', $this->id);
2182 $tagstr = self::cacheGet($keypart);
2184 if ($tagstr !== false) {
2185 $tags = explode(',', $tagstr);
2187 $tag = new Notice_tag();
2188 $tag->notice_id = $this->id;
2190 while ($tag->fetch()) {
2191 $tags[] = $tag->tag;
2194 self::cacheSet($keypart, implode(',', $tags));
2200 static private function utcDate($dt)
2202 $dateStr = date('d F Y H:i:s', strtotime($dt));
2203 $d = new DateTime($dateStr, new DateTimeZone('UTC'));
2204 return $d->format(DATE_W3C);
2208 * Look up the creation timestamp for a given notice ID, even
2209 * if it's been deleted.
2212 * @return mixed string recorded creation timestamp, or false if can't be found
2214 public static function getAsTimestamp($id)
2220 $notice = Notice::getKV('id', $id);
2222 return $notice->created;
2225 $deleted = Deleted_notice::getKV('id', $id);
2227 return $deleted->created;
2234 * Build an SQL 'where' fragment for timestamp-based sorting from a since_id
2235 * parameter, matching notices posted after the given one (exclusive).
2237 * If the referenced notice can't be found, will return false.
2240 * @param string $idField
2241 * @param string $createdField
2242 * @return mixed string or false if no match
2244 public static function whereSinceId($id, $idField='id', $createdField='created')
2246 $since = Notice::getAsTimestamp($id);
2248 return sprintf("($createdField = '%s' and $idField > %d) or ($createdField > '%s')", $since, $id, $since);
2254 * Build an SQL 'where' fragment for timestamp-based sorting from a since_id
2255 * parameter, matching notices posted after the given one (exclusive), and
2256 * if necessary add it to the data object's query.
2258 * @param DB_DataObject $obj
2260 * @param string $idField
2261 * @param string $createdField
2262 * @return mixed string or false if no match
2264 public static function addWhereSinceId(DB_DataObject $obj, $id, $idField='id', $createdField='created')
2266 $since = self::whereSinceId($id, $idField, $createdField);
2268 $obj->whereAdd($since);
2273 * Build an SQL 'where' fragment for timestamp-based sorting from a max_id
2274 * parameter, matching notices posted before the given one (inclusive).
2276 * If the referenced notice can't be found, will return false.
2279 * @param string $idField
2280 * @param string $createdField
2281 * @return mixed string or false if no match
2283 public static function whereMaxId($id, $idField='id', $createdField='created')
2285 $max = Notice::getAsTimestamp($id);
2287 return sprintf("($createdField < '%s') or ($createdField = '%s' and $idField <= %d)", $max, $max, $id);
2293 * Build an SQL 'where' fragment for timestamp-based sorting from a max_id
2294 * parameter, matching notices posted before the given one (inclusive), and
2295 * if necessary add it to the data object's query.
2297 * @param DB_DataObject $obj
2299 * @param string $idField
2300 * @param string $createdField
2301 * @return mixed string or false if no match
2303 public static function addWhereMaxId(DB_DataObject $obj, $id, $idField='id', $createdField='created')
2305 $max = self::whereMaxId($id, $idField, $createdField);
2307 $obj->whereAdd($max);
2313 if (common_config('public', 'localonly')) {
2314 return ($this->is_local == Notice::LOCAL_PUBLIC);
2316 return (($this->is_local != Notice::LOCAL_NONPUBLIC) &&
2317 ($this->is_local != Notice::GATEWAY));
2322 * Check that the given profile is allowed to read, respond to, or otherwise
2323 * act on this notice.
2325 * The $scope member is a bitmask of scopes, representing a logical AND of the
2326 * scope requirement. So, 0x03 (Notice::ADDRESSEE_SCOPE | Notice::SITE_SCOPE) means
2327 * "only visible to people who are mentioned in the notice AND are users on this site."
2328 * Users on the site who are not mentioned in the notice will not be able to see the
2331 * @param Profile $profile The profile to check; pass null to check for public/unauthenticated users.
2333 * @return boolean whether the profile is in the notice's scope
2335 function inScope($profile)
2337 if (is_null($profile)) {
2338 $keypart = sprintf('notice:in-scope-for:%d:null', $this->id);
2340 $keypart = sprintf('notice:in-scope-for:%d:%d', $this->id, $profile->id);
2343 $result = self::cacheGet($keypart);
2345 if ($result === false) {
2347 if (Event::handle('StartNoticeInScope', array($this, $profile, &$bResult))) {
2348 $bResult = $this->_inScope($profile);
2349 Event::handle('EndNoticeInScope', array($this, $profile, &$bResult));
2351 $result = ($bResult) ? 1 : 0;
2352 self::cacheSet($keypart, $result, 0, 300);
2355 return ($result == 1) ? true : false;
2358 protected function _inScope($profile)
2360 if (!is_null($this->scope)) {
2361 $scope = $this->scope;
2363 $scope = self::defaultScope();
2366 // If there's no scope, anyone (even anon) is in scope.
2368 if ($scope == 0) { // Not private
2370 return !$this->isHiddenSpam($profile);
2372 } else { // Private, somehow
2374 // If there's scope, anon cannot be in scope
2376 if (empty($profile)) {
2380 // Author is always in scope
2382 if ($this->profile_id == $profile->id) {
2386 // Only for users on this site
2388 if (($scope & Notice::SITE_SCOPE) && !$profile->isLocal()) {
2392 // Only for users mentioned in the notice
2394 if ($scope & Notice::ADDRESSEE_SCOPE) {
2396 $reply = Reply::pkeyGet(array('notice_id' => $this->id,
2397 'profile_id' => $profile->id));
2399 if (!$reply instanceof Reply) {
2404 // Only for members of the given group
2406 if ($scope & Notice::GROUP_SCOPE) {
2408 // XXX: just query for the single membership
2410 $groups = $this->getGroups();
2414 foreach ($groups as $group) {
2415 if ($profile->isMember($group)) {
2426 // Only for followers of the author
2430 if ($scope & Notice::FOLLOWER_SCOPE) {
2433 $author = $this->getProfile();
2434 } catch (Exception $e) {
2438 if (!Subscription::exists($profile, $author)) {
2443 return !$this->isHiddenSpam($profile);
2447 function isHiddenSpam($profile) {
2449 // Hide posts by silenced users from everyone but moderators.
2451 if (common_config('notice', 'hidespam')) {
2454 $author = $this->getProfile();
2455 } catch(Exception $e) {
2456 // If we can't get an author, keep it hidden.
2457 // XXX: technically not spam, but, whatever.
2461 if ($author->hasRole(Profile_role::SILENCED)) {
2462 if (!$profile instanceof Profile || (($profile->id !== $author->id) && (!$profile->hasRight(Right::REVIEWSPAM)))) {
2471 public function getParent()
2473 $parent = Notice::getKV('id', $this->reply_to);
2475 if (!$parent instanceof Notice) {
2476 throw new ServerException('Notice has no parent');
2483 * Magic function called at serialize() time.
2485 * We use this to drop a couple process-specific references
2486 * from DB_DataObject which can cause trouble in future
2489 * @return array of variable names to include in serialization.
2494 $vars = parent::__sleep();
2495 $skip = array('_profile', '_groups', '_attachments', '_faves', '_replies', '_repeats');
2496 return array_diff($vars, $skip);
2499 static function defaultScope()
2501 $scope = common_config('notice', 'defaultscope');
2502 if (is_null($scope)) {
2503 if (common_config('site', 'private')) {
2512 static function fillProfiles($notices)
2514 $map = self::getProfiles($notices);
2516 foreach ($notices as $entry=>$notice) {
2518 if (array_key_exists($notice->profile_id, $map)) {
2519 $notice->_setProfile($map[$notice->profile_id]);
2521 } catch (NoProfileException $e) {
2522 common_log(LOG_WARNING, "Failed to fill profile in Notice with non-existing entry for profile_id: {$e->id}");
2523 unset($notices[$entry]);
2527 return array_values($map);
2530 static function getProfiles(&$notices)
2533 foreach ($notices as $notice) {
2534 $ids[] = $notice->profile_id;
2537 $ids = array_unique($ids);
2539 return Profile::pivotGet('id', $ids);
2542 static function fillGroups(&$notices)
2544 $ids = self::_idsOf($notices);
2546 $gis = Group_inbox::listGet('notice_id', $ids);
2550 foreach ($gis as $id => $gi)
2554 $gids[] = $g->group_id;
2558 $gids = array_unique($gids);
2560 $group = User_group::pivotGet('id', $gids);
2562 foreach ($notices as $notice)
2565 $gi = $gis[$notice->id];
2566 foreach ($gi as $g) {
2567 $grps[] = $group[$g->group_id];
2569 $notice->_setGroups($grps);
2573 static function _idsOf(&$notices)
2576 foreach ($notices as $notice) {
2577 $ids[] = $notice->id;
2579 $ids = array_unique($ids);
2583 static function fillAttachments(&$notices)
2585 $ids = self::_idsOf($notices);
2587 $f2pMap = File_to_post::listGet('post_id', $ids);
2591 foreach ($f2pMap as $noticeId => $f2ps) {
2592 foreach ($f2ps as $f2p) {
2593 $fileIds[] = $f2p->file_id;
2597 $fileIds = array_unique($fileIds);
2599 $fileMap = File::pivotGet('id', $fileIds);
2601 foreach ($notices as $notice)
2604 $f2ps = $f2pMap[$notice->id];
2605 foreach ($f2ps as $f2p) {
2606 $files[] = $fileMap[$f2p->file_id];
2608 $notice->_setAttachments($files);
2615 * All faves of this notice
2617 * @return array Array of Fave objects
2622 if (isset($this->_faves) && is_array($this->_faves)) {
2623 return $this->_faves;
2625 $faveMap = Fave::listGet('notice_id', array($this->id));
2626 $this->_faves = $faveMap[$this->id];
2627 return $this->_faves;
2630 function _setFaves($faves)
2632 $this->_faves = $faves;
2635 static function fillFaves(&$notices)
2637 $ids = self::_idsOf($notices);
2638 $faveMap = Fave::listGet('notice_id', $ids);
2641 foreach ($faveMap as $id => $faves) {
2642 $cnt += count($faves);
2643 if (count($faves) > 0) {
2647 foreach ($notices as $notice) {
2648 $faves = $faveMap[$notice->id];
2649 $notice->_setFaves($faves);
2653 static function fillReplies(&$notices)
2655 $ids = self::_idsOf($notices);
2656 $replyMap = Reply::listGet('notice_id', $ids);
2657 foreach ($notices as $notice) {
2658 $replies = $replyMap[$notice->id];
2660 foreach ($replies as $reply) {
2661 $ids[] = $reply->profile_id;
2663 $notice->_setReplies($ids);
2667 protected $_repeats;
2669 function getRepeats()
2671 if (isset($this->_repeats) && is_array($this->_repeats)) {
2672 return $this->_repeats;
2674 $repeatMap = Notice::listGet('repeat_of', array($this->id));
2675 $this->_repeats = $repeatMap[$this->id];
2676 return $this->_repeats;
2679 function _setRepeats($repeats)
2681 $this->_repeats = $repeats;
2684 static function fillRepeats(&$notices)
2686 $ids = self::_idsOf($notices);
2687 $repeatMap = Notice::listGet('repeat_of', $ids);
2688 foreach ($notices as $notice) {
2689 $repeats = $repeatMap[$notice->id];
2690 $notice->_setRepeats($repeats);