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)
69 public $lat; // decimal(10,7)
70 public $lon; // decimal(10,7)
71 public $location_id; // int(4)
72 public $location_ns; // int(4)
75 function staticGet($k,$v=NULL) {
76 return Memcached_DataObject::staticGet('Notice',$k,$v);
79 /* the code above is auto generated do not remove the tag below */
83 const LOCAL_PUBLIC = 1;
85 const LOCAL_NONPUBLIC = -1;
90 return Profile::staticGet('id', $this->profile_id);
95 $this->blowCaches(true);
96 $this->blowFavesCache(true);
97 $this->blowSubsCache(true);
99 // For auditing purposes, save a record that the notice
102 $deleted = new Deleted_notice();
104 $deleted->id = $this->id;
105 $deleted->profile_id = $this->profile_id;
106 $deleted->uri = $this->uri;
107 $deleted->created = $this->created;
108 $deleted->deleted = common_sql_now();
110 $this->query('BEGIN');
114 //Null any notices that are replies to this notice
115 $this->query(sprintf("UPDATE notice set reply_to = null WHERE reply_to = %d", $this->id));
116 $related = array('Reply',
123 foreach ($related as $cls) {
125 $inst->notice_id = $this->id;
128 $result = parent::delete();
129 $this->query('COMMIT');
134 /* extract all #hastags */
135 $count = preg_match_all('/(?:^|\s)#([\pL\pN_\-\.]{1,64})/', strtolower($this->content), $match);
140 //turn each into their canonical tag
141 //this is needed to remove dupes before saving e.g. #hash.tag = #hashtag
143 for($i=0; $i<count($match[1]); $i++) {
144 $hashtags[] = common_canonical_tag($match[1][$i]);
147 /* Add them to the database */
148 foreach(array_unique($hashtags) as $hashtag) {
149 /* elide characters we don't want in the tag */
150 $this->saveTag($hashtag);
155 function saveTag($hashtag)
157 $tag = new Notice_tag();
158 $tag->notice_id = $this->id;
159 $tag->tag = $hashtag;
160 $tag->created = $this->created;
161 $id = $tag->insert();
164 throw new ServerException(sprintf(_('DB error inserting hashtag: %s'),
165 $last_error->message));
170 static function saveNew($profile_id, $content, $source=null,
171 $is_local=Notice::LOCAL_PUBLIC, $reply_to=null, $uri=null, $created=null,
172 $lat=null, $lon=null, $location_id=null, $location_ns=null) {
174 $profile = Profile::staticGet($profile_id);
176 $final = common_shorten_links($content);
178 if (Notice::contentTooLong($final)) {
179 throw new ClientException(_('Problem saving notice. Too long.'));
182 if (empty($profile)) {
183 throw new ClientException(_('Problem saving notice. Unknown user.'));
186 if (common_config('throttle', 'enabled') && !Notice::checkEditThrottle($profile_id)) {
187 common_log(LOG_WARNING, 'Excessive posting by profile #' . $profile_id . '; throttled.');
188 throw new ClientException(_('Too many notices too fast; take a breather '.
189 'and post again in a few minutes.'));
192 if (common_config('site', 'dupelimit') > 0 && !Notice::checkDupes($profile_id, $final)) {
193 common_log(LOG_WARNING, 'Dupe posting by profile #' . $profile_id . '; throttled.');
194 throw new ClientException(_('Too many duplicate messages too quickly;'.
195 ' take a breather and post again in a few minutes.'));
198 if (!$profile->hasRight(Right::NEWNOTICE)) {
199 common_log(LOG_WARNING, "Attempted post from user disallowed to post: " . $profile->nickname);
200 throw new ClientException(_('You are banned from posting notices on this site.'));
203 $notice = new Notice();
204 $notice->profile_id = $profile_id;
206 $autosource = common_config('public', 'autosource');
208 # Sandboxed are non-false, but not 1, either
210 if (!$profile->hasRight(Right::PUBLICNOTICE) ||
211 ($source && $autosource && in_array($source, $autosource))) {
212 $notice->is_local = Notice::LOCAL_NONPUBLIC;
214 $notice->is_local = $is_local;
217 if (!empty($created)) {
218 $notice->created = $created;
220 $notice->created = common_sql_now();
223 $notice->content = $final;
224 $notice->rendered = common_render_content($final, $notice);
225 $notice->source = $source;
228 $notice->reply_to = self::getReplyTo($reply_to, $profile_id, $source, $final);
230 if (!empty($notice->reply_to)) {
231 $reply = Notice::staticGet('id', $notice->reply_to);
232 $notice->conversation = $reply->conversation;
235 if (!empty($lat) && !empty($lon)) {
238 $notice->location_id = $location_id;
239 $notice->location_ns = $location_ns;
240 } else if (!empty($location_ns) && !empty($location_id)) {
241 $location = Location::fromId($location_id, $location_ns);
242 if (!empty($location)) {
243 $notice->lat = $location->lat;
244 $notice->lon = $location->lon;
245 $notice->location_id = $location_id;
246 $notice->location_ns = $location_ns;
249 $notice->lat = $profile->lat;
250 $notice->lon = $profile->lon;
251 $notice->location_id = $profile->location_id;
252 $notice->location_ns = $profile->location_ns;
255 if (Event::handle('StartNoticeSave', array(&$notice))) {
257 // XXX: some of these functions write to the DB
259 $notice->query('BEGIN');
261 $id = $notice->insert();
264 common_log_db_error($notice, 'INSERT', __FILE__);
265 throw new ServerException(_('Problem saving notice.'));
268 // Update ID-dependent columns: URI, conversation
270 $orig = clone($notice);
275 $notice->uri = common_notice_uri($notice);
279 // If it's not part of a conversation, it's
280 // the beginning of a new conversation.
282 if (empty($notice->conversation)) {
283 $notice->conversation = $notice->id;
288 if (!$notice->update($orig)) {
289 common_log_db_error($notice, 'UPDATE', __FILE__);
290 throw new ServerException(_('Problem saving notice.'));
294 // XXX: do we need to change this for remote users?
298 $notice->addToInboxes();
302 $notice->query('COMMIT');
304 Event::handle('EndNoticeSave', array($notice));
307 # Clear the cache for subscribed users, so they'll update at next request
308 # XXX: someone clever could prepend instead of clearing the cache
310 $notice->blowCaches();
315 /** save all urls in the notice to the db
317 * follow redirects and save all available file information
318 * (mimetype, date, size, oembed, etc.)
322 function saveUrls() {
323 common_replace_urls_callback($this->content, array($this, 'saveUrl'), $this->id);
326 function saveUrl($data) {
327 list($url, $notice_id) = $data;
328 File::processNew($url, $notice_id);
331 static function checkDupes($profile_id, $content) {
332 $profile = Profile::staticGet($profile_id);
333 if (empty($profile)) {
336 $notice = $profile->getNotices(0, NOTICE_CACHE_WINDOW);
337 if (!empty($notice)) {
339 while ($notice->fetch()) {
340 if (time() - strtotime($notice->created) >= common_config('site', 'dupelimit')) {
342 } else if ($notice->content == $content) {
347 # If we get here, oldest item in cache window is not
348 # old enough for dupe limit; do direct check against DB
349 $notice = new Notice();
350 $notice->profile_id = $profile_id;
351 $notice->content = $content;
352 if (common_config('db','type') == 'pgsql')
353 $notice->whereAdd('extract(epoch from now() - created) < ' . common_config('site', 'dupelimit'));
355 $notice->whereAdd('now() - created < ' . common_config('site', 'dupelimit'));
357 $cnt = $notice->count();
361 static function checkEditThrottle($profile_id) {
362 $profile = Profile::staticGet($profile_id);
363 if (empty($profile)) {
367 $notice = $profile->getNotices(common_config('throttle', 'count') - 1, 1);
368 if ($notice && $notice->fetch()) {
369 # If the Nth notice was posted less than timespan seconds ago
370 if (time() - strtotime($notice->created) <= common_config('throttle', 'timespan')) {
375 # Either not N notices in the stream, OR the Nth was not posted within timespan seconds
379 function getUploadedAttachment() {
381 $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"';
382 $post->query($query);
384 if (empty($post->up) || empty($post->i)) {
387 $ret = array($post->up, $post->i);
393 function hasAttachments() {
395 $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);
396 $post->query($query);
398 $n_attachments = intval($post->n_attachments);
400 return $n_attachments;
403 function attachments() {
406 $f2p = new File_to_post;
407 $f2p->post_id = $this->id;
409 while ($f2p->fetch()) {
410 $f = File::staticGet($f2p->file_id);
417 function blowCaches($blowLast=false)
419 $this->blowSubsCache($blowLast);
420 $this->blowNoticeCache($blowLast);
421 $this->blowRepliesCache($blowLast);
422 $this->blowPublicCache($blowLast);
423 $this->blowTagCache($blowLast);
424 $this->blowGroupCache($blowLast);
425 $this->blowConversationCache($blowLast);
426 $profile = Profile::staticGet($this->profile_id);
427 $profile->blowNoticeCount();
430 function blowConversationCache($blowLast=false)
432 $cache = common_memcache();
434 $ck = common_cache_key('notice:conversation_ids:'.$this->conversation);
437 $cache->delete($ck.';last');
442 function blowGroupCache($blowLast=false)
444 $cache = common_memcache();
446 $group_inbox = new Group_inbox();
447 $group_inbox->notice_id = $this->id;
448 if ($group_inbox->find()) {
449 while ($group_inbox->fetch()) {
450 $cache->delete(common_cache_key('user_group:notice_ids:' . $group_inbox->group_id));
452 $cache->delete(common_cache_key('user_group:notice_ids:' . $group_inbox->group_id.';last'));
454 $member = new Group_member();
455 $member->group_id = $group_inbox->group_id;
456 if ($member->find()) {
457 while ($member->fetch()) {
458 $cache->delete(common_cache_key('notice_inbox:by_user:' . $member->profile_id));
460 $cache->delete(common_cache_key('notice_inbox:by_user:' . $member->profile_id . ';last'));
466 $group_inbox->free();
471 function blowTagCache($blowLast=false)
473 $cache = common_memcache();
475 $tag = new Notice_tag();
476 $tag->notice_id = $this->id;
478 while ($tag->fetch()) {
479 $tag->blowCache($blowLast);
480 $ck = 'profile:notice_ids_tagged:' . $this->profile_id . ':' . $tag->tag;
484 $cache->delete($ck . ';last');
493 function blowSubsCache($blowLast=false)
495 $cache = common_memcache();
499 $UT = common_config('db','type')=='pgsql'?'"user"':'user';
500 $user->query('SELECT id ' .
502 "FROM $UT JOIN subscription ON $UT.id = subscription.subscriber " .
503 'WHERE subscription.subscribed = ' . $this->profile_id);
505 while ($user->fetch()) {
506 $cache->delete(common_cache_key('notice_inbox:by_user:'.$user->id));
507 $cache->delete(common_cache_key('notice_inbox:by_user_own:'.$user->id));
509 $cache->delete(common_cache_key('notice_inbox:by_user:'.$user->id.';last'));
510 $cache->delete(common_cache_key('notice_inbox:by_user_own:'.$user->id.';last'));
518 function blowNoticeCache($blowLast=false)
520 if ($this->is_local) {
521 $cache = common_memcache();
522 if (!empty($cache)) {
523 $cache->delete(common_cache_key('profile:notice_ids:'.$this->profile_id));
525 $cache->delete(common_cache_key('profile:notice_ids:'.$this->profile_id.';last'));
531 function blowRepliesCache($blowLast=false)
533 $cache = common_memcache();
535 $reply = new Reply();
536 $reply->notice_id = $this->id;
537 if ($reply->find()) {
538 while ($reply->fetch()) {
539 $cache->delete(common_cache_key('reply:stream:'.$reply->profile_id));
541 $cache->delete(common_cache_key('reply:stream:'.$reply->profile_id.';last'));
550 function blowPublicCache($blowLast=false)
552 if ($this->is_local == Notice::LOCAL_PUBLIC) {
553 $cache = common_memcache();
555 $cache->delete(common_cache_key('public'));
557 $cache->delete(common_cache_key('public').';last');
563 function blowFavesCache($blowLast=false)
565 $cache = common_memcache();
568 $fave->notice_id = $this->id;
570 while ($fave->fetch()) {
571 $cache->delete(common_cache_key('fave:ids_by_user:'.$fave->user_id));
572 $cache->delete(common_cache_key('fave:by_user_own:'.$fave->user_id));
574 $cache->delete(common_cache_key('fave:ids_by_user:'.$fave->user_id.';last'));
575 $cache->delete(common_cache_key('fave:by_user_own:'.$fave->user_id.';last'));
584 # XXX: too many args; we need to move to named params or even a separate
585 # class for notice streams
587 static function getStream($qry, $cachekey, $offset=0, $limit=20, $since_id=0, $max_id=0, $order=null, $since=null) {
589 if (common_config('memcached', 'enabled')) {
591 # Skip the cache if this is a since, since_id or max_id qry
592 if ($since_id > 0 || $max_id > 0 || $since) {
593 return Notice::getStreamDirect($qry, $offset, $limit, $since_id, $max_id, $order, $since);
595 return Notice::getCachedStream($qry, $cachekey, $offset, $limit, $order);
599 return Notice::getStreamDirect($qry, $offset, $limit, $since_id, $max_id, $order, $since);
602 static function getStreamDirect($qry, $offset, $limit, $since_id, $max_id, $order, $since) {
607 if (preg_match('/\bWHERE\b/i', $qry)) {
621 $qry .= ' notice.id > ' . $since_id;
633 $qry .= ' notice.id <= ' . $max_id;
645 $qry .= ' notice.created > \'' . date('Y-m-d H:i:s', $since) . '\'';
648 # Allow ORDER override
653 $qry .= ' ORDER BY notice.created DESC, notice.id DESC ';
656 if (common_config('db','type') == 'pgsql') {
657 $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
659 $qry .= ' LIMIT ' . $offset . ', ' . $limit;
662 $notice = new Notice();
664 $notice->query($qry);
669 # XXX: this is pretty long and should probably be broken up into
670 # some helper functions
672 static function getCachedStream($qry, $cachekey, $offset, $limit, $order) {
674 # If outside our cache window, just go to the DB
676 if ($offset + $limit > NOTICE_CACHE_WINDOW) {
677 return Notice::getStreamDirect($qry, $offset, $limit, null, null, $order, null);
680 # Get the cache; if we can't, just go to the DB
682 $cache = common_memcache();
685 return Notice::getStreamDirect($qry, $offset, $limit, null, null, $order, null);
688 # Get the notices out of the cache
690 $notices = $cache->get(common_cache_key($cachekey));
692 # On a cache hit, return a DB-object-like wrapper
694 if ($notices !== false) {
695 $wrapper = new ArrayWrapper(array_slice($notices, $offset, $limit));
699 # If the cache was invalidated because of new data being
700 # added, we can try and just get the new stuff. We keep an additional
701 # copy of the data at the key + ';last'
703 # No cache hit. Try to get the *last* cached version
705 $last_notices = $cache->get(common_cache_key($cachekey) . ';last');
709 # Reverse-chron order, so last ID is last.
711 $last_id = $last_notices[0]->id;
713 # XXX: this assumes monotonically increasing IDs; a fair
716 $new_notice = Notice::getStreamDirect($qry, 0, NOTICE_CACHE_WINDOW,
717 $last_id, null, $order, null);
720 $new_notices = array();
721 while ($new_notice->fetch()) {
722 $new_notices[] = clone($new_notice);
725 $notices = array_slice(array_merge($new_notices, $last_notices),
726 0, NOTICE_CACHE_WINDOW);
728 # Store the array in the cache for next time
730 $result = $cache->set(common_cache_key($cachekey), $notices);
731 $result = $cache->set(common_cache_key($cachekey) . ';last', $notices);
733 # return a wrapper of the array for use now
735 return new ArrayWrapper(array_slice($notices, $offset, $limit));
739 # Otherwise, get the full cache window out of the DB
741 $notice = Notice::getStreamDirect($qry, 0, NOTICE_CACHE_WINDOW, null, null, $order, null);
743 # If there are no hits, just return the value
745 if (empty($notice)) {
749 # Pack results into an array
753 while ($notice->fetch()) {
754 $notices[] = clone($notice);
759 # Store the array in the cache for next time
761 $result = $cache->set(common_cache_key($cachekey), $notices);
762 $result = $cache->set(common_cache_key($cachekey) . ';last', $notices);
764 # return a wrapper of the array for use now
766 $wrapper = new ArrayWrapper(array_slice($notices, $offset, $limit));
771 function getStreamByIds($ids)
773 $cache = common_memcache();
775 if (!empty($cache)) {
777 foreach ($ids as $id) {
778 $n = Notice::staticGet('id', $id);
783 return new ArrayWrapper($notices);
785 $notice = new Notice();
787 //if no IDs requested, just return the notice object
790 $notice->whereAdd('id in (' . implode(', ', $ids) . ')');
796 while ($notice->fetch()) {
797 $temp[$notice->id] = clone($notice);
802 foreach ($ids as $id) {
803 if (array_key_exists($id, $temp)) {
804 $wrapped[] = $temp[$id];
808 return new ArrayWrapper($wrapped);
812 function publicStream($offset=0, $limit=20, $since_id=0, $max_id=0, $since=null)
814 $ids = Notice::stream(array('Notice', '_publicStreamDirect'),
817 $offset, $limit, $since_id, $max_id, $since);
819 return Notice::getStreamByIds($ids);
822 function _publicStreamDirect($offset=0, $limit=20, $since_id=0, $max_id=0, $since=null)
824 $notice = new Notice();
826 $notice->selectAdd(); // clears it
827 $notice->selectAdd('id');
829 $notice->orderBy('id DESC');
831 if (!is_null($offset)) {
832 $notice->limit($offset, $limit);
835 if (common_config('public', 'localonly')) {
836 $notice->whereAdd('is_local = ' . Notice::LOCAL_PUBLIC);
838 # -1 == blacklisted, -2 == gateway (i.e. Twitter)
839 $notice->whereAdd('is_local !='. Notice::LOCAL_NONPUBLIC);
840 $notice->whereAdd('is_local !='. Notice::GATEWAY);
843 if ($since_id != 0) {
844 $notice->whereAdd('id > ' . $since_id);
848 $notice->whereAdd('id <= ' . $max_id);
851 if (!is_null($since)) {
852 $notice->whereAdd('created > \'' . date('Y-m-d H:i:s', $since) . '\'');
857 if ($notice->find()) {
858 while ($notice->fetch()) {
859 $ids[] = $notice->id;
869 function conversationStream($id, $offset=0, $limit=20, $since_id=0, $max_id=0, $since=null)
871 $ids = Notice::stream(array('Notice', '_conversationStreamDirect'),
873 'notice:conversation_ids:'.$id,
874 $offset, $limit, $since_id, $max_id, $since);
876 return Notice::getStreamByIds($ids);
879 function _conversationStreamDirect($id, $offset=0, $limit=20, $since_id=0, $max_id=0, $since=null)
881 $notice = new Notice();
883 $notice->selectAdd(); // clears it
884 $notice->selectAdd('id');
886 $notice->conversation = $id;
888 $notice->orderBy('id DESC');
890 if (!is_null($offset)) {
891 $notice->limit($offset, $limit);
894 if ($since_id != 0) {
895 $notice->whereAdd('id > ' . $since_id);
899 $notice->whereAdd('id <= ' . $max_id);
902 if (!is_null($since)) {
903 $notice->whereAdd('created > \'' . date('Y-m-d H:i:s', $since) . '\'');
908 if ($notice->find()) {
909 while ($notice->fetch()) {
910 $ids[] = $notice->id;
920 function addToInboxes()
922 // XXX: loads constants
924 $inbox = new Notice_inbox();
926 $users = $this->getSubscribedUsers();
928 // FIXME: kind of ignoring 'transitional'...
929 // we'll probably stop supporting inboxless mode
934 foreach ($users as $id) {
935 $ni[$id] = NOTICE_INBOX_SOURCE_SUB;
938 $groups = $this->saveGroups();
939 $profile = $this->getProfile();
941 foreach ($groups as $group) {
942 $users = $group->getUserMembers();
943 foreach ($users as $id) {
944 if (!array_key_exists($id, $ni)) {
945 $user = User::staticGet('id', $id);
946 if (!$user->hasBlocked($profile)) {
947 $ni[$id] = NOTICE_INBOX_SOURCE_GROUP;
953 $recipients = $this->saveReplies();
955 foreach ($recipients as $recipient) {
957 if (!array_key_exists($recipient, $ni)) {
958 $recipientUser = User::staticGet('id', $recipient);
959 if (!empty($recipientUser)) {
960 $ni[$recipient] = NOTICE_INBOX_SOURCE_REPLY;
965 Notice_inbox::bulkInsert($this->id, $this->created, $ni);
970 function getSubscribedUsers()
974 if(common_config('db','quote_identifiers'))
975 $user_table = '"user"';
976 else $user_table = 'user';
980 'FROM '. $user_table .' JOIN subscription '.
981 'ON '. $user_table .'.id = subscription.subscriber ' .
982 'WHERE subscription.subscribed = %d ';
984 $user->query(sprintf($qry, $this->profile_id));
988 while ($user->fetch()) {
997 function saveGroups()
1001 /* extract all !group */
1002 $count = preg_match_all('/(?:^|\s)!([A-Za-z0-9]{1,64})/',
1003 strtolower($this->content),
1009 $profile = $this->getProfile();
1011 /* Add them to the database */
1013 foreach (array_unique($match[1]) as $nickname) {
1014 /* XXX: remote groups. */
1015 $group = User_group::getForNickname($nickname);
1017 if (empty($group)) {
1021 // we automatically add a tag for every group name, too
1023 $tag = Notice_tag::pkeyGet(array('tag' => common_canonical_tag($nickname),
1024 'notice_id' => $this->id));
1026 if (is_null($tag)) {
1027 $this->saveTag($nickname);
1030 if ($profile->isMember($group)) {
1032 $result = $this->addToGroupInbox($group);
1035 common_log_db_error($gi, 'INSERT', __FILE__);
1038 $groups[] = clone($group);
1045 function addToGroupInbox($group)
1047 $gi = Group_inbox::pkeyGet(array('group_id' => $group->id,
1048 'notice_id' => $this->id));
1052 $gi = new Group_inbox();
1054 $gi->group_id = $group->id;
1055 $gi->notice_id = $this->id;
1056 $gi->created = $this->created;
1058 return $gi->insert();
1064 function saveReplies()
1066 // Alternative reply format
1068 if (preg_match('/^T ([A-Z0-9]{1,64}) /', $this->content, $match)) {
1071 // extract all @messages
1072 $cnt = preg_match_all('/(?:^|\s)@([a-z0-9]{1,64})/', $this->content, $match);
1076 if ($cnt || $tname) {
1077 // XXX: is there another way to make an array copy?
1078 $names = ($tname) ? array_unique(array_merge(array(strtolower($tname)), $match[1])) : array_unique($match[1]);
1081 $sender = Profile::staticGet($this->profile_id);
1085 // store replied only for first @ (what user/notice what the reply directed,
1086 // we assume first @ is it)
1088 for ($i=0; $i<count($names); $i++) {
1089 $nickname = $names[$i];
1090 $recipient = common_relative_profile($sender, $nickname, $this->created);
1091 if (empty($recipient)) {
1094 // Don't save replies from blocked profile to local user
1095 $recipient_user = User::staticGet('id', $recipient->id);
1096 if (!empty($recipient_user) && $recipient_user->hasBlocked($sender)) {
1099 $reply = new Reply();
1100 $reply->notice_id = $this->id;
1101 $reply->profile_id = $recipient->id;
1102 $id = $reply->insert();
1104 $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError');
1105 common_log(LOG_ERR, 'DB error inserting reply: ' . $last_error->message);
1106 common_server_error(sprintf(_('DB error inserting reply: %s'), $last_error->message));
1109 $replied[$recipient->id] = 1;
1113 // Hash format replies, too
1114 $cnt = preg_match_all('/(?:^|\s)@#([a-z0-9]{1,64})/', $this->content, $match);
1116 foreach ($match[1] as $tag) {
1117 $tagged = Profile_tag::getTagged($sender->id, $tag);
1118 foreach ($tagged as $t) {
1119 if (!$replied[$t->id]) {
1120 // Don't save replies from blocked profile to local user
1121 $t_user = User::staticGet('id', $t->id);
1122 if ($t_user && $t_user->hasBlocked($sender)) {
1125 $reply = new Reply();
1126 $reply->notice_id = $this->id;
1127 $reply->profile_id = $t->id;
1128 $id = $reply->insert();
1130 common_log_db_error($reply, 'INSERT', __FILE__);
1133 $replied[$recipient->id] = 1;
1140 $recipientIds = array_keys($replied);
1142 foreach ($recipientIds as $recipient) {
1143 $user = User::staticGet('id', $recipient);
1145 mail_notify_attn($user, $this);
1149 return $recipientIds;
1152 function asAtomEntry($namespace=false, $source=false)
1154 $profile = $this->getProfile();
1156 $xs = new XMLStringer(true);
1159 $attrs = array('xmlns' => 'http://www.w3.org/2005/Atom',
1160 'xmlns:thr' => 'http://purl.org/syndication/thread/1.0');
1165 $xs->elementStart('entry', $attrs);
1168 $xs->elementStart('source');
1169 $xs->element('title', null, $profile->nickname . " - " . common_config('site', 'name'));
1170 $xs->element('link', array('href' => $profile->profileurl));
1171 $user = User::staticGet('id', $profile->id);
1172 if (!empty($user)) {
1173 $atom_feed = common_local_url('ApiTimelineUser',
1174 array('format' => 'atom',
1175 'id' => $profile->nickname));
1176 $xs->element('link', array('rel' => 'self',
1177 'type' => 'application/atom+xml',
1178 'href' => $profile->profileurl));
1179 $xs->element('link', array('rel' => 'license',
1180 'href' => common_config('license', 'url')));
1183 $xs->element('icon', null, $profile->avatarUrl(AVATAR_PROFILE_SIZE));
1186 $xs->elementStart('author');
1187 $xs->element('name', null, $profile->nickname);
1188 $xs->element('uri', null, $profile->profileurl);
1189 $xs->elementEnd('author');
1192 $xs->elementEnd('source');
1195 $xs->element('title', null, $this->content);
1196 $xs->element('summary', null, $this->content);
1198 $xs->element('link', array('rel' => 'alternate',
1199 'href' => $this->bestUrl()));
1201 $xs->element('id', null, $this->uri);
1203 $xs->element('published', null, common_date_w3dtf($this->created));
1204 $xs->element('updated', null, common_date_w3dtf($this->modified));
1206 if ($this->reply_to) {
1207 $reply_notice = Notice::staticGet('id', $this->reply_to);
1208 if (!empty($reply_notice)) {
1209 $xs->element('link', array('rel' => 'related',
1210 'href' => $reply_notice->bestUrl()));
1211 $xs->element('thr:in-reply-to',
1212 array('ref' => $reply_notice->uri,
1213 'href' => $reply_notice->bestUrl()));
1217 $xs->element('content', array('type' => 'html'), $this->rendered);
1219 $tag = new Notice_tag();
1220 $tag->notice_id = $this->id;
1222 while ($tag->fetch()) {
1223 $xs->element('category', array('term' => $tag->tag));
1229 $attachments = $this->attachments();
1231 foreach($attachments as $attachment){
1232 $enclosure=$attachment->getEnclosure();
1234 $attributes = array('rel'=>'enclosure','href'=>$enclosure->url,'type'=>$enclosure->mimetype,'length'=>$enclosure->size);
1235 if($enclosure->title){
1236 $attributes['title']=$enclosure->title;
1238 $xs->element('link', $attributes, null);
1243 if (!empty($this->lat) && !empty($this->lon)) {
1244 $xs->elementStart('geo', array('xmlns:georss' => 'http://www.georss.org/georss'));
1245 $xs->element('georss:point', null, $this->lat . ' ' . $this->lon);
1246 $xs->elementEnd('geo');
1249 $xs->elementEnd('entry');
1251 return $xs->getString();
1256 if (!empty($this->url)) {
1258 } else if (!empty($this->uri) && preg_match('/^https?:/', $this->uri)) {
1261 return common_local_url('shownotice',
1262 array('notice' => $this->id));
1266 function stream($fn, $args, $cachekey, $offset=0, $limit=20, $since_id=0, $max_id=0, $since=null)
1268 $cache = common_memcache();
1270 if (empty($cache) ||
1271 $since_id != 0 || $max_id != 0 || (!is_null($since) && $since > 0) ||
1273 ($offset + $limit) > NOTICE_CACHE_WINDOW) {
1274 return call_user_func_array($fn, array_merge($args, array($offset, $limit, $since_id,
1278 $idkey = common_cache_key($cachekey);
1280 $idstr = $cache->get($idkey);
1282 if (!empty($idstr)) {
1283 // Cache hit! Woohoo!
1284 $window = explode(',', $idstr);
1285 $ids = array_slice($window, $offset, $limit);
1289 $laststr = $cache->get($idkey.';last');
1291 if (!empty($laststr)) {
1292 $window = explode(',', $laststr);
1293 $last_id = $window[0];
1294 $new_ids = call_user_func_array($fn, array_merge($args, array(0, NOTICE_CACHE_WINDOW,
1295 $last_id, 0, null)));
1297 $new_window = array_merge($new_ids, $window);
1299 $new_windowstr = implode(',', $new_window);
1301 $result = $cache->set($idkey, $new_windowstr);
1302 $result = $cache->set($idkey . ';last', $new_windowstr);
1304 $ids = array_slice($new_window, $offset, $limit);
1309 $window = call_user_func_array($fn, array_merge($args, array(0, NOTICE_CACHE_WINDOW,
1312 $windowstr = implode(',', $window);
1314 $result = $cache->set($idkey, $windowstr);
1315 $result = $cache->set($idkey . ';last', $windowstr);
1317 $ids = array_slice($window, $offset, $limit);
1323 * Determine which notice, if any, a new notice is in reply to.
1325 * For conversation tracking, we try to see where this notice fits
1326 * in the tree. Rough algorithm is:
1328 * if (reply_to is set and valid) {
1330 * } else if ((source not API or Web) and (content starts with "T NAME" or "@name ")) {
1331 * return ID of last notice by initial @name in content;
1334 * Note that all @nickname instances will still be used to save "reply" records,
1335 * so the notice shows up in the mentioned users' "replies" tab.
1337 * @param integer $reply_to ID passed in by Web or API
1338 * @param integer $profile_id ID of author
1339 * @param string $source Source tag, like 'web' or 'gwibber'
1340 * @param string $content Final notice content
1342 * @return integer ID of replied-to notice, or null for not a reply.
1345 static function getReplyTo($reply_to, $profile_id, $source, $content)
1347 static $lb = array('xmpp', 'mail', 'sms', 'omb');
1349 // If $reply_to is specified, we check that it exists, and then
1350 // return it if it does
1352 if (!empty($reply_to)) {
1353 $reply_notice = Notice::staticGet('id', $reply_to);
1354 if (!empty($reply_notice)) {
1359 // If it's not a "low bandwidth" source (one where you can't set
1360 // a reply_to argument), we return. This is mostly web and API
1363 if (!in_array($source, $lb)) {
1367 // Is there an initial @ or T?
1369 if (preg_match('/^T ([A-Z0-9]{1,64}) /', $content, $match) ||
1370 preg_match('/^@([a-z0-9]{1,64})\s+/', $content, $match)) {
1371 $nickname = common_canonical_nickname($match[1]);
1376 // Figure out who that is.
1378 $sender = Profile::staticGet('id', $profile_id);
1379 $recipient = common_relative_profile($sender, $nickname, common_sql_now());
1381 if (empty($recipient)) {
1385 // Get their last notice
1387 $last = $recipient->getCurrentNotice();
1389 if (!empty($last)) {
1394 static function maxContent()
1396 $contentlimit = common_config('notice', 'contentlimit');
1397 // null => use global limit (distinct from 0!)
1398 if (is_null($contentlimit)) {
1399 $contentlimit = common_config('site', 'textlimit');
1401 return $contentlimit;
1404 static function contentTooLong($content)
1406 $contentlimit = self::maxContent();
1407 return ($contentlimit > 0 && !empty($content) && (mb_strlen($content) > $contentlimit));
1410 function getLocation()
1414 if (!empty($this->location_id) && !empty($this->location_ns)) {
1415 $location = Location::fromId($this->location_id, $this->location_ns);
1418 if (is_null($location)) { // no ID, or Location::fromId() failed
1419 if (!empty($this->lat) && !empty($this->lon)) {
1420 $location = Location::fromLatLon($this->lat, $this->lon);