This repository has been archived by the owner on May 15, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlists.php
190 lines (167 loc) · 7.2 KB
/
lists.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
<?php
// Sample output from invoking Mailman scripts:
/*
$ ./add_members -r - test <<< [email protected]
Subscribed: [email protected]
$ ./find_member [email protected]
[email protected] found in:
test
$ ./remove_members -f - test <<< [email protected]
$ ./find_member [email protected]
$ ./remove_members -f - test <<< [email protected]
No such member: [email protected]
$ ./add_members -r - test <<< [email protected]
Subscribed: [email protected]
$ ./add_members -r - test <<< [email protected]
Already a member: [email protected]
*/
// The location of all the Mailman2 scripts used in Lists.
define('MAIL_BIN', '/var/lib/mailman/bin/');
// The Lists API is a simple python API wrapper around Mailman2 just for
// managing member subscriptions; this should be further wrapped for REST use.
// Note: all illegal characters in $list and $email are translated to _.
// TODO: Support multiple add, remove, find, info.
class Lists {
protected function __construct() {}
protected function __clone() {}
// List all available mailing lists.
// Returns the array of all mailing lists.
public static function all(bool $names = false): array {
$api_bin = MAIL_BIN; // TODO: remove
$output = `bash -c '{$api_bin}list_lists -a'` ?: '';
$output = preg_replace('/(?:[\S]* matching mailing lists found:[\n]*)/i', '', $output);
preg_match_all('/(?:(?:[\s]*)([\S]*) - ([^\n]*)(?:[\n]*))/i', $output, $matches);
$matches = array_combine($matches[1], $matches[2]);
$matches = array_change_key_case($matches, CASE_LOWER);
if ($names) return $matches;
else return array_keys($matches);
}
// Lists all members of a given mailing $list.
// Returns the array of all members on the $list.
public static function list(string $list): array {
$api_bin = MAIL_BIN; // TODO: remove
$list = preg_replace('/[^a-z0-9=_+.-]/i', '_', $list);
if(!in_array($list, Lists::all()))
return [];
$output = `bash -c '{$api_bin}list_members "{$list}"'` ?: '';
if (strpos($output, 'No such list:') === false) {
return preg_split("/[\s]+/", $output, -1, PREG_SPLIT_NO_EMPTY);
} else return [];
}
// Add a member by $email to a mailing $list.
// Returns true if successfully added, false if otherwise.
public static function add(string $list, string $email): bool {
$api_bin = MAIL_BIN; // TODO: remove
$list = preg_replace('/[^a-z0-9=_+.-]/i', '_', $list);
$email = preg_replace('/[^a-z0-9@_+.-]/i', '_', $email);
if(!in_array($list, Lists::all()))
return false;
$output = `bash -c '{$api_bin}add_members -r - "{$list}" <<< {$email}'` ?: '';
return (strpos($output, 'Subscribed:') !== false);
}
// Finds a member by $email in all mailing lists.
// Returns the array of all mailing lists subscribed.
public static function find(string $email): array {
$api_bin = MAIL_BIN; // TODO: remove
$email = preg_replace('/[^a-z0-9@_+.-]/i', '_', $email);
$output = `bash -c '{$api_bin}find_member "{$email}"'` ?: '';
if ($output !== '') {
$output = preg_replace('/([\s\S]*found in:\n)/i', '', $output);
$output = preg_split("/[\s]+/", $output, -1, PREG_SPLIT_NO_EMPTY);
// Make sure we don't expose private lists.
$mask = Lists::all();
$output = array_filter($output, function($v) use (&$mask) {
return in_array($v, $mask);
});
return array_values($output);
} else return [];
}
// Gets a member's info by $email if it is a Purdue Career Account.
// Returns the array of information Purdue's LDAP server gives.
public static function info(string $email): array {
$email = preg_replace('/[^a-z0-9@_+.-]/i', '_', $email);
$id = preg_replace('/(@purdue.edu)/i', '', $email, -1, $count);
if ($count !== 1) return [];
$ds = ldap_connect("ped.purdue.edu");
if (!$ds) return [];
$r = ldap_bind($ds);
$sr = ldap_search($ds, "dc=purdue,dc=edu", "uid=$id");
$info = ldap_get_entries($ds, $sr);
ldap_close($ds);
return convert_ldap($info);
}
// Remove a member by $email from a mailing $list.
// Returns true if successfully removed, false if otherwise.
public static function remove(string $list, string $email): bool {
$api_bin = MAIL_BIN; // TODO: remove
$list = preg_replace('/[^a-z0-9=_+.-]/i', '_', $list);
$email = preg_replace('/[^a-z0-9@_+.-]/i', '_', $email);
if(!in_array($list, Lists::all()))
return false;
$output = `bash -c '{$api_bin}remove_members -f - "{$list}" <<< {$email}'` ?: '';
return (strpos($output, 'No such member:') === false);
}
}
// Utility for returning JSON along with a response code.
function http_return($value, $code = 200) {
http_response_code($code);
$body = json_encode($value)."\n";
header('Content-Type: application/json');
header('Content-Length: '.strlen($body));
exit($body);
}
// Utility to convert an LDAP result to something readable.
function convert_ldap($info) {
if ($info['count'] == 0)
return [];
foreach ($info as $inf) {
if (!is_array($inf)) continue;
foreach ($inf as $key => $in) {
if ((count($inf[$key]) - 1) > 0) {
if (is_array($in))
unset($inf[$key]["count"]);
$results[$key] = $inf[$key];
}
}
}
//$results["dn"] = explode(',', $info[0]["dn"]);
return $results;
}
// Dynamically invokes a method and maps the associative array of arguments
// onto the method's parameter names. If any non-optional arguments are
// missing, the $missing callback is invoked with the parameter name.
// If the $arguments array contains more arguments than method parameters exist,
// these leftover arguments will be automatically discarded.
function dynamic_invoke($method, $arguments, callable $missing) {
$values = [];
$all = (new \ReflectionMethod($method))->getParameters();
foreach ($all as $p) {
$name = $p->getName();
$exists = array_key_exists($name, $arguments);
if (!$exists && !$p->isDefaultValueAvailable()) {
$missing($name);
$arguments[$name] = null;
}
$values[$p->getPosition()] = $exists ? $arguments[$name] : $p->getDefaultValue();
}
return $method(...$values);
}
// If this script was directly invoked, magically turn into an HTTP API!
// Note: use `define('LISTS_STANDALONE', true)` to enable this.
if (LISTS_STANDALONE === true && basename(__FILE__) == basename($_SERVER['SCRIPT_FILENAME'])) {
// Extract the method from the parameters first.
$params = $_GET;
if (!isset($params['method']))
return http_return(["error" => "no method given"], 400);
$method = $params['method'];
unset($params['method']);
// Dynamically invoke the right method with the right args.
try {
return http_return(["result" => dynamic_invoke("Lists::$method", $params, function($x) {
return http_return(["error" => "invalid parameter $x"], 400);
})]);
} catch (ReflectionException $e) {
return http_return(["error" => "no such method"], 400);
}
}
?>