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; // text()
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) { return Memcached_DataObject::staticGet('Notice',$k,$v); }
56 /* the code above is auto generated do not remove the tag below */
60 const LOCAL_PUBLIC = 1;
62 const LOCAL_NONPUBLIC = -1;
67 return Profile::staticGet('id', $this->profile_id);
72 $this->blowCaches(true);
73 $this->blowFavesCache(true);
74 $this->blowSubsCache(true);
76 // For auditing purposes, save a record that the notice
79 $deleted = new Deleted_notice();
81 $deleted->id = $this->id;
82 $deleted->profile_id = $this->profile_id;
83 $deleted->uri = $this->uri;
84 $deleted->created = $this->created;
85 $deleted->deleted = common_sql_now();
87 $this->query('BEGIN');
91 //Null any notices that are replies to this notice
92 $this->query(sprintf("UPDATE notice set reply_to = null WHERE reply_to = %d", $this->id));
93 $related = array('Reply',
98 if (common_config('inboxes', 'enabled')) {
99 $related[] = 'Notice_inbox';
101 foreach ($related as $cls) {
103 $inst->notice_id = $this->id;
106 $result = parent::delete();
107 $this->query('COMMIT');
112 /* extract all #hastags */
113 $count = preg_match_all('/(?:^|\s)#([\pL\pN_\-\.]{1,64})/', strtolower($this->content), $match);
118 //turn each into their canonical tag
119 //this is needed to remove dupes before saving e.g. #hash.tag = #hashtag
121 for($i=0; $i<count($match[1]); $i++) {
122 $hashtags[] = common_canonical_tag($match[1][$i]);
125 /* Add them to the database */
126 foreach(array_unique($hashtags) as $hashtag) {
127 /* elide characters we don't want in the tag */
128 $this->saveTag($hashtag);
133 function saveTag($hashtag)
135 $tag = new Notice_tag();
136 $tag->notice_id = $this->id;
137 $tag->tag = $hashtag;
138 $tag->created = $this->created;
139 $id = $tag->insert();
142 throw new ServerException(sprintf(_('DB error inserting hashtag: %s'),
143 $last_error->message));
148 static function saveNew($profile_id, $content, $source=null,
149 $is_local=Notice::LOCAL_PUBLIC, $reply_to=null, $uri=null, $created=null) {
151 $profile = Profile::staticGet($profile_id);
153 $final = common_shorten_links($content);
155 if (Notice::contentTooLong($final)) {
156 common_log(LOG_INFO, 'Rejecting notice that is too long.');
157 return _('Problem saving notice. Too long.');
161 common_log(LOG_ERR, 'Problem saving notice. Unknown user.');
162 return _('Problem saving notice. Unknown user.');
165 if (common_config('throttle', 'enabled') && !Notice::checkEditThrottle($profile_id)) {
166 common_log(LOG_WARNING, 'Excessive posting by profile #' . $profile_id . '; throttled.');
167 return _('Too many notices too fast; take a breather and post again in a few minutes.');
170 if (common_config('site', 'dupelimit') > 0 && !Notice::checkDupes($profile_id, $final)) {
171 common_log(LOG_WARNING, 'Dupe posting by profile #' . $profile_id . '; throttled.');
172 return _('Too many duplicate messages too quickly; take a breather and post again in a few minutes.');
175 $banned = common_config('profile', 'banned');
177 if ( in_array($profile_id, $banned) || in_array($profile->nickname, $banned)) {
178 common_log(LOG_WARNING, "Attempted post from banned user: $profile->nickname (user id = $profile_id).");
179 return _('You are banned from posting notices on this site.');
182 $notice = new Notice();
183 $notice->profile_id = $profile_id;
185 $blacklist = common_config('public', 'blacklist');
186 $autosource = common_config('public', 'autosource');
188 # Blacklisted are non-false, but not 1, either
190 if (($blacklist && in_array($profile_id, $blacklist)) ||
191 ($source && $autosource && in_array($source, $autosource))) {
192 $notice->is_local = Notice::LOCAL_NONPUBLIC;
194 $notice->is_local = $is_local;
197 if (!empty($created)) {
198 $notice->created = $created;
200 $notice->created = common_sql_now();
203 $notice->content = $final;
204 $notice->rendered = common_render_content($final, $notice);
205 $notice->source = $source;
208 $notice->reply_to = self::getReplyTo($reply_to, $profile_id, $source, $final);
210 if (!empty($notice->reply_to)) {
211 $reply = Notice::staticGet('id', $notice->reply_to);
212 $notice->conversation = $reply->conversation;
215 if (Event::handle('StartNoticeSave', array(&$notice))) {
217 // XXX: some of these functions write to the DB
219 $notice->query('BEGIN');
221 $id = $notice->insert();
224 common_log_db_error($notice, 'INSERT', __FILE__);
225 return _('Problem saving notice.');
228 // Update ID-dependent columns: URI, conversation
230 $orig = clone($notice);
235 $notice->uri = common_notice_uri($notice);
239 // If it's not part of a conversation, it's
240 // the beginning of a new conversation.
242 if (empty($notice->conversation)) {
243 $notice->conversation = $notice->id;
248 if (!$notice->update($orig)) {
249 common_log_db_error($notice, 'UPDATE', __FILE__);
250 return _('Problem saving notice.');
254 // XXX: do we need to change this for remote users?
256 $notice->saveReplies();
259 $notice->addToInboxes();
263 $notice->query('COMMIT');
265 Event::handle('EndNoticeSave', array($notice));
268 # Clear the cache for subscribed users, so they'll update at next request
269 # XXX: someone clever could prepend instead of clearing the cache
271 $notice->blowCaches();
276 /** save all urls in the notice to the db
278 * follow redirects and save all available file information
279 * (mimetype, date, size, oembed, etc.)
283 function saveUrls() {
284 common_replace_urls_callback($this->content, array($this, 'saveUrl'), $this->id);
287 function saveUrl($data) {
288 list($url, $notice_id) = $data;
289 File::processNew($url, $notice_id);
292 static function checkDupes($profile_id, $content) {
293 $profile = Profile::staticGet($profile_id);
297 $notice = $profile->getNotices(0, NOTICE_CACHE_WINDOW);
300 while ($notice->fetch()) {
301 if (time() - strtotime($notice->created) >= common_config('site', 'dupelimit')) {
303 } else if ($notice->content == $content) {
308 # If we get here, oldest item in cache window is not
309 # old enough for dupe limit; do direct check against DB
310 $notice = new Notice();
311 $notice->profile_id = $profile_id;
312 $notice->content = $content;
313 if (common_config('db','type') == 'pgsql')
314 $notice->whereAdd('extract(epoch from now() - created) < ' . common_config('site', 'dupelimit'));
316 $notice->whereAdd('now() - created < ' . common_config('site', 'dupelimit'));
318 $cnt = $notice->count();
322 static function checkEditThrottle($profile_id) {
323 $profile = Profile::staticGet($profile_id);
328 $notice = $profile->getNotices(common_config('throttle', 'count') - 1, 1);
329 if ($notice && $notice->fetch()) {
330 # If the Nth notice was posted less than timespan seconds ago
331 if (time() - strtotime($notice->created) <= common_config('throttle', 'timespan')) {
336 # Either not N notices in the stream, OR the Nth was not posted within timespan seconds
340 function getUploadedAttachment() {
342 $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"';
343 $post->query($query);
345 if (empty($post->up) || empty($post->i)) {
348 $ret = array($post->up, $post->i);
354 function hasAttachments() {
356 $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);
357 $post->query($query);
359 $n_attachments = intval($post->n_attachments);
361 return $n_attachments;
364 function attachments() {
367 $f2p = new File_to_post;
368 $f2p->post_id = $this->id;
370 while ($f2p->fetch()) {
371 $f = File::staticGet($f2p->file_id);
378 function blowCaches($blowLast=false)
380 $this->blowSubsCache($blowLast);
381 $this->blowNoticeCache($blowLast);
382 $this->blowRepliesCache($blowLast);
383 $this->blowPublicCache($blowLast);
384 $this->blowTagCache($blowLast);
385 $this->blowGroupCache($blowLast);
386 $this->blowConversationCache($blowLast);
387 $profile = Profile::staticGet($this->profile_id);
388 $profile->blowNoticeCount();
391 function blowConversationCache($blowLast=false)
393 $cache = common_memcache();
395 $ck = common_cache_key('notice:conversation_ids:'.$this->conversation);
398 $cache->delete($ck.';last');
403 function blowGroupCache($blowLast=false)
405 $cache = common_memcache();
407 $group_inbox = new Group_inbox();
408 $group_inbox->notice_id = $this->id;
409 if ($group_inbox->find()) {
410 while ($group_inbox->fetch()) {
411 $cache->delete(common_cache_key('user_group:notice_ids:' . $group_inbox->group_id));
413 $cache->delete(common_cache_key('user_group:notice_ids:' . $group_inbox->group_id.';last'));
415 $member = new Group_member();
416 $member->group_id = $group_inbox->group_id;
417 if ($member->find()) {
418 while ($member->fetch()) {
419 $cache->delete(common_cache_key('notice_inbox:by_user:' . $member->profile_id));
421 $cache->delete(common_cache_key('notice_inbox:by_user:' . $member->profile_id . ';last'));
427 $group_inbox->free();
432 function blowTagCache($blowLast=false)
434 $cache = common_memcache();
436 $tag = new Notice_tag();
437 $tag->notice_id = $this->id;
439 while ($tag->fetch()) {
440 $tag->blowCache($blowLast);
441 $ck = 'profile:notice_ids_tagged:' . $this->profile_id . ':' . $tag->tag;
445 $cache->delete($ck . ';last');
454 function blowSubsCache($blowLast=false)
456 $cache = common_memcache();
460 $UT = common_config('db','type')=='pgsql'?'"user"':'user';
461 $user->query('SELECT id ' .
463 "FROM $UT JOIN subscription ON $UT.id = subscription.subscriber " .
464 'WHERE subscription.subscribed = ' . $this->profile_id);
466 while ($user->fetch()) {
467 $cache->delete(common_cache_key('notice_inbox:by_user:'.$user->id));
468 $cache->delete(common_cache_key('notice_inbox:by_user_own:'.$user->id));
470 $cache->delete(common_cache_key('notice_inbox:by_user:'.$user->id.';last'));
471 $cache->delete(common_cache_key('notice_inbox:by_user_own:'.$user->id.';last'));
479 function blowNoticeCache($blowLast=false)
481 if ($this->is_local) {
482 $cache = common_memcache();
483 if (!empty($cache)) {
484 $cache->delete(common_cache_key('profile:notice_ids:'.$this->profile_id));
486 $cache->delete(common_cache_key('profile:notice_ids:'.$this->profile_id.';last'));
492 function blowRepliesCache($blowLast=false)
494 $cache = common_memcache();
496 $reply = new Reply();
497 $reply->notice_id = $this->id;
498 if ($reply->find()) {
499 while ($reply->fetch()) {
500 $cache->delete(common_cache_key('reply:stream:'.$reply->profile_id));
502 $cache->delete(common_cache_key('reply:stream:'.$reply->profile_id.';last'));
511 function blowPublicCache($blowLast=false)
513 if ($this->is_local == Notice::LOCAL_PUBLIC) {
514 $cache = common_memcache();
516 $cache->delete(common_cache_key('public'));
518 $cache->delete(common_cache_key('public').';last');
524 function blowFavesCache($blowLast=false)
526 $cache = common_memcache();
529 $fave->notice_id = $this->id;
531 while ($fave->fetch()) {
532 $cache->delete(common_cache_key('fave:ids_by_user:'.$fave->user_id));
533 $cache->delete(common_cache_key('fave:by_user_own:'.$fave->user_id));
535 $cache->delete(common_cache_key('fave:ids_by_user:'.$fave->user_id.';last'));
536 $cache->delete(common_cache_key('fave:by_user_own:'.$fave->user_id.';last'));
545 # XXX: too many args; we need to move to named params or even a separate
546 # class for notice streams
548 static function getStream($qry, $cachekey, $offset=0, $limit=20, $since_id=0, $max_id=0, $order=null, $since=null) {
550 if (common_config('memcached', 'enabled')) {
552 # Skip the cache if this is a since, since_id or max_id qry
553 if ($since_id > 0 || $max_id > 0 || $since) {
554 return Notice::getStreamDirect($qry, $offset, $limit, $since_id, $max_id, $order, $since);
556 return Notice::getCachedStream($qry, $cachekey, $offset, $limit, $order);
560 return Notice::getStreamDirect($qry, $offset, $limit, $since_id, $max_id, $order, $since);
563 static function getStreamDirect($qry, $offset, $limit, $since_id, $max_id, $order, $since) {
568 if (preg_match('/\bWHERE\b/i', $qry)) {
582 $qry .= ' notice.id > ' . $since_id;
594 $qry .= ' notice.id <= ' . $max_id;
606 $qry .= ' notice.created > \'' . date('Y-m-d H:i:s', $since) . '\'';
609 # Allow ORDER override
614 $qry .= ' ORDER BY notice.created DESC, notice.id DESC ';
617 if (common_config('db','type') == 'pgsql') {
618 $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
620 $qry .= ' LIMIT ' . $offset . ', ' . $limit;
623 $notice = new Notice();
625 $notice->query($qry);
630 # XXX: this is pretty long and should probably be broken up into
631 # some helper functions
633 static function getCachedStream($qry, $cachekey, $offset, $limit, $order) {
635 # If outside our cache window, just go to the DB
637 if ($offset + $limit > NOTICE_CACHE_WINDOW) {
638 return Notice::getStreamDirect($qry, $offset, $limit, null, null, $order, null);
641 # Get the cache; if we can't, just go to the DB
643 $cache = common_memcache();
646 return Notice::getStreamDirect($qry, $offset, $limit, null, null, $order, null);
649 # Get the notices out of the cache
651 $notices = $cache->get(common_cache_key($cachekey));
653 # On a cache hit, return a DB-object-like wrapper
655 if ($notices !== false) {
656 $wrapper = new ArrayWrapper(array_slice($notices, $offset, $limit));
660 # If the cache was invalidated because of new data being
661 # added, we can try and just get the new stuff. We keep an additional
662 # copy of the data at the key + ';last'
664 # No cache hit. Try to get the *last* cached version
666 $last_notices = $cache->get(common_cache_key($cachekey) . ';last');
670 # Reverse-chron order, so last ID is last.
672 $last_id = $last_notices[0]->id;
674 # XXX: this assumes monotonically increasing IDs; a fair
677 $new_notice = Notice::getStreamDirect($qry, 0, NOTICE_CACHE_WINDOW,
678 $last_id, null, $order, null);
681 $new_notices = array();
682 while ($new_notice->fetch()) {
683 $new_notices[] = clone($new_notice);
686 $notices = array_slice(array_merge($new_notices, $last_notices),
687 0, NOTICE_CACHE_WINDOW);
689 # Store the array in the cache for next time
691 $result = $cache->set(common_cache_key($cachekey), $notices);
692 $result = $cache->set(common_cache_key($cachekey) . ';last', $notices);
694 # return a wrapper of the array for use now
696 return new ArrayWrapper(array_slice($notices, $offset, $limit));
700 # Otherwise, get the full cache window out of the DB
702 $notice = Notice::getStreamDirect($qry, 0, NOTICE_CACHE_WINDOW, null, null, $order, null);
704 # If there are no hits, just return the value
710 # Pack results into an array
714 while ($notice->fetch()) {
715 $notices[] = clone($notice);
720 # Store the array in the cache for next time
722 $result = $cache->set(common_cache_key($cachekey), $notices);
723 $result = $cache->set(common_cache_key($cachekey) . ';last', $notices);
725 # return a wrapper of the array for use now
727 $wrapper = new ArrayWrapper(array_slice($notices, $offset, $limit));
732 function getStreamByIds($ids)
734 $cache = common_memcache();
736 if (!empty($cache)) {
738 foreach ($ids as $id) {
739 $n = Notice::staticGet('id', $id);
744 return new ArrayWrapper($notices);
746 $notice = new Notice();
748 //if no IDs requested, just return the notice object
751 $notice->whereAdd('id in (' . implode(', ', $ids) . ')');
752 $notice->orderBy('id DESC');
759 function publicStream($offset=0, $limit=20, $since_id=0, $max_id=0, $since=null)
761 $ids = Notice::stream(array('Notice', '_publicStreamDirect'),
764 $offset, $limit, $since_id, $max_id, $since);
766 return Notice::getStreamByIds($ids);
769 function _publicStreamDirect($offset=0, $limit=20, $since_id=0, $max_id=0, $since=null)
771 $notice = new Notice();
773 $notice->selectAdd(); // clears it
774 $notice->selectAdd('id');
776 $notice->orderBy('id DESC');
778 if (!is_null($offset)) {
779 $notice->limit($offset, $limit);
782 if (common_config('public', 'localonly')) {
783 $notice->whereAdd('is_local = ' . Notice::LOCAL_PUBLIC);
785 # -1 == blacklisted, -2 == gateway (i.e. Twitter)
786 $notice->whereAdd('is_local !='. Notice::LOCAL_NONPUBLIC);
787 $notice->whereAdd('is_local !='. Notice::GATEWAY);
790 if ($since_id != 0) {
791 $notice->whereAdd('id > ' . $since_id);
795 $notice->whereAdd('id <= ' . $max_id);
798 if (!is_null($since)) {
799 $notice->whereAdd('created > \'' . date('Y-m-d H:i:s', $since) . '\'');
804 if ($notice->find()) {
805 while ($notice->fetch()) {
806 $ids[] = $notice->id;
816 function conversationStream($id, $offset=0, $limit=20, $since_id=0, $max_id=0, $since=null)
818 $ids = Notice::stream(array('Notice', '_conversationStreamDirect'),
820 'notice:conversation_ids:'.$id,
821 $offset, $limit, $since_id, $max_id, $since);
823 return Notice::getStreamByIds($ids);
826 function _conversationStreamDirect($id, $offset=0, $limit=20, $since_id=0, $max_id=0, $since=null)
828 $notice = new Notice();
830 $notice->selectAdd(); // clears it
831 $notice->selectAdd('id');
833 $notice->conversation = $id;
835 $notice->orderBy('id DESC');
837 if (!is_null($offset)) {
838 $notice->limit($offset, $limit);
841 if ($since_id != 0) {
842 $notice->whereAdd('id > ' . $since_id);
846 $notice->whereAdd('id <= ' . $max_id);
849 if (!is_null($since)) {
850 $notice->whereAdd('created > \'' . date('Y-m-d H:i:s', $since) . '\'');
855 if ($notice->find()) {
856 while ($notice->fetch()) {
857 $ids[] = $notice->id;
867 function addToInboxes()
869 $enabled = common_config('inboxes', 'enabled');
871 if ($enabled === true || $enabled === 'transitional') {
873 // XXX: loads constants
875 $inbox = new Notice_inbox();
877 $users = $this->getSubscribedUsers();
879 // FIXME: kind of ignoring 'transitional'...
880 // we'll probably stop supporting inboxless mode
885 foreach ($users as $id) {
886 $ni[$id] = NOTICE_INBOX_SOURCE_SUB;
889 $groups = $this->saveGroups();
891 foreach ($groups as $group) {
892 $users = $group->getUserMembers();
893 foreach ($users as $id) {
894 if (!array_key_exists($id, $ni)) {
895 $ni[$id] = NOTICE_INBOX_SOURCE_GROUP;
902 $qryhdr = 'INSERT INTO notice_inbox (user_id, notice_id, source, created) VALUES ';
905 foreach ($ni as $id => $source) {
909 $qry .= '('.$id.', '.$this->id.', '.$source.", '".$this->created. "') ";
911 if (rand() % NOTICE_INBOX_SOFT_LIMIT == 0) {
912 Notice_inbox::gc($id);
914 if ($cnt >= MAX_BOXCARS) {
915 $inbox = new Notice_inbox();
923 $inbox = new Notice_inbox();
931 function getSubscribedUsers()
935 if(common_config('db','quote_identifiers'))
936 $user_table = '"user"';
937 else $user_table = 'user';
941 'FROM '. $user_table .' JOIN subscription '.
942 'ON '. $user_table .'.id = subscription.subscriber ' .
943 'WHERE subscription.subscribed = %d ';
945 $user->query(sprintf($qry, $this->profile_id));
949 while ($user->fetch()) {
958 function saveGroups()
962 $enabled = common_config('inboxes', 'enabled');
963 if ($enabled !== true && $enabled !== 'transitional') {
967 /* extract all !group */
968 $count = preg_match_all('/(?:^|\s)!([A-Za-z0-9]{1,64})/',
969 strtolower($this->content),
975 $profile = $this->getProfile();
977 /* Add them to the database */
979 foreach (array_unique($match[1]) as $nickname) {
980 /* XXX: remote groups. */
981 $group = User_group::getForNickname($nickname);
987 // we automatically add a tag for every group name, too
989 $tag = Notice_tag::pkeyGet(array('tag' => common_canonical_tag($nickname),
990 'notice_id' => $this->id));
993 $this->saveTag($nickname);
996 if ($profile->isMember($group)) {
998 $result = $this->addToGroupInbox($group);
1001 common_log_db_error($gi, 'INSERT', __FILE__);
1004 $groups[] = clone($group);
1011 function addToGroupInbox($group)
1013 $gi = Group_inbox::pkeyGet(array('group_id' => $group->id,
1014 'notice_id' => $this->id));
1018 $gi = new Group_inbox();
1020 $gi->group_id = $group->id;
1021 $gi->notice_id = $this->id;
1022 $gi->created = $this->created;
1024 return $gi->insert();
1030 function saveReplies()
1032 // Alternative reply format
1034 if (preg_match('/^T ([A-Z0-9]{1,64}) /', $this->content, $match)) {
1037 // extract all @messages
1038 $cnt = preg_match_all('/(?:^|\s)@([a-z0-9]{1,64})/', $this->content, $match);
1042 if ($cnt || $tname) {
1043 // XXX: is there another way to make an array copy?
1044 $names = ($tname) ? array_unique(array_merge(array(strtolower($tname)), $match[1])) : array_unique($match[1]);
1047 $sender = Profile::staticGet($this->profile_id);
1051 // store replied only for first @ (what user/notice what the reply directed,
1052 // we assume first @ is it)
1054 for ($i=0; $i<count($names); $i++) {
1055 $nickname = $names[$i];
1056 $recipient = common_relative_profile($sender, $nickname, $this->created);
1060 // Don't save replies from blocked profile to local user
1061 $recipient_user = User::staticGet('id', $recipient->id);
1062 if ($recipient_user && $recipient_user->hasBlocked($sender)) {
1065 $reply = new Reply();
1066 $reply->notice_id = $this->id;
1067 $reply->profile_id = $recipient->id;
1068 $id = $reply->insert();
1070 $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError');
1071 common_log(LOG_ERR, 'DB error inserting reply: ' . $last_error->message);
1072 common_server_error(sprintf(_('DB error inserting reply: %s'), $last_error->message));
1075 $replied[$recipient->id] = 1;
1079 // Hash format replies, too
1080 $cnt = preg_match_all('/(?:^|\s)@#([a-z0-9]{1,64})/', $this->content, $match);
1082 foreach ($match[1] as $tag) {
1083 $tagged = Profile_tag::getTagged($sender->id, $tag);
1084 foreach ($tagged as $t) {
1085 if (!$replied[$t->id]) {
1086 // Don't save replies from blocked profile to local user
1087 $t_user = User::staticGet('id', $t->id);
1088 if ($t_user && $t_user->hasBlocked($sender)) {
1091 $reply = new Reply();
1092 $reply->notice_id = $this->id;
1093 $reply->profile_id = $t->id;
1094 $id = $reply->insert();
1096 common_log_db_error($reply, 'INSERT', __FILE__);
1099 $replied[$recipient->id] = 1;
1106 foreach (array_keys($replied) as $recipient) {
1107 $user = User::staticGet('id', $recipient);
1109 mail_notify_attn($user, $this);
1114 function asAtomEntry($namespace=false, $source=false)
1116 $profile = $this->getProfile();
1118 $xs = new XMLStringer(true);
1121 $attrs = array('xmlns' => 'http://www.w3.org/2005/Atom',
1122 'xmlns:thr' => 'http://purl.org/syndication/thread/1.0');
1127 $xs->elementStart('entry', $attrs);
1130 $xs->elementStart('source');
1131 $xs->element('title', null, $profile->nickname . " - " . common_config('site', 'name'));
1132 $xs->element('link', array('href' => $profile->profileurl));
1133 $user = User::staticGet('id', $profile->id);
1134 if (!empty($user)) {
1135 $atom_feed = common_local_url('api',
1136 array('apiaction' => 'statuses',
1137 'method' => 'user_timeline',
1138 'argument' => $profile->nickname.'.atom'));
1139 $xs->element('link', array('rel' => 'self',
1140 'type' => 'application/atom+xml',
1141 'href' => $profile->profileurl));
1142 $xs->element('link', array('rel' => 'license',
1143 'href' => common_config('license', 'url')));
1146 $xs->element('icon', null, $profile->avatarUrl(AVATAR_PROFILE_SIZE));
1149 $xs->elementStart('author');
1150 $xs->element('name', null, $profile->nickname);
1151 $xs->element('uri', null, $profile->profileurl);
1152 $xs->elementEnd('author');
1155 $xs->elementEnd('source');
1158 $xs->element('title', null, $this->content);
1159 $xs->element('summary', null, $this->content);
1161 $xs->element('link', array('rel' => 'alternate',
1162 'href' => $this->bestUrl()));
1164 $xs->element('id', null, $this->uri);
1166 $xs->element('published', null, common_date_w3dtf($this->created));
1167 $xs->element('updated', null, common_date_w3dtf($this->modified));
1169 if ($this->reply_to) {
1170 $reply_notice = Notice::staticGet('id', $this->reply_to);
1171 if (!empty($reply_notice)) {
1172 $xs->element('link', array('rel' => 'related',
1173 'href' => $reply_notice->bestUrl()));
1174 $xs->element('thr:in-reply-to',
1175 array('ref' => $reply_notice->uri,
1176 'href' => $reply_notice->bestUrl()));
1180 $xs->element('content', array('type' => 'html'), $this->rendered);
1182 $tag = new Notice_tag();
1183 $tag->notice_id = $this->id;
1185 while ($tag->fetch()) {
1186 $xs->element('category', array('term' => $tag->tag));
1192 $attachments = $this->attachments();
1194 foreach($attachments as $attachment){
1195 $enclosure=$attachment->getEnclosure();
1197 $attributes = array('rel'=>'enclosure','href'=>$enclosure->url,'type'=>$enclosure->mimetype,'length'=>$enclosure->size);
1198 if($enclosure->title){
1199 $attributes['title']=$enclosure->title;
1201 $xs->element('link', $attributes, null);
1206 $xs->elementEnd('entry');
1208 return $xs->getString();
1213 if (!empty($this->url)) {
1215 } else if (!empty($this->uri) && preg_match('/^https?:/', $this->uri)) {
1218 return common_local_url('shownotice',
1219 array('notice' => $this->id));
1223 function stream($fn, $args, $cachekey, $offset=0, $limit=20, $since_id=0, $max_id=0, $since=null)
1225 $cache = common_memcache();
1227 if (empty($cache) ||
1228 $since_id != 0 || $max_id != 0 || (!is_null($since) && $since > 0) ||
1230 ($offset + $limit) > NOTICE_CACHE_WINDOW) {
1231 return call_user_func_array($fn, array_merge($args, array($offset, $limit, $since_id,
1235 $idkey = common_cache_key($cachekey);
1237 $idstr = $cache->get($idkey);
1239 if (!empty($idstr)) {
1240 // Cache hit! Woohoo!
1241 $window = explode(',', $idstr);
1242 $ids = array_slice($window, $offset, $limit);
1246 $laststr = $cache->get($idkey.';last');
1248 if (!empty($laststr)) {
1249 $window = explode(',', $laststr);
1250 $last_id = $window[0];
1251 $new_ids = call_user_func_array($fn, array_merge($args, array(0, NOTICE_CACHE_WINDOW,
1252 $last_id, 0, null)));
1254 $new_window = array_merge($new_ids, $window);
1256 $new_windowstr = implode(',', $new_window);
1258 $result = $cache->set($idkey, $new_windowstr);
1259 $result = $cache->set($idkey . ';last', $new_windowstr);
1261 $ids = array_slice($new_window, $offset, $limit);
1266 $window = call_user_func_array($fn, array_merge($args, array(0, NOTICE_CACHE_WINDOW,
1269 $windowstr = implode(',', $window);
1271 $result = $cache->set($idkey, $windowstr);
1272 $result = $cache->set($idkey . ';last', $windowstr);
1274 $ids = array_slice($window, $offset, $limit);
1280 * Determine which notice, if any, a new notice is in reply to.
1282 * For conversation tracking, we try to see where this notice fits
1283 * in the tree. Rough algorithm is:
1285 * if (reply_to is set and valid) {
1287 * } else if ((source not API or Web) and (content starts with "T NAME" or "@name ")) {
1288 * return ID of last notice by initial @name in content;
1291 * Note that all @nickname instances will still be used to save "reply" records,
1292 * so the notice shows up in the mentioned users' "replies" tab.
1294 * @param integer $reply_to ID passed in by Web or API
1295 * @param integer $profile_id ID of author
1296 * @param string $source Source tag, like 'web' or 'gwibber'
1297 * @param string $content Final notice content
1299 * @return integer ID of replied-to notice, or null for not a reply.
1302 static function getReplyTo($reply_to, $profile_id, $source, $content)
1304 static $lb = array('xmpp', 'mail', 'sms', 'omb');
1306 // If $reply_to is specified, we check that it exists, and then
1307 // return it if it does
1309 if (!empty($reply_to)) {
1310 $reply_notice = Notice::staticGet('id', $reply_to);
1311 if (!empty($reply_notice)) {
1316 // If it's not a "low bandwidth" source (one where you can't set
1317 // a reply_to argument), we return. This is mostly web and API
1320 if (!in_array($source, $lb)) {
1324 // Is there an initial @ or T?
1326 if (preg_match('/^T ([A-Z0-9]{1,64}) /', $content, $match) ||
1327 preg_match('/^@([a-z0-9]{1,64})\s+/', $content, $match)) {
1328 $nickname = common_canonical_nickname($match[1]);
1333 // Figure out who that is.
1335 $sender = Profile::staticGet('id', $profile_id);
1336 $recipient = common_relative_profile($sender, $nickname, common_sql_now());
1338 if (empty($recipient)) {
1342 // Get their last notice
1344 $last = $recipient->getCurrentNotice();
1346 if (!empty($last)) {
1351 static function maxContent()
1353 $contentlimit = common_config('notice', 'contentlimit');
1354 // null => use global limit (distinct from 0!)
1355 if (is_null($contentlimit)) {
1356 $contentlimit = common_config('site', 'textlimit');
1358 return $contentlimit;
1361 static function contentTooLong($content)
1363 $contentlimit = self::maxContent();
1364 return ($contentlimit > 0 && !empty($content) && (mb_strlen($content) > $contentlimit));