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 * @license GNU Affero General Public License http://www.gnu.org/licenses/
35 if (!defined('STATUSNET') && !defined('LACONICA')) {
40 * Table Definition for notice
42 require_once INSTALLDIR.'/classes/Memcached_DataObject.php';
44 /* We keep the first three 20-notice pages, plus one for pagination check,
45 * in the memcached cache. */
47 define('NOTICE_CACHE_WINDOW', 61);
49 define('MAX_BOXCARS', 128);
51 class Notice extends Memcached_DataObject
54 /* the code below is auto generated do not remove the above tag */
56 public $__table = 'notice'; // table name
57 public $id; // int(4) primary_key not_null
58 public $profile_id; // int(4) multiple_key not_null
59 public $uri; // varchar(255) unique_key
60 public $content; // text
61 public $rendered; // text
62 public $url; // varchar(255)
63 public $created; // datetime multiple_key not_null default_0000-00-00%2000%3A00%3A00
64 public $modified; // timestamp not_null default_CURRENT_TIMESTAMP
65 public $reply_to; // int(4)
66 public $is_local; // tinyint(1)
67 public $source; // varchar(32)
68 public $conversation; // int(4)
69 public $lat; // decimal(10,7)
70 public $lon; // decimal(10,7)
71 public $location_id; // int(4)
72 public $location_ns; // int(4)
73 public $repeat_of; // int(4)
76 function staticGet($k,$v=NULL)
78 return Memcached_DataObject::staticGet('Notice',$k,$v);
81 /* the code above is auto generated do not remove the tag below */
85 const LOCAL_PUBLIC = 1;
87 const LOCAL_NONPUBLIC = -1;
92 return Profile::staticGet('id', $this->profile_id);
97 $this->blowCaches(true);
98 $this->blowFavesCache(true);
99 $this->blowSubsCache(true);
101 // For auditing purposes, save a record that the notice
104 $deleted = new Deleted_notice();
106 $deleted->id = $this->id;
107 $deleted->profile_id = $this->profile_id;
108 $deleted->uri = $this->uri;
109 $deleted->created = $this->created;
110 $deleted->deleted = common_sql_now();
112 $this->query('BEGIN');
116 //Null any notices that are replies to this notice
117 $this->query(sprintf("UPDATE notice set reply_to = null WHERE reply_to = %d", $this->id));
119 //Null any notices that are repeats of this notice
120 //XXX: probably need to uncache these, too
122 $this->query(sprintf("UPDATE notice set repeat_of = null WHERE repeat_of = %d", $this->id));
124 $related = array('Reply',
131 foreach ($related as $cls) {
133 $inst->notice_id = $this->id;
136 $result = parent::delete();
137 $this->query('COMMIT');
142 /* extract all #hastags */
143 $count = preg_match_all('/(?:^|\s)#([\pL\pN_\-\.]{1,64})/', strtolower($this->content), $match);
148 //turn each into their canonical tag
149 //this is needed to remove dupes before saving e.g. #hash.tag = #hashtag
151 for($i=0; $i<count($match[1]); $i++) {
152 $hashtags[] = common_canonical_tag($match[1][$i]);
155 /* Add them to the database */
156 foreach(array_unique($hashtags) as $hashtag) {
157 /* elide characters we don't want in the tag */
158 $this->saveTag($hashtag);
163 function saveTag($hashtag)
165 $tag = new Notice_tag();
166 $tag->notice_id = $this->id;
167 $tag->tag = $hashtag;
168 $tag->created = $this->created;
169 $id = $tag->insert();
172 throw new ServerException(sprintf(_('DB error inserting hashtag: %s'),
173 $last_error->message));
179 * Save a new notice and push it out to subscribers' inboxes.
180 * Poster's permissions are checked before sending.
182 * @param int $profile_id Profile ID of the poster
183 * @param string $content source message text; links may be shortened
184 * per current user's preference
185 * @param string $source source key ('web', 'api', etc)
186 * @param array $options Associative array of optional properties:
187 * string 'created' timestamp of notice; defaults to now
188 * int 'is_local' source/gateway ID, one of:
189 * Notice::LOCAL_PUBLIC - Local, ok to appear in public timeline
190 * Notice::REMOTE_OMB - Sent from a remote OMB service;
191 * hide from public timeline but show in
192 * local "and friends" timelines
193 * Notice::LOCAL_NONPUBLIC - Local, but hide from public timeline
194 * Notice::GATEWAY - From another non-OMB service;
195 * will not appear in public views
196 * float 'lat' decimal latitude for geolocation
197 * float 'lon' decimal longitude for geolocation
198 * int 'location_id' geoname identifier
199 * int 'location_ns' geoname namespace to interpret location_id
200 * int 'reply_to'; notice ID this is a reply to
201 * int 'repeat_of'; notice ID this is a repeat of
202 * string 'uri' permalink to notice; defaults to local notice URL
205 * @throws ClientException
207 static function saveNew($profile_id, $content, $source, $options=null) {
208 $defaults = array('uri' => null,
210 'repeat_of' => null);
212 if (!empty($options)) {
213 $options = $options + $defaults;
217 if (empty($is_local)) {
218 $is_local = Notice::LOCAL_PUBLIC;
221 $profile = Profile::staticGet($profile_id);
223 $final = common_shorten_links($content);
225 if (Notice::contentTooLong($final)) {
226 throw new ClientException(_('Problem saving notice. Too long.'));
229 if (empty($profile)) {
230 throw new ClientException(_('Problem saving notice. Unknown user.'));
233 if (common_config('throttle', 'enabled') && !Notice::checkEditThrottle($profile_id)) {
234 common_log(LOG_WARNING, 'Excessive posting by profile #' . $profile_id . '; throttled.');
235 throw new ClientException(_('Too many notices too fast; take a breather '.
236 'and post again in a few minutes.'));
239 if (common_config('site', 'dupelimit') > 0 && !Notice::checkDupes($profile_id, $final)) {
240 common_log(LOG_WARNING, 'Dupe posting by profile #' . $profile_id . '; throttled.');
241 throw new ClientException(_('Too many duplicate messages too quickly;'.
242 ' take a breather and post again in a few minutes.'));
245 if (!$profile->hasRight(Right::NEWNOTICE)) {
246 common_log(LOG_WARNING, "Attempted post from user disallowed to post: " . $profile->nickname);
247 throw new ClientException(_('You are banned from posting notices on this site.'));
250 $notice = new Notice();
251 $notice->profile_id = $profile_id;
253 $autosource = common_config('public', 'autosource');
255 # Sandboxed are non-false, but not 1, either
257 if (!$profile->hasRight(Right::PUBLICNOTICE) ||
258 ($source && $autosource && in_array($source, $autosource))) {
259 $notice->is_local = Notice::LOCAL_NONPUBLIC;
261 $notice->is_local = $is_local;
264 if (!empty($created)) {
265 $notice->created = $created;
267 $notice->created = common_sql_now();
270 $notice->content = $final;
271 $notice->rendered = common_render_content($final, $notice);
272 $notice->source = $source;
275 // Handle repeat case
277 if (isset($repeat_of)) {
278 $notice->repeat_of = $repeat_of;
279 $notice->reply_to = $repeat_of;
281 $notice->reply_to = self::getReplyTo($reply_to, $profile_id, $source, $final);
284 if (!empty($notice->reply_to)) {
285 $reply = Notice::staticGet('id', $notice->reply_to);
286 $notice->conversation = $reply->conversation;
289 if (!empty($lat) && !empty($lon)) {
292 $notice->location_id = $location_id;
293 $notice->location_ns = $location_ns;
294 } else if (!empty($location_ns) && !empty($location_id)) {
295 $location = Location::fromId($location_id, $location_ns);
296 if (!empty($location)) {
297 $notice->lat = $location->lat;
298 $notice->lon = $location->lon;
299 $notice->location_id = $location_id;
300 $notice->location_ns = $location_ns;
303 $notice->lat = $profile->lat;
304 $notice->lon = $profile->lon;
305 $notice->location_id = $profile->location_id;
306 $notice->location_ns = $profile->location_ns;
309 if (Event::handle('StartNoticeSave', array(&$notice))) {
311 // XXX: some of these functions write to the DB
313 $notice->query('BEGIN');
315 $id = $notice->insert();
318 common_log_db_error($notice, 'INSERT', __FILE__);
319 throw new ServerException(_('Problem saving notice.'));
322 // Update ID-dependent columns: URI, conversation
324 $orig = clone($notice);
329 $notice->uri = common_notice_uri($notice);
333 // If it's not part of a conversation, it's
334 // the beginning of a new conversation.
336 if (empty($notice->conversation)) {
337 $notice->conversation = $notice->id;
342 if (!$notice->update($orig)) {
343 common_log_db_error($notice, 'UPDATE', __FILE__);
344 throw new ServerException(_('Problem saving notice.'));
348 // XXX: do we need to change this for remote users?
352 $notice->addToInboxes();
356 $notice->query('COMMIT');
358 Event::handle('EndNoticeSave', array($notice));
361 # Clear the cache for subscribed users, so they'll update at next request
362 # XXX: someone clever could prepend instead of clearing the cache
364 $notice->blowCaches();
369 /** save all urls in the notice to the db
371 * follow redirects and save all available file information
372 * (mimetype, date, size, oembed, etc.)
376 function saveUrls() {
377 common_replace_urls_callback($this->content, array($this, 'saveUrl'), $this->id);
380 function saveUrl($data) {
381 list($url, $notice_id) = $data;
382 File::processNew($url, $notice_id);
385 static function checkDupes($profile_id, $content) {
386 $profile = Profile::staticGet($profile_id);
387 if (empty($profile)) {
390 $notice = $profile->getNotices(0, NOTICE_CACHE_WINDOW);
391 if (!empty($notice)) {
393 while ($notice->fetch()) {
394 if (time() - strtotime($notice->created) >= common_config('site', 'dupelimit')) {
396 } else if ($notice->content == $content) {
401 # If we get here, oldest item in cache window is not
402 # old enough for dupe limit; do direct check against DB
403 $notice = new Notice();
404 $notice->profile_id = $profile_id;
405 $notice->content = $content;
406 if (common_config('db','type') == 'pgsql')
407 $notice->whereAdd('extract(epoch from now() - created) < ' . common_config('site', 'dupelimit'));
409 $notice->whereAdd('now() - created < ' . common_config('site', 'dupelimit'));
411 $cnt = $notice->count();
415 static function checkEditThrottle($profile_id) {
416 $profile = Profile::staticGet($profile_id);
417 if (empty($profile)) {
421 $notice = $profile->getNotices(common_config('throttle', 'count') - 1, 1);
422 if ($notice && $notice->fetch()) {
423 # If the Nth notice was posted less than timespan seconds ago
424 if (time() - strtotime($notice->created) <= common_config('throttle', 'timespan')) {
429 # Either not N notices in the stream, OR the Nth was not posted within timespan seconds
433 function getUploadedAttachment() {
435 $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"';
436 $post->query($query);
438 if (empty($post->up) || empty($post->i)) {
441 $ret = array($post->up, $post->i);
447 function hasAttachments() {
449 $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);
450 $post->query($query);
452 $n_attachments = intval($post->n_attachments);
454 return $n_attachments;
457 function attachments() {
460 $f2p = new File_to_post;
461 $f2p->post_id = $this->id;
463 while ($f2p->fetch()) {
464 $f = File::staticGet($f2p->file_id);
471 function blowCaches($blowLast=false)
473 $this->blowSubsCache($blowLast);
474 $this->blowNoticeCache($blowLast);
475 $this->blowRepliesCache($blowLast);
476 $this->blowPublicCache($blowLast);
477 $this->blowTagCache($blowLast);
478 $this->blowGroupCache($blowLast);
479 $this->blowConversationCache($blowLast);
480 $this->blowRepeatCache();
481 $profile = Profile::staticGet($this->profile_id);
482 $profile->blowNoticeCount();
485 function blowRepeatCache()
487 if (!empty($this->repeat_of)) {
488 $cache = common_memcache();
489 if (!empty($cache)) {
490 // XXX: only blow if <100 in cache
491 $ck = common_cache_key('notice:repeats:'.$this->repeat_of);
492 $result = $cache->delete($ck);
494 $user = User::staticGet('id', $this->profile_id);
497 $uk = common_cache_key('user:repeated_by_me:'.$user->id);
503 $original = Notice::staticGet('id', $this->repeat_of);
505 if (!empty($original)) {
506 $originalUser = User::staticGet('id', $original->profile_id);
507 if (!empty($originalUser)) {
508 $ouk = common_cache_key('user:repeats_of_me:'.$originalUser->id);
509 $cache->delete($ouk);
510 $originalUser->free();
511 unset($originalUser);
517 $ni = new Notice_inbox();
519 $ni->notice_id = $this->id;
522 while ($ni->fetch()) {
523 $tmk = common_cache_key('user:repeated_to_me:'.$ni->user_id);
524 $cache->delete($tmk);
534 function blowConversationCache($blowLast=false)
536 $cache = common_memcache();
538 $ck = common_cache_key('notice:conversation_ids:'.$this->conversation);
541 $cache->delete($ck.';last');
546 function blowGroupCache($blowLast=false)
548 $cache = common_memcache();
550 $group_inbox = new Group_inbox();
551 $group_inbox->notice_id = $this->id;
552 if ($group_inbox->find()) {
553 while ($group_inbox->fetch()) {
554 $cache->delete(common_cache_key('user_group:notice_ids:' . $group_inbox->group_id));
556 $cache->delete(common_cache_key('user_group:notice_ids:' . $group_inbox->group_id.';last'));
558 $member = new Group_member();
559 $member->group_id = $group_inbox->group_id;
560 if ($member->find()) {
561 while ($member->fetch()) {
562 $cache->delete(common_cache_key('notice_inbox:by_user:' . $member->profile_id));
563 $cache->delete(common_cache_key('notice_inbox:by_user_own:' . $member->profile_id));
564 if (empty($this->repeat_of)) {
565 $cache->delete(common_cache_key('user:friends_timeline:' . $member->profile_id));
566 $cache->delete(common_cache_key('user:friends_timeline_own:' . $member->profile_id));
569 $cache->delete(common_cache_key('notice_inbox:by_user:' . $member->profile_id . ';last'));
570 $cache->delete(common_cache_key('notice_inbox:by_user_own:' . $member->profile_id . ';last'));
571 if (empty($this->repeat_of)) {
572 $cache->delete(common_cache_key('user:friends_timeline:' . $member->profile_id . ';last'));
573 $cache->delete(common_cache_key('user:friends_timeline_own:' . $member->profile_id . ';last'));
580 $group_inbox->free();
585 function blowTagCache($blowLast=false)
587 $cache = common_memcache();
589 $tag = new Notice_tag();
590 $tag->notice_id = $this->id;
592 while ($tag->fetch()) {
593 $tag->blowCache($blowLast);
594 $ck = 'profile:notice_ids_tagged:' . $this->profile_id . ':' . $tag->tag;
598 $cache->delete($ck . ';last');
607 function blowSubsCache($blowLast=false)
609 $cache = common_memcache();
613 $UT = common_config('db','type')=='pgsql'?'"user"':'user';
614 $user->query('SELECT id ' .
616 "FROM $UT JOIN subscription ON $UT.id = subscription.subscriber " .
617 'WHERE subscription.subscribed = ' . $this->profile_id);
619 while ($user->fetch()) {
620 $cache->delete(common_cache_key('notice_inbox:by_user:'.$user->id));
621 $cache->delete(common_cache_key('notice_inbox:by_user_own:'.$user->id));
622 if (empty($this->repeat_of)) {
623 $cache->delete(common_cache_key('user:friends_timeline:'.$user->id));
624 $cache->delete(common_cache_key('user:friends_timeline_own:'.$user->id));
627 $cache->delete(common_cache_key('notice_inbox:by_user:'.$user->id.';last'));
628 $cache->delete(common_cache_key('notice_inbox:by_user_own:'.$user->id.';last'));
629 if (empty($this->repeat_of)) {
630 $cache->delete(common_cache_key('user:friends_timeline:'.$user->id.';last'));
631 $cache->delete(common_cache_key('user:friends_timeline_own:'.$user->id.';last'));
640 function blowNoticeCache($blowLast=false)
642 if ($this->is_local) {
643 $cache = common_memcache();
644 if (!empty($cache)) {
645 $cache->delete(common_cache_key('profile:notice_ids:'.$this->profile_id));
647 $cache->delete(common_cache_key('profile:notice_ids:'.$this->profile_id.';last'));
653 function blowRepliesCache($blowLast=false)
655 $cache = common_memcache();
657 $reply = new Reply();
658 $reply->notice_id = $this->id;
659 if ($reply->find()) {
660 while ($reply->fetch()) {
661 $cache->delete(common_cache_key('reply:stream:'.$reply->profile_id));
663 $cache->delete(common_cache_key('reply:stream:'.$reply->profile_id.';last'));
672 function blowPublicCache($blowLast=false)
674 if ($this->is_local == Notice::LOCAL_PUBLIC) {
675 $cache = common_memcache();
677 $cache->delete(common_cache_key('public'));
679 $cache->delete(common_cache_key('public').';last');
685 function blowFavesCache($blowLast=false)
687 $cache = common_memcache();
690 $fave->notice_id = $this->id;
692 while ($fave->fetch()) {
693 $cache->delete(common_cache_key('fave:ids_by_user:'.$fave->user_id));
694 $cache->delete(common_cache_key('fave:by_user_own:'.$fave->user_id));
696 $cache->delete(common_cache_key('fave:ids_by_user:'.$fave->user_id.';last'));
697 $cache->delete(common_cache_key('fave:by_user_own:'.$fave->user_id.';last'));
706 function getStreamByIds($ids)
708 $cache = common_memcache();
710 if (!empty($cache)) {
712 foreach ($ids as $id) {
713 $n = Notice::staticGet('id', $id);
718 return new ArrayWrapper($notices);
720 $notice = new Notice();
722 //if no IDs requested, just return the notice object
725 $notice->whereAdd('id in (' . implode(', ', $ids) . ')');
731 while ($notice->fetch()) {
732 $temp[$notice->id] = clone($notice);
737 foreach ($ids as $id) {
738 if (array_key_exists($id, $temp)) {
739 $wrapped[] = $temp[$id];
743 return new ArrayWrapper($wrapped);
747 function publicStream($offset=0, $limit=20, $since_id=0, $max_id=0, $since=null)
749 $ids = Notice::stream(array('Notice', '_publicStreamDirect'),
752 $offset, $limit, $since_id, $max_id, $since);
754 return Notice::getStreamByIds($ids);
757 function _publicStreamDirect($offset=0, $limit=20, $since_id=0, $max_id=0, $since=null)
759 $notice = new Notice();
761 $notice->selectAdd(); // clears it
762 $notice->selectAdd('id');
764 $notice->orderBy('id DESC');
766 if (!is_null($offset)) {
767 $notice->limit($offset, $limit);
770 if (common_config('public', 'localonly')) {
771 $notice->whereAdd('is_local = ' . Notice::LOCAL_PUBLIC);
773 # -1 == blacklisted, -2 == gateway (i.e. Twitter)
774 $notice->whereAdd('is_local !='. Notice::LOCAL_NONPUBLIC);
775 $notice->whereAdd('is_local !='. Notice::GATEWAY);
778 if ($since_id != 0) {
779 $notice->whereAdd('id > ' . $since_id);
783 $notice->whereAdd('id <= ' . $max_id);
786 if (!is_null($since)) {
787 $notice->whereAdd('created > \'' . date('Y-m-d H:i:s', $since) . '\'');
792 if ($notice->find()) {
793 while ($notice->fetch()) {
794 $ids[] = $notice->id;
804 function conversationStream($id, $offset=0, $limit=20, $since_id=0, $max_id=0, $since=null)
806 $ids = Notice::stream(array('Notice', '_conversationStreamDirect'),
808 'notice:conversation_ids:'.$id,
809 $offset, $limit, $since_id, $max_id, $since);
811 return Notice::getStreamByIds($ids);
814 function _conversationStreamDirect($id, $offset=0, $limit=20, $since_id=0, $max_id=0, $since=null)
816 $notice = new Notice();
818 $notice->selectAdd(); // clears it
819 $notice->selectAdd('id');
821 $notice->conversation = $id;
823 $notice->orderBy('id DESC');
825 if (!is_null($offset)) {
826 $notice->limit($offset, $limit);
829 if ($since_id != 0) {
830 $notice->whereAdd('id > ' . $since_id);
834 $notice->whereAdd('id <= ' . $max_id);
837 if (!is_null($since)) {
838 $notice->whereAdd('created > \'' . date('Y-m-d H:i:s', $since) . '\'');
843 if ($notice->find()) {
844 while ($notice->fetch()) {
845 $ids[] = $notice->id;
855 function addToInboxes()
857 // XXX: loads constants
859 $inbox = new Notice_inbox();
861 $users = $this->getSubscribedUsers();
863 // FIXME: kind of ignoring 'transitional'...
864 // we'll probably stop supporting inboxless mode
869 foreach ($users as $id) {
870 $ni[$id] = NOTICE_INBOX_SOURCE_SUB;
873 $groups = $this->saveGroups();
874 $profile = $this->getProfile();
876 foreach ($groups as $group) {
877 $users = $group->getUserMembers();
878 foreach ($users as $id) {
879 if (!array_key_exists($id, $ni)) {
880 $user = User::staticGet('id', $id);
881 if (!$user->hasBlocked($profile)) {
882 $ni[$id] = NOTICE_INBOX_SOURCE_GROUP;
888 $recipients = $this->saveReplies();
890 foreach ($recipients as $recipient) {
892 if (!array_key_exists($recipient, $ni)) {
893 $recipientUser = User::staticGet('id', $recipient);
894 if (!empty($recipientUser)) {
895 $ni[$recipient] = NOTICE_INBOX_SOURCE_REPLY;
900 Notice_inbox::bulkInsert($this->id, $this->created, $ni);
905 function getSubscribedUsers()
909 if(common_config('db','quote_identifiers'))
910 $user_table = '"user"';
911 else $user_table = 'user';
915 'FROM '. $user_table .' JOIN subscription '.
916 'ON '. $user_table .'.id = subscription.subscriber ' .
917 'WHERE subscription.subscribed = %d ';
919 $user->query(sprintf($qry, $this->profile_id));
923 while ($user->fetch()) {
932 function saveGroups()
936 /* extract all !group */
937 $count = preg_match_all('/(?:^|\s)!([A-Za-z0-9]{1,64})/',
938 strtolower($this->content),
944 $profile = $this->getProfile();
946 /* Add them to the database */
948 foreach (array_unique($match[1]) as $nickname) {
949 /* XXX: remote groups. */
950 $group = User_group::getForNickname($nickname);
956 // we automatically add a tag for every group name, too
958 $tag = Notice_tag::pkeyGet(array('tag' => common_canonical_tag($nickname),
959 'notice_id' => $this->id));
962 $this->saveTag($nickname);
965 if ($profile->isMember($group)) {
967 $result = $this->addToGroupInbox($group);
970 common_log_db_error($gi, 'INSERT', __FILE__);
973 $groups[] = clone($group);
980 function addToGroupInbox($group)
982 $gi = Group_inbox::pkeyGet(array('group_id' => $group->id,
983 'notice_id' => $this->id));
987 $gi = new Group_inbox();
989 $gi->group_id = $group->id;
990 $gi->notice_id = $this->id;
991 $gi->created = $this->created;
993 return $gi->insert();
1000 * @return array of integer profile IDs
1002 function saveReplies()
1004 // Alternative reply format
1006 if (preg_match('/^T ([A-Z0-9]{1,64}) /', $this->content, $match)) {
1009 // extract all @messages
1010 $cnt = preg_match_all('/(?:^|\s)@([a-z0-9]{1,64})/', $this->content, $match);
1014 if ($cnt || $tname) {
1015 // XXX: is there another way to make an array copy?
1016 $names = ($tname) ? array_unique(array_merge(array(strtolower($tname)), $match[1])) : array_unique($match[1]);
1019 $sender = Profile::staticGet($this->profile_id);
1023 // store replied only for first @ (what user/notice what the reply directed,
1024 // we assume first @ is it)
1026 for ($i=0; $i<count($names); $i++) {
1027 $nickname = $names[$i];
1028 $recipient = common_relative_profile($sender, $nickname, $this->created);
1029 if (empty($recipient)) {
1032 // Don't save replies from blocked profile to local user
1033 $recipient_user = User::staticGet('id', $recipient->id);
1034 if (!empty($recipient_user) && $recipient_user->hasBlocked($sender)) {
1037 $reply = new Reply();
1038 $reply->notice_id = $this->id;
1039 $reply->profile_id = $recipient->id;
1040 $id = $reply->insert();
1042 $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError');
1043 common_log(LOG_ERR, 'DB error inserting reply: ' . $last_error->message);
1044 common_server_error(sprintf(_('DB error inserting reply: %s'), $last_error->message));
1047 $replied[$recipient->id] = 1;
1051 // Hash format replies, too
1052 $cnt = preg_match_all('/(?:^|\s)@#([a-z0-9]{1,64})/', $this->content, $match);
1054 foreach ($match[1] as $tag) {
1055 $tagged = Profile_tag::getTagged($sender->id, $tag);
1056 foreach ($tagged as $t) {
1057 if (!$replied[$t->id]) {
1058 // Don't save replies from blocked profile to local user
1059 $t_user = User::staticGet('id', $t->id);
1060 if ($t_user && $t_user->hasBlocked($sender)) {
1063 $reply = new Reply();
1064 $reply->notice_id = $this->id;
1065 $reply->profile_id = $t->id;
1066 $id = $reply->insert();
1068 common_log_db_error($reply, 'INSERT', __FILE__);
1071 $replied[$recipient->id] = 1;
1078 $recipientIds = array_keys($replied);
1080 foreach ($recipientIds as $recipientId) {
1081 $user = User::staticGet('id', $recipientId);
1083 mail_notify_attn($user, $this);
1087 return $recipientIds;
1090 function asAtomEntry($namespace=false, $source=false)
1092 $profile = $this->getProfile();
1094 $xs = new XMLStringer(true);
1097 $attrs = array('xmlns' => 'http://www.w3.org/2005/Atom',
1098 'xmlns:thr' => 'http://purl.org/syndication/thread/1.0');
1103 $xs->elementStart('entry', $attrs);
1106 $xs->elementStart('source');
1107 $xs->element('title', null, $profile->nickname . " - " . common_config('site', 'name'));
1108 $xs->element('link', array('href' => $profile->profileurl));
1109 $user = User::staticGet('id', $profile->id);
1110 if (!empty($user)) {
1111 $atom_feed = common_local_url('ApiTimelineUser',
1112 array('format' => 'atom',
1113 'id' => $profile->nickname));
1114 $xs->element('link', array('rel' => 'self',
1115 'type' => 'application/atom+xml',
1116 'href' => $profile->profileurl));
1117 $xs->element('link', array('rel' => 'license',
1118 'href' => common_config('license', 'url')));
1121 $xs->element('icon', null, $profile->avatarUrl(AVATAR_PROFILE_SIZE));
1124 $xs->elementStart('author');
1125 $xs->element('name', null, $profile->nickname);
1126 $xs->element('uri', null, $profile->profileurl);
1127 $xs->elementEnd('author');
1130 $xs->elementEnd('source');
1133 $xs->element('title', null, $this->content);
1134 $xs->element('summary', null, $this->content);
1136 $xs->element('link', array('rel' => 'alternate',
1137 'href' => $this->bestUrl()));
1139 $xs->element('id', null, $this->uri);
1141 $xs->element('published', null, common_date_w3dtf($this->created));
1142 $xs->element('updated', null, common_date_w3dtf($this->modified));
1144 if ($this->reply_to) {
1145 $reply_notice = Notice::staticGet('id', $this->reply_to);
1146 if (!empty($reply_notice)) {
1147 $xs->element('link', array('rel' => 'related',
1148 'href' => $reply_notice->bestUrl()));
1149 $xs->element('thr:in-reply-to',
1150 array('ref' => $reply_notice->uri,
1151 'href' => $reply_notice->bestUrl()));
1155 $xs->element('content', array('type' => 'html'), $this->rendered);
1157 $tag = new Notice_tag();
1158 $tag->notice_id = $this->id;
1160 while ($tag->fetch()) {
1161 $xs->element('category', array('term' => $tag->tag));
1167 $attachments = $this->attachments();
1169 foreach($attachments as $attachment){
1170 $enclosure=$attachment->getEnclosure();
1172 $attributes = array('rel'=>'enclosure','href'=>$enclosure->url,'type'=>$enclosure->mimetype,'length'=>$enclosure->size);
1173 if($enclosure->title){
1174 $attributes['title']=$enclosure->title;
1176 $xs->element('link', $attributes, null);
1181 if (!empty($this->lat) && !empty($this->lon)) {
1182 $xs->elementStart('geo', array('xmlns:georss' => 'http://www.georss.org/georss'));
1183 $xs->element('georss:point', null, $this->lat . ' ' . $this->lon);
1184 $xs->elementEnd('geo');
1187 $xs->elementEnd('entry');
1189 return $xs->getString();
1194 if (!empty($this->url)) {
1196 } else if (!empty($this->uri) && preg_match('/^https?:/', $this->uri)) {
1199 return common_local_url('shownotice',
1200 array('notice' => $this->id));
1204 function stream($fn, $args, $cachekey, $offset=0, $limit=20, $since_id=0, $max_id=0, $since=null)
1206 $cache = common_memcache();
1208 if (empty($cache) ||
1209 $since_id != 0 || $max_id != 0 || (!is_null($since) && $since > 0) ||
1211 ($offset + $limit) > NOTICE_CACHE_WINDOW) {
1212 return call_user_func_array($fn, array_merge($args, array($offset, $limit, $since_id,
1216 $idkey = common_cache_key($cachekey);
1218 $idstr = $cache->get($idkey);
1220 if (!empty($idstr)) {
1221 // Cache hit! Woohoo!
1222 $window = explode(',', $idstr);
1223 $ids = array_slice($window, $offset, $limit);
1227 $laststr = $cache->get($idkey.';last');
1229 if (!empty($laststr)) {
1230 $window = explode(',', $laststr);
1231 $last_id = $window[0];
1232 $new_ids = call_user_func_array($fn, array_merge($args, array(0, NOTICE_CACHE_WINDOW,
1233 $last_id, 0, null)));
1235 $new_window = array_merge($new_ids, $window);
1237 $new_windowstr = implode(',', $new_window);
1239 $result = $cache->set($idkey, $new_windowstr);
1240 $result = $cache->set($idkey . ';last', $new_windowstr);
1242 $ids = array_slice($new_window, $offset, $limit);
1247 $window = call_user_func_array($fn, array_merge($args, array(0, NOTICE_CACHE_WINDOW,
1250 $windowstr = implode(',', $window);
1252 $result = $cache->set($idkey, $windowstr);
1253 $result = $cache->set($idkey . ';last', $windowstr);
1255 $ids = array_slice($window, $offset, $limit);
1261 * Determine which notice, if any, a new notice is in reply to.
1263 * For conversation tracking, we try to see where this notice fits
1264 * in the tree. Rough algorithm is:
1266 * if (reply_to is set and valid) {
1268 * } else if ((source not API or Web) and (content starts with "T NAME" or "@name ")) {
1269 * return ID of last notice by initial @name in content;
1272 * Note that all @nickname instances will still be used to save "reply" records,
1273 * so the notice shows up in the mentioned users' "replies" tab.
1275 * @param integer $reply_to ID passed in by Web or API
1276 * @param integer $profile_id ID of author
1277 * @param string $source Source tag, like 'web' or 'gwibber'
1278 * @param string $content Final notice content
1280 * @return integer ID of replied-to notice, or null for not a reply.
1283 static function getReplyTo($reply_to, $profile_id, $source, $content)
1285 static $lb = array('xmpp', 'mail', 'sms', 'omb');
1287 // If $reply_to is specified, we check that it exists, and then
1288 // return it if it does
1290 if (!empty($reply_to)) {
1291 $reply_notice = Notice::staticGet('id', $reply_to);
1292 if (!empty($reply_notice)) {
1297 // If it's not a "low bandwidth" source (one where you can't set
1298 // a reply_to argument), we return. This is mostly web and API
1301 if (!in_array($source, $lb)) {
1305 // Is there an initial @ or T?
1307 if (preg_match('/^T ([A-Z0-9]{1,64}) /', $content, $match) ||
1308 preg_match('/^@([a-z0-9]{1,64})\s+/', $content, $match)) {
1309 $nickname = common_canonical_nickname($match[1]);
1314 // Figure out who that is.
1316 $sender = Profile::staticGet('id', $profile_id);
1317 $recipient = common_relative_profile($sender, $nickname, common_sql_now());
1319 if (empty($recipient)) {
1323 // Get their last notice
1325 $last = $recipient->getCurrentNotice();
1327 if (!empty($last)) {
1332 static function maxContent()
1334 $contentlimit = common_config('notice', 'contentlimit');
1335 // null => use global limit (distinct from 0!)
1336 if (is_null($contentlimit)) {
1337 $contentlimit = common_config('site', 'textlimit');
1339 return $contentlimit;
1342 static function contentTooLong($content)
1344 $contentlimit = self::maxContent();
1345 return ($contentlimit > 0 && !empty($content) && (mb_strlen($content) > $contentlimit));
1348 function getLocation()
1352 if (!empty($this->location_id) && !empty($this->location_ns)) {
1353 $location = Location::fromId($this->location_id, $this->location_ns);
1356 if (is_null($location)) { // no ID, or Location::fromId() failed
1357 if (!empty($this->lat) && !empty($this->lon)) {
1358 $location = Location::fromLatLon($this->lat, $this->lon);
1365 function repeat($repeater_id, $source)
1367 $author = Profile::staticGet('id', $this->profile_id);
1369 // FIXME: truncate on long repeats...?
1371 $content = sprintf(_('RT @%1$s %2$s'),
1375 return self::saveNew($repeater_id, $content, $source,
1376 array('repeat_of' => $this->id));
1379 // These are supposed to be in chron order!
1381 function repeatStream($limit=100)
1383 $cache = common_memcache();
1385 if (empty($cache)) {
1386 $ids = $this->_repeatStreamDirect($limit);
1388 $idstr = $cache->get(common_cache_key('notice:repeats:'.$this->id));
1389 if (!empty($idstr)) {
1390 $ids = explode(',', $idstr);
1392 $ids = $this->_repeatStreamDirect(100);
1393 $cache->set(common_cache_key('notice:repeats:'.$this->id), implode(',', $ids));
1396 // We do a max of 100, so slice down to limit
1397 $ids = array_slice($ids, 0, $limit);
1401 return Notice::getStreamByIds($ids);
1404 function _repeatStreamDirect($limit)
1406 $notice = new Notice();
1408 $notice->selectAdd(); // clears it
1409 $notice->selectAdd('id');
1411 $notice->repeat_of = $this->id;
1413 $notice->orderBy('created'); // NB: asc!
1415 if (!is_null($offset)) {
1416 $notice->limit($offset, $limit);
1421 if ($notice->find()) {
1422 while ($notice->fetch()) {
1423 $ids[] = $notice->id;