153615990ac84d83e2a6b6184ca11f332ba13952
[iserv-mod-error-reporter.git] / inc / class_erErrorReportManager.inc
1 <?php
2 /**
3 * @file class_erErrorReportManager.inc -- management of multiple error reports
4 * @author Roland Hieber (roland.hieber@wilhelm-gym.net)
5 * @date 18.10.2007
6 *
7 * Copyright © 2007 Roland Hieber
8 *
9 * Permission is hereby granted, free of charge, to any person obtaining
10 * copy of this software and associated documentation files (the "Software"),
11 * to deal in the Software without restriction, including without limitation
12 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
13 * and/or sell copies of the Software, and to permit persons to whom the
14 * Software is furnished to do so, subject to the following conditions:
15 *
16 * The above copyright notice and this permission notice shall be included in
17 * all copies or substantial portions of the Software.
18 *
19 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
20 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
21 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
22 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
23 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
24 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
25 * THE SOFTWARE.
26 */
27
28 require_once("mod_error-reporter/class_erErrorReport.inc");
29 require_once("mod_error-reporter/class_erConfig.inc");
30 require_once("mod_error-reporter/functions.inc");
31 require_once("db.inc");
32 require_once("user.inc");
33
34 db_query("SET DATESTYLE = ISO ");
35
36 /**
37 * @page errorreportmanager_constants erErrorReportManager Constants
38 * @section errorreportmanager_sorting Sorting constants
39 * - @b ER_ERM_SORT_UID: Array is sorted by unique ID
40 * - @b ER_ERM_SORT_DATE: Array is sorted by the creation date
41 * - @b ER_ERM_SORT_OWNER: Array is sorted by owner of the error report
42 * - @b ER_ERM_SORT_MACHINE: Array is sorted by the machine to which the report refers
43 * - @b ER_ERM_SORT_TEXT: Array is sorted by text / notes
44 * - @b ER_ERM_SORT_COMMENT: Array is sorted by comment
45 * - @b ER_ERM_SORT_COMMENTOWNER: Array is sorted by the account name of the person who wrote the comment
46 * - @b ER_ERM_SORT_VISIBILITY: Array is sorted by hide status
47 * @section errorreportmanager_sorting_dir Sorting direction constants
48 * - @b ER_ERM_SORT_ASC: Array is sorted in ascending order
49 * - @b ER_ERM_SORT_DESC: Array is sorted in descending order
50 */
51 define("ER_ERM_SORT_UID", 0); /*< sort by unique ID */
52 define("ER_ERM_SORT_DATE", 1); /*< sort by date */
53 define("ER_ERM_SORT_OWNER", 2); /*< sort by owner */
54 define("ER_ERM_SORT_MACHINE", 3); /*< sort by machine to which the report refers */
55 define("ER_ERM_SORT_TEXT", 4); /*< sort by text*/
56 define("ER_ERM_SORT_COMMENT", 5); /*< sort by comment */
57 define("ER_ERM_SORT_COMMENTOWNER", 6); /*< sort by account name of the person who wrote the comment */
58 define("ER_ERM_SORT_VISIBILITY", 6); /*< sort by visibility */
59
60 define("ER_ERM_SORT_ASC", 0); /*< sort ascending */
61 define("ER_ERM_SORT_DESC", 1); /*< sort descending */
62
63 /**
64 * Management of error reports
65 *
66 * This class allows a comprehensive management of error reports.
67 *
68 * @par Error reports management
69 * To add an error reports, simply create an instance of this class and call writeErrorReport()
70 * with a erErrorReport object as the only parameter. If the $nUid member of the erErrorReport
71 * object is <tt>null</tt>, writeErrorReport() will use the next ID which is not used in the
72 * table.
73 *
74 * @par
75 * An error report that has been written to the database can be changed using
76 * writeErrorReport(), setting the $nUid member of the erErrorReport parameter to the UID of the
77 * error report to be changed.
78 *
79 * @par
80 * To change the visibility of an error report to @e hidden, call setErrorReportDoneFlag() with
81 * the UID of the error report and set the second parameter to <tt>false</tt>.
82 *
83 * @par
84 * To delete an error report from the database, call deleteErrorReport() with the UID of the
85 * error report you want to delete.
86 *
87 * @par
88 * Error reports can be retrieved by their UID (getErrorReportByID()), by creation date
89 * (getErrorReportsByDate()), by owner (getErrorReportsByOwner()), by machine to which the
90 * report refers (getErrorReportsByMachine()) and by the person who wrote the comment
91 * (getErrorReportsByCommentOwner()). All error reports in the database can be retrieved using
92 * getErrorReports(). All of these functions return a object of type erErrorReport or an array
93 * of erErrorReport objects.
94 *
95 * @par Example
96 * The following example creates a new error report “This doesn’t work”, written by the user
97 * “testuser” on February 5, 2007, which refers to the machine “Client-26” and is not visible for
98 * non-admin users. Then it adds a nice comment, makes the error report visible and writes it to
99 * the database.
100 * @code
101 * <?php
102 * require_once("class_erErrorReportManager.inc");
103 * $obj = new erErrorReportManager;
104 * $em = new erErrorReport(strtotime("2007-02-05"), "testuser", "Client-26",
105 * "This doesn’t work", false);
106 * $em->setComment("We know that already", "admin");
107 *
108 * $nNewID = $obj->writeErrorReport($em); // $em->nUid is null, so writeErrorReport()
109 * // calculates the UID by itself
110 * ?>
111 * @endcode
112 */
113
114 class erErrorReportManager {
115
116
117 /**
118 * (object of type erConfig) pointer to the configuration class
119 */
120 protected $objcfg;
121
122 /**
123 * Constructor
124 * @param $objcfg (object of type erConfig) Pointer to the configuration class for retrieving the
125 * configuration data
126 * @return erErrorReportManager
127 */
128 public function __construct(&$objcfg) {
129 $this->objcfg = &$objcfg;
130 }
131
132 //////////////////////////////////////////// QUERYING ///////////////////////////////////////////
133
134 /**
135 * @name Quering
136 * @{ */
137
138 /**
139 * Get all error reports in the database.
140 * If this function fails, it returns <tt>null</tt>. Call getLastError() to get more information.
141 * @param $arcSort (array of constants) Defines the sorting of the returned array.
142 * See the documentation of the $arcSort parameter of buildOrderByClause() for more information.
143 * @return array of objects of type erErrorReport
144 */
145 public function getErrorReports($arcSort = array(ER_ERM_SORT_UID => ER_ERM_SORT_ASC)) {
146 return $this->readFromSQL("", $arcSort);
147 }
148
149 /**
150 * Get an error report by its unique ID in database.
151 * If this function fails, it returns <tt>null</tt>.
152 * @param $nID (int) ID of the error report
153 * @return erErrorReport
154 */
155 public function getErrorReportByID($nID) {
156 $arReturn = $this->readFromSQL("er_uid = ".qdb(intval($nID)));
157 if(is_array($arReturn) and count($arReturn) > 0) {
158 return $arReturn[0]; // return as scalar
159 } else {
160 return null;
161 }
162 }
163
164 /**
165 * Get all error reports which have been created on the specified date.
166 * If this function fails, it returns <tt>null</tt>. Call getLastError() to get more information.
167 * @param $tsDate (timestamp) Date
168 * @param $arcSort (array of constants) Defines the sorting of the returned array.
169 * See the documentation of the $arcSort parameter of buildOrderByClause() for more information.
170 * @return array of objects of type erErrorReport
171 */
172 public function getErrorReportsByDate($tsDate, $arcSort = array(ER_ERM_SORT_UID => ER_ERM_SORT_ASC)) {
173 return $this->readFromSQL("er_date = ".qdb(date("Y\-m\-d", $tsDate)), $arcSort);
174 }
175
176 /**
177 * Get all error reports which have been created by the specified user.
178 * If this function fails, it returns <tt>null</tt>. Call getLastError() to get more information.
179 * @param $strAct (string) Account name
180 * @param $arcSort (array of constants) Defines the sorting of the returned array.
181 * See the documentation of the $arcSort parameter of buildOrderByClause() for more information.
182 * @return array of objects of type erErrorReport
183 */
184 public function getErrorReportsByOwner($strAct, $arcSort = array(ER_ERM_SORT_UID => ER_ERM_SORT_ASC)) {
185 return $this->readFromSQL("er_act = ".qdb($strAct), $arcSort);
186 }
187
188 /**
189 * Get all error reports which are related to a specified machine.
190 * If this function fails, it returns <tt>null</tt>. Call getLastError() to get more information.
191 * @param $strMachine (string) Machine name
192 * @param $arcSort (array of constants) Defines the sorting of the returned array.
193 * See the documentation of the $arcSort parameter of buildOrderByClause() for more information.
194 * @return array of objects of type erErrorReport
195 */
196 public function getErrorReportsByMachine($strMachine,
197 $arcSort = array(ER_ERM_SORT_UID => ER_ERM_SORT_ASC)) {
198 return $this->readFromSQL("er_machine = ".qdb($strMachine), $arcSort);
199 }
200
201 /**
202 * Get all error reports which have been commented by the specified user.
203 * If this function fails, it returns <tt>null</tt>. Call getLastError() to get more information.
204 * @param $strAct (string) Account name
205 * @param $arcSort (array of constants) Defines the sorting of the returned array.
206 * See the documentation of the $arcSort parameter of buildOrderByClause() for more information.
207 * @return array of objects of type erErrorReport
208 */
209 public function getErrorReportsByCommentOwner($strAct,
210 $arcSort = array(ER_ERM_SORT_UID => ER_ERM_SORT_ASC)) {
211 return $this->readFromSQL("er_commentact = ".qdb($strAct), $arcSort);
212 }
213
214 /*@}*/
215
216 /**
217 * Get datasets from the SQL tables.
218 * This function should not be called directly. Use the getBy* functions instead.
219 * If this function fails, it returns <tt>null</tt>. Call getLastError() to get more information.
220 * @internal
221 * @param $strWhere (string) Parameters for the SQL WHERE clause
222 * @param $arcSort (array of constants) Defines the sorting of the returned array.
223 * See the documentation of the $arcSort parameter of buildOrderByClause() for more information.
224 * @return array of objects of type erErrorReport
225 */
226 protected function readFromSQL($strWhere = "", $arcSort = array(ER_ERM_SORT_UID => ER_ERM_SORT_ASC)) {
227 $arReturn = array();
228
229 // only allow visible reports for non-admins, but all reports for admins and owners
230 if($this->objcfg->userIsAdmin()) {
231 $strWhereClause = (trim($strWhere) == "") ? "" : "WHERE $strWhere";
232 } else {
233 $strWhereClause = "WHERE ".((trim($strWhere) == "") ? "" : "$strWhere AND ").
234 sprintf("((er_act = '%s') or (er_hidden IS NULL OR NOT er_hidden))", $_SESSION["act"]);
235 }
236
237 $strSortClause = $this->buildOrderByClause($arcSort);
238
239 // fetch the error reports
240 $hQuery = db_query("SELECT * FROM mod_errorreporter $strWhereClause $strSortClause;");
241 if(!is_resource($hQuery)) {
242 setLastError(ER_ERROR_SQL);
243 return null;
244 }
245 while($arResult = pg_fetch_array($hQuery)) {
246 $er = new erErrorReport(strtotime($arResult["er_date"]), $arResult["er_act"],
247 $arResult["er_machine"], $arResult["er_text"], $arResult["er_hidden"] == "t");
248 $er->setUid($arResult["er_uid"]);
249 $er->setComment($arResult["er_comment"], $arResult["er_commentact"]);
250 $arReturn[] = $er;
251 }
252 return $arReturn;
253 }
254
255 /**
256 * Build a ORDER BY clause from an array.
257 * This helper function takes an array of sorting constants as input and returns an ORDER BY
258 * clause. The values in the clause are in the same order as the constants in the array.
259 * The function in the following example returns an ORDER BY clause where the datasets are first
260 * sorted ascending by visibility, then descending by the machine name to which they refer and
261 * finally ascending by their UID:
262 * @code
263 * $strOrder = buildOrderClause(array(
264 * ER_ERM_SORT_VISIBILITY => ER_ERM_SORT_ASC,
265 * ER_ERM_SORT_MACHINE => ER_ERM_SORT_DESC,
266 * ER_ERM_SORT_UID => ER_ERM_SORT_ASC));
267 * echo $strOrder;
268 * @endcode
269 * The output is: <tt>ORDER BY er_hidden ASC, er_machine DESC, er_uid ASC</tt>
270 * @internal
271 * @param $arcSort (array of constants) The array which declares the order of the SQL rows. Use
272 * @ref errorreportmanager_sorting as keys and @ref errorreportmanager_sorting_dir as values.
273 * @return string
274 */
275 protected function buildOrderByClause($arcSort) {
276 // build the sorting clause
277 $arstrSort = array();
278 foreach($arcSort as $cSort => $cDir) {
279 switch($cSort) {
280 case ER_ERM_SORT_UID:
281 $arstrSort[] = "er_uid ".($cDir == ER_ERM_SORT_DESC ? "DESC" : "ASC"); break;
282 case ER_ERM_SORT_DATE:
283 $arstrSort[] = "er_date ".($cDir == ER_ERM_SORT_DESC ? "DESC" : "ASC"); break;
284 case ER_ERM_SORT_OWNER:
285 $arstrSort[] = "er_act ".($cDir == ER_ERM_SORT_DESC ? "DESC" : "ASC"); break;
286 case ER_ERM_SORT_MACHINE:
287 $arstrSort[] = "er_machine ".($cDir == ER_ERM_SORT_DESC ? "DESC" : "ASC"); break;
288 case ER_ERM_SORT_TEXT:
289 $arstrSort[] = "er_text ".($cDir == ER_ERM_SORT_DESC ? "DESC" : "ASC"); break;
290 case ER_ERM_SORT_COMMENT:
291 $arstrSort[] = "er_comment ".($cDir == ER_ERM_SORT_DESC ? "DESC" : "ASC"); break;
292 case ER_ERM_SORT_COMMENTOWNER:
293 $arstrSort[] = "er_commentact ".($cDir == ER_ERM_SORT_DESC ? "DESC" : "ASC"); break;
294 case ER_ERM_SORT_VISIBILITY:
295 $arstrSort[] = "er_hidden ".($cDir == ER_ERM_SORT_DESC ? "DESC" : "ASC"); break;
296 }
297 }
298 return ("ORDER BY ".join(", ", $arstrSort));
299 }
300
301 //////////////////////////////////// ERROR MESSAGE MANAGEMENT ///////////////////////////////////
302
303 /**
304 * @name Error report management
305 * @{
306 */
307
308 /**
309 * Insert or update an error report in the database.
310 * When the $nUid member of the $erErrorReport object is <tt>null</tt>, a new unique ID is
311 * assigned and the error report is written to the database. Otherwise, the corresponding
312 * record in the table is updated.
313 * @param $er (erErrorReport)
314 * @return (int) The unique ID of the inserted or updated record.
315 * @throws Exception
316 */
317 public function writeErrorReport(erErrorReport $er) {
318 if(!$this->objcfg->userHasAccess() and (!$this->userIsOwner($er->nUid) or
319 ($er->getUid() == null and !($this->objcfg->userIsAdmin())))) {
320 throw new Exception(ER_ERROR_ACCESS_DENIED);
321 }
322
323 $strWhere = null;
324 $strLog = "";
325
326 // Update or insert?
327 $arPut = array();
328 if($er->getUid() == null) {
329 // er_uid is now serial
330 /*$hQuery = db_query("SELECT MAX(er_uid) AS id FROM mod_errorreporter;");
331 if(!is_resource($hQuery)) {
332 setLastError(ER_ERROR_SQL);
333 return -1;
334 }
335 $arResult = pg_fetch_array($hQuery);
336 $er->setUid(intval($arResult["id"]) + 1);*/
337 $strLog = sprintf("Fehlermeldung für Rechner „%s“ eingetragen.",
338 $er->getMachine());
339 } else {
340 $strWhere = "er_uid = ".qdb(intval($er->getUid()));
341 $oOldReport = $this->getErrorReportByID($er->getUid());
342 $strLog = sprintf("Fehlermeldung geändert, Rechner war „%s“, Text war „%s“. ".
343 "Neuer Rechner: „%s“, neuer Text: „%s“, Kommentar: %s",
344 $oOldReport->getMachine(), $oOldReport->getText(), $er->getMachine(),
345 $er->getText(), (strlen($er->getComment()) > 0) ? "„".$er->getComment()."“" : "(leer)");
346 }
347 $arPut["er_date"] = date("Y\-m\-d\ G\:i\:s", $er->getDate());
348 $arPut["er_act"] = $er->getOwner();
349 $arPut["er_machine"] = $er->getMachine();
350 $arPut["er_text"] = $er->getText();
351 $arPut["er_comment"] = $er->getComment();
352 $arPut["er_commentact"] = $er->getCommentOwner();
353 $arPut["er_hidden"] = $er->isHidden() ? "true" : "false";
354 db_store("mod_errorreporter", $arPut, $strWhere);
355
356 erInsertLog($strLog);
357
358 // send notification mail, but only if the message is new
359 if($this->objcfg->isMailNotify() and $er->getUid() == null) {
360 $strMailText = sprintf("<html><body>\nEin Benutzer hat eine Fehlermeldung mit dem ".
361 "Fehlermeldungs-Assistenten abgeschickt. Nachfolgend finden sich Angaben über den ".
362 "Fehler.\n<table>\n<tr><td>Fehler gemeldet von:</td><td>%s</td></tr>\n".
363 "<tr><td>Datum:</td><td>%s</td></tr>\n<tr><td>Betroffener Rechner:</td><td>%s</td></tr>\n".
364 "<tr><td colspan='2'>%s</td></tr>\n</table>\n<hr />\nDiese Mail wurde automatisch ".
365 "generiert.\n</body></html>", q(erGetRealUserName($er->getOwner())),
366 q(date("d\.m\.Y\ G\:i\:s", $er->getDate())), q($er->getMachine()), q($er->getText()));
367 $strMailSubject = sprintf("%s hat einen Fehler im System gemeldet",
368 q(erGetRealUserName($er->getOwner())));
369 $strMailHeader = sprintf("From: %s <%s>\nContent-Type: text/html; charset=utf-8",
370 q(erGetRealUserName($er->getOwner())), user_mail_addr($er->getOwner()));
371 mail($this->objcfg->getMailNotifyAddr(), $strMailSubject, $strMailText, $strMailHeader);
372 }
373
374 return $er->getUid();
375 }
376
377 /**
378 * Delete an error report from the database.
379 * @param $nErrorReportID (int) Unique ID of the error report to delete or -1 if an error
380 * occured. In this case, call getLastError() to get more information.
381 */
382 public function deleteErrorReport($nErrorReportID) {
383 if(!($this->objcfg->userIsAdmin() or $this->userIsOwner($nErrorReportID))) {
384 setLastError(ER_ERROR_ACCESS_DENIED);
385 return -1;
386 }
387
388 $oOldReport = $this->getErrorReportByID($nErrorReportID);
389 db_query(sprintf("DELETE FROM mod_errorreporter WHERE er_uid = '%d';", intval($nErrorReportID)));
390 erInsertLog(sprintf("Fehlermeldung gelöscht, Rechner war „%s“, Text war „%s“",
391 $oOldReport->getMachine(), $oOldReport->getText()));
392 }
393
394 /**
395 * Determine if the current user is the owner of a specified error report.
396 * If this function fails, call getLastError() to get more information.
397 * @param $nID (int) Unique ID of the error report
398 * @return bool
399 */
400 public function userIsOwner($nID) {
401 if(!$_SESSION["act"]) {
402 return false; // user is not logged in
403 } else {
404 $hQuery = db_query(sprintf("SELECT er_act FROM mod_errorreporter WHERE er_uid = %d;", intval($nID)));
405 if(!is_resource($hQuery)) {
406 setLastError(ER_ERROR_SQL);
407 return false;
408 }
409 $arResult = pg_fetch_array($hQuery);
410 return ($arResult["er_act"] == $_SESSION["act"]);
411 }
412 }
413 }
414 ?>
This page took 0.061731 seconds and 3 git commands to generate.