-
Notifications
You must be signed in to change notification settings - Fork 38
Expand file tree
/
Copy pathSchedule.php
More file actions
259 lines (217 loc) · 9.21 KB
/
Schedule.php
File metadata and controls
259 lines (217 loc) · 9.21 KB
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
<?php
namespace API;
use Exception;
use Imagick;
class Schedule
{
private function icalFormatTime($time) {
// Get the GMT difference
$gmtDiff = substr(date("O"), 0, 3);
// Minutes->hrs mins
$hr = (int)($time / 60);
$min = $time % 60;
return str_pad($hr % 24, 2, '0', STR_PAD_LEFT)
. str_pad($min, 2, '0', STR_PAD_LEFT)
. "00";
}
private function firstDayAfterDate($weekday, $startDate) {
$weekdayOfStart = date('w', $startDate);
if ($weekdayOfStart > $weekday) {
// Try next week:
// 5 = 7 - 1 (we only go up to six) - 1 (we don't want to double count "today")
$startDate += 60*60*24*(5-$weekDayOfStart);
$weekdayOfStart = 0;
}
// weekday - weekDayOfStart = number of days between now and the first instance of that week day
return $startDate + (60*60*24*($weekday-$weekdayOfStart));
}
private function hashTime($time, $schedule) {
return ($time['start'] . "-" .
$time['end'] . "-" .
$time['bldg'][$schedule['bldgStyle']] . "-" .
$time['room']);
}
public function generateIcal($schedule) {
date_default_timezone_set('America/New_York');
// Globals
global $HTTPROOTADDRESS, $dbConn;
// We need to lookup the information about the quarter
$term = $dbConn->real_escape_string($schedule['term']);
$query = "SELECT start, end FROM quarters WHERE quarter='{$term}'";
$result = $dbConn->query($query);
$term = $result->fetch_assoc();
$termStart = strtotime($term['start']);
$termEnd = date("Ymd", strtotime($term['end']));
// Start generating code
$code = "";
// Header
$code .= "BEGIN:VCALENDAR\r\n";
$code .= "VERSION:2.0\r\n";
$code .= "PRODID: -//CSH ScheduleMaker//iCal4j 1.0//EN\r\n";
$code .= "METHOD:PUBLISH\r\n";
$code .= "CALSCALE:GREGORIAN\r\n";
// Iterate over all the courses
foreach($schedule['courses'] as $course) {
// Skip classes that don't meet
if(empty($course['times'])) {
continue;
}
$scheduleByTime = array();
foreach($course['times'] as $time) {
$hash = $this->hashTime($time, $schedule);
// Add to scheduleByTime array
if (array_key_exists($hash, $scheduleByTime)) {
$scheduleByTime[$hash][] = $time;
} else {
$scheduleByTime[$hash] = array($time);
}
}
// Iterate over all the times
foreach($scheduleByTime as $times) {
$code .= "BEGIN:VEVENT\r\n";
$code .= "UID:" . md5(uniqid(mt_rand(), true) . " @{$HTTPROOTADDRESS}");
$code .= "\r\n";
$code .= "TZID:America/New_York\r\n";
$code .= "DTSTAMP:" . gmdate('Ymd') . "T" . gmdate("His") . "Z\r\n";
$startTime = $this->icalFormatTime($times[0]['start']);
$endTime = $this->icalFormatTime($times[0]['end']);
// The start day of the event MUST be offset by it's day
// the -1 is b/c quarter starts are on Monday(=1)
// This /could/ be done via the RRULE WKST param, but that means
// translating days from numbers to some other esoteric format.
// @TODO: Retrieve the timezone from php or the config file
$day = date("Ymd", $this->firstDayAfterDate($times[0]['day'], $termStart));
$code .= "DTSTART;TZID=America/New_York:{$day}T{$startTime}\r\n";
$code .= "DTEND;TZID=America/New_York:{$day}T{$endTime}\r\n";
//$holidayTimes is an array of DateTimes that are listed as holidays in RIT's calendar.
$code .= "EXDATE:{$holidayTimes}\r\n";
$dayCodes = array('SU', 'MO', 'TU', 'WE', 'TH', 'FR', 'SA');
$days = array();
foreach ($times as $time) {
$days[] = $dayCodes[$time['day']];
}
$dayString = implode(',', $days);
$code .= "RRULE:FREQ=WEEKLY;INTERVAL=1;WKST=SU;BYDAY={$dayString};UNTIL={$termEnd}\r\n";
$code .= "ORGANIZER:RIT\r\n";
// Course name
$code .= "SUMMARY:{$course['title']}";
if($course['courseNum'] != 'non') {
$code .= " ({$course['courseNum']})";
}
$code .= "\r\n";
// Meeting location
if($course['courseNum'] != 'non') {
$bldg = $times[0]['bldg'][$schedule['bldgStyle']];
$code .= "LOCATION:{$bldg}-{$times[0]['room']}\r\n";
}
$code .= "END:VEVENT\r\n";
}
}
$code .= "END:VCALENDAR\r\n";
return $code;
}
public function getScheduleFromId($id) {
global $dbConn;
// Query to see if the id exists, if we can update the last accessed time,
// then the id most definitely exists.
$query = "UPDATE schedules SET datelastaccessed = NOW() WHERE id={$id}";
$result = $dbConn->query($query);
$query = "SELECT startday, endday, starttime, endtime, building, `quarter`, CAST(`image` AS unsigned int) AS `image` FROM schedules WHERE id={$id}";
$result = $dbConn->query($query);
if(!$result) {
return NULL;
}
$scheduleInfo = $result->fetch_assoc();
if(!$scheduleInfo) {
return NULL;
}
// Grab the metadata of the schedule
$startDay = (int)$scheduleInfo['startday'];
$endDay = (int)$scheduleInfo['endday'];
$startTime = (int)$scheduleInfo['starttime'];
$endTime = (int)$scheduleInfo['endtime'];
$building = $scheduleInfo['building'];
$term = $scheduleInfo['quarter'];
$image = $scheduleInfo['image'] == 1;
// Create storage for the courses that will be returned
$schedule = array();
// It exists, so grab all the courses that exist for this schedule
$query = "SELECT section FROM schedulecourses WHERE schedule = {$id}";
$result = $dbConn->query($query);
while($course = $result->fetch_assoc()) {
$schedule[] = getCourseBySectionId($course['section']);
}
// Grab all the non courses that exist for this schedule
$query = "SELECT * FROM schedulenoncourses WHERE schedule = $id";
$result = $dbConn->query($query);
if(!$result) {
echo $dbConn->error();
}
while($nonCourseInfo = $result->fetch_assoc()) {
$schedule[] = array(
"title" => $nonCourseInfo['title'],
"courseNum" => "non",
"times" => array(array(
"day" => $nonCourseInfo['day'],
"start" => $nonCourseInfo['start'],
"end" => $nonCourseInfo['end']
))
);
}
return array(
//REMOVED WEIRD NESTED ARRAY FOR 'courses'??????
"courses" => $schedule,
"startTime" => $startTime,
"endTime" => $endTime,
"startDay" => $startDay,
"endDay" => $endDay,
"bldgStyle" => $building,
"term" => $term,
"image" => $image
);
}
private function getScheduleFromOldId($id) {
global $dbConn;
$query = "SELECT id FROM schedules WHERE oldid = '{$id}'";
$result = $dbConn->query($query);
if(!$result || $result->num_rows != 1) {
return NULL;
} else {
$newId = $result->fetch_assoc();
$newId = $newId['id'];
$schedule = $this->getScheduleFromId($newId);
$schedule['id'] = $newId;
return $schedule;
}
}
/**
* Generates a render of schedule's SVG. The PNG render of the image will be
* stored in /img/schedules/ with a filename equal to the id of the schedule.
* @param $svg string The SVG code for the image
* @param $id string The ID of the schedule, for file name generation
* @return bool True on success, False otherwise.
*/
public function renderSvg($svg, $id) {
try {
global $s3ImageManager;
// Prepend parsing info
$svg = preg_replace('/(.*<svg[^>]* width=")(100\%)(.*)/', '${1}1000px${3}', $svg);
$svg = '<?xml version="1.0" encoding="UTF-8" standalone="no"?>' . $svg;
// Load the image into an ImageMagick object
$im = new Imagick();
$im->readImageBlob($svg);
// Convert it to png
$im->setImageFormat("png24");
$im->scaleimage(1000, 600, true);
// Write it to s3
//TODO Generate non-white image
$s3ImageManager->saveImage($im, $id);
$im->clear();
$im->destroy();
// Success!
return true;
} catch(Exception $e) {
return false;
}
}
}