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) multiple_key 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 multiple_key not_null default_0000-00-00%2000%3A00%3A00
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)
69 public $lat; // decimal(10,7)
70 public $lon; // decimal(10,7)
71 public $location_id; // int(4)
72 public $location_ns; // int(4)
73 public $repeat_of; // int(4)
76 function staticGet($k,$v=NULL)
78 return Memcached_DataObject::staticGet('Notice',$k,$v);
81 /* the code above is auto generated do not remove the tag below */
85 const LOCAL_PUBLIC = 1;
87 const LOCAL_NONPUBLIC = -1;
92 return Profile::staticGet('id', $this->profile_id);
97 $this->blowCaches(true);
98 $this->blowFavesCache(true);
99 $this->blowSubsCache(true);
101 // For auditing purposes, save a record that the notice
104 $deleted = new Deleted_notice();
106 $deleted->id = $this->id;
107 $deleted->profile_id = $this->profile_id;
108 $deleted->uri = $this->uri;
109 $deleted->created = $this->created;
110 $deleted->deleted = common_sql_now();
112 $this->query('BEGIN');
116 //Null any notices that are replies to this notice
117 $this->query(sprintf("UPDATE notice set reply_to = null WHERE reply_to = %d", $this->id));
118 $related = array('Reply',
125 foreach ($related as $cls) {
127 $inst->notice_id = $this->id;
130 $result = parent::delete();
131 $this->query('COMMIT');
136 /* extract all #hastags */
137 $count = preg_match_all('/(?:^|\s)#([\pL\pN_\-\.]{1,64})/', strtolower($this->content), $match);
142 //turn each into their canonical tag
143 //this is needed to remove dupes before saving e.g. #hash.tag = #hashtag
145 for($i=0; $i<count($match[1]); $i++) {
146 $hashtags[] = common_canonical_tag($match[1][$i]);
149 /* Add them to the database */
150 foreach(array_unique($hashtags) as $hashtag) {
151 /* elide characters we don't want in the tag */
152 $this->saveTag($hashtag);
157 function saveTag($hashtag)
159 $tag = new Notice_tag();
160 $tag->notice_id = $this->id;
161 $tag->tag = $hashtag;
162 $tag->created = $this->created;
163 $id = $tag->insert();
166 throw new ServerException(sprintf(_('DB error inserting hashtag: %s'),
167 $last_error->message));
172 static function saveNew($profile_id, $content, $source, $options=null) {
174 if (!empty($options)) {
176 if (!isset($reply_to)) {
181 if (empty($is_local)) {
182 $is_local = Notice::LOCAL_PUBLIC;
185 $profile = Profile::staticGet($profile_id);
187 $final = common_shorten_links($content);
189 if (Notice::contentTooLong($final)) {
190 throw new ClientException(_('Problem saving notice. Too long.'));
193 if (empty($profile)) {
194 throw new ClientException(_('Problem saving notice. Unknown user.'));
197 if (common_config('throttle', 'enabled') && !Notice::checkEditThrottle($profile_id)) {
198 common_log(LOG_WARNING, 'Excessive posting by profile #' . $profile_id . '; throttled.');
199 throw new ClientException(_('Too many notices too fast; take a breather '.
200 'and post again in a few minutes.'));
203 if (common_config('site', 'dupelimit') > 0 && !Notice::checkDupes($profile_id, $final)) {
204 common_log(LOG_WARNING, 'Dupe posting by profile #' . $profile_id . '; throttled.');
205 throw new ClientException(_('Too many duplicate messages too quickly;'.
206 ' take a breather and post again in a few minutes.'));
209 if (!$profile->hasRight(Right::NEWNOTICE)) {
210 common_log(LOG_WARNING, "Attempted post from user disallowed to post: " . $profile->nickname);
211 throw new ClientException(_('You are banned from posting notices on this site.'));
214 $notice = new Notice();
215 $notice->profile_id = $profile_id;
217 $autosource = common_config('public', 'autosource');
219 # Sandboxed are non-false, but not 1, either
221 if (!$profile->hasRight(Right::PUBLICNOTICE) ||
222 ($source && $autosource && in_array($source, $autosource))) {
223 $notice->is_local = Notice::LOCAL_NONPUBLIC;
225 $notice->is_local = $is_local;
228 if (!empty($created)) {
229 $notice->created = $created;
231 $notice->created = common_sql_now();
234 $notice->content = $final;
235 $notice->rendered = common_render_content($final, $notice);
236 $notice->source = $source;
239 // Handle repeat case
241 if (isset($repeat_of)) {
242 $notice->repeat_of = $repeat_of;
243 $notice->reply_to = $repeat_of;
245 $notice->reply_to = self::getReplyTo($reply_to, $profile_id, $source, $final);
248 if (!empty($notice->reply_to)) {
249 $reply = Notice::staticGet('id', $notice->reply_to);
250 $notice->conversation = $reply->conversation;
253 if (!empty($lat) && !empty($lon)) {
256 $notice->location_id = $location_id;
257 $notice->location_ns = $location_ns;
258 } else if (!empty($location_ns) && !empty($location_id)) {
259 $location = Location::fromId($location_id, $location_ns);
260 if (!empty($location)) {
261 $notice->lat = $location->lat;
262 $notice->lon = $location->lon;
263 $notice->location_id = $location_id;
264 $notice->location_ns = $location_ns;
267 $notice->lat = $profile->lat;
268 $notice->lon = $profile->lon;
269 $notice->location_id = $profile->location_id;
270 $notice->location_ns = $profile->location_ns;
273 if (Event::handle('StartNoticeSave', array(&$notice))) {
275 // XXX: some of these functions write to the DB
277 $notice->query('BEGIN');
279 $id = $notice->insert();
282 common_log_db_error($notice, 'INSERT', __FILE__);
283 throw new ServerException(_('Problem saving notice.'));
286 // Update ID-dependent columns: URI, conversation
288 $orig = clone($notice);
293 $notice->uri = common_notice_uri($notice);
297 // If it's not part of a conversation, it's
298 // the beginning of a new conversation.
300 if (empty($notice->conversation)) {
301 $notice->conversation = $notice->id;
306 if (!$notice->update($orig)) {
307 common_log_db_error($notice, 'UPDATE', __FILE__);
308 throw new ServerException(_('Problem saving notice.'));
312 // XXX: do we need to change this for remote users?
316 $notice->addToInboxes();
320 $notice->query('COMMIT');
322 Event::handle('EndNoticeSave', array($notice));
325 # Clear the cache for subscribed users, so they'll update at next request
326 # XXX: someone clever could prepend instead of clearing the cache
328 $notice->blowCaches();
333 /** save all urls in the notice to the db
335 * follow redirects and save all available file information
336 * (mimetype, date, size, oembed, etc.)
340 function saveUrls() {
341 common_replace_urls_callback($this->content, array($this, 'saveUrl'), $this->id);
344 function saveUrl($data) {
345 list($url, $notice_id) = $data;
346 File::processNew($url, $notice_id);
349 static function checkDupes($profile_id, $content) {
350 $profile = Profile::staticGet($profile_id);
351 if (empty($profile)) {
354 $notice = $profile->getNotices(0, NOTICE_CACHE_WINDOW);
355 if (!empty($notice)) {
357 while ($notice->fetch()) {
358 if (time() - strtotime($notice->created) >= common_config('site', 'dupelimit')) {
360 } else if ($notice->content == $content) {
365 # If we get here, oldest item in cache window is not
366 # old enough for dupe limit; do direct check against DB
367 $notice = new Notice();
368 $notice->profile_id = $profile_id;
369 $notice->content = $content;
370 if (common_config('db','type') == 'pgsql')
371 $notice->whereAdd('extract(epoch from now() - created) < ' . common_config('site', 'dupelimit'));
373 $notice->whereAdd('now() - created < ' . common_config('site', 'dupelimit'));
375 $cnt = $notice->count();
379 static function checkEditThrottle($profile_id) {
380 $profile = Profile::staticGet($profile_id);
381 if (empty($profile)) {
385 $notice = $profile->getNotices(common_config('throttle', 'count') - 1, 1);
386 if ($notice && $notice->fetch()) {
387 # If the Nth notice was posted less than timespan seconds ago
388 if (time() - strtotime($notice->created) <= common_config('throttle', 'timespan')) {
393 # Either not N notices in the stream, OR the Nth was not posted within timespan seconds
397 function getUploadedAttachment() {
399 $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"';
400 $post->query($query);
402 if (empty($post->up) || empty($post->i)) {
405 $ret = array($post->up, $post->i);
411 function hasAttachments() {
413 $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);
414 $post->query($query);
416 $n_attachments = intval($post->n_attachments);
418 return $n_attachments;
421 function attachments() {
424 $f2p = new File_to_post;
425 $f2p->post_id = $this->id;
427 while ($f2p->fetch()) {
428 $f = File::staticGet($f2p->file_id);
435 function blowCaches($blowLast=false)
437 $this->blowSubsCache($blowLast);
438 $this->blowNoticeCache($blowLast);
439 $this->blowRepliesCache($blowLast);
440 $this->blowPublicCache($blowLast);
441 $this->blowTagCache($blowLast);
442 $this->blowGroupCache($blowLast);
443 $this->blowConversationCache($blowLast);
444 $this->blowRepeatCache();
445 $profile = Profile::staticGet($this->profile_id);
446 $profile->blowNoticeCount();
449 function blowRepeatCache()
451 if (!empty($this->repeat_of)) {
452 $cache = common_memcache();
453 if (!empty($cache)) {
454 // XXX: only blow if <100 in cache
455 $ck = common_cache_key('notice:repeats:'.$this->repeat_of);
456 $result = $cache->delete($ck);
458 $user = User::staticGet('id', $this->profile_id);
461 $uk = common_cache_key('user:repeated_by_me:'.$user->id);
470 function blowConversationCache($blowLast=false)
472 $cache = common_memcache();
474 $ck = common_cache_key('notice:conversation_ids:'.$this->conversation);
477 $cache->delete($ck.';last');
482 function blowGroupCache($blowLast=false)
484 $cache = common_memcache();
486 $group_inbox = new Group_inbox();
487 $group_inbox->notice_id = $this->id;
488 if ($group_inbox->find()) {
489 while ($group_inbox->fetch()) {
490 $cache->delete(common_cache_key('user_group:notice_ids:' . $group_inbox->group_id));
492 $cache->delete(common_cache_key('user_group:notice_ids:' . $group_inbox->group_id.';last'));
494 $member = new Group_member();
495 $member->group_id = $group_inbox->group_id;
496 if ($member->find()) {
497 while ($member->fetch()) {
498 $cache->delete(common_cache_key('notice_inbox:by_user:' . $member->profile_id));
500 $cache->delete(common_cache_key('notice_inbox:by_user:' . $member->profile_id . ';last'));
506 $group_inbox->free();
511 function blowTagCache($blowLast=false)
513 $cache = common_memcache();
515 $tag = new Notice_tag();
516 $tag->notice_id = $this->id;
518 while ($tag->fetch()) {
519 $tag->blowCache($blowLast);
520 $ck = 'profile:notice_ids_tagged:' . $this->profile_id . ':' . $tag->tag;
524 $cache->delete($ck . ';last');
533 function blowSubsCache($blowLast=false)
535 $cache = common_memcache();
539 $UT = common_config('db','type')=='pgsql'?'"user"':'user';
540 $user->query('SELECT id ' .
542 "FROM $UT JOIN subscription ON $UT.id = subscription.subscriber " .
543 'WHERE subscription.subscribed = ' . $this->profile_id);
545 while ($user->fetch()) {
546 $cache->delete(common_cache_key('notice_inbox:by_user:'.$user->id));
547 $cache->delete(common_cache_key('notice_inbox:by_user_own:'.$user->id));
549 $cache->delete(common_cache_key('notice_inbox:by_user:'.$user->id.';last'));
550 $cache->delete(common_cache_key('notice_inbox:by_user_own:'.$user->id.';last'));
558 function blowNoticeCache($blowLast=false)
560 if ($this->is_local) {
561 $cache = common_memcache();
562 if (!empty($cache)) {
563 $cache->delete(common_cache_key('profile:notice_ids:'.$this->profile_id));
565 $cache->delete(common_cache_key('profile:notice_ids:'.$this->profile_id.';last'));
571 function blowRepliesCache($blowLast=false)
573 $cache = common_memcache();
575 $reply = new Reply();
576 $reply->notice_id = $this->id;
577 if ($reply->find()) {
578 while ($reply->fetch()) {
579 $cache->delete(common_cache_key('reply:stream:'.$reply->profile_id));
581 $cache->delete(common_cache_key('reply:stream:'.$reply->profile_id.';last'));
590 function blowPublicCache($blowLast=false)
592 if ($this->is_local == Notice::LOCAL_PUBLIC) {
593 $cache = common_memcache();
595 $cache->delete(common_cache_key('public'));
597 $cache->delete(common_cache_key('public').';last');
603 function blowFavesCache($blowLast=false)
605 $cache = common_memcache();
608 $fave->notice_id = $this->id;
610 while ($fave->fetch()) {
611 $cache->delete(common_cache_key('fave:ids_by_user:'.$fave->user_id));
612 $cache->delete(common_cache_key('fave:by_user_own:'.$fave->user_id));
614 $cache->delete(common_cache_key('fave:ids_by_user:'.$fave->user_id.';last'));
615 $cache->delete(common_cache_key('fave:by_user_own:'.$fave->user_id.';last'));
624 # XXX: too many args; we need to move to named params or even a separate
625 # class for notice streams
627 static function getStream($qry, $cachekey, $offset=0, $limit=20, $since_id=0, $max_id=0, $order=null, $since=null) {
629 if (common_config('memcached', 'enabled')) {
631 # Skip the cache if this is a since, since_id or max_id qry
632 if ($since_id > 0 || $max_id > 0 || $since) {
633 return Notice::getStreamDirect($qry, $offset, $limit, $since_id, $max_id, $order, $since);
635 return Notice::getCachedStream($qry, $cachekey, $offset, $limit, $order);
639 return Notice::getStreamDirect($qry, $offset, $limit, $since_id, $max_id, $order, $since);
642 static function getStreamDirect($qry, $offset, $limit, $since_id, $max_id, $order, $since) {
647 if (preg_match('/\bWHERE\b/i', $qry)) {
661 $qry .= ' notice.id > ' . $since_id;
673 $qry .= ' notice.id <= ' . $max_id;
685 $qry .= ' notice.created > \'' . date('Y-m-d H:i:s', $since) . '\'';
688 # Allow ORDER override
693 $qry .= ' ORDER BY notice.created DESC, notice.id DESC ';
696 if (common_config('db','type') == 'pgsql') {
697 $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
699 $qry .= ' LIMIT ' . $offset . ', ' . $limit;
702 $notice = new Notice();
704 $notice->query($qry);
709 # XXX: this is pretty long and should probably be broken up into
710 # some helper functions
712 static function getCachedStream($qry, $cachekey, $offset, $limit, $order) {
714 # If outside our cache window, just go to the DB
716 if ($offset + $limit > NOTICE_CACHE_WINDOW) {
717 return Notice::getStreamDirect($qry, $offset, $limit, null, null, $order, null);
720 # Get the cache; if we can't, just go to the DB
722 $cache = common_memcache();
725 return Notice::getStreamDirect($qry, $offset, $limit, null, null, $order, null);
728 # Get the notices out of the cache
730 $notices = $cache->get(common_cache_key($cachekey));
732 # On a cache hit, return a DB-object-like wrapper
734 if ($notices !== false) {
735 $wrapper = new ArrayWrapper(array_slice($notices, $offset, $limit));
739 # If the cache was invalidated because of new data being
740 # added, we can try and just get the new stuff. We keep an additional
741 # copy of the data at the key + ';last'
743 # No cache hit. Try to get the *last* cached version
745 $last_notices = $cache->get(common_cache_key($cachekey) . ';last');
749 # Reverse-chron order, so last ID is last.
751 $last_id = $last_notices[0]->id;
753 # XXX: this assumes monotonically increasing IDs; a fair
756 $new_notice = Notice::getStreamDirect($qry, 0, NOTICE_CACHE_WINDOW,
757 $last_id, null, $order, null);
760 $new_notices = array();
761 while ($new_notice->fetch()) {
762 $new_notices[] = clone($new_notice);
765 $notices = array_slice(array_merge($new_notices, $last_notices),
766 0, NOTICE_CACHE_WINDOW);
768 # Store the array in the cache for next time
770 $result = $cache->set(common_cache_key($cachekey), $notices);
771 $result = $cache->set(common_cache_key($cachekey) . ';last', $notices);
773 # return a wrapper of the array for use now
775 return new ArrayWrapper(array_slice($notices, $offset, $limit));
779 # Otherwise, get the full cache window out of the DB
781 $notice = Notice::getStreamDirect($qry, 0, NOTICE_CACHE_WINDOW, null, null, $order, null);
783 # If there are no hits, just return the value
785 if (empty($notice)) {
789 # Pack results into an array
793 while ($notice->fetch()) {
794 $notices[] = clone($notice);
799 # Store the array in the cache for next time
801 $result = $cache->set(common_cache_key($cachekey), $notices);
802 $result = $cache->set(common_cache_key($cachekey) . ';last', $notices);
804 # return a wrapper of the array for use now
806 $wrapper = new ArrayWrapper(array_slice($notices, $offset, $limit));
811 function getStreamByIds($ids)
813 $cache = common_memcache();
815 if (!empty($cache)) {
817 foreach ($ids as $id) {
818 $n = Notice::staticGet('id', $id);
823 return new ArrayWrapper($notices);
825 $notice = new Notice();
827 //if no IDs requested, just return the notice object
830 $notice->whereAdd('id in (' . implode(', ', $ids) . ')');
836 while ($notice->fetch()) {
837 $temp[$notice->id] = clone($notice);
842 foreach ($ids as $id) {
843 if (array_key_exists($id, $temp)) {
844 $wrapped[] = $temp[$id];
848 return new ArrayWrapper($wrapped);
852 function publicStream($offset=0, $limit=20, $since_id=0, $max_id=0, $since=null)
854 $ids = Notice::stream(array('Notice', '_publicStreamDirect'),
857 $offset, $limit, $since_id, $max_id, $since);
859 return Notice::getStreamByIds($ids);
862 function _publicStreamDirect($offset=0, $limit=20, $since_id=0, $max_id=0, $since=null)
864 $notice = new Notice();
866 $notice->selectAdd(); // clears it
867 $notice->selectAdd('id');
869 $notice->orderBy('id DESC');
871 if (!is_null($offset)) {
872 $notice->limit($offset, $limit);
875 if (common_config('public', 'localonly')) {
876 $notice->whereAdd('is_local = ' . Notice::LOCAL_PUBLIC);
878 # -1 == blacklisted, -2 == gateway (i.e. Twitter)
879 $notice->whereAdd('is_local !='. Notice::LOCAL_NONPUBLIC);
880 $notice->whereAdd('is_local !='. Notice::GATEWAY);
883 if ($since_id != 0) {
884 $notice->whereAdd('id > ' . $since_id);
888 $notice->whereAdd('id <= ' . $max_id);
891 if (!is_null($since)) {
892 $notice->whereAdd('created > \'' . date('Y-m-d H:i:s', $since) . '\'');
897 if ($notice->find()) {
898 while ($notice->fetch()) {
899 $ids[] = $notice->id;
909 function conversationStream($id, $offset=0, $limit=20, $since_id=0, $max_id=0, $since=null)
911 $ids = Notice::stream(array('Notice', '_conversationStreamDirect'),
913 'notice:conversation_ids:'.$id,
914 $offset, $limit, $since_id, $max_id, $since);
916 return Notice::getStreamByIds($ids);
919 function _conversationStreamDirect($id, $offset=0, $limit=20, $since_id=0, $max_id=0, $since=null)
921 $notice = new Notice();
923 $notice->selectAdd(); // clears it
924 $notice->selectAdd('id');
926 $notice->conversation = $id;
928 $notice->orderBy('id DESC');
930 if (!is_null($offset)) {
931 $notice->limit($offset, $limit);
934 if ($since_id != 0) {
935 $notice->whereAdd('id > ' . $since_id);
939 $notice->whereAdd('id <= ' . $max_id);
942 if (!is_null($since)) {
943 $notice->whereAdd('created > \'' . date('Y-m-d H:i:s', $since) . '\'');
948 if ($notice->find()) {
949 while ($notice->fetch()) {
950 $ids[] = $notice->id;
960 function addToInboxes()
962 // XXX: loads constants
964 $inbox = new Notice_inbox();
966 $users = $this->getSubscribedUsers();
968 // FIXME: kind of ignoring 'transitional'...
969 // we'll probably stop supporting inboxless mode
974 foreach ($users as $id) {
975 $ni[$id] = NOTICE_INBOX_SOURCE_SUB;
978 $groups = $this->saveGroups();
979 $profile = $this->getProfile();
981 foreach ($groups as $group) {
982 $users = $group->getUserMembers();
983 foreach ($users as $id) {
984 if (!array_key_exists($id, $ni)) {
985 $user = User::staticGet('id', $id);
986 if (!$user->hasBlocked($profile)) {
987 $ni[$id] = NOTICE_INBOX_SOURCE_GROUP;
993 $recipients = $this->saveReplies();
995 foreach ($recipients as $recipient) {
997 if (!array_key_exists($recipient, $ni)) {
998 $recipientUser = User::staticGet('id', $recipient);
999 if (!empty($recipientUser)) {
1000 $ni[$recipient] = NOTICE_INBOX_SOURCE_REPLY;
1005 Notice_inbox::bulkInsert($this->id, $this->created, $ni);
1010 function getSubscribedUsers()
1014 if(common_config('db','quote_identifiers'))
1015 $user_table = '"user"';
1016 else $user_table = 'user';
1020 'FROM '. $user_table .' JOIN subscription '.
1021 'ON '. $user_table .'.id = subscription.subscriber ' .
1022 'WHERE subscription.subscribed = %d ';
1024 $user->query(sprintf($qry, $this->profile_id));
1028 while ($user->fetch()) {
1037 function saveGroups()
1041 /* extract all !group */
1042 $count = preg_match_all('/(?:^|\s)!([A-Za-z0-9]{1,64})/',
1043 strtolower($this->content),
1049 $profile = $this->getProfile();
1051 /* Add them to the database */
1053 foreach (array_unique($match[1]) as $nickname) {
1054 /* XXX: remote groups. */
1055 $group = User_group::getForNickname($nickname);
1057 if (empty($group)) {
1061 // we automatically add a tag for every group name, too
1063 $tag = Notice_tag::pkeyGet(array('tag' => common_canonical_tag($nickname),
1064 'notice_id' => $this->id));
1066 if (is_null($tag)) {
1067 $this->saveTag($nickname);
1070 if ($profile->isMember($group)) {
1072 $result = $this->addToGroupInbox($group);
1075 common_log_db_error($gi, 'INSERT', __FILE__);
1078 $groups[] = clone($group);
1085 function addToGroupInbox($group)
1087 $gi = Group_inbox::pkeyGet(array('group_id' => $group->id,
1088 'notice_id' => $this->id));
1092 $gi = new Group_inbox();
1094 $gi->group_id = $group->id;
1095 $gi->notice_id = $this->id;
1096 $gi->created = $this->created;
1098 return $gi->insert();
1104 function saveReplies()
1106 // Alternative reply format
1108 if (preg_match('/^T ([A-Z0-9]{1,64}) /', $this->content, $match)) {
1111 // extract all @messages
1112 $cnt = preg_match_all('/(?:^|\s)@([a-z0-9]{1,64})/', $this->content, $match);
1116 if ($cnt || $tname) {
1117 // XXX: is there another way to make an array copy?
1118 $names = ($tname) ? array_unique(array_merge(array(strtolower($tname)), $match[1])) : array_unique($match[1]);
1121 $sender = Profile::staticGet($this->profile_id);
1125 // store replied only for first @ (what user/notice what the reply directed,
1126 // we assume first @ is it)
1128 for ($i=0; $i<count($names); $i++) {
1129 $nickname = $names[$i];
1130 $recipient = common_relative_profile($sender, $nickname, $this->created);
1131 if (empty($recipient)) {
1134 // Don't save replies from blocked profile to local user
1135 $recipient_user = User::staticGet('id', $recipient->id);
1136 if (!empty($recipient_user) && $recipient_user->hasBlocked($sender)) {
1139 $reply = new Reply();
1140 $reply->notice_id = $this->id;
1141 $reply->profile_id = $recipient->id;
1142 $id = $reply->insert();
1144 $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError');
1145 common_log(LOG_ERR, 'DB error inserting reply: ' . $last_error->message);
1146 common_server_error(sprintf(_('DB error inserting reply: %s'), $last_error->message));
1149 $replied[$recipient->id] = 1;
1153 // Hash format replies, too
1154 $cnt = preg_match_all('/(?:^|\s)@#([a-z0-9]{1,64})/', $this->content, $match);
1156 foreach ($match[1] as $tag) {
1157 $tagged = Profile_tag::getTagged($sender->id, $tag);
1158 foreach ($tagged as $t) {
1159 if (!$replied[$t->id]) {
1160 // Don't save replies from blocked profile to local user
1161 $t_user = User::staticGet('id', $t->id);
1162 if ($t_user && $t_user->hasBlocked($sender)) {
1165 $reply = new Reply();
1166 $reply->notice_id = $this->id;
1167 $reply->profile_id = $t->id;
1168 $id = $reply->insert();
1170 common_log_db_error($reply, 'INSERT', __FILE__);
1173 $replied[$recipient->id] = 1;
1180 $recipientIds = array_keys($replied);
1182 foreach ($recipientIds as $recipient) {
1183 $user = User::staticGet('id', $recipient);
1185 mail_notify_attn($user, $this);
1189 return $recipientIds;
1192 function asAtomEntry($namespace=false, $source=false)
1194 $profile = $this->getProfile();
1196 $xs = new XMLStringer(true);
1199 $attrs = array('xmlns' => 'http://www.w3.org/2005/Atom',
1200 'xmlns:thr' => 'http://purl.org/syndication/thread/1.0');
1205 $xs->elementStart('entry', $attrs);
1208 $xs->elementStart('source');
1209 $xs->element('title', null, $profile->nickname . " - " . common_config('site', 'name'));
1210 $xs->element('link', array('href' => $profile->profileurl));
1211 $user = User::staticGet('id', $profile->id);
1212 if (!empty($user)) {
1213 $atom_feed = common_local_url('ApiTimelineUser',
1214 array('format' => 'atom',
1215 'id' => $profile->nickname));
1216 $xs->element('link', array('rel' => 'self',
1217 'type' => 'application/atom+xml',
1218 'href' => $profile->profileurl));
1219 $xs->element('link', array('rel' => 'license',
1220 'href' => common_config('license', 'url')));
1223 $xs->element('icon', null, $profile->avatarUrl(AVATAR_PROFILE_SIZE));
1226 $xs->elementStart('author');
1227 $xs->element('name', null, $profile->nickname);
1228 $xs->element('uri', null, $profile->profileurl);
1229 $xs->elementEnd('author');
1232 $xs->elementEnd('source');
1235 $xs->element('title', null, $this->content);
1236 $xs->element('summary', null, $this->content);
1238 $xs->element('link', array('rel' => 'alternate',
1239 'href' => $this->bestUrl()));
1241 $xs->element('id', null, $this->uri);
1243 $xs->element('published', null, common_date_w3dtf($this->created));
1244 $xs->element('updated', null, common_date_w3dtf($this->modified));
1246 if ($this->reply_to) {
1247 $reply_notice = Notice::staticGet('id', $this->reply_to);
1248 if (!empty($reply_notice)) {
1249 $xs->element('link', array('rel' => 'related',
1250 'href' => $reply_notice->bestUrl()));
1251 $xs->element('thr:in-reply-to',
1252 array('ref' => $reply_notice->uri,
1253 'href' => $reply_notice->bestUrl()));
1257 $xs->element('content', array('type' => 'html'), $this->rendered);
1259 $tag = new Notice_tag();
1260 $tag->notice_id = $this->id;
1262 while ($tag->fetch()) {
1263 $xs->element('category', array('term' => $tag->tag));
1269 $attachments = $this->attachments();
1271 foreach($attachments as $attachment){
1272 $enclosure=$attachment->getEnclosure();
1274 $attributes = array('rel'=>'enclosure','href'=>$enclosure->url,'type'=>$enclosure->mimetype,'length'=>$enclosure->size);
1275 if($enclosure->title){
1276 $attributes['title']=$enclosure->title;
1278 $xs->element('link', $attributes, null);
1283 if (!empty($this->lat) && !empty($this->lon)) {
1284 $xs->elementStart('geo', array('xmlns:georss' => 'http://www.georss.org/georss'));
1285 $xs->element('georss:point', null, $this->lat . ' ' . $this->lon);
1286 $xs->elementEnd('geo');
1289 $xs->elementEnd('entry');
1291 return $xs->getString();
1296 if (!empty($this->url)) {
1298 } else if (!empty($this->uri) && preg_match('/^https?:/', $this->uri)) {
1301 return common_local_url('shownotice',
1302 array('notice' => $this->id));
1306 function stream($fn, $args, $cachekey, $offset=0, $limit=20, $since_id=0, $max_id=0, $since=null)
1308 $cache = common_memcache();
1310 if (empty($cache) ||
1311 $since_id != 0 || $max_id != 0 || (!is_null($since) && $since > 0) ||
1313 ($offset + $limit) > NOTICE_CACHE_WINDOW) {
1314 return call_user_func_array($fn, array_merge($args, array($offset, $limit, $since_id,
1318 $idkey = common_cache_key($cachekey);
1320 $idstr = $cache->get($idkey);
1322 if (!empty($idstr)) {
1323 // Cache hit! Woohoo!
1324 $window = explode(',', $idstr);
1325 $ids = array_slice($window, $offset, $limit);
1329 $laststr = $cache->get($idkey.';last');
1331 if (!empty($laststr)) {
1332 $window = explode(',', $laststr);
1333 $last_id = $window[0];
1334 $new_ids = call_user_func_array($fn, array_merge($args, array(0, NOTICE_CACHE_WINDOW,
1335 $last_id, 0, null)));
1337 $new_window = array_merge($new_ids, $window);
1339 $new_windowstr = implode(',', $new_window);
1341 $result = $cache->set($idkey, $new_windowstr);
1342 $result = $cache->set($idkey . ';last', $new_windowstr);
1344 $ids = array_slice($new_window, $offset, $limit);
1349 $window = call_user_func_array($fn, array_merge($args, array(0, NOTICE_CACHE_WINDOW,
1352 $windowstr = implode(',', $window);
1354 $result = $cache->set($idkey, $windowstr);
1355 $result = $cache->set($idkey . ';last', $windowstr);
1357 $ids = array_slice($window, $offset, $limit);
1363 * Determine which notice, if any, a new notice is in reply to.
1365 * For conversation tracking, we try to see where this notice fits
1366 * in the tree. Rough algorithm is:
1368 * if (reply_to is set and valid) {
1370 * } else if ((source not API or Web) and (content starts with "T NAME" or "@name ")) {
1371 * return ID of last notice by initial @name in content;
1374 * Note that all @nickname instances will still be used to save "reply" records,
1375 * so the notice shows up in the mentioned users' "replies" tab.
1377 * @param integer $reply_to ID passed in by Web or API
1378 * @param integer $profile_id ID of author
1379 * @param string $source Source tag, like 'web' or 'gwibber'
1380 * @param string $content Final notice content
1382 * @return integer ID of replied-to notice, or null for not a reply.
1385 static function getReplyTo($reply_to, $profile_id, $source, $content)
1387 static $lb = array('xmpp', 'mail', 'sms', 'omb');
1389 // If $reply_to is specified, we check that it exists, and then
1390 // return it if it does
1392 if (!empty($reply_to)) {
1393 $reply_notice = Notice::staticGet('id', $reply_to);
1394 if (!empty($reply_notice)) {
1399 // If it's not a "low bandwidth" source (one where you can't set
1400 // a reply_to argument), we return. This is mostly web and API
1403 if (!in_array($source, $lb)) {
1407 // Is there an initial @ or T?
1409 if (preg_match('/^T ([A-Z0-9]{1,64}) /', $content, $match) ||
1410 preg_match('/^@([a-z0-9]{1,64})\s+/', $content, $match)) {
1411 $nickname = common_canonical_nickname($match[1]);
1416 // Figure out who that is.
1418 $sender = Profile::staticGet('id', $profile_id);
1419 $recipient = common_relative_profile($sender, $nickname, common_sql_now());
1421 if (empty($recipient)) {
1425 // Get their last notice
1427 $last = $recipient->getCurrentNotice();
1429 if (!empty($last)) {
1434 static function maxContent()
1436 $contentlimit = common_config('notice', 'contentlimit');
1437 // null => use global limit (distinct from 0!)
1438 if (is_null($contentlimit)) {
1439 $contentlimit = common_config('site', 'textlimit');
1441 return $contentlimit;
1444 static function contentTooLong($content)
1446 $contentlimit = self::maxContent();
1447 return ($contentlimit > 0 && !empty($content) && (mb_strlen($content) > $contentlimit));
1450 function getLocation()
1454 if (!empty($this->location_id) && !empty($this->location_ns)) {
1455 $location = Location::fromId($this->location_id, $this->location_ns);
1458 if (is_null($location)) { // no ID, or Location::fromId() failed
1459 if (!empty($this->lat) && !empty($this->lon)) {
1460 $location = Location::fromLatLon($this->lat, $this->lon);
1467 function repeat($repeater_id, $source)
1469 $author = Profile::staticGet('id', $this->profile_id);
1471 // FIXME: truncate on long repeats...?
1473 $content = sprintf(_('RT @%1$s %2$s'),
1477 return self::saveNew($repeater_id, $content, $source,
1478 array('repeat_of' => $this->id));
1481 // These are supposed to be in chron order!
1483 function repeatStream($limit=100)
1485 $cache = common_memcache();
1487 if (empty($cache)) {
1488 $ids = $this->_repeatStreamDirect($limit);
1490 $idstr = $cache->get(common_cache_key('notice:repeats:'.$this->id));
1491 if (!empty($idstr)) {
1492 $ids = explode(',', $idstr);
1494 $ids = $this->_repeatStreamDirect(100);
1495 $cache->set(common_cache_key('notice:repeats:'.$this->id), implode(',', $ids));
1498 // We do a max of 100, so slice down to limit
1499 $ids = array_slice($ids, 0, $limit);
1503 return Notice::getStreamByIds($ids);
1506 function _repeatStreamDirect($limit)
1508 $notice = new Notice();
1510 $notice->selectAdd(); // clears it
1511 $notice->selectAdd('id');
1513 $notice->repeat_of = $this->id;
1515 $notice->orderBy('created'); // NB: asc!
1517 if (!is_null($offset)) {
1518 $notice->limit($offset, $limit);
1523 if ($notice->find()) {
1524 while ($notice->fetch()) {
1525 $ids[] = $notice->id;