Merge commit 'origin/master' into fusionax
[platal.git] / include / googleapps.inc.php
1 <?php
2 /***************************************************************************
3 * Copyright (C) 2003-2009 Polytechnique.org *
4 * http://opensource.polytechnique.org/ *
5 * *
6 * This program is free software; you can redistribute it and/or modify *
7 * it under the terms of the GNU General Public License as published by *
8 * the Free Software Foundation; either version 2 of the License, or *
9 * (at your option) any later version. *
10 * *
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 General Public License for more details. *
15 * *
16 * You should have received a copy of the GNU General Public License *
17 * along with this program; if not, write to the Free Software *
18 * Foundation, Inc., *
19 * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *
20 ***************************************************************************/
21
22 // Post-processes the successful Google Apps account creation queue job.
23 function post_queue_u_create($job) {
24 global $globals;
25
26 // Retrieves the user parameters (GoogleApps username and user_id).
27 $parameters = json_decode($job['j_parameters'], true);
28 $username = isset($parameters['username']) ? $parameters['username'] : null;
29 if (!($user = User::getSilent($username))) {
30 return;
31 }
32
33 // Adds a redirection to the Google Apps delivery address, if requested by
34 // the user at creation time.
35 $account = new GoogleAppsAccount($user);
36 if ($account->activate_mail_redirection) {
37 require_once('emails.inc.php');
38 $storage = new EmailStorage($user, 'googleapps');
39 $storage->activate();
40 }
41
42 // Sends the 'account created' email to the user, with basic documentation.
43 $res = XDB::query(
44 "SELECT FIND_IN_SET('femme', u.flags), prenom
45 FROM auth_user_md5 AS u
46 WHERE u.user_id = {?}", $user->id());
47 list($sexe, $prenom) = $res->fetchOneRow();
48
49 $mailer = new PlMailer('googleapps/create.mail.tpl');
50 $mailer->assign('account', $account);
51 $mailer->assign('email', $user->bestEmail());
52 $mailer->assign('googleapps_domain', $globals->mailstorage->googleapps_domain);
53 $mailer->assign('prenom', $prenom);
54 $mailer->assign('sexe', $sexe);
55 $mailer->send();
56 }
57
58 // Post-processes the successful Google Apps account update queue job.
59 function post_queue_u_update($job) {
60 global $globals;
61
62 // If the u_update job was an unsuspend request, re-adds the redirection
63 // to the Google Apps delivery address, provided the account is active (it might
64 // have been deleted between the unsuspension and the post-queue processing).
65 $parameters = json_decode($job['j_parameters'], true);
66 $username = isset($parameters['username']) ? $parameters['username'] : null;
67 if (!($user = User::getSilent($username))) {
68 return;
69 }
70
71 if (isset($parameters['suspended']) && $parameters['suspended'] == false) {
72 require_once('emails.inc.php');
73 $account = new GoogleAppsAccount($user);
74 if ($account->active()) {
75 // Re-adds the email redirection (if the user did request it).
76 if ($account->activate_mail_redirection) {
77 $storage = new EmailStorage($user, 'googleapps');
78 $storage->activate();
79 }
80
81 // Sends an email to the account owner.
82 $res = XDB::query(
83 "SELECT FIND_IN_SET('femme', u.flags), prenom
84 FROM auth_user_md5 AS u
85 WHERE u.user_id = {?}", $user->id());
86 list($sexe, $prenom) = $res->fetchOneRow();
87
88 $mailer = new PlMailer('googleapps/unsuspend.mail.tpl');
89 $mailer->assign('account', $account);
90 $mailer->assign('email', $user->bestEmail());
91 $mailer->assign('prenom', $prenom);
92 $mailer->assign('sexe', $sexe);
93 $mailer->send();
94 }
95 }
96 }
97
98 // Reprensentation of an SQL-stored Google Apps account.
99 // This class is the interface with the gappsd SQL tables: gappsd is the python
100 // daemon which deals with Google Apps provisioning APIs.
101 // TODO(vincent.zanotti): add the url of gappsd, when available.
102 class GoogleAppsAccount
103 {
104 // User identification: user id, and hruid.
105 private $user;
106 public $g_account_name;
107
108 // Local account parameters.
109 public $sync_password;
110 public $activate_mail_redirection;
111
112 // Account status, obtained from Google Apps provisioning & reporting APIs.
113 public $g_account_id;
114 public $g_status;
115 public $g_suspension;
116 public $r_disk_usage;
117 public $r_creation;
118 public $r_last_login;
119 public $r_last_webmail;
120 public $reporting_date;
121
122 // Nicknames (aliases) registered for that user, lazily loaded.
123 public $nicknames;
124
125 // Pending requests in the gappsd job queue (cf. top note).
126 public $pending_create;
127 public $pending_delete;
128 public $pending_update;
129 public $pending_update_admin;
130 public $pending_update_other;
131 public $pending_update_password;
132 public $pending_update_suspension;
133
134 // Pending requests in plat/al validation queue.
135 public $pending_validation_unsuspend;
136
137 // Constructs the account object, by retrieving all informations from the
138 // GApps account table, from GApps job queue, and from plat/al validation queue.
139 public function __construct(User &$user)
140 {
141 $this->user = &$user;
142 if (!$this->user || !$this->user->login()) {
143 return;
144 }
145
146 // TODO: switch to multi-domain Google Apps, and use $this->user->forlifeEmail()
147 // as Google Apps idenfiant (requires changes in gappsd).
148 $this->g_account_name = $this->user->login();
149 $this->g_status = NULL;
150
151 $res = XDB::query(
152 "SELECT l_sync_password, l_activate_mail_redirection,
153 g_account_name, g_account_id, g_status, g_suspension, r_disk_usage,
154 UNIX_TIMESTAMP(r_creation) as r_creation,
155 UNIX_TIMESTAMP(r_last_login) as r_last_login,
156 UNIX_TIMESTAMP(r_last_webmail) as r_last_webmail
157 FROM gapps_accounts
158 WHERE g_account_name = {?}", $this->g_account_name);
159 if ($account = $res->fetchOneAssoc()) {
160 $this->sync_password = $account['l_sync_password'];
161 $this->activate_mail_redirection = $account['l_activate_mail_redirection'];
162 $this->g_account_id = $account['g_account_id'];
163 $this->g_status = $account['g_status'];
164 $this->g_suspension = $account['g_suspension'];
165 $this->r_disk_usage = $account['r_disk_usage'];
166 $this->r_creation = $account['r_creation'];
167 $this->r_last_login = $account['r_last_webmail'];
168 $this->r_last_webmail = $account['r_last_webmail'];
169
170 $this->load_pending_counts();
171 $this->load_pending_validations();
172 if ($this->pending_update) {
173 $this->load_pending_updates();
174 }
175
176 $res = XDB::query("SELECT MAX(date) FROM gapps_reporting");
177 $this->reporting_date = $res->fetchOneCell();
178 }
179 }
180
181 // Determines if changes to the Google Account are currently waiting in the
182 // GApps job queue, and initializes the local values accordingly.
183 private function load_pending_counts()
184 {
185 $res = XDB::query(
186 "SELECT SUM(j_type = 'u_create') AS pending_create,
187 SUM(j_type = 'u_update') AS pending_update,
188 SUM(j_type = 'u_delete') AS pending_delete
189 FROM gapps_queue
190 WHERE q_recipient_id = {?} AND
191 p_status IN ('idle', 'active', 'softfail')
192 GROUP BY j_type", $this->user->id());
193 $pending = $res->fetchOneAssoc();
194 $this->pending_create = $pending['pending_create'];
195 $this->pending_update = $pending['pending_update'];
196 $this->pending_delete = $pending['pending_delete'];
197
198 $this->pending_update_admin = false;
199 $this->pending_update_other = false;
200 $this->pending_update_password = false;
201 $this->pending_update_suspension = false;
202 }
203
204 // Checks for unsuspend requests waiting for validation in plat/al
205 // validation queue.
206 private function load_pending_validations()
207 {
208 require_once('validations.inc.php');
209 $this->pending_validation_unsuspend =
210 Validate::get_typed_requests_count($this->user->id(), 'gapps-unsuspend');
211 }
212
213 // Retrieves all the pending update job in the gappsd queue for the current
214 // user, and analyzes the scope of the update (ie. the fields in the user
215 // account which are going to be updated).
216 private function load_pending_updates()
217 {
218 $res = XDB::iterator(
219 "SELECT j_parameters
220 FROM gapps_queue
221 WHERE q_recipient_id = {?} AND
222 p_status IN ('idle', 'active', 'softfail') AND
223 j_type = 'u_update'", $this->user->id());
224 while ($update = $res->next()) {
225 $update_data = json_decode($update["j_parameters"], true);
226
227 if (isset($update_data["suspended"])) {
228 $this->pending_update_suspension = true;
229 } elseif (isset($update_data["password"])) {
230 $this->pending_update_password = true;
231 } elseif (isset($update_data["admin"])) {
232 $this->pending_update_admin = true;
233 } else {
234 $this->pending_update_other = true;
235 }
236 }
237 }
238
239 // Creates a queue job of the @p type, for the user represented by this
240 // GoogleAppsAccount object, using @p parameters. @p parameters is supposed
241 // to be a one-dimension array of key-value mappings.
242 // The created job as a 'immediate' priority, and is scheduled for immediate
243 // execution.
244 private function create_queue_job($type, $parameters) {
245 $parameters["username"] = $this->g_account_name;
246 XDB::execute(
247 "INSERT INTO gapps_queue
248 SET q_owner_id = {?}, q_recipient_id = {?},
249 p_entry_date = NOW(), p_notbefore_date = NOW(),
250 p_priority = 'immediate',
251 j_type = {?}, j_parameters = {?}",
252 S::v('uid'),
253 $this->user->id(),
254 $type,
255 json_encode($parameters));
256 }
257
258
259 // Returns true if the account is currently active.
260 public function active()
261 {
262 return $this->g_status == 'active';
263 }
264
265 // Returns true if the account exists in Google Apps.
266 public function provisioned()
267 {
268 return $this->g_status == 'active' or $this->g_status == 'disabled';
269 }
270
271 // Returns true if the account exists, but cannot be used (user-requested
272 // suspension, or Google-requested suspension).
273 public function suspended()
274 {
275 return $this->g_status == 'disabled';
276 }
277
278 // Loads and returns the list of nicknames for the user.
279 public function nicknames()
280 {
281 if ($this->nicknames == null) {
282 $res = XDB::query(
283 "SELECT g_nickname
284 FROM gapps_nicknames
285 WHERE g_account_name = {?}
286 ORDER BY g_nickname",
287 $this->g_account_name);
288 $this->nicknames = $res->fetchColumn();
289 }
290 return $this->nicknames;
291 }
292
293
294 // Changes the GoogleApps password.
295 public function set_password($password) {
296 if (!$this->provisioned()) {
297 return;
298 }
299
300 if (!$this->pending_update_password) {
301 $this->create_queue_job('u_update', array('password' => $password));
302 $this->pending_update_password = true;
303 }
304 }
305
306
307 // Changes the password synchronization status ("sync = true" means that the
308 // Polytechnique.org password will be replicated to the Google Apps account).
309 public function set_password_sync($sync) {
310 if (!$this->provisioned()) {
311 return;
312 }
313
314 $this->sync_password = $sync;
315 XDB::execute(
316 "UPDATE gapps_accounts
317 SET l_sync_password = {?}
318 WHERE g_account_name = {?}",
319 $sync,
320 $this->g_account_name);
321 }
322
323 // Suspends the Google Apps account.
324 public function suspend() {
325 if (!$this->provisioned()) {
326 return;
327 }
328
329 if (!$this->pending_update_suspension) {
330 $this->create_queue_job('u_update', array('suspended' => true));
331 $this->pending_update_suspension = true;
332 XDB::execute(
333 "UPDATE gapps_accounts
334 SET g_status = 'disabled'
335 WHERE g_account_name = {?} AND g_status = 'active'",
336 $this->g_account_name);
337 }
338 }
339
340 // Adds an unsuspension request to the validation queue (used on user-request).
341 public function unsuspend($activate_mail_redirection = NULL) {
342 if (!$this->provisioned()) {
343 return;
344 }
345 if ($activate_mail_redirection !== NULL) {
346 $this->activate_mail_redirection = $activate_mail_redirection;
347 XDB::execute(
348 "UPDATE gapps_accounts
349 SET l_activate_mail_redirection = {?}
350 WHERE g_account_name = {?}",
351 $activate_mail_redirection,
352 $this->g_account_name);
353 }
354
355 if (!$this->pending_update_suspension && !$this->pending_validation_unsuspend) {
356 require_once('validations.inc.php');
357 $unsuspend = new GoogleAppsUnsuspendReq($this->user);
358 $unsuspend->submit();
359 $this->pending_validation_unsuspend = true;
360 }
361 }
362
363 // Unsuspends the Google Apps account (used on admin-request, or on validation of
364 // an user-request).
365 public function do_unsuspend() {
366 if (!$this->provisioned()) {
367 return;
368 }
369
370 if (!$this->pending_update_suspension) {
371 if ($this->sync_password) {
372 $res = XDB::query(
373 "SELECT password
374 FROM auth_user_md5
375 WHERE user_id = {?}", $this->user->id());
376 $password = ($res->numRows() > 0 ? $res->fetchOneCell() : false);
377 } else {
378 $password = false;
379 }
380
381 if ($password) {
382 $this->create_queue_job('u_update', array('suspended' => false, 'password' => $password));
383 } else {
384 $this->create_queue_job('u_update', array('suspended' => false));
385 }
386 $this->pending_update_suspension = true;
387 return true;
388 }
389 return false;
390 }
391
392 // Creates a new Google Apps account with the @p local parameters.
393 public function create($password_sync, $password, $redirect_mails) {
394 if ($this->g_status != NULL) {
395 return;
396 }
397
398 if (!$this->pending_create) {
399 // Retrieves information on the new account.
400 $res = XDB::query(
401 "SELECT nom, nom_usage, prenom
402 FROM auth_user_md5
403 WHERE user_id = {?}", $this->user->id());
404 list($nom, $nom_usage, $prenom) = $res->fetchOneRow();
405
406 // Adds an 'unprovisioned' entry in the gapps_accounts table.
407 XDB::execute(
408 "INSERT INTO gapps_accounts
409 SET l_userid = {?},
410 l_sync_password = {?},
411 l_activate_mail_redirection = {?},
412 g_account_name = {?},
413 g_first_name = {?},
414 g_last_name = {?},
415 g_status = 'unprovisioned'",
416 $this->user->id(),
417 $password_sync,
418 $redirect_mails,
419 $this->g_account_name,
420 $prenom,
421 ($nom_usage ? $nom_usage : $nom));
422
423 // Adds the creation job in the GApps queue.
424 $this->create_queue_job(
425 'u_create',
426 array(
427 'username' => $this->g_account_name,
428 'first_name' => $prenom,
429 'last_name' => ($nom_usage ? $nom_usage : $nom),
430 'password' => $password,
431 ));
432
433 // Updates the GoogleAppsAccount status.
434 $this->__construct($this->user);
435 }
436 }
437
438
439 // Returns the status of the Google Apps account for @p user, or false
440 // when no account exists.
441 static public function account_status($uid) {
442 $res = XDB::query(
443 "SELECT g_status
444 FROM gapps_accounts
445 WHERE l_userid = {?}", $uid);
446 return ($res->numRows() > 0 ? $res->fetchOneCell() : false);
447 }
448
449 // Returns true if the @p user is an administrator of the Google Apps domain.
450 static public function is_administrator($uid) {
451 $res = XDB::query(
452 "SELECT g_admin
453 FROM gapps_accounts
454 WHERE l_userid = {?} AND g_status = 'active'", $uid);
455 return ($res->numRows() > 0 ? (bool)$res->fetchOneCell() : false);
456 }
457 }
458
459 // vim:set et sw=4 sts=4 sws=4 foldmethod=marker enc=utf-8:
460 ?>