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)
75 public $object_type; // varchar(255)
76 public $scope; // int(4)
79 function staticGet($k,$v=NULL)
81 return Memcached_DataObject::staticGet('Notice',$k,$v);
84 /* the code above is auto generated do not remove the tag below */
88 const LOCAL_PUBLIC = 1;
90 const LOCAL_NONPUBLIC = -1;
95 $profile = Profile::staticGet('id', $this->profile_id);
97 if (empty($profile)) {
98 // TRANS: Server exception thrown when a user profile for a notice cannot be found.
99 // TRANS: %1$d is a profile ID (number), %2$d is a notice ID (number).
100 throw new ServerException(sprintf(_('No such profile (%1$d) for notice (%2$d).'), $this->profile_id, $this->id));
108 // For auditing purposes, save a record that the notice
111 // @fixme we have some cases where things get re-run and so the
113 $deleted = Deleted_notice::staticGet('id', $this->id);
116 $deleted = Deleted_notice::staticGet('uri', $this->uri);
120 $deleted = new Deleted_notice();
122 $deleted->id = $this->id;
123 $deleted->profile_id = $this->profile_id;
124 $deleted->uri = $this->uri;
125 $deleted->created = $this->created;
126 $deleted->deleted = common_sql_now();
131 if (Event::handle('NoticeDeleteRelated', array($this))) {
133 // Clear related records
135 $this->clearReplies();
136 $this->clearRepeats();
139 $this->clearGroupInboxes();
142 // NOTE: we don't clear inboxes
143 // NOTE: we don't clear queue items
146 $result = parent::delete();
148 $this->blowOnDelete();
153 * Extract #hashtags from this notice's content and save them to the database.
157 /* extract all #hastags */
158 $count = preg_match_all('/(?:^|\s)#([\pL\pN_\-\.]{1,64})/u', strtolower($this->content), $match);
163 /* Add them to the database */
164 return $this->saveKnownTags($match[1]);
168 * Record the given set of hash tags in the db for this notice.
169 * Given tag strings will be normalized and checked for dupes.
171 function saveKnownTags($hashtags)
173 //turn each into their canonical tag
174 //this is needed to remove dupes before saving e.g. #hash.tag = #hashtag
175 for($i=0; $i<count($hashtags); $i++) {
176 /* elide characters we don't want in the tag */
177 $hashtags[$i] = common_canonical_tag($hashtags[$i]);
180 foreach(array_unique($hashtags) as $hashtag) {
181 $this->saveTag($hashtag);
182 self::blow('profile:notice_ids_tagged:%d:%s', $this->profile_id, $hashtag);
188 * Record a single hash tag as associated with this notice.
189 * Tag format and uniqueness must be validated by caller.
191 function saveTag($hashtag)
193 $tag = new Notice_tag();
194 $tag->notice_id = $this->id;
195 $tag->tag = $hashtag;
196 $tag->created = $this->created;
197 $id = $tag->insert();
200 // TRANS: Server exception. %s are the error details.
201 throw new ServerException(sprintf(_('Database error inserting hashtag: %s'),
202 $last_error->message));
206 // if it's saved, blow its cache
207 $tag->blowCache(false);
211 * Save a new notice and push it out to subscribers' inboxes.
212 * Poster's permissions are checked before sending.
214 * @param int $profile_id Profile ID of the poster
215 * @param string $content source message text; links may be shortened
216 * per current user's preference
217 * @param string $source source key ('web', 'api', etc)
218 * @param array $options Associative array of optional properties:
219 * string 'created' timestamp of notice; defaults to now
220 * int 'is_local' source/gateway ID, one of:
221 * Notice::LOCAL_PUBLIC - Local, ok to appear in public timeline
222 * Notice::REMOTE_OMB - Sent from a remote OMB service;
223 * hide from public timeline but show in
224 * local "and friends" timelines
225 * Notice::LOCAL_NONPUBLIC - Local, but hide from public timeline
226 * Notice::GATEWAY - From another non-OMB service;
227 * will not appear in public views
228 * float 'lat' decimal latitude for geolocation
229 * float 'lon' decimal longitude for geolocation
230 * int 'location_id' geoname identifier
231 * int 'location_ns' geoname namespace to interpret location_id
232 * int 'reply_to'; notice ID this is a reply to
233 * int 'repeat_of'; notice ID this is a repeat of
234 * string 'uri' unique ID for notice; defaults to local notice URL
235 * string 'url' permalink to notice; defaults to local notice URL
236 * string 'rendered' rendered HTML version of content
237 * array 'replies' list of profile URIs for reply delivery in
238 * place of extracting @-replies from content.
239 * array 'groups' list of group IDs to deliver to, in place of
240 * extracting ! tags from content
241 * array 'tags' list of hashtag strings to save with the notice
242 * in place of extracting # tags from content
243 * array 'urls' list of attached/referred URLs to save with the
244 * notice in place of extracting links from content
245 * boolean 'distribute' whether to distribute the notice, default true
246 * string 'object_type' URL of the associated object type (default ActivityObject::NOTE)
248 * @fixme tag override
251 * @throws ClientException
253 static function saveNew($profile_id, $content, $source, $options=null) {
254 $defaults = array('uri' => null,
258 'distribute' => true);
260 if (!empty($options)) {
261 $options = $options + $defaults;
267 if (!isset($is_local)) {
268 $is_local = Notice::LOCAL_PUBLIC;
271 $profile = Profile::staticGet('id', $profile_id);
272 $user = User::staticGet('id', $profile_id);
274 // Use the local user's shortening preferences, if applicable.
275 $final = $user->shortenLinks($content);
277 $final = common_shorten_links($content);
280 if (Notice::contentTooLong($final)) {
281 // TRANS: Client exception thrown if a notice contains too many characters.
282 throw new ClientException(_('Problem saving notice. Too long.'));
285 if (empty($profile)) {
286 // TRANS: Client exception thrown when trying to save a notice for an unknown user.
287 throw new ClientException(_('Problem saving notice. Unknown user.'));
290 if (common_config('throttle', 'enabled') && !Notice::checkEditThrottle($profile_id)) {
291 common_log(LOG_WARNING, 'Excessive posting by profile #' . $profile_id . '; throttled.');
292 // TRANS: Client exception thrown when a user tries to post too many notices in a given time frame.
293 throw new ClientException(_('Too many notices too fast; take a breather '.
294 'and post again in a few minutes.'));
297 if (common_config('site', 'dupelimit') > 0 && !Notice::checkDupes($profile_id, $final)) {
298 common_log(LOG_WARNING, 'Dupe posting by profile #' . $profile_id . '; throttled.');
299 // TRANS: Client exception thrown when a user tries to post too many duplicate notices in a given time frame.
300 throw new ClientException(_('Too many duplicate messages too quickly;'.
301 ' take a breather and post again in a few minutes.'));
304 if (!$profile->hasRight(Right::NEWNOTICE)) {
305 common_log(LOG_WARNING, "Attempted post from user disallowed to post: " . $profile->nickname);
307 // TRANS: Client exception thrown when a user tries to post while being banned.
308 throw new ClientException(_('You are banned from posting notices on this site.'), 403);
311 $notice = new Notice();
312 $notice->profile_id = $profile_id;
314 $autosource = common_config('public', 'autosource');
316 // Sandboxed are non-false, but not 1, either
318 if (!$profile->hasRight(Right::PUBLICNOTICE) ||
319 ($source && $autosource && in_array($source, $autosource))) {
320 $notice->is_local = Notice::LOCAL_NONPUBLIC;
322 $notice->is_local = $is_local;
325 if (!empty($created)) {
326 $notice->created = $created;
328 $notice->created = common_sql_now();
331 $notice->content = $final;
333 $notice->source = $source;
337 // Handle repeat case
339 if (isset($repeat_of)) {
340 $notice->repeat_of = $repeat_of;
342 $notice->reply_to = self::getReplyTo($reply_to, $profile_id, $source, $final);
345 if (!empty($notice->reply_to)) {
346 $reply = Notice::staticGet('id', $notice->reply_to);
347 $notice->conversation = $reply->conversation;
350 if (!empty($lat) && !empty($lon)) {
355 if (!empty($location_ns) && !empty($location_id)) {
356 $notice->location_id = $location_id;
357 $notice->location_ns = $location_ns;
360 if (!empty($rendered)) {
361 $notice->rendered = $rendered;
363 $notice->rendered = common_render_content($final, $notice);
366 if (empty($object_type)) {
367 $notice->object_type = (empty($notice->reply_to)) ? ActivityObject::NOTE : ActivityObject::COMMENT;
369 $notice->object_type = $object_type;
372 if (Event::handle('StartNoticeSave', array(&$notice))) {
374 // XXX: some of these functions write to the DB
376 $id = $notice->insert();
379 common_log_db_error($notice, 'INSERT', __FILE__);
380 // TRANS: Server exception thrown when a notice cannot be saved.
381 throw new ServerException(_('Problem saving notice.'));
384 // Update ID-dependent columns: URI, conversation
386 $orig = clone($notice);
391 $notice->uri = common_notice_uri($notice);
395 // If it's not part of a conversation, it's
396 // the beginning of a new conversation.
398 if (empty($notice->conversation)) {
399 $conv = Conversation::create();
400 $notice->conversation = $conv->id;
405 if (!$notice->update($orig)) {
406 common_log_db_error($notice, 'UPDATE', __FILE__);
407 // TRANS: Server exception thrown when a notice cannot be updated.
408 throw new ServerException(_('Problem saving notice.'));
414 // Clear the cache for subscribed users, so they'll update at next request
415 // XXX: someone clever could prepend instead of clearing the cache
417 $notice->blowOnInsert();
419 // Save per-notice metadata...
421 if (isset($replies)) {
422 $notice->saveKnownReplies($replies);
424 $notice->saveReplies();
428 $notice->saveKnownTags($tags);
433 // Note: groups may save tags, so must be run after tags are saved
434 // to avoid errors on duplicates.
435 if (isset($groups)) {
436 $notice->saveKnownGroups($groups);
438 $notice->saveGroups();
442 $notice->saveKnownUrls($urls);
448 // Prepare inbox delivery, may be queued to background.
449 $notice->distribute();
455 function blowOnInsert($conversation = false)
457 self::blow('profile:notice_ids:%d', $this->profile_id);
459 if ($this->isPublic()) {
460 self::blow('public');
463 // XXX: Before we were blowing the casche only if the notice id
464 // was not the root of the conversation. What to do now?
466 self::blow('notice:conversation_ids:%d', $this->conversation);
468 if (!empty($this->repeat_of)) {
469 self::blow('notice:repeats:%d', $this->repeat_of);
472 $original = Notice::staticGet('id', $this->repeat_of);
474 if (!empty($original)) {
475 $originalUser = User::staticGet('id', $original->profile_id);
476 if (!empty($originalUser)) {
477 self::blow('user:repeats_of_me:%d', $originalUser->id);
481 $profile = Profile::staticGet($this->profile_id);
482 if (!empty($profile)) {
483 $profile->blowNoticeCount();
488 * Clear cache entries related to this notice at delete time.
489 * Necessary to avoid breaking paging on public, profile timelines.
491 function blowOnDelete()
493 $this->blowOnInsert();
495 self::blow('profile:notice_ids:%d;last', $this->profile_id);
497 if ($this->isPublic()) {
498 self::blow('public;last');
501 self::blow('fave:by_notice', $this->id);
503 if ($this->conversation) {
504 // In case we're the first, will need to calc a new root.
505 self::blow('notice:conversation_root:%d', $this->conversation);
509 /** save all urls in the notice to the db
511 * follow redirects and save all available file information
512 * (mimetype, date, size, oembed, etc.)
516 function saveUrls() {
517 if (common_config('attachments', 'process_links')) {
518 common_replace_urls_callback($this->content, array($this, 'saveUrl'), $this->id);
523 * Save the given URLs as related links/attachments to the db
525 * follow redirects and save all available file information
526 * (mimetype, date, size, oembed, etc.)
530 function saveKnownUrls($urls)
532 if (common_config('attachments', 'process_links')) {
533 // @fixme validation?
534 foreach (array_unique($urls) as $url) {
535 File::processNew($url, $this->id);
543 function saveUrl($url, $notice_id) {
544 File::processNew($url, $notice_id);
547 static function checkDupes($profile_id, $content) {
548 $profile = Profile::staticGet($profile_id);
549 if (empty($profile)) {
552 $notice = $profile->getNotices(0, NOTICE_CACHE_WINDOW);
553 if (!empty($notice)) {
555 while ($notice->fetch()) {
556 if (time() - strtotime($notice->created) >= common_config('site', 'dupelimit')) {
558 } else if ($notice->content == $content) {
563 // If we get here, oldest item in cache window is not
564 // old enough for dupe limit; do direct check against DB
565 $notice = new Notice();
566 $notice->profile_id = $profile_id;
567 $notice->content = $content;
568 $threshold = common_sql_date(time() - common_config('site', 'dupelimit'));
569 $notice->whereAdd(sprintf("created > '%s'", $notice->escape($threshold)));
571 $cnt = $notice->count();
575 static function checkEditThrottle($profile_id) {
576 $profile = Profile::staticGet($profile_id);
577 if (empty($profile)) {
580 // Get the Nth notice
581 $notice = $profile->getNotices(common_config('throttle', 'count') - 1, 1);
582 if ($notice && $notice->fetch()) {
583 // If the Nth notice was posted less than timespan seconds ago
584 if (time() - strtotime($notice->created) <= common_config('throttle', 'timespan')) {
589 // Either not N notices in the stream, OR the Nth was not posted within timespan seconds
593 function getUploadedAttachment() {
595 $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"';
596 $post->query($query);
598 if (empty($post->up) || empty($post->i)) {
601 $ret = array($post->up, $post->i);
607 function hasAttachments() {
609 $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);
610 $post->query($query);
612 $n_attachments = intval($post->n_attachments);
614 return $n_attachments;
617 function attachments() {
620 $f2p = new File_to_post;
621 $f2p->post_id = $this->id;
623 while ($f2p->fetch()) {
624 $f = File::staticGet($f2p->file_id);
633 function getStreamByIds($ids)
635 $cache = Cache::instance();
637 if (!empty($cache)) {
639 foreach ($ids as $id) {
640 $n = Notice::staticGet('id', $id);
645 return new ArrayWrapper($notices);
647 $notice = new Notice();
649 //if no IDs requested, just return the notice object
652 $notice->whereAdd('id in (' . implode(', ', $ids) . ')');
658 while ($notice->fetch()) {
659 $temp[$notice->id] = clone($notice);
664 foreach ($ids as $id) {
665 if (array_key_exists($id, $temp)) {
666 $wrapped[] = $temp[$id];
670 return new ArrayWrapper($wrapped);
674 function publicStream($offset=0, $limit=20, $since_id=0, $max_id=0)
676 $ids = Notice::stream(array('Notice', '_publicStreamDirect'),
679 $offset, $limit, $since_id, $max_id);
680 return Notice::getStreamByIds($ids);
683 function _publicStreamDirect($offset=0, $limit=20, $since_id=0, $max_id=0)
685 $notice = new Notice();
687 $notice->selectAdd(); // clears it
688 $notice->selectAdd('id');
690 $notice->orderBy('created DESC, id DESC');
692 if (!is_null($offset)) {
693 $notice->limit($offset, $limit);
696 if (common_config('public', 'localonly')) {
697 $notice->whereAdd('is_local = ' . Notice::LOCAL_PUBLIC);
699 // -1 == blacklisted, -2 == gateway (i.e. Twitter)
700 $notice->whereAdd('is_local !='. Notice::LOCAL_NONPUBLIC);
701 $notice->whereAdd('is_local !='. Notice::GATEWAY);
704 Notice::addWhereSinceId($notice, $since_id);
705 Notice::addWhereMaxId($notice, $max_id);
709 if ($notice->find()) {
710 while ($notice->fetch()) {
711 $ids[] = $notice->id;
721 function conversationStream($id, $offset=0, $limit=20, $since_id=0, $max_id=0)
723 $ids = Notice::stream(array('Notice', '_conversationStreamDirect'),
725 'notice:conversation_ids:'.$id,
726 $offset, $limit, $since_id, $max_id);
728 return Notice::getStreamByIds($ids);
731 function _conversationStreamDirect($id, $offset=0, $limit=20, $since_id=0, $max_id=0)
733 $notice = new Notice();
735 $notice->selectAdd(); // clears it
736 $notice->selectAdd('id');
738 $notice->conversation = $id;
740 $notice->orderBy('created DESC, id DESC');
742 if (!is_null($offset)) {
743 $notice->limit($offset, $limit);
746 Notice::addWhereSinceId($notice, $since_id);
747 Notice::addWhereMaxId($notice, $max_id);
751 if ($notice->find()) {
752 while ($notice->fetch()) {
753 $ids[] = $notice->id;
764 * Is this notice part of an active conversation?
766 * @return boolean true if other messages exist in the same
767 * conversation, false if this is the only one
769 function hasConversation()
771 if (!empty($this->conversation)) {
772 $conversation = Notice::conversationStream(
778 if ($conversation->N > 0) {
786 * Grab the earliest notice from this conversation.
788 * @return Notice or null
790 function conversationRoot()
792 if (!empty($this->conversation)) {
793 $c = self::memcache();
795 $key = Cache::key('notice:conversation_root:' . $this->conversation);
796 $notice = $c->get($key);
801 $notice = new Notice();
802 $notice->conversation = $this->conversation;
803 $notice->orderBy('CREATED');
808 $c->set($key, $notice);
815 * Pull up a full list of local recipients who will be getting
816 * this notice in their inbox. Results will be cached, so don't
817 * change the input data wily-nilly!
819 * @param array $groups optional list of Group objects;
820 * if left empty, will be loaded from group_inbox records
821 * @param array $recipient optional list of reply profile ids
822 * if left empty, will be loaded from reply records
823 * @return array associating recipient user IDs with an inbox source constant
825 function whoGets($groups=null, $recipients=null)
827 $c = self::memcache();
830 $ni = $c->get(Cache::key('notice:who_gets:'.$this->id));
836 if (is_null($groups)) {
837 $groups = $this->getGroups();
840 if (is_null($recipients)) {
841 $recipients = $this->getReplies();
844 $users = $this->getSubscribedUsers();
846 // FIXME: kind of ignoring 'transitional'...
847 // we'll probably stop supporting inboxless mode
852 // Give plugins a chance to add folks in at start...
853 if (Event::handle('StartNoticeWhoGets', array($this, &$ni))) {
855 foreach ($users as $id) {
856 $ni[$id] = NOTICE_INBOX_SOURCE_SUB;
859 foreach ($groups as $group) {
860 $users = $group->getUserMembers();
861 foreach ($users as $id) {
862 if (!array_key_exists($id, $ni)) {
863 $ni[$id] = NOTICE_INBOX_SOURCE_GROUP;
868 foreach ($recipients as $recipient) {
869 if (!array_key_exists($recipient, $ni)) {
870 $ni[$recipient] = NOTICE_INBOX_SOURCE_REPLY;
874 // Exclude any deleted, non-local, or blocking recipients.
875 $profile = $this->getProfile();
876 $originalProfile = null;
877 if ($this->repeat_of) {
878 // Check blocks against the original notice's poster as well.
879 $original = Notice::staticGet('id', $this->repeat_of);
881 $originalProfile = $original->getProfile();
884 foreach ($ni as $id => $source) {
885 $user = User::staticGet('id', $id);
886 if (empty($user) || $user->hasBlocked($profile) ||
887 ($originalProfile && $user->hasBlocked($originalProfile))) {
892 // Give plugins a chance to filter out...
893 Event::handle('EndNoticeWhoGets', array($this, &$ni));
897 // XXX: pack this data better
898 $c->set(Cache::key('notice:who_gets:'.$this->id), $ni);
905 * Adds this notice to the inboxes of each local user who should receive
906 * it, based on author subscriptions, group memberships, and @-replies.
908 * Warning: running a second time currently will make items appear
909 * multiple times in users' inboxes.
911 * @fixme make more robust against errors
912 * @fixme break up massive deliveries to smaller background tasks
914 * @param array $groups optional list of Group objects;
915 * if left empty, will be loaded from group_inbox records
916 * @param array $recipient optional list of reply profile ids
917 * if left empty, will be loaded from reply records
919 function addToInboxes($groups=null, $recipients=null)
921 $ni = $this->whoGets($groups, $recipients);
923 $ids = array_keys($ni);
925 // We remove the author (if they're a local user),
926 // since we'll have already done this in distribute()
928 $i = array_search($this->profile_id, $ids);
936 Inbox::bulkInsert($this->id, $ids);
941 function getSubscribedUsers()
945 if(common_config('db','quote_identifiers'))
946 $user_table = '"user"';
947 else $user_table = 'user';
951 'FROM '. $user_table .' JOIN subscription '.
952 'ON '. $user_table .'.id = subscription.subscriber ' .
953 'WHERE subscription.subscribed = %d ';
955 $user->query(sprintf($qry, $this->profile_id));
959 while ($user->fetch()) {
969 * Record this notice to the given group inboxes for delivery.
970 * Overrides the regular parsing of !group markup.
972 * @param string $group_ids
973 * @fixme might prefer URIs as identifiers, as for replies?
974 * best with generalizations on user_group to support
975 * remote groups better.
977 function saveKnownGroups($group_ids)
979 if (!is_array($group_ids)) {
980 // TRANS: Server exception thrown when no array is provided to the method saveKnownGroups().
981 throw new ServerException(_('Bad type provided to saveKnownGroups.'));
985 foreach (array_unique($group_ids) as $id) {
986 $group = User_group::staticGet('id', $id);
988 common_log(LOG_ERR, "Local delivery to group id $id, $group->nickname");
989 $result = $this->addToGroupInbox($group);
991 common_log_db_error($gi, 'INSERT', __FILE__);
994 // @fixme should we save the tags here or not?
995 $groups[] = clone($group);
997 common_log(LOG_ERR, "Local delivery to group id $id skipped, doesn't exist");
1005 * Parse !group delivery and record targets into group_inbox.
1006 * @return array of Group objects
1008 function saveGroups()
1010 // Don't save groups for repeats
1012 if (!empty($this->repeat_of)) {
1018 /* extract all !group */
1019 $count = preg_match_all('/(?:^|\s)!(' . Nickname::DISPLAY_FMT . ')/',
1020 strtolower($this->content),
1026 $profile = $this->getProfile();
1028 /* Add them to the database */
1030 foreach (array_unique($match[1]) as $nickname) {
1031 /* XXX: remote groups. */
1032 $group = User_group::getForNickname($nickname, $profile);
1034 if (empty($group)) {
1038 // we automatically add a tag for every group name, too
1040 $tag = Notice_tag::pkeyGet(array('tag' => common_canonical_tag($nickname),
1041 'notice_id' => $this->id));
1043 if (is_null($tag)) {
1044 $this->saveTag($nickname);
1047 if ($profile->isMember($group)) {
1049 $result = $this->addToGroupInbox($group);
1052 common_log_db_error($gi, 'INSERT', __FILE__);
1055 $groups[] = clone($group);
1062 function addToGroupInbox($group)
1064 $gi = Group_inbox::pkeyGet(array('group_id' => $group->id,
1065 'notice_id' => $this->id));
1069 $gi = new Group_inbox();
1071 $gi->group_id = $group->id;
1072 $gi->notice_id = $this->id;
1073 $gi->created = $this->created;
1075 $result = $gi->insert();
1078 common_log_db_error($gi, 'INSERT', __FILE__);
1079 // TRANS: Server exception thrown when an update for a group inbox fails.
1080 throw new ServerException(_('Problem saving group inbox.'));
1083 self::blow('user_group:notice_ids:%d', $gi->group_id);
1090 * Save reply records indicating that this notice needs to be
1091 * delivered to the local users with the given URIs.
1093 * Since this is expected to be used when saving foreign-sourced
1094 * messages, we won't deliver to any remote targets as that's the
1095 * source service's responsibility.
1097 * Mail notifications etc will be handled later.
1099 * @param array of unique identifier URIs for recipients
1101 function saveKnownReplies($uris)
1107 $sender = Profile::staticGet($this->profile_id);
1109 foreach (array_unique($uris) as $uri) {
1111 $profile = Profile::fromURI($uri);
1113 if (empty($profile)) {
1114 common_log(LOG_WARNING, "Unable to determine profile for URI '$uri'");
1118 if ($profile->hasBlocked($sender)) {
1119 common_log(LOG_INFO, "Not saving reply to profile {$profile->id} ($uri) from sender {$sender->id} because of a block.");
1123 $reply = new Reply();
1125 $reply->notice_id = $this->id;
1126 $reply->profile_id = $profile->id;
1127 $reply->modified = $this->created;
1129 common_log(LOG_INFO, __METHOD__ . ": saving reply: notice $this->id to profile $profile->id");
1131 $id = $reply->insert();
1138 * Pull @-replies from this message's content in StatusNet markup format
1139 * and save reply records indicating that this message needs to be
1140 * delivered to those users.
1142 * Mail notifications to local profiles will be sent later.
1144 * @return array of integer profile IDs
1147 function saveReplies()
1149 // Don't save reply data for repeats
1151 if (!empty($this->repeat_of)) {
1155 $sender = Profile::staticGet($this->profile_id);
1157 // @todo ideally this parser information would only
1158 // be calculated once.
1160 $mentions = common_find_mentions($this->content, $this);
1164 // store replied only for first @ (what user/notice what the reply directed,
1165 // we assume first @ is it)
1167 foreach ($mentions as $mention) {
1169 foreach ($mention['mentioned'] as $mentioned) {
1171 // skip if they're already covered
1173 if (!empty($replied[$mentioned->id])) {
1177 // Don't save replies from blocked profile to local user
1179 $mentioned_user = User::staticGet('id', $mentioned->id);
1180 if (!empty($mentioned_user) && $mentioned_user->hasBlocked($sender)) {
1184 $reply = new Reply();
1186 $reply->notice_id = $this->id;
1187 $reply->profile_id = $mentioned->id;
1188 $reply->modified = $this->created;
1190 $id = $reply->insert();
1193 common_log_db_error($reply, 'INSERT', __FILE__);
1194 // TRANS: Server exception thrown when a reply cannot be saved.
1195 // TRANS: %1$d is a notice ID, %2$d is the ID of the mentioned user.
1196 throw new ServerException(sprintf(_('Could not save reply for %1$d, %2$d.'), $this->id, $mentioned->id));
1198 $replied[$mentioned->id] = 1;
1199 self::blow('reply:stream:%d', $mentioned->id);
1204 $recipientIds = array_keys($replied);
1206 return $recipientIds;
1210 * Pull the complete list of @-reply targets for this notice.
1212 * @return array of integer profile ids
1214 function getReplies()
1220 $reply = new Reply();
1221 $reply->selectAdd();
1222 $reply->selectAdd('profile_id');
1223 $reply->notice_id = $this->id;
1225 if ($reply->find()) {
1226 while($reply->fetch()) {
1227 $ids[] = $reply->profile_id;
1237 * Send e-mail notifications to local @-reply targets.
1239 * Replies must already have been saved; this is expected to be run
1240 * from the distrib queue handler.
1242 function sendReplyNotifications()
1244 // Don't send reply notifications for repeats
1246 if (!empty($this->repeat_of)) {
1250 $recipientIds = $this->getReplies();
1252 foreach ($recipientIds as $recipientId) {
1253 $user = User::staticGet('id', $recipientId);
1254 if (!empty($user)) {
1255 mail_notify_attn($user, $this);
1261 * Pull list of groups this notice needs to be delivered to,
1262 * as previously recorded by saveGroups() or saveKnownGroups().
1264 * @return array of Group objects
1266 function getGroups()
1268 // Don't save groups for repeats
1270 if (!empty($this->repeat_of)) {
1278 $gi = new Group_inbox();
1281 $gi->selectAdd('group_id');
1283 $gi->notice_id = $this->id;
1286 while ($gi->fetch()) {
1287 $group = User_group::staticGet('id', $gi->group_id);
1300 * Convert a notice into an activity for export.
1302 * @param User $cur Current user
1304 * @return Activity activity object representing this Notice.
1307 function asActivity($cur)
1309 $act = self::cacheGet(Cache::codeKey('notice:as-activity:'.$this->id));
1314 $act = new Activity();
1316 if (Event::handle('StartNoticeAsActivity', array($this, &$act))) {
1318 $profile = $this->getProfile();
1320 $act->actor = ActivityObject::fromProfile($profile);
1321 $act->actor->extra[] = $profile->profileInfo($cur);
1322 $act->verb = ActivityVerb::POST;
1323 $act->objects[] = ActivityObject::fromNotice($this);
1325 // XXX: should this be handled by default processing for object entry?
1327 $act->time = strtotime($this->created);
1328 $act->link = $this->bestUrl();
1330 $act->content = common_xml_safe_str($this->rendered);
1331 $act->id = $this->uri;
1332 $act->title = common_xml_safe_str($this->content);
1336 $tags = $this->getTags();
1338 foreach ($tags as $tag) {
1339 $cat = new AtomCategory();
1342 $act->categories[] = $cat;
1346 // XXX: use Atom Media and/or File activity objects instead
1348 $attachments = $this->attachments();
1350 foreach ($attachments as $attachment) {
1351 $enclosure = $attachment->getEnclosure();
1353 $act->enclosures[] = $enclosure;
1357 $ctx = new ActivityContext();
1359 if (!empty($this->reply_to)) {
1360 $reply = Notice::staticGet('id', $this->reply_to);
1361 if (!empty($reply)) {
1362 $ctx->replyToID = $reply->uri;
1363 $ctx->replyToUrl = $reply->bestUrl();
1367 $ctx->location = $this->getLocation();
1371 if (!empty($this->conversation)) {
1372 $conv = Conversation::staticGet('id', $this->conversation);
1373 if (!empty($conv)) {
1374 $ctx->conversation = $conv->uri;
1378 $reply_ids = $this->getReplies();
1380 foreach ($reply_ids as $id) {
1381 $profile = Profile::staticGet('id', $id);
1382 if (!empty($profile)) {
1383 $ctx->attention[] = $profile->getUri();
1387 $groups = $this->getGroups();
1389 foreach ($groups as $group) {
1390 $ctx->attention[] = $group->getUri();
1393 // XXX: deprecated; use ActivityVerb::SHARE instead
1397 if (!empty($this->repeat_of)) {
1398 $repeat = Notice::staticGet('id', $this->repeat_of);
1399 $ctx->forwardID = $repeat->uri;
1400 $ctx->forwardUrl = $repeat->bestUrl();
1403 $act->context = $ctx;
1407 $atom_feed = $profile->getAtomFeed();
1409 if (!empty($atom_feed)) {
1411 $act->source = new ActivitySource();
1413 // XXX: we should store the actual feed ID
1415 $act->source->id = $atom_feed;
1417 // XXX: we should store the actual feed title
1419 $act->source->title = $profile->getBestName();
1421 $act->source->links['alternate'] = $profile->profileurl;
1422 $act->source->links['self'] = $atom_feed;
1424 $act->source->icon = $profile->avatarUrl(AVATAR_PROFILE_SIZE);
1426 $notice = $profile->getCurrentNotice();
1428 if (!empty($notice)) {
1429 $act->source->updated = self::utcDate($notice->created);
1432 $user = User::staticGet('id', $profile->id);
1434 if (!empty($user)) {
1435 $act->source->links['license'] = common_config('license', 'url');
1439 if ($this->isLocal()) {
1440 $act->selfLink = common_local_url('ApiStatusesShow', array('id' => $this->id,
1441 'format' => 'atom'));
1442 $act->editLink = $act->selfLink;
1445 Event::handle('EndNoticeAsActivity', array($this, &$act));
1448 self::cacheSet(Cache::codeKey('notice:as-activity:'.$this->id), $act);
1453 // This has gotten way too long. Needs to be sliced up into functional bits
1454 // or ideally exported to a utility class.
1456 function asAtomEntry($namespace=false,
1461 $act = $this->asActivity($cur);
1462 $act->extra[] = $this->noticeInfo($cur);
1463 return $act->asString($namespace, $author, $source);
1467 * Extra notice info for atom entries
1469 * Clients use some extra notice info in the atom stream.
1470 * This gives it to them.
1472 * @param User $cur Current user
1474 * @return array representation of <statusnet:notice_info> element
1477 function noticeInfo($cur)
1479 // local notice ID (useful to clients for ordering)
1481 $noticeInfoAttr = array('local_id' => $this->id);
1485 $ns = $this->getSource();
1488 $noticeInfoAttr['source'] = $ns->code;
1489 if (!empty($ns->url)) {
1490 $noticeInfoAttr['source_link'] = $ns->url;
1491 if (!empty($ns->name)) {
1492 $noticeInfoAttr['source'] = '<a href="'
1493 . htmlspecialchars($ns->url)
1494 . '" rel="nofollow">'
1495 . htmlspecialchars($ns->name)
1501 // favorite and repeated
1504 $noticeInfoAttr['favorite'] = ($cur->hasFave($this)) ? "true" : "false";
1505 $cp = $cur->getProfile();
1506 $noticeInfoAttr['repeated'] = ($cp->hasRepeated($this->id)) ? "true" : "false";
1509 if (!empty($this->repeat_of)) {
1510 $noticeInfoAttr['repeat_of'] = $this->repeat_of;
1513 return array('statusnet:notice_info', $noticeInfoAttr, null);
1517 * Returns an XML string fragment with a reference to a notice as an
1518 * Activity Streams noun object with the given element type.
1520 * Assumes that 'activity' namespace has been previously defined.
1522 * @param string $element one of 'subject', 'object', 'target'
1526 function asActivityNoun($element)
1528 $noun = ActivityObject::fromNotice($this);
1529 return $noun->asString('activity:' . $element);
1534 if (!empty($this->url)) {
1536 } else if (!empty($this->uri) && preg_match('/^https?:/', $this->uri)) {
1539 return common_local_url('shownotice',
1540 array('notice' => $this->id));
1544 function stream($fn, $args, $cachekey, $offset=0, $limit=20, $since_id=0, $max_id=0)
1546 $cache = Cache::instance();
1548 if (empty($cache) ||
1549 $since_id != 0 || $max_id != 0 ||
1551 ($offset + $limit) > NOTICE_CACHE_WINDOW) {
1552 return call_user_func_array($fn, array_merge($args, array($offset, $limit, $since_id,
1556 $idkey = Cache::key($cachekey);
1558 $idstr = $cache->get($idkey);
1560 if ($idstr !== false) {
1561 // Cache hit! Woohoo!
1562 $window = explode(',', $idstr);
1563 $ids = array_slice($window, $offset, $limit);
1567 $laststr = $cache->get($idkey.';last');
1569 if ($laststr !== false) {
1570 $window = explode(',', $laststr);
1571 $last_id = $window[0];
1572 $new_ids = call_user_func_array($fn, array_merge($args, array(0, NOTICE_CACHE_WINDOW,
1573 $last_id, 0, null)));
1575 $new_window = array_merge($new_ids, $window);
1577 $new_windowstr = implode(',', $new_window);
1579 $result = $cache->set($idkey, $new_windowstr);
1580 $result = $cache->set($idkey . ';last', $new_windowstr);
1582 $ids = array_slice($new_window, $offset, $limit);
1587 $window = call_user_func_array($fn, array_merge($args, array(0, NOTICE_CACHE_WINDOW,
1590 $windowstr = implode(',', $window);
1592 $result = $cache->set($idkey, $windowstr);
1593 $result = $cache->set($idkey . ';last', $windowstr);
1595 $ids = array_slice($window, $offset, $limit);
1601 * Determine which notice, if any, a new notice is in reply to.
1603 * For conversation tracking, we try to see where this notice fits
1604 * in the tree. Rough algorithm is:
1606 * if (reply_to is set and valid) {
1608 * } else if ((source not API or Web) and (content starts with "T NAME" or "@name ")) {
1609 * return ID of last notice by initial @name in content;
1612 * Note that all @nickname instances will still be used to save "reply" records,
1613 * so the notice shows up in the mentioned users' "replies" tab.
1615 * @param integer $reply_to ID passed in by Web or API
1616 * @param integer $profile_id ID of author
1617 * @param string $source Source tag, like 'web' or 'gwibber'
1618 * @param string $content Final notice content
1620 * @return integer ID of replied-to notice, or null for not a reply.
1623 static function getReplyTo($reply_to, $profile_id, $source, $content)
1625 static $lb = array('xmpp', 'mail', 'sms', 'omb');
1627 // If $reply_to is specified, we check that it exists, and then
1628 // return it if it does
1630 if (!empty($reply_to)) {
1631 $reply_notice = Notice::staticGet('id', $reply_to);
1632 if (!empty($reply_notice)) {
1637 // If it's not a "low bandwidth" source (one where you can't set
1638 // a reply_to argument), we return. This is mostly web and API
1641 if (!in_array($source, $lb)) {
1645 // Is there an initial @ or T?
1647 if (preg_match('/^T ([A-Z0-9]{1,64}) /', $content, $match) ||
1648 preg_match('/^@([a-z0-9]{1,64})\s+/', $content, $match)) {
1649 $nickname = common_canonical_nickname($match[1]);
1654 // Figure out who that is.
1656 $sender = Profile::staticGet('id', $profile_id);
1657 if (empty($sender)) {
1661 $recipient = common_relative_profile($sender, $nickname, common_sql_now());
1663 if (empty($recipient)) {
1667 // Get their last notice
1669 $last = $recipient->getCurrentNotice();
1671 if (!empty($last)) {
1676 static function maxContent()
1678 $contentlimit = common_config('notice', 'contentlimit');
1679 // null => use global limit (distinct from 0!)
1680 if (is_null($contentlimit)) {
1681 $contentlimit = common_config('site', 'textlimit');
1683 return $contentlimit;
1686 static function contentTooLong($content)
1688 $contentlimit = self::maxContent();
1689 return ($contentlimit > 0 && !empty($content) && (mb_strlen($content) > $contentlimit));
1692 function getLocation()
1696 if (!empty($this->location_id) && !empty($this->location_ns)) {
1697 $location = Location::fromId($this->location_id, $this->location_ns);
1700 if (is_null($location)) { // no ID, or Location::fromId() failed
1701 if (!empty($this->lat) && !empty($this->lon)) {
1702 $location = Location::fromLatLon($this->lat, $this->lon);
1709 function repeat($repeater_id, $source)
1711 $author = Profile::staticGet('id', $this->profile_id);
1713 // TRANS: Message used to repeat a notice. RT is the abbreviation of 'retweet'.
1714 // TRANS: %1$s is the repeated user's name, %2$s is the repeated notice.
1715 $content = sprintf(_('RT @%1$s %2$s'),
1719 $maxlen = common_config('site', 'textlimit');
1720 if ($maxlen > 0 && mb_strlen($content) > $maxlen) {
1721 // Web interface and current Twitter API clients will
1722 // pull the original notice's text, but some older
1723 // clients and RSS/Atom feeds will see this trimmed text.
1725 // Unfortunately this is likely to lose tags or URLs
1726 // at the end of long notices.
1727 $content = mb_substr($content, 0, $maxlen - 4) . ' ...';
1730 return self::saveNew($repeater_id, $content, $source,
1731 array('repeat_of' => $this->id));
1734 // These are supposed to be in chron order!
1736 function repeatStream($limit=100)
1738 $cache = Cache::instance();
1740 if (empty($cache)) {
1741 $ids = $this->_repeatStreamDirect($limit);
1743 $idstr = $cache->get(Cache::key('notice:repeats:'.$this->id));
1744 if ($idstr !== false) {
1745 $ids = explode(',', $idstr);
1747 $ids = $this->_repeatStreamDirect(100);
1748 $cache->set(Cache::key('notice:repeats:'.$this->id), implode(',', $ids));
1751 // We do a max of 100, so slice down to limit
1752 $ids = array_slice($ids, 0, $limit);
1756 return Notice::getStreamByIds($ids);
1759 function _repeatStreamDirect($limit)
1761 $notice = new Notice();
1763 $notice->selectAdd(); // clears it
1764 $notice->selectAdd('id');
1766 $notice->repeat_of = $this->id;
1768 $notice->orderBy('created, id'); // NB: asc!
1770 if (!is_null($limit)) {
1771 $notice->limit(0, $limit);
1776 if ($notice->find()) {
1777 while ($notice->fetch()) {
1778 $ids[] = $notice->id;
1788 function locationOptions($lat, $lon, $location_id, $location_ns, $profile = null)
1792 if (!empty($location_id) && !empty($location_ns)) {
1793 $options['location_id'] = $location_id;
1794 $options['location_ns'] = $location_ns;
1796 $location = Location::fromId($location_id, $location_ns);
1798 if (!empty($location)) {
1799 $options['lat'] = $location->lat;
1800 $options['lon'] = $location->lon;
1803 } else if (!empty($lat) && !empty($lon)) {
1804 $options['lat'] = $lat;
1805 $options['lon'] = $lon;
1807 $location = Location::fromLatLon($lat, $lon);
1809 if (!empty($location)) {
1810 $options['location_id'] = $location->location_id;
1811 $options['location_ns'] = $location->location_ns;
1813 } else if (!empty($profile)) {
1814 if (isset($profile->lat) && isset($profile->lon)) {
1815 $options['lat'] = $profile->lat;
1816 $options['lon'] = $profile->lon;
1819 if (isset($profile->location_id) && isset($profile->location_ns)) {
1820 $options['location_id'] = $profile->location_id;
1821 $options['location_ns'] = $profile->location_ns;
1828 function clearReplies()
1830 $replyNotice = new Notice();
1831 $replyNotice->reply_to = $this->id;
1833 //Null any notices that are replies to this notice
1835 if ($replyNotice->find()) {
1836 while ($replyNotice->fetch()) {
1837 $orig = clone($replyNotice);
1838 $replyNotice->reply_to = null;
1839 $replyNotice->update($orig);
1845 $reply = new Reply();
1846 $reply->notice_id = $this->id;
1848 if ($reply->find()) {
1849 while($reply->fetch()) {
1850 self::blow('reply:stream:%d', $reply->profile_id);
1858 function clearFiles()
1860 $f2p = new File_to_post();
1862 $f2p->post_id = $this->id;
1865 while ($f2p->fetch()) {
1869 // FIXME: decide whether to delete File objects
1870 // ...and related (actual) files
1873 function clearRepeats()
1875 $repeatNotice = new Notice();
1876 $repeatNotice->repeat_of = $this->id;
1878 //Null any notices that are repeats of this notice
1880 if ($repeatNotice->find()) {
1881 while ($repeatNotice->fetch()) {
1882 $orig = clone($repeatNotice);
1883 $repeatNotice->repeat_of = null;
1884 $repeatNotice->update($orig);
1889 function clearFaves()
1892 $fave->notice_id = $this->id;
1894 if ($fave->find()) {
1895 while ($fave->fetch()) {
1896 self::blow('fave:ids_by_user_own:%d', $fave->user_id);
1897 self::blow('fave:ids_by_user_own:%d;last', $fave->user_id);
1898 self::blow('fave:ids_by_user:%d', $fave->user_id);
1899 self::blow('fave:ids_by_user:%d;last', $fave->user_id);
1907 function clearTags()
1909 $tag = new Notice_tag();
1910 $tag->notice_id = $this->id;
1913 while ($tag->fetch()) {
1914 self::blow('profile:notice_ids_tagged:%d:%s', $this->profile_id, Cache::keyize($tag->tag));
1915 self::blow('profile:notice_ids_tagged:%d:%s;last', $this->profile_id, Cache::keyize($tag->tag));
1916 self::blow('notice_tag:notice_ids:%s', Cache::keyize($tag->tag));
1917 self::blow('notice_tag:notice_ids:%s;last', Cache::keyize($tag->tag));
1925 function clearGroupInboxes()
1927 $gi = new Group_inbox();
1929 $gi->notice_id = $this->id;
1932 while ($gi->fetch()) {
1933 self::blow('user_group:notice_ids:%d', $gi->group_id);
1941 function distribute()
1943 // We always insert for the author so they don't
1945 Event::handle('StartNoticeDistribute', array($this));
1947 $user = User::staticGet('id', $this->profile_id);
1948 if (!empty($user)) {
1949 Inbox::insertNotice($user->id, $this->id);
1952 if (common_config('queue', 'inboxes')) {
1953 // If there's a failure, we want to _force_
1954 // distribution at this point.
1956 $qm = QueueManager::get();
1957 $qm->enqueue($this, 'distrib');
1958 } catch (Exception $e) {
1959 // If the exception isn't transient, this
1960 // may throw more exceptions as DQH does
1961 // its own enqueueing. So, we ignore them!
1963 $handler = new DistribQueueHandler();
1964 $handler->handle($this);
1965 } catch (Exception $e) {
1966 common_log(LOG_ERR, "emergency redistribution resulted in " . $e->getMessage());
1968 // Re-throw so somebody smarter can handle it.
1972 $handler = new DistribQueueHandler();
1973 $handler->handle($this);
1979 $result = parent::insert();
1982 // Profile::hasRepeated() abuses pkeyGet(), so we
1983 // have to clear manually
1984 if (!empty($this->repeat_of)) {
1985 $c = self::memcache();
1987 $ck = self::multicacheKey('Notice',
1988 array('profile_id' => $this->profile_id,
1989 'repeat_of' => $this->repeat_of));
1999 * Get the source of the notice
2001 * @return Notice_source $ns A notice source object. 'code' is the only attribute
2002 * guaranteed to be populated.
2004 function getSource()
2006 $ns = new Notice_source();
2007 if (!empty($this->source)) {
2008 switch ($this->source) {
2015 $ns->code = $this->source;
2018 $ns = Notice_source::staticGet($this->source);
2020 $ns = new Notice_source();
2021 $ns->code = $this->source;
2022 $app = Oauth_application::staticGet('name', $this->source);
2024 $ns->name = $app->name;
2025 $ns->url = $app->source_url;
2035 * Determine whether the notice was locally created
2037 * @return boolean locality
2040 public function isLocal()
2042 return ($this->is_local == Notice::LOCAL_PUBLIC ||
2043 $this->is_local == Notice::LOCAL_NONPUBLIC);
2047 * Get the list of hash tags saved with this notice.
2049 * @return array of strings
2051 public function getTags()
2054 $tag = new Notice_tag();
2055 $tag->notice_id = $this->id;
2057 while ($tag->fetch()) {
2058 $tags[] = $tag->tag;
2065 static private function utcDate($dt)
2067 $dateStr = date('d F Y H:i:s', strtotime($dt));
2068 $d = new DateTime($dateStr, new DateTimeZone('UTC'));
2069 return $d->format(DATE_W3C);
2073 * Look up the creation timestamp for a given notice ID, even
2074 * if it's been deleted.
2077 * @return mixed string recorded creation timestamp, or false if can't be found
2079 public static function getAsTimestamp($id)
2085 $notice = Notice::staticGet('id', $id);
2087 return $notice->created;
2090 $deleted = Deleted_notice::staticGet('id', $id);
2092 return $deleted->created;
2099 * Build an SQL 'where' fragment for timestamp-based sorting from a since_id
2100 * parameter, matching notices posted after the given one (exclusive).
2102 * If the referenced notice can't be found, will return false.
2105 * @param string $idField
2106 * @param string $createdField
2107 * @return mixed string or false if no match
2109 public static function whereSinceId($id, $idField='id', $createdField='created')
2111 $since = Notice::getAsTimestamp($id);
2113 return sprintf("($createdField = '%s' and $idField > %d) or ($createdField > '%s')", $since, $id, $since);
2119 * Build an SQL 'where' fragment for timestamp-based sorting from a since_id
2120 * parameter, matching notices posted after the given one (exclusive), and
2121 * if necessary add it to the data object's query.
2123 * @param DB_DataObject $obj
2125 * @param string $idField
2126 * @param string $createdField
2127 * @return mixed string or false if no match
2129 public static function addWhereSinceId(DB_DataObject $obj, $id, $idField='id', $createdField='created')
2131 $since = self::whereSinceId($id, $idField, $createdField);
2133 $obj->whereAdd($since);
2138 * Build an SQL 'where' fragment for timestamp-based sorting from a max_id
2139 * parameter, matching notices posted before the given one (inclusive).
2141 * If the referenced notice can't be found, will return false.
2144 * @param string $idField
2145 * @param string $createdField
2146 * @return mixed string or false if no match
2148 public static function whereMaxId($id, $idField='id', $createdField='created')
2150 $max = Notice::getAsTimestamp($id);
2152 return sprintf("($createdField < '%s') or ($createdField = '%s' and $idField <= %d)", $max, $max, $id);
2158 * Build an SQL 'where' fragment for timestamp-based sorting from a max_id
2159 * parameter, matching notices posted before the given one (inclusive), and
2160 * if necessary add it to the data object's query.
2162 * @param DB_DataObject $obj
2164 * @param string $idField
2165 * @param string $createdField
2166 * @return mixed string or false if no match
2168 public static function addWhereMaxId(DB_DataObject $obj, $id, $idField='id', $createdField='created')
2170 $max = self::whereMaxId($id, $idField, $createdField);
2172 $obj->whereAdd($max);
2178 if (common_config('public', 'localonly')) {
2179 return ($this->is_local == Notice::LOCAL_PUBLIC);
2181 return (($this->is_local != Notice::LOCAL_NONPUBLIC) &&
2182 ($this->is_local != Notice::GATEWAY));