Merge "Align "What's this" vertically"
[lhc/web/wiklou.git] / includes / FeedUtils.php
1 <?php
2 /**
3 * Helper functions for feeds.
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
19 *
20 * @file
21 * @ingroup Feed
22 */
23
24 /**
25 * Helper functions for feeds
26 *
27 * @ingroup Feed
28 */
29 class FeedUtils {
30
31 /**
32 * Check whether feed's cache should be cleared; for changes feeds
33 * If the feed should be purged; $timekey and $key will be removed from cache
34 *
35 * @param string $timekey Cache key of the timestamp of the last item
36 * @param string $key Cache key of feed's content
37 */
38 public static function checkPurge( $timekey, $key ) {
39 global $wgRequest, $wgUser;
40
41 $purge = $wgRequest->getVal( 'action' ) === 'purge';
42 // Allow users with 'purge' right to clear feed caches
43 if ( $purge && $wgUser->isAllowed( 'purge' ) ) {
44 $cache = ObjectCache::getMainWANInstance();
45 $cache->delete( $timekey, 1 );
46 $cache->delete( $key, 1 );
47 }
48 }
49
50 /**
51 * Check whether feeds can be used and that $type is a valid feed type
52 *
53 * @param string $type Feed type, as requested by the user
54 * @return bool
55 */
56 public static function checkFeedOutput( $type ) {
57 global $wgOut, $wgFeed, $wgFeedClasses;
58
59 if ( !$wgFeed ) {
60 $wgOut->addWikiMsg( 'feed-unavailable' );
61 return false;
62 }
63
64 if ( !isset( $wgFeedClasses[$type] ) ) {
65 $wgOut->addWikiMsg( 'feed-invalid' );
66 return false;
67 }
68
69 return true;
70 }
71
72 /**
73 * Format a diff for the newsfeed
74 *
75 * @param object $row Row from the recentchanges table, including fields as
76 * appropriate for CommentStore
77 * @return string
78 */
79 public static function formatDiff( $row ) {
80 $titleObj = Title::makeTitle( $row->rc_namespace, $row->rc_title );
81 $timestamp = wfTimestamp( TS_MW, $row->rc_timestamp );
82 $actiontext = '';
83 if ( $row->rc_type == RC_LOG ) {
84 $rcRow = (array)$row; // newFromRow() only accepts arrays for RC rows
85 $actiontext = LogFormatter::newFromRow( $rcRow )->getActionText();
86 }
87 return self::formatDiffRow( $titleObj,
88 $row->rc_last_oldid, $row->rc_this_oldid,
89 $timestamp,
90 $row->rc_deleted & Revision::DELETED_COMMENT
91 ? wfMessage( 'rev-deleted-comment' )->escaped()
92 : CommentStore::newKey( 'rc_comment' )
93 // Legacy from RecentChange::selectFields() via ChangesListSpecialPage::doMainQuery()
94 ->getCommentLegacy( wfGetDB( DB_REPLICA ), $row )->text,
95 $actiontext
96 );
97 }
98
99 /**
100 * Really format a diff for the newsfeed
101 *
102 * @param Title $title Title object
103 * @param int $oldid Old revision's id
104 * @param int $newid New revision's id
105 * @param int $timestamp New revision's timestamp
106 * @param string $comment New revision's comment
107 * @param string $actiontext Text of the action; in case of log event
108 * @return string
109 */
110 public static function formatDiffRow( $title, $oldid, $newid, $timestamp,
111 $comment, $actiontext = ''
112 ) {
113 global $wgFeedDiffCutoff, $wgLang;
114
115 // log entries
116 $completeText = '<p>' . implode( ' ',
117 array_filter(
118 [
119 $actiontext,
120 Linker::formatComment( $comment ) ] ) ) . "</p>\n";
121
122 // NOTE: Check permissions for anonymous users, not current user.
123 // No "privileged" version should end up in the cache.
124 // Most feed readers will not log in anyway.
125 $anon = new User();
126 $accErrors = $title->getUserPermissionsErrors( 'read', $anon, true );
127
128 // Can't diff special pages, unreadable pages or pages with no new revision
129 // to compare against: just return the text.
130 if ( $title->getNamespace() < 0 || $accErrors || !$newid ) {
131 return $completeText;
132 }
133
134 if ( $oldid ) {
135 $diffText = '';
136 // Don't bother generating the diff if we won't be able to show it
137 if ( $wgFeedDiffCutoff > 0 ) {
138 $rev = Revision::newFromId( $oldid );
139
140 if ( !$rev ) {
141 $diffText = false;
142 } else {
143 $context = clone RequestContext::getMain();
144 $context->setTitle( $title );
145
146 $contentHandler = $rev->getContentHandler();
147 $de = $contentHandler->createDifferenceEngine( $context, $oldid, $newid );
148 $diffText = $de->getDiff(
149 wfMessage( 'previousrevision' )->text(), // hack
150 wfMessage( 'revisionasof',
151 $wgLang->timeanddate( $timestamp ),
152 $wgLang->date( $timestamp ),
153 $wgLang->time( $timestamp ) )->text() );
154 }
155 }
156
157 if ( $wgFeedDiffCutoff <= 0 || ( strlen( $diffText ) > $wgFeedDiffCutoff ) ) {
158 // Omit large diffs
159 $diffText = self::getDiffLink( $title, $newid, $oldid );
160 } elseif ( $diffText === false ) {
161 // Error in diff engine, probably a missing revision
162 $diffText = "<p>Can't load revision $newid</p>";
163 } else {
164 // Diff output fine, clean up any illegal UTF-8
165 $diffText = UtfNormal\Validator::cleanUp( $diffText );
166 $diffText = self::applyDiffStyle( $diffText );
167 }
168 } else {
169 $rev = Revision::newFromId( $newid );
170 if ( $wgFeedDiffCutoff <= 0 || is_null( $rev ) ) {
171 $newContent = ContentHandler::getForTitle( $title )->makeEmptyContent();
172 } else {
173 $newContent = $rev->getContent();
174 }
175
176 if ( $newContent instanceof TextContent ) {
177 // only textual content has a "source view".
178 $text = $newContent->getNativeData();
179
180 if ( $wgFeedDiffCutoff <= 0 || strlen( $text ) > $wgFeedDiffCutoff ) {
181 $html = null;
182 } else {
183 $html = nl2br( htmlspecialchars( $text ) );
184 }
185 } else {
186 // XXX: we could get an HTML representation of the content via getParserOutput, but that may
187 // contain JS magic and generally may not be suitable for inclusion in a feed.
188 // Perhaps Content should have a getDescriptiveHtml method and/or a getSourceText method.
189 // Compare also ApiFeedContributions::feedItemDesc
190 $html = null;
191 }
192
193 if ( $html === null ) {
194 // Omit large new page diffs, T31110
195 // Also use diff link for non-textual content
196 $diffText = self::getDiffLink( $title, $newid );
197 } else {
198 $diffText = '<p><b>' . wfMessage( 'newpage' )->text() . '</b></p>' .
199 '<div>' . $html . '</div>';
200 }
201 }
202 $completeText .= $diffText;
203
204 return $completeText;
205 }
206
207 /**
208 * Generates a diff link. Used when the full diff is not wanted for example
209 * when $wgFeedDiffCutoff is 0.
210 *
211 * @param Title $title Title object: used to generate the diff URL
212 * @param int $newid Newid for this diff
213 * @param int|null $oldid Oldid for the diff. Null means it is a new article
214 * @return string
215 */
216 protected static function getDiffLink( Title $title, $newid, $oldid = null ) {
217 $queryParameters = [ 'diff' => $newid ];
218 if ( $oldid != null ) {
219 $queryParameters['oldid'] = $oldid;
220 }
221 $diffUrl = $title->getFullURL( $queryParameters );
222
223 $diffLink = Html::element( 'a', [ 'href' => $diffUrl ],
224 wfMessage( 'showdiff' )->inContentLanguage()->text() );
225
226 return $diffLink;
227 }
228
229 /**
230 * Hacky application of diff styles for the feeds.
231 * Might be 'cleaner' to use DOM or XSLT or something,
232 * but *gack* it's a pain in the ass.
233 *
234 * @param string $text Diff's HTML output
235 * @return string Modified HTML
236 */
237 public static function applyDiffStyle( $text ) {
238 $styles = [
239 'diff' => 'background-color: white; color:black;',
240 'diff-otitle' => 'background-color: white; color:black; text-align: center;',
241 'diff-ntitle' => 'background-color: white; color:black; text-align: center;',
242 'diff-addedline' => 'color:black; font-size: 88%; border-style: solid; '
243 . 'border-width: 1px 1px 1px 4px; border-radius: 0.33em; border-color: #a3d3ff; '
244 . 'vertical-align: top; white-space: pre-wrap;',
245 'diff-deletedline' => 'color:black; font-size: 88%; border-style: solid; '
246 . 'border-width: 1px 1px 1px 4px; border-radius: 0.33em; border-color: #ffe49c; '
247 . 'vertical-align: top; white-space: pre-wrap;',
248 'diff-context' => 'background-color: #f9f9f9; color: #333333; font-size: 88%; '
249 . 'border-style: solid; border-width: 1px 1px 1px 4px; border-radius: 0.33em; '
250 . 'border-color: #e6e6e6; vertical-align: top; white-space: pre-wrap;',
251 'diffchange' => 'font-weight: bold; text-decoration: none;',
252 ];
253
254 foreach ( $styles as $class => $style ) {
255 $text = preg_replace( "/(<[^>]+)class=(['\"])$class\\2([^>]*>)/",
256 "\\1style=\"$style\"\\3", $text );
257 }
258
259 return $text;
260 }
261
262 }