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/>.
20 if (!defined('STATUSNET') && !defined('LACONICA')) { exit(1); }
23 * Table Definition for notice
25 require_once INSTALLDIR.'/classes/Memcached_DataObject.php';
27 /* We keep the first three 20-notice pages, plus one for pagination check,
28 * in the memcached cache. */
30 define('NOTICE_CACHE_WINDOW', 61);
32 define('MAX_BOXCARS', 128);
34 class Notice extends Memcached_DataObject
37 /* the code below is auto generated do not remove the above tag */
39 public $__table = 'notice'; // table name
40 public $id; // int(4) primary_key not_null
41 public $profile_id; // int(4) not_null
42 public $uri; // varchar(255) unique_key
43 public $content; // varchar(140)
44 public $rendered; // text()
45 public $url; // varchar(255)
46 public $created; // datetime() not_null
47 public $modified; // timestamp() not_null default_CURRENT_TIMESTAMP
48 public $reply_to; // int(4)
49 public $is_local; // tinyint(1)
50 public $source; // varchar(32)
51 public $conversation; // int(4)
54 function staticGet($k,$v=NULL) {
55 return Memcached_DataObject::staticGet('Notice',$k,$v);
58 /* the code above is auto generated do not remove the tag below */
62 const LOCAL_PUBLIC = 1;
64 const LOCAL_NONPUBLIC = -1;
69 return Profile::staticGet('id', $this->profile_id);
74 $this->blowCaches(true);
75 $this->blowFavesCache(true);
76 $this->blowSubsCache(true);
78 $this->query('BEGIN');
79 //Null any notices that are replies to this notice
80 $this->query(sprintf("UPDATE notice set reply_to = null WHERE reply_to = %d", $this->id));
81 $related = array('Reply',
86 if (common_config('inboxes', 'enabled')) {
87 $related[] = 'Notice_inbox';
89 foreach ($related as $cls) {
91 $inst->notice_id = $this->id;
94 $result = parent::delete();
95 $this->query('COMMIT');
100 /* extract all #hastags */
101 $count = preg_match_all('/(?:^|\s)#([\pL\pN_\-\.]{1,64})/', strtolower($this->content), $match);
106 //turn each into their canonical tag
107 //this is needed to remove dupes before saving e.g. #hash.tag = #hashtag
109 for($i=0; $i<count($match[1]); $i++) {
110 $hashtags[] = common_canonical_tag($match[1][$i]);
113 /* Add them to the database */
114 foreach(array_unique($hashtags) as $hashtag) {
115 /* elide characters we don't want in the tag */
116 $this->saveTag($hashtag);
121 function saveTag($hashtag)
123 $tag = new Notice_tag();
124 $tag->notice_id = $this->id;
125 $tag->tag = $hashtag;
126 $tag->created = $this->created;
127 $id = $tag->insert();
130 throw new ServerException(sprintf(_('DB error inserting hashtag: %s'),
131 $last_error->message));
136 static function saveNew($profile_id, $content, $source=null,
137 $is_local=Notice::LOCAL_PUBLIC, $reply_to=null, $uri=null, $created=null) {
139 $profile = Profile::staticGet($profile_id);
141 $final = common_shorten_links($content);
143 if (mb_strlen($final) > 140) {
144 common_log(LOG_INFO, 'Rejecting notice that is too long.');
145 return _('Problem saving notice. Too long.');
149 common_log(LOG_ERR, 'Problem saving notice. Unknown user.');
150 return _('Problem saving notice. Unknown user.');
153 if (common_config('throttle', 'enabled') && !Notice::checkEditThrottle($profile_id)) {
154 common_log(LOG_WARNING, 'Excessive posting by profile #' . $profile_id . '; throttled.');
155 return _('Too many notices too fast; take a breather and post again in a few minutes.');
158 if (common_config('site', 'dupelimit') > 0 && !Notice::checkDupes($profile_id, $final)) {
159 common_log(LOG_WARNING, 'Dupe posting by profile #' . $profile_id . '; throttled.');
160 return _('Too many duplicate messages too quickly; take a breather and post again in a few minutes.');
163 $banned = common_config('profile', 'banned');
165 if ( in_array($profile_id, $banned) || in_array($profile->nickname, $banned)) {
166 common_log(LOG_WARNING, "Attempted post from banned user: $profile->nickname (user id = $profile_id).");
167 return _('You are banned from posting notices on this site.');
170 $notice = new Notice();
171 $notice->profile_id = $profile_id;
173 $blacklist = common_config('public', 'blacklist');
174 $autosource = common_config('public', 'autosource');
176 # Blacklisted are non-false, but not 1, either
178 if (($blacklist && in_array($profile_id, $blacklist)) ||
179 ($source && $autosource && in_array($source, $autosource))) {
180 $notice->is_local = Notice::LOCAL_NONPUBLIC;
182 $notice->is_local = $is_local;
185 if (!empty($created)) {
186 $notice->created = $created;
188 $notice->created = common_sql_now();
191 $notice->content = $final;
192 $notice->rendered = common_render_content($final, $notice);
193 $notice->source = $source;
196 $notice->reply_to = self::getReplyTo($reply_to, $profile_id, $source, $final);
198 if (!empty($notice->reply_to)) {
199 $reply = Notice::staticGet('id', $notice->reply_to);
200 $notice->conversation = $reply->conversation;
203 if (Event::handle('StartNoticeSave', array(&$notice))) {
205 // XXX: some of these functions write to the DB
207 $notice->query('BEGIN');
209 $id = $notice->insert();
212 common_log_db_error($notice, 'INSERT', __FILE__);
213 return _('Problem saving notice.');
216 // Update ID-dependent columns: URI, conversation
218 $orig = clone($notice);
223 $notice->uri = common_notice_uri($notice);
227 // If it's not part of a conversation, it's
228 // the beginning of a new conversation.
230 if (empty($notice->conversation)) {
231 $notice->conversation = $notice->id;
236 if (!$notice->update($orig)) {
237 common_log_db_error($notice, 'UPDATE', __FILE__);
238 return _('Problem saving notice.');
242 // XXX: do we need to change this for remote users?
244 $notice->saveReplies();
247 $notice->addToInboxes();
251 $notice->query('COMMIT');
253 Event::handle('EndNoticeSave', array($notice));
256 # Clear the cache for subscribed users, so they'll update at next request
257 # XXX: someone clever could prepend instead of clearing the cache
259 $notice->blowCaches();
264 /** save all urls in the notice to the db
266 * follow redirects and save all available file information
267 * (mimetype, date, size, oembed, etc.)
271 function saveUrls() {
272 common_replace_urls_callback($this->content, array($this, 'saveUrl'), $this->id);
275 function saveUrl($data) {
276 list($url, $notice_id) = $data;
277 File::processNew($url, $notice_id);
280 static function checkDupes($profile_id, $content) {
281 $profile = Profile::staticGet($profile_id);
285 $notice = $profile->getNotices(0, NOTICE_CACHE_WINDOW);
288 while ($notice->fetch()) {
289 if (time() - strtotime($notice->created) >= common_config('site', 'dupelimit')) {
291 } else if ($notice->content == $content) {
296 # If we get here, oldest item in cache window is not
297 # old enough for dupe limit; do direct check against DB
298 $notice = new Notice();
299 $notice->profile_id = $profile_id;
300 $notice->content = $content;
301 if (common_config('db','type') == 'pgsql')
302 $notice->whereAdd('extract(epoch from now() - created) < ' . common_config('site', 'dupelimit'));
304 $notice->whereAdd('now() - created < ' . common_config('site', 'dupelimit'));
306 $cnt = $notice->count();
310 static function checkEditThrottle($profile_id) {
311 $profile = Profile::staticGet($profile_id);
316 $notice = $profile->getNotices(common_config('throttle', 'count') - 1, 1);
317 if ($notice && $notice->fetch()) {
318 # If the Nth notice was posted less than timespan seconds ago
319 if (time() - strtotime($notice->created) <= common_config('throttle', 'timespan')) {
324 # Either not N notices in the stream, OR the Nth was not posted within timespan seconds
328 function getUploadedAttachment() {
330 $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"';
331 $post->query($query);
333 if (empty($post->up) || empty($post->i)) {
336 $ret = array($post->up, $post->i);
342 function hasAttachments() {
344 $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);
345 $post->query($query);
347 $n_attachments = intval($post->n_attachments);
349 return $n_attachments;
352 function attachments() {
355 $f2p = new File_to_post;
356 $f2p->post_id = $this->id;
358 while ($f2p->fetch()) {
359 $f = File::staticGet($f2p->file_id);
366 function blowCaches($blowLast=false)
368 $this->blowSubsCache($blowLast);
369 $this->blowNoticeCache($blowLast);
370 $this->blowRepliesCache($blowLast);
371 $this->blowPublicCache($blowLast);
372 $this->blowTagCache($blowLast);
373 $this->blowGroupCache($blowLast);
374 $this->blowConversationCache($blowLast);
375 $profile = Profile::staticGet($this->profile_id);
376 $profile->blowNoticeCount();
379 function blowConversationCache($blowLast=false)
381 $cache = common_memcache();
383 $ck = common_cache_key('notice:conversation_ids:'.$this->conversation);
386 $cache->delete($ck.';last');
391 function blowGroupCache($blowLast=false)
393 $cache = common_memcache();
395 $group_inbox = new Group_inbox();
396 $group_inbox->notice_id = $this->id;
397 if ($group_inbox->find()) {
398 while ($group_inbox->fetch()) {
399 $cache->delete(common_cache_key('user_group:notice_ids:' . $group_inbox->group_id));
401 $cache->delete(common_cache_key('user_group:notice_ids:' . $group_inbox->group_id.';last'));
403 $member = new Group_member();
404 $member->group_id = $group_inbox->group_id;
405 if ($member->find()) {
406 while ($member->fetch()) {
407 $cache->delete(common_cache_key('notice_inbox:by_user:' . $member->profile_id));
409 $cache->delete(common_cache_key('notice_inbox:by_user:' . $member->profile_id . ';last'));
415 $group_inbox->free();
420 function blowTagCache($blowLast=false)
422 $cache = common_memcache();
424 $tag = new Notice_tag();
425 $tag->notice_id = $this->id;
427 while ($tag->fetch()) {
428 $tag->blowCache($blowLast);
429 $ck = 'profile:notice_ids_tagged:' . $this->profile_id . ':' . $tag->tag;
433 $cache->delete($ck . ';last');
442 function blowSubsCache($blowLast=false)
444 $cache = common_memcache();
448 $UT = common_config('db','type')=='pgsql'?'"user"':'user';
449 $user->query('SELECT id ' .
451 "FROM $UT JOIN subscription ON $UT.id = subscription.subscriber " .
452 'WHERE subscription.subscribed = ' . $this->profile_id);
454 while ($user->fetch()) {
455 $cache->delete(common_cache_key('notice_inbox:by_user:'.$user->id));
456 $cache->delete(common_cache_key('notice_inbox:by_user_own:'.$user->id));
458 $cache->delete(common_cache_key('notice_inbox:by_user:'.$user->id.';last'));
459 $cache->delete(common_cache_key('notice_inbox:by_user_own:'.$user->id.';last'));
467 function blowNoticeCache($blowLast=false)
469 if ($this->is_local) {
470 $cache = common_memcache();
471 if (!empty($cache)) {
472 $cache->delete(common_cache_key('profile:notice_ids:'.$this->profile_id));
474 $cache->delete(common_cache_key('profile:notice_ids:'.$this->profile_id.';last'));
480 function blowRepliesCache($blowLast=false)
482 $cache = common_memcache();
484 $reply = new Reply();
485 $reply->notice_id = $this->id;
486 if ($reply->find()) {
487 while ($reply->fetch()) {
488 $cache->delete(common_cache_key('reply:stream:'.$reply->profile_id));
490 $cache->delete(common_cache_key('reply:stream:'.$reply->profile_id.';last'));
499 function blowPublicCache($blowLast=false)
501 if ($this->is_local == Notice::LOCAL_PUBLIC) {
502 $cache = common_memcache();
504 $cache->delete(common_cache_key('public'));
506 $cache->delete(common_cache_key('public').';last');
512 function blowFavesCache($blowLast=false)
514 $cache = common_memcache();
517 $fave->notice_id = $this->id;
519 while ($fave->fetch()) {
520 $cache->delete(common_cache_key('fave:ids_by_user:'.$fave->user_id));
521 $cache->delete(common_cache_key('fave:by_user_own:'.$fave->user_id));
523 $cache->delete(common_cache_key('fave:ids_by_user:'.$fave->user_id.';last'));
524 $cache->delete(common_cache_key('fave:by_user_own:'.$fave->user_id.';last'));
533 # XXX: too many args; we need to move to named params or even a separate
534 # class for notice streams
536 static function getStream($qry, $cachekey, $offset=0, $limit=20, $since_id=0, $max_id=0, $order=null, $since=null) {
538 if (common_config('memcached', 'enabled')) {
540 # Skip the cache if this is a since, since_id or max_id qry
541 if ($since_id > 0 || $max_id > 0 || $since) {
542 return Notice::getStreamDirect($qry, $offset, $limit, $since_id, $max_id, $order, $since);
544 return Notice::getCachedStream($qry, $cachekey, $offset, $limit, $order);
548 return Notice::getStreamDirect($qry, $offset, $limit, $since_id, $max_id, $order, $since);
551 static function getStreamDirect($qry, $offset, $limit, $since_id, $max_id, $order, $since) {
556 if (preg_match('/\bWHERE\b/i', $qry)) {
570 $qry .= ' notice.id > ' . $since_id;
582 $qry .= ' notice.id <= ' . $max_id;
594 $qry .= ' notice.created > \'' . date('Y-m-d H:i:s', $since) . '\'';
597 # Allow ORDER override
602 $qry .= ' ORDER BY notice.created DESC, notice.id DESC ';
605 if (common_config('db','type') == 'pgsql') {
606 $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
608 $qry .= ' LIMIT ' . $offset . ', ' . $limit;
611 $notice = new Notice();
613 $notice->query($qry);
618 # XXX: this is pretty long and should probably be broken up into
619 # some helper functions
621 static function getCachedStream($qry, $cachekey, $offset, $limit, $order) {
623 # If outside our cache window, just go to the DB
625 if ($offset + $limit > NOTICE_CACHE_WINDOW) {
626 return Notice::getStreamDirect($qry, $offset, $limit, null, null, $order, null);
629 # Get the cache; if we can't, just go to the DB
631 $cache = common_memcache();
634 return Notice::getStreamDirect($qry, $offset, $limit, null, null, $order, null);
637 # Get the notices out of the cache
639 $notices = $cache->get(common_cache_key($cachekey));
641 # On a cache hit, return a DB-object-like wrapper
643 if ($notices !== false) {
644 $wrapper = new ArrayWrapper(array_slice($notices, $offset, $limit));
648 # If the cache was invalidated because of new data being
649 # added, we can try and just get the new stuff. We keep an additional
650 # copy of the data at the key + ';last'
652 # No cache hit. Try to get the *last* cached version
654 $last_notices = $cache->get(common_cache_key($cachekey) . ';last');
658 # Reverse-chron order, so last ID is last.
660 $last_id = $last_notices[0]->id;
662 # XXX: this assumes monotonically increasing IDs; a fair
665 $new_notice = Notice::getStreamDirect($qry, 0, NOTICE_CACHE_WINDOW,
666 $last_id, null, $order, null);
669 $new_notices = array();
670 while ($new_notice->fetch()) {
671 $new_notices[] = clone($new_notice);
674 $notices = array_slice(array_merge($new_notices, $last_notices),
675 0, NOTICE_CACHE_WINDOW);
677 # Store the array in the cache for next time
679 $result = $cache->set(common_cache_key($cachekey), $notices);
680 $result = $cache->set(common_cache_key($cachekey) . ';last', $notices);
682 # return a wrapper of the array for use now
684 return new ArrayWrapper(array_slice($notices, $offset, $limit));
688 # Otherwise, get the full cache window out of the DB
690 $notice = Notice::getStreamDirect($qry, 0, NOTICE_CACHE_WINDOW, null, null, $order, null);
692 # If there are no hits, just return the value
698 # Pack results into an array
702 while ($notice->fetch()) {
703 $notices[] = clone($notice);
708 # Store the array in the cache for next time
710 $result = $cache->set(common_cache_key($cachekey), $notices);
711 $result = $cache->set(common_cache_key($cachekey) . ';last', $notices);
713 # return a wrapper of the array for use now
715 $wrapper = new ArrayWrapper(array_slice($notices, $offset, $limit));
720 function getStreamByIds($ids)
722 $cache = common_memcache();
724 if (!empty($cache)) {
726 foreach ($ids as $id) {
727 $n = Notice::staticGet('id', $id);
732 return new ArrayWrapper($notices);
734 $notice = new Notice();
735 $notice->whereAdd('id in (' . implode(', ', $ids) . ')');
736 $notice->orderBy('id DESC');
743 function publicStream($offset=0, $limit=20, $since_id=0, $max_id=0, $since=null)
745 $ids = Notice::stream(array('Notice', '_publicStreamDirect'),
748 $offset, $limit, $since_id, $max_id, $since);
750 return Notice::getStreamByIds($ids);
753 function _publicStreamDirect($offset=0, $limit=20, $since_id=0, $max_id=0, $since=null)
755 $notice = new Notice();
757 $notice->selectAdd(); // clears it
758 $notice->selectAdd('id');
760 $notice->orderBy('id DESC');
762 if (!is_null($offset)) {
763 $notice->limit($offset, $limit);
766 if (common_config('public', 'localonly')) {
767 $notice->whereAdd('is_local = ' . Notice::LOCAL_PUBLIC);
769 # -1 == blacklisted, -2 == gateway (i.e. Twitter)
770 $notice->whereAdd('is_local !='. Notice::LOCAL_NONPUBLIC);
771 $notice->whereAdd('is_local !='. Notice::GATEWAY);
774 if ($since_id != 0) {
775 $notice->whereAdd('id > ' . $since_id);
779 $notice->whereAdd('id <= ' . $max_id);
782 if (!is_null($since)) {
783 $notice->whereAdd('created > \'' . date('Y-m-d H:i:s', $since) . '\'');
788 if ($notice->find()) {
789 while ($notice->fetch()) {
790 $ids[] = $notice->id;
800 function conversationStream($id, $offset=0, $limit=20, $since_id=0, $max_id=0, $since=null)
802 $ids = Notice::stream(array('Notice', '_conversationStreamDirect'),
804 'notice:conversation_ids:'.$id,
805 $offset, $limit, $since_id, $max_id, $since);
807 return Notice::getStreamByIds($ids);
810 function _conversationStreamDirect($id, $offset=0, $limit=20, $since_id=0, $max_id=0, $since=null)
812 $notice = new Notice();
814 $notice->selectAdd(); // clears it
815 $notice->selectAdd('id');
817 $notice->conversation = $id;
819 $notice->orderBy('id DESC');
821 if (!is_null($offset)) {
822 $notice->limit($offset, $limit);
825 if ($since_id != 0) {
826 $notice->whereAdd('id > ' . $since_id);
830 $notice->whereAdd('id <= ' . $max_id);
833 if (!is_null($since)) {
834 $notice->whereAdd('created > \'' . date('Y-m-d H:i:s', $since) . '\'');
839 if ($notice->find()) {
840 while ($notice->fetch()) {
841 $ids[] = $notice->id;
851 function addToInboxes()
853 $enabled = common_config('inboxes', 'enabled');
855 if ($enabled === true || $enabled === 'transitional') {
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();
875 foreach ($groups as $group) {
876 $users = $group->getUserMembers();
877 foreach ($users as $id) {
878 if (!array_key_exists($id, $ni)) {
879 $ni[$id] = NOTICE_INBOX_SOURCE_GROUP;
886 $qryhdr = 'INSERT INTO notice_inbox (user_id, notice_id, source, created) VALUES ';
889 foreach ($ni as $id => $source) {
893 $qry .= '('.$id.', '.$this->id.', '.$source.", '".$this->created. "') ";
895 if (rand() % NOTICE_INBOX_SOFT_LIMIT == 0) {
896 Notice_inbox::gc($id);
898 if ($cnt >= MAX_BOXCARS) {
899 $inbox = new Notice_inbox();
907 $inbox = new Notice_inbox();
915 function getSubscribedUsers()
919 if(common_config('db','quote_identifiers'))
920 $user_table = '"user"';
921 else $user_table = 'user';
925 'FROM '. $user_table .' JOIN subscription '.
926 'ON '. $user_table .'.id = subscription.subscriber ' .
927 'WHERE subscription.subscribed = %d ';
929 $user->query(sprintf($qry, $this->profile_id));
933 while ($user->fetch()) {
942 function saveGroups()
946 $enabled = common_config('inboxes', 'enabled');
947 if ($enabled !== true && $enabled !== 'transitional') {
951 /* extract all !group */
952 $count = preg_match_all('/(?:^|\s)!([A-Za-z0-9]{1,64})/',
953 strtolower($this->content),
959 $profile = $this->getProfile();
961 /* Add them to the database */
963 foreach (array_unique($match[1]) as $nickname) {
964 /* XXX: remote groups. */
965 $group = User_group::getForNickname($nickname);
971 // we automatically add a tag for every group name, too
973 $tag = Notice_tag::pkeyGet(array('tag' => common_canonical_tag($nickname),
974 'notice_id' => $this->id));
977 $this->saveTag($nickname);
980 if ($profile->isMember($group)) {
982 $result = $this->addToGroupInbox($group);
985 common_log_db_error($gi, 'INSERT', __FILE__);
988 $groups[] = clone($group);
995 function addToGroupInbox($group)
997 $gi = Group_inbox::pkeyGet(array('group_id' => $group->id,
998 'notice_id' => $this->id));
1002 $gi = new Group_inbox();
1004 $gi->group_id = $group->id;
1005 $gi->notice_id = $this->id;
1006 $gi->created = $this->created;
1008 return $gi->insert();
1014 function saveReplies()
1016 // Alternative reply format
1018 if (preg_match('/^T ([A-Z0-9]{1,64}) /', $this->content, $match)) {
1021 // extract all @messages
1022 $cnt = preg_match_all('/(?:^|\s)@([a-z0-9]{1,64})/', $this->content, $match);
1026 if ($cnt || $tname) {
1027 // XXX: is there another way to make an array copy?
1028 $names = ($tname) ? array_unique(array_merge(array(strtolower($tname)), $match[1])) : array_unique($match[1]);
1031 $sender = Profile::staticGet($this->profile_id);
1035 // store replied only for first @ (what user/notice what the reply directed,
1036 // we assume first @ is it)
1038 for ($i=0; $i<count($names); $i++) {
1039 $nickname = $names[$i];
1040 $recipient = common_relative_profile($sender, $nickname, $this->created);
1044 // Don't save replies from blocked profile to local user
1045 $recipient_user = User::staticGet('id', $recipient->id);
1046 if ($recipient_user && $recipient_user->hasBlocked($sender)) {
1049 $reply = new Reply();
1050 $reply->notice_id = $this->id;
1051 $reply->profile_id = $recipient->id;
1052 $id = $reply->insert();
1054 $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError');
1055 common_log(LOG_ERR, 'DB error inserting reply: ' . $last_error->message);
1056 common_server_error(sprintf(_('DB error inserting reply: %s'), $last_error->message));
1059 $replied[$recipient->id] = 1;
1063 // Hash format replies, too
1064 $cnt = preg_match_all('/(?:^|\s)@#([a-z0-9]{1,64})/', $this->content, $match);
1066 foreach ($match[1] as $tag) {
1067 $tagged = Profile_tag::getTagged($sender->id, $tag);
1068 foreach ($tagged as $t) {
1069 if (!$replied[$t->id]) {
1070 // Don't save replies from blocked profile to local user
1071 $t_user = User::staticGet('id', $t->id);
1072 if ($t_user && $t_user->hasBlocked($sender)) {
1075 $reply = new Reply();
1076 $reply->notice_id = $this->id;
1077 $reply->profile_id = $t->id;
1078 $id = $reply->insert();
1080 common_log_db_error($reply, 'INSERT', __FILE__);
1083 $replied[$recipient->id] = 1;
1090 foreach (array_keys($replied) as $recipient) {
1091 $user = User::staticGet('id', $recipient);
1093 mail_notify_attn($user, $this);
1098 function asAtomEntry($namespace=false, $source=false)
1100 $profile = $this->getProfile();
1102 $xs = new XMLStringer(true);
1105 $attrs = array('xmlns' => 'http://www.w3.org/2005/Atom',
1106 'xmlns:thr' => 'http://purl.org/syndication/thread/1.0');
1111 $xs->elementStart('entry', $attrs);
1114 $xs->elementStart('source');
1115 $xs->element('title', null, $profile->nickname . " - " . common_config('site', 'name'));
1116 $xs->element('link', array('href' => $profile->profileurl));
1117 $user = User::staticGet('id', $profile->id);
1118 if (!empty($user)) {
1119 $atom_feed = common_local_url('api',
1120 array('apiaction' => 'statuses',
1121 'method' => 'user_timeline',
1122 'argument' => $profile->nickname.'.atom'));
1123 $xs->element('link', array('rel' => 'self',
1124 'type' => 'application/atom+xml',
1125 'href' => $profile->profileurl));
1126 $xs->element('link', array('rel' => 'license',
1127 'href' => common_config('license', 'url')));
1130 $xs->element('icon', null, $profile->avatarUrl(AVATAR_PROFILE_SIZE));
1133 $xs->elementStart('author');
1134 $xs->element('name', null, $profile->nickname);
1135 $xs->element('uri', null, $profile->profileurl);
1136 $xs->elementEnd('author');
1139 $xs->elementEnd('source');
1142 $xs->element('title', null, $this->content);
1143 $xs->element('summary', null, $this->content);
1145 $xs->element('link', array('rel' => 'alternate',
1146 'href' => $this->bestUrl()));
1148 $xs->element('id', null, $this->uri);
1150 $xs->element('published', null, common_date_w3dtf($this->created));
1151 $xs->element('updated', null, common_date_w3dtf($this->modified));
1153 if ($this->reply_to) {
1154 $reply_notice = Notice::staticGet('id', $this->reply_to);
1155 if (!empty($reply_notice)) {
1156 $xs->element('link', array('rel' => 'related',
1157 'href' => $reply_notice->bestUrl()));
1158 $xs->element('thr:in-reply-to',
1159 array('ref' => $reply_notice->uri,
1160 'href' => $reply_notice->bestUrl()));
1164 $xs->element('content', array('type' => 'html'), $this->rendered);
1166 $tag = new Notice_tag();
1167 $tag->notice_id = $this->id;
1169 while ($tag->fetch()) {
1170 $xs->element('category', array('term' => $tag->tag));
1176 $attachments = $this->attachments();
1178 foreach($attachments as $attachment){
1179 if ($attachment->isEnclosure()) {
1180 $attributes = array('rel'=>'enclosure','href'=>$attachment->url,'type'=>$attachment->mimetype,'length'=>$attachment->size);
1181 if($attachment->title){
1182 $attributes['title']=$attachment->title;
1184 $xs->element('link', $attributes, null);
1189 $xs->elementEnd('entry');
1191 return $xs->getString();
1196 if (!empty($this->url)) {
1198 } else if (!empty($this->uri) && preg_match('/^https?:/', $this->uri)) {
1201 return common_local_url('shownotice',
1202 array('notice' => $this->id));
1206 function stream($fn, $args, $cachekey, $offset=0, $limit=20, $since_id=0, $max_id=0, $since=null)
1208 $cache = common_memcache();
1210 if (empty($cache) ||
1211 $since_id != 0 || $max_id != 0 || (!is_null($since) && $since > 0) ||
1213 ($offset + $limit) > NOTICE_CACHE_WINDOW) {
1214 return call_user_func_array($fn, array_merge($args, array($offset, $limit, $since_id,
1218 $idkey = common_cache_key($cachekey);
1220 $idstr = $cache->get($idkey);
1222 if (!empty($idstr)) {
1223 // Cache hit! Woohoo!
1224 $window = explode(',', $idstr);
1225 $ids = array_slice($window, $offset, $limit);
1229 $laststr = $cache->get($idkey.';last');
1231 if (!empty($laststr)) {
1232 $window = explode(',', $laststr);
1233 $last_id = $window[0];
1234 $new_ids = call_user_func_array($fn, array_merge($args, array(0, NOTICE_CACHE_WINDOW,
1235 $last_id, 0, null)));
1237 $new_window = array_merge($new_ids, $window);
1239 $new_windowstr = implode(',', $new_window);
1241 $result = $cache->set($idkey, $new_windowstr);
1242 $result = $cache->set($idkey . ';last', $new_windowstr);
1244 $ids = array_slice($new_window, $offset, $limit);
1249 $window = call_user_func_array($fn, array_merge($args, array(0, NOTICE_CACHE_WINDOW,
1252 $windowstr = implode(',', $window);
1254 $result = $cache->set($idkey, $windowstr);
1255 $result = $cache->set($idkey . ';last', $windowstr);
1257 $ids = array_slice($window, $offset, $limit);
1263 * Determine which notice, if any, a new notice is in reply to.
1265 * For conversation tracking, we try to see where this notice fits
1266 * in the tree. Rough algorithm is:
1268 * if (reply_to is set and valid) {
1270 * } else if ((source not API or Web) and (content starts with "T NAME" or "@name ")) {
1271 * return ID of last notice by initial @name in content;
1274 * Note that all @nickname instances will still be used to save "reply" records,
1275 * so the notice shows up in the mentioned users' "replies" tab.
1277 * @param integer $reply_to ID passed in by Web or API
1278 * @param integer $profile_id ID of author
1279 * @param string $source Source tag, like 'web' or 'gwibber'
1280 * @param string $content Final notice content
1282 * @return integer ID of replied-to notice, or null for not a reply.
1285 static function getReplyTo($reply_to, $profile_id, $source, $content)
1287 static $lb = array('xmpp', 'mail', 'sms', 'omb');
1289 // If $reply_to is specified, we check that it exists, and then
1290 // return it if it does
1292 if (!empty($reply_to)) {
1293 $reply_notice = Notice::staticGet('id', $reply_to);
1294 if (!empty($reply_notice)) {
1299 // If it's not a "low bandwidth" source (one where you can't set
1300 // a reply_to argument), we return. This is mostly web and API
1303 if (!in_array($source, $lb)) {
1307 // Is there an initial @ or T?
1309 if (preg_match('/^T ([A-Z0-9]{1,64}) /', $content, $match) ||
1310 preg_match('/^@([a-z0-9]{1,64})\s+/', $content, $match)) {
1311 $nickname = common_canonical_nickname($match[1]);
1316 // Figure out who that is.
1318 $sender = Profile::staticGet('id', $profile_id);
1319 $recipient = common_relative_profile($sender, $nickname, common_sql_now());
1321 if (empty($recipient)) {
1325 // Get their last notice
1327 $last = $recipient->getCurrentNotice();
1329 if (!empty($last)) {