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)
78 function staticGet($k,$v=NULL)
80 return Memcached_DataObject::staticGet('Notice',$k,$v);
83 /* the code above is auto generated do not remove the tag below */
87 const LOCAL_PUBLIC = 1;
89 const LOCAL_NONPUBLIC = -1;
94 $profile = Profile::staticGet('id', $this->profile_id);
96 if (empty($profile)) {
97 // TRANS: Server exception thrown when a user profile for a notice cannot be found.
98 // TRANS: %1$d is a profile ID (number), %2$d is a notice ID (number).
99 throw new ServerException(sprintf(_('No such profile (%1$d) for notice (%2$d).'), $this->profile_id, $this->id));
107 // For auditing purposes, save a record that the notice
110 // @fixme we have some cases where things get re-run and so the
112 $deleted = Deleted_notice::staticGet('id', $this->id);
115 $deleted = Deleted_notice::staticGet('uri', $this->uri);
119 $deleted = new Deleted_notice();
121 $deleted->id = $this->id;
122 $deleted->profile_id = $this->profile_id;
123 $deleted->uri = $this->uri;
124 $deleted->created = $this->created;
125 $deleted->deleted = common_sql_now();
130 if (Event::handle('NoticeDeleteRelated', array($this))) {
132 // Clear related records
134 $this->clearReplies();
135 $this->clearRepeats();
138 $this->clearGroupInboxes();
141 // NOTE: we don't clear inboxes
142 // NOTE: we don't clear queue items
145 $result = parent::delete();
147 $this->blowOnDelete();
152 * Extract #hashtags from this notice's content and save them to the database.
156 /* extract all #hastags */
157 $count = preg_match_all('/(?:^|\s)#([\pL\pN_\-\.]{1,64})/u', strtolower($this->content), $match);
162 /* Add them to the database */
163 return $this->saveKnownTags($match[1]);
167 * Record the given set of hash tags in the db for this notice.
168 * Given tag strings will be normalized and checked for dupes.
170 function saveKnownTags($hashtags)
172 //turn each into their canonical tag
173 //this is needed to remove dupes before saving e.g. #hash.tag = #hashtag
174 for($i=0; $i<count($hashtags); $i++) {
175 /* elide characters we don't want in the tag */
176 $hashtags[$i] = common_canonical_tag($hashtags[$i]);
179 foreach(array_unique($hashtags) as $hashtag) {
180 $this->saveTag($hashtag);
181 self::blow('profile:notice_ids_tagged:%d:%s', $this->profile_id, $hashtag);
187 * Record a single hash tag as associated with this notice.
188 * Tag format and uniqueness must be validated by caller.
190 function saveTag($hashtag)
192 $tag = new Notice_tag();
193 $tag->notice_id = $this->id;
194 $tag->tag = $hashtag;
195 $tag->created = $this->created;
196 $id = $tag->insert();
199 // TRANS: Server exception. %s are the error details.
200 throw new ServerException(sprintf(_('Database error inserting hashtag: %s'),
201 $last_error->message));
205 // if it's saved, blow its cache
206 $tag->blowCache(false);
210 * Save a new notice and push it out to subscribers' inboxes.
211 * Poster's permissions are checked before sending.
213 * @param int $profile_id Profile ID of the poster
214 * @param string $content source message text; links may be shortened
215 * per current user's preference
216 * @param string $source source key ('web', 'api', etc)
217 * @param array $options Associative array of optional properties:
218 * string 'created' timestamp of notice; defaults to now
219 * int 'is_local' source/gateway ID, one of:
220 * Notice::LOCAL_PUBLIC - Local, ok to appear in public timeline
221 * Notice::REMOTE_OMB - Sent from a remote OMB service;
222 * hide from public timeline but show in
223 * local "and friends" timelines
224 * Notice::LOCAL_NONPUBLIC - Local, but hide from public timeline
225 * Notice::GATEWAY - From another non-OMB service;
226 * will not appear in public views
227 * float 'lat' decimal latitude for geolocation
228 * float 'lon' decimal longitude for geolocation
229 * int 'location_id' geoname identifier
230 * int 'location_ns' geoname namespace to interpret location_id
231 * int 'reply_to'; notice ID this is a reply to
232 * int 'repeat_of'; notice ID this is a repeat of
233 * string 'uri' unique ID for notice; defaults to local notice URL
234 * string 'url' permalink to notice; defaults to local notice URL
235 * string 'rendered' rendered HTML version of content
236 * array 'replies' list of profile URIs for reply delivery in
237 * place of extracting @-replies from content.
238 * array 'groups' list of group IDs to deliver to, in place of
239 * extracting ! tags from content
240 * array 'tags' list of hashtag strings to save with the notice
241 * in place of extracting # tags from content
242 * array 'urls' list of attached/referred URLs to save with the
243 * notice in place of extracting links from content
244 * boolean 'distribute' whether to distribute the notice, default true
245 * string 'object_type' URL of the associated object type (default ActivityObject::NOTE)
247 * @fixme tag override
250 * @throws ClientException
252 static function saveNew($profile_id, $content, $source, $options=null) {
253 $defaults = array('uri' => null,
257 'distribute' => true);
259 if (!empty($options)) {
260 $options = $options + $defaults;
266 if (!isset($is_local)) {
267 $is_local = Notice::LOCAL_PUBLIC;
270 $profile = Profile::staticGet('id', $profile_id);
271 $user = User::staticGet('id', $profile_id);
273 // Use the local user's shortening preferences, if applicable.
274 $final = $user->shortenLinks($content);
276 $final = common_shorten_links($content);
279 if (Notice::contentTooLong($final)) {
280 // TRANS: Client exception thrown if a notice contains too many characters.
281 throw new ClientException(_('Problem saving notice. Too long.'));
284 if (empty($profile)) {
285 // TRANS: Client exception thrown when trying to save a notice for an unknown user.
286 throw new ClientException(_('Problem saving notice. Unknown user.'));
289 if (common_config('throttle', 'enabled') && !Notice::checkEditThrottle($profile_id)) {
290 common_log(LOG_WARNING, 'Excessive posting by profile #' . $profile_id . '; throttled.');
291 // TRANS: Client exception thrown when a user tries to post too many notices in a given time frame.
292 throw new ClientException(_('Too many notices too fast; take a breather '.
293 'and post again in a few minutes.'));
296 if (common_config('site', 'dupelimit') > 0 && !Notice::checkDupes($profile_id, $final)) {
297 common_log(LOG_WARNING, 'Dupe posting by profile #' . $profile_id . '; throttled.');
298 // TRANS: Client exception thrown when a user tries to post too many duplicate notices in a given time frame.
299 throw new ClientException(_('Too many duplicate messages too quickly;'.
300 ' take a breather and post again in a few minutes.'));
303 if (!$profile->hasRight(Right::NEWNOTICE)) {
304 common_log(LOG_WARNING, "Attempted post from user disallowed to post: " . $profile->nickname);
306 // TRANS: Client exception thrown when a user tries to post while being banned.
307 throw new ClientException(_('You are banned from posting notices on this site.'), 403);
310 $notice = new Notice();
311 $notice->profile_id = $profile_id;
313 $autosource = common_config('public', 'autosource');
315 // Sandboxed are non-false, but not 1, either
317 if (!$profile->hasRight(Right::PUBLICNOTICE) ||
318 ($source && $autosource && in_array($source, $autosource))) {
319 $notice->is_local = Notice::LOCAL_NONPUBLIC;
321 $notice->is_local = $is_local;
324 if (!empty($created)) {
325 $notice->created = $created;
327 $notice->created = common_sql_now();
330 $notice->content = $final;
332 $notice->source = $source;
336 // Handle repeat case
338 if (isset($repeat_of)) {
339 $notice->repeat_of = $repeat_of;
341 $notice->reply_to = self::getReplyTo($reply_to, $profile_id, $source, $final);
344 if (!empty($notice->reply_to)) {
345 $reply = Notice::staticGet('id', $notice->reply_to);
346 $notice->conversation = $reply->conversation;
349 if (!empty($lat) && !empty($lon)) {
354 if (!empty($location_ns) && !empty($location_id)) {
355 $notice->location_id = $location_id;
356 $notice->location_ns = $location_ns;
359 if (!empty($rendered)) {
360 $notice->rendered = $rendered;
362 $notice->rendered = common_render_content($final, $notice);
365 if (empty($object_type)) {
366 $notice->object_type = (empty($notice->reply_to)) ? ActivityObject::NOTE : ActivityObject::COMMENT;
368 $notice->object_type = $object_type;
371 if (Event::handle('StartNoticeSave', array(&$notice))) {
373 // XXX: some of these functions write to the DB
375 $id = $notice->insert();
378 common_log_db_error($notice, 'INSERT', __FILE__);
379 // TRANS: Server exception thrown when a notice cannot be saved.
380 throw new ServerException(_('Problem saving notice.'));
383 // Update ID-dependent columns: URI, conversation
385 $orig = clone($notice);
390 $notice->uri = common_notice_uri($notice);
394 // If it's not part of a conversation, it's
395 // the beginning of a new conversation.
397 if (empty($notice->conversation)) {
398 $conv = Conversation::create();
399 $notice->conversation = $conv->id;
404 if (!$notice->update($orig)) {
405 common_log_db_error($notice, 'UPDATE', __FILE__);
406 // TRANS: Server exception thrown when a notice cannot be updated.
407 throw new ServerException(_('Problem saving notice.'));
413 // Clear the cache for subscribed users, so they'll update at next request
414 // XXX: someone clever could prepend instead of clearing the cache
416 $notice->blowOnInsert();
418 // Save per-notice metadata...
420 if (isset($replies)) {
421 $notice->saveKnownReplies($replies);
423 $notice->saveReplies();
427 $notice->saveKnownTags($tags);
432 // Note: groups may save tags, so must be run after tags are saved
433 // to avoid errors on duplicates.
434 if (isset($groups)) {
435 $notice->saveKnownGroups($groups);
437 $notice->saveGroups();
441 $notice->saveKnownUrls($urls);
447 // Prepare inbox delivery, may be queued to background.
448 $notice->distribute();
454 function blowOnInsert($conversation = false)
456 self::blow('profile:notice_ids:%d', $this->profile_id);
458 if ($this->isPublic()) {
459 self::blow('public');
462 // XXX: Before we were blowing the casche only if the notice id
463 // was not the root of the conversation. What to do now?
465 self::blow('notice:conversation_ids:%d', $this->conversation);
467 if (!empty($this->repeat_of)) {
468 self::blow('notice:repeats:%d', $this->repeat_of);
471 $original = Notice::staticGet('id', $this->repeat_of);
473 if (!empty($original)) {
474 $originalUser = User::staticGet('id', $original->profile_id);
475 if (!empty($originalUser)) {
476 self::blow('user:repeats_of_me:%d', $originalUser->id);
480 $profile = Profile::staticGet($this->profile_id);
481 if (!empty($profile)) {
482 $profile->blowNoticeCount();
487 * Clear cache entries related to this notice at delete time.
488 * Necessary to avoid breaking paging on public, profile timelines.
490 function blowOnDelete()
492 $this->blowOnInsert();
494 self::blow('profile:notice_ids:%d;last', $this->profile_id);
496 if ($this->isPublic()) {
497 self::blow('public;last');
500 self::blow('fave:by_notice', $this->id);
502 if ($this->conversation) {
503 // In case we're the first, will need to calc a new root.
504 self::blow('notice:conversation_root:%d', $this->conversation);
508 /** save all urls in the notice to the db
510 * follow redirects and save all available file information
511 * (mimetype, date, size, oembed, etc.)
515 function saveUrls() {
516 if (common_config('attachments', 'process_links')) {
517 common_replace_urls_callback($this->content, array($this, 'saveUrl'), $this->id);
522 * Save the given URLs as related links/attachments to the db
524 * follow redirects and save all available file information
525 * (mimetype, date, size, oembed, etc.)
529 function saveKnownUrls($urls)
531 if (common_config('attachments', 'process_links')) {
532 // @fixme validation?
533 foreach (array_unique($urls) as $url) {
534 File::processNew($url, $this->id);
542 function saveUrl($url, $notice_id) {
543 File::processNew($url, $notice_id);
546 static function checkDupes($profile_id, $content) {
547 $profile = Profile::staticGet($profile_id);
548 if (empty($profile)) {
551 $notice = $profile->getNotices(0, NOTICE_CACHE_WINDOW);
552 if (!empty($notice)) {
554 while ($notice->fetch()) {
555 if (time() - strtotime($notice->created) >= common_config('site', 'dupelimit')) {
557 } else if ($notice->content == $content) {
562 // If we get here, oldest item in cache window is not
563 // old enough for dupe limit; do direct check against DB
564 $notice = new Notice();
565 $notice->profile_id = $profile_id;
566 $notice->content = $content;
567 $threshold = common_sql_date(time() - common_config('site', 'dupelimit'));
568 $notice->whereAdd(sprintf("created > '%s'", $notice->escape($threshold)));
570 $cnt = $notice->count();
574 static function checkEditThrottle($profile_id) {
575 $profile = Profile::staticGet($profile_id);
576 if (empty($profile)) {
579 // Get the Nth notice
580 $notice = $profile->getNotices(common_config('throttle', 'count') - 1, 1);
581 if ($notice && $notice->fetch()) {
582 // If the Nth notice was posted less than timespan seconds ago
583 if (time() - strtotime($notice->created) <= common_config('throttle', 'timespan')) {
588 // Either not N notices in the stream, OR the Nth was not posted within timespan seconds
592 function getUploadedAttachment() {
594 $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"';
595 $post->query($query);
597 if (empty($post->up) || empty($post->i)) {
600 $ret = array($post->up, $post->i);
606 function hasAttachments() {
608 $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);
609 $post->query($query);
611 $n_attachments = intval($post->n_attachments);
613 return $n_attachments;
616 function attachments() {
619 $f2p = new File_to_post;
620 $f2p->post_id = $this->id;
622 while ($f2p->fetch()) {
623 $f = File::staticGet($f2p->file_id);
632 function getStreamByIds($ids)
634 $cache = Cache::instance();
636 if (!empty($cache)) {
638 foreach ($ids as $id) {
639 $n = Notice::staticGet('id', $id);
644 return new ArrayWrapper($notices);
646 $notice = new Notice();
648 //if no IDs requested, just return the notice object
651 $notice->whereAdd('id in (' . implode(', ', $ids) . ')');
657 while ($notice->fetch()) {
658 $temp[$notice->id] = clone($notice);
663 foreach ($ids as $id) {
664 if (array_key_exists($id, $temp)) {
665 $wrapped[] = $temp[$id];
669 return new ArrayWrapper($wrapped);
673 function publicStream($offset=0, $limit=20, $since_id=0, $max_id=0)
675 $ids = Notice::stream(array('Notice', '_publicStreamDirect'),
678 $offset, $limit, $since_id, $max_id);
679 return Notice::getStreamByIds($ids);
682 function _publicStreamDirect($offset=0, $limit=20, $since_id=0, $max_id=0)
684 $notice = new Notice();
686 $notice->selectAdd(); // clears it
687 $notice->selectAdd('id');
689 $notice->orderBy('created DESC, id DESC');
691 if (!is_null($offset)) {
692 $notice->limit($offset, $limit);
695 if (common_config('public', 'localonly')) {
696 $notice->whereAdd('is_local = ' . Notice::LOCAL_PUBLIC);
698 // -1 == blacklisted, -2 == gateway (i.e. Twitter)
699 $notice->whereAdd('is_local !='. Notice::LOCAL_NONPUBLIC);
700 $notice->whereAdd('is_local !='. Notice::GATEWAY);
703 Notice::addWhereSinceId($notice, $since_id);
704 Notice::addWhereMaxId($notice, $max_id);
708 if ($notice->find()) {
709 while ($notice->fetch()) {
710 $ids[] = $notice->id;
720 function conversationStream($id, $offset=0, $limit=20, $since_id=0, $max_id=0)
722 $ids = Notice::stream(array('Notice', '_conversationStreamDirect'),
724 'notice:conversation_ids:'.$id,
725 $offset, $limit, $since_id, $max_id);
727 return Notice::getStreamByIds($ids);
730 function _conversationStreamDirect($id, $offset=0, $limit=20, $since_id=0, $max_id=0)
732 $notice = new Notice();
734 $notice->selectAdd(); // clears it
735 $notice->selectAdd('id');
737 $notice->conversation = $id;
739 $notice->orderBy('created DESC, id DESC');
741 if (!is_null($offset)) {
742 $notice->limit($offset, $limit);
745 Notice::addWhereSinceId($notice, $since_id);
746 Notice::addWhereMaxId($notice, $max_id);
750 if ($notice->find()) {
751 while ($notice->fetch()) {
752 $ids[] = $notice->id;
763 * Is this notice part of an active conversation?
765 * @return boolean true if other messages exist in the same
766 * conversation, false if this is the only one
768 function hasConversation()
770 if (!empty($this->conversation)) {
771 $conversation = Notice::conversationStream(
777 if ($conversation->N > 0) {
785 * Grab the earliest notice from this conversation.
787 * @return Notice or null
789 function conversationRoot()
791 if (!empty($this->conversation)) {
792 $c = self::memcache();
794 $key = Cache::key('notice:conversation_root:' . $this->conversation);
795 $notice = $c->get($key);
800 $notice = new Notice();
801 $notice->conversation = $this->conversation;
802 $notice->orderBy('CREATED');
807 $c->set($key, $notice);
814 * Pull up a full list of local recipients who will be getting
815 * this notice in their inbox. Results will be cached, so don't
816 * change the input data wily-nilly!
818 * @param array $groups optional list of Group objects;
819 * if left empty, will be loaded from group_inbox records
820 * @param array $recipient optional list of reply profile ids
821 * if left empty, will be loaded from reply records
822 * @return array associating recipient user IDs with an inbox source constant
824 function whoGets($groups=null, $recipients=null)
826 $c = self::memcache();
829 $ni = $c->get(Cache::key('notice:who_gets:'.$this->id));
835 if (is_null($groups)) {
836 $groups = $this->getGroups();
839 if (is_null($recipients)) {
840 $recipients = $this->getReplies();
843 $users = $this->getSubscribedUsers();
845 // FIXME: kind of ignoring 'transitional'...
846 // we'll probably stop supporting inboxless mode
851 // Give plugins a chance to add folks in at start...
852 if (Event::handle('StartNoticeWhoGets', array($this, &$ni))) {
854 foreach ($users as $id) {
855 $ni[$id] = NOTICE_INBOX_SOURCE_SUB;
858 foreach ($groups as $group) {
859 $users = $group->getUserMembers();
860 foreach ($users as $id) {
861 if (!array_key_exists($id, $ni)) {
862 $ni[$id] = NOTICE_INBOX_SOURCE_GROUP;
867 foreach ($recipients as $recipient) {
868 if (!array_key_exists($recipient, $ni)) {
869 $ni[$recipient] = NOTICE_INBOX_SOURCE_REPLY;
873 // Exclude any deleted, non-local, or blocking recipients.
874 $profile = $this->getProfile();
875 $originalProfile = null;
876 if ($this->repeat_of) {
877 // Check blocks against the original notice's poster as well.
878 $original = Notice::staticGet('id', $this->repeat_of);
880 $originalProfile = $original->getProfile();
883 foreach ($ni as $id => $source) {
884 $user = User::staticGet('id', $id);
885 if (empty($user) || $user->hasBlocked($profile) ||
886 ($originalProfile && $user->hasBlocked($originalProfile))) {
891 // Give plugins a chance to filter out...
892 Event::handle('EndNoticeWhoGets', array($this, &$ni));
896 // XXX: pack this data better
897 $c->set(Cache::key('notice:who_gets:'.$this->id), $ni);
904 * Adds this notice to the inboxes of each local user who should receive
905 * it, based on author subscriptions, group memberships, and @-replies.
907 * Warning: running a second time currently will make items appear
908 * multiple times in users' inboxes.
910 * @fixme make more robust against errors
911 * @fixme break up massive deliveries to smaller background tasks
913 * @param array $groups optional list of Group objects;
914 * if left empty, will be loaded from group_inbox records
915 * @param array $recipient optional list of reply profile ids
916 * if left empty, will be loaded from reply records
918 function addToInboxes($groups=null, $recipients=null)
920 $ni = $this->whoGets($groups, $recipients);
922 $ids = array_keys($ni);
924 // We remove the author (if they're a local user),
925 // since we'll have already done this in distribute()
927 $i = array_search($this->profile_id, $ids);
935 Inbox::bulkInsert($this->id, $ids);
940 function getSubscribedUsers()
944 if(common_config('db','quote_identifiers'))
945 $user_table = '"user"';
946 else $user_table = 'user';
950 'FROM '. $user_table .' JOIN subscription '.
951 'ON '. $user_table .'.id = subscription.subscriber ' .
952 'WHERE subscription.subscribed = %d ';
954 $user->query(sprintf($qry, $this->profile_id));
958 while ($user->fetch()) {
968 * Record this notice to the given group inboxes for delivery.
969 * Overrides the regular parsing of !group markup.
971 * @param string $group_ids
972 * @fixme might prefer URIs as identifiers, as for replies?
973 * best with generalizations on user_group to support
974 * remote groups better.
976 function saveKnownGroups($group_ids)
978 if (!is_array($group_ids)) {
979 // TRANS: Server exception thrown when no array is provided to the method saveKnownGroups().
980 throw new ServerException(_('Bad type provided to saveKnownGroups.'));
984 foreach (array_unique($group_ids) as $id) {
985 $group = User_group::staticGet('id', $id);
987 common_log(LOG_ERR, "Local delivery to group id $id, $group->nickname");
988 $result = $this->addToGroupInbox($group);
990 common_log_db_error($gi, 'INSERT', __FILE__);
993 // @fixme should we save the tags here or not?
994 $groups[] = clone($group);
996 common_log(LOG_ERR, "Local delivery to group id $id skipped, doesn't exist");
1004 * Parse !group delivery and record targets into group_inbox.
1005 * @return array of Group objects
1007 function saveGroups()
1009 // Don't save groups for repeats
1011 if (!empty($this->repeat_of)) {
1017 /* extract all !group */
1018 $count = preg_match_all('/(?:^|\s)!(' . Nickname::DISPLAY_FMT . ')/',
1019 strtolower($this->content),
1025 $profile = $this->getProfile();
1027 /* Add them to the database */
1029 foreach (array_unique($match[1]) as $nickname) {
1030 /* XXX: remote groups. */
1031 $group = User_group::getForNickname($nickname, $profile);
1033 if (empty($group)) {
1037 // we automatically add a tag for every group name, too
1039 $tag = Notice_tag::pkeyGet(array('tag' => common_canonical_tag($nickname),
1040 'notice_id' => $this->id));
1042 if (is_null($tag)) {
1043 $this->saveTag($nickname);
1046 if ($profile->isMember($group)) {
1048 $result = $this->addToGroupInbox($group);
1051 common_log_db_error($gi, 'INSERT', __FILE__);
1054 $groups[] = clone($group);
1061 function addToGroupInbox($group)
1063 $gi = Group_inbox::pkeyGet(array('group_id' => $group->id,
1064 'notice_id' => $this->id));
1068 $gi = new Group_inbox();
1070 $gi->group_id = $group->id;
1071 $gi->notice_id = $this->id;
1072 $gi->created = $this->created;
1074 $result = $gi->insert();
1077 common_log_db_error($gi, 'INSERT', __FILE__);
1078 // TRANS: Server exception thrown when an update for a group inbox fails.
1079 throw new ServerException(_('Problem saving group inbox.'));
1082 self::blow('user_group:notice_ids:%d', $gi->group_id);
1089 * Save reply records indicating that this notice needs to be
1090 * delivered to the local users with the given URIs.
1092 * Since this is expected to be used when saving foreign-sourced
1093 * messages, we won't deliver to any remote targets as that's the
1094 * source service's responsibility.
1096 * Mail notifications etc will be handled later.
1098 * @param array of unique identifier URIs for recipients
1100 function saveKnownReplies($uris)
1106 $sender = Profile::staticGet($this->profile_id);
1108 foreach (array_unique($uris) as $uri) {
1110 $profile = Profile::fromURI($uri);
1112 if (empty($profile)) {
1113 common_log(LOG_WARNING, "Unable to determine profile for URI '$uri'");
1117 if ($profile->hasBlocked($sender)) {
1118 common_log(LOG_INFO, "Not saving reply to profile {$profile->id} ($uri) from sender {$sender->id} because of a block.");
1122 $reply = new Reply();
1124 $reply->notice_id = $this->id;
1125 $reply->profile_id = $profile->id;
1126 $reply->modified = $this->created;
1128 common_log(LOG_INFO, __METHOD__ . ": saving reply: notice $this->id to profile $profile->id");
1130 $id = $reply->insert();
1137 * Pull @-replies from this message's content in StatusNet markup format
1138 * and save reply records indicating that this message needs to be
1139 * delivered to those users.
1141 * Mail notifications to local profiles will be sent later.
1143 * @return array of integer profile IDs
1146 function saveReplies()
1148 // Don't save reply data for repeats
1150 if (!empty($this->repeat_of)) {
1154 $sender = Profile::staticGet($this->profile_id);
1156 // @todo ideally this parser information would only
1157 // be calculated once.
1159 $mentions = common_find_mentions($this->content, $this);
1163 // store replied only for first @ (what user/notice what the reply directed,
1164 // we assume first @ is it)
1166 foreach ($mentions as $mention) {
1168 foreach ($mention['mentioned'] as $mentioned) {
1170 // skip if they're already covered
1172 if (!empty($replied[$mentioned->id])) {
1176 // Don't save replies from blocked profile to local user
1178 $mentioned_user = User::staticGet('id', $mentioned->id);
1179 if (!empty($mentioned_user) && $mentioned_user->hasBlocked($sender)) {
1183 $reply = new Reply();
1185 $reply->notice_id = $this->id;
1186 $reply->profile_id = $mentioned->id;
1187 $reply->modified = $this->created;
1189 $id = $reply->insert();
1192 common_log_db_error($reply, 'INSERT', __FILE__);
1193 // TRANS: Server exception thrown when a reply cannot be saved.
1194 // TRANS: %1$d is a notice ID, %2$d is the ID of the mentioned user.
1195 throw new ServerException(sprintf(_('Could not save reply for %1$d, %2$d.'), $this->id, $mentioned->id));
1197 $replied[$mentioned->id] = 1;
1198 self::blow('reply:stream:%d', $mentioned->id);
1203 $recipientIds = array_keys($replied);
1205 return $recipientIds;
1209 * Pull the complete list of @-reply targets for this notice.
1211 * @return array of integer profile ids
1213 function getReplies()
1219 $reply = new Reply();
1220 $reply->selectAdd();
1221 $reply->selectAdd('profile_id');
1222 $reply->notice_id = $this->id;
1224 if ($reply->find()) {
1225 while($reply->fetch()) {
1226 $ids[] = $reply->profile_id;
1236 * Send e-mail notifications to local @-reply targets.
1238 * Replies must already have been saved; this is expected to be run
1239 * from the distrib queue handler.
1241 function sendReplyNotifications()
1243 // Don't send reply notifications for repeats
1245 if (!empty($this->repeat_of)) {
1249 $recipientIds = $this->getReplies();
1251 foreach ($recipientIds as $recipientId) {
1252 $user = User::staticGet('id', $recipientId);
1253 if (!empty($user)) {
1254 mail_notify_attn($user, $this);
1260 * Pull list of groups this notice needs to be delivered to,
1261 * as previously recorded by saveGroups() or saveKnownGroups().
1263 * @return array of Group objects
1265 function getGroups()
1267 // Don't save groups for repeats
1269 if (!empty($this->repeat_of)) {
1277 $gi = new Group_inbox();
1280 $gi->selectAdd('group_id');
1282 $gi->notice_id = $this->id;
1285 while ($gi->fetch()) {
1286 $group = User_group::staticGet('id', $gi->group_id);
1299 * Convert a notice into an activity for export.
1301 * @param User $cur Current user
1303 * @return Activity activity object representing this Notice.
1306 function asActivity($cur)
1308 $act = self::cacheGet(Cache::codeKey('notice:as-activity:'.$this->id));
1313 $act = new Activity();
1315 if (Event::handle('StartNoticeAsActivity', array($this, &$act))) {
1317 $profile = $this->getProfile();
1319 $act->actor = ActivityObject::fromProfile($profile);
1320 $act->actor->extra[] = $profile->profileInfo($cur);
1321 $act->verb = ActivityVerb::POST;
1322 $act->objects[] = ActivityObject::fromNotice($this);
1324 // XXX: should this be handled by default processing for object entry?
1326 $act->time = strtotime($this->created);
1327 $act->link = $this->bestUrl();
1329 $act->content = common_xml_safe_str($this->rendered);
1330 $act->id = $this->uri;
1331 $act->title = common_xml_safe_str($this->content);
1335 $tags = $this->getTags();
1337 foreach ($tags as $tag) {
1338 $cat = new AtomCategory();
1341 $act->categories[] = $cat;
1345 // XXX: use Atom Media and/or File activity objects instead
1347 $attachments = $this->attachments();
1349 foreach ($attachments as $attachment) {
1350 $enclosure = $attachment->getEnclosure();
1352 $act->enclosures[] = $enclosure;
1356 $ctx = new ActivityContext();
1358 if (!empty($this->reply_to)) {
1359 $reply = Notice::staticGet('id', $this->reply_to);
1360 if (!empty($reply)) {
1361 $ctx->replyToID = $reply->uri;
1362 $ctx->replyToUrl = $reply->bestUrl();
1366 $ctx->location = $this->getLocation();
1370 if (!empty($this->conversation)) {
1371 $conv = Conversation::staticGet('id', $this->conversation);
1372 if (!empty($conv)) {
1373 $ctx->conversation = $conv->uri;
1377 $reply_ids = $this->getReplies();
1379 foreach ($reply_ids as $id) {
1380 $profile = Profile::staticGet('id', $id);
1381 if (!empty($profile)) {
1382 $ctx->attention[] = $profile->getUri();
1386 $groups = $this->getGroups();
1388 foreach ($groups as $group) {
1389 $ctx->attention[] = $group->getUri();
1392 // XXX: deprecated; use ActivityVerb::SHARE instead
1396 if (!empty($this->repeat_of)) {
1397 $repeat = Notice::staticGet('id', $this->repeat_of);
1398 $ctx->forwardID = $repeat->uri;
1399 $ctx->forwardUrl = $repeat->bestUrl();
1402 $act->context = $ctx;
1406 $atom_feed = $profile->getAtomFeed();
1408 if (!empty($atom_feed)) {
1410 $act->source = new ActivitySource();
1412 // XXX: we should store the actual feed ID
1414 $act->source->id = $atom_feed;
1416 // XXX: we should store the actual feed title
1418 $act->source->title = $profile->getBestName();
1420 $act->source->links['alternate'] = $profile->profileurl;
1421 $act->source->links['self'] = $atom_feed;
1423 $act->source->icon = $profile->avatarUrl(AVATAR_PROFILE_SIZE);
1425 $notice = $profile->getCurrentNotice();
1427 if (!empty($notice)) {
1428 $act->source->updated = self::utcDate($notice->created);
1431 $user = User::staticGet('id', $profile->id);
1433 if (!empty($user)) {
1434 $act->source->links['license'] = common_config('license', 'url');
1438 if ($this->isLocal()) {
1439 $act->selfLink = common_local_url('ApiStatusesShow', array('id' => $this->id,
1440 'format' => 'atom'));
1441 $act->editLink = $act->selfLink;
1444 Event::handle('EndNoticeAsActivity', array($this, &$act));
1447 self::cacheSet(Cache::codeKey('notice:as-activity:'.$this->id), $act);
1452 // This has gotten way too long. Needs to be sliced up into functional bits
1453 // or ideally exported to a utility class.
1455 function asAtomEntry($namespace=false,
1460 $act = $this->asActivity($cur);
1461 $act->extra[] = $this->noticeInfo($cur);
1462 return $act->asString($namespace, $author, $source);
1466 * Extra notice info for atom entries
1468 * Clients use some extra notice info in the atom stream.
1469 * This gives it to them.
1471 * @param User $cur Current user
1473 * @return array representation of <statusnet:notice_info> element
1476 function noticeInfo($cur)
1478 // local notice ID (useful to clients for ordering)
1480 $noticeInfoAttr = array('local_id' => $this->id);
1484 $ns = $this->getSource();
1487 $noticeInfoAttr['source'] = $ns->code;
1488 if (!empty($ns->url)) {
1489 $noticeInfoAttr['source_link'] = $ns->url;
1490 if (!empty($ns->name)) {
1491 $noticeInfoAttr['source'] = '<a href="'
1492 . htmlspecialchars($ns->url)
1493 . '" rel="nofollow">'
1494 . htmlspecialchars($ns->name)
1500 // favorite and repeated
1503 $noticeInfoAttr['favorite'] = ($cur->hasFave($this)) ? "true" : "false";
1504 $cp = $cur->getProfile();
1505 $noticeInfoAttr['repeated'] = ($cp->hasRepeated($this->id)) ? "true" : "false";
1508 if (!empty($this->repeat_of)) {
1509 $noticeInfoAttr['repeat_of'] = $this->repeat_of;
1512 return array('statusnet:notice_info', $noticeInfoAttr, null);
1516 * Returns an XML string fragment with a reference to a notice as an
1517 * Activity Streams noun object with the given element type.
1519 * Assumes that 'activity' namespace has been previously defined.
1521 * @param string $element one of 'subject', 'object', 'target'
1525 function asActivityNoun($element)
1527 $noun = ActivityObject::fromNotice($this);
1528 return $noun->asString('activity:' . $element);
1533 if (!empty($this->url)) {
1535 } else if (!empty($this->uri) && preg_match('/^https?:/', $this->uri)) {
1538 return common_local_url('shownotice',
1539 array('notice' => $this->id));
1543 function stream($fn, $args, $cachekey, $offset=0, $limit=20, $since_id=0, $max_id=0)
1545 $cache = Cache::instance();
1547 if (empty($cache) ||
1548 $since_id != 0 || $max_id != 0 ||
1550 ($offset + $limit) > NOTICE_CACHE_WINDOW) {
1551 return call_user_func_array($fn, array_merge($args, array($offset, $limit, $since_id,
1555 $idkey = Cache::key($cachekey);
1557 $idstr = $cache->get($idkey);
1559 if ($idstr !== false) {
1560 // Cache hit! Woohoo!
1561 $window = explode(',', $idstr);
1562 $ids = array_slice($window, $offset, $limit);
1566 $laststr = $cache->get($idkey.';last');
1568 if ($laststr !== false) {
1569 $window = explode(',', $laststr);
1570 $last_id = $window[0];
1571 $new_ids = call_user_func_array($fn, array_merge($args, array(0, NOTICE_CACHE_WINDOW,
1572 $last_id, 0, null)));
1574 $new_window = array_merge($new_ids, $window);
1576 $new_windowstr = implode(',', $new_window);
1578 $result = $cache->set($idkey, $new_windowstr);
1579 $result = $cache->set($idkey . ';last', $new_windowstr);
1581 $ids = array_slice($new_window, $offset, $limit);
1586 $window = call_user_func_array($fn, array_merge($args, array(0, NOTICE_CACHE_WINDOW,
1589 $windowstr = implode(',', $window);
1591 $result = $cache->set($idkey, $windowstr);
1592 $result = $cache->set($idkey . ';last', $windowstr);
1594 $ids = array_slice($window, $offset, $limit);
1600 * Determine which notice, if any, a new notice is in reply to.
1602 * For conversation tracking, we try to see where this notice fits
1603 * in the tree. Rough algorithm is:
1605 * if (reply_to is set and valid) {
1607 * } else if ((source not API or Web) and (content starts with "T NAME" or "@name ")) {
1608 * return ID of last notice by initial @name in content;
1611 * Note that all @nickname instances will still be used to save "reply" records,
1612 * so the notice shows up in the mentioned users' "replies" tab.
1614 * @param integer $reply_to ID passed in by Web or API
1615 * @param integer $profile_id ID of author
1616 * @param string $source Source tag, like 'web' or 'gwibber'
1617 * @param string $content Final notice content
1619 * @return integer ID of replied-to notice, or null for not a reply.
1622 static function getReplyTo($reply_to, $profile_id, $source, $content)
1624 static $lb = array('xmpp', 'mail', 'sms', 'omb');
1626 // If $reply_to is specified, we check that it exists, and then
1627 // return it if it does
1629 if (!empty($reply_to)) {
1630 $reply_notice = Notice::staticGet('id', $reply_to);
1631 if (!empty($reply_notice)) {
1636 // If it's not a "low bandwidth" source (one where you can't set
1637 // a reply_to argument), we return. This is mostly web and API
1640 if (!in_array($source, $lb)) {
1644 // Is there an initial @ or T?
1646 if (preg_match('/^T ([A-Z0-9]{1,64}) /', $content, $match) ||
1647 preg_match('/^@([a-z0-9]{1,64})\s+/', $content, $match)) {
1648 $nickname = common_canonical_nickname($match[1]);
1653 // Figure out who that is.
1655 $sender = Profile::staticGet('id', $profile_id);
1656 if (empty($sender)) {
1660 $recipient = common_relative_profile($sender, $nickname, common_sql_now());
1662 if (empty($recipient)) {
1666 // Get their last notice
1668 $last = $recipient->getCurrentNotice();
1670 if (!empty($last)) {
1675 static function maxContent()
1677 $contentlimit = common_config('notice', 'contentlimit');
1678 // null => use global limit (distinct from 0!)
1679 if (is_null($contentlimit)) {
1680 $contentlimit = common_config('site', 'textlimit');
1682 return $contentlimit;
1685 static function contentTooLong($content)
1687 $contentlimit = self::maxContent();
1688 return ($contentlimit > 0 && !empty($content) && (mb_strlen($content) > $contentlimit));
1691 function getLocation()
1695 if (!empty($this->location_id) && !empty($this->location_ns)) {
1696 $location = Location::fromId($this->location_id, $this->location_ns);
1699 if (is_null($location)) { // no ID, or Location::fromId() failed
1700 if (!empty($this->lat) && !empty($this->lon)) {
1701 $location = Location::fromLatLon($this->lat, $this->lon);
1708 function repeat($repeater_id, $source)
1710 $author = Profile::staticGet('id', $this->profile_id);
1712 // TRANS: Message used to repeat a notice. RT is the abbreviation of 'retweet'.
1713 // TRANS: %1$s is the repeated user's name, %2$s is the repeated notice.
1714 $content = sprintf(_('RT @%1$s %2$s'),
1718 $maxlen = common_config('site', 'textlimit');
1719 if ($maxlen > 0 && mb_strlen($content) > $maxlen) {
1720 // Web interface and current Twitter API clients will
1721 // pull the original notice's text, but some older
1722 // clients and RSS/Atom feeds will see this trimmed text.
1724 // Unfortunately this is likely to lose tags or URLs
1725 // at the end of long notices.
1726 $content = mb_substr($content, 0, $maxlen - 4) . ' ...';
1729 return self::saveNew($repeater_id, $content, $source,
1730 array('repeat_of' => $this->id));
1733 // These are supposed to be in chron order!
1735 function repeatStream($limit=100)
1737 $cache = Cache::instance();
1739 if (empty($cache)) {
1740 $ids = $this->_repeatStreamDirect($limit);
1742 $idstr = $cache->get(Cache::key('notice:repeats:'.$this->id));
1743 if ($idstr !== false) {
1744 $ids = explode(',', $idstr);
1746 $ids = $this->_repeatStreamDirect(100);
1747 $cache->set(Cache::key('notice:repeats:'.$this->id), implode(',', $ids));
1750 // We do a max of 100, so slice down to limit
1751 $ids = array_slice($ids, 0, $limit);
1755 return Notice::getStreamByIds($ids);
1758 function _repeatStreamDirect($limit)
1760 $notice = new Notice();
1762 $notice->selectAdd(); // clears it
1763 $notice->selectAdd('id');
1765 $notice->repeat_of = $this->id;
1767 $notice->orderBy('created, id'); // NB: asc!
1769 if (!is_null($limit)) {
1770 $notice->limit(0, $limit);
1775 if ($notice->find()) {
1776 while ($notice->fetch()) {
1777 $ids[] = $notice->id;
1787 function locationOptions($lat, $lon, $location_id, $location_ns, $profile = null)
1791 if (!empty($location_id) && !empty($location_ns)) {
1792 $options['location_id'] = $location_id;
1793 $options['location_ns'] = $location_ns;
1795 $location = Location::fromId($location_id, $location_ns);
1797 if (!empty($location)) {
1798 $options['lat'] = $location->lat;
1799 $options['lon'] = $location->lon;
1802 } else if (!empty($lat) && !empty($lon)) {
1803 $options['lat'] = $lat;
1804 $options['lon'] = $lon;
1806 $location = Location::fromLatLon($lat, $lon);
1808 if (!empty($location)) {
1809 $options['location_id'] = $location->location_id;
1810 $options['location_ns'] = $location->location_ns;
1812 } else if (!empty($profile)) {
1813 if (isset($profile->lat) && isset($profile->lon)) {
1814 $options['lat'] = $profile->lat;
1815 $options['lon'] = $profile->lon;
1818 if (isset($profile->location_id) && isset($profile->location_ns)) {
1819 $options['location_id'] = $profile->location_id;
1820 $options['location_ns'] = $profile->location_ns;
1827 function clearReplies()
1829 $replyNotice = new Notice();
1830 $replyNotice->reply_to = $this->id;
1832 //Null any notices that are replies to this notice
1834 if ($replyNotice->find()) {
1835 while ($replyNotice->fetch()) {
1836 $orig = clone($replyNotice);
1837 $replyNotice->reply_to = null;
1838 $replyNotice->update($orig);
1844 $reply = new Reply();
1845 $reply->notice_id = $this->id;
1847 if ($reply->find()) {
1848 while($reply->fetch()) {
1849 self::blow('reply:stream:%d', $reply->profile_id);
1857 function clearFiles()
1859 $f2p = new File_to_post();
1861 $f2p->post_id = $this->id;
1864 while ($f2p->fetch()) {
1868 // FIXME: decide whether to delete File objects
1869 // ...and related (actual) files
1872 function clearRepeats()
1874 $repeatNotice = new Notice();
1875 $repeatNotice->repeat_of = $this->id;
1877 //Null any notices that are repeats of this notice
1879 if ($repeatNotice->find()) {
1880 while ($repeatNotice->fetch()) {
1881 $orig = clone($repeatNotice);
1882 $repeatNotice->repeat_of = null;
1883 $repeatNotice->update($orig);
1888 function clearFaves()
1891 $fave->notice_id = $this->id;
1893 if ($fave->find()) {
1894 while ($fave->fetch()) {
1895 self::blow('fave:ids_by_user_own:%d', $fave->user_id);
1896 self::blow('fave:ids_by_user_own:%d;last', $fave->user_id);
1897 self::blow('fave:ids_by_user:%d', $fave->user_id);
1898 self::blow('fave:ids_by_user:%d;last', $fave->user_id);
1906 function clearTags()
1908 $tag = new Notice_tag();
1909 $tag->notice_id = $this->id;
1912 while ($tag->fetch()) {
1913 self::blow('profile:notice_ids_tagged:%d:%s', $this->profile_id, Cache::keyize($tag->tag));
1914 self::blow('profile:notice_ids_tagged:%d:%s;last', $this->profile_id, Cache::keyize($tag->tag));
1915 self::blow('notice_tag:notice_ids:%s', Cache::keyize($tag->tag));
1916 self::blow('notice_tag:notice_ids:%s;last', Cache::keyize($tag->tag));
1924 function clearGroupInboxes()
1926 $gi = new Group_inbox();
1928 $gi->notice_id = $this->id;
1931 while ($gi->fetch()) {
1932 self::blow('user_group:notice_ids:%d', $gi->group_id);
1940 function distribute()
1942 // We always insert for the author so they don't
1944 Event::handle('StartNoticeDistribute', array($this));
1946 $user = User::staticGet('id', $this->profile_id);
1947 if (!empty($user)) {
1948 Inbox::insertNotice($user->id, $this->id);
1951 if (common_config('queue', 'inboxes')) {
1952 // If there's a failure, we want to _force_
1953 // distribution at this point.
1955 $qm = QueueManager::get();
1956 $qm->enqueue($this, 'distrib');
1957 } catch (Exception $e) {
1958 // If the exception isn't transient, this
1959 // may throw more exceptions as DQH does
1960 // its own enqueueing. So, we ignore them!
1962 $handler = new DistribQueueHandler();
1963 $handler->handle($this);
1964 } catch (Exception $e) {
1965 common_log(LOG_ERR, "emergency redistribution resulted in " . $e->getMessage());
1967 // Re-throw so somebody smarter can handle it.
1971 $handler = new DistribQueueHandler();
1972 $handler->handle($this);
1978 $result = parent::insert();
1981 // Profile::hasRepeated() abuses pkeyGet(), so we
1982 // have to clear manually
1983 if (!empty($this->repeat_of)) {
1984 $c = self::memcache();
1986 $ck = self::multicacheKey('Notice',
1987 array('profile_id' => $this->profile_id,
1988 'repeat_of' => $this->repeat_of));
1998 * Get the source of the notice
2000 * @return Notice_source $ns A notice source object. 'code' is the only attribute
2001 * guaranteed to be populated.
2003 function getSource()
2005 $ns = new Notice_source();
2006 if (!empty($this->source)) {
2007 switch ($this->source) {
2014 $ns->code = $this->source;
2017 $ns = Notice_source::staticGet($this->source);
2019 $ns = new Notice_source();
2020 $ns->code = $this->source;
2021 $app = Oauth_application::staticGet('name', $this->source);
2023 $ns->name = $app->name;
2024 $ns->url = $app->source_url;
2034 * Determine whether the notice was locally created
2036 * @return boolean locality
2039 public function isLocal()
2041 return ($this->is_local == Notice::LOCAL_PUBLIC ||
2042 $this->is_local == Notice::LOCAL_NONPUBLIC);
2046 * Get the list of hash tags saved with this notice.
2048 * @return array of strings
2050 public function getTags()
2053 $tag = new Notice_tag();
2054 $tag->notice_id = $this->id;
2056 while ($tag->fetch()) {
2057 $tags[] = $tag->tag;
2064 static private function utcDate($dt)
2066 $dateStr = date('d F Y H:i:s', strtotime($dt));
2067 $d = new DateTime($dateStr, new DateTimeZone('UTC'));
2068 return $d->format(DATE_W3C);
2072 * Look up the creation timestamp for a given notice ID, even
2073 * if it's been deleted.
2076 * @return mixed string recorded creation timestamp, or false if can't be found
2078 public static function getAsTimestamp($id)
2084 $notice = Notice::staticGet('id', $id);
2086 return $notice->created;
2089 $deleted = Deleted_notice::staticGet('id', $id);
2091 return $deleted->created;
2098 * Build an SQL 'where' fragment for timestamp-based sorting from a since_id
2099 * parameter, matching notices posted after the given one (exclusive).
2101 * If the referenced notice can't be found, will return false.
2104 * @param string $idField
2105 * @param string $createdField
2106 * @return mixed string or false if no match
2108 public static function whereSinceId($id, $idField='id', $createdField='created')
2110 $since = Notice::getAsTimestamp($id);
2112 return sprintf("($createdField = '%s' and $idField > %d) or ($createdField > '%s')", $since, $id, $since);
2118 * Build an SQL 'where' fragment for timestamp-based sorting from a since_id
2119 * parameter, matching notices posted after the given one (exclusive), and
2120 * if necessary add it to the data object's query.
2122 * @param DB_DataObject $obj
2124 * @param string $idField
2125 * @param string $createdField
2126 * @return mixed string or false if no match
2128 public static function addWhereSinceId(DB_DataObject $obj, $id, $idField='id', $createdField='created')
2130 $since = self::whereSinceId($id, $idField, $createdField);
2132 $obj->whereAdd($since);
2137 * Build an SQL 'where' fragment for timestamp-based sorting from a max_id
2138 * parameter, matching notices posted before the given one (inclusive).
2140 * If the referenced notice can't be found, will return false.
2143 * @param string $idField
2144 * @param string $createdField
2145 * @return mixed string or false if no match
2147 public static function whereMaxId($id, $idField='id', $createdField='created')
2149 $max = Notice::getAsTimestamp($id);
2151 return sprintf("($createdField < '%s') or ($createdField = '%s' and $idField <= %d)", $max, $max, $id);
2157 * Build an SQL 'where' fragment for timestamp-based sorting from a max_id
2158 * parameter, matching notices posted before the given one (inclusive), and
2159 * if necessary add it to the data object's query.
2161 * @param DB_DataObject $obj
2163 * @param string $idField
2164 * @param string $createdField
2165 * @return mixed string or false if no match
2167 public static function addWhereMaxId(DB_DataObject $obj, $id, $idField='id', $createdField='created')
2169 $max = self::whereMaxId($id, $idField, $createdField);
2171 $obj->whereAdd($max);
2177 if (common_config('public', 'localonly')) {
2178 return ($this->is_local == Notice::LOCAL_PUBLIC);
2180 return (($this->is_local != Notice::LOCAL_NONPUBLIC) &&
2181 ($this->is_local != Notice::GATEWAY));