blob: 363968d4c527a6fbf6cc073be98eded570cb1a10 [file] [log] [blame]
Copybara botbe50d492023-11-30 00:16:42 +01001<?php
2class registry {
3 const LOGS_PAGINATION_LIMIT = 30;
4 const REGISTRY_PAGINATION_LIMIT = 20;
5
6 const STATE_REGISTERED = 0;
7 const STATE_MANUALLY_INVALIDATED = 1;
8 const STATE_VALIDATED_BY_WORKER = 2;
9
10 public static $stateIcons = [
11 0 => "check",
12 1 => "delete_forever",
13 2 => "verified_user"
14 ];
15
16 public static $stateIconColors = [
17 0 => "mdl-color-text--green",
18 1 => "mdl-color-text--red",
19 2 => "mdl-color-text--green"
20 ];
21
22 public static $stateTooltips = [
23 0 => "Registrado",
24 1 => "Invalidado manualmente",
25 2 => "Validado"
26 ];
27
28 public static $workerPendingWhere = "r.workervalidated = 0";
29 public static $notInvalidatedWhere = "r.invalidated = 0";
30 public static $logsWarnings = "LOCATE('[warning]', logdetails) as warningpos, LOCATE('[error]', logdetails) as errorpos, LOCATE('[fatalerror]', logdetails) as fatalerrorpos";
31
32 private static function recordLog(&$log, $time, $executedby = -1, $quiet = false) {
33 global $con;
34
35 $slog = db::sanitize($log);
36 $sday = (int)$time;
37 $srealtime = (int)time();
38 $sexecutedby = (int)$executedby;
39
40 $status = mysqli_query($con, "INSERT INTO logs (realtime, day, executedby, logdetails) VALUES ($srealtime, $sday, $sexecutedby, '$slog')");
41
42 if (!$status) {
43 if (!$quiet) echo "[fatalerror] Couldn't record log into the database!\n";
44 return false;
45 } else {
46 if (!$quiet) echo "[success] Log recorded into the database.\n";
47 return mysqli_insert_id($con);
48 }
49 }
50
51 public static function getLogs($start = 0, $limit = self::LOGS_PAGINATION_LIMIT) {
52 global $con;
53
54 $query = mysqli_query($con, "SELECT id, realtime, day, executedby, ".self::$logsWarnings." FROM logs ORDER BY id DESC".db::limitPagination($start, $limit));
55
56 $return = [];
57 while ($row = mysqli_fetch_assoc($query)) {
58 $return[] = $row;
59 }
60
61 return $return;
62 }
63
64 public static function getLog($id) {
65 global $con;
66
67 $sid = (int)$id;
68
69 $query = mysqli_query($con, "SELECT logdetails, ".self::$logsWarnings." FROM logs WHERE id = $sid");
70
71 if (!mysqli_num_rows($query)) return false;
72
73 $row = mysqli_fetch_assoc($query);
74
75 return $row;
76 }
77
78 public static function beautifyLog($str) {
79 $str = str_replace("[info]", "<span style='font-weight: bold;' class='mdl-color-text--blue'>[info]</span>", $str);
80 $str = str_replace("[warning]", "<span style='font-weight: bold;' class='mdl-color-text--orange'>[warning]</span>", $str);
81 $str = str_replace("[error]", "<span style='font-weight: bold;' class='mdl-color-text--red'>[error]</span>", $str);
82 $str = str_replace("[fatalerror]", "<span style='font-weight: bold;' class='mdl-color-text--red-900'>[fatalerror]</span>", $str);
83 return $str;
84 }
85
86 private static function addToLog(&$log, $quiet, $msg) {
87 $log .= $msg;
88 if (!$quiet) echo $msg;
89 }
90
91 private static function alreadyRegistered($time, $worker) {
92 global $con;
93
94 $stime = (int)$time;
95 $sworker = (int)$worker;
96
97 $query = mysqli_query($con, "SELECT id FROM records WHERE worker = $sworker AND day = $stime AND invalidated = 0 LIMIT 1");
98
99 return (mysqli_num_rows($query) > 0);
100 }
101
102 private static function register($time, $worker, $schedule, $creator = -1) {
103 global $con;
104
105 $sworker = (int)$worker;
106 $stime = (int)$time;
107 $srealtime = (int)time();
108 $screator = (int)$creator;
109 $sbeginswork = (int)$schedule["beginswork"];
110 $sendswork = (int)$schedule["endswork"];
111 $sbeginsbreakfast = (int)$schedule["beginsbreakfast"];
112 $sendsbreakfast = (int)$schedule["endsbreakfast"];
113 $sbeginslunch = (int)$schedule["beginslunch"];
114 $sendslunch = (int)$schedule["endslunch"];
115
116 return mysqli_query($con, "INSERT INTO records (worker, day, created, creator, beginswork, endswork, beginsbreakfast, endsbreakfast, beginslunch, endslunch) VALUES ($sworker, $stime, $srealtime, $screator, $sbeginswork, $sendswork, $sbeginsbreakfast, $sendsbreakfast, $sbeginslunch, $sendslunch)");
117 }
118
119 public static function getWorkerCategory($id) {
120 global $con;
121
122 $sid = (int)$id;
123
124 $query = mysqli_query($con, "SELECT p.category category FROM workers w INNER JOIN people p ON w.person = p.id WHERE w.id = $sid");
125
126 if ($query === false || !mysqli_num_rows($query)) {
127 return false;
128 }
129
130 $row = mysqli_fetch_assoc($query);
131
132 return $row["category"];
133 }
134
135 public static function getDayTypes($time) {
136 global $con;
137
138 $stime = (int)$time;
139
140 $query = mysqli_query($con, "SELECT id, category, details FROM calendars WHERE begins <= $stime AND ends >= $stime");
141 if ($query === false) return false;
142
143 $calendars = [];
144 while ($row = mysqli_fetch_assoc($query)) {
145 $calendar = json_decode($row["details"], true);
146 if (json_last_error() !== JSON_ERROR_NONE) return false;
147 if (!isset($calendar[$time])) return false;
148
149 $calendars[$row["category"]] = $calendar[$time];
150 }
151
152 return $calendars;
153 }
154
155 private static function getApplicableSchedules($time) {
156 global $con;
157
158 $stime = (int)$time;
159
160 $query = mysqli_query($con, "SELECT id FROM schedules WHERE begins <= $stime AND ends >= $stime AND active = 1");
161 if ($query === false) return false;
162
163 $schedules = [];
164 while ($row = mysqli_fetch_assoc($query)) {
165 $schedules[] = $row["id"];
166 }
167
168 return $schedules;
169 }
170
171 public static function generateNow($originaltime, &$logId, $quiet = true, $executedby = -1, $workersWhitelist = false) {
172 global $con;
173
174 $log = "";
175
176 if ($workersWhitelist !== false) self::addToLog($log, $quiet, "[info] This is a partial registry generation, because a whitelist of workers was passed: [".implode(", ", $workersWhitelist)."]\n");
177
178 $datetime = new DateTime();
179 $datetime->setTimestamp($originaltime);
180 self::addToLog($log, $quiet, "[info] Time passed: ".$datetime->format("Y-m-d H:i:s")."\n");
181
182 $rawdate = $datetime->format("Y-m-d")."T00:00:00";
183 self::addToLog($log, $quiet, "[info] Working with this date: $rawdate\n");
184 $date = new DateTime($rawdate);
185
186 $time = $date->getTimestamp();
187 $dow = (int)$date->format("N") - 1;
188 self::addToLog($log, $quiet, "[info] Final date timestamp: $time, Dow: $dow\n");
189
190 $days = self::getDayTypes($time);
191 if ($days === false) {
192 self::addToLog($log, $quiet, "[fatalerror] An error occurred while loading the calendars.\n");
193 $logId = self::recordLog($log, $time, $executedby, $quiet);
194 return 1;
195 }
196
197 $schedules = self::getApplicableSchedules($time);
198 if ($schedules === false) {
199 self::addToLog($log, $quiet, "[fatalerror] An error occurred while loading the active schedules.\n");
200 $logId = self::recordLog($log, $time, $executedby, $quiet);
201 return 2;
202 }
203
204 self::addToLog($log, $quiet, "[info] Found ".count($schedules)." active schedule(s)\n");
205
206 foreach ($schedules as $scheduleid) {
207 self::addToLog($log, $quiet, "\n[info] Processing schedule $scheduleid\n");
208
209 $s = schedules::get($scheduleid);
210 if ($s === false) {
211 self::addToLog($log, $quiet, "[fatalerror] An error ocurred while loading schedule with id $scheduleid (it doesn't exist or there was an error with the SQL query)\n");
212 $logId = self::recordLog($log, $time, $executedby, $quiet);
213 return 3;
214 }
215
216 if ($workersWhitelist !== false && !in_array($s["worker"], $workersWhitelist)) {
217 self::addToLog($log, $quiet, "[info] This schedule's worker (".$s["worker"].") is not in the whitelist, so skipping\n");
218 continue;
219 }
220
221 $category = self::getWorkerCategory($s["worker"]);
222
223 if (isset($days[$category])) {
224 self::addToLog($log, $quiet, "[info] Using worker's (".$s["worker"].") category ($category) calendar\n");
225 $typeday = $days[$category];
226 } else if (isset($days[-1])) {
227 self::addToLog($log, $quiet, "[info] Using default calendar\n");
228 $typeday = $days[-1];
229 } else {
230 self::addToLog($log, $quiet, "[warning] No calendar applies, so skipping this schedule\n");
231 continue;
232 }
233
234 if (!isset($s["days"][$typeday])) {
235 self::addToLog($log, $quiet, "[info] This schedule doesn't have this type of day ($typeday) set up, so skipping\n");
236 continue;
237 }
238
239 if (!isset($s["days"][$typeday][$dow])) {
240 self::addToLog($log, $quiet, "[info] This schedule doesn't have a daily schedule for this day of the week ($dow) and type of day ($typeday), so skipping.\n");
241 continue;
242 }
243
244 self::addToLog($log, $quiet, "[info] Found matching daily schedule. We'll proceed to register it\n");
245
246 if (self::alreadyRegistered($time, $s["worker"])) {
247 self::addToLog($log, $quiet, "[warning] We're actually NOT going to register it because another registry already exists for this worker at the same day.\n");
248 } else {
249 if (self::register($time, $s["worker"], $s["days"][$typeday][$dow], $executedby)) {
250 self::addToLog($log, $quiet, "[info] Registered with id ".mysqli_insert_id($con)."\n");
251 } else {
252 self::addToLog($log, $quiet, "[error] Couldn't register this schedule because of an unknown error!\n");
253 }
254 }
255 }
256
257 $logId = self::recordLog($log, $time, $executedby, $quiet);
258
259 return 0;
260 }
261
262 public static function getStatus($row) {
263 if ($row["invalidated"] == 1) return self::STATE_MANUALLY_INVALIDATED;
264 elseif ($row["workervalidated"] == 1) return self::STATE_VALIDATED_BY_WORKER;
265 else return self::STATE_REGISTERED;
266 }
267
268 private static function magicRecord(&$row) {
269 $row["state"] = self::getStatus($row);
270 }
271
272 public static function get($id, $magic = false) {
273 global $con;
274
275 $sid = (int)$id;
276
277 $query = mysqli_query($con, "SELECT * FROM records WHERE id = $sid LIMIT 1");
278
279 if (!mysqli_num_rows($query)) return false;
280
281 $row = mysqli_fetch_assoc($query);
282 if ($magic) self::magicRecord($row);
283
284 return $row;
285 }
286
287 public static function getRecords($worker = false, $begins = false, $ends = false, $returnInvalid = false, $includeWorkerInfo = false, $sortByDateDesc = false, $start = 0, $limit = self::REGISTRY_PAGINATION_LIMIT, $treatWorkerAttributeAsUser = false, $onlyWorkerPending = false, $magic = true) {
288 global $con;
289
290 if ($treatWorkerAttributeAsUser && !$includeWorkerInfo) return false;
291
292 $where = [];
293
294 if ($worker !== false) $where[] = ($treatWorkerAttributeAsUser ? "w.person" : "r.worker")." = ".(int)$worker;
295
296 $dateLimit = ($begins !== false && $ends !== false);
297 if ($dateLimit) {
298 $where[] = "r.day >= ".(int)$begins;
299 $where[] = "r.day <= ".(int)$ends;
300 }
301
302 if (!$returnInvalid || $onlyWorkerPending) $where[] = self::$notInvalidatedWhere;
303
304 if ($onlyWorkerPending) $where[] = self::$workerPendingWhere;
305
306 $query = mysqli_query($con, "SELECT r.*".($includeWorkerInfo ? ", p.id personid, p.name workername, w.company companyid" : "")." FROM records r LEFT JOIN workers w ON r.worker = w.id".($includeWorkerInfo ? " LEFT JOIN people p ON w.person = p.id" : "").(count($where) ? " WHERE ".implode(" AND ", $where) : "")." ORDER BY".($sortByDateDesc ? " r.day DESC, w.company DESC," : "")." id DESC".db::limitPagination($start, $limit));
307
308 $return = [];
309 while ($row = mysqli_fetch_assoc($query)) {
310 if ($magic) self::magicRecord($row);
311 $return[] = $row;
312 }
313
314 return $return;
315 }
316
317 public static function getWorkerRecords($worker, $begins = false, $ends = false, $returnInvalid = false, $onlyWorkerPending = false) {
318 return self::getRecords($worker, $begins, $ends, $returnInvalid, false, true, 0, 0, false, $onlyWorkerPending);
319 }
320
321 public static function numRows($includingInvalidated = false) {
322 global $con;
323
324 $query = mysqli_query($con, "SELECT COUNT(*) count FROM records".($includingInvalidated ? "" : " WHERE invalidated = 0"));
325
326 if (!mysqli_num_rows($query)) return false;
327
328 $row = mysqli_fetch_assoc($query);
329
330 return (isset($row["count"]) ? (int)$row["count"] : false);
331 }
332
333 public static function numRowsUser($user, $includingInvalidated = true) {
334 global $con;
335
336 $where = [];
337 if (!$includingInvalidated) $where[] = "r.invlidated = 0";
338 $where[] = "w.person = ".(int)$user;
339
340 $query = mysqli_query($con, "SELECT COUNT(*) count FROM records r LEFT JOIN workers w ON r.worker = w.id".(count($where) ? " WHERE ".implode(" AND ", $where) : ""));
341
342 if (!mysqli_num_rows($query)) return false;
343
344 $row = mysqli_fetch_assoc($query);
345
346 return (isset($row["count"]) ? (int)$row["count"] : false);
347 }
348
349 public static function checkRecordIsFromPerson($record, $person = "ME", $boolean = false) {
350 global $con;
351
352 if ($person == "ME") $person = people::userData("id");
353
354 $srecord = (int)$record;
355 $sperson = (int)$person;
356
357 $query = mysqli_query($con, "SELECT r.id FROM records r INNER JOIN workers w ON r.worker = w.id INNER JOIN people p ON w.person = p.id WHERE p.id = $sperson AND r.id = $srecord LIMIT 1");
358
359 if (!mysqli_num_rows($query)) {
360 if ($boolean) return false;
361 security::denyUseMethod(security::METHOD_NOTFOUND);
362 }
363
364 return true;
365 }
366
367 public static function invalidate($id, $invalidatedby = "ME") {
368 global $con;
369
370 $sid = (int)$id;
371
372 if ($invalidatedby === "ME") $invalidatedby = people::userData("id");
373 $sinvalidatedby = (int)$invalidatedby;
374
375 return mysqli_query($con, "UPDATE records SET invalidated = 1, invalidatedby = $sinvalidatedby WHERE id = $sid LIMIT 1");
376 }
377
378 public static function invalidateAll($id, $beginsRawDate, $endsRawDate, $invalidatedby = "ME") {
379 global $con;
380
381 $beginsDate = new DateTime($beginsRawDate);
382 $sbegins = (int)$beginsDate->getTimestamp();
383 $endsDate = new DateTime($endsRawDate);
384 $sends = (int)$endsDate->getTimestamp();
385
386 $sid = (int)$id;
387
388 if ($invalidatedby === "ME") $invalidatedby = people::userData("id");
389 $sinvalidatedby = (int)$invalidatedby;
390
391 return mysqli_query($con, "UPDATE records SET invalidated = 1, invalidatedby = $sinvalidatedby WHERE worker = $sid AND invalidated = 0 AND day <= $sends AND day >= $sbegins");
392 }
393}