New functions introduced, several rewrites:
[mailer.git] / inc / libs / admins_functions.php
1 <?php
2 /************************************************************************
3  * Mailer v0.2.1-FINAL                                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 ((isExtensionInstalledAndNewer('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, $element = '') {
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 ((!empty($element)) && (isset($postData[$element]))) {
166                         // Save this setting
167                         SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_admins` SET `%s`='%s' WHERE `id`=%s LIMIT 1",
168                                 array($element, $postData[$element][$id], $id), __FILE__, __LINE__);
169
170                         // Admin account saved
171                         $message = getMessage('ADMIN_ACCOUNT_SAVED');
172                 } elseif ($postData['pass1'][$id] == $postData['pass2'][$id]) {
173                         // Save only when both passwords are the same (also when they are empty)
174                         $add = ''; $cache_update = 1;
175
176                         // Generate hash
177                         $hash = generateHash($postData['pass1'][$id]);
178
179                         // Save password when set
180                         if (!empty($postData['pass1'][$id])) $add = sprintf(", `password`='%s'", SQL_ESCAPE($hash));
181
182                         // Get admin's id
183                         $adminId = getCurrentAdminId();
184                         $salt = substr(getAdminHash($adminId), 0, -40);
185
186                         // Rewrite cookie when it's own account
187                         if ($adminId == $id) {
188                                 // Set timeout cookie
189                                 setSession('admin_last', time());
190
191                                 if ($login != getSession('admin_login')) {
192                                         // Update login cookie
193                                         setSession('admin_login', $login);
194
195                                         // Update password cookie as well?
196                                         if (!empty($add)) setSession('admin_md5', $hash);
197                                 } elseif (generateHash($postData['pass1'][$id], $salt) != getSession('admin_md5')) {
198                                         // Update password cookie
199                                         setSession('admin_md5', $hash);
200                                 }
201                         } // END - if
202
203                         // Get default ACL from admin to check if we can allow him to change the default ACL
204                         $default = getAdminDefaultAcl(getCurrentAdminId());
205
206                         // Update admin account
207                         if ($default == 'allow') {
208                                 // Allow changing default ACL
209                                 SQL_QUERY_ESC("UPDATE
210         `{?_MYSQL_PREFIX?}_admins`
211 SET
212         `login`='%s'".$add.",
213         `email`='%s',
214         `default_acl`='%s',
215         `la_mode`='%s'
216 WHERE
217         `id`=%s
218 LIMIT 1",
219                                 array(
220                                         $login,
221                                         $postData['email'][$id],
222                                         $postData['mode'][$id],
223                                         $postData['la_mode'][$id],
224                                         $id
225                                 ), __FUNCTION__, __LINE__);
226                         } else {
227                                 // Do not allow it here
228                                 SQL_QUERY_ESC("UPDATE
229         `{?_MYSQL_PREFIX?}_admins`
230 SET
231         `login`='%s'".$add.",
232         `email`='%s',
233         `la_mode`='%s'
234 WHERE
235         `id`=%s
236 LIMIT 1",
237                                 array(
238                                         $login,
239                                         $postData['email'][$id],
240                                         $postData['la_mode'][$id],
241                                         $id
242                                 ), __FUNCTION__, __LINE__);
243                         }
244
245                         // Admin account saved
246                         $message = getMessage('ADMIN_ACCOUNT_SAVED');
247                 } else {
248                         // Passwords did not match
249                         $message = getMessage('ADMINS_ERROR_PASS_MISMATCH');
250                 }
251         } // END - foreach
252
253         // Display message
254         if (!empty($message)) {
255                 loadTemplate('admin_settings_saved', false, $message);
256         } // END - if
257
258         // Remove cache file
259         runFilterChain('post_admin_edited', postRequestArray());
260 }
261
262 // Make admin accounts editable
263 function adminsEditAdminAccount ($postData) {
264         // "Resolve" current's admin access mode
265         $currMode = getAdminDefaultAcl(getCurrentAdminId());
266
267         // Begin the edit loop
268         $OUT = ''; $SW = 2;
269         foreach ($postData['sel'] as $id => $selected) {
270                 // Secure id number
271                 $id = bigintval($id);
272
273                 // Get the admin's data
274                 $result = SQL_QUERY_ESC("SELECT `login`, `email`, `default_acl` AS mode, `la_mode` FROM `{?_MYSQL_PREFIX?}_admins` WHERE `id`=%s LIMIT 1",
275                         array($id), __FUNCTION__, __LINE__);
276                 if ((SQL_NUMROWS($result) == 1) && ($selected == 1)) {
277                         // Entry found
278                         $content = SQL_FETCHARRAY($result);
279                         SQL_FREERESULT($result);
280
281                         // Prepare some more data for the template
282                         $content['sw'] = $SW;
283                         $content['id'] = $id;
284
285                         // Shall we allow changing default ACL?
286                         if ($currMode == 'allow') {
287                                 // Allow chaning it
288                                 $content['mode']    = generateOptionList('/ARRAY/', array('allow', 'deny'), array(getMessage('ADMINS_ALLOW_MODE'), getMessage('ADMINS_DENY_MODE')), $content['mode']);
289                         } else {
290                                 // Don't allow it
291                                 $content['mode'] = '&nbsp;';
292                         }
293                         $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']);
294
295                         // Load row template and switch color
296                         $OUT .= loadTemplate('admin_edit_admins_row', true, $content);
297                         $SW = 3 - $SW;
298                 }
299         }
300
301         // Load template
302         loadTemplate('admin_edit_admins', false, $OUT);
303 }
304
305 // Delete given admin accounts
306 function adminsDeleteAdminAccount ($postData) {
307         // Check if this account is the last one which cannot be deleted...
308         $result_main = SQL_QUERY("SELECT `id` FROM `{?_MYSQL_PREFIX?}_admins`", __FUNCTION__, __LINE__);
309         $accounts = SQL_NUMROWS($result_main);
310         SQL_FREERESULT($result_main);
311         if ($accounts > 1) {
312                 // Delete accounts
313                 $OUT = ''; $SW = 2;
314                 foreach ($postData['sel'] as $id => $selected) {
315                         // Secure id number
316                         $id = bigintval($id);
317
318                         // Get the admin's data
319                         $result = SQL_QUERY_ESC("SELECT login, email, default_acl AS mode, la_mode FROM `{?_MYSQL_PREFIX?}_admins` WHERE `id`=%s LIMIT 1",
320                                 array($id), __FUNCTION__, __LINE__);
321                         if (SQL_NUMROWS($result) == 1) {
322                                 // Entry found
323                                 $content = SQL_FETCHARRAY($result);
324                                 SQL_FREERESULT($result);
325                                 $content['mode'] = getMessage('ADMINS_'.strtoupper($content['mode']).'_MODE');
326                                 $content['la_mode'] = getMessage('ADMINS_'.strtoupper($content['la_mode']).'_LA_SETTING');
327
328                                 // Prepare some more data
329                                 $content['sw'] = $SW;
330                                 $content['id'] = $id;
331
332                                 // Load row template and switch color
333                                 $OUT .= loadTemplate('admin_del_admins_row', true, $content);
334                                 $SW = 3 - $SW;
335                         }
336                 }
337
338                 // Load template
339                 loadTemplate('admin_del_admins', false, $OUT);
340         } else {
341                 // Cannot delete last account!
342                 loadTemplate('admin_settings_saved', false, getMessage('ADMIN_ADMINS_CANNOT_DELETE_LAST'));
343         }
344 }
345
346 // Remove the given accounts
347 function adminsRemoveAdminAccount ($postData) {
348         // Begin removal
349         $cache_update = '0';
350         foreach ($postData['sel'] as $id => $del) {
351                 // Secure id number
352                 $id = bigintval($id);
353
354                 // Delete only when it's not your own account!
355                 if (($del == 1) && (getCurrentAdminId() != $id)) {
356                         // Rewrite his tasks to all admins
357                         SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_task_system` SET `assigned_admin`=0 WHERE `assigned_admin`=%s",
358                                 array($id), __FUNCTION__, __LINE__);
359
360                         // Remove account
361                         SQL_QUERY_ESC("DELETE LOW_PRIORITY FROM `{?_MYSQL_PREFIX?}_admins` WHERE `id`=%s LIMIT 1",
362                                 array($id), __FUNCTION__, __LINE__);
363                 }
364         }
365
366         // Remove cache if cache system is activated
367         runFilterChain('post_admin_deleted', postRequestArray());
368 }
369
370 // List all admin accounts
371 function adminsListAdminAccounts() {
372         // Select all admin accounts
373         $result = SQL_QUERY("SELECT `id`, `login`, `email`, `default_acl` AS mode, `la_mode` FROM `{?_MYSQL_PREFIX?}_admins` ORDER BY `login` ASC", __FUNCTION__, __LINE__);
374         $OUT = ''; $SW = 2;
375         while ($content = SQL_FETCHARRAY($result)) {
376                 // Compile some variables
377                 $content['mode'] = getMessage('ADMINS_'.strtoupper($content['mode']).'_MODE');
378                 $content['la_mode'] = getMessage('ADMINS_'.strtoupper($content['la_mode']).'_LA_SETTING');
379
380                 // Prepare some more data
381                 $content['sw']         = $SW;
382                 $content['email_link'] = generateEmailLink($content['id'], 'admins');
383
384                 // Load row template and switch color
385                 $OUT .= loadTemplate('admin_list_admins_row', true, $content);
386                 $SW = 3 - $SW;
387         }
388
389         // Free memory
390         SQL_FREERESULT($result);
391
392         // Load template
393         loadTemplate('admin_list_admins', false, $OUT);
394 }
395
396 // Filter for adding extra data to the query
397 function FILTER_ADD_EXTRA_SQL_DATA ($add = '') {
398         // Is the admins extension updated? (should be!)
399         if (getExtensionVersion('admins') >= '0.3.0') $add .= ', `default_acl` AS def_acl';
400         if (getExtensionVersion('admins') >= '0.6.7') $add .= ', `la_mode`';
401         if (getExtensionVersion('admins') >= '0.7.2') $add .= ', `login_failures`, UNIX_TIMESTAMP(`last_failure`) AS last_failure';
402         if (getExtensionVersion('admins') >= '0.7.3') $add .= ', `expert_settings`, `expert_warning`';
403
404         // Return it
405         return $add;
406 }
407
408 // Sends out mail to all administrators
409 // IMPORTANT: Please use SEND_ADMIN_NOTIFCATION() for now!
410 function sendAdminsEmails ($subj, $template, $content, $userid) {
411         // Trim template name
412         $template = trim($template);
413
414         // Load email template
415         $message = loadEmailTemplate($template, $content, $userid);
416
417         // Check which admin shall receive this mail
418         $result = SQL_QUERY_ESC("SELECT `admin_id` FROM `{?_MYSQL_PREFIX?}_admins_mails` WHERE `mail_template`='%s' ORDER BY `admin_id` ASC",
419                 array($template), __FUNCTION__, __LINE__);
420         if (SQL_NUMROWS($result) == '0') {
421                 // Create new entry (to all admins)
422                 SQL_QUERY_ESC("INSERT INTO `{?_MYSQL_PREFIX?}_admins_mails` (`admin_id`, `mail_template`) VALUES (0, '%s')",
423                         array($template), __FUNCTION__, __LINE__);
424         } else {
425                 // Load admin ids...
426                 // @TODO This can be, somehow, rewritten
427                 $adminIds = array();
428                 while ($content = SQL_FETCHARRAY($result)) {
429                         $adminIds[] = $content['admin_id'];
430                 } // END - while
431
432                 // Free memory
433                 SQL_FREERESULT($result);
434
435                 // Init result
436                 $result = false;
437
438                 // "implode" ids and query string
439                 $adminId = implode(',', $adminIds);
440                 if ($adminId == '-1') {
441                         if (isExtensionActive('events')) {
442                                 // Add line to user events
443                                 EVENTS_ADD_LINE($subj, $message, $userid);
444                         } else {
445                                 // Log error for debug
446                                 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Extension 'events' missing: tpl=%s,subj=%s,userid=%s",
447                                         $template,
448                                         $subj,
449                                         $userid
450                                 ));
451                         }
452                 } elseif ($adminId == '0') {
453                         // Select all email adresses
454                         $result = SQL_QUERY("SELECT `email` FROM `{?_MYSQL_PREFIX?}_admins` ORDER BY `id` ASC",
455                                 __FUNCTION__, __LINE__);
456                 } else {
457                         // If Admin-Id is not "to-all" select
458                         $result = SQL_QUERY_ESC("SELECT `email` FROM `{?_MYSQL_PREFIX?}_admins` WHERE `id` IN (%s) ORDER BY `id` ASC",
459                                 array($adminId), __FUNCTION__, __LINE__);
460                 }
461         }
462
463         // Load email addresses and send away
464         while ($content = SQL_FETCHARRAY($result)) {
465                 sendEmail($content['email'], $subj, $message);
466         } // END - while
467
468         // Free memory
469         SQL_FREERESULT($result);
470 }
471
472 // "Getter" for current admin's expert settings
473 function getAminsExpertSettings () {
474         // Default is has not the right
475         $data['expert_settings'] = 'N';
476
477         // Get current admin login
478         $admin = getAdminLogin(getCurrentAdminId());
479
480         // Lookup settings in cache
481         if (isset($GLOBALS['cache_array']['admin']['expert_settings'][$admin])) {
482                 // Use cache
483                 $data['expert_settings'] = $GLOBALS['cache_array']['admin']['expert_settings'][$admin];
484
485                 // Update cache hits
486                 incrementStatsEntry('cache_hits');
487         } elseif (!isExtensionInstalled('cache')) {
488                 // Load from database
489                 $result = SQL_QUERY_ESC("SELECT `expert_settings` FROM `{?_MYSQL_PREFIX?}_admins` WHERE `login`='%s' LIMIT 1",
490                         array($admin), __FUNCTION__, __LINE__);
491
492                 // Entry found?
493                 if (SQL_NUMROWS($result) == 1) {
494                         // Fetch data
495                         $data = SQL_FETCHARRAY($result);
496
497                         // Set cache
498                         $GLOBALS['cache_array']['admin']['expert_settings'][$admin] = $data['expert_settings'];
499                 } // END - if
500
501                 // Free memory
502                 SQL_FREERESULT($result);
503         }
504
505         // Return the result
506         return $data['expert_settings'];
507 }
508
509 // "Getter" for current admin's expert warning (if he wants to see them or not
510 function getAminsExpertWarning () {
511         // Default is has not the right
512         $data['expert_warning'] = 'N';
513
514         // Get current admin login
515         $admin = getAdminLogin(getCurrentAdminId());
516
517         // Lookup warning in cache
518         if (isset($GLOBALS['cache_array']['admin']['expert_warning'][$admin])) {
519                 // Use cache
520                 $data['expert_warning'] = $GLOBALS['cache_array']['admin']['expert_warning'][$admin];
521
522                 // Update cache hits
523                 incrementStatsEntry('cache_hits');
524         } elseif (!isExtensionInstalled('cache')) {
525                 // Load from database
526                 $result = SQL_QUERY_ESC("SELECT `expert_warning` FROM `{?_MYSQL_PREFIX?}_admins` WHERE `login`='%s' LIMIT 1",
527                         array($admin), __FUNCTION__, __LINE__);
528
529                 // Entry found?
530                 if (SQL_NUMROWS($result) == 1) {
531                         // Fetch data
532                         $data = SQL_FETCHARRAY($result);
533
534                         // Set cache
535                         $GLOBALS['cache_array']['admin']['expert_warning'][$admin] = $data['expert_warning'];
536                 } // END - if
537
538                 // Free memory
539                 SQL_FREERESULT($result);
540         }
541
542         // Return the result
543         return $data['expert_warning'];
544 }
545
546 // [EOF]
547 ?>