1#!/usr/bin/env php
2<?php
3
4/*
5 +-----------------------------------------------------------------------+
6 | This file is part of the Roundcube Webmail client                     |
7 |                                                                       |
8 | Copyright (C) The Roundcube Dev Team                                  |
9 |                                                                       |
10 | Licensed under the GNU General Public License version 3 or            |
11 | any later version with exceptions for skins & plugins.                |
12 | See the README file for a full license statement.                     |
13 |                                                                       |
14 | PURPOSE:                                                              |
15 |   Utility script to remove all data related to a certain user         |
16 |   from the local database.                                            |
17 +-----------------------------------------------------------------------+
18 | Author: Thomas Bruederli <thomas@roundcube.net>                       |
19 +-----------------------------------------------------------------------+
20*/
21
22define('INSTALL_PATH', realpath(__DIR__ . '/..') . '/' );
23
24require_once INSTALL_PATH . 'program/include/clisetup.php';
25
26function print_usage()
27{
28    print "Usage: deluser.sh [--host=HOST][--age=DAYS][--dry-run] [username]\n";
29    print "--host=HOST  The IMAP hostname or IP the given user is related to\n";
30    print "--age=DAYS   Delete all users who have not logged in for more than X days\n";
31    print "--dry-run    List users but do not delete them (for use with --age)\n";
32}
33
34function _die($msg, $usage=false)
35{
36    fwrite(STDERR, $msg . "\n");
37    if ($usage) print_usage();
38    exit(1);
39}
40
41$rcmail = rcube::get_instance();
42
43// get arguments
44$args = rcube_utils::get_opt(['h' => 'host', 'a' => 'age', 'd' => 'dry-run:bool']);
45
46if (!empty($args['age']) && ($age = intval($args['age']))) {
47    $db = $rcmail->get_dbh();
48    $db->db_connect('r');
49
50    $query = $db->query("SELECT `username`, `mail_host` FROM " . $db->table_name('users', true)
51        . " WHERE `last_login` < " . $db->now($age * -1 * 86400)
52        . ($args['host'] ? " AND `mail_host` = " . $db->quote($args['host']) : '')
53    );
54
55    while ($user = $db->fetch_assoc($query)) {
56        if (!empty($args['dry-run'])) {
57            printf("%s (%s)\n", $user['username'], $user['mail_host']);
58            continue;
59        }
60        system(sprintf("php %s/deluser.sh --host=%s %s", INSTALL_PATH . 'bin', escapeshellarg($user['mail_host']), escapeshellarg($user['username'])));
61    }
62    exit(0);
63}
64
65$username = isset($args[0]) ? trim($args[0]) : null;
66if (empty($username)) {
67    _die("Missing required parameters", true);
68}
69
70if (empty($args['host'])) {
71    $hosts = $rcmail->config->get('default_host', '');
72    if (is_string($hosts)) {
73        $args['host'] = $hosts;
74    }
75    else if (is_array($hosts) && count($hosts) == 1) {
76        $args['host'] = reset($hosts);
77    }
78    else {
79        _die("Specify a host name", true);
80    }
81
82    // host can be a URL like tls://192.168.12.44
83    $host_url = parse_url($args['host']);
84    if ($host_url['host']) {
85        $args['host'] = $host_url['host'];
86    }
87}
88
89// connect to DB
90$db = $rcmail->get_dbh();
91$db->db_connect('w');
92$transaction = false;
93
94if (!$db->is_connected() || $db->is_error()) {
95    _die("No DB connection\n" . $db->is_error());
96}
97
98// find user in local database
99$user = rcube_user::query($username, $args['host']);
100
101if (!$user) {
102    die("User not found.\n");
103}
104
105// inform plugins about approaching user deletion
106$plugin = $rcmail->plugins->exec_hook('user_delete_prepare', ['user' => $user, 'username' => $username, 'host' => $args['host']]);
107
108// let plugins cleanup their own user-related data
109if (!$plugin['abort']) {
110    $transaction = $db->startTransaction();
111    $plugin = $rcmail->plugins->exec_hook('user_delete', $plugin);
112}
113
114if ($plugin['abort']) {
115    if ($transaction) {
116        $db->rollbackTransaction();
117    }
118    _die("User deletion aborted by plugin");
119}
120
121// deleting the user record should be sufficient due to ON DELETE CASCADE foreign key references
122// but not all database backends actually support this so let's do it by hand
123foreach (['identities','contacts','contactgroups','dictionary','cache','cache_index','cache_messages','cache_thread','searches','users'] as $table) {
124    $db->query('DELETE FROM ' . $db->table_name($table, true) . ' WHERE `user_id` = ?', $user->ID);
125}
126
127if ($db->is_error()) {
128    $rcmail->plugins->exec_hook('user_delete_rollback', $plugin);
129    _die("DB error occurred: " . $db->is_error());
130}
131else {
132    // inform plugins about executed user deletion
133    $plugin = $rcmail->plugins->exec_hook('user_delete_commit', $plugin);
134
135    if ($plugin['abort']) {
136        unset($plugin['abort']);
137        $db->rollbackTransaction();
138        $rcmail->plugins->exec_hook('user_delete_rollback', $plugin);
139    }
140    else {
141        $db->endTransaction();
142        echo "Successfully deleted user $user->ID\n";
143    }
144}
145