More fixes, taskId shall be NULL instead '0' everywhere?
[mailer.git] / inc / modules / admin / overview-inc.php
1 <?php
2 /************************************************************************
3  * Mailer v0.2.1-FINAL                                Start: 07/13/2004 *
4  * ===================                          Last change: 08/02/2004 *
5  *                                                                      *
6  * -------------------------------------------------------------------- *
7  * File              : overview-inc.php                                 *
8  * -------------------------------------------------------------------- *
9  * Short description : Output standard task management                  *
10  * -------------------------------------------------------------------- *
11  * Kurzbeschreibung  : Standard-Aufgaben-Management ausgeben            *
12  * -------------------------------------------------------------------- *
13  * $Revision::                                                        $ *
14  * $Date::                                                            $ *
15  * $Tag:: 0.2.1-FINAL                                                 $ *
16  * $Author::                                                          $ *
17  * -------------------------------------------------------------------- *
18  * Copyright (c) 2003 - 2009 by Roland Haeder                           *
19  * Copyright (c) 2009 - 2012 by Mailer Developer Team                   *
20  * For more information visit: http://mxchange.org                      *
21  *                                                                      *
22  * This program is free software; you can redistribute it and/or modify *
23  * it under the terms of the GNU General Public License as published by *
24  * the Free Software Foundation; either version 2 of the License, or    *
25  * (at your option) any later version.                                  *
26  *                                                                      *
27  * This program is distributed in the hope that it will be useful,      *
28  * but WITHOUT ANY WARRANTY; without even the implied warranty of       *
29  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the        *
30  * GNU General Public License for more details.                         *
31  *                                                                      *
32  * You should have received a copy of the GNU General Public License    *
33  * along with this program; if not, write to the Free Software          *
34  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston,               *
35  * MA  02110-1301  USA                                                  *
36  ************************************************************************/
37
38 // Some security stuff...
39 if ((!defined('__SECURITY')) || (!isAdmin())) {
40         die();
41 } // END - if
42
43 // @TODO This function does also check for uncompleted tasks
44 function outputStandardOverview (&$result_tasks) {
45         // First check for solved and not assigned tasks and assign them to current admin
46         SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_task_system` SET `assigned_admin`=%s WHERE `assigned_admin` IS NULL AND status != 'NEW'",
47                 array(getCurrentAdminId()), __FILE__, __LINE__);
48
49         // We currently don't want to install an extension so let's find out if we need...
50         setExtensionMode('test');
51         $jobsDone = true;
52
53         // Open the extension directory
54         $extensionList = getArrayFromDirectory('inc/extensions/', 'ext-', false, false);
55         foreach ($extensionList as $file) {
56                 // Only file name is required... :(
57                 $file = basename($file);
58
59                 // Is this file an extension?
60                 if ((substr($file, 0, 4) == 'ext-') && (substr($file, -4) == '.php')) {
61                         // Possible newly installed extension found so we extract extension's name
62                         $ext_name = strtolower(substr($file, 4, -4)); // Keep always extension names on lower case!!!
63
64                         // Init variables
65                         $result = false;
66
67                         // Check if extension is installed or not
68                         $extInstalled = (isExtensionInstalled($ext_name) && (isExtensionActive($ext_name)));
69
70                         // Is the extension not yet installed?
71                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'ext_name=' . $ext_name . ',extInstalled=' . intval($extInstalled));
72                         if ($extInstalled === false) {
73                                 // We maybe want to install an extension so let's test-drive it...
74                                 if (loadExtension($ext_name, 'test', '0.0.0', true)) {
75                                         // Create a task for newly installed extension (we ignore the task id here)
76                                         createNewExtensionTask($ext_name);
77                                 } // END - if
78                         } else {
79                                 // Test-drive extension
80                                 loadExtension($ext_name, 'test');
81
82                                 // Get extension version
83                                 $ext_ver = getExtensionVersion($ext_name);
84                                 //* DEBUG: */ debugOutput($ext_name.'='.$ext_ver);
85
86                                 // Update extension if extension is installed and outdated
87                                 //* DEBUG: */ debugOutput('ext=' . $ext_name . ',ver=' . getThisExtensionVersion() . '/' . getExtensionVersion($ext_name));
88                                 if (getThisExtensionVersion() > $ext_ver) {
89                                         // Update the extension
90                                         updateExtension($ext_name, $ext_ver);
91                                 } // END - if
92
93                                 if (isset($GLOBALS['cache_array']['always_active'][$ext_name])) {
94                                         // Maybe we want to keept the current extension active?
95                                         if (($GLOBALS['cache_array']['always_active'][$ext_name] == 'Y') && (!isExtensionActive($ext_name))) {
96                                                 // Reactivate this extension!
97                                                 doActivateExtension($ext_name);
98                                         } // END - if
99                                 } // END - if
100                         }
101                 } // END - if
102         } // END - foreach
103
104         // At last - but not least - check for own and new unassigned tasks...
105         $result_tasks = SQL_QUERY_ESC("SELECT
106         `id`,
107         `assigned_admin`,
108         `userid`,
109         `task_type`,
110         `subject`,
111         `text`,
112         `task_created`
113 FROM
114         `{?_MYSQL_PREFIX?}_task_system`
115 WHERE
116         `assigned_admin`=%s OR ((`assigned_admin`=0 OR `assigned_admin` IS NULL) AND `status`='NEW')
117 ORDER BY
118         `userid` DESC,
119         `task_type` DESC,
120         `subject` ASC,
121         `task_created` DESC",
122                 array(getCurrentAdminId()), __FILE__, __LINE__);
123
124         if (!SQL_HASZERONUMS($result_tasks)) {
125                 // New jobs found
126                 $jobsDone = false;
127         } // END - if
128
129         // Free the result
130         SQL_FREERESULT($result);
131
132         // Return status
133         return $jobsDone;
134 }
135
136 // Outputs selected tasks
137 function outputSeletectedTasks ($postData, $result_tasks) {
138         if ((isset($postData['assign'])) && (count($postData['sel']) > 0)) {
139                 // Assign / do tasks
140                 $OUT = '';
141                 foreach ($postData['sel'] as $taskId => $sel) {
142                         $result_task = SQL_QUERY_ESC("SELECT
143         `id`,`userid`,`task_type`,`subject`,`text`,`task_created`,`status`,`assigned_admin`
144 FROM
145         `{?_MYSQL_PREFIX?}_task_system`
146 WHERE
147         `id`=%s AND (`assigned_admin`=%s OR ((`assigned_admin`=0 OR `assigned_admin` IS NULL) AND `status`='NEW'))
148 LIMIT 1",
149                                 array(
150                                         bigintval($taskId),
151                                         getCurrentAdminId()
152                                 ), __FILE__, __LINE__);
153
154                         // Task is found?
155                         if (SQL_NUMROWS($result_task) == 1) {
156                                 // Task is valid so load it's data
157                                 $taskData = SQL_FETCHARRAY($result_task);
158
159                                 if ($taskData['assigned_admin'] == '0') {
160                                         // Assgin current admin to unassgigned task
161                                         SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_task_system` SET `assigned_admin`=%s WHERE `id`=%s AND `assigned_admin` IS NULL LIMIT 1",
162                                                 array(
163                                                         getCurrentAdminId(),
164                                                         bigintval($taskData['id'])
165                                                 ), __FILE__, __LINE__);
166                                 } // END - if
167
168                                 $add = '';
169                                 // @TODO Rewrite this to a filter
170                                 if ($taskData['task_type'] == 'MEMBER_SUPPORT') {
171                                         $mode = substr($taskData['text'], 0, strpos($taskData['text'], ':'));
172                                         $taskData['text'] = substr($taskData['text'], strpos($taskData['text'], ':') + 1);
173                                         $add = '<li>{--ADMIN_TASK_SUPPORT_MODE--}: <strong>' . $mode . '</strong></li>';
174                                 } // END - if
175
176                                 // Is a userid assign?
177                                 if ($taskData['userid'] > 0) {
178                                         // Then load his data!
179                                         if (fetchUserData($taskData['userid'])) {
180                                                 // Fetch row
181                                                 $content = getUserDataArray();
182
183                                                 // Generate HTML list entry
184                                                 $add = '<li>{--ADMIN_MEMBER_USERID--}: <strong>' . generateUserProfileLink($taskData['userid'], 'user_data') . ' (<a href="' . generateEmailLink($content['email'], 'user_data') . '">{%pipe,translateGender=' . $content['gender'] . '%} ' . $content['surname'] . ' ' . $content['family'] . '</a>)</strong></li>';
185                                         } else {
186                                                 // Invalid userid, so log and zero it
187                                                 logDebugMessage(__FUNCTION__, __LINE__, 'fetchUserData() failed: userid=' . $taskData['userid'] . ' not found.');
188                                                 $taskData['userid'] = '0';
189                                         }
190                                 } // END - if
191
192                                 // Decode entities of the text
193                                 $taskData['text'] = decodeEntities($taskData['text']);
194
195                                 // Compile and insert text from task into table template
196                                 $taskData['text'] = loadTemplate('admin_extensions_text', true, $taskData['text']);
197
198                                 // Initialize variables (no title for SQL commands by default)
199                                 $ext_name = ''; $ext_ver = '';
200                                 $title = '{--ADMIN_TASK_NO_SQL_TITLE--}';
201
202                                 // Shall I list SQL commands assigned to an extension installation or update task?
203                                 if ((isVerboseSqlEnabled()) || (!isExtensionInstalled('sql_patches'))) {
204                                         // Extract extension name from subject
205                                         $ext_name = substr($taskData['subject'], 1, strpos($taskData['subject'], ':') - 1);
206
207                                         // Update task or extension task?
208                                         if (($taskData['task_type'] == 'EXTENSION') && (!isExtensionInstalled($ext_name))) {
209                                                 // Load SQL commands for registering in dry-run
210                                                 registerExtension($ext_name, $taskId, true);
211
212                                                 // Is this non-productive?
213                                                 if (isExtensionProductive() === false) {
214                                                         // Issue warning
215                                                         $taskData['text'] = displayMessage('{%message,ADMIN_EXTENSION_IS_NON_PRODUCTIVE=' . $ext_name . '%}', true) . $taskData['text'];
216                                                 } // END - if
217
218                                                 // Set current extension name
219                                                 setCurrentExtensionName($ext_name);
220
221                                                 // Add notes to text
222                                                 $taskData['text'] .= getExtensionNotes();
223
224                                                 // Set title
225                                                 $title = '{--ADMIN_SQLS_EXECUTED_ON_REGISTER--}';
226                                         } elseif ($taskData['task_type'] == 'EXTENSION_UPDATE') {
227                                                 // Prepare extension name and version
228                                                 $ext_name = substr($ext_name, 7);
229                                                 $ext_name = substr($ext_name, 0, strpos($ext_name, '-'));
230                                                 $test = '[UPDATE-' . $ext_name . '-';
231                                                 $ext_ver = substr($taskData['subject'], strlen($test));
232                                                 $ext_ver = substr($ext_ver, 0, strpos($ext_ver, ':'));
233
234                                                 // Load SQLs from file
235                                                 updateExtension($ext_name, $ext_ver, true);
236
237                                                 // Set current extension name
238                                                 setCurrentExtensionName($ext_name);
239
240                                                 // Add notes to text
241                                                 $taskData['text'] .= getExtensionNotes();
242
243                                                 // Set title
244                                                 $title = '{--ADMIN_SQLS_EXECUTED_ON_UPDATE--}';
245                                         } else {
246                                                 // Remove extension's name
247                                                 $ext_name = '';
248                                         }
249
250                                         // Add SQLs to a table
251                                         if ((!empty($ext_name)) && (isVerboseSqlEnabled())) {
252                                                 // Add verbose SQL table
253                                                 $taskData['text'] .= addExtensionVerboseSqlTable($title);
254                                         } // END - if
255                                 } elseif ((!empty($ext_name)) && (!empty($ext_ver))) {
256                                         // Run SQL commands in dry mode but only return the notes
257                                         updateExtension($ext_name, $ext_ver, true);
258
259                                         // Set current extension name
260                                         setCurrentExtensionName($ext_name);
261
262                                         // Get notes
263                                         $taskData['text'] .= getExtensionNotes();
264                                 } else {
265                                         // This should not normally happen!
266                                         reportBug(__FILE__, __LINE__, 'ext_name(' . $ext_name . ') or ext_ver(' . $ext_ver . ') is empty! isVerboseSqlEnabled=' . intval(isVerboseSqlEnabled()));
267                                 }
268
269                                 // Prepare array for the template
270                                 $content = array(
271                                         'subject'      => $taskData['subject'],
272                                         'add'          => $add,
273                                         'text'         => $taskData['text'],
274                                         'task_created' => generateDateTime($taskData['task_created'], '1'),
275                                         'ext_name'     => $ext_name
276                                 );
277
278                                 // Load template
279                                 $OUT .= loadTemplate('admin_overview_row', true, $content);
280
281                                 // Which task do we actually have here?
282                                 // @TODO Rewrite this to something with include files and/or filter
283                                 switch ($taskData['task_type']) {
284                                         case 'EXTENSION': // Install new extensions
285                                                 $ext_name = substr($taskData['subject'], 1, strpos($taskData['subject'], ':') - 1);
286                                                 if (!isExtensionInstalled($ext_name)) {
287                                                         // New (not yet installed) extension found
288                                                         $OUT .= loadTemplate('admin_extension_reg_form', true, array(
289                                                                 'id'       => bigintval($taskId),
290                                                                 'ext_name' => $ext_name
291                                                         ));
292                                                 } else {
293                                                         // Extension is already installed
294                                                         $OUT .= '<div class="notice">{--ADMIN_EXTENSION_ALREADY_REGISTERED--}</div>';
295
296                                                         // Close task but not already closed, solved, deleted or update tasks
297                                                         if ((!in_array($taskData['status'], array('CLOSED', 'DELETED', 'SOLVED'))) && ($taskData['task_type'] != 'EXTENSION_UPDATE')) {
298                                                                 // Solve the task
299                                                                 runFilterChain('solve_task', $taskData['id']);
300                                                         } // END - if
301                                                 }
302                                                 break;
303
304                                         case 'EXTENSION_UPDATE': // Extension update
305                                                 // Extension updates are installed automatically
306                                                 $OUT .= '<div class="notice medium">{--ADMIN_EXTENSION_UPDATED--}</div>';
307
308                                                 // Close task if not closed or deleted
309                                                 if (!in_array($taskData['status'], array('CLOSED', 'DELETED'))) {
310                                                         // Solve the task
311                                                         runFilterChain('solve_task', $taskData['id']);
312                                                 } // END - if
313                                                 break;
314
315                                         case 'MEMBER_SUPPORT': // Assign on member's support request
316                                                 // @TODO This may also be rewritten to include files
317                                                 switch ($mode) {
318                                                         default: // @TODO Unknown support mode
319                                                         logDebugMessage(__FILE__, __LINE__, sprintf("Unknown support mode %s detected. This part is under construction.", $mode));
320                                                         $OUT .= '<div class="notice medium">{%message,ADMIN_UNKNOWN_SUPPORT_MODE=' . $mode . '%}</div>';
321                                                         break;
322                                                 } // END - switch
323                                                 break;
324
325                                         case 'PAYOUT_REQUEST': // Payout requests
326                                                 if (isExtensionActive('payout')) {
327                                                         // Extension is installed so let him send a notification to the user
328                                                         $result_pay = SQL_QUERY_ESC("SELECT `id` FROM `{?_MYSQL_PREFIX?}_user_payouts` WHERE `userid`=%s AND `payout_timestamp`=%s LIMIT 1",
329                                                                 array(bigintval($taskData['userid']), bigintval($taskData['task_created'])), __FILE__, __LINE__);
330                                                         list($pid) = SQL_FETCHROW($result_pay);
331                                                         SQL_FREERESULT($result_pay);
332
333                                                         if ((!empty($pid)) && ($pid > 0)) {
334                                                                 // Payout id can be obtained
335                                                                 $content = array(
336                                                                         'pid' => $pid,
337                                                                         'tid' => $taskData['id'],
338                                                                 );
339
340                                                                 // Load template
341                                                                 $OUT .= loadTemplate('admin_payout_overview_form', true, $content);
342                                                         } else {
343                                                                 // Problem obtaining payout id
344                                                                 $OUT .= '<div class="notice medium">{--ADMIN_PAYOUT_OBTAIN_ID_FAILED--}</div>';
345                                                         }
346                                                 } else {
347                                                         // Extension is not installed
348                                                         $OUT .= '<div class="notice medium">{--ADMIN_PAYOUT_NOT_INSTALLED--}</div>';
349                                                 }
350                                                 break;
351
352                                         case 'WERNIS_REQUEST': // Wernis requests
353                                                 if (isExtensionActive('wernis')) {
354                                                         // Extension is installed so let him send a notification to the user
355                                                         $result_pay = SQL_QUERY_ESC("SELECT `id` FROM `{?_MYSQL_PREFIX?}_user_wernis` WHERE `userid`=%s AND wernis_timestamp=%s LIMIT 1",
356                                                                 array(bigintval($taskData['userid']), bigintval($taskData['task_created'])), __FILE__, __LINE__);
357                                                         list($pid) = SQL_FETCHROW($result_pay);
358                                                         SQL_FREERESULT($result_pay);
359
360                                                         if ((!empty($pid)) && ($pid > 0)) {
361                                                                 // Payout id can be obtained
362                                                                 $content = array(
363                                                                         'pid' => $pid,
364                                                                         'tid' => $taskData['id'],
365                                                                 );
366                                                                 $OUT .= loadTemplate('admin_wernis_overview_form', true, $content);
367                                                         } else {
368                                                                 // Problem obtaining wernis id
369                                                                 $OUT .= '<div class="notice medium">{--WERNIS_OBTAIN_ID_FAILED--}</div>';
370                                                         }
371                                                 } else {
372                                                         // Extension is not installed
373                                                         $OUT .= '<div class="notice medium">{--ADMIN_WERNIS_NOT_INSTALLED--}</div>';
374                                                 }
375                                                 break;
376
377                                         case 'HOLIDAY_REQUEST': // Holiday requests
378                                                 $OUT .= loadTemplate('admin_task_holiday', true, $taskData['userid']);
379                                                 break;
380
381                                         case 'MEMBER_ORDER': // Member mail orders
382                                                 $OUT .= loadTemplate('admin_task_order', true, $taskId);
383                                                 break;
384
385                                         default: // Unknown task type
386                                                 logDebugMessage(__FILE__, __LINE__, sprintf("Unknown task type %s detected.", $taskData['task_type']));
387                                                 $OUT .= '<div class="notice medium">' . sprintf(getMessage('ADMIN_UNKNOWN_TASK_TYPE'), $taskData['task_type'], $taskId) . '</div>';
388                                                 break;
389                                 }
390                                 $OUT .= '
391   </td>
392 </tr>';
393                         } // END - if
394
395                         // Free result
396                         SQL_FREERESULT($result_task);
397                 } // END - foreach
398
399                 // Load final template
400                 loadTemplate('admin_overview_list', false, $OUT);
401         } else {
402                 if ((isset($postData['sel'])) && ((count($postData['sel']) > 0) || ($postData['sel'][0] == 1))) {
403                         // Only unassign / delete tasks when there are selected tasks posted
404                         if (!empty($postData['unassign'])) {
405                                 // Unassign from tasks
406                                 foreach ($postData['sel'] as $taskId => $sel) {
407                                         SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_task_system` SET `assigned_admin`=NULL WHERE `id`=%s AND `assigned_admin`=%s LIMIT 1",
408                                                 array(bigintval($taskId), getCurrentAdminId()), __FILE__, __LINE__);
409                                 } // END - foreach
410                         } elseif (!empty($postData['delete'])) {
411                                 // Delete tasks
412                                 foreach ($postData['sel'] as $taskId => $sel) {
413                                         SQL_QUERY_ESC("DELETE LOW_PRIORITY FROM `{?_MYSQL_PREFIX?}_task_system` WHERE `id`=%s AND `assigned_admin` IN (%s,0,NULL) LIMIT 1",
414                                                 array(bigintval($taskId), getCurrentAdminId()), __FILE__, __LINE__);
415                                 } // END - foreach
416                         } else {
417                                 // Unknown action
418                                 reportBug(__FILE__, __LINE__, sprintf("Unknown task action performed. data=<pre>%s</pre>", print_r($postData, true)));
419                         }
420
421                         // Update query
422                         $result_tasks = SQL_QUERY_ESC("SELECT `id`,`assigned_admin`,`userid`,`task_type`,`subject`,`text`,`task_created` FROM `{?_MYSQL_PREFIX?}_task_system` WHERE `assigned_admin`=%s OR ((`assigned_admin`=0 OR `assigned_admin` IS NULL) AND `status`='NEW') ORDER BY `task_created` DESC",
423                                 array(getCurrentAdminId()), __FILE__, __LINE__);
424                 } // END - if
425
426                 // There are uncompleted jobs!
427                 $OUT = '';
428                 while ($content = SQL_FETCHARRAY($result_tasks)) {
429                         // Init infos
430                         $content['infos'] = '';
431
432                         // Generate infos
433                         // @TODO Try to move this in includes
434                         switch ($content['task_type']) {
435                                 case 'EXTENSION':
436                                 case 'EXTENSION_UPDATE':
437                                         $content['infos'] = substr($content['subject'], 1, strpos($content['subject'], ':') - 1);
438                                         break;
439                         } // END - switch
440
441                         if (isValidUserId($content['userid'])) {
442                                 // Member found otherwise it's a system task
443                                 $content['userid'] = generateUserProfileLink($content['userid']);
444                         } else {
445                                 $content['userid'] = '{--ADMIN_IS_SYSTEM_TASK--}';
446                         }
447
448                         // Add/translate some content
449                         $content['task_created'] = generateDateTime($content['task_created'], 2);
450
451                         // Do we have extension task?
452                         if (isExtensionTask($content)) {
453                                 // Load extension row template
454                                 $OUT .= loadTemplate('admin_overview_list_ext_rows', true, $content);
455                         } else {
456                                 // Load default row template
457                                 $OUT .= loadTemplate('admin_overview_list_rows', true, $content);
458                         }
459                 } // END - while
460
461                 // Free memory
462                 SQL_FREERESULT($result_tasks);
463
464                 // Load footer template
465                 loadTemplate('admin_overview_table', false, $OUT);
466         }
467 }
468
469 // [EOF]
470 ?>