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) 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() not_null
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)
71 function staticGet($k,$v=NULL) { return Memcached_DataObject::staticGet('Notice',$k,$v); }
73 /* the code above is auto generated do not remove the tag below */
77 const LOCAL_PUBLIC = 1;
79 const LOCAL_NONPUBLIC = -1;
84 return Profile::staticGet('id', $this->profile_id);
89 $this->blowCaches(true);
90 $this->blowFavesCache(true);
91 $this->blowSubsCache(true);
93 // For auditing purposes, save a record that the notice
96 $deleted = new Deleted_notice();
98 $deleted->id = $this->id;
99 $deleted->profile_id = $this->profile_id;
100 $deleted->uri = $this->uri;
101 $deleted->created = $this->created;
102 $deleted->deleted = common_sql_now();
104 $this->query('BEGIN');
108 //Null any notices that are replies to this notice
109 $this->query(sprintf("UPDATE notice set reply_to = null WHERE reply_to = %d", $this->id));
110 $related = array('Reply',
117 foreach ($related as $cls) {
119 $inst->notice_id = $this->id;
122 $result = parent::delete();
123 $this->query('COMMIT');
128 /* extract all #hastags */
129 $count = preg_match_all('/(?:^|\s)#([\pL\pN_\-\.]{1,64})/', strtolower($this->content), $match);
134 //turn each into their canonical tag
135 //this is needed to remove dupes before saving e.g. #hash.tag = #hashtag
137 for($i=0; $i<count($match[1]); $i++) {
138 $hashtags[] = common_canonical_tag($match[1][$i]);
141 /* Add them to the database */
142 foreach(array_unique($hashtags) as $hashtag) {
143 /* elide characters we don't want in the tag */
144 $this->saveTag($hashtag);
149 function saveTag($hashtag)
151 $tag = new Notice_tag();
152 $tag->notice_id = $this->id;
153 $tag->tag = $hashtag;
154 $tag->created = $this->created;
155 $id = $tag->insert();
158 throw new ServerException(sprintf(_('DB error inserting hashtag: %s'),
159 $last_error->message));
164 static function saveNew($profile_id, $content, $source=null,
165 $is_local=Notice::LOCAL_PUBLIC, $reply_to=null, $uri=null, $created=null) {
167 $profile = Profile::staticGet($profile_id);
169 $final = common_shorten_links($content);
171 if (Notice::contentTooLong($final)) {
172 throw new ClientException(_('Problem saving notice. Too long.'));
176 throw new ClientException(_('Problem saving notice. Unknown user.'));
179 if (common_config('throttle', 'enabled') && !Notice::checkEditThrottle($profile_id)) {
180 common_log(LOG_WARNING, 'Excessive posting by profile #' . $profile_id . '; throttled.');
181 throw new ClientException(_('Too many notices too fast; take a breather '.
182 'and post again in a few minutes.'));
185 if (common_config('site', 'dupelimit') > 0 && !Notice::checkDupes($profile_id, $final)) {
186 common_log(LOG_WARNING, 'Dupe posting by profile #' . $profile_id . '; throttled.');
187 throw new ClientException(_('Too many duplicate messages too quickly;'.
188 ' take a breather and post again in a few minutes.'));
191 $banned = common_config('profile', 'banned');
193 if ( in_array($profile_id, $banned) || in_array($profile->nickname, $banned)) {
194 common_log(LOG_WARNING, "Attempted post from banned user: $profile->nickname (user id = $profile_id).");
195 throw new ClientException(_('You are banned from posting notices on this site.'));
198 $notice = new Notice();
199 $notice->profile_id = $profile_id;
201 $blacklist = common_config('public', 'blacklist');
202 $autosource = common_config('public', 'autosource');
204 # Blacklisted are non-false, but not 1, either
206 if (($blacklist && in_array($profile_id, $blacklist)) ||
207 ($source && $autosource && in_array($source, $autosource))) {
208 $notice->is_local = Notice::LOCAL_NONPUBLIC;
210 $notice->is_local = $is_local;
213 if (!empty($created)) {
214 $notice->created = $created;
216 $notice->created = common_sql_now();
219 $notice->content = $final;
220 $notice->rendered = common_render_content($final, $notice);
221 $notice->source = $source;
224 $notice->reply_to = self::getReplyTo($reply_to, $profile_id, $source, $final);
226 if (!empty($notice->reply_to)) {
227 $reply = Notice::staticGet('id', $notice->reply_to);
228 $notice->conversation = $reply->conversation;
231 if (Event::handle('StartNoticeSave', array(&$notice))) {
233 // XXX: some of these functions write to the DB
235 $notice->query('BEGIN');
237 $id = $notice->insert();
240 common_log_db_error($notice, 'INSERT', __FILE__);
241 throw new ServerException(_('Problem saving notice.'));
244 // Update ID-dependent columns: URI, conversation
246 $orig = clone($notice);
251 $notice->uri = common_notice_uri($notice);
255 // If it's not part of a conversation, it's
256 // the beginning of a new conversation.
258 if (empty($notice->conversation)) {
259 $notice->conversation = $notice->id;
264 if (!$notice->update($orig)) {
265 common_log_db_error($notice, 'UPDATE', __FILE__);
266 throw new ServerException(_('Problem saving notice.'));
270 // XXX: do we need to change this for remote users?
272 $notice->saveReplies();
275 $notice->addToInboxes();
279 $notice->query('COMMIT');
281 Event::handle('EndNoticeSave', array($notice));
284 # Clear the cache for subscribed users, so they'll update at next request
285 # XXX: someone clever could prepend instead of clearing the cache
287 $notice->blowCaches();
292 /** save all urls in the notice to the db
294 * follow redirects and save all available file information
295 * (mimetype, date, size, oembed, etc.)
299 function saveUrls() {
300 common_replace_urls_callback($this->content, array($this, 'saveUrl'), $this->id);
303 function saveUrl($data) {
304 list($url, $notice_id) = $data;
305 File::processNew($url, $notice_id);
308 static function checkDupes($profile_id, $content) {
309 $profile = Profile::staticGet($profile_id);
313 $notice = $profile->getNotices(0, NOTICE_CACHE_WINDOW);
316 while ($notice->fetch()) {
317 if (time() - strtotime($notice->created) >= common_config('site', 'dupelimit')) {
319 } else if ($notice->content == $content) {
324 # If we get here, oldest item in cache window is not
325 # old enough for dupe limit; do direct check against DB
326 $notice = new Notice();
327 $notice->profile_id = $profile_id;
328 $notice->content = $content;
329 if (common_config('db','type') == 'pgsql')
330 $notice->whereAdd('extract(epoch from now() - created) < ' . common_config('site', 'dupelimit'));
332 $notice->whereAdd('now() - created < ' . common_config('site', 'dupelimit'));
334 $cnt = $notice->count();
338 static function checkEditThrottle($profile_id) {
339 $profile = Profile::staticGet($profile_id);
344 $notice = $profile->getNotices(common_config('throttle', 'count') - 1, 1);
345 if ($notice && $notice->fetch()) {
346 # If the Nth notice was posted less than timespan seconds ago
347 if (time() - strtotime($notice->created) <= common_config('throttle', 'timespan')) {
352 # Either not N notices in the stream, OR the Nth was not posted within timespan seconds
356 function getUploadedAttachment() {
358 $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"';
359 $post->query($query);
361 if (empty($post->up) || empty($post->i)) {
364 $ret = array($post->up, $post->i);
370 function hasAttachments() {
372 $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);
373 $post->query($query);
375 $n_attachments = intval($post->n_attachments);
377 return $n_attachments;
380 function attachments() {
383 $f2p = new File_to_post;
384 $f2p->post_id = $this->id;
386 while ($f2p->fetch()) {
387 $f = File::staticGet($f2p->file_id);
394 function blowCaches($blowLast=false)
396 $this->blowSubsCache($blowLast);
397 $this->blowNoticeCache($blowLast);
398 $this->blowRepliesCache($blowLast);
399 $this->blowPublicCache($blowLast);
400 $this->blowTagCache($blowLast);
401 $this->blowGroupCache($blowLast);
402 $this->blowConversationCache($blowLast);
403 $profile = Profile::staticGet($this->profile_id);
404 $profile->blowNoticeCount();
407 function blowConversationCache($blowLast=false)
409 $cache = common_memcache();
411 $ck = common_cache_key('notice:conversation_ids:'.$this->conversation);
414 $cache->delete($ck.';last');
419 function blowGroupCache($blowLast=false)
421 $cache = common_memcache();
423 $group_inbox = new Group_inbox();
424 $group_inbox->notice_id = $this->id;
425 if ($group_inbox->find()) {
426 while ($group_inbox->fetch()) {
427 $cache->delete(common_cache_key('user_group:notice_ids:' . $group_inbox->group_id));
429 $cache->delete(common_cache_key('user_group:notice_ids:' . $group_inbox->group_id.';last'));
431 $member = new Group_member();
432 $member->group_id = $group_inbox->group_id;
433 if ($member->find()) {
434 while ($member->fetch()) {
435 $cache->delete(common_cache_key('notice_inbox:by_user:' . $member->profile_id));
437 $cache->delete(common_cache_key('notice_inbox:by_user:' . $member->profile_id . ';last'));
443 $group_inbox->free();
448 function blowTagCache($blowLast=false)
450 $cache = common_memcache();
452 $tag = new Notice_tag();
453 $tag->notice_id = $this->id;
455 while ($tag->fetch()) {
456 $tag->blowCache($blowLast);
457 $ck = 'profile:notice_ids_tagged:' . $this->profile_id . ':' . $tag->tag;
461 $cache->delete($ck . ';last');
470 function blowSubsCache($blowLast=false)
472 $cache = common_memcache();
476 $UT = common_config('db','type')=='pgsql'?'"user"':'user';
477 $user->query('SELECT id ' .
479 "FROM $UT JOIN subscription ON $UT.id = subscription.subscriber " .
480 'WHERE subscription.subscribed = ' . $this->profile_id);
482 while ($user->fetch()) {
483 $cache->delete(common_cache_key('notice_inbox:by_user:'.$user->id));
484 $cache->delete(common_cache_key('notice_inbox:by_user_own:'.$user->id));
486 $cache->delete(common_cache_key('notice_inbox:by_user:'.$user->id.';last'));
487 $cache->delete(common_cache_key('notice_inbox:by_user_own:'.$user->id.';last'));
495 function blowNoticeCache($blowLast=false)
497 if ($this->is_local) {
498 $cache = common_memcache();
499 if (!empty($cache)) {
500 $cache->delete(common_cache_key('profile:notice_ids:'.$this->profile_id));
502 $cache->delete(common_cache_key('profile:notice_ids:'.$this->profile_id.';last'));
508 function blowRepliesCache($blowLast=false)
510 $cache = common_memcache();
512 $reply = new Reply();
513 $reply->notice_id = $this->id;
514 if ($reply->find()) {
515 while ($reply->fetch()) {
516 $cache->delete(common_cache_key('reply:stream:'.$reply->profile_id));
518 $cache->delete(common_cache_key('reply:stream:'.$reply->profile_id.';last'));
527 function blowPublicCache($blowLast=false)
529 if ($this->is_local == Notice::LOCAL_PUBLIC) {
530 $cache = common_memcache();
532 $cache->delete(common_cache_key('public'));
534 $cache->delete(common_cache_key('public').';last');
540 function blowFavesCache($blowLast=false)
542 $cache = common_memcache();
545 $fave->notice_id = $this->id;
547 while ($fave->fetch()) {
548 $cache->delete(common_cache_key('fave:ids_by_user:'.$fave->user_id));
549 $cache->delete(common_cache_key('fave:by_user_own:'.$fave->user_id));
551 $cache->delete(common_cache_key('fave:ids_by_user:'.$fave->user_id.';last'));
552 $cache->delete(common_cache_key('fave:by_user_own:'.$fave->user_id.';last'));
561 # XXX: too many args; we need to move to named params or even a separate
562 # class for notice streams
564 static function getStream($qry, $cachekey, $offset=0, $limit=20, $since_id=0, $max_id=0, $order=null, $since=null) {
566 if (common_config('memcached', 'enabled')) {
568 # Skip the cache if this is a since, since_id or max_id qry
569 if ($since_id > 0 || $max_id > 0 || $since) {
570 return Notice::getStreamDirect($qry, $offset, $limit, $since_id, $max_id, $order, $since);
572 return Notice::getCachedStream($qry, $cachekey, $offset, $limit, $order);
576 return Notice::getStreamDirect($qry, $offset, $limit, $since_id, $max_id, $order, $since);
579 static function getStreamDirect($qry, $offset, $limit, $since_id, $max_id, $order, $since) {
584 if (preg_match('/\bWHERE\b/i', $qry)) {
598 $qry .= ' notice.id > ' . $since_id;
610 $qry .= ' notice.id <= ' . $max_id;
622 $qry .= ' notice.created > \'' . date('Y-m-d H:i:s', $since) . '\'';
625 # Allow ORDER override
630 $qry .= ' ORDER BY notice.created DESC, notice.id DESC ';
633 if (common_config('db','type') == 'pgsql') {
634 $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
636 $qry .= ' LIMIT ' . $offset . ', ' . $limit;
639 $notice = new Notice();
641 $notice->query($qry);
646 # XXX: this is pretty long and should probably be broken up into
647 # some helper functions
649 static function getCachedStream($qry, $cachekey, $offset, $limit, $order) {
651 # If outside our cache window, just go to the DB
653 if ($offset + $limit > NOTICE_CACHE_WINDOW) {
654 return Notice::getStreamDirect($qry, $offset, $limit, null, null, $order, null);
657 # Get the cache; if we can't, just go to the DB
659 $cache = common_memcache();
662 return Notice::getStreamDirect($qry, $offset, $limit, null, null, $order, null);
665 # Get the notices out of the cache
667 $notices = $cache->get(common_cache_key($cachekey));
669 # On a cache hit, return a DB-object-like wrapper
671 if ($notices !== false) {
672 $wrapper = new ArrayWrapper(array_slice($notices, $offset, $limit));
676 # If the cache was invalidated because of new data being
677 # added, we can try and just get the new stuff. We keep an additional
678 # copy of the data at the key + ';last'
680 # No cache hit. Try to get the *last* cached version
682 $last_notices = $cache->get(common_cache_key($cachekey) . ';last');
686 # Reverse-chron order, so last ID is last.
688 $last_id = $last_notices[0]->id;
690 # XXX: this assumes monotonically increasing IDs; a fair
693 $new_notice = Notice::getStreamDirect($qry, 0, NOTICE_CACHE_WINDOW,
694 $last_id, null, $order, null);
697 $new_notices = array();
698 while ($new_notice->fetch()) {
699 $new_notices[] = clone($new_notice);
702 $notices = array_slice(array_merge($new_notices, $last_notices),
703 0, NOTICE_CACHE_WINDOW);
705 # Store the array in the cache for next time
707 $result = $cache->set(common_cache_key($cachekey), $notices);
708 $result = $cache->set(common_cache_key($cachekey) . ';last', $notices);
710 # return a wrapper of the array for use now
712 return new ArrayWrapper(array_slice($notices, $offset, $limit));
716 # Otherwise, get the full cache window out of the DB
718 $notice = Notice::getStreamDirect($qry, 0, NOTICE_CACHE_WINDOW, null, null, $order, null);
720 # If there are no hits, just return the value
726 # Pack results into an array
730 while ($notice->fetch()) {
731 $notices[] = clone($notice);
736 # Store the array in the cache for next time
738 $result = $cache->set(common_cache_key($cachekey), $notices);
739 $result = $cache->set(common_cache_key($cachekey) . ';last', $notices);
741 # return a wrapper of the array for use now
743 $wrapper = new ArrayWrapper(array_slice($notices, $offset, $limit));
748 function getStreamByIds($ids)
750 $cache = common_memcache();
752 if (!empty($cache)) {
754 foreach ($ids as $id) {
755 $n = Notice::staticGet('id', $id);
760 return new ArrayWrapper($notices);
762 $notice = new Notice();
764 //if no IDs requested, just return the notice object
767 $notice->whereAdd('id in (' . implode(', ', $ids) . ')');
768 $notice->orderBy('id DESC');
775 function publicStream($offset=0, $limit=20, $since_id=0, $max_id=0, $since=null)
777 $ids = Notice::stream(array('Notice', '_publicStreamDirect'),
780 $offset, $limit, $since_id, $max_id, $since);
782 return Notice::getStreamByIds($ids);
785 function _publicStreamDirect($offset=0, $limit=20, $since_id=0, $max_id=0, $since=null)
787 $notice = new Notice();
789 $notice->selectAdd(); // clears it
790 $notice->selectAdd('id');
792 $notice->orderBy('id DESC');
794 if (!is_null($offset)) {
795 $notice->limit($offset, $limit);
798 if (common_config('public', 'localonly')) {
799 $notice->whereAdd('is_local = ' . Notice::LOCAL_PUBLIC);
801 # -1 == blacklisted, -2 == gateway (i.e. Twitter)
802 $notice->whereAdd('is_local !='. Notice::LOCAL_NONPUBLIC);
803 $notice->whereAdd('is_local !='. Notice::GATEWAY);
806 if ($since_id != 0) {
807 $notice->whereAdd('id > ' . $since_id);
811 $notice->whereAdd('id <= ' . $max_id);
814 if (!is_null($since)) {
815 $notice->whereAdd('created > \'' . date('Y-m-d H:i:s', $since) . '\'');
820 if ($notice->find()) {
821 while ($notice->fetch()) {
822 $ids[] = $notice->id;
832 function conversationStream($id, $offset=0, $limit=20, $since_id=0, $max_id=0, $since=null)
834 $ids = Notice::stream(array('Notice', '_conversationStreamDirect'),
836 'notice:conversation_ids:'.$id,
837 $offset, $limit, $since_id, $max_id, $since);
839 return Notice::getStreamByIds($ids);
842 function _conversationStreamDirect($id, $offset=0, $limit=20, $since_id=0, $max_id=0, $since=null)
844 $notice = new Notice();
846 $notice->selectAdd(); // clears it
847 $notice->selectAdd('id');
849 $notice->conversation = $id;
851 $notice->orderBy('id DESC');
853 if (!is_null($offset)) {
854 $notice->limit($offset, $limit);
857 if ($since_id != 0) {
858 $notice->whereAdd('id > ' . $since_id);
862 $notice->whereAdd('id <= ' . $max_id);
865 if (!is_null($since)) {
866 $notice->whereAdd('created > \'' . date('Y-m-d H:i:s', $since) . '\'');
871 if ($notice->find()) {
872 while ($notice->fetch()) {
873 $ids[] = $notice->id;
883 function addToInboxes()
885 // XXX: loads constants
887 $inbox = new Notice_inbox();
889 $users = $this->getSubscribedUsers();
891 // FIXME: kind of ignoring 'transitional'...
892 // we'll probably stop supporting inboxless mode
897 foreach ($users as $id) {
898 $ni[$id] = NOTICE_INBOX_SOURCE_SUB;
901 $groups = $this->saveGroups();
903 foreach ($groups as $group) {
904 $users = $group->getUserMembers();
905 foreach ($users as $id) {
906 if (!array_key_exists($id, $ni)) {
907 $ni[$id] = NOTICE_INBOX_SOURCE_GROUP;
914 $qryhdr = 'INSERT INTO notice_inbox (user_id, notice_id, source, created) VALUES ';
917 foreach ($ni as $id => $source) {
921 $qry .= '('.$id.', '.$this->id.', '.$source.", '".$this->created. "') ";
923 if (rand() % NOTICE_INBOX_SOFT_LIMIT == 0) {
924 // FIXME: Causes lag in replicated servers
925 // Notice_inbox::gc($id);
927 if ($cnt >= MAX_BOXCARS) {
928 $inbox = new Notice_inbox();
936 $inbox = new Notice_inbox();
943 function getSubscribedUsers()
947 if(common_config('db','quote_identifiers'))
948 $user_table = '"user"';
949 else $user_table = 'user';
953 'FROM '. $user_table .' JOIN subscription '.
954 'ON '. $user_table .'.id = subscription.subscriber ' .
955 'WHERE subscription.subscribed = %d ';
957 $user->query(sprintf($qry, $this->profile_id));
961 while ($user->fetch()) {
970 function saveGroups()
974 /* extract all !group */
975 $count = preg_match_all('/(?:^|\s)!([A-Za-z0-9]{1,64})/',
976 strtolower($this->content),
982 $profile = $this->getProfile();
984 /* Add them to the database */
986 foreach (array_unique($match[1]) as $nickname) {
987 /* XXX: remote groups. */
988 $group = User_group::getForNickname($nickname);
994 // we automatically add a tag for every group name, too
996 $tag = Notice_tag::pkeyGet(array('tag' => common_canonical_tag($nickname),
997 'notice_id' => $this->id));
1000 $this->saveTag($nickname);
1003 if ($profile->isMember($group)) {
1005 $result = $this->addToGroupInbox($group);
1008 common_log_db_error($gi, 'INSERT', __FILE__);
1011 $groups[] = clone($group);
1018 function addToGroupInbox($group)
1020 $gi = Group_inbox::pkeyGet(array('group_id' => $group->id,
1021 'notice_id' => $this->id));
1025 $gi = new Group_inbox();
1027 $gi->group_id = $group->id;
1028 $gi->notice_id = $this->id;
1029 $gi->created = $this->created;
1031 return $gi->insert();
1037 function saveReplies()
1039 // Alternative reply format
1041 if (preg_match('/^T ([A-Z0-9]{1,64}) /', $this->content, $match)) {
1044 // extract all @messages
1045 $cnt = preg_match_all('/(?:^|\s)@([a-z0-9]{1,64})/', $this->content, $match);
1049 if ($cnt || $tname) {
1050 // XXX: is there another way to make an array copy?
1051 $names = ($tname) ? array_unique(array_merge(array(strtolower($tname)), $match[1])) : array_unique($match[1]);
1054 $sender = Profile::staticGet($this->profile_id);
1058 // store replied only for first @ (what user/notice what the reply directed,
1059 // we assume first @ is it)
1061 for ($i=0; $i<count($names); $i++) {
1062 $nickname = $names[$i];
1063 $recipient = common_relative_profile($sender, $nickname, $this->created);
1067 // Don't save replies from blocked profile to local user
1068 $recipient_user = User::staticGet('id', $recipient->id);
1069 if ($recipient_user && $recipient_user->hasBlocked($sender)) {
1072 $reply = new Reply();
1073 $reply->notice_id = $this->id;
1074 $reply->profile_id = $recipient->id;
1075 $id = $reply->insert();
1077 $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError');
1078 common_log(LOG_ERR, 'DB error inserting reply: ' . $last_error->message);
1079 common_server_error(sprintf(_('DB error inserting reply: %s'), $last_error->message));
1082 $replied[$recipient->id] = 1;
1086 // Hash format replies, too
1087 $cnt = preg_match_all('/(?:^|\s)@#([a-z0-9]{1,64})/', $this->content, $match);
1089 foreach ($match[1] as $tag) {
1090 $tagged = Profile_tag::getTagged($sender->id, $tag);
1091 foreach ($tagged as $t) {
1092 if (!$replied[$t->id]) {
1093 // Don't save replies from blocked profile to local user
1094 $t_user = User::staticGet('id', $t->id);
1095 if ($t_user && $t_user->hasBlocked($sender)) {
1098 $reply = new Reply();
1099 $reply->notice_id = $this->id;
1100 $reply->profile_id = $t->id;
1101 $id = $reply->insert();
1103 common_log_db_error($reply, 'INSERT', __FILE__);
1106 $replied[$recipient->id] = 1;
1113 foreach (array_keys($replied) as $recipient) {
1114 $user = User::staticGet('id', $recipient);
1116 mail_notify_attn($user, $this);
1121 function asAtomEntry($namespace=false, $source=false)
1123 $profile = $this->getProfile();
1125 $xs = new XMLStringer(true);
1128 $attrs = array('xmlns' => 'http://www.w3.org/2005/Atom',
1129 'xmlns:thr' => 'http://purl.org/syndication/thread/1.0');
1134 $xs->elementStart('entry', $attrs);
1137 $xs->elementStart('source');
1138 $xs->element('title', null, $profile->nickname . " - " . common_config('site', 'name'));
1139 $xs->element('link', array('href' => $profile->profileurl));
1140 $user = User::staticGet('id', $profile->id);
1141 if (!empty($user)) {
1142 $atom_feed = common_local_url('api',
1143 array('apiaction' => 'statuses',
1144 'method' => 'user_timeline',
1145 'argument' => $profile->nickname.'.atom'));
1146 $xs->element('link', array('rel' => 'self',
1147 'type' => 'application/atom+xml',
1148 'href' => $profile->profileurl));
1149 $xs->element('link', array('rel' => 'license',
1150 'href' => common_config('license', 'url')));
1153 $xs->element('icon', null, $profile->avatarUrl(AVATAR_PROFILE_SIZE));
1156 $xs->elementStart('author');
1157 $xs->element('name', null, $profile->nickname);
1158 $xs->element('uri', null, $profile->profileurl);
1159 $xs->elementEnd('author');
1162 $xs->elementEnd('source');
1165 $xs->element('title', null, $this->content);
1166 $xs->element('summary', null, $this->content);
1168 $xs->element('link', array('rel' => 'alternate',
1169 'href' => $this->bestUrl()));
1171 $xs->element('id', null, $this->uri);
1173 $xs->element('published', null, common_date_w3dtf($this->created));
1174 $xs->element('updated', null, common_date_w3dtf($this->modified));
1176 if ($this->reply_to) {
1177 $reply_notice = Notice::staticGet('id', $this->reply_to);
1178 if (!empty($reply_notice)) {
1179 $xs->element('link', array('rel' => 'related',
1180 'href' => $reply_notice->bestUrl()));
1181 $xs->element('thr:in-reply-to',
1182 array('ref' => $reply_notice->uri,
1183 'href' => $reply_notice->bestUrl()));
1187 $xs->element('content', array('type' => 'html'), $this->rendered);
1189 $tag = new Notice_tag();
1190 $tag->notice_id = $this->id;
1192 while ($tag->fetch()) {
1193 $xs->element('category', array('term' => $tag->tag));
1199 $attachments = $this->attachments();
1201 foreach($attachments as $attachment){
1202 $enclosure=$attachment->getEnclosure();
1204 $attributes = array('rel'=>'enclosure','href'=>$enclosure->url,'type'=>$enclosure->mimetype,'length'=>$enclosure->size);
1205 if($enclosure->title){
1206 $attributes['title']=$enclosure->title;
1208 $xs->element('link', $attributes, null);
1213 $xs->elementEnd('entry');
1215 return $xs->getString();
1220 if (!empty($this->url)) {
1222 } else if (!empty($this->uri) && preg_match('/^https?:/', $this->uri)) {
1225 return common_local_url('shownotice',
1226 array('notice' => $this->id));
1230 function stream($fn, $args, $cachekey, $offset=0, $limit=20, $since_id=0, $max_id=0, $since=null)
1232 $cache = common_memcache();
1234 if (empty($cache) ||
1235 $since_id != 0 || $max_id != 0 || (!is_null($since) && $since > 0) ||
1237 ($offset + $limit) > NOTICE_CACHE_WINDOW) {
1238 return call_user_func_array($fn, array_merge($args, array($offset, $limit, $since_id,
1242 $idkey = common_cache_key($cachekey);
1244 $idstr = $cache->get($idkey);
1246 if (!empty($idstr)) {
1247 // Cache hit! Woohoo!
1248 $window = explode(',', $idstr);
1249 $ids = array_slice($window, $offset, $limit);
1253 $laststr = $cache->get($idkey.';last');
1255 if (!empty($laststr)) {
1256 $window = explode(',', $laststr);
1257 $last_id = $window[0];
1258 $new_ids = call_user_func_array($fn, array_merge($args, array(0, NOTICE_CACHE_WINDOW,
1259 $last_id, 0, null)));
1261 $new_window = array_merge($new_ids, $window);
1263 $new_windowstr = implode(',', $new_window);
1265 $result = $cache->set($idkey, $new_windowstr);
1266 $result = $cache->set($idkey . ';last', $new_windowstr);
1268 $ids = array_slice($new_window, $offset, $limit);
1273 $window = call_user_func_array($fn, array_merge($args, array(0, NOTICE_CACHE_WINDOW,
1276 $windowstr = implode(',', $window);
1278 $result = $cache->set($idkey, $windowstr);
1279 $result = $cache->set($idkey . ';last', $windowstr);
1281 $ids = array_slice($window, $offset, $limit);
1287 * Determine which notice, if any, a new notice is in reply to.
1289 * For conversation tracking, we try to see where this notice fits
1290 * in the tree. Rough algorithm is:
1292 * if (reply_to is set and valid) {
1294 * } else if ((source not API or Web) and (content starts with "T NAME" or "@name ")) {
1295 * return ID of last notice by initial @name in content;
1298 * Note that all @nickname instances will still be used to save "reply" records,
1299 * so the notice shows up in the mentioned users' "replies" tab.
1301 * @param integer $reply_to ID passed in by Web or API
1302 * @param integer $profile_id ID of author
1303 * @param string $source Source tag, like 'web' or 'gwibber'
1304 * @param string $content Final notice content
1306 * @return integer ID of replied-to notice, or null for not a reply.
1309 static function getReplyTo($reply_to, $profile_id, $source, $content)
1311 static $lb = array('xmpp', 'mail', 'sms', 'omb');
1313 // If $reply_to is specified, we check that it exists, and then
1314 // return it if it does
1316 if (!empty($reply_to)) {
1317 $reply_notice = Notice::staticGet('id', $reply_to);
1318 if (!empty($reply_notice)) {
1323 // If it's not a "low bandwidth" source (one where you can't set
1324 // a reply_to argument), we return. This is mostly web and API
1327 if (!in_array($source, $lb)) {
1331 // Is there an initial @ or T?
1333 if (preg_match('/^T ([A-Z0-9]{1,64}) /', $content, $match) ||
1334 preg_match('/^@([a-z0-9]{1,64})\s+/', $content, $match)) {
1335 $nickname = common_canonical_nickname($match[1]);
1340 // Figure out who that is.
1342 $sender = Profile::staticGet('id', $profile_id);
1343 $recipient = common_relative_profile($sender, $nickname, common_sql_now());
1345 if (empty($recipient)) {
1349 // Get their last notice
1351 $last = $recipient->getCurrentNotice();
1353 if (!empty($last)) {
1358 static function maxContent()
1360 $contentlimit = common_config('notice', 'contentlimit');
1361 // null => use global limit (distinct from 0!)
1362 if (is_null($contentlimit)) {
1363 $contentlimit = common_config('site', 'textlimit');
1365 return $contentlimit;
1368 static function contentTooLong($content)
1370 $contentlimit = self::maxContent();
1371 return ($contentlimit > 0 && !empty($content) && (mb_strlen($content) > $contentlimit));