-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsetAlarm.php
538 lines (448 loc) · 19.2 KB
/
setAlarm.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Set Alarm</title>
<link href='http://fonts.googleapis.com/css?family=Reenie+Beanie&subset=latin' rel='stylesheet' type='text/css'>
<link href='http://fonts.googleapis.com/css?family=Eagle+Lake' rel='stylesheet' type='text/css'>
<!-- <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script> -->
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css">
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<!-- <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/jquery-ui.min.js"></script> -->
<script src="js/msdropdown/jquery.dd.min.js" type="text/javascript"></script>
<link rel="stylesheet" type="text/css" href="css/msdropdown/dd.css" />
<link rel=StyleSheet href="standard.css" type="text/css">
<link rel="icon" href="favicon.ico" type="image/x-icon">
<link rel="shortcut icon" href="favicon.ico" type="image/x-icon">
</head>
<body>
<script language="javascript">
$(document).ready(function(e) {
try {
$("body select").msDropDown();
} catch(e) {
alert(e.message);
}
});
</script>
<?php
/*
PiRadio Plays an assortment of radio stations on a webhost (I've got a
Raspberry Pi on my bookshelf with a pair of speakers plugged into it.)
Copyright (C) 2014 Kevin Lucas
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
require_once 'settings.php';
function print_form($db){
// get the time and date today for use in setting minimum's
date_default_timezone_set('America/Toronto');
$today = date('Y-m-d');
$now = date('H:i');
// get a list of stations from the databaseName
$sql = "SELECT stations.Name, stations.StationID, stations.FileName FROM stations";
$q = mysqli_query($db, $sql);
print <<<HERE
<center><h2>Set Alarm</h2>
<form action="setAlarm.php" method="POST">
<table class='mine' border = '1'>
<tr>
<th><center>Time</center></th>
<th><center>Date</center></th>
<th><center>Station</center></th>
<th><center>Recurring</center></th>
</tr>
<tr>
<td><center><input type="time" name="time" autocomplete="on" value="$now" autofocus required></center></td>
<td><center><input type="date" name="date" autocomplete="on" min="$today" value="$today" required></center></td>
<td><select class="station" name="station" id="station" required onchange="showValue(this)">
HERE;
while ($row = mysqli_fetch_array($q, MYSQLI_NUM)){
print "<option data-image=\"uploads/25x25_$row[2]\">$row[0]</option>";
} // end while
print <<<HERE
</select></td>
<td><center><input type="checkbox" name="recurring" value='1'></center></td>
</tr>
</table>
<center><INPUT class="myButton" type="submit" name="Generate" value="Set Alarm"></center>
</form>
<div align='right'>
<FORM action="radio.php" method="POST">
<INPUT class="myGreenButton" type="submit" name="Generate" value="Back to Main Menu">
</FORM>
</div>
HERE;
return 0;
} // end function definition for print_form()
function write_shell_script($command, $date, $time, $fRecurring){
// a function to write a quick shell script
// this is needed because php is executing my at
// command in /bin/sh rather than /bin/bash
// which doesn't have the <<< construct used in the
// command
//debug
//var_dump($date);
//var_dump($time);
//var_dump($command);
if (1 == $fRecurring){
// remove existing file if it exists (for recurring alarm)
$filePath = "/tmp/alarm_script-" . $date . "_" . $time . ".sh";
} else {
// remove existing file if it exists (for one-off job)
$filePath = "/tmp/alarm_script.sh";
} // end else
unlink("$filePath");
// open file for writing
$handle = fopen("$filePath", "w");
// write the hash bang line
$line = "#!/bin/bash\n";
fwrite($handle, $line);
// write the command to the file
$line = "$command";
fwrite($handle, $line);
// close the handle
fclose($handle);
// make the file executable
$command = "chmod u+x $filePath";
$command = escapeshellcmd($command);
shell_exec($command);
return 0;
}
function show_set_alarms($db){
// a function to retreive alamrs already set and display them on the screen
$sql = "SELECT stations.Name, alarms.Date, alarms.Time, stations.FileName, alarms.AlarmID, alarms.fRecurring FROM alarms INNER JOIN stations ON alarms.StationID = stations.StationID";
$q = mysqli_query($db, $sql);
//debug
//var_dump($dbOutputArray);
//<td><center><img src="uploads/$row[2]" alt="Station Logo" width="100" height="100"></center></td>
//$command = "atq";
//$command = escapeshellcmd($command);
//exec($command, $outputArray);
//debug
//var_dump($q->num_rows);
if ($q->num_rows != NULL){
print <<<HERE
<BR>
<p>The following alarms are set</p>
<table class='mine' border='1'>
HERE;
while ($row = mysqli_fetch_array($q, MYSQLI_NUM)){
print "<tr>";
print "<td><center><img src=\"uploads/$row[3]\" alt=\"Station Logo\" width=\"100\" height=\"100\"></center></td>";
print "<td><center><h3>$row[0]</h3></center></td>";
print "<td><center><h3>$row[1]</h3></center></td>";
print "<td><center><h3>$row[2]</h3></center></td>";
if (1 == $row[5]){
print "<td><center><h3>Daily</h3></center></td>";
} else {
print "<td><center><h3>Once</h3></center></td>";
} // end else
print "<td><center><form action=\"setAlarm.php\" method=\"post\"><INPUT type=\"hidden\" name=\"AlarmID\" value=\"$row[4]\"><INPUT class=\"myButton\" type=\"submit\" name=\"Generate\" value=\"Cancel Alarm\"></form></center></td>";
// AlarmID is $row[4]. Use to cancel alarm
print "</tr>";
} // end while
print "</table>";
} // end if
return 0;
}
function remove_old_shell_script($date, $time){
// a function to remove the no longer needed shell script file
// when canceling a recurring alarm
$fileName = "/tmp/alarm_script-" . $date . "_" . $time . ".sh";
unlink($fileName);
return 0;
}
function cancel_alarm($db, $AlarmID){
// a function to cancell an existing alarm
// check if the alarm is a recurring one or not
$fRecurring = 0;
$sql = "SELECT alarms.fRecurring FROM alarms WHERE alarms.AlarmID = $AlarmID";
$q = mysqli_query($db, $sql);
while ($row = mysqli_fetch_array($q, MYSQLI_NUM)){
$fRecurring = $row[0];
} // end while
if (0 == $fRecurring){
$command = "atq";
exec($command, $atqOutputArray);
// sample atq output
//25 Fri Nov 7 09:17:00 2014 a www-data
//24 Fri Nov 7 08:16:00 2014 a www-data
// get the time & date of selected alarm
$sql = "SELECT alarms.Date, alarms.Time FROM alarms WHERE alarms.AlarmID = $AlarmID";
$q = mysqli_query($db, $sql);
while ($row = mysqli_fetch_array($q, MYSQLI_NUM)){
// the above query should only ever return 1 row
$date = $row[0];
$time = $row[1];
} // end while
// okay, so now I've got the output of the aqt command and the time and date from the db
// need to isolate the time and date of each at job. If it matches I'll need the at job number
// change the date format to match the atq output
$unixTimestamp = strtotime("$date $time");
$datetimeAtFormat = date('D M j H:i:s Y', $unixTimestamp);
// loop through the lines of atq output
foreach ($atqOutputArray as $key=>$line){
// split line on whitespace so we can deal with the individual elements
$lineArray = preg_split('/\s+/', $line);
$datetimeFromAt = $lineArray[1] . " " . $lineArray[2] . " " . $lineArray[3] . " " . $lineArray[4] . " " . $lineArray[5];
// debug
// var_dump($datetimeFromAt);
// string(18) "Fri Nov 7 09:17:00" string(18) "Fri Nov 7 08:16:00"
// var_dump($datetimeAtFormat);
// string(23) "Fri Nov 7 08:16:00 2014" string(23) "Fri Nov 7 08:16:00 2014"
if ($datetimeAtFormat == $datetimeFromAt){
$atJobNumber = $lineArray[0];
} // end if
} // end foreach
// delete the matched at job
if (NULL != $atJobNumber){
$command = "atrm $atJobNumber";
exec($command);
} // end if
// delete the row from the database
if (NULL != $atJobNumber){
$sql = "DELETE FROM alarms WHERE alarms.AlarmID = $AlarmID";
mysqli_query($db, $sql);
} // end if
/*
[Fri Nov 07 06:49:49.040356 2014] [:error] [pid 24467] [client 127.0.0.1:48628] PHP Notice: Undefined variable: atJobNumber in /var/www/PiRadio/setAlarm.php on line 199
Usage: at [-V] [-q x] [-f file] [-mMlbv] timespec ...
at [-V] [-q x] [-f file] [-mMlbv] -t time
at -c job ...
atq [-V] [-q x]
at [ -rd ] job ...
atrm [-V] job ...
batch
*/
} else {
//print "<BR>Not Yet working. You'll have to manually remove the job from www-data's crontab for now.<BR>";
exec('crontab -l', $output);
//$output = implode("\n", $output);
// now need to search $output for the line that matches
// remove it, then update the crontab
// FIX: done
// get the time & date of selected alarm
$sql = "SELECT alarms.Date, alarms.Time FROM alarms WHERE alarms.AlarmID = $AlarmID";
$q = mysqli_query($db, $sql);
while ($row = mysqli_fetch_array($q, MYSQLI_NUM)){
// the above query should only ever return 1 row
$date = $row[0];
$time = $row[1];
} // end while
//debug
// compare output to $date & $time
//var_dump($output);
//var_dump($date);
//var_dump($time);
/*
Not Yet working. You'll have to manually remove the job from www-data's crontab for now.
array(2) { [0]=> string(56) "00 18 10 11 * /tmp/alarm_script-2014-11-10_18:00.sh" [1]=> string(56) "00 19 10 11 * /tmp/alarm_script-2014-11-10_19:00.sh" } string(10) "2014-11-10" string(8) "18:00:00"
*/
$minute = substr($time, -5, 2);
$hour = substr($time, 0, 2);
$dayOfMonth = substr($date, -2);
$month = substr($date, -5, 2);
foreach ($output as $cronJob){
// check if $cronJob is the one we want to cancel based on time
$lineArray = explode(" ", $cronJob);
//debug
//foreach ($lineArray as $val){
// print "<br>value of lineArray element on line 298 is: $val<br>";
// var_dump($minute);
// var_dump($hour);
// var_dump($dayOfMonth);
// var_dump($month);
//} // end foreach
if ($minute == $lineArray[0] && $hour == $lineArray[1] && $dayOfMonth == $lineArray[2] && $month == $lineArray[3]){
// if it is don't output it to the new crontab we'll have to write
} else {
$newCrontab[] = $cronJob;
} // end else
} // end foreach
// If I've done this right the new crontab file we need to load up is in the
// $newCrontab array at this point. Write this out to a file, purge the old
// crontab via the exec() function and load this one (again via the exec()
// function.
// 2014-11-12 Closer but I'm getting blank lines in www-data's crontab
// when removing lines. Need to sort that out and add a way to remove
// .sh files when deleteing cron jobs.
// 2014-11-14 this is done now.
//debug
//print "<br>value of newCrontab is:<br>";
//var_dump($newCrontab);
// write new crontab file
unlink('/tmp/tmp-crontab.txt');
$handle = fopen('/tmp/tmp-crontab.txt', 'w');
foreach ($newCrontab as $line){
if ($line == ""){
// pass
} else {
$line = $line . "\n";
fwrite($handle, $line);
} // end else
} // end foreach
// crontab complaining about no new line at end of file
fwrite($handle, "\n");
fclose($handle);
// purge old crontab
$command = "crontab -r";
exec($command);
// set crontab
$command = "crontab /tmp/tmp-crontab.txt";
shell_exec($command);
// remove meta info from db
$sql = "DELETE FROM alarms WHERE alarms.AlarmID = '$AlarmID'";
mysqli_query($db, $sql);
// remove associated shell script
$time = $hour . ":" . $minute;
remove_old_shell_script($date, $time);
} // end else
return 0;
}
function write_alarm_meta_info_to_db($db, $stationID, $date, $time, $fRecurring){
// a function to write info about the alarm being set to a table in the db
$sql = "INSERT INTO alarms VALUES ('NULL', '$stationID', '$date', '$time', '$fRecurring')";
//$sql = mysqli_real_escape_string($db, $sql);
mysqli_query($db, $sql);
//debug
//var_dump($sql);
return 0;
}
function write_crontab_file($date, $time){
// a function to write out a file in the crontab format
// with the scheduling info based on the values of $date
// and $time
// remove existing file if it exists
unlink('/tmp/tmp-crontab.txt');
// open file for writing
$handle = fopen('/tmp/tmp-crontab.txt', "w");
// get existing crontab contents & write them
exec('crontab -l', $output);
$output = implode("\n", $output);
if (empty($output)){
// do nothing
} else {
// append a new line character
$output = $output . "\n";
} // end else
fwrite($handle, $output);
$minute = substr($time, -2);
$hour = substr($time, 0, 2);
//debug
//var_dump($minute);
//var_dump($hour);
$dayOfMonth = substr($date, -2);
$month = substr($date, -5, 2);
$dayOfWeek = "*";
$filePath = "/tmp/alarm_script-" . $date . "_" . $time . ".sh";
$command = $filePath;
$line = $minute . " " . $hour . " " . $dayOfMonth . " " . $month . " " . $dayOfWeek . " " . $command . "\n";
fwrite ($handle, $line);
// close the handle
fclose($handle);
/*
Linux Crontab Format
MIN HOUR DOM MON DOW CMD
Table: Crontab Fields and Allowed Ranges (Linux Crontab Syntax)
Field Description Allowed Value
MIN Minute field 0 to 59
HOUR Hour field 0 to 23
DOM Day of Month 1-31
MON Month field 1-12
DOW Day Of Week 0-6
CMD Command Any command to be executed.
*/
return 0;
}
function get_alarm_id($db, $date, $time){
// a function to return the alarm ID given the date and time
// I'm assuming that no two alarms are going to be set for the
// same date / time.
$timeWithSeconds = $time . ":00";
$sql = "SELECT AlarmID FROM alarms WHERE alarms.Date = '$date' AND alarms.Time = '$timeWithSeconds'";
$q = mysqli_query($db, $sql);
while ($row = mysqli_fetch_array($q, MYSQLI_NUM)){
// should only be one row returned
$AlarmID = $row[0];
} // while
return $AlarmID;
}
function set_alarm($db, $stationName, $date, $time, $user, $pass, $fRecurring){
// get station ID
$sql = "SELECT stations.StationURL, stations.StationID FROM stations WHERE stations.Name = '$stationName'";
$q = mysqli_query($db, $sql);
while ($row = mysqli_fetch_array($q, MYSQLI_NUM)){
$stationUrl = $row[0];
$stationID = $row[1];
} // end while
if (0 == $fRecurring){
write_alarm_meta_info_to_db($db, $stationID, $date, $time, $fRecurring);
$AlarmID = get_alarm_id($db, $date, $time);
$command = "at $time $date <<< '/usr/bin/killall vlc; mysql -u $user -p$pass radio -e \"DELETE FROM NowPlaying\"; mysql -u $user -p$pass radio -e \"INSERT INTO NowPlaying SET NowPlaying.StationID = $stationID\"; mysql -u $user -p$pass radio -e \"DELETE FROM alarms WHERE alarms.AlarmID = $AlarmID\"; /usr/bin/cvlc $stationUrl'";
//debug
//var_dump($command);
/*
string(390) "at 10:00 2014-11-14 <<< '/usr/bin/killall vlc; mysql -u klucas -p7lemon6 radio -e "DELETE FROM NowPlaying"; mysql -u klucas -p7lemon6 radio -e "INSERT INTO NowPlaying SET NowPlaying.StationID = 3"; mysql -u klucas -p7lemon6 radio -e "DELETE FROM alarms WHERE alarms.date = '2014-11-14' AND alarms.time = '10:00'"; /usr/bin/cvlc http://playerservices.streamtheworld.com/pls/CBC_R1_TOR_L.pls'"
*/
write_shell_script($command, $date, $time, $fRecurring);
$command = "/tmp/alarm_script.sh";
$command = escapeshellcmd($command);
$output = shell_exec($command);
// remove temp file
unlink('/tmp/alarm_script.sh');
} else if (1 == $fRecurring){
// set cron job for recurring alarm
write_crontab_file($date, $time);
$command = "/usr/bin/killall vlc; mysql -u $user -p$pass radio -e \"DELETE FROM NowPlaying\"; mysql -u $user -p$pass radio -e \"INSERT INTO NowPlaying SET NowPlaying.StationID = $stationID\"; /usr/bin/cvlc $stationUrl";
write_shell_script($command, $date, $time, $fRecurring);
$command = "crontab /tmp/tmp-crontab.txt";
shell_exec($command);
write_alarm_meta_info_to_db($db, $stationID, $date, $time, $fRecurring);
}
return 0;
}
// HERE'S MAIN
$time = $_POST["time"];
$date = $_POST["date"];
$stationName = $_POST["station"];
$fRecurring = $_POST["recurring"];
$AlarmID = $_POST["AlarmID"];
$db = mysqli_connect($dbServer, $user, $pass, $databaseName);
//debug
// test data
//$AlarmID = 21;
//cancel_alarm($db, $AlarmID);
//$time = "12:37:00";
//$date = "2014-11-09";
//write_crontab_file($date, $time);
//var_dump($time);
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
// see if we're cancelling a set alarm
if ($AlarmID != NULL){
cancel_alarm($db, $AlarmID);
} // end if
if (empty($time)){
print_form($db);
show_set_alarms($db);
} else {
print_form($db);
set_alarm($db, $stationName, $date, $time, $user, $pass, $fRecurring);
//print "<h3>DONE! Alarm Set.</h3>";
show_set_alarms($db);
} // end the grand else
mysqli_close($db);
?>