rcmail_utils.php
12.2 KB
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
<?php
/**
+-----------------------------------------------------------------------+
| This file is part of the Roundcube Webmail client |
| |
| Copyright (C) The Roundcube Dev Team |
| |
| Licensed under the GNU General Public License version 3 or |
| any later version with exceptions for skins & plugins. |
| See the README file for a full license statement. |
| |
| CONTENTS: |
| Roundcube utilities |
+-----------------------------------------------------------------------+
| Author: Thomas Bruederli <roundcube@gmail.com> |
| Author: Aleksander Machniak <alec@alec.pl> |
+-----------------------------------------------------------------------+
*/
/**
* Roundcube utilities
*
* @package Webmail
* @subpackage Utils
*/
class rcmail_utils
{
public static $db;
/**
* Initialize database object and connect
*
* @return rcube_db Database instance
*/
public static function db()
{
if (self::$db === null) {
$rc = rcube::get_instance();
$db = rcube_db::factory($rc->config->get('db_dsnw'));
$db->set_debug((bool)$rc->config->get('sql_debug'));
// Connect to database
$db->db_connect('w');
if (!$db->is_connected()) {
rcube::raise_error("Failed to connect to database", false, true);
}
self::$db = $db;
}
return self::$db;
}
/**
* Initialize database schema
*
* @param string $dir Directory with sql files
*/
public static function db_init($dir)
{
$db = self::db();
$error = null;
$file = $dir . '/' . $db->db_provider . '.initial.sql';
if (!file_exists($file)) {
rcube::raise_error("DDL file $file not found", false, true);
}
echo "Creating database schema... ";
if ($sql = file_get_contents($file)) {
if (!$db->exec_script($sql)) {
$error = $db->is_error();
}
}
else {
$error = "Unable to read file $file or it is empty";
}
if ($error) {
echo "[FAILED]\n";
rcube::raise_error($error, false, true);
}
else {
echo "[OK]\n";
}
}
/**
* Update database schema
*
* @param string $dir Directory with sql files
* @param string $package Component name
* @param string $ver Optional current version number
* @param array $opts Parameters (errors, quiet)
*
* @return True on success, False on failure
*/
public static function db_update($dir, $package, $ver = null, $opts = [])
{
// Check if directory exists
if (!file_exists($dir)) {
if (!empty($opts['errors'])) {
rcube::raise_error("Specified database schema directory doesn't exist.", false, true);
}
return false;
}
$db = self::db();
// Read DB schema version from database (if 'system' table exists)
if (in_array($db->table_name('system'), (array)$db->list_tables())) {
$version = self::db_version($package);
}
// DB version not found, but release version is specified
if (empty($version) && $ver) {
// Map old release version string to DB schema version
// Note: This is for backward compat. only, do not need to be updated
$map = [
'0.1-stable' => 1,
'0.1.1' => 2008030300,
'0.2-alpha' => 2008040500,
'0.2-beta' => 2008060900,
'0.2-stable' => 2008092100,
'0.2.1' => 2008092100,
'0.2.2' => 2008092100,
'0.3-stable' => 2008092100,
'0.3.1' => 2009090400,
'0.4-beta' => 2009103100,
'0.4' => 2010042300,
'0.4.1' => 2010042300,
'0.4.2' => 2010042300,
'0.5-beta' => 2010100600,
'0.5' => 2010100600,
'0.5.1' => 2010100600,
'0.5.2' => 2010100600,
'0.5.3' => 2010100600,
'0.5.4' => 2010100600,
'0.6-beta' => 2011011200,
'0.6' => 2011011200,
'0.7-beta' => 2011092800,
'0.7' => 2011111600,
'0.7.1' => 2011111600,
'0.7.2' => 2011111600,
'0.7.3' => 2011111600,
'0.7.4' => 2011111600,
'0.8-beta' => 2011121400,
'0.8-rc' => 2011121400,
'0.8.0' => 2011121400,
'0.8.1' => 2011121400,
'0.8.2' => 2011121400,
'0.8.3' => 2011121400,
'0.8.4' => 2011121400,
'0.8.5' => 2011121400,
'0.8.6' => 2011121400,
'0.9-beta' => 2012080700,
];
$version = $map[$ver];
}
// Assume last version before the 'system' table was added
if (empty($version)) {
$version = 2012080700;
}
$dir .= '/' . $db->db_provider;
if (!file_exists($dir)) {
if ($opts['errors']) {
rcube::raise_error("DDL Upgrade files for " . $db->db_provider . " driver not found.", false, true);
}
return false;
}
$dh = opendir($dir);
$result = [];
while ($file = readdir($dh)) {
if (preg_match('/^([0-9]+)\.sql$/', $file, $m) && $m[1] > $version) {
$result[] = $m[1];
}
}
sort($result, SORT_NUMERIC);
foreach ($result as $v) {
if (empty($opts['quiet'])) {
echo "Updating database schema ($v)... ";
}
// Ignore errors here to print the error only once
$db->set_option('ignore_errors', true);
$error = self::db_update_schema($package, $v, "$dir/$v.sql");
$db->set_option('ignore_errors', false);
if ($error) {
if (empty($opts['quiet'])) {
echo "[FAILED]\n";
}
if (!empty($opts['errors'])) {
rcube::raise_error("Error in DDL upgrade $v: $error", false, true);
}
return false;
}
else if (empty($opts['quiet'])) {
echo "[OK]\n";
}
}
return true;
}
/**
* Run database update from a single sql file
*/
protected static function db_update_schema($package, $version, $file)
{
$db = self::db();
// read DDL file
if ($sql = file_get_contents($file)) {
if (!$db->exec_script($sql)) {
return $db->is_error();
}
}
// escape if 'system' table does not exist
if ($version < 2013011000) {
return;
}
$system_table = $db->table_name('system', true);
$db->query("UPDATE " . $system_table
. " SET `value` = ?"
. " WHERE `name` = ?",
$version, $package . '-version');
if (!$db->is_error() && !$db->affected_rows()) {
$db->query("INSERT INTO " . $system_table
." (`name`, `value`) VALUES (?, ?)",
$package . '-version', $version);
}
return $db->is_error();
}
/**
* Get version string for the specified package
*
* @param string $package Package name
*
* @return string Version string
*/
public static function db_version($package = 'roundcube')
{
$db = self::db();
$db->query("SELECT `value`"
. " FROM " . $db->table_name('system', true)
. " WHERE `name` = ?",
$package . '-version');
$row = $db->fetch_array();
$version = preg_replace('/[^0-9]/', '', $row[0]);
return $version;
}
/**
* Removes all deleted records older than X days
*
* @param int $days Number of days
*/
public static function db_clean($days)
{
// mapping for table name => primary key
$primary_keys = [
'contacts' => 'contact_id',
'contactgroups' => 'contactgroup_id',
];
$db = self::db();
$threshold = date('Y-m-d 00:00:00', time() - $days * 86400);
foreach (['contacts','contactgroups','identities'] as $table) {
$sqltable = $db->table_name($table, true);
// also delete linked records
// could be skipped for databases which respect foreign key constraints
if ($db->db_provider == 'sqlite' && ($table == 'contacts' || $table == 'contactgroups')) {
$pk = $primary_keys[$table];
$memberstable = $db->table_name('contactgroupmembers');
$db->query(
"DELETE FROM " . $db->quote_identifier($memberstable)
. " WHERE `$pk` IN ("
. "SELECT `$pk` FROM $sqltable"
. " WHERE `del` = 1 AND `changed` < ?"
. ")",
$threshold);
echo $db->affected_rows() . " records deleted from '$memberstable'\n";
}
// delete outdated records
$db->query("DELETE FROM $sqltable WHERE `del` = 1 AND `changed` < ?", $threshold);
echo $db->affected_rows() . " records deleted from '$table'\n";
}
}
/**
* Reindex contacts
*/
public static function indexcontacts()
{
$db = self::db();
// iterate over all users
$sql_result = $db->query("SELECT `user_id` FROM " . $db->table_name('users', true) . " ORDER BY `user_id`");
while ($sql_result && ($sql_arr = $db->fetch_assoc($sql_result))) {
echo "Indexing contacts for user " . $sql_arr['user_id'] . "...\n";
$contacts = new rcube_contacts($db, $sql_arr['user_id']);
$contacts->set_pagesize(9999);
$result = $contacts->list_records();
while ($result->count && ($row = $result->next())) {
unset($row['words']);
$contacts->update($row['ID'], $row);
}
}
echo "done.\n";
}
/**
* Modify user preferences
*
* @param string $name Option name
* @param string $value Option value
* @param int $userid Optional user identifier
* @param string $type Optional value type (bool, int, string)
*/
public static function mod_pref($name, $value, $userid = null, $type = 'string')
{
$db = self::db();
if ($userid) {
$query = '`user_id` = ' . intval($userid);
}
else {
$query = '1=1';
}
$type = strtolower($type);
if ($type == 'bool' || $type == 'boolean') {
$value = rcube_utils::get_boolean($value);
}
else if ($type == 'int' || $type == 'integer') {
$value = (int) $value;
}
// iterate over all users
$sql_result = $db->query("SELECT * FROM " . $db->table_name('users', true) . " WHERE $query");
while ($sql_result && ($sql_arr = $db->fetch_assoc($sql_result))) {
echo "Updating prefs for user " . $sql_arr['user_id'] . "...";
$user = new rcube_user($sql_arr['user_id'], $sql_arr);
$prefs = $old_prefs = $user->get_prefs();
$prefs[$name] = $value;
if ($prefs != $old_prefs) {
$user->save_prefs($prefs, true);
echo "saved.\n";
}
else {
echo "nothing changed.\n";
}
}
}
}