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',
115 if (common_config('inboxes', 'enabled')) {
116 $related[] = 'Notice_inbox';
118 foreach ($related as $cls) {
120 $inst->notice_id = $this->id;
123 $result = parent::delete();
124 $this->query('COMMIT');
129 /* extract all #hastags */
130 $count = preg_match_all('/(?:^|\s)#([\pL\pN_\-\.]{1,64})/', strtolower($this->content), $match);
135 //turn each into their canonical tag
136 //this is needed to remove dupes before saving e.g. #hash.tag = #hashtag
138 for($i=0; $i<count($match[1]); $i++) {
139 $hashtags[] = common_canonical_tag($match[1][$i]);
142 /* Add them to the database */
143 foreach(array_unique($hashtags) as $hashtag) {
144 /* elide characters we don't want in the tag */
145 $this->saveTag($hashtag);
150 function saveTag($hashtag)
152 $tag = new Notice_tag();
153 $tag->notice_id = $this->id;
154 $tag->tag = $hashtag;
155 $tag->created = $this->created;
156 $id = $tag->insert();
159 throw new ServerException(sprintf(_('DB error inserting hashtag: %s'),
160 $last_error->message));
165 static function saveNew($profile_id, $content, $source=null,
166 $is_local=Notice::LOCAL_PUBLIC, $reply_to=null, $uri=null, $created=null) {
168 $profile = Profile::staticGet($profile_id);
170 $final = common_shorten_links($content);
172 if (Notice::contentTooLong($final)) {
173 throw new ClientException(_('Problem saving notice. Too long.'));
177 throw new ClientException(_('Problem saving notice. Unknown user.'));
180 if (common_config('throttle', 'enabled') && !Notice::checkEditThrottle($profile_id)) {
181 common_log(LOG_WARNING, 'Excessive posting by profile #' . $profile_id . '; throttled.');
182 throw new ClientException(_('Too many notices too fast; take a breather '.
183 'and post again in a few minutes.'));
186 if (common_config('site', 'dupelimit') > 0 && !Notice::checkDupes($profile_id, $final)) {
187 common_log(LOG_WARNING, 'Dupe posting by profile #' . $profile_id . '; throttled.');
188 throw new ClientException(_('Too many duplicate messages too quickly;'.
189 ' take a breather and post again in a few minutes.'));
192 $banned = common_config('profile', 'banned');
194 if ( in_array($profile_id, $banned) || in_array($profile->nickname, $banned)) {
195 common_log(LOG_WARNING, "Attempted post from banned user: $profile->nickname (user id = $profile_id).");
196 throw new ClientException(_('You are banned from posting notices on this site.'));
199 $notice = new Notice();
200 $notice->profile_id = $profile_id;
202 $blacklist = common_config('public', 'blacklist');
203 $autosource = common_config('public', 'autosource');
205 # Blacklisted are non-false, but not 1, either
207 if (($blacklist && in_array($profile_id, $blacklist)) ||
208 ($source && $autosource && in_array($source, $autosource))) {
209 $notice->is_local = Notice::LOCAL_NONPUBLIC;
211 $notice->is_local = $is_local;
214 if (!empty($created)) {
215 $notice->created = $created;
217 $notice->created = common_sql_now();
220 $notice->content = $final;
221 $notice->rendered = common_render_content($final, $notice);
222 $notice->source = $source;
225 $notice->reply_to = self::getReplyTo($reply_to, $profile_id, $source, $final);
227 if (!empty($notice->reply_to)) {
228 $reply = Notice::staticGet('id', $notice->reply_to);
229 $notice->conversation = $reply->conversation;
232 if (Event::handle('StartNoticeSave', array(&$notice))) {
234 // XXX: some of these functions write to the DB
236 $notice->query('BEGIN');
238 $id = $notice->insert();
241 common_log_db_error($notice, 'INSERT', __FILE__);
242 throw new ServerException(_('Problem saving notice.'));
245 // Update ID-dependent columns: URI, conversation
247 $orig = clone($notice);
252 $notice->uri = common_notice_uri($notice);
256 // If it's not part of a conversation, it's
257 // the beginning of a new conversation.
259 if (empty($notice->conversation)) {
260 $notice->conversation = $notice->id;
265 if (!$notice->update($orig)) {
266 common_log_db_error($notice, 'UPDATE', __FILE__);
267 throw new ServerException(_('Problem saving notice.'));
271 // XXX: do we need to change this for remote users?
273 $notice->saveReplies();
276 $notice->addToInboxes();
280 $notice->query('COMMIT');
282 Event::handle('EndNoticeSave', array($notice));
285 # Clear the cache for subscribed users, so they'll update at next request
286 # XXX: someone clever could prepend instead of clearing the cache
288 $notice->blowCaches();
293 /** save all urls in the notice to the db
295 * follow redirects and save all available file information
296 * (mimetype, date, size, oembed, etc.)
300 function saveUrls() {
301 common_replace_urls_callback($this->content, array($this, 'saveUrl'), $this->id);
304 function saveUrl($data) {
305 list($url, $notice_id) = $data;
306 File::processNew($url, $notice_id);
309 static function checkDupes($profile_id, $content) {
310 $profile = Profile::staticGet($profile_id);
314 $notice = $profile->getNotices(0, NOTICE_CACHE_WINDOW);
317 while ($notice->fetch()) {
318 if (time() - strtotime($notice->created) >= common_config('site', 'dupelimit')) {
320 } else if ($notice->content == $content) {
325 # If we get here, oldest item in cache window is not
326 # old enough for dupe limit; do direct check against DB
327 $notice = new Notice();
328 $notice->profile_id = $profile_id;
329 $notice->content = $content;
330 if (common_config('db','type') == 'pgsql')
331 $notice->whereAdd('extract(epoch from now() - created) < ' . common_config('site', 'dupelimit'));
333 $notice->whereAdd('now() - created < ' . common_config('site', 'dupelimit'));
335 $cnt = $notice->count();
339 static function checkEditThrottle($profile_id) {
340 $profile = Profile::staticGet($profile_id);
345 $notice = $profile->getNotices(common_config('throttle', 'count') - 1, 1);
346 if ($notice && $notice->fetch()) {
347 # If the Nth notice was posted less than timespan seconds ago
348 if (time() - strtotime($notice->created) <= common_config('throttle', 'timespan')) {
353 # Either not N notices in the stream, OR the Nth was not posted within timespan seconds
357 function getUploadedAttachment() {
359 $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"';
360 $post->query($query);
362 if (empty($post->up) || empty($post->i)) {
365 $ret = array($post->up, $post->i);
371 function hasAttachments() {
373 $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);
374 $post->query($query);
376 $n_attachments = intval($post->n_attachments);
378 return $n_attachments;
381 function attachments() {
384 $f2p = new File_to_post;
385 $f2p->post_id = $this->id;
387 while ($f2p->fetch()) {
388 $f = File::staticGet($f2p->file_id);
395 function blowCaches($blowLast=false)
397 $this->blowSubsCache($blowLast);
398 $this->blowNoticeCache($blowLast);
399 $this->blowRepliesCache($blowLast);
400 $this->blowPublicCache($blowLast);
401 $this->blowTagCache($blowLast);
402 $this->blowGroupCache($blowLast);
403 $this->blowConversationCache($blowLast);
404 $profile = Profile::staticGet($this->profile_id);
405 $profile->blowNoticeCount();
408 function blowConversationCache($blowLast=false)
410 $cache = common_memcache();
412 $ck = common_cache_key('notice:conversation_ids:'.$this->conversation);
415 $cache->delete($ck.';last');
420 function blowGroupCache($blowLast=false)
422 $cache = common_memcache();
424 $group_inbox = new Group_inbox();
425 $group_inbox->notice_id = $this->id;
426 if ($group_inbox->find()) {
427 while ($group_inbox->fetch()) {
428 $cache->delete(common_cache_key('user_group:notice_ids:' . $group_inbox->group_id));
430 $cache->delete(common_cache_key('user_group:notice_ids:' . $group_inbox->group_id.';last'));
432 $member = new Group_member();
433 $member->group_id = $group_inbox->group_id;
434 if ($member->find()) {
435 while ($member->fetch()) {
436 $cache->delete(common_cache_key('notice_inbox:by_user:' . $member->profile_id));
438 $cache->delete(common_cache_key('notice_inbox:by_user:' . $member->profile_id . ';last'));
444 $group_inbox->free();
449 function blowTagCache($blowLast=false)
451 $cache = common_memcache();
453 $tag = new Notice_tag();
454 $tag->notice_id = $this->id;
456 while ($tag->fetch()) {
457 $tag->blowCache($blowLast);
458 $ck = 'profile:notice_ids_tagged:' . $this->profile_id . ':' . $tag->tag;
462 $cache->delete($ck . ';last');
471 function blowSubsCache($blowLast=false)
473 $cache = common_memcache();
477 $UT = common_config('db','type')=='pgsql'?'"user"':'user';
478 $user->query('SELECT id ' .
480 "FROM $UT JOIN subscription ON $UT.id = subscription.subscriber " .
481 'WHERE subscription.subscribed = ' . $this->profile_id);
483 while ($user->fetch()) {
484 $cache->delete(common_cache_key('notice_inbox:by_user:'.$user->id));
485 $cache->delete(common_cache_key('notice_inbox:by_user_own:'.$user->id));
487 $cache->delete(common_cache_key('notice_inbox:by_user:'.$user->id.';last'));
488 $cache->delete(common_cache_key('notice_inbox:by_user_own:'.$user->id.';last'));
496 function blowNoticeCache($blowLast=false)
498 if ($this->is_local) {
499 $cache = common_memcache();
500 if (!empty($cache)) {
501 $cache->delete(common_cache_key('profile:notice_ids:'.$this->profile_id));
503 $cache->delete(common_cache_key('profile:notice_ids:'.$this->profile_id.';last'));
509 function blowRepliesCache($blowLast=false)
511 $cache = common_memcache();
513 $reply = new Reply();
514 $reply->notice_id = $this->id;
515 if ($reply->find()) {
516 while ($reply->fetch()) {
517 $cache->delete(common_cache_key('reply:stream:'.$reply->profile_id));
519 $cache->delete(common_cache_key('reply:stream:'.$reply->profile_id.';last'));
528 function blowPublicCache($blowLast=false)
530 if ($this->is_local == Notice::LOCAL_PUBLIC) {
531 $cache = common_memcache();
533 $cache->delete(common_cache_key('public'));
535 $cache->delete(common_cache_key('public').';last');
541 function blowFavesCache($blowLast=false)
543 $cache = common_memcache();
546 $fave->notice_id = $this->id;
548 while ($fave->fetch()) {
549 $cache->delete(common_cache_key('fave:ids_by_user:'.$fave->user_id));
550 $cache->delete(common_cache_key('fave:by_user_own:'.$fave->user_id));
552 $cache->delete(common_cache_key('fave:ids_by_user:'.$fave->user_id.';last'));
553 $cache->delete(common_cache_key('fave:by_user_own:'.$fave->user_id.';last'));
562 # XXX: too many args; we need to move to named params or even a separate
563 # class for notice streams
565 static function getStream($qry, $cachekey, $offset=0, $limit=20, $since_id=0, $max_id=0, $order=null, $since=null) {
567 if (common_config('memcached', 'enabled')) {
569 # Skip the cache if this is a since, since_id or max_id qry
570 if ($since_id > 0 || $max_id > 0 || $since) {
571 return Notice::getStreamDirect($qry, $offset, $limit, $since_id, $max_id, $order, $since);
573 return Notice::getCachedStream($qry, $cachekey, $offset, $limit, $order);
577 return Notice::getStreamDirect($qry, $offset, $limit, $since_id, $max_id, $order, $since);
580 static function getStreamDirect($qry, $offset, $limit, $since_id, $max_id, $order, $since) {
585 if (preg_match('/\bWHERE\b/i', $qry)) {
599 $qry .= ' notice.id > ' . $since_id;
611 $qry .= ' notice.id <= ' . $max_id;
623 $qry .= ' notice.created > \'' . date('Y-m-d H:i:s', $since) . '\'';
626 # Allow ORDER override
631 $qry .= ' ORDER BY notice.created DESC, notice.id DESC ';
634 if (common_config('db','type') == 'pgsql') {
635 $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
637 $qry .= ' LIMIT ' . $offset . ', ' . $limit;
640 $notice = new Notice();
642 $notice->query($qry);
647 # XXX: this is pretty long and should probably be broken up into
648 # some helper functions
650 static function getCachedStream($qry, $cachekey, $offset, $limit, $order) {
652 # If outside our cache window, just go to the DB
654 if ($offset + $limit > NOTICE_CACHE_WINDOW) {
655 return Notice::getStreamDirect($qry, $offset, $limit, null, null, $order, null);
658 # Get the cache; if we can't, just go to the DB
660 $cache = common_memcache();
663 return Notice::getStreamDirect($qry, $offset, $limit, null, null, $order, null);
666 # Get the notices out of the cache
668 $notices = $cache->get(common_cache_key($cachekey));
670 # On a cache hit, return a DB-object-like wrapper
672 if ($notices !== false) {
673 $wrapper = new ArrayWrapper(array_slice($notices, $offset, $limit));
677 # If the cache was invalidated because of new data being
678 # added, we can try and just get the new stuff. We keep an additional
679 # copy of the data at the key + ';last'
681 # No cache hit. Try to get the *last* cached version
683 $last_notices = $cache->get(common_cache_key($cachekey) . ';last');
687 # Reverse-chron order, so last ID is last.
689 $last_id = $last_notices[0]->id;
691 # XXX: this assumes monotonically increasing IDs; a fair
694 $new_notice = Notice::getStreamDirect($qry, 0, NOTICE_CACHE_WINDOW,
695 $last_id, null, $order, null);
698 $new_notices = array();
699 while ($new_notice->fetch()) {
700 $new_notices[] = clone($new_notice);
703 $notices = array_slice(array_merge($new_notices, $last_notices),
704 0, NOTICE_CACHE_WINDOW);
706 # Store the array in the cache for next time
708 $result = $cache->set(common_cache_key($cachekey), $notices);
709 $result = $cache->set(common_cache_key($cachekey) . ';last', $notices);
711 # return a wrapper of the array for use now
713 return new ArrayWrapper(array_slice($notices, $offset, $limit));
717 # Otherwise, get the full cache window out of the DB
719 $notice = Notice::getStreamDirect($qry, 0, NOTICE_CACHE_WINDOW, null, null, $order, null);
721 # If there are no hits, just return the value
727 # Pack results into an array
731 while ($notice->fetch()) {
732 $notices[] = clone($notice);
737 # Store the array in the cache for next time
739 $result = $cache->set(common_cache_key($cachekey), $notices);
740 $result = $cache->set(common_cache_key($cachekey) . ';last', $notices);
742 # return a wrapper of the array for use now
744 $wrapper = new ArrayWrapper(array_slice($notices, $offset, $limit));
749 function getStreamByIds($ids)
751 $cache = common_memcache();
753 if (!empty($cache)) {
755 foreach ($ids as $id) {
756 $n = Notice::staticGet('id', $id);
761 return new ArrayWrapper($notices);
763 $notice = new Notice();
765 //if no IDs requested, just return the notice object
768 $notice->whereAdd('id in (' . implode(', ', $ids) . ')');
769 $notice->orderBy('id DESC');
776 function publicStream($offset=0, $limit=20, $since_id=0, $max_id=0, $since=null)
778 $ids = Notice::stream(array('Notice', '_publicStreamDirect'),
781 $offset, $limit, $since_id, $max_id, $since);
783 return Notice::getStreamByIds($ids);
786 function _publicStreamDirect($offset=0, $limit=20, $since_id=0, $max_id=0, $since=null)
788 $notice = new Notice();
790 $notice->selectAdd(); // clears it
791 $notice->selectAdd('id');
793 $notice->orderBy('id DESC');
795 if (!is_null($offset)) {
796 $notice->limit($offset, $limit);
799 if (common_config('public', 'localonly')) {
800 $notice->whereAdd('is_local = ' . Notice::LOCAL_PUBLIC);
802 # -1 == blacklisted, -2 == gateway (i.e. Twitter)
803 $notice->whereAdd('is_local !='. Notice::LOCAL_NONPUBLIC);
804 $notice->whereAdd('is_local !='. Notice::GATEWAY);
807 if ($since_id != 0) {
808 $notice->whereAdd('id > ' . $since_id);
812 $notice->whereAdd('id <= ' . $max_id);
815 if (!is_null($since)) {
816 $notice->whereAdd('created > \'' . date('Y-m-d H:i:s', $since) . '\'');
821 if ($notice->find()) {
822 while ($notice->fetch()) {
823 $ids[] = $notice->id;
833 function conversationStream($id, $offset=0, $limit=20, $since_id=0, $max_id=0, $since=null)
835 $ids = Notice::stream(array('Notice', '_conversationStreamDirect'),
837 'notice:conversation_ids:'.$id,
838 $offset, $limit, $since_id, $max_id, $since);
840 return Notice::getStreamByIds($ids);
843 function _conversationStreamDirect($id, $offset=0, $limit=20, $since_id=0, $max_id=0, $since=null)
845 $notice = new Notice();
847 $notice->selectAdd(); // clears it
848 $notice->selectAdd('id');
850 $notice->conversation = $id;
852 $notice->orderBy('id DESC');
854 if (!is_null($offset)) {
855 $notice->limit($offset, $limit);
858 if ($since_id != 0) {
859 $notice->whereAdd('id > ' . $since_id);
863 $notice->whereAdd('id <= ' . $max_id);
866 if (!is_null($since)) {
867 $notice->whereAdd('created > \'' . date('Y-m-d H:i:s', $since) . '\'');
872 if ($notice->find()) {
873 while ($notice->fetch()) {
874 $ids[] = $notice->id;
884 function addToInboxes()
886 $enabled = common_config('inboxes', 'enabled');
888 if ($enabled === true || $enabled === 'transitional') {
890 // XXX: loads constants
892 $inbox = new Notice_inbox();
894 $users = $this->getSubscribedUsers();
896 // FIXME: kind of ignoring 'transitional'...
897 // we'll probably stop supporting inboxless mode
902 foreach ($users as $id) {
903 $ni[$id] = NOTICE_INBOX_SOURCE_SUB;
906 $groups = $this->saveGroups();
908 foreach ($groups as $group) {
909 $users = $group->getUserMembers();
910 foreach ($users as $id) {
911 if (!array_key_exists($id, $ni)) {
912 $ni[$id] = NOTICE_INBOX_SOURCE_GROUP;
919 $qryhdr = 'INSERT INTO notice_inbox (user_id, notice_id, source, created) VALUES ';
922 foreach ($ni as $id => $source) {
926 $qry .= '('.$id.', '.$this->id.', '.$source.", '".$this->created. "') ";
928 if (rand() % NOTICE_INBOX_SOFT_LIMIT == 0) {
929 // FIXME: Causes lag in replicated servers
930 // Notice_inbox::gc($id);
932 if ($cnt >= MAX_BOXCARS) {
933 $inbox = new Notice_inbox();
941 $inbox = new Notice_inbox();
949 function getSubscribedUsers()
953 if(common_config('db','quote_identifiers'))
954 $user_table = '"user"';
955 else $user_table = 'user';
959 'FROM '. $user_table .' JOIN subscription '.
960 'ON '. $user_table .'.id = subscription.subscriber ' .
961 'WHERE subscription.subscribed = %d ';
963 $user->query(sprintf($qry, $this->profile_id));
967 while ($user->fetch()) {
976 function saveGroups()
980 $enabled = common_config('inboxes', 'enabled');
981 if ($enabled !== true && $enabled !== 'transitional') {
985 /* extract all !group */
986 $count = preg_match_all('/(?:^|\s)!([A-Za-z0-9]{1,64})/',
987 strtolower($this->content),
993 $profile = $this->getProfile();
995 /* Add them to the database */
997 foreach (array_unique($match[1]) as $nickname) {
998 /* XXX: remote groups. */
999 $group = User_group::getForNickname($nickname);
1001 if (empty($group)) {
1005 // we automatically add a tag for every group name, too
1007 $tag = Notice_tag::pkeyGet(array('tag' => common_canonical_tag($nickname),
1008 'notice_id' => $this->id));
1010 if (is_null($tag)) {
1011 $this->saveTag($nickname);
1014 if ($profile->isMember($group)) {
1016 $result = $this->addToGroupInbox($group);
1019 common_log_db_error($gi, 'INSERT', __FILE__);
1022 $groups[] = clone($group);
1029 function addToGroupInbox($group)
1031 $gi = Group_inbox::pkeyGet(array('group_id' => $group->id,
1032 'notice_id' => $this->id));
1036 $gi = new Group_inbox();
1038 $gi->group_id = $group->id;
1039 $gi->notice_id = $this->id;
1040 $gi->created = $this->created;
1042 return $gi->insert();
1048 function saveReplies()
1050 // Alternative reply format
1052 if (preg_match('/^T ([A-Z0-9]{1,64}) /', $this->content, $match)) {
1055 // extract all @messages
1056 $cnt = preg_match_all('/(?:^|\s)@([a-z0-9]{1,64})/', $this->content, $match);
1060 if ($cnt || $tname) {
1061 // XXX: is there another way to make an array copy?
1062 $names = ($tname) ? array_unique(array_merge(array(strtolower($tname)), $match[1])) : array_unique($match[1]);
1065 $sender = Profile::staticGet($this->profile_id);
1069 // store replied only for first @ (what user/notice what the reply directed,
1070 // we assume first @ is it)
1072 for ($i=0; $i<count($names); $i++) {
1073 $nickname = $names[$i];
1074 $recipient = common_relative_profile($sender, $nickname, $this->created);
1078 // Don't save replies from blocked profile to local user
1079 $recipient_user = User::staticGet('id', $recipient->id);
1080 if ($recipient_user && $recipient_user->hasBlocked($sender)) {
1083 $reply = new Reply();
1084 $reply->notice_id = $this->id;
1085 $reply->profile_id = $recipient->id;
1086 $id = $reply->insert();
1088 $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError');
1089 common_log(LOG_ERR, 'DB error inserting reply: ' . $last_error->message);
1090 common_server_error(sprintf(_('DB error inserting reply: %s'), $last_error->message));
1093 $replied[$recipient->id] = 1;
1097 // Hash format replies, too
1098 $cnt = preg_match_all('/(?:^|\s)@#([a-z0-9]{1,64})/', $this->content, $match);
1100 foreach ($match[1] as $tag) {
1101 $tagged = Profile_tag::getTagged($sender->id, $tag);
1102 foreach ($tagged as $t) {
1103 if (!$replied[$t->id]) {
1104 // Don't save replies from blocked profile to local user
1105 $t_user = User::staticGet('id', $t->id);
1106 if ($t_user && $t_user->hasBlocked($sender)) {
1109 $reply = new Reply();
1110 $reply->notice_id = $this->id;
1111 $reply->profile_id = $t->id;
1112 $id = $reply->insert();
1114 common_log_db_error($reply, 'INSERT', __FILE__);
1117 $replied[$recipient->id] = 1;
1124 foreach (array_keys($replied) as $recipient) {
1125 $user = User::staticGet('id', $recipient);
1127 mail_notify_attn($user, $this);
1132 function asAtomEntry($namespace=false, $source=false)
1134 $profile = $this->getProfile();
1136 $xs = new XMLStringer(true);
1139 $attrs = array('xmlns' => 'http://www.w3.org/2005/Atom',
1140 'xmlns:thr' => 'http://purl.org/syndication/thread/1.0');
1145 $xs->elementStart('entry', $attrs);
1148 $xs->elementStart('source');
1149 $xs->element('title', null, $profile->nickname . " - " . common_config('site', 'name'));
1150 $xs->element('link', array('href' => $profile->profileurl));
1151 $user = User::staticGet('id', $profile->id);
1152 if (!empty($user)) {
1153 $atom_feed = common_local_url('api',
1154 array('apiaction' => 'statuses',
1155 'method' => 'user_timeline',
1156 'argument' => $profile->nickname.'.atom'));
1157 $xs->element('link', array('rel' => 'self',
1158 'type' => 'application/atom+xml',
1159 'href' => $profile->profileurl));
1160 $xs->element('link', array('rel' => 'license',
1161 'href' => common_config('license', 'url')));
1164 $xs->element('icon', null, $profile->avatarUrl(AVATAR_PROFILE_SIZE));
1167 $xs->elementStart('author');
1168 $xs->element('name', null, $profile->nickname);
1169 $xs->element('uri', null, $profile->profileurl);
1170 $xs->elementEnd('author');
1173 $xs->elementEnd('source');
1176 $xs->element('title', null, $this->content);
1177 $xs->element('summary', null, $this->content);
1179 $xs->element('link', array('rel' => 'alternate',
1180 'href' => $this->bestUrl()));
1182 $xs->element('id', null, $this->uri);
1184 $xs->element('published', null, common_date_w3dtf($this->created));
1185 $xs->element('updated', null, common_date_w3dtf($this->modified));
1187 if ($this->reply_to) {
1188 $reply_notice = Notice::staticGet('id', $this->reply_to);
1189 if (!empty($reply_notice)) {
1190 $xs->element('link', array('rel' => 'related',
1191 'href' => $reply_notice->bestUrl()));
1192 $xs->element('thr:in-reply-to',
1193 array('ref' => $reply_notice->uri,
1194 'href' => $reply_notice->bestUrl()));
1198 $xs->element('content', array('type' => 'html'), $this->rendered);
1200 $tag = new Notice_tag();
1201 $tag->notice_id = $this->id;
1203 while ($tag->fetch()) {
1204 $xs->element('category', array('term' => $tag->tag));
1210 $attachments = $this->attachments();
1212 foreach($attachments as $attachment){
1213 $enclosure=$attachment->getEnclosure();
1215 $attributes = array('rel'=>'enclosure','href'=>$enclosure->url,'type'=>$enclosure->mimetype,'length'=>$enclosure->size);
1216 if($enclosure->title){
1217 $attributes['title']=$enclosure->title;
1219 $xs->element('link', $attributes, null);
1224 $xs->elementEnd('entry');
1226 return $xs->getString();
1231 if (!empty($this->url)) {
1233 } else if (!empty($this->uri) && preg_match('/^https?:/', $this->uri)) {
1236 return common_local_url('shownotice',
1237 array('notice' => $this->id));
1241 function stream($fn, $args, $cachekey, $offset=0, $limit=20, $since_id=0, $max_id=0, $since=null)
1243 $cache = common_memcache();
1245 if (empty($cache) ||
1246 $since_id != 0 || $max_id != 0 || (!is_null($since) && $since > 0) ||
1248 ($offset + $limit) > NOTICE_CACHE_WINDOW) {
1249 return call_user_func_array($fn, array_merge($args, array($offset, $limit, $since_id,
1253 $idkey = common_cache_key($cachekey);
1255 $idstr = $cache->get($idkey);
1257 if (!empty($idstr)) {
1258 // Cache hit! Woohoo!
1259 $window = explode(',', $idstr);
1260 $ids = array_slice($window, $offset, $limit);
1264 $laststr = $cache->get($idkey.';last');
1266 if (!empty($laststr)) {
1267 $window = explode(',', $laststr);
1268 $last_id = $window[0];
1269 $new_ids = call_user_func_array($fn, array_merge($args, array(0, NOTICE_CACHE_WINDOW,
1270 $last_id, 0, null)));
1272 $new_window = array_merge($new_ids, $window);
1274 $new_windowstr = implode(',', $new_window);
1276 $result = $cache->set($idkey, $new_windowstr);
1277 $result = $cache->set($idkey . ';last', $new_windowstr);
1279 $ids = array_slice($new_window, $offset, $limit);
1284 $window = call_user_func_array($fn, array_merge($args, array(0, NOTICE_CACHE_WINDOW,
1287 $windowstr = implode(',', $window);
1289 $result = $cache->set($idkey, $windowstr);
1290 $result = $cache->set($idkey . ';last', $windowstr);
1292 $ids = array_slice($window, $offset, $limit);
1298 * Determine which notice, if any, a new notice is in reply to.
1300 * For conversation tracking, we try to see where this notice fits
1301 * in the tree. Rough algorithm is:
1303 * if (reply_to is set and valid) {
1305 * } else if ((source not API or Web) and (content starts with "T NAME" or "@name ")) {
1306 * return ID of last notice by initial @name in content;
1309 * Note that all @nickname instances will still be used to save "reply" records,
1310 * so the notice shows up in the mentioned users' "replies" tab.
1312 * @param integer $reply_to ID passed in by Web or API
1313 * @param integer $profile_id ID of author
1314 * @param string $source Source tag, like 'web' or 'gwibber'
1315 * @param string $content Final notice content
1317 * @return integer ID of replied-to notice, or null for not a reply.
1320 static function getReplyTo($reply_to, $profile_id, $source, $content)
1322 static $lb = array('xmpp', 'mail', 'sms', 'omb');
1324 // If $reply_to is specified, we check that it exists, and then
1325 // return it if it does
1327 if (!empty($reply_to)) {
1328 $reply_notice = Notice::staticGet('id', $reply_to);
1329 if (!empty($reply_notice)) {
1334 // If it's not a "low bandwidth" source (one where you can't set
1335 // a reply_to argument), we return. This is mostly web and API
1338 if (!in_array($source, $lb)) {
1342 // Is there an initial @ or T?
1344 if (preg_match('/^T ([A-Z0-9]{1,64}) /', $content, $match) ||
1345 preg_match('/^@([a-z0-9]{1,64})\s+/', $content, $match)) {
1346 $nickname = common_canonical_nickname($match[1]);
1351 // Figure out who that is.
1353 $sender = Profile::staticGet('id', $profile_id);
1354 $recipient = common_relative_profile($sender, $nickname, common_sql_now());
1356 if (empty($recipient)) {
1360 // Get their last notice
1362 $last = $recipient->getCurrentNotice();
1364 if (!empty($last)) {
1369 static function maxContent()
1371 $contentlimit = common_config('notice', 'contentlimit');
1372 // null => use global limit (distinct from 0!)
1373 if (is_null($contentlimit)) {
1374 $contentlimit = common_config('site', 'textlimit');
1376 return $contentlimit;
1379 static function contentTooLong($content)
1381 $contentlimit = self::maxContent();
1382 return ($contentlimit > 0 && !empty($content) && (mb_strlen($content) > $contentlimit));