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();
440 if (isset($peopletags)) {
441 $notice->saveProfileTags($peopletags);
443 $notice->saveProfileTags();
447 $notice->saveKnownUrls($urls);
453 // Prepare inbox delivery, may be queued to background.
454 $notice->distribute();
460 function blowOnInsert($conversation = false)
462 self::blow('profile:notice_ids:%d', $this->profile_id);
464 if ($this->isPublic()) {
465 self::blow('public');
468 // XXX: Before we were blowing the casche only if the notice id
469 // was not the root of the conversation. What to do now?
471 self::blow('notice:conversation_ids:%d', $this->conversation);
473 if (!empty($this->repeat_of)) {
474 self::blow('notice:repeats:%d', $this->repeat_of);
477 $original = Notice::staticGet('id', $this->repeat_of);
479 if (!empty($original)) {
480 $originalUser = User::staticGet('id', $original->profile_id);
481 if (!empty($originalUser)) {
482 self::blow('user:repeats_of_me:%d', $originalUser->id);
486 $profile = Profile::staticGet($this->profile_id);
487 if (!empty($profile)) {
488 $profile->blowNoticeCount();
493 * Clear cache entries related to this notice at delete time.
494 * Necessary to avoid breaking paging on public, profile timelines.
496 function blowOnDelete()
498 $this->blowOnInsert();
500 self::blow('profile:notice_ids:%d;last', $this->profile_id);
502 if ($this->isPublic()) {
503 self::blow('public;last');
506 self::blow('fave:by_notice', $this->id);
508 if ($this->conversation) {
509 // In case we're the first, will need to calc a new root.
510 self::blow('notice:conversation_root:%d', $this->conversation);
514 /** save all urls in the notice to the db
516 * follow redirects and save all available file information
517 * (mimetype, date, size, oembed, etc.)
521 function saveUrls() {
522 if (common_config('attachments', 'process_links')) {
523 common_replace_urls_callback($this->content, array($this, 'saveUrl'), $this->id);
528 * Save the given URLs as related links/attachments to the db
530 * follow redirects and save all available file information
531 * (mimetype, date, size, oembed, etc.)
535 function saveKnownUrls($urls)
537 if (common_config('attachments', 'process_links')) {
538 // @fixme validation?
539 foreach (array_unique($urls) as $url) {
540 File::processNew($url, $this->id);
548 function saveUrl($url, $notice_id) {
549 File::processNew($url, $notice_id);
552 static function checkDupes($profile_id, $content) {
553 $profile = Profile::staticGet($profile_id);
554 if (empty($profile)) {
557 $notice = $profile->getNotices(0, NOTICE_CACHE_WINDOW);
558 if (!empty($notice)) {
560 while ($notice->fetch()) {
561 if (time() - strtotime($notice->created) >= common_config('site', 'dupelimit')) {
563 } else if ($notice->content == $content) {
568 # If we get here, oldest item in cache window is not
569 # old enough for dupe limit; do direct check against DB
570 $notice = new Notice();
571 $notice->profile_id = $profile_id;
572 $notice->content = $content;
573 $threshold = common_sql_date(time() - common_config('site', 'dupelimit'));
574 $notice->whereAdd(sprintf("created > '%s'", $notice->escape($threshold)));
576 $cnt = $notice->count();
580 static function checkEditThrottle($profile_id) {
581 $profile = Profile::staticGet($profile_id);
582 if (empty($profile)) {
586 $notice = $profile->getNotices(common_config('throttle', 'count') - 1, 1);
587 if ($notice && $notice->fetch()) {
588 # If the Nth notice was posted less than timespan seconds ago
589 if (time() - strtotime($notice->created) <= common_config('throttle', 'timespan')) {
594 # Either not N notices in the stream, OR the Nth was not posted within timespan seconds
598 function getUploadedAttachment() {
600 $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"';
601 $post->query($query);
603 if (empty($post->up) || empty($post->i)) {
606 $ret = array($post->up, $post->i);
612 function hasAttachments() {
614 $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);
615 $post->query($query);
617 $n_attachments = intval($post->n_attachments);
619 return $n_attachments;
622 function attachments() {
625 $f2p = new File_to_post;
626 $f2p->post_id = $this->id;
628 while ($f2p->fetch()) {
629 $f = File::staticGet($f2p->file_id);
638 function getStreamByIds($ids)
640 $cache = Cache::instance();
642 if (!empty($cache)) {
644 foreach ($ids as $id) {
645 $n = Notice::staticGet('id', $id);
650 return new ArrayWrapper($notices);
652 $notice = new Notice();
654 //if no IDs requested, just return the notice object
657 $notice->whereAdd('id in (' . implode(', ', $ids) . ')');
663 while ($notice->fetch()) {
664 $temp[$notice->id] = clone($notice);
669 foreach ($ids as $id) {
670 if (array_key_exists($id, $temp)) {
671 $wrapped[] = $temp[$id];
675 return new ArrayWrapper($wrapped);
679 function publicStream($offset=0, $limit=20, $since_id=0, $max_id=0)
681 $ids = Notice::stream(array('Notice', '_publicStreamDirect'),
684 $offset, $limit, $since_id, $max_id);
685 return Notice::getStreamByIds($ids);
688 function _publicStreamDirect($offset=0, $limit=20, $since_id=0, $max_id=0)
690 $notice = new Notice();
692 $notice->selectAdd(); // clears it
693 $notice->selectAdd('id');
695 $notice->orderBy('created DESC, id DESC');
697 if (!is_null($offset)) {
698 $notice->limit($offset, $limit);
701 if (common_config('public', 'localonly')) {
702 $notice->whereAdd('is_local = ' . Notice::LOCAL_PUBLIC);
704 # -1 == blacklisted, -2 == gateway (i.e. Twitter)
705 $notice->whereAdd('is_local !='. Notice::LOCAL_NONPUBLIC);
706 $notice->whereAdd('is_local !='. Notice::GATEWAY);
709 Notice::addWhereSinceId($notice, $since_id);
710 Notice::addWhereMaxId($notice, $max_id);
714 if ($notice->find()) {
715 while ($notice->fetch()) {
716 $ids[] = $notice->id;
726 function conversationStream($id, $offset=0, $limit=20, $since_id=0, $max_id=0)
728 $ids = Notice::stream(array('Notice', '_conversationStreamDirect'),
730 'notice:conversation_ids:'.$id,
731 $offset, $limit, $since_id, $max_id);
733 return Notice::getStreamByIds($ids);
736 function _conversationStreamDirect($id, $offset=0, $limit=20, $since_id=0, $max_id=0)
738 $notice = new Notice();
740 $notice->selectAdd(); // clears it
741 $notice->selectAdd('id');
743 $notice->conversation = $id;
745 $notice->orderBy('created DESC, id DESC');
747 if (!is_null($offset)) {
748 $notice->limit($offset, $limit);
751 Notice::addWhereSinceId($notice, $since_id);
752 Notice::addWhereMaxId($notice, $max_id);
756 if ($notice->find()) {
757 while ($notice->fetch()) {
758 $ids[] = $notice->id;
769 * Is this notice part of an active conversation?
771 * @return boolean true if other messages exist in the same
772 * conversation, false if this is the only one
774 function hasConversation()
776 if (!empty($this->conversation)) {
777 $conversation = Notice::conversationStream(
783 if ($conversation->N > 0) {
791 * Grab the earliest notice from this conversation.
793 * @return Notice or null
795 function conversationRoot()
797 if (!empty($this->conversation)) {
798 $c = self::memcache();
800 $key = Cache::key('notice:conversation_root:' . $this->conversation);
801 $notice = $c->get($key);
806 $notice = new Notice();
807 $notice->conversation = $this->conversation;
808 $notice->orderBy('CREATED');
813 $c->set($key, $notice);
820 * Pull up a full list of local recipients who will be getting
821 * this notice in their inbox. Results will be cached, so don't
822 * change the input data wily-nilly!
824 * @param array $groups optional list of Group objects;
825 * if left empty, will be loaded from group_inbox records
826 * @param array $recipient optional list of reply profile ids
827 * if left empty, will be loaded from reply records
828 * @return array associating recipient user IDs with an inbox source constant
830 function whoGets($groups=null, $recipients=null)
832 $c = self::memcache();
835 $ni = $c->get(Cache::key('notice:who_gets:'.$this->id));
841 if (is_null($groups)) {
842 $groups = $this->getGroups();
845 if (is_null($recipients)) {
846 $recipients = $this->getReplies();
849 $users = $this->getSubscribedUsers();
850 $ptags = $this->getProfileTags();
852 // FIXME: kind of ignoring 'transitional'...
853 // we'll probably stop supporting inboxless mode
858 // Give plugins a chance to add folks in at start...
859 if (Event::handle('StartNoticeWhoGets', array($this, &$ni))) {
861 foreach ($users as $id) {
862 $ni[$id] = NOTICE_INBOX_SOURCE_SUB;
865 foreach ($groups as $group) {
866 $users = $group->getUserMembers();
867 foreach ($users as $id) {
868 if (!array_key_exists($id, $ni)) {
869 $ni[$id] = NOTICE_INBOX_SOURCE_GROUP;
874 foreach ($ptags as $ptag) {
875 $users = $ptag->getUserSubscribers();
876 foreach ($users as $id) {
877 if (!array_key_exists($id, $ni)) {
878 $user = User::staticGet('id', $id);
879 if (!$user->hasBlocked($profile)) {
880 $ni[$id] = NOTICE_INBOX_SOURCE_PROFILE_TAG;
886 foreach ($recipients as $recipient) {
887 if (!array_key_exists($recipient, $ni)) {
888 $ni[$recipient] = NOTICE_INBOX_SOURCE_REPLY;
891 // Exclude any deleted, non-local, or blocking recipients.
892 $profile = $this->getProfile();
893 $originalProfile = null;
894 if ($this->repeat_of) {
895 // Check blocks against the original notice's poster as well.
896 $original = Notice::staticGet('id', $this->repeat_of);
898 $originalProfile = $original->getProfile();
901 foreach ($ni as $id => $source) {
902 $user = User::staticGet('id', $id);
903 if (empty($user) || $user->hasBlocked($profile) ||
904 ($originalProfile && $user->hasBlocked($originalProfile))) {
910 // Give plugins a chance to filter out...
911 Event::handle('EndNoticeWhoGets', array($this, &$ni));
915 // XXX: pack this data better
916 $c->set(Cache::key('notice:who_gets:'.$this->id), $ni);
923 * Adds this notice to the inboxes of each local user who should receive
924 * it, based on author subscriptions, group memberships, and @-replies.
926 * Warning: running a second time currently will make items appear
927 * multiple times in users' inboxes.
929 * @fixme make more robust against errors
930 * @fixme break up massive deliveries to smaller background tasks
932 * @param array $groups optional list of Group objects;
933 * if left empty, will be loaded from group_inbox records
934 * @param array $recipient optional list of reply profile ids
935 * if left empty, will be loaded from reply records
937 function addToInboxes($groups=null, $recipients=null)
939 $ni = $this->whoGets($groups, $recipients);
941 $ids = array_keys($ni);
943 // We remove the author (if they're a local user),
944 // since we'll have already done this in distribute()
946 $i = array_search($this->profile_id, $ids);
954 Inbox::bulkInsert($this->id, $ids);
959 function getSubscribedUsers()
963 if(common_config('db','quote_identifiers'))
964 $user_table = '"user"';
965 else $user_table = 'user';
969 'FROM '. $user_table .' JOIN subscription '.
970 'ON '. $user_table .'.id = subscription.subscriber ' .
971 'WHERE subscription.subscribed = %d ';
973 $user->query(sprintf($qry, $this->profile_id));
977 while ($user->fetch()) {
986 function getProfileTags()
988 // Don't save ptags for repeats, for now.
990 if (!empty($this->repeat_of)) {
998 $ptagi = new Profile_tag_inbox();
1000 $ptagi->selectAdd();
1001 $ptagi->selectAdd('profile_tag_id');
1003 $ptagi->notice_id = $this->id;
1005 if ($ptagi->find()) {
1006 while ($ptagi->fetch()) {
1007 $profile_list = Profile_list::staticGet('id', $ptagi->profile_tag_id);
1008 if ($profile_list) {
1009 $ptags[] = $profile_list;
1020 * Record this notice to the given group inboxes for delivery.
1021 * Overrides the regular parsing of !group markup.
1023 * @param string $group_ids
1024 * @fixme might prefer URIs as identifiers, as for replies?
1025 * best with generalizations on user_group to support
1026 * remote groups better.
1028 function saveKnownGroups($group_ids)
1030 if (!is_array($group_ids)) {
1031 // TRANS: Server exception thrown when no array is provided to the method saveKnownGroups().
1032 throw new ServerException(_('Bad type provided to saveKnownGroups.'));
1036 foreach (array_unique($group_ids) as $id) {
1037 $group = User_group::staticGet('id', $id);
1039 common_log(LOG_ERR, "Local delivery to group id $id, $group->nickname");
1040 $result = $this->addToGroupInbox($group);
1042 common_log_db_error($gi, 'INSERT', __FILE__);
1045 // @fixme should we save the tags here or not?
1046 $groups[] = clone($group);
1048 common_log(LOG_ERR, "Local delivery to group id $id skipped, doesn't exist");
1056 * Parse !group delivery and record targets into group_inbox.
1057 * @return array of Group objects
1059 function saveGroups()
1061 // Don't save groups for repeats
1063 if (!empty($this->repeat_of)) {
1069 /* extract all !group */
1070 $count = preg_match_all('/(?:^|\s)!(' . Nickname::DISPLAY_FMT . ')/',
1071 strtolower($this->content),
1077 $profile = $this->getProfile();
1079 /* Add them to the database */
1081 foreach (array_unique($match[1]) as $nickname) {
1082 /* XXX: remote groups. */
1083 $group = User_group::getForNickname($nickname, $profile);
1085 if (empty($group)) {
1089 // we automatically add a tag for every group name, too
1091 $tag = Notice_tag::pkeyGet(array('tag' => common_canonical_tag($nickname),
1092 'notice_id' => $this->id));
1094 if (is_null($tag)) {
1095 $this->saveTag($nickname);
1098 if ($profile->isMember($group)) {
1100 $result = $this->addToGroupInbox($group);
1103 common_log_db_error($gi, 'INSERT', __FILE__);
1106 $groups[] = clone($group);
1113 function addToGroupInbox($group)
1115 $gi = Group_inbox::pkeyGet(array('group_id' => $group->id,
1116 'notice_id' => $this->id));
1120 $gi = new Group_inbox();
1122 $gi->group_id = $group->id;
1123 $gi->notice_id = $this->id;
1124 $gi->created = $this->created;
1126 $result = $gi->insert();
1129 common_log_db_error($gi, 'INSERT', __FILE__);
1130 // TRANS: Server exception thrown when an update for a group inbox fails.
1131 throw new ServerException(_('Problem saving group inbox.'));
1134 self::blow('user_group:notice_ids:%d', $gi->group_id);
1141 * record targets into profile_tag_inbox.
1142 * @return array of Profile_list objects
1144 function saveProfileTags($known=array())
1146 // Don't save ptags for repeats, for now
1148 if (!empty($this->repeat_of)) {
1152 if (is_array($known)) {
1158 $ptag = new Profile_tag();
1159 $ptag->tagged = $this->profile_id;
1162 while($ptag->fetch()) {
1163 $plist = Profile_list::getByTaggerAndTag($ptag->tagger, $ptag->tag);
1164 $ptags[] = clone($plist);
1168 foreach ($ptags as $target) {
1169 $this->addToProfileTagInbox($target);
1175 function addToProfileTagInbox($plist)
1177 $ptagi = Profile_tag_inbox::pkeyGet(array('profile_tag_id' => $plist->id,
1178 'notice_id' => $this->id));
1180 if (empty($ptagi)) {
1182 $ptagi = new Profile_tag_inbox();
1184 $ptagi->query('BEGIN');
1185 $ptagi->profile_tag_id = $plist->id;
1186 $ptagi->notice_id = $this->id;
1187 $ptagi->created = $this->created;
1189 $result = $ptagi->insert();
1191 common_log_db_error($ptagi, 'INSERT', __FILE__);
1192 throw new ServerException(_('Problem saving profile_tag inbox.'));
1195 $ptagi->query('COMMIT');
1197 self::blow('profile_tag:notice_ids:%d', $ptagi->profile_tag_id);
1204 * Save reply records indicating that this notice needs to be
1205 * delivered to the local users with the given URIs.
1207 * Since this is expected to be used when saving foreign-sourced
1208 * messages, we won't deliver to any remote targets as that's the
1209 * source service's responsibility.
1211 * Mail notifications etc will be handled later.
1213 * @param array of unique identifier URIs for recipients
1215 function saveKnownReplies($uris)
1221 $sender = Profile::staticGet($this->profile_id);
1223 foreach (array_unique($uris) as $uri) {
1225 $profile = Profile::fromURI($uri);
1227 if (empty($profile)) {
1228 common_log(LOG_WARNING, "Unable to determine profile for URI '$uri'");
1232 if ($profile->hasBlocked($sender)) {
1233 common_log(LOG_INFO, "Not saving reply to profile {$profile->id} ($uri) from sender {$sender->id} because of a block.");
1237 $reply = new Reply();
1239 $reply->notice_id = $this->id;
1240 $reply->profile_id = $profile->id;
1241 $reply->modified = $this->created;
1243 common_log(LOG_INFO, __METHOD__ . ": saving reply: notice $this->id to profile $profile->id");
1245 $id = $reply->insert();
1252 * Pull @-replies from this message's content in StatusNet markup format
1253 * and save reply records indicating that this message needs to be
1254 * delivered to those users.
1256 * Mail notifications to local profiles will be sent later.
1258 * @return array of integer profile IDs
1261 function saveReplies()
1263 // Don't save reply data for repeats
1265 if (!empty($this->repeat_of)) {
1269 $sender = Profile::staticGet($this->profile_id);
1271 // @todo ideally this parser information would only
1272 // be calculated once.
1274 $mentions = common_find_mentions($this->content, $this);
1278 // store replied only for first @ (what user/notice what the reply directed,
1279 // we assume first @ is it)
1281 foreach ($mentions as $mention) {
1283 foreach ($mention['mentioned'] as $mentioned) {
1285 // skip if they're already covered
1287 if (!empty($replied[$mentioned->id])) {
1291 // Don't save replies from blocked profile to local user
1293 $mentioned_user = User::staticGet('id', $mentioned->id);
1294 if (!empty($mentioned_user) && $mentioned_user->hasBlocked($sender)) {
1298 $reply = new Reply();
1300 $reply->notice_id = $this->id;
1301 $reply->profile_id = $mentioned->id;
1302 $reply->modified = $this->created;
1304 $id = $reply->insert();
1307 common_log_db_error($reply, 'INSERT', __FILE__);
1308 // TRANS: Server exception thrown when a reply cannot be saved.
1309 // TRANS: %1$d is a notice ID, %2$d is the ID of the mentioned user.
1310 throw new ServerException(sprintf(_('Could not save reply for %1$d, %2$d.'), $this->id, $mentioned->id));
1312 $replied[$mentioned->id] = 1;
1313 self::blow('reply:stream:%d', $mentioned->id);
1318 $recipientIds = array_keys($replied);
1320 return $recipientIds;
1324 * Pull the complete list of @-reply targets for this notice.
1326 * @return array of integer profile ids
1328 function getReplies()
1334 $reply = new Reply();
1335 $reply->selectAdd();
1336 $reply->selectAdd('profile_id');
1337 $reply->notice_id = $this->id;
1339 if ($reply->find()) {
1340 while($reply->fetch()) {
1341 $ids[] = $reply->profile_id;
1351 * Send e-mail notifications to local @-reply targets.
1353 * Replies must already have been saved; this is expected to be run
1354 * from the distrib queue handler.
1356 function sendReplyNotifications()
1358 // Don't send reply notifications for repeats
1360 if (!empty($this->repeat_of)) {
1364 $recipientIds = $this->getReplies();
1366 foreach ($recipientIds as $recipientId) {
1367 $user = User::staticGet('id', $recipientId);
1368 if (!empty($user)) {
1369 mail_notify_attn($user, $this);
1375 * Pull list of groups this notice needs to be delivered to,
1376 * as previously recorded by saveGroups() or saveKnownGroups().
1378 * @return array of Group objects
1380 function getGroups()
1382 // Don't save groups for repeats
1384 if (!empty($this->repeat_of)) {
1392 $gi = new Group_inbox();
1395 $gi->selectAdd('group_id');
1397 $gi->notice_id = $this->id;
1400 while ($gi->fetch()) {
1401 $group = User_group::staticGet('id', $gi->group_id);
1414 * Convert a notice into an activity for export.
1416 * @param User $cur Current user
1418 * @return Activity activity object representing this Notice.
1421 function asActivity($cur)
1423 $act = self::cacheGet(Cache::codeKey('notice:as-activity:'.$this->id));
1428 $act = new Activity();
1430 if (Event::handle('StartNoticeAsActivity', array($this, &$act))) {
1432 $profile = $this->getProfile();
1434 $act->actor = ActivityObject::fromProfile($profile);
1435 $act->actor->extra[] = $profile->profileInfo($cur);
1436 $act->verb = ActivityVerb::POST;
1437 $act->objects[] = ActivityObject::fromNotice($this);
1439 // XXX: should this be handled by default processing for object entry?
1441 $act->time = strtotime($this->created);
1442 $act->link = $this->bestUrl();
1444 $act->content = common_xml_safe_str($this->rendered);
1445 $act->id = $this->uri;
1446 $act->title = common_xml_safe_str($this->content);
1450 $tags = $this->getTags();
1452 foreach ($tags as $tag) {
1453 $cat = new AtomCategory();
1456 $act->categories[] = $cat;
1460 // XXX: use Atom Media and/or File activity objects instead
1462 $attachments = $this->attachments();
1464 foreach ($attachments as $attachment) {
1465 $enclosure = $attachment->getEnclosure();
1467 $act->enclosures[] = $enclosure;
1471 $ctx = new ActivityContext();
1473 if (!empty($this->reply_to)) {
1474 $reply = Notice::staticGet('id', $this->reply_to);
1475 if (!empty($reply)) {
1476 $ctx->replyToID = $reply->uri;
1477 $ctx->replyToUrl = $reply->bestUrl();
1481 $ctx->location = $this->getLocation();
1485 if (!empty($this->conversation)) {
1486 $conv = Conversation::staticGet('id', $this->conversation);
1487 if (!empty($conv)) {
1488 $ctx->conversation = $conv->uri;
1492 $reply_ids = $this->getReplies();
1494 foreach ($reply_ids as $id) {
1495 $profile = Profile::staticGet('id', $id);
1496 if (!empty($profile)) {
1497 $ctx->attention[] = $profile->getUri();
1501 $groups = $this->getGroups();
1503 foreach ($groups as $group) {
1504 $ctx->attention[] = $group->getUri();
1507 // XXX: deprecated; use ActivityVerb::SHARE instead
1511 if (!empty($this->repeat_of)) {
1512 $repeat = Notice::staticGet('id', $this->repeat_of);
1513 $ctx->forwardID = $repeat->uri;
1514 $ctx->forwardUrl = $repeat->bestUrl();
1517 $act->context = $ctx;
1521 $atom_feed = $profile->getAtomFeed();
1523 if (!empty($atom_feed)) {
1525 $act->source = new ActivitySource();
1527 // XXX: we should store the actual feed ID
1529 $act->source->id = $atom_feed;
1531 // XXX: we should store the actual feed title
1533 $act->source->title = $profile->getBestName();
1535 $act->source->links['alternate'] = $profile->profileurl;
1536 $act->source->links['self'] = $atom_feed;
1538 $act->source->icon = $profile->avatarUrl(AVATAR_PROFILE_SIZE);
1540 $notice = $profile->getCurrentNotice();
1542 if (!empty($notice)) {
1543 $act->source->updated = self::utcDate($notice->created);
1546 $user = User::staticGet('id', $profile->id);
1548 if (!empty($user)) {
1549 $act->source->links['license'] = common_config('license', 'url');
1553 if ($this->isLocal()) {
1554 $act->selfLink = common_local_url('ApiStatusesShow', array('id' => $this->id,
1555 'format' => 'atom'));
1556 $act->editLink = $act->selfLink;
1559 Event::handle('EndNoticeAsActivity', array($this, &$act));
1562 self::cacheSet(Cache::codeKey('notice:as-activity:'.$this->id), $act);
1567 // This has gotten way too long. Needs to be sliced up into functional bits
1568 // or ideally exported to a utility class.
1570 function asAtomEntry($namespace=false,
1575 $act = $this->asActivity($cur);
1576 $act->extra[] = $this->noticeInfo($cur);
1577 return $act->asString($namespace, $author, $source);
1581 * Extra notice info for atom entries
1583 * Clients use some extra notice info in the atom stream.
1584 * This gives it to them.
1586 * @param User $cur Current user
1588 * @return array representation of <statusnet:notice_info> element
1591 function noticeInfo($cur)
1593 // local notice ID (useful to clients for ordering)
1595 $noticeInfoAttr = array('local_id' => $this->id);
1599 $ns = $this->getSource();
1602 $noticeInfoAttr['source'] = $ns->code;
1603 if (!empty($ns->url)) {
1604 $noticeInfoAttr['source_link'] = $ns->url;
1605 if (!empty($ns->name)) {
1606 $noticeInfoAttr['source'] = '<a href="'
1607 . htmlspecialchars($ns->url)
1608 . '" rel="nofollow">'
1609 . htmlspecialchars($ns->name)
1615 // favorite and repeated
1618 $noticeInfoAttr['favorite'] = ($cur->hasFave($this)) ? "true" : "false";
1619 $cp = $cur->getProfile();
1620 $noticeInfoAttr['repeated'] = ($cp->hasRepeated($this->id)) ? "true" : "false";
1623 if (!empty($this->repeat_of)) {
1624 $noticeInfoAttr['repeat_of'] = $this->repeat_of;
1627 return array('statusnet:notice_info', $noticeInfoAttr, null);
1631 * Returns an XML string fragment with a reference to a notice as an
1632 * Activity Streams noun object with the given element type.
1634 * Assumes that 'activity' namespace has been previously defined.
1636 * @param string $element one of 'subject', 'object', 'target'
1640 function asActivityNoun($element)
1642 $noun = ActivityObject::fromNotice($this);
1643 return $noun->asString('activity:' . $element);
1648 if (!empty($this->url)) {
1650 } else if (!empty($this->uri) && preg_match('/^https?:/', $this->uri)) {
1653 return common_local_url('shownotice',
1654 array('notice' => $this->id));
1658 function stream($fn, $args, $cachekey, $offset=0, $limit=20, $since_id=0, $max_id=0)
1660 $cache = Cache::instance();
1662 if (empty($cache) ||
1663 $since_id != 0 || $max_id != 0 ||
1665 ($offset + $limit) > NOTICE_CACHE_WINDOW) {
1666 return call_user_func_array($fn, array_merge($args, array($offset, $limit, $since_id,
1670 $idkey = Cache::key($cachekey);
1672 $idstr = $cache->get($idkey);
1674 if ($idstr !== false) {
1675 // Cache hit! Woohoo!
1676 $window = explode(',', $idstr);
1677 $ids = array_slice($window, $offset, $limit);
1681 $laststr = $cache->get($idkey.';last');
1683 if ($laststr !== false) {
1684 $window = explode(',', $laststr);
1685 $last_id = $window[0];
1686 $new_ids = call_user_func_array($fn, array_merge($args, array(0, NOTICE_CACHE_WINDOW,
1687 $last_id, 0, null)));
1689 $new_window = array_merge($new_ids, $window);
1691 $new_windowstr = implode(',', $new_window);
1693 $result = $cache->set($idkey, $new_windowstr);
1694 $result = $cache->set($idkey . ';last', $new_windowstr);
1696 $ids = array_slice($new_window, $offset, $limit);
1701 $window = call_user_func_array($fn, array_merge($args, array(0, NOTICE_CACHE_WINDOW,
1704 $windowstr = implode(',', $window);
1706 $result = $cache->set($idkey, $windowstr);
1707 $result = $cache->set($idkey . ';last', $windowstr);
1709 $ids = array_slice($window, $offset, $limit);
1715 * Determine which notice, if any, a new notice is in reply to.
1717 * For conversation tracking, we try to see where this notice fits
1718 * in the tree. Rough algorithm is:
1720 * if (reply_to is set and valid) {
1722 * } else if ((source not API or Web) and (content starts with "T NAME" or "@name ")) {
1723 * return ID of last notice by initial @name in content;
1726 * Note that all @nickname instances will still be used to save "reply" records,
1727 * so the notice shows up in the mentioned users' "replies" tab.
1729 * @param integer $reply_to ID passed in by Web or API
1730 * @param integer $profile_id ID of author
1731 * @param string $source Source tag, like 'web' or 'gwibber'
1732 * @param string $content Final notice content
1734 * @return integer ID of replied-to notice, or null for not a reply.
1737 static function getReplyTo($reply_to, $profile_id, $source, $content)
1739 static $lb = array('xmpp', 'mail', 'sms', 'omb');
1741 // If $reply_to is specified, we check that it exists, and then
1742 // return it if it does
1744 if (!empty($reply_to)) {
1745 $reply_notice = Notice::staticGet('id', $reply_to);
1746 if (!empty($reply_notice)) {
1751 // If it's not a "low bandwidth" source (one where you can't set
1752 // a reply_to argument), we return. This is mostly web and API
1755 if (!in_array($source, $lb)) {
1759 // Is there an initial @ or T?
1761 if (preg_match('/^T ([A-Z0-9]{1,64}) /', $content, $match) ||
1762 preg_match('/^@([a-z0-9]{1,64})\s+/', $content, $match)) {
1763 $nickname = common_canonical_nickname($match[1]);
1768 // Figure out who that is.
1770 $sender = Profile::staticGet('id', $profile_id);
1771 if (empty($sender)) {
1775 $recipient = common_relative_profile($sender, $nickname, common_sql_now());
1777 if (empty($recipient)) {
1781 // Get their last notice
1783 $last = $recipient->getCurrentNotice();
1785 if (!empty($last)) {
1790 static function maxContent()
1792 $contentlimit = common_config('notice', 'contentlimit');
1793 // null => use global limit (distinct from 0!)
1794 if (is_null($contentlimit)) {
1795 $contentlimit = common_config('site', 'textlimit');
1797 return $contentlimit;
1800 static function contentTooLong($content)
1802 $contentlimit = self::maxContent();
1803 return ($contentlimit > 0 && !empty($content) && (mb_strlen($content) > $contentlimit));
1806 function getLocation()
1810 if (!empty($this->location_id) && !empty($this->location_ns)) {
1811 $location = Location::fromId($this->location_id, $this->location_ns);
1814 if (is_null($location)) { // no ID, or Location::fromId() failed
1815 if (!empty($this->lat) && !empty($this->lon)) {
1816 $location = Location::fromLatLon($this->lat, $this->lon);
1823 function repeat($repeater_id, $source)
1825 $author = Profile::staticGet('id', $this->profile_id);
1827 // TRANS: Message used to repeat a notice. RT is the abbreviation of 'retweet'.
1828 // TRANS: %1$s is the repeated user's name, %2$s is the repeated notice.
1829 $content = sprintf(_('RT @%1$s %2$s'),
1833 $maxlen = common_config('site', 'textlimit');
1834 if ($maxlen > 0 && mb_strlen($content) > $maxlen) {
1835 // Web interface and current Twitter API clients will
1836 // pull the original notice's text, but some older
1837 // clients and RSS/Atom feeds will see this trimmed text.
1839 // Unfortunately this is likely to lose tags or URLs
1840 // at the end of long notices.
1841 $content = mb_substr($content, 0, $maxlen - 4) . ' ...';
1844 return self::saveNew($repeater_id, $content, $source,
1845 array('repeat_of' => $this->id));
1848 // These are supposed to be in chron order!
1850 function repeatStream($limit=100)
1852 $cache = Cache::instance();
1854 if (empty($cache)) {
1855 $ids = $this->_repeatStreamDirect($limit);
1857 $idstr = $cache->get(Cache::key('notice:repeats:'.$this->id));
1858 if ($idstr !== false) {
1859 $ids = explode(',', $idstr);
1861 $ids = $this->_repeatStreamDirect(100);
1862 $cache->set(Cache::key('notice:repeats:'.$this->id), implode(',', $ids));
1865 // We do a max of 100, so slice down to limit
1866 $ids = array_slice($ids, 0, $limit);
1870 return Notice::getStreamByIds($ids);
1873 function _repeatStreamDirect($limit)
1875 $notice = new Notice();
1877 $notice->selectAdd(); // clears it
1878 $notice->selectAdd('id');
1880 $notice->repeat_of = $this->id;
1882 $notice->orderBy('created, id'); // NB: asc!
1884 if (!is_null($limit)) {
1885 $notice->limit(0, $limit);
1890 if ($notice->find()) {
1891 while ($notice->fetch()) {
1892 $ids[] = $notice->id;
1902 function locationOptions($lat, $lon, $location_id, $location_ns, $profile = null)
1906 if (!empty($location_id) && !empty($location_ns)) {
1907 $options['location_id'] = $location_id;
1908 $options['location_ns'] = $location_ns;
1910 $location = Location::fromId($location_id, $location_ns);
1912 if (!empty($location)) {
1913 $options['lat'] = $location->lat;
1914 $options['lon'] = $location->lon;
1917 } else if (!empty($lat) && !empty($lon)) {
1918 $options['lat'] = $lat;
1919 $options['lon'] = $lon;
1921 $location = Location::fromLatLon($lat, $lon);
1923 if (!empty($location)) {
1924 $options['location_id'] = $location->location_id;
1925 $options['location_ns'] = $location->location_ns;
1927 } else if (!empty($profile)) {
1928 if (isset($profile->lat) && isset($profile->lon)) {
1929 $options['lat'] = $profile->lat;
1930 $options['lon'] = $profile->lon;
1933 if (isset($profile->location_id) && isset($profile->location_ns)) {
1934 $options['location_id'] = $profile->location_id;
1935 $options['location_ns'] = $profile->location_ns;
1942 function clearReplies()
1944 $replyNotice = new Notice();
1945 $replyNotice->reply_to = $this->id;
1947 //Null any notices that are replies to this notice
1949 if ($replyNotice->find()) {
1950 while ($replyNotice->fetch()) {
1951 $orig = clone($replyNotice);
1952 $replyNotice->reply_to = null;
1953 $replyNotice->update($orig);
1959 $reply = new Reply();
1960 $reply->notice_id = $this->id;
1962 if ($reply->find()) {
1963 while($reply->fetch()) {
1964 self::blow('reply:stream:%d', $reply->profile_id);
1972 function clearFiles()
1974 $f2p = new File_to_post();
1976 $f2p->post_id = $this->id;
1979 while ($f2p->fetch()) {
1983 // FIXME: decide whether to delete File objects
1984 // ...and related (actual) files
1987 function clearRepeats()
1989 $repeatNotice = new Notice();
1990 $repeatNotice->repeat_of = $this->id;
1992 //Null any notices that are repeats of this notice
1994 if ($repeatNotice->find()) {
1995 while ($repeatNotice->fetch()) {
1996 $orig = clone($repeatNotice);
1997 $repeatNotice->repeat_of = null;
1998 $repeatNotice->update($orig);
2003 function clearFaves()
2006 $fave->notice_id = $this->id;
2008 if ($fave->find()) {
2009 while ($fave->fetch()) {
2010 self::blow('fave:ids_by_user_own:%d', $fave->user_id);
2011 self::blow('fave:ids_by_user_own:%d;last', $fave->user_id);
2012 self::blow('fave:ids_by_user:%d', $fave->user_id);
2013 self::blow('fave:ids_by_user:%d;last', $fave->user_id);
2021 function clearTags()
2023 $tag = new Notice_tag();
2024 $tag->notice_id = $this->id;
2027 while ($tag->fetch()) {
2028 self::blow('profile:notice_ids_tagged:%d:%s', $this->profile_id, Cache::keyize($tag->tag));
2029 self::blow('profile:notice_ids_tagged:%d:%s;last', $this->profile_id, Cache::keyize($tag->tag));
2030 self::blow('notice_tag:notice_ids:%s', Cache::keyize($tag->tag));
2031 self::blow('notice_tag:notice_ids:%s;last', Cache::keyize($tag->tag));
2039 function clearGroupInboxes()
2041 $gi = new Group_inbox();
2043 $gi->notice_id = $this->id;
2046 while ($gi->fetch()) {
2047 self::blow('user_group:notice_ids:%d', $gi->group_id);
2055 function distribute()
2057 // We always insert for the author so they don't
2059 Event::handle('StartNoticeDistribute', array($this));
2061 $user = User::staticGet('id', $this->profile_id);
2062 if (!empty($user)) {
2063 Inbox::insertNotice($user->id, $this->id);
2066 if (common_config('queue', 'inboxes')) {
2067 // If there's a failure, we want to _force_
2068 // distribution at this point.
2070 $qm = QueueManager::get();
2071 $qm->enqueue($this, 'distrib');
2072 } catch (Exception $e) {
2073 // If the exception isn't transient, this
2074 // may throw more exceptions as DQH does
2075 // its own enqueueing. So, we ignore them!
2077 $handler = new DistribQueueHandler();
2078 $handler->handle($this);
2079 } catch (Exception $e) {
2080 common_log(LOG_ERR, "emergency redistribution resulted in " . $e->getMessage());
2082 // Re-throw so somebody smarter can handle it.
2086 $handler = new DistribQueueHandler();
2087 $handler->handle($this);
2093 $result = parent::insert();
2096 // Profile::hasRepeated() abuses pkeyGet(), so we
2097 // have to clear manually
2098 if (!empty($this->repeat_of)) {
2099 $c = self::memcache();
2101 $ck = self::multicacheKey('Notice',
2102 array('profile_id' => $this->profile_id,
2103 'repeat_of' => $this->repeat_of));
2113 * Get the source of the notice
2115 * @return Notice_source $ns A notice source object. 'code' is the only attribute
2116 * guaranteed to be populated.
2118 function getSource()
2120 $ns = new Notice_source();
2121 if (!empty($this->source)) {
2122 switch ($this->source) {
2129 $ns->code = $this->source;
2132 $ns = Notice_source::staticGet($this->source);
2134 $ns = new Notice_source();
2135 $ns->code = $this->source;
2136 $app = Oauth_application::staticGet('name', $this->source);
2138 $ns->name = $app->name;
2139 $ns->url = $app->source_url;
2149 * Determine whether the notice was locally created
2151 * @return boolean locality
2154 public function isLocal()
2156 return ($this->is_local == Notice::LOCAL_PUBLIC ||
2157 $this->is_local == Notice::LOCAL_NONPUBLIC);
2161 * Get the list of hash tags saved with this notice.
2163 * @return array of strings
2165 public function getTags()
2168 $tag = new Notice_tag();
2169 $tag->notice_id = $this->id;
2171 while ($tag->fetch()) {
2172 $tags[] = $tag->tag;
2179 static private function utcDate($dt)
2181 $dateStr = date('d F Y H:i:s', strtotime($dt));
2182 $d = new DateTime($dateStr, new DateTimeZone('UTC'));
2183 return $d->format(DATE_W3C);
2187 * Look up the creation timestamp for a given notice ID, even
2188 * if it's been deleted.
2191 * @return mixed string recorded creation timestamp, or false if can't be found
2193 public static function getAsTimestamp($id)
2199 $notice = Notice::staticGet('id', $id);
2201 return $notice->created;
2204 $deleted = Deleted_notice::staticGet('id', $id);
2206 return $deleted->created;
2213 * Build an SQL 'where' fragment for timestamp-based sorting from a since_id
2214 * parameter, matching notices posted after the given one (exclusive).
2216 * If the referenced notice can't be found, will return false.
2219 * @param string $idField
2220 * @param string $createdField
2221 * @return mixed string or false if no match
2223 public static function whereSinceId($id, $idField='id', $createdField='created')
2225 $since = Notice::getAsTimestamp($id);
2227 return sprintf("($createdField = '%s' and $idField > %d) or ($createdField > '%s')", $since, $id, $since);
2233 * Build an SQL 'where' fragment for timestamp-based sorting from a since_id
2234 * parameter, matching notices posted after the given one (exclusive), and
2235 * if necessary add it to the data object's query.
2237 * @param DB_DataObject $obj
2239 * @param string $idField
2240 * @param string $createdField
2241 * @return mixed string or false if no match
2243 public static function addWhereSinceId(DB_DataObject $obj, $id, $idField='id', $createdField='created')
2245 $since = self::whereSinceId($id, $idField, $createdField);
2247 $obj->whereAdd($since);
2252 * Build an SQL 'where' fragment for timestamp-based sorting from a max_id
2253 * parameter, matching notices posted before the given one (inclusive).
2255 * If the referenced notice can't be found, will return false.
2258 * @param string $idField
2259 * @param string $createdField
2260 * @return mixed string or false if no match
2262 public static function whereMaxId($id, $idField='id', $createdField='created')
2264 $max = Notice::getAsTimestamp($id);
2266 return sprintf("($createdField < '%s') or ($createdField = '%s' and $idField <= %d)", $max, $max, $id);
2272 * Build an SQL 'where' fragment for timestamp-based sorting from a max_id
2273 * parameter, matching notices posted before the given one (inclusive), and
2274 * if necessary add it to the data object's query.
2276 * @param DB_DataObject $obj
2278 * @param string $idField
2279 * @param string $createdField
2280 * @return mixed string or false if no match
2282 public static function addWhereMaxId(DB_DataObject $obj, $id, $idField='id', $createdField='created')
2284 $max = self::whereMaxId($id, $idField, $createdField);
2286 $obj->whereAdd($max);
2292 if (common_config('public', 'localonly')) {
2293 return ($this->is_local == Notice::LOCAL_PUBLIC);
2295 return (($this->is_local != Notice::LOCAL_NONPUBLIC) &&
2296 ($this->is_local != Notice::GATEWAY));