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();
736 //if no IDs requested, just return the notice object
739 $notice->whereAdd('id in (' . implode(', ', $ids) . ')');
740 $notice->orderBy('id DESC');
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 $enabled = common_config('inboxes', 'enabled');
859 if ($enabled === true || $enabled === 'transitional') {
861 // XXX: loads constants
863 $inbox = new Notice_inbox();
865 $users = $this->getSubscribedUsers();
867 // FIXME: kind of ignoring 'transitional'...
868 // we'll probably stop supporting inboxless mode
873 foreach ($users as $id) {
874 $ni[$id] = NOTICE_INBOX_SOURCE_SUB;
877 $groups = $this->saveGroups();
879 foreach ($groups as $group) {
880 $users = $group->getUserMembers();
881 foreach ($users as $id) {
882 if (!array_key_exists($id, $ni)) {
883 $ni[$id] = NOTICE_INBOX_SOURCE_GROUP;
890 $qryhdr = 'INSERT INTO notice_inbox (user_id, notice_id, source, created) VALUES ';
893 foreach ($ni as $id => $source) {
897 $qry .= '('.$id.', '.$this->id.', '.$source.", '".$this->created. "') ";
899 if (rand() % NOTICE_INBOX_SOFT_LIMIT == 0) {
900 // FIXME: Causes lag in replicated servers
901 // Notice_inbox::gc($id);
903 if ($cnt >= MAX_BOXCARS) {
904 $inbox = new Notice_inbox();
912 $inbox = new Notice_inbox();
920 function getSubscribedUsers()
924 if(common_config('db','quote_identifiers'))
925 $user_table = '"user"';
926 else $user_table = 'user';
930 'FROM '. $user_table .' JOIN subscription '.
931 'ON '. $user_table .'.id = subscription.subscriber ' .
932 'WHERE subscription.subscribed = %d ';
934 $user->query(sprintf($qry, $this->profile_id));
938 while ($user->fetch()) {
947 function saveGroups()
951 $enabled = common_config('inboxes', 'enabled');
952 if ($enabled !== true && $enabled !== 'transitional') {
956 /* extract all !group */
957 $count = preg_match_all('/(?:^|\s)!([A-Za-z0-9]{1,64})/',
958 strtolower($this->content),
964 $profile = $this->getProfile();
966 /* Add them to the database */
968 foreach (array_unique($match[1]) as $nickname) {
969 /* XXX: remote groups. */
970 $group = User_group::getForNickname($nickname);
976 // we automatically add a tag for every group name, too
978 $tag = Notice_tag::pkeyGet(array('tag' => common_canonical_tag($nickname),
979 'notice_id' => $this->id));
982 $this->saveTag($nickname);
985 if ($profile->isMember($group)) {
987 $result = $this->addToGroupInbox($group);
990 common_log_db_error($gi, 'INSERT', __FILE__);
993 $groups[] = clone($group);
1000 function addToGroupInbox($group)
1002 $gi = Group_inbox::pkeyGet(array('group_id' => $group->id,
1003 'notice_id' => $this->id));
1007 $gi = new Group_inbox();
1009 $gi->group_id = $group->id;
1010 $gi->notice_id = $this->id;
1011 $gi->created = $this->created;
1013 return $gi->insert();
1019 function saveReplies()
1021 // Alternative reply format
1023 if (preg_match('/^T ([A-Z0-9]{1,64}) /', $this->content, $match)) {
1026 // extract all @messages
1027 $cnt = preg_match_all('/(?:^|\s)@([a-z0-9]{1,64})/', $this->content, $match);
1031 if ($cnt || $tname) {
1032 // XXX: is there another way to make an array copy?
1033 $names = ($tname) ? array_unique(array_merge(array(strtolower($tname)), $match[1])) : array_unique($match[1]);
1036 $sender = Profile::staticGet($this->profile_id);
1040 // store replied only for first @ (what user/notice what the reply directed,
1041 // we assume first @ is it)
1043 for ($i=0; $i<count($names); $i++) {
1044 $nickname = $names[$i];
1045 $recipient = common_relative_profile($sender, $nickname, $this->created);
1049 // Don't save replies from blocked profile to local user
1050 $recipient_user = User::staticGet('id', $recipient->id);
1051 if ($recipient_user && $recipient_user->hasBlocked($sender)) {
1054 $reply = new Reply();
1055 $reply->notice_id = $this->id;
1056 $reply->profile_id = $recipient->id;
1057 $id = $reply->insert();
1059 $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError');
1060 common_log(LOG_ERR, 'DB error inserting reply: ' . $last_error->message);
1061 common_server_error(sprintf(_('DB error inserting reply: %s'), $last_error->message));
1064 $replied[$recipient->id] = 1;
1068 // Hash format replies, too
1069 $cnt = preg_match_all('/(?:^|\s)@#([a-z0-9]{1,64})/', $this->content, $match);
1071 foreach ($match[1] as $tag) {
1072 $tagged = Profile_tag::getTagged($sender->id, $tag);
1073 foreach ($tagged as $t) {
1074 if (!$replied[$t->id]) {
1075 // Don't save replies from blocked profile to local user
1076 $t_user = User::staticGet('id', $t->id);
1077 if ($t_user && $t_user->hasBlocked($sender)) {
1080 $reply = new Reply();
1081 $reply->notice_id = $this->id;
1082 $reply->profile_id = $t->id;
1083 $id = $reply->insert();
1085 common_log_db_error($reply, 'INSERT', __FILE__);
1088 $replied[$recipient->id] = 1;
1095 foreach (array_keys($replied) as $recipient) {
1096 $user = User::staticGet('id', $recipient);
1098 mail_notify_attn($user, $this);
1103 function asAtomEntry($namespace=false, $source=false)
1105 $profile = $this->getProfile();
1107 $xs = new XMLStringer(true);
1110 $attrs = array('xmlns' => 'http://www.w3.org/2005/Atom',
1111 'xmlns:thr' => 'http://purl.org/syndication/thread/1.0');
1116 $xs->elementStart('entry', $attrs);
1119 $xs->elementStart('source');
1120 $xs->element('title', null, $profile->nickname . " - " . common_config('site', 'name'));
1121 $xs->element('link', array('href' => $profile->profileurl));
1122 $user = User::staticGet('id', $profile->id);
1123 if (!empty($user)) {
1124 $atom_feed = common_local_url('api',
1125 array('apiaction' => 'statuses',
1126 'method' => 'user_timeline',
1127 'argument' => $profile->nickname.'.atom'));
1128 $xs->element('link', array('rel' => 'self',
1129 'type' => 'application/atom+xml',
1130 'href' => $profile->profileurl));
1131 $xs->element('link', array('rel' => 'license',
1132 'href' => common_config('license', 'url')));
1135 $xs->element('icon', null, $profile->avatarUrl(AVATAR_PROFILE_SIZE));
1138 $xs->elementStart('author');
1139 $xs->element('name', null, $profile->nickname);
1140 $xs->element('uri', null, $profile->profileurl);
1141 $xs->elementEnd('author');
1144 $xs->elementEnd('source');
1147 $xs->element('title', null, $this->content);
1148 $xs->element('summary', null, $this->content);
1150 $xs->element('link', array('rel' => 'alternate',
1151 'href' => $this->bestUrl()));
1153 $xs->element('id', null, $this->uri);
1155 $xs->element('published', null, common_date_w3dtf($this->created));
1156 $xs->element('updated', null, common_date_w3dtf($this->modified));
1158 if ($this->reply_to) {
1159 $reply_notice = Notice::staticGet('id', $this->reply_to);
1160 if (!empty($reply_notice)) {
1161 $xs->element('link', array('rel' => 'related',
1162 'href' => $reply_notice->bestUrl()));
1163 $xs->element('thr:in-reply-to',
1164 array('ref' => $reply_notice->uri,
1165 'href' => $reply_notice->bestUrl()));
1169 $xs->element('content', array('type' => 'html'), $this->rendered);
1171 $tag = new Notice_tag();
1172 $tag->notice_id = $this->id;
1174 while ($tag->fetch()) {
1175 $xs->element('category', array('term' => $tag->tag));
1181 $attachments = $this->attachments();
1183 foreach($attachments as $attachment){
1184 if ($attachment->isEnclosure()) {
1185 $attributes = array('rel'=>'enclosure','href'=>$attachment->url,'type'=>$attachment->mimetype,'length'=>$attachment->size);
1186 if($attachment->title){
1187 $attributes['title']=$attachment->title;
1189 $xs->element('link', $attributes, null);
1194 $xs->elementEnd('entry');
1196 return $xs->getString();
1201 if (!empty($this->url)) {
1203 } else if (!empty($this->uri) && preg_match('/^https?:/', $this->uri)) {
1206 return common_local_url('shownotice',
1207 array('notice' => $this->id));
1211 function stream($fn, $args, $cachekey, $offset=0, $limit=20, $since_id=0, $max_id=0, $since=null)
1213 $cache = common_memcache();
1215 if (empty($cache) ||
1216 $since_id != 0 || $max_id != 0 || (!is_null($since) && $since > 0) ||
1218 ($offset + $limit) > NOTICE_CACHE_WINDOW) {
1219 return call_user_func_array($fn, array_merge($args, array($offset, $limit, $since_id,
1223 $idkey = common_cache_key($cachekey);
1225 $idstr = $cache->get($idkey);
1227 if (!empty($idstr)) {
1228 // Cache hit! Woohoo!
1229 $window = explode(',', $idstr);
1230 $ids = array_slice($window, $offset, $limit);
1234 $laststr = $cache->get($idkey.';last');
1236 if (!empty($laststr)) {
1237 $window = explode(',', $laststr);
1238 $last_id = $window[0];
1239 $new_ids = call_user_func_array($fn, array_merge($args, array(0, NOTICE_CACHE_WINDOW,
1240 $last_id, 0, null)));
1242 $new_window = array_merge($new_ids, $window);
1244 $new_windowstr = implode(',', $new_window);
1246 $result = $cache->set($idkey, $new_windowstr);
1247 $result = $cache->set($idkey . ';last', $new_windowstr);
1249 $ids = array_slice($new_window, $offset, $limit);
1254 $window = call_user_func_array($fn, array_merge($args, array(0, NOTICE_CACHE_WINDOW,
1257 $windowstr = implode(',', $window);
1259 $result = $cache->set($idkey, $windowstr);
1260 $result = $cache->set($idkey . ';last', $windowstr);
1262 $ids = array_slice($window, $offset, $limit);
1268 * Determine which notice, if any, a new notice is in reply to.
1270 * For conversation tracking, we try to see where this notice fits
1271 * in the tree. Rough algorithm is:
1273 * if (reply_to is set and valid) {
1275 * } else if ((source not API or Web) and (content starts with "T NAME" or "@name ")) {
1276 * return ID of last notice by initial @name in content;
1279 * Note that all @nickname instances will still be used to save "reply" records,
1280 * so the notice shows up in the mentioned users' "replies" tab.
1282 * @param integer $reply_to ID passed in by Web or API
1283 * @param integer $profile_id ID of author
1284 * @param string $source Source tag, like 'web' or 'gwibber'
1285 * @param string $content Final notice content
1287 * @return integer ID of replied-to notice, or null for not a reply.
1290 static function getReplyTo($reply_to, $profile_id, $source, $content)
1292 static $lb = array('xmpp', 'mail', 'sms', 'omb');
1294 // If $reply_to is specified, we check that it exists, and then
1295 // return it if it does
1297 if (!empty($reply_to)) {
1298 $reply_notice = Notice::staticGet('id', $reply_to);
1299 if (!empty($reply_notice)) {
1304 // If it's not a "low bandwidth" source (one where you can't set
1305 // a reply_to argument), we return. This is mostly web and API
1308 if (!in_array($source, $lb)) {
1312 // Is there an initial @ or T?
1314 if (preg_match('/^T ([A-Z0-9]{1,64}) /', $content, $match) ||
1315 preg_match('/^@([a-z0-9]{1,64})\s+/', $content, $match)) {
1316 $nickname = common_canonical_nickname($match[1]);
1321 // Figure out who that is.
1323 $sender = Profile::staticGet('id', $profile_id);
1324 $recipient = common_relative_profile($sender, $nickname, common_sql_now());
1326 if (empty($recipient)) {
1330 // Get their last notice
1332 $last = $recipient->getCurrentNotice();
1334 if (!empty($last)) {