427353749031c0d932eb0bb9847621432ae1d536
[mailer.git] / inc / libs / admins_functions.php
1 <?php
2 /************************************************************************
3  * MXChange v0.2.1                                    Start: 06/30/2003 *
4  * ===============                              Last change: 11/27/2004 *
5  *                                                                      *
6  * -------------------------------------------------------------------- *
7  * File              : admins_functions.php                             *
8  * -------------------------------------------------------------------- *
9  * Short description : Functions for the admins extension               *
10  * -------------------------------------------------------------------- *
11  * Kurzbeschreibung  : Funktionen fuer die admins-Erweiterung           *
12  * -------------------------------------------------------------------- *
13  * $Revision::                                                        $ *
14  * $Date::                                                            $ *
15  * $Tag:: 0.2.1-FINAL                                                 $ *
16  * $Author::                                                          $ *
17  * Needs to be in all Files and every File needs "svn propset           *
18  * svn:keywords Date Revision" (autoprobset!) at least!!!!!!            *
19  * -------------------------------------------------------------------- *
20  * Copyright (c) 2003 - 2009 by Roland Haeder                           *
21  * For more information visit: http://www.mxchange.org                  *
22  *                                                                      *
23  * This program is free software; you can redistribute it and/or modify *
24  * it under the terms of the GNU General Public License as published by *
25  * the Free Software Foundation; either version 2 of the License, or    *
26  * (at your option) any later version.                                  *
27  *                                                                      *
28  * This program is distributed in the hope that it will be useful,      *
29  * but WITHOUT ANY WARRANTY; without even the implied warranty of       *
30  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the        *
31  * GNU General Public License for more details.                         *
32  *                                                                      *
33  * You should have received a copy of the GNU General Public License    *
34  * along with this program; if not, write to the Free Software          *
35  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston,               *
36  * MA  02110-1301  USA                                                  *
37  ************************************************************************/
38
39 // Some security stuff...
40 if (!defined('__SECURITY')) {
41         die();
42 }
43
44 // Check ACL for menu combination
45 function adminsCheckAdminAcl ($action, $what) {
46         // If action is login or logout allow allways!
47         $default = 'allow';
48         if (($action == 'login') || ($action == 'logout')) return true;
49
50         // Default is deny
51         $ret = false;
52
53         // Get admin's ID
54         $adminId = getCurrentAdminId();
55
56         // Get admin's defult access right
57         $default = getAdminDefaultAcl($adminId);
58
59         if (!empty($what)) {
60                 // Check for parent menu:
61                 // First get it's action value
62                 $parent_action = getModeAction('admin', $what);
63
64                 // Check with this function...
65                 $parent = adminsCheckAdminAcl($parent_action, '');
66         } else {
67                 // Anything else is true!
68                 $parent = false;
69         }
70
71         // Shall I test for a main or sub menu? (action or what?)
72         $acl_mode = 'failed';
73         if ((getExtensionVersion('cache') >= '0.1.2') && (isset($GLOBALS['cache_array']['admin_acls'])) && (count($GLOBALS['cache_array']['admin_acls']) > 0)) {
74                 // Lookup in cache
75                 if ((!empty($action)) && (isset($GLOBALS['cache_array']['admin_acls']['action_menu'][$adminId])) & ($GLOBALS['cache_array']['admin_acls']['action_menu'][$adminId] == $action)) {
76                         // Main menu line found
77                         $acl_mode = $GLOBALS['cache_array']['admin_acls']['access_mode'][$adminId];
78
79                         // Count cache hits
80                         incrementStatsEntry('cache_hits');
81                 } elseif ((!empty($what)) && (isset($GLOBALS['cache_array']['admin_acls']['what_menu'][$adminId])) && ($GLOBALS['cache_array']['admin_acls']['what_menu'][$adminId] == $what)) {
82                         // Check sub menu
83                         $acl_mode = $GLOBALS['cache_array']['admin_acls']['access_mode'][$adminId];
84
85                         // Count cache hits
86                         incrementStatsEntry('cache_hits');
87                 }
88         } elseif (!isExtensionActive('cache')) {
89                 // Old version, so load it from database
90                 $result = false;
91                 if (!empty($action)) {
92                         // Main menu
93                         $result = SQL_QUERY_ESC("SELECT `access_mode` FROM `{?_MYSQL_PREFIX?}_admins_acls` WHERE `admin_id`=%s AND `action_menu`='%s' LIMIT 1",
94                                 array(bigintval($adminId), $action), __FUNCTION__, __LINE__);
95                 } elseif (!empty($what)) {
96                         // Sub menu
97                         $result = SQL_QUERY_ESC("SELECT `access_mode` FROM `{?_MYSQL_PREFIX?}_admins_acls` WHERE `admin_id`=%s AND `what_menu`='%s' LIMIT 1",
98                                 array(bigintval($adminId), $what), __FUNCTION__, __LINE__);
99                 }
100
101                 // Is an entry found?
102                 if (SQL_NUMROWS($result) == 1) {
103                         // Load ACL
104                         list($acl_mode) = SQL_FETCHROW($result);
105                 } // END - if
106
107                 // Free memory
108                 SQL_FREERESULT($result);
109         }
110
111         // Check ACL and (maybe) allow
112         //* DEBUG: */ print 'default='.$default.',acl_mode='.$acl_mode.',parent='.intval($parent).'<br />';
113         if (($default == 'allow') || (($default == 'deny') && ($acl_mode == 'allow')) || ($parent === true) || (($default == '***') && ($acl_mode == 'failed') && ($parent === false))) {
114                 // Access is granted
115                 $ret = true;
116         } // END - if
117
118         // Return value
119         //* DEBUG: */ outputHtml(__FUNCTION__."[".__LINE__."]:act={$action},wht={$whatOR},default={$default},acl_mode={$acl_mode}<br />");
120         return $ret;
121 }
122
123 // Create email link to admins's account
124 function generateAdminEmailLink ($email, $mod = 'admin') {
125         // Is it an email?
126         if (strpos($email, '@') !== false) {
127                 // Create email link
128                 $result = SQL_QUERY_ESC("SELECT `id`
129 FROM
130         `{?_MYSQL_PREFIX?}_admins`
131 WHERE
132         `email`='%s'
133 LIMIT 1",
134                 array($email), __FUNCTION__, __LINE__);
135
136                 // Is there an entry?
137                 if (SQL_NUMROWS($result) == 1) {
138                         // Load userid
139                         list($adminId) = SQL_FETCHROW($result);
140
141                         // Rewrite email address to contact link
142                         $email = "{?URL?}/modules.php?module=".$mod."&amp;what=admins_contct&amp;admin=".bigintval($adminId);
143                 } // END - if
144
145                 // Free memory
146                 SQL_FREERESULT($result);
147         } elseif ((is_int($email)) && ($email > 0)) {
148                 // Direct ID given
149                 $email = "{?URL?}/modules.php?module=".$mod."&amp;what=admins_contct&amp;admin=".bigintval($email);
150         }
151
152         // Return rewritten (?) email address
153         return $email;
154 }
155
156 // Change a lot admin account
157 function adminsChangeAdminAccount ($postData) {
158         // Begin the update
159         $cache_update = 0;
160         foreach ($postData['login'] as $id => $login) {
161                 // Secure ID number
162                 $id = bigintval($id);
163
164                 // When both passwords match update admin account
165                 if ($postData['pass1'][$id] == $postData['pass2'][$id]) {
166                         // Save only when both passwords are the same (also when they are empty)
167                         $add = ''; $cache_update = '1';
168
169                         // Generate hash
170                         $hash = generateHash($postData['pass1'][$id]);
171
172                         // Save password when set
173                         if (!empty($postData['pass1'][$id])) $add = sprintf(", password='%s'", SQL_ESCAPE($hash));
174
175                         // Get admin's ID
176                         $adminId = getCurrentAdminId();
177                         $salt = substr(getAdminHash($adminId), 0, -40);
178
179                         // Rewrite cookie when it's own account
180                         if ($adminId == $id) {
181                                 // Set timeout cookie
182                                 setSession('admin_last', time());
183
184                                 if ($login != getSession('admin_login')) {
185                                         // Update login cookie
186                                         setSession('admin_login', $login);
187
188                                         // Update password cookie as well?
189                                         if (!empty($add)) setSession('admin_md5', $hash);
190                                 } elseif (generateHash($postData['pass1'][$id], $salt) != getSession('admin_md5')) {
191                                         // Update password cookie
192                                         setSession('admin_md5', $hash);
193                                 }
194                         } // END - if
195
196                         // Get default ACL from admin to check if we can allow him to change the default ACL
197                         $default = getAdminDefaultAcl(getCurrentAdminId());
198
199                         // Update admin account
200                         if ($default == 'allow') {
201                                 // Allow changing default ACL
202                                 SQL_QUERY_ESC("UPDATE
203         `{?_MYSQL_PREFIX?}_admins`
204 SET
205         `login`='%s'".$add.",
206         `email`='%s',
207         `default_acl`='%s',
208         `la_mode`='%s'
209 WHERE
210         `id`=%s
211 LIMIT 1",
212                                 array(
213                                         $login,
214                                         $postData['email'][$id],
215                                         $postData['mode'][$id],
216                                         $postData['la_mode'][$id],
217                                         $id
218                                 ), __FUNCTION__, __LINE__);
219                         } else {
220                                 // Do not allow it here
221                                 SQL_QUERY_ESC("UPDATE
222         `{?_MYSQL_PREFIX?}_admins`
223 SET
224         `login`='%s'".$add.",
225         `email`='%s',
226         `la_mode`='%s'
227 WHERE
228         `id`=%s
229 LIMIT 1",
230                                 array(
231                                         $login,
232                                         $postData['email'][$id],
233                                         $postData['la_mode'][$id],
234                                         $id
235                                 ), __FUNCTION__, __LINE__);
236                         }
237
238                         // Admin account saved
239                         $message = getMessage('ADMIN_ACCOUNT_SAVED');
240                 } else {
241                         // Passwords did not match
242                         $message = getMessage('ADMINS_ERROR_PASS_MISMATCH');
243                 }
244
245                 // Display message
246                 if (!empty($message)) {
247                         loadTemplate('admin_settings_saved', false, $message);
248                 }
249         }
250
251         // Remove cache file
252         runFilterChain('post_admin_edited', postRequestArray());
253 }
254
255 // Make admin accounts editable
256 function adminsEditAdminAccount ($postData) {
257         // "Resolve" current's admin access mode
258         $currMode = getAdminDefaultAcl(getCurrentAdminId());
259
260         // Begin the edit loop
261         $OUT = ''; $SW = 2;
262         foreach ($postData['sel'] as $id => $selected) {
263                 // Secure ID number
264                 $id = bigintval($id);
265
266                 // Get the admin's data
267                 $result = SQL_QUERY_ESC("SELECT `login`, `email`, `default_acl` AS mode, `la_mode` FROM `{?_MYSQL_PREFIX?}_admins` WHERE `id`=%s LIMIT 1",
268                         array($id), __FUNCTION__, __LINE__);
269                 if ((SQL_NUMROWS($result) == 1) && ($selected == 1)) {
270                         // Entry found
271                         $content = SQL_FETCHARRAY($result);
272                         SQL_FREERESULT($result);
273
274                         // Prepare some more data for the template
275                         $content['sw'] = $SW;
276                         $content['id'] = $id;
277
278                         // Shall we allow changing default ACL?
279                         if ($currMode == 'allow') {
280                                 // Allow chaning it
281                                 $content['mode']    = generateOptionList('/ARRAY/', array('allow', 'deny'), array(getMessage('ADMINS_ALLOW_MODE'), getMessage('ADMINS_DENY_MODE')), $content['mode']);
282                         } else {
283                                 // Don't allow it
284                                 $content['mode'] = '&nbsp;';
285                         }
286                         $content['la_mode'] = generateOptionList('/ARRAY/', array('global', 'OLD', 'NEW'), array(getMessage('ADMINS_GLOBAL_LA_SETTING'), getMessage('ADMINS_OLD_LA_SETTING'), getMessage('ADMINS_NEW_LA_SETTING')), $content['la_mode']);
287
288                         // Load row template and switch color
289                         $OUT .= loadTemplate('admin_edit_admins_row', true, $content);
290                         $SW = 3 - $SW;
291                 }
292         }
293
294         // Load template
295         loadTemplate('admin_edit_admins', false, $OUT);
296 }
297
298 // Delete given admin accounts
299 function adminsDeleteAdminAccount ($postData) {
300         // Check if this account is the last one which cannot be deleted...
301         $result_main = SQL_QUERY("SELECT `id` FROM `{?_MYSQL_PREFIX?}_admins`", __FUNCTION__, __LINE__);
302         $accounts = SQL_NUMROWS($result_main);
303         SQL_FREERESULT($result_main);
304         if ($accounts > 1) {
305                 // Delete accounts
306                 $OUT = ''; $SW = 2;
307                 foreach ($postData['sel'] as $id => $selected) {
308                         // Secure ID number
309                         $id = bigintval($id);
310
311                         // Get the admin's data
312                         $result = SQL_QUERY_ESC("SELECT login, email, default_acl AS mode, la_mode FROM `{?_MYSQL_PREFIX?}_admins` WHERE `id`=%s LIMIT 1",
313                         array($id), __FUNCTION__, __LINE__);
314                         if (SQL_NUMROWS($result) == 1) {
315                                 // Entry found
316                                 $content = SQL_FETCHARRAY($result);
317                                 SQL_FREERESULT($result);
318                                 $content['mode'] = getMessage('ADMINS_'.strtoupper($content['mode']).'_MODE');
319                                 $content['la_mode'] = getMessage('ADMINS_'.strtoupper($content['la_mode']).'_LA_SETTING');
320
321                                 // Prepare some more data
322                                 $content['sw'] = $SW;
323                                 $content['id'] = $id;
324
325                                 // Load row template and switch color
326                                 $OUT .= loadTemplate('admin_del_admins_row', true, $content);
327                                 $SW = 3 - $SW;
328                         }
329                 }
330
331                 // Load template
332                 loadTemplate('admin_del_admins', false, $OUT);
333         } else {
334                 // Cannot delete last account!
335                 loadTemplate('admin_settings_saved', false, getMessage('ADMIN_ADMINS_CANNOT_DELETE_LAST'));
336         }
337 }
338
339 // Remove the given accounts
340 function adminsRemoveAdminAccount ($postData) {
341         // Begin removal
342         $cache_update = 0;
343         foreach ($postData['sel'] as $id => $del) {
344                 // Secure ID number
345                 $id = bigintval($id);
346
347                 // Delete only when it's not your own account!
348                 if (($del == 1) && (getCurrentAdminId() != $id)) {
349                         // Rewrite his tasks to all admins
350                         SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_task_system` SET `assigned_admin`=0 WHERE `assigned_admin`=%s",
351                                 array($id), __FUNCTION__, __LINE__);
352
353                         // Remove account
354                         SQL_QUERY_ESC("DELETE LOW_PRIORITY FROM `{?_MYSQL_PREFIX?}_admins` WHERE `id`=%s LIMIT 1",
355                                 array($id), __FUNCTION__, __LINE__);
356                 }
357         }
358
359         // Remove cache if cache system is activated
360         runFilterChain('post_admin_deleted', postRequestArray());
361 }
362
363 // List all admin accounts
364 function adminsListAdminAccounts() {
365         // Select all admin accounts
366         $result = SQL_QUERY("SELECT `id`, `login`, `email`, `default_acl` AS mode, `la_mode` FROM `{?_MYSQL_PREFIX?}_admins` ORDER BY `login` ASC", __FUNCTION__, __LINE__);
367         $OUT = ''; $SW = 2;
368         while ($content = SQL_FETCHARRAY($result)) {
369                 // Compile some variables
370                 $content['mode'] = getMessage('ADMINS_'.strtoupper($content['mode']).'_MODE');
371                 $content['la_mode'] = getMessage('ADMINS_'.strtoupper($content['la_mode']).'_LA_SETTING');
372
373                 // Prepare some more data
374                 $content['sw']         = $SW;
375                 $content['email_link'] = generateEmailLink($content['id'], 'admins');
376
377                 // Load row template and switch color
378                 $OUT .= loadTemplate('admin_list_admins_row', true, $content);
379                 $SW = 3 - $SW;
380         }
381
382         // Free memory
383         SQL_FREERESULT($result);
384
385         // Load template
386         loadTemplate('admin_list_admins', false, $OUT);
387 }
388
389 // Filter for adding extra data to the query
390 function FILTER_ADD_EXTRA_SQL_DATA ($add = '') {
391         // Is the admins extension updated? (should be!)
392         if (getExtensionVersion('admins') >= '0.3.0') $add .= ', `default_acl` AS def_acl';
393         if (getExtensionVersion('admins') >= '0.6.7') $add .= ', `la_mode`';
394         if (getExtensionVersion('admins') >= '0.7.2') $add .= ', `login_failures`, UNIX_TIMESTAMP(`last_failure`) AS last_failure';
395
396         // Return it
397         return $add;
398 }
399
400 // Sends out mail to all administrators
401 // IMPORTANT: Please use SEND_ADMIN_NOTIFCATION() for now!
402 function sendAdminsEmails ($subj, $template, $content, $UID) {
403         // Trim template name
404         $template = trim($template);
405
406         // Load email template
407         $message = loadEmailTemplate($template, $content, $UID);
408
409         // Check which admin shall receive this mail
410         $result = SQL_QUERY_ESC("SELECT `admin_id` FROM `{?_MYSQL_PREFIX?}_admins_mails` WHERE `mail_template`='%s' ORDER BY `admin_id` ASC",
411                 array($template), __FUNCTION__, __LINE__);
412         if (SQL_NUMROWS($result) == 0) {
413                 // Create new entry (to all admins)
414                 SQL_QUERY_ESC("INSERT INTO `{?_MYSQL_PREFIX?}_admins_mails` (`admin_id`, `mail_template`) VALUES (0, '%s')",
415                         array($template), __FUNCTION__, __LINE__);
416         } else {
417                 // Load admin IDs...
418                 // @TODO This can be, somehow, rewritten
419                 $adminIds = array();
420                 while ($content = SQL_FETCHARRAY($result)) {
421                         $adminIds[] = $content['admin_id'];
422                 } // END - while
423
424                 // Free memory
425                 SQL_FREERESULT($result);
426
427                 // Init result
428                 $result = false;
429
430                 // "implode" IDs and query string
431                 $adminId = implode(',', $adminIds);
432                 if ($adminId == '-1') {
433                         if (isExtensionActive('events')) {
434                                 // Add line to user events
435                                 EVENTS_ADD_LINE($subj, $message, $UID);
436                         } else {
437                                 // Log error for debug
438                                 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Extension 'events' missing: tpl=%s,subj=%s,UID=%s",
439                                         $template,
440                                         $subj,
441                                         $UID
442                                 ));
443                         }
444                 } elseif ($adminId == '0') {
445                         // Select all email adresses
446                         $result = SQL_QUERY("SELECT `email` FROM `{?_MYSQL_PREFIX?}_admins` ORDER BY `id` ASC",
447                                 __FUNCTION__, __LINE__);
448                 } else {
449                         // If Admin-ID is not "to-all" select
450                         $result = SQL_QUERY_ESC("SELECT `email` FROM `{?_MYSQL_PREFIX?}_admins` WHERE `id` IN (%s) ORDER BY `id` ASC",
451                                 array($adminId), __FUNCTION__, __LINE__);
452                 }
453         }
454
455         // Load email addresses and send away
456         while ($content = SQL_FETCHARRAY($result)) {
457                 sendEmail($content['email'], $subj, $message);
458         } // END - while
459
460         // Free memory
461         SQL_FREERESULT($result);
462 }
463
464 // [EOF]
465 ?>