forked from enwikipedia-acc/waca
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfunctions.php
422 lines (359 loc) · 11.7 KB
/
functions.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
<?php
/**************************************************************************
********** English Wikipedia Account Request Interface **********
***************************************************************************
** Wikipedia Account Request Graphic Design by Charles Melbye, **
** which is licensed under a Creative Commons **
** Attribution-Noncommercial-Share Alike 3.0 United States License. **
** **
** All other code are released under the Public Domain **
** by the ACC Development Team. **
** **
** See CREDITS for the list of developers. **
***************************************************************************/
global $ACC;
global $baseurl;
global $dontUseWikiDb;
if (!defined("ACC")) {
die();
} // Invalid entry point
require_once 'queryBrowser.php';
require_once 'includes/session.php';
// Initialize the class objects.
$session = new session();
/** Initialises the PHP Session */
function initialiseSession() {
session_start();
}
/**
* Send a "close pend ticket" email to the end user. (created, taken, etc...)
*/
function sendemail($messageno, $target, $id)
{
$template = EmailTemplate::getById($messageno, gGetDb());
$headers = 'From: accounts-enwiki-l@lists.wikimedia.org';
// Get the closing user's Email signature and append it to the Email.
if (User::getCurrent()->getEmailSig() != "") {
$emailsig = html_entity_decode(User::getCurrent()->getEmailSig(), ENT_QUOTES, "UTF-8");
mail($target, "RE: [ACC #$id] English Wikipedia Account Request", $template->getText() . "\n\n" . $emailsig, $headers);
}
else {
mail($target, "RE: [ACC #$id] English Wikipedia Account Request", $template->getText(), $headers);
}
}
/**
* Returns a value indicating whether the current request was issued over HTTPSs
* @return bool true if HTTPS
*/
function isHttps()
{
if (isset($_SERVER['HTTP_X_FORWARDED_PROTO'])) {
if ($_SERVER['HTTP_X_FORWARDED_PROTO'] === 'https') {
// Client <=> Proxy is encrypted
return true;
}
else {
// Proxy <=> Server link is encrypted, but not Client <=> Proxy.
return false;
}
}
if (isset($_SERVER['HTTPS'])) {
if ($_SERVER['HTTPS'] === 'off') {
// ISAPI on IIS breaks the spec. :(
return false;
}
if ($_SERVER['HTTPS'] !== '') {
// Set to a non-empty value
return true;
}
}
return false;
}
/**
* Show the login page
*/
function showlogin()
{
global $smarty;
// Check whether there are any errors.
$errorbartext = "";
if (isset($_GET['error'])) {
if ($_GET['error'] == 'authfail') {
$errorbartext = BootstrapSkin::displayAlertBox("Username and/or password incorrect. Please try again.", "alert-error", "Auth failure", true, false, true);
}
elseif ($_GET['error'] == 'noid') {
$errorbartext = BootstrapSkin::displayAlertBox("User account is not identified. Please email accounts-enwiki-l@lists.wikimedia.org if you believe this is in error.", "alert-error", "Auth failure", true, false, true);
}
elseif ($_GET['error'] == 'newacct') {
$errorbartext = BootstrapSkin::displayAlertBox("I'm sorry, but, your account has not been approved by a site administrator yet. Please stand by.", "alert-info", "Account pending", true, false, true);
}
}
$smarty->assign("errorbar", $errorbartext);
global $strictTransportSecurityExpiry;
if ($strictTransportSecurityExpiry !== false) {
if (isHttps()) {
// Client can clearly use HTTPS, so let's enforce it for all connections.
header("Strict-Transport-Security: max-age=15768000");
}
else {
// This is the login form, not the request form. We need protection here.
$path = 'https://' . $_SERVER["SERVER_NAME"] . $_SERVER["REQUEST_URI"];
header("Location: " . $path);
}
}
$smarty->display("login.tpl");
}
function defaultpage()
{
global $availableRequestStates, $defaultRequestStateKey, $requestLimitShowOnly, $enableEmailConfirm;
$database = gGetDb();
$requestSectionData = array();
if ($enableEmailConfirm == 1) {
$query = "SELECT * FROM request WHERE status = :type AND emailconfirm = 'Confirmed' LIMIT :lim;";
$totalquery = "SELECT COUNT(*) FROM request WHERE status = :type AND emailconfirm = 'Confirmed';";
}
else {
$query = "SELECT * FROM request WHERE status = :type LIMIT :lim;";
$totalquery = "SELECT COUNT(*) FROM request WHERE status = :type;";
}
$statement = $database->prepare($query);
$statement->bindValue(":lim", $requestLimitShowOnly, PDO::PARAM_INT);
$totalRequestsStatement = $database->prepare($totalquery);
// list requests in each section
foreach ($availableRequestStates as $type => $v) {
$statement->bindValue(":type", $type);
$statement->execute();
$requests = $statement->fetchAll(PDO::FETCH_CLASS, "Request");
foreach ($requests as $req) {
$req->setDatabase($database);
}
$totalRequestsStatement->bindValue(":type", $type);
$totalRequestsStatement->execute();
$totalRequests = $totalRequestsStatement->fetchColumn();
$totalRequestsStatement->closeCursor();
$requestSectionData[$v['header']] = array(
"requests" => $requests,
"total" => $totalRequests,
"api" => $v['api'],
"type" => $type);
}
global $smarty;
$smarty->assign("requestLimitShowOnly", $requestLimitShowOnly);
$query = <<<SQL
SELECT request.id, request.name, request.checksum
FROM request
JOIN log ON log.objectid = request.id and log.objecttype = 'Request'
WHERE log.action LIKE 'Closed%'
ORDER BY log.timestamp DESC
LIMIT 5;
SQL;
$statement = $database->prepare($query);
$statement->execute();
$last5result = $statement->fetchAll(PDO::FETCH_ASSOC);
$smarty->assign("lastFive", $last5result);
$smarty->assign("requestSectionData", $requestSectionData);
$html = $smarty->fetch("mainpage/mainpage.tpl");
return $html;
}
function array_search_recursive($needle, $haystack, $path = array())
{
foreach ($haystack as $id => $val) {
$path2 = $path;
$path2[] = $id;
if ($val === $needle) {
return $path2;
}
else if (is_array($val)) {
if ($ret = array_search_recursive($needle, $val, $path2)) {
return $ret;
}
}
}
return false;
}
require_once('zoompage.php');
function displayPreview($wikicode)
{
$parseresult = unserialize(file_get_contents('http://en.wikipedia.org/w/api.php?action=parse&format=php&text=' . urlencode($wikicode)));
$out = "<br />\n<h3>Preview</h3>\n<div style=\"border: 2px dashed rgb(26, 79, 133);\">\n<div style=\"margin: 20px;\">";
$out .= $parseresult['parse']['text']['*'];
$out .= '</div></div>';
return $out;
}
/**
* Parses an XFF header and client IP to find the last trusted client IP
*
* @param string $dbip The IP address the request came from
* @param string $dbproxyip The contents of the XFF header of the request
* @return string
*/
function getTrustedClientIP($dbip, $dbproxyip)
{
global $xffTrustProvider;
$clientIpAddr = $dbip;
if ($dbproxyip) {
$ipList = explode(",", $dbproxyip);
$ipList[] = $clientIpAddr;
$ipList = array_reverse($ipList);
foreach ($ipList as $ipnumber => $ip) {
if ($xffTrustProvider->isTrusted(trim($ip)) && $ipnumber < (count($ipList) - 1)) {
continue;
}
$clientIpAddr = $ip;
break;
}
}
return $clientIpAddr;
}
/**
* Explodes a CIDR range into an array of addresses
*
* @param string $range A CIDR-format range
* @return array An array containing every IP address in the range
*/
function explodeCidr($range)
{
$ip_arr = explode('/', $range);
if (!isset($ip_arr[1])) {
return array($range);
}
$blow = (
str_pad(decbin(ip2long($ip_arr[0])), 32, "0", STR_PAD_LEFT) &
str_pad(str_pad("", $ip_arr[1], "1"), 32, "0")
);
$bhigh = ($blow | str_pad(str_pad("", $ip_arr[1], "0"), 32, "1"));
$list = array();
$bindecBHigh = bindec($bhigh);
for ($x = bindec($blow); $x <= $bindecBHigh; $x++) {
$list[] = long2ip($x);
}
return $list;
}
/**
* Takes an array( "low" => "high" ) values, and returns true if $needle is in at least one of them.
* @param string $ip
* @param array $haystack
*/
function ipInRange($haystack, $ip)
{
$needle = ip2long($ip);
foreach ($haystack as $low => $high) {
if (ip2long($low) <= $needle && ip2long($high) >= $needle) {
return true;
}
}
return false;
}
/**
* @return string
*/
function welcomerbotRenderSig($creator, $sig)
{
$signature = html_entity_decode($sig) . ' ~~~~~';
if (!preg_match("/((\[\[[ ]*(w:)?[ ]*(en:)?)|(\{\{subst:))[ ]*User[ ]*:[ ]*" . $creator . "[ ]*(\]\]|\||\}\}|\/)/i", $signature)) {
$signature = "--[[User:$creator|$creator]] ([[User talk:$creator|talk]]) ~~~~~";
}
return $signature;
}
/**
* Transforms a date string into a relative representation of the date ("2 weeks ago").
* @param string $input A string representing a date
* @return string
* @example {$variable|relativedate} from Smarty
*/
function relativedate($input)
{
$now = new DateTime();
$then = new DateTime($input);
$secs = $now->getTimestamp() - $then->getTimestamp();
$second = 1;
$minute = 60 * $second;
$minuteCut = 60 * $second;
$hour = 60 * $minute;
$hourCut = 60 * $minute;
$day = 24 * $hour;
$dayCut = 48 * $hour;
$week = 7 * $day;
$weekCut = 14 * $day;
$month = 30 * $day;
$year = 365 * $day;
$pluralise = true;
if ($secs <= 10) {
$output = "just now";
$pluralise = false;
}
elseif ($secs > 10 && $secs < $minuteCut) {
$output = round($secs / $second) . " second";
}
elseif ($secs >= $minuteCut && $secs < $hourCut) {
$output = round($secs / $minute) . " minute";
}
elseif ($secs >= $hourCut && $secs < $dayCut) {
$output = round($secs / $hour) . " hour";
}
elseif ($secs >= $dayCut && $secs < $weekCut) {
$output = round($secs / $day) . " day";
}
elseif ($secs >= $weekCut && $secs < $month) {
$output = round($secs / $week) . " week";
}
elseif ($secs >= $month && $secs < $year) {
$output = round($secs / $month) . " month";
}
elseif ($secs >= $year && $secs < $year * 10) {
$output = round($secs / $year) . " year";
}
else {
$output = "a long time ago";
$pluralise = false;
}
if ($pluralise) {
$output = (substr($output, 0, 2) <> "1 ") ? $output . "s ago" : $output . " ago";
}
return $output;
}
/**
* Summary of reattachOAuthAccount
* @param User $user
* @throws TransactionException
*/
function reattachOAuthAccount(User $user)
{
global $oauthConsumerToken, $oauthSecretToken, $oauthBaseUrl, $oauthBaseUrlInternal;
try {
// Get a request token for OAuth
$util = new OAuthUtility($oauthConsumerToken, $oauthSecretToken, $oauthBaseUrl, $oauthBaseUrlInternal);
$requestToken = $util->getRequestToken();
// save the request token for later
$user->setOAuthRequestToken($requestToken->key);
$user->setOAuthRequestSecret($requestToken->secret);
$user->save();
$redirectUrl = $util->getAuthoriseUrl($requestToken);
header("Location: {$redirectUrl}");
die();
}
catch (Exception $ex) {
throw new TransactionException($ex->getMessage(), "Connection to Wikipedia failed.", "alert-error", 0, $ex);
}
}
/**
* Generates the JavaScript source for XSS-safe typeahead autocompletion for usernames. This output is expected to be
* passed as the $tailscript argument to \BootstrapSkin::displayInternalFooter().
*
* @param $users string[] Array of usernames as strings
* @return string
*/
function getTypeaheadSource($users)
{
$userList = "";
foreach ($users as $v) {
$userList .= "\"" . htmlentities($v) . "\", ";
}
$userList = "[" . rtrim($userList, ", ") . "]";
$tailscript = <<<JS
$('.username-typeahead').typeahead({
source: {$userList}
});
JS;
return $tailscript;
}