3 * StatusNet - the distributed open-source microblogging tool
4 * Copyright (C) 2008, 2009, StatusNet, Inc.
6 * This program is free software: you can redistribute it and/or modify
7 * it under the terms of the GNU Affero General Public License as published by
8 * the Free Software Foundation, either version 3 of the License, or
9 * (at your option) any later version.
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU Affero General Public License for more details.
16 * You should have received a copy of the GNU Affero General Public License
17 * along with this program. If not, see <http://www.gnu.org/licenses/>.
21 * @author Brenda Wallace <shiny@cpan.org>
22 * @author Christopher Vollick <psycotica0@gmail.com>
23 * @author CiaranG <ciaran@ciarang.com>
24 * @author Craig Andrews <candrews@integralblue.com>
25 * @author Evan Prodromou <evan@controlezvous.ca>
26 * @author Gina Haeussge <osd@foosel.net>
27 * @author Jeffery To <jeffery.to@gmail.com>
28 * @author Mike Cochrane <mikec@mikenz.geek.nz>
29 * @author Robin Millette <millette@controlyourself.ca>
30 * @author Sarven Capadisli <csarven@controlyourself.ca>
31 * @author Tom Adams <tom@holizz.com>
32 * @copyright 2009 Free Software Foundation, Inc http://www.fsf.org
33 * @license GNU Affero General Public License http://www.gnu.org/licenses/
36 if (!defined('STATUSNET') && !defined('LACONICA')) {
41 * Table Definition for notice
43 require_once INSTALLDIR.'/classes/Memcached_DataObject.php';
45 /* We keep 200 notices, the max number of notices available per API request,
46 * in the memcached cache. */
48 define('NOTICE_CACHE_WINDOW', 200);
50 define('MAX_BOXCARS', 128);
52 class Notice extends Memcached_DataObject
55 /* the code below is auto generated do not remove the above tag */
57 public $__table = 'notice'; // table name
58 public $id; // int(4) primary_key not_null
59 public $profile_id; // int(4) multiple_key not_null
60 public $uri; // varchar(255) unique_key
61 public $content; // text
62 public $rendered; // text
63 public $url; // varchar(255)
64 public $created; // datetime multiple_key not_null default_0000-00-00%2000%3A00%3A00
65 public $modified; // timestamp not_null default_CURRENT_TIMESTAMP
66 public $reply_to; // int(4)
67 public $is_local; // int(4)
68 public $source; // varchar(32)
69 public $conversation; // int(4)
70 public $lat; // decimal(10,7)
71 public $lon; // decimal(10,7)
72 public $location_id; // int(4)
73 public $location_ns; // int(4)
74 public $repeat_of; // int(4)
77 function staticGet($k,$v=NULL)
79 return Memcached_DataObject::staticGet('Notice',$k,$v);
82 /* the code above is auto generated do not remove the tag below */
86 const LOCAL_PUBLIC = 1;
88 const LOCAL_NONPUBLIC = -1;
93 $profile = Profile::staticGet('id', $this->profile_id);
95 if (empty($profile)) {
96 // TRANS: Server exception thrown when a user profile for a notice cannot be found.
97 // TRANS: %1$d is a profile ID (number), %2$d is a notice ID (number).
98 throw new ServerException(sprintf(_('No such profile (%1$d) for notice (%2$d).'), $this->profile_id, $this->id));
106 // For auditing purposes, save a record that the notice
109 // @fixme we have some cases where things get re-run and so the
111 $deleted = Deleted_notice::staticGet('id', $this->id);
114 $deleted = Deleted_notice::staticGet('uri', $this->uri);
118 $deleted = new Deleted_notice();
120 $deleted->id = $this->id;
121 $deleted->profile_id = $this->profile_id;
122 $deleted->uri = $this->uri;
123 $deleted->created = $this->created;
124 $deleted->deleted = common_sql_now();
129 if (Event::handle('NoticeDeleteRelated', array($this))) {
131 // Clear related records
133 $this->clearReplies();
134 $this->clearRepeats();
137 $this->clearGroupInboxes();
140 // NOTE: we don't clear inboxes
141 // NOTE: we don't clear queue items
144 $result = parent::delete();
146 $this->blowOnDelete();
151 * Extract #hashtags from this notice's content and save them to the database.
155 /* extract all #hastags */
156 $count = preg_match_all('/(?:^|\s)#([\pL\pN_\-\.]{1,64})/u', strtolower($this->content), $match);
161 /* Add them to the database */
162 return $this->saveKnownTags($match[1]);
166 * Record the given set of hash tags in the db for this notice.
167 * Given tag strings will be normalized and checked for dupes.
169 function saveKnownTags($hashtags)
171 //turn each into their canonical tag
172 //this is needed to remove dupes before saving e.g. #hash.tag = #hashtag
173 for($i=0; $i<count($hashtags); $i++) {
174 /* elide characters we don't want in the tag */
175 $hashtags[$i] = common_canonical_tag($hashtags[$i]);
178 foreach(array_unique($hashtags) as $hashtag) {
179 $this->saveTag($hashtag);
180 self::blow('profile:notice_ids_tagged:%d:%s', $this->profile_id, $hashtag);
186 * Record a single hash tag as associated with this notice.
187 * Tag format and uniqueness must be validated by caller.
189 function saveTag($hashtag)
191 $tag = new Notice_tag();
192 $tag->notice_id = $this->id;
193 $tag->tag = $hashtag;
194 $tag->created = $this->created;
195 $id = $tag->insert();
198 // TRANS: Server exception. %s are the error details.
199 throw new ServerException(sprintf(_('Database error inserting hashtag: %s'),
200 $last_error->message));
204 // if it's saved, blow its cache
205 $tag->blowCache(false);
209 * Save a new notice and push it out to subscribers' inboxes.
210 * Poster's permissions are checked before sending.
212 * @param int $profile_id Profile ID of the poster
213 * @param string $content source message text; links may be shortened
214 * per current user's preference
215 * @param string $source source key ('web', 'api', etc)
216 * @param array $options Associative array of optional properties:
217 * string 'created' timestamp of notice; defaults to now
218 * int 'is_local' source/gateway ID, one of:
219 * Notice::LOCAL_PUBLIC - Local, ok to appear in public timeline
220 * Notice::REMOTE_OMB - Sent from a remote OMB service;
221 * hide from public timeline but show in
222 * local "and friends" timelines
223 * Notice::LOCAL_NONPUBLIC - Local, but hide from public timeline
224 * Notice::GATEWAY - From another non-OMB service;
225 * will not appear in public views
226 * float 'lat' decimal latitude for geolocation
227 * float 'lon' decimal longitude for geolocation
228 * int 'location_id' geoname identifier
229 * int 'location_ns' geoname namespace to interpret location_id
230 * int 'reply_to'; notice ID this is a reply to
231 * int 'repeat_of'; notice ID this is a repeat of
232 * string 'uri' unique ID for notice; defaults to local notice URL
233 * string 'url' permalink to notice; defaults to local notice URL
234 * string 'rendered' rendered HTML version of content
235 * array 'replies' list of profile URIs for reply delivery in
236 * place of extracting @-replies from content.
237 * array 'groups' list of group IDs to deliver to, in place of
238 * extracting ! tags from content
239 * array 'tags' list of hashtag strings to save with the notice
240 * in place of extracting # tags from content
241 * array 'urls' list of attached/referred URLs to save with the
242 * notice in place of extracting links from content
243 * boolean 'distribute' whether to distribute the notice, default true
245 * @fixme tag override
248 * @throws ClientException
250 static function saveNew($profile_id, $content, $source, $options=null) {
251 $defaults = array('uri' => null,
255 'distribute' => true);
257 if (!empty($options)) {
258 $options = $options + $defaults;
264 if (!isset($is_local)) {
265 $is_local = Notice::LOCAL_PUBLIC;
268 $profile = Profile::staticGet('id', $profile_id);
269 $user = User::staticGet('id', $profile_id);
271 // Use the local user's shortening preferences, if applicable.
272 $final = $user->shortenLinks($content);
274 $final = common_shorten_links($content);
277 if (Notice::contentTooLong($final)) {
278 // TRANS: Client exception thrown if a notice contains too many characters.
279 throw new ClientException(_('Problem saving notice. Too long.'));
282 if (empty($profile)) {
283 // TRANS: Client exception thrown when trying to save a notice for an unknown user.
284 throw new ClientException(_('Problem saving notice. Unknown user.'));
287 if (common_config('throttle', 'enabled') && !Notice::checkEditThrottle($profile_id)) {
288 common_log(LOG_WARNING, 'Excessive posting by profile #' . $profile_id . '; throttled.');
289 // TRANS: Client exception thrown when a user tries to post too many notices in a given time frame.
290 throw new ClientException(_('Too many notices too fast; take a breather '.
291 'and post again in a few minutes.'));
294 if (common_config('site', 'dupelimit') > 0 && !Notice::checkDupes($profile_id, $final)) {
295 common_log(LOG_WARNING, 'Dupe posting by profile #' . $profile_id . '; throttled.');
296 // TRANS: Client exception thrown when a user tries to post too many duplicate notices in a given time frame.
297 throw new ClientException(_('Too many duplicate messages too quickly;'.
298 ' take a breather and post again in a few minutes.'));
301 if (!$profile->hasRight(Right::NEWNOTICE)) {
302 common_log(LOG_WARNING, "Attempted post from user disallowed to post: " . $profile->nickname);
304 // TRANS: Client exception thrown when a user tries to post while being banned.
305 throw new ClientException(_('You are banned from posting notices on this site.'), 403);
308 $notice = new Notice();
309 $notice->profile_id = $profile_id;
311 $autosource = common_config('public', 'autosource');
313 # Sandboxed are non-false, but not 1, either
315 if (!$profile->hasRight(Right::PUBLICNOTICE) ||
316 ($source && $autosource && in_array($source, $autosource))) {
317 $notice->is_local = Notice::LOCAL_NONPUBLIC;
319 $notice->is_local = $is_local;
322 if (!empty($created)) {
323 $notice->created = $created;
325 $notice->created = common_sql_now();
328 $notice->content = $final;
330 $notice->source = $source;
334 // Handle repeat case
336 if (isset($repeat_of)) {
337 $notice->repeat_of = $repeat_of;
339 $notice->reply_to = self::getReplyTo($reply_to, $profile_id, $source, $final);
342 if (!empty($notice->reply_to)) {
343 $reply = Notice::staticGet('id', $notice->reply_to);
344 $notice->conversation = $reply->conversation;
347 if (!empty($lat) && !empty($lon)) {
352 if (!empty($location_ns) && !empty($location_id)) {
353 $notice->location_id = $location_id;
354 $notice->location_ns = $location_ns;
357 if (!empty($rendered)) {
358 $notice->rendered = $rendered;
360 $notice->rendered = common_render_content($final, $notice);
363 if (Event::handle('StartNoticeSave', array(&$notice))) {
365 // XXX: some of these functions write to the DB
367 $id = $notice->insert();
370 common_log_db_error($notice, 'INSERT', __FILE__);
371 // TRANS: Server exception thrown when a notice cannot be saved.
372 throw new ServerException(_('Problem saving notice.'));
375 // Update ID-dependent columns: URI, conversation
377 $orig = clone($notice);
382 $notice->uri = common_notice_uri($notice);
386 // If it's not part of a conversation, it's
387 // the beginning of a new conversation.
389 if (empty($notice->conversation)) {
390 $conv = Conversation::create();
391 $notice->conversation = $conv->id;
396 if (!$notice->update($orig)) {
397 common_log_db_error($notice, 'UPDATE', __FILE__);
398 // TRANS: Server exception thrown when a notice cannot be updated.
399 throw new ServerException(_('Problem saving notice.'));
405 # Clear the cache for subscribed users, so they'll update at next request
406 # XXX: someone clever could prepend instead of clearing the cache
408 $notice->blowOnInsert();
410 // Save per-notice metadata...
412 if (isset($replies)) {
413 $notice->saveKnownReplies($replies);
415 $notice->saveReplies();
419 $notice->saveKnownTags($tags);
424 // Note: groups may save tags, so must be run after tags are saved
425 // to avoid errors on duplicates.
426 if (isset($groups)) {
427 $notice->saveKnownGroups($groups);
429 $notice->saveGroups();
433 $notice->saveKnownUrls($urls);
439 // Prepare inbox delivery, may be queued to background.
440 $notice->distribute();
446 function blowOnInsert($conversation = false)
448 self::blow('profile:notice_ids:%d', $this->profile_id);
450 if ($this->isPublic()) {
451 self::blow('public');
454 // XXX: Before we were blowing the casche only if the notice id
455 // was not the root of the conversation. What to do now?
457 self::blow('notice:conversation_ids:%d', $this->conversation);
459 if (!empty($this->repeat_of)) {
460 self::blow('notice:repeats:%d', $this->repeat_of);
463 $original = Notice::staticGet('id', $this->repeat_of);
465 if (!empty($original)) {
466 $originalUser = User::staticGet('id', $original->profile_id);
467 if (!empty($originalUser)) {
468 self::blow('user:repeats_of_me:%d', $originalUser->id);
472 $profile = Profile::staticGet($this->profile_id);
473 if (!empty($profile)) {
474 $profile->blowNoticeCount();
479 * Clear cache entries related to this notice at delete time.
480 * Necessary to avoid breaking paging on public, profile timelines.
482 function blowOnDelete()
484 $this->blowOnInsert();
486 self::blow('profile:notice_ids:%d;last', $this->profile_id);
488 if ($this->isPublic()) {
489 self::blow('public;last');
493 /** save all urls in the notice to the db
495 * follow redirects and save all available file information
496 * (mimetype, date, size, oembed, etc.)
500 function saveUrls() {
501 if (common_config('attachments', 'process_links')) {
502 common_replace_urls_callback($this->content, array($this, 'saveUrl'), $this->id);
507 * Save the given URLs as related links/attachments to the db
509 * follow redirects and save all available file information
510 * (mimetype, date, size, oembed, etc.)
514 function saveKnownUrls($urls)
516 if (common_config('attachments', 'process_links')) {
517 // @fixme validation?
518 foreach (array_unique($urls) as $url) {
519 File::processNew($url, $this->id);
527 function saveUrl($url, $notice_id) {
528 File::processNew($url, $notice_id);
531 static function checkDupes($profile_id, $content) {
532 $profile = Profile::staticGet($profile_id);
533 if (empty($profile)) {
536 $notice = $profile->getNotices(0, NOTICE_CACHE_WINDOW);
537 if (!empty($notice)) {
539 while ($notice->fetch()) {
540 if (time() - strtotime($notice->created) >= common_config('site', 'dupelimit')) {
542 } else if ($notice->content == $content) {
547 # If we get here, oldest item in cache window is not
548 # old enough for dupe limit; do direct check against DB
549 $notice = new Notice();
550 $notice->profile_id = $profile_id;
551 $notice->content = $content;
552 $threshold = common_sql_date(time() - common_config('site', 'dupelimit'));
553 $notice->whereAdd(sprintf("created > '%s'", $notice->escape($threshold)));
555 $cnt = $notice->count();
559 static function checkEditThrottle($profile_id) {
560 $profile = Profile::staticGet($profile_id);
561 if (empty($profile)) {
565 $notice = $profile->getNotices(common_config('throttle', 'count') - 1, 1);
566 if ($notice && $notice->fetch()) {
567 # If the Nth notice was posted less than timespan seconds ago
568 if (time() - strtotime($notice->created) <= common_config('throttle', 'timespan')) {
573 # Either not N notices in the stream, OR the Nth was not posted within timespan seconds
577 function getUploadedAttachment() {
579 $query = 'select file.url as up, file.id as i from file join file_to_post on file.id = file_id where post_id=' . $post->escape($post->id) . ' and url like "%/notice/%/file"';
580 $post->query($query);
582 if (empty($post->up) || empty($post->i)) {
585 $ret = array($post->up, $post->i);
591 function hasAttachments() {
593 $query = "select count(file_id) as n_attachments from file join file_to_post on (file_id = file.id) join notice on (post_id = notice.id) where post_id = " . $post->escape($post->id);
594 $post->query($query);
596 $n_attachments = intval($post->n_attachments);
598 return $n_attachments;
601 function attachments() {
604 $f2p = new File_to_post;
605 $f2p->post_id = $this->id;
607 while ($f2p->fetch()) {
608 $f = File::staticGet($f2p->file_id);
617 function getStreamByIds($ids)
619 $cache = Cache::instance();
621 if (!empty($cache)) {
623 foreach ($ids as $id) {
624 $n = Notice::staticGet('id', $id);
629 return new ArrayWrapper($notices);
631 $notice = new Notice();
633 //if no IDs requested, just return the notice object
636 $notice->whereAdd('id in (' . implode(', ', $ids) . ')');
642 while ($notice->fetch()) {
643 $temp[$notice->id] = clone($notice);
648 foreach ($ids as $id) {
649 if (array_key_exists($id, $temp)) {
650 $wrapped[] = $temp[$id];
654 return new ArrayWrapper($wrapped);
658 function publicStream($offset=0, $limit=20, $since_id=0, $max_id=0)
660 $ids = Notice::stream(array('Notice', '_publicStreamDirect'),
663 $offset, $limit, $since_id, $max_id);
664 return Notice::getStreamByIds($ids);
667 function _publicStreamDirect($offset=0, $limit=20, $since_id=0, $max_id=0)
669 $notice = new Notice();
671 $notice->selectAdd(); // clears it
672 $notice->selectAdd('id');
674 $notice->orderBy('created DESC, id DESC');
676 if (!is_null($offset)) {
677 $notice->limit($offset, $limit);
680 if (common_config('public', 'localonly')) {
681 $notice->whereAdd('is_local = ' . Notice::LOCAL_PUBLIC);
683 # -1 == blacklisted, -2 == gateway (i.e. Twitter)
684 $notice->whereAdd('is_local !='. Notice::LOCAL_NONPUBLIC);
685 $notice->whereAdd('is_local !='. Notice::GATEWAY);
688 Notice::addWhereSinceId($notice, $since_id);
689 Notice::addWhereMaxId($notice, $max_id);
693 if ($notice->find()) {
694 while ($notice->fetch()) {
695 $ids[] = $notice->id;
705 function conversationStream($id, $offset=0, $limit=20, $since_id=0, $max_id=0)
707 $ids = Notice::stream(array('Notice', '_conversationStreamDirect'),
709 'notice:conversation_ids:'.$id,
710 $offset, $limit, $since_id, $max_id);
712 return Notice::getStreamByIds($ids);
715 function _conversationStreamDirect($id, $offset=0, $limit=20, $since_id=0, $max_id=0)
717 $notice = new Notice();
719 $notice->selectAdd(); // clears it
720 $notice->selectAdd('id');
722 $notice->conversation = $id;
724 $notice->orderBy('created DESC, id DESC');
726 if (!is_null($offset)) {
727 $notice->limit($offset, $limit);
730 Notice::addWhereSinceId($notice, $since_id);
731 Notice::addWhereMaxId($notice, $max_id);
735 if ($notice->find()) {
736 while ($notice->fetch()) {
737 $ids[] = $notice->id;
748 * Is this notice part of an active conversation?
750 * @return boolean true if other messages exist in the same
751 * conversation, false if this is the only one
753 function hasConversation()
755 if (!empty($this->conversation)) {
756 $conversation = Notice::conversationStream(
762 if ($conversation->N > 0) {
770 * Pull up a full list of local recipients who will be getting
771 * this notice in their inbox. Results will be cached, so don't
772 * change the input data wily-nilly!
774 * @param array $groups optional list of Group objects;
775 * if left empty, will be loaded from group_inbox records
776 * @param array $recipient optional list of reply profile ids
777 * if left empty, will be loaded from reply records
778 * @return array associating recipient user IDs with an inbox source constant
780 function whoGets($groups=null, $recipients=null)
782 $c = self::memcache();
785 $ni = $c->get(Cache::key('notice:who_gets:'.$this->id));
791 if (is_null($groups)) {
792 $groups = $this->getGroups();
795 if (is_null($recipients)) {
796 $recipients = $this->getReplies();
799 $users = $this->getSubscribedUsers();
801 // FIXME: kind of ignoring 'transitional'...
802 // we'll probably stop supporting inboxless mode
807 foreach ($users as $id) {
808 $ni[$id] = NOTICE_INBOX_SOURCE_SUB;
811 foreach ($groups as $group) {
812 $users = $group->getUserMembers();
813 foreach ($users as $id) {
814 if (!array_key_exists($id, $ni)) {
815 $ni[$id] = NOTICE_INBOX_SOURCE_GROUP;
820 foreach ($recipients as $recipient) {
821 if (!array_key_exists($recipient, $ni)) {
822 $ni[$recipient] = NOTICE_INBOX_SOURCE_REPLY;
826 // Exclude any deleted, non-local, or blocking recipients.
827 $profile = $this->getProfile();
828 $originalProfile = null;
829 if ($this->repeat_of) {
830 // Check blocks against the original notice's poster as well.
831 $original = Notice::staticGet('id', $this->repeat_of);
833 $originalProfile = $original->getProfile();
836 foreach ($ni as $id => $source) {
837 $user = User::staticGet('id', $id);
838 if (empty($user) || $user->hasBlocked($profile) ||
839 ($originalProfile && $user->hasBlocked($originalProfile))) {
845 // XXX: pack this data better
846 $c->set(Cache::key('notice:who_gets:'.$this->id), $ni);
853 * Adds this notice to the inboxes of each local user who should receive
854 * it, based on author subscriptions, group memberships, and @-replies.
856 * Warning: running a second time currently will make items appear
857 * multiple times in users' inboxes.
859 * @fixme make more robust against errors
860 * @fixme break up massive deliveries to smaller background tasks
862 * @param array $groups optional list of Group objects;
863 * if left empty, will be loaded from group_inbox records
864 * @param array $recipient optional list of reply profile ids
865 * if left empty, will be loaded from reply records
867 function addToInboxes($groups=null, $recipients=null)
869 $ni = $this->whoGets($groups, $recipients);
871 $ids = array_keys($ni);
873 // We remove the author (if they're a local user),
874 // since we'll have already done this in distribute()
876 $i = array_search($this->profile_id, $ids);
884 Inbox::bulkInsert($this->id, $ids);
889 function getSubscribedUsers()
893 if(common_config('db','quote_identifiers'))
894 $user_table = '"user"';
895 else $user_table = 'user';
899 'FROM '. $user_table .' JOIN subscription '.
900 'ON '. $user_table .'.id = subscription.subscriber ' .
901 'WHERE subscription.subscribed = %d ';
903 $user->query(sprintf($qry, $this->profile_id));
907 while ($user->fetch()) {
917 * Record this notice to the given group inboxes for delivery.
918 * Overrides the regular parsing of !group markup.
920 * @param string $group_ids
921 * @fixme might prefer URIs as identifiers, as for replies?
922 * best with generalizations on user_group to support
923 * remote groups better.
925 function saveKnownGroups($group_ids)
927 if (!is_array($group_ids)) {
928 // TRANS: Server exception thrown when no array is provided to the method saveKnownGroups().
929 throw new ServerException(_('Bad type provided to saveKnownGroups.'));
933 foreach (array_unique($group_ids) as $id) {
934 $group = User_group::staticGet('id', $id);
936 common_log(LOG_ERR, "Local delivery to group id $id, $group->nickname");
937 $result = $this->addToGroupInbox($group);
939 common_log_db_error($gi, 'INSERT', __FILE__);
942 // @fixme should we save the tags here or not?
943 $groups[] = clone($group);
945 common_log(LOG_ERR, "Local delivery to group id $id skipped, doesn't exist");
953 * Parse !group delivery and record targets into group_inbox.
954 * @return array of Group objects
956 function saveGroups()
958 // Don't save groups for repeats
960 if (!empty($this->repeat_of)) {
966 /* extract all !group */
967 $count = preg_match_all('/(?:^|\s)!(' . Nickname::DISPLAY_FMT . ')/',
968 strtolower($this->content),
974 $profile = $this->getProfile();
976 /* Add them to the database */
978 foreach (array_unique($match[1]) as $nickname) {
979 /* XXX: remote groups. */
980 $group = User_group::getForNickname($nickname, $profile);
986 // we automatically add a tag for every group name, too
988 $tag = Notice_tag::pkeyGet(array('tag' => common_canonical_tag($nickname),
989 'notice_id' => $this->id));
992 $this->saveTag($nickname);
995 if ($profile->isMember($group)) {
997 $result = $this->addToGroupInbox($group);
1000 common_log_db_error($gi, 'INSERT', __FILE__);
1003 $groups[] = clone($group);
1010 function addToGroupInbox($group)
1012 $gi = Group_inbox::pkeyGet(array('group_id' => $group->id,
1013 'notice_id' => $this->id));
1017 $gi = new Group_inbox();
1019 $gi->group_id = $group->id;
1020 $gi->notice_id = $this->id;
1021 $gi->created = $this->created;
1023 $result = $gi->insert();
1026 common_log_db_error($gi, 'INSERT', __FILE__);
1027 // TRANS: Server exception thrown when an update for a group inbox fails.
1028 throw new ServerException(_('Problem saving group inbox.'));
1031 self::blow('user_group:notice_ids:%d', $gi->group_id);
1038 * Save reply records indicating that this notice needs to be
1039 * delivered to the local users with the given URIs.
1041 * Since this is expected to be used when saving foreign-sourced
1042 * messages, we won't deliver to any remote targets as that's the
1043 * source service's responsibility.
1045 * Mail notifications etc will be handled later.
1047 * @param array of unique identifier URIs for recipients
1049 function saveKnownReplies($uris)
1055 $sender = Profile::staticGet($this->profile_id);
1057 foreach (array_unique($uris) as $uri) {
1059 $profile = Profile::fromURI($uri);
1061 if (empty($profile)) {
1062 common_log(LOG_WARNING, "Unable to determine profile for URI '$uri'");
1066 if ($profile->hasBlocked($sender)) {
1067 common_log(LOG_INFO, "Not saving reply to profile {$profile->id} ($uri) from sender {$sender->id} because of a block.");
1071 $reply = new Reply();
1073 $reply->notice_id = $this->id;
1074 $reply->profile_id = $profile->id;
1075 $reply->modified = $this->created;
1077 common_log(LOG_INFO, __METHOD__ . ": saving reply: notice $this->id to profile $profile->id");
1079 $id = $reply->insert();
1086 * Pull @-replies from this message's content in StatusNet markup format
1087 * and save reply records indicating that this message needs to be
1088 * delivered to those users.
1090 * Mail notifications to local profiles will be sent later.
1092 * @return array of integer profile IDs
1095 function saveReplies()
1097 // Don't save reply data for repeats
1099 if (!empty($this->repeat_of)) {
1103 $sender = Profile::staticGet($this->profile_id);
1105 // @todo ideally this parser information would only
1106 // be calculated once.
1108 $mentions = common_find_mentions($this->content, $this);
1112 // store replied only for first @ (what user/notice what the reply directed,
1113 // we assume first @ is it)
1115 foreach ($mentions as $mention) {
1117 foreach ($mention['mentioned'] as $mentioned) {
1119 // skip if they're already covered
1121 if (!empty($replied[$mentioned->id])) {
1125 // Don't save replies from blocked profile to local user
1127 $mentioned_user = User::staticGet('id', $mentioned->id);
1128 if (!empty($mentioned_user) && $mentioned_user->hasBlocked($sender)) {
1132 $reply = new Reply();
1134 $reply->notice_id = $this->id;
1135 $reply->profile_id = $mentioned->id;
1136 $reply->modified = $this->created;
1138 $id = $reply->insert();
1141 common_log_db_error($reply, 'INSERT', __FILE__);
1142 // TRANS: Server exception thrown when a reply cannot be saved.
1143 // TRANS: %1$d is a notice ID, %2$d is the ID of the mentioned user.
1144 throw new ServerException(sprintf(_('Could not save reply for %1$d, %2$d.'), $this->id, $mentioned->id));
1146 $replied[$mentioned->id] = 1;
1147 self::blow('reply:stream:%d', $mentioned->id);
1152 $recipientIds = array_keys($replied);
1154 return $recipientIds;
1158 * Pull the complete list of @-reply targets for this notice.
1160 * @return array of integer profile ids
1162 function getReplies()
1168 $reply = new Reply();
1169 $reply->selectAdd();
1170 $reply->selectAdd('profile_id');
1171 $reply->notice_id = $this->id;
1173 if ($reply->find()) {
1174 while($reply->fetch()) {
1175 $ids[] = $reply->profile_id;
1185 * Send e-mail notifications to local @-reply targets.
1187 * Replies must already have been saved; this is expected to be run
1188 * from the distrib queue handler.
1190 function sendReplyNotifications()
1192 // Don't send reply notifications for repeats
1194 if (!empty($this->repeat_of)) {
1198 $recipientIds = $this->getReplies();
1200 foreach ($recipientIds as $recipientId) {
1201 $user = User::staticGet('id', $recipientId);
1202 if (!empty($user)) {
1203 mail_notify_attn($user, $this);
1209 * Pull list of groups this notice needs to be delivered to,
1210 * as previously recorded by saveGroups() or saveKnownGroups().
1212 * @return array of Group objects
1214 function getGroups()
1216 // Don't save groups for repeats
1218 if (!empty($this->repeat_of)) {
1226 $gi = new Group_inbox();
1229 $gi->selectAdd('group_id');
1231 $gi->notice_id = $this->id;
1234 while ($gi->fetch()) {
1235 $group = User_group::staticGet('id', $gi->group_id);
1248 * Convert a notice into an activity for export.
1250 * @param User $cur Current user
1252 * @return Activity activity object representing this Notice.
1255 function asActivity($cur)
1257 $act = self::cacheGet(Cache::codeKey('notice:as-activity:'.$this->id));
1262 $act = new Activity();
1264 if (Event::handle('StartNoticeAsActivity', array($this, &$act))) {
1266 $profile = $this->getProfile();
1268 $act->actor = ActivityObject::fromProfile($profile);
1269 $act->actor->extra[] = $profile->profileInfo($cur);
1270 $act->verb = ActivityVerb::POST;
1271 $act->objects[] = ActivityObject::fromNotice($this);
1273 // XXX: should this be handled by default processing for object entry?
1275 $act->time = strtotime($this->created);
1276 $act->link = $this->bestUrl();
1278 $act->content = common_xml_safe_str($this->rendered);
1279 $act->id = $this->uri;
1280 $act->title = common_xml_safe_str($this->content);
1284 $tags = $this->getTags();
1286 foreach ($tags as $tag) {
1287 $cat = new AtomCategory();
1290 $act->categories[] = $cat;
1294 // XXX: use Atom Media and/or File activity objects instead
1296 $attachments = $this->attachments();
1298 foreach ($attachments as $attachment) {
1299 $enclosure = $attachment->getEnclosure();
1301 $act->enclosures[] = $enclosure;
1305 $ctx = new ActivityContext();
1307 if (!empty($this->reply_to)) {
1308 $reply = Notice::staticGet('id', $this->reply_to);
1309 if (!empty($reply)) {
1310 $ctx->replyToID = $reply->uri;
1311 $ctx->replyToUrl = $reply->bestUrl();
1315 $ctx->location = $this->getLocation();
1319 if (!empty($this->conversation)) {
1320 $conv = Conversation::staticGet('id', $this->conversation);
1321 if (!empty($conv)) {
1322 $ctx->conversation = $conv->uri;
1326 $reply_ids = $this->getReplies();
1328 foreach ($reply_ids as $id) {
1329 $profile = Profile::staticGet('id', $id);
1330 if (!empty($profile)) {
1331 $ctx->attention[] = $profile->getUri();
1335 $groups = $this->getGroups();
1337 foreach ($groups as $group) {
1338 $ctx->attention[] = $group->getUri();
1341 // XXX: deprecated; use ActivityVerb::SHARE instead
1345 if (!empty($this->repeat_of)) {
1346 $repeat = Notice::staticGet('id', $this->repeat_of);
1347 $ctx->forwardID = $repeat->uri;
1348 $ctx->forwardUrl = $repeat->bestUrl();
1351 $act->context = $ctx;
1355 $atom_feed = $profile->getAtomFeed();
1357 if (!empty($atom_feed)) {
1359 $act->source = new ActivitySource();
1361 // XXX: we should store the actual feed ID
1363 $act->source->id = $atom_feed;
1365 // XXX: we should store the actual feed title
1367 $act->source->title = $profile->getBestName();
1369 $act->source->links['alternate'] = $profile->profileurl;
1370 $act->source->links['self'] = $atom_feed;
1372 $act->source->icon = $profile->avatarUrl(AVATAR_PROFILE_SIZE);
1374 $notice = $profile->getCurrentNotice();
1376 if (!empty($notice)) {
1377 $act->source->updated = self::utcDate($notice->created);
1380 $user = User::staticGet('id', $profile->id);
1382 if (!empty($user)) {
1383 $act->source->links['license'] = common_config('license', 'url');
1387 if ($this->isLocal()) {
1388 $act->selfLink = common_local_url('ApiStatusesShow', array('id' => $this->id,
1389 'format' => 'atom'));
1390 $act->editLink = $act->selfLink;
1393 Event::handle('EndNoticeAsActivity', array($this, &$act));
1396 self::cacheSet(Cache::codeKey('notice:as-activity:'.$this->id), $act);
1401 // This has gotten way too long. Needs to be sliced up into functional bits
1402 // or ideally exported to a utility class.
1404 function asAtomEntry($namespace=false,
1409 $act = $this->asActivity($cur);
1410 $act->extra[] = $this->noticeInfo($cur);
1411 return $act->asString($namespace, $author, $source);
1415 * Extra notice info for atom entries
1417 * Clients use some extra notice info in the atom stream.
1418 * This gives it to them.
1420 * @param User $cur Current user
1422 * @return array representation of <statusnet:notice_info> element
1425 function noticeInfo($cur)
1427 // local notice ID (useful to clients for ordering)
1429 $noticeInfoAttr = array('local_id' => $this->id);
1433 $ns = $this->getSource();
1436 $noticeInfoAttr['source'] = $ns->code;
1437 if (!empty($ns->url)) {
1438 $noticeInfoAttr['source_link'] = $ns->url;
1439 if (!empty($ns->name)) {
1440 $noticeInfoAttr['source'] = '<a href="'
1441 . htmlspecialchars($ns->url)
1442 . '" rel="nofollow">'
1443 . htmlspecialchars($ns->name)
1449 // favorite and repeated
1452 $noticeInfoAttr['favorite'] = ($cur->hasFave($this)) ? "true" : "false";
1453 $cp = $cur->getProfile();
1454 $noticeInfoAttr['repeated'] = ($cp->hasRepeated($this->id)) ? "true" : "false";
1457 if (!empty($this->repeat_of)) {
1458 $noticeInfoAttr['repeat_of'] = $this->repeat_of;
1461 return array('statusnet:notice_info', $noticeInfoAttr, null);
1465 * Returns an XML string fragment with a reference to a notice as an
1466 * Activity Streams noun object with the given element type.
1468 * Assumes that 'activity' namespace has been previously defined.
1470 * @param string $element one of 'subject', 'object', 'target'
1474 function asActivityNoun($element)
1476 $noun = ActivityObject::fromNotice($this);
1477 return $noun->asString('activity:' . $element);
1482 if (!empty($this->url)) {
1484 } else if (!empty($this->uri) && preg_match('/^https?:/', $this->uri)) {
1487 return common_local_url('shownotice',
1488 array('notice' => $this->id));
1492 function stream($fn, $args, $cachekey, $offset=0, $limit=20, $since_id=0, $max_id=0)
1494 $cache = Cache::instance();
1496 if (empty($cache) ||
1497 $since_id != 0 || $max_id != 0 ||
1499 ($offset + $limit) > NOTICE_CACHE_WINDOW) {
1500 return call_user_func_array($fn, array_merge($args, array($offset, $limit, $since_id,
1504 $idkey = Cache::key($cachekey);
1506 $idstr = $cache->get($idkey);
1508 if ($idstr !== false) {
1509 // Cache hit! Woohoo!
1510 $window = explode(',', $idstr);
1511 $ids = array_slice($window, $offset, $limit);
1515 $laststr = $cache->get($idkey.';last');
1517 if ($laststr !== false) {
1518 $window = explode(',', $laststr);
1519 $last_id = $window[0];
1520 $new_ids = call_user_func_array($fn, array_merge($args, array(0, NOTICE_CACHE_WINDOW,
1521 $last_id, 0, null)));
1523 $new_window = array_merge($new_ids, $window);
1525 $new_windowstr = implode(',', $new_window);
1527 $result = $cache->set($idkey, $new_windowstr);
1528 $result = $cache->set($idkey . ';last', $new_windowstr);
1530 $ids = array_slice($new_window, $offset, $limit);
1535 $window = call_user_func_array($fn, array_merge($args, array(0, NOTICE_CACHE_WINDOW,
1538 $windowstr = implode(',', $window);
1540 $result = $cache->set($idkey, $windowstr);
1541 $result = $cache->set($idkey . ';last', $windowstr);
1543 $ids = array_slice($window, $offset, $limit);
1549 * Determine which notice, if any, a new notice is in reply to.
1551 * For conversation tracking, we try to see where this notice fits
1552 * in the tree. Rough algorithm is:
1554 * if (reply_to is set and valid) {
1556 * } else if ((source not API or Web) and (content starts with "T NAME" or "@name ")) {
1557 * return ID of last notice by initial @name in content;
1560 * Note that all @nickname instances will still be used to save "reply" records,
1561 * so the notice shows up in the mentioned users' "replies" tab.
1563 * @param integer $reply_to ID passed in by Web or API
1564 * @param integer $profile_id ID of author
1565 * @param string $source Source tag, like 'web' or 'gwibber'
1566 * @param string $content Final notice content
1568 * @return integer ID of replied-to notice, or null for not a reply.
1571 static function getReplyTo($reply_to, $profile_id, $source, $content)
1573 static $lb = array('xmpp', 'mail', 'sms', 'omb');
1575 // If $reply_to is specified, we check that it exists, and then
1576 // return it if it does
1578 if (!empty($reply_to)) {
1579 $reply_notice = Notice::staticGet('id', $reply_to);
1580 if (!empty($reply_notice)) {
1585 // If it's not a "low bandwidth" source (one where you can't set
1586 // a reply_to argument), we return. This is mostly web and API
1589 if (!in_array($source, $lb)) {
1593 // Is there an initial @ or T?
1595 if (preg_match('/^T ([A-Z0-9]{1,64}) /', $content, $match) ||
1596 preg_match('/^@([a-z0-9]{1,64})\s+/', $content, $match)) {
1597 $nickname = common_canonical_nickname($match[1]);
1602 // Figure out who that is.
1604 $sender = Profile::staticGet('id', $profile_id);
1605 if (empty($sender)) {
1609 $recipient = common_relative_profile($sender, $nickname, common_sql_now());
1611 if (empty($recipient)) {
1615 // Get their last notice
1617 $last = $recipient->getCurrentNotice();
1619 if (!empty($last)) {
1624 static function maxContent()
1626 $contentlimit = common_config('notice', 'contentlimit');
1627 // null => use global limit (distinct from 0!)
1628 if (is_null($contentlimit)) {
1629 $contentlimit = common_config('site', 'textlimit');
1631 return $contentlimit;
1634 static function contentTooLong($content)
1636 $contentlimit = self::maxContent();
1637 return ($contentlimit > 0 && !empty($content) && (mb_strlen($content) > $contentlimit));
1640 function getLocation()
1644 if (!empty($this->location_id) && !empty($this->location_ns)) {
1645 $location = Location::fromId($this->location_id, $this->location_ns);
1648 if (is_null($location)) { // no ID, or Location::fromId() failed
1649 if (!empty($this->lat) && !empty($this->lon)) {
1650 $location = Location::fromLatLon($this->lat, $this->lon);
1657 function repeat($repeater_id, $source)
1659 $author = Profile::staticGet('id', $this->profile_id);
1661 // TRANS: Message used to repeat a notice. RT is the abbreviation of 'retweet'.
1662 // TRANS: %1$s is the repeated user's name, %2$s is the repeated notice.
1663 $content = sprintf(_('RT @%1$s %2$s'),
1667 $maxlen = common_config('site', 'textlimit');
1668 if ($maxlen > 0 && mb_strlen($content) > $maxlen) {
1669 // Web interface and current Twitter API clients will
1670 // pull the original notice's text, but some older
1671 // clients and RSS/Atom feeds will see this trimmed text.
1673 // Unfortunately this is likely to lose tags or URLs
1674 // at the end of long notices.
1675 $content = mb_substr($content, 0, $maxlen - 4) . ' ...';
1678 return self::saveNew($repeater_id, $content, $source,
1679 array('repeat_of' => $this->id));
1682 // These are supposed to be in chron order!
1684 function repeatStream($limit=100)
1686 $cache = Cache::instance();
1688 if (empty($cache)) {
1689 $ids = $this->_repeatStreamDirect($limit);
1691 $idstr = $cache->get(Cache::key('notice:repeats:'.$this->id));
1692 if ($idstr !== false) {
1693 $ids = explode(',', $idstr);
1695 $ids = $this->_repeatStreamDirect(100);
1696 $cache->set(Cache::key('notice:repeats:'.$this->id), implode(',', $ids));
1699 // We do a max of 100, so slice down to limit
1700 $ids = array_slice($ids, 0, $limit);
1704 return Notice::getStreamByIds($ids);
1707 function _repeatStreamDirect($limit)
1709 $notice = new Notice();
1711 $notice->selectAdd(); // clears it
1712 $notice->selectAdd('id');
1714 $notice->repeat_of = $this->id;
1716 $notice->orderBy('created, id'); // NB: asc!
1718 if (!is_null($limit)) {
1719 $notice->limit(0, $limit);
1724 if ($notice->find()) {
1725 while ($notice->fetch()) {
1726 $ids[] = $notice->id;
1736 function locationOptions($lat, $lon, $location_id, $location_ns, $profile = null)
1740 if (!empty($location_id) && !empty($location_ns)) {
1741 $options['location_id'] = $location_id;
1742 $options['location_ns'] = $location_ns;
1744 $location = Location::fromId($location_id, $location_ns);
1746 if (!empty($location)) {
1747 $options['lat'] = $location->lat;
1748 $options['lon'] = $location->lon;
1751 } else if (!empty($lat) && !empty($lon)) {
1752 $options['lat'] = $lat;
1753 $options['lon'] = $lon;
1755 $location = Location::fromLatLon($lat, $lon);
1757 if (!empty($location)) {
1758 $options['location_id'] = $location->location_id;
1759 $options['location_ns'] = $location->location_ns;
1761 } else if (!empty($profile)) {
1762 if (isset($profile->lat) && isset($profile->lon)) {
1763 $options['lat'] = $profile->lat;
1764 $options['lon'] = $profile->lon;
1767 if (isset($profile->location_id) && isset($profile->location_ns)) {
1768 $options['location_id'] = $profile->location_id;
1769 $options['location_ns'] = $profile->location_ns;
1776 function clearReplies()
1778 $replyNotice = new Notice();
1779 $replyNotice->reply_to = $this->id;
1781 //Null any notices that are replies to this notice
1783 if ($replyNotice->find()) {
1784 while ($replyNotice->fetch()) {
1785 $orig = clone($replyNotice);
1786 $replyNotice->reply_to = null;
1787 $replyNotice->update($orig);
1793 $reply = new Reply();
1794 $reply->notice_id = $this->id;
1796 if ($reply->find()) {
1797 while($reply->fetch()) {
1798 self::blow('reply:stream:%d', $reply->profile_id);
1806 function clearFiles()
1808 $f2p = new File_to_post();
1810 $f2p->post_id = $this->id;
1813 while ($f2p->fetch()) {
1817 // FIXME: decide whether to delete File objects
1818 // ...and related (actual) files
1821 function clearRepeats()
1823 $repeatNotice = new Notice();
1824 $repeatNotice->repeat_of = $this->id;
1826 //Null any notices that are repeats of this notice
1828 if ($repeatNotice->find()) {
1829 while ($repeatNotice->fetch()) {
1830 $orig = clone($repeatNotice);
1831 $repeatNotice->repeat_of = null;
1832 $repeatNotice->update($orig);
1837 function clearFaves()
1840 $fave->notice_id = $this->id;
1842 if ($fave->find()) {
1843 while ($fave->fetch()) {
1844 self::blow('fave:ids_by_user_own:%d', $fave->user_id);
1845 self::blow('fave:ids_by_user_own:%d;last', $fave->user_id);
1846 self::blow('fave:ids_by_user:%d', $fave->user_id);
1847 self::blow('fave:ids_by_user:%d;last', $fave->user_id);
1855 function clearTags()
1857 $tag = new Notice_tag();
1858 $tag->notice_id = $this->id;
1861 while ($tag->fetch()) {
1862 self::blow('profile:notice_ids_tagged:%d:%s', $this->profile_id, Cache::keyize($tag->tag));
1863 self::blow('profile:notice_ids_tagged:%d:%s;last', $this->profile_id, Cache::keyize($tag->tag));
1864 self::blow('notice_tag:notice_ids:%s', Cache::keyize($tag->tag));
1865 self::blow('notice_tag:notice_ids:%s;last', Cache::keyize($tag->tag));
1873 function clearGroupInboxes()
1875 $gi = new Group_inbox();
1877 $gi->notice_id = $this->id;
1880 while ($gi->fetch()) {
1881 self::blow('user_group:notice_ids:%d', $gi->group_id);
1889 function distribute()
1891 // We always insert for the author so they don't
1893 Event::handle('StartNoticeDistribute', array($this));
1895 $user = User::staticGet('id', $this->profile_id);
1896 if (!empty($user)) {
1897 Inbox::insertNotice($user->id, $this->id);
1900 if (common_config('queue', 'inboxes')) {
1901 // If there's a failure, we want to _force_
1902 // distribution at this point.
1904 $qm = QueueManager::get();
1905 $qm->enqueue($this, 'distrib');
1906 } catch (Exception $e) {
1907 // If the exception isn't transient, this
1908 // may throw more exceptions as DQH does
1909 // its own enqueueing. So, we ignore them!
1911 $handler = new DistribQueueHandler();
1912 $handler->handle($this);
1913 } catch (Exception $e) {
1914 common_log(LOG_ERR, "emergency redistribution resulted in " . $e->getMessage());
1916 // Re-throw so somebody smarter can handle it.
1920 $handler = new DistribQueueHandler();
1921 $handler->handle($this);
1927 $result = parent::insert();
1930 // Profile::hasRepeated() abuses pkeyGet(), so we
1931 // have to clear manually
1932 if (!empty($this->repeat_of)) {
1933 $c = self::memcache();
1935 $ck = self::multicacheKey('Notice',
1936 array('profile_id' => $this->profile_id,
1937 'repeat_of' => $this->repeat_of));
1947 * Get the source of the notice
1949 * @return Notice_source $ns A notice source object. 'code' is the only attribute
1950 * guaranteed to be populated.
1952 function getSource()
1954 $ns = new Notice_source();
1955 if (!empty($this->source)) {
1956 switch ($this->source) {
1963 $ns->code = $this->source;
1966 $ns = Notice_source::staticGet($this->source);
1968 $ns = new Notice_source();
1969 $ns->code = $this->source;
1970 $app = Oauth_application::staticGet('name', $this->source);
1972 $ns->name = $app->name;
1973 $ns->url = $app->source_url;
1983 * Determine whether the notice was locally created
1985 * @return boolean locality
1988 public function isLocal()
1990 return ($this->is_local == Notice::LOCAL_PUBLIC ||
1991 $this->is_local == Notice::LOCAL_NONPUBLIC);
1994 public function getTags()
1997 $tag = new Notice_tag();
1998 $tag->notice_id = $this->id;
2000 while ($tag->fetch()) {
2001 $tags[] = $tag->tag;
2008 static private function utcDate($dt)
2010 $dateStr = date('d F Y H:i:s', strtotime($dt));
2011 $d = new DateTime($dateStr, new DateTimeZone('UTC'));
2012 return $d->format(DATE_W3C);
2016 * Look up the creation timestamp for a given notice ID, even
2017 * if it's been deleted.
2020 * @return mixed string recorded creation timestamp, or false if can't be found
2022 public static function getAsTimestamp($id)
2028 $notice = Notice::staticGet('id', $id);
2030 return $notice->created;
2033 $deleted = Deleted_notice::staticGet('id', $id);
2035 return $deleted->created;
2042 * Build an SQL 'where' fragment for timestamp-based sorting from a since_id
2043 * parameter, matching notices posted after the given one (exclusive).
2045 * If the referenced notice can't be found, will return false.
2048 * @param string $idField
2049 * @param string $createdField
2050 * @return mixed string or false if no match
2052 public static function whereSinceId($id, $idField='id', $createdField='created')
2054 $since = Notice::getAsTimestamp($id);
2056 return sprintf("($createdField = '%s' and $idField > %d) or ($createdField > '%s')", $since, $id, $since);
2062 * Build an SQL 'where' fragment for timestamp-based sorting from a since_id
2063 * parameter, matching notices posted after the given one (exclusive), and
2064 * if necessary add it to the data object's query.
2066 * @param DB_DataObject $obj
2068 * @param string $idField
2069 * @param string $createdField
2070 * @return mixed string or false if no match
2072 public static function addWhereSinceId(DB_DataObject $obj, $id, $idField='id', $createdField='created')
2074 $since = self::whereSinceId($id, $idField, $createdField);
2076 $obj->whereAdd($since);
2081 * Build an SQL 'where' fragment for timestamp-based sorting from a max_id
2082 * parameter, matching notices posted before the given one (inclusive).
2084 * If the referenced notice can't be found, will return false.
2087 * @param string $idField
2088 * @param string $createdField
2089 * @return mixed string or false if no match
2091 public static function whereMaxId($id, $idField='id', $createdField='created')
2093 $max = Notice::getAsTimestamp($id);
2095 return sprintf("($createdField < '%s') or ($createdField = '%s' and $idField <= %d)", $max, $max, $id);
2101 * Build an SQL 'where' fragment for timestamp-based sorting from a max_id
2102 * parameter, matching notices posted before the given one (inclusive), and
2103 * if necessary add it to the data object's query.
2105 * @param DB_DataObject $obj
2107 * @param string $idField
2108 * @param string $createdField
2109 * @return mixed string or false if no match
2111 public static function addWhereMaxId(DB_DataObject $obj, $id, $idField='id', $createdField='created')
2113 $max = self::whereMaxId($id, $idField, $createdField);
2115 $obj->whereAdd($max);
2121 if (common_config('public', 'localonly')) {
2122 return ($this->is_local == Notice::LOCAL_PUBLIC);
2124 return (($this->is_local != Notice::LOCAL_NONPUBLIC) &&
2125 ($this->is_local != Notice::GATEWAY));