Completed
Push — develop ( 5bc2b0...db625e )
by Seth
04:17
created
import.php 1 patch
Indentation   +247 added lines, -247 removed lines patch added patch discarded remove patch
@@ -1,12 +1,12 @@  discard block
 block discarded – undo
1 1
 <?php
2 2
 
3 3
 if (php_sapi_name() == 'cli') {
4
-	// TODO there is a more streamlined way of doing this that escapes me just this second
5
-	$_REQUEST['cal'] = $argv[1];
6
-	$_REQUEST['canvas_url'] = $argv[2];
7
-	$_REQUEST['schedule'] = $argv[3];
4
+    // TODO there is a more streamlined way of doing this that escapes me just this second
5
+    $_REQUEST['cal'] = $argv[1];
6
+    $_REQUEST['canvas_url'] = $argv[2];
7
+    $_REQUEST['schedule'] = $argv[3];
8 8
 
9
-	define ('IGNORE_LTI', true);
9
+    define ('IGNORE_LTI', true);
10 10
 }
11 11
 
12 12
 require_once 'common.inc.php';
@@ -20,49 +20,49 @@  discard block
 block discarded – undo
20 20
  * Check to see if a URL exists
21 21
  **/
22 22
 function urlExists($url) {
23
-	$handle = fopen($url, 'r');
24
-	return $handle !== false;
23
+    $handle = fopen($url, 'r');
24
+    return $handle !== false;
25 25
 }
26 26
 
27 27
 /**
28 28
  * compute the calendar context for the canvas object based on its URL
29 29
  **/
30 30
 function getCanvasContext($canvasUrl) {
31
-	global $metadata;
32
-
33
-	// TODO: accept calendar2?contexts links too (they would be an intuitively obvious link to use, after all)
34
-	// FIXME: users aren't working
35
-	// TODO: it would probably be better to look up users by email address than URL
36
-	/* get the context (user, course or group) for the canvas URL */
37
-	$canvasContext = array();
38
-	if (preg_match('%(https?://)?(' . parse_url($metadata['CANVAS_INSTANCE_URL'], PHP_URL_HOST) . '/((about/(\d+))|(courses/(\d+)(/groups/(\d+))?)|(accounts/\d+/groups/(\d+))))%', $_REQUEST['canvas_url'], $matches)) {
39
-		$canvasContext['canonical_url'] = "https://{$matches[2]}"; // https://stmarksschool.instructure.com/courses/953
40
-
41
-		// course or account groups
42
-		if (isset($matches[9]) || isset($matches[11])) {
43
-			$canvasContext['context'] = 'group'; // used to for context_code in events
44
-			$canvasContext['id'] = ($matches[9] > $matches[11] ? $matches[9] : $matches[11]);
45
-			$canvasContext['verification_url'] = "groups/{$canvasContext['id']}"; // used once to look up the object to be sure it really exists
46
-
47
-		// courses
48
-		} elseif (isset($matches[7])) {
49
-			$canvasContext['context'] = 'course';
50
-			$canvasContext['id'] = $matches[7];
51
-			$canvasContext['verification_url'] = "courses/{$canvasContext['id']}";
52
-
53
-		// users
54
-		} elseif (isset($matches[5])) {
55
-			$canvasContext['context'] = 'user';
56
-			$canvasContext['id'] = $matches[5];
57
-			$canvasContext['verification_url'] = "users/{$canvasContext['id']}/profile";
58
-
59
-		// we're somewhere where we don't know where we are
60
-		} else {
61
-			return false;
62
-		}
63
-		return $canvasContext;
64
-	}
65
-	return false;
31
+    global $metadata;
32
+
33
+    // TODO: accept calendar2?contexts links too (they would be an intuitively obvious link to use, after all)
34
+    // FIXME: users aren't working
35
+    // TODO: it would probably be better to look up users by email address than URL
36
+    /* get the context (user, course or group) for the canvas URL */
37
+    $canvasContext = array();
38
+    if (preg_match('%(https?://)?(' . parse_url($metadata['CANVAS_INSTANCE_URL'], PHP_URL_HOST) . '/((about/(\d+))|(courses/(\d+)(/groups/(\d+))?)|(accounts/\d+/groups/(\d+))))%', $_REQUEST['canvas_url'], $matches)) {
39
+        $canvasContext['canonical_url'] = "https://{$matches[2]}"; // https://stmarksschool.instructure.com/courses/953
40
+
41
+        // course or account groups
42
+        if (isset($matches[9]) || isset($matches[11])) {
43
+            $canvasContext['context'] = 'group'; // used to for context_code in events
44
+            $canvasContext['id'] = ($matches[9] > $matches[11] ? $matches[9] : $matches[11]);
45
+            $canvasContext['verification_url'] = "groups/{$canvasContext['id']}"; // used once to look up the object to be sure it really exists
46
+
47
+        // courses
48
+        } elseif (isset($matches[7])) {
49
+            $canvasContext['context'] = 'course';
50
+            $canvasContext['id'] = $matches[7];
51
+            $canvasContext['verification_url'] = "courses/{$canvasContext['id']}";
52
+
53
+        // users
54
+        } elseif (isset($matches[5])) {
55
+            $canvasContext['context'] = 'user';
56
+            $canvasContext['id'] = $matches[5];
57
+            $canvasContext['verification_url'] = "users/{$canvasContext['id']}/profile";
58
+
59
+        // we're somewhere where we don't know where we are
60
+        } else {
61
+            return false;
62
+        }
63
+        return $canvasContext;
64
+    }
65
+    return false;
66 66
 }
67 67
 
68 68
 /**
@@ -71,7 +71,7 @@  discard block
 block discarded – undo
71 71
  * This must happen AFTER the event hash has been calculated!
72 72
  **/
73 73
 function filterEvent($event, $calendarCache) {
74
- 	return (
74
+        return (
75 75
         (
76 76
             // TODO actual multi-day events would be nice
77 77
             // only include first day of multi-day events
@@ -80,21 +80,21 @@  discard block
 block discarded – undo
80 80
         ) &&
81 81
         (
82 82
             // include this event if filtering is off...
83
-     		$calendarCache['enable_regexp_filter'] == false ||
84
-     		(
85
-    			(
86
-    				( // if filtering is on, and there's an include pattern test that pattern...
87
-    					!empty($calendarCache['include_regexp']) &&
88
-    					preg_match("%{$calendarCache['include_regexp']}%", $event->getProperty('SUMMARY'))
89
-    				)
90
-    			) &&
91
-    			!( // if there is an exclude pattern, make sure that this event is NOT excluded
92
-    				!empty($calendarCache['exclude_regexp']) &&
93
-    				preg_match("%{$calendarCache['exclude_regexp']}%", $event->getProperty('SUMMARY'))
94
-    			)
95
-    		)
83
+                $calendarCache['enable_regexp_filter'] == false ||
84
+             (
85
+                (
86
+                    ( // if filtering is on, and there's an include pattern test that pattern...
87
+                        !empty($calendarCache['include_regexp']) &&
88
+                        preg_match("%{$calendarCache['include_regexp']}%", $event->getProperty('SUMMARY'))
89
+                    )
90
+                ) &&
91
+                !( // if there is an exclude pattern, make sure that this event is NOT excluded
92
+                    !empty($calendarCache['exclude_regexp']) &&
93
+                    preg_match("%{$calendarCache['exclude_regexp']}%", $event->getProperty('SUMMARY'))
94
+                )
95
+            )
96 96
         )
97
-	);
97
+    );
98 98
 }
99 99
 
100 100
 // TODO: it would be nice to be able to cleanly remove a synched calendar
@@ -106,61 +106,61 @@  discard block
 block discarded – undo
106 106
    object)? */
107 107
 if (isset($_REQUEST['cal']) && isset($_REQUEST['canvas_url'])) {
108 108
 
109
-	if ($canvasContext = getCanvasContext($_REQUEST['canvas_url'])) {
110
-		/* check ICS feed to be sure it exists */
111
-		if(urlExists($_REQUEST['cal'])) {
112
-			/* look up the canvas object -- mostly to make sure that it exists! */
109
+    if ($canvasContext = getCanvasContext($_REQUEST['canvas_url'])) {
110
+        /* check ICS feed to be sure it exists */
111
+        if(urlExists($_REQUEST['cal'])) {
112
+            /* look up the canvas object -- mostly to make sure that it exists! */
113 113
             $canvasObject = false;
114 114
             try {
115 115
                 $canvasObject = $api->get($canvasContext['verification_url']);
116 116
             } catch (Exception $e) {
117 117
                 postMessage("Error accessing Canvas object", $canvasContext['verification_url'], NotificationMessage::DANGER);
118 118
             }
119
-			if ($canvasObject) {
119
+            if ($canvasObject) {
120 120
 
121
-				/* calculate the unique pairing ID of this ICS feed and canvas object */
122
-				$pairingHash = getPairingHash($_REQUEST['cal'], $canvasContext['canonical_url']);
123
-				$log = Log::singleton('file', __DIR__ . "/logs/$pairingHash.log");
124
-				postMessage('Sync started', getSyncTimestamp(), NotificationMessage::INFO);
121
+                /* calculate the unique pairing ID of this ICS feed and canvas object */
122
+                $pairingHash = getPairingHash($_REQUEST['cal'], $canvasContext['canonical_url']);
123
+                $log = Log::singleton('file', __DIR__ . "/logs/$pairingHash.log");
124
+                postMessage('Sync started', getSyncTimestamp(), NotificationMessage::INFO);
125 125
 
126
-				/* tell users that it's started and to cool their jets */
127
-				if (php_sapi_name() != 'cli') {
128
-					$smarty->assign('content', '
126
+                /* tell users that it's started and to cool their jets */
127
+                if (php_sapi_name() != 'cli') {
128
+                    $smarty->assign('content', '
129 129
 						<h3>Calendar Import Started</h3>
130 130
 						<p>The calendar import that you requested has begun. You may leave this page at anytime. You can see the progress of the import by visiting <a target="_blank" href="https://' . parse_url($metadata['CANVAS_INSTANCE_URL'], PHP_URL_HOST) . "/calendar?include_contexts={$canvasContext['context']}_{$canvasObject['id']}\">this calendar</a> in Canvas.</p>"
131
-					);
132
-					$smarty->display('page.tpl');
133
-				}
134
-
135
-				/* parse the ICS feed */
136
-				$ics = new vcalendar(
137
-					array(
138
-						'unique_id' => $metadata['APP_ID'],
139
-						'url' => $_REQUEST['cal']
140
-					)
141
-				);
142
-				$ics->parse();
143
-
144
-				/* log this pairing in the database cache, if it doesn't already exist */
145
-				$calendarCacheResponse = $sql->query("
131
+                    );
132
+                    $smarty->display('page.tpl');
133
+                }
134
+
135
+                /* parse the ICS feed */
136
+                $ics = new vcalendar(
137
+                    array(
138
+                        'unique_id' => $metadata['APP_ID'],
139
+                        'url' => $_REQUEST['cal']
140
+                    )
141
+                );
142
+                $ics->parse();
143
+
144
+                /* log this pairing in the database cache, if it doesn't already exist */
145
+                $calendarCacheResponse = $sql->query("
146 146
 					SELECT *
147 147
 						FROM `calendars`
148 148
 						WHERE
149 149
 							`id` = '$pairingHash'
150 150
 				");
151
-				$calendarCache = $calendarCacheResponse->fetch_assoc();
151
+                $calendarCache = $calendarCacheResponse->fetch_assoc();
152 152
 
153
-				/* if the calendar is already cached, just update the sync timestamp */
154
-				if ($calendarCache) {
155
-					$sql->query("
153
+                /* if the calendar is already cached, just update the sync timestamp */
154
+                if ($calendarCache) {
155
+                    $sql->query("
156 156
 						UPDATE `calendars`
157 157
 							SET
158 158
 								`synced` = '" . getSyncTimestamp() . "'
159 159
 							WHERE
160 160
 								`id` = '$pairingHash'
161 161
 					");
162
-				} else {
163
-					$sql->query("
162
+                } else {
163
+                    $sql->query("
164 164
 						INSERT INTO `calendars`
165 165
 							(
166 166
 								`id`,
@@ -183,46 +183,46 @@  discard block
 block discarded – undo
183 183
 								" . ($_REQUEST['enable_regexp_filter'] == VALUE_ENABLE_REGEXP_FILTER ? "'" . $sql->real_escape_string($_REQUEST['exclude_regexp']) . "'" : 'NULL') . "
184 184
 							)
185 185
 					");
186
-				}
186
+                }
187 187
 
188
-				/* refresh calendar information from cache database */
189
-				$calendarCacheResponse = $sql->query("
188
+                /* refresh calendar information from cache database */
189
+                $calendarCacheResponse = $sql->query("
190 190
 					SELECT *
191 191
 						FROM `calendars`
192 192
 						WHERE
193 193
 							`id` = '$pairingHash'
194 194
 				");
195
-				$calendarCache = $calendarCacheResponse->fetch_assoc();
195
+                $calendarCache = $calendarCacheResponse->fetch_assoc();
196 196
 
197
-				/* walk through $master_array and update the Canvas calendar to match the
197
+                /* walk through $master_array and update the Canvas calendar to match the
198 198
 				   ICS feed, caching changes in the database */
199
-				// TODO: would it be worth the performance improvement to just process things from today's date forward? (i.e. ignore old items, even if they've changed...)
200
-				// TODO: the best window for syncing would be the term of the course in question, right?
201
-				// TODO: Arbitrarily selecting events in for a year on either side of today's date, probably a better system?
202
-				foreach ($ics->selectComponents(
203
-					date('Y')-1, // startYear
204
-					date('m'), // startMonth
205
-					date('d'), // startDay
206
-					date('Y')+1, // endYEar
207
-					date('m'), // endMonth
208
-					date('d'), // endDay
209
-					'vevent', // cType
210
-					false, // flat
211
-					true, // any
212
-					true // split
213
-				) as $year) {
214
-					foreach ($year as $month => $days) {
215
-						foreach ($days as $day => $events) {
216
-							foreach ($events as $i => $event) {
217
-
218
-								/* does this event already exist in Canvas? */
219
-								$eventHash = getEventHash($event);
220
-
221
-								/* if the event should be included... */
222
-								if (filterEvent($event, $calendarCache)) {
223
-
224
-									/* have we cached this event already? */
225
-									$eventCacheResponse = $sql->query("
199
+                // TODO: would it be worth the performance improvement to just process things from today's date forward? (i.e. ignore old items, even if they've changed...)
200
+                // TODO: the best window for syncing would be the term of the course in question, right?
201
+                // TODO: Arbitrarily selecting events in for a year on either side of today's date, probably a better system?
202
+                foreach ($ics->selectComponents(
203
+                    date('Y')-1, // startYear
204
+                    date('m'), // startMonth
205
+                    date('d'), // startDay
206
+                    date('Y')+1, // endYEar
207
+                    date('m'), // endMonth
208
+                    date('d'), // endDay
209
+                    'vevent', // cType
210
+                    false, // flat
211
+                    true, // any
212
+                    true // split
213
+                ) as $year) {
214
+                    foreach ($year as $month => $days) {
215
+                        foreach ($days as $day => $events) {
216
+                            foreach ($events as $i => $event) {
217
+
218
+                                /* does this event already exist in Canvas? */
219
+                                $eventHash = getEventHash($event);
220
+
221
+                                /* if the event should be included... */
222
+                                if (filterEvent($event, $calendarCache)) {
223
+
224
+                                    /* have we cached this event already? */
225
+                                    $eventCacheResponse = $sql->query("
226 226
 										SELECT *
227 227
 											FROM `events`
228 228
 											WHERE
@@ -231,11 +231,11 @@  discard block
 block discarded – undo
231 231
 									");
232 232
 
233 233
 
234
-									/* if we already have the event cached in its current form, just update
234
+                                    /* if we already have the event cached in its current form, just update
235 235
 									   the timestamp */
236
-									$eventCache = $eventCacheResponse->fetch_assoc();
237
-									if ($eventCache) {
238
-										$sql->query("
236
+                                    $eventCache = $eventCacheResponse->fetch_assoc();
237
+                                    if ($eventCache) {
238
+                                        $sql->query("
239 239
 											UPDATE `events`
240 240
 												SET
241 241
 													`synced` = '" . getSyncTimestamp() . "'
@@ -243,29 +243,29 @@  discard block
 block discarded – undo
243 243
 													`id` = '{$eventCache['id']}'
244 244
 										");
245 245
 
246
-									/* otherwise, add this new event and cache it */
247
-									} else {
248
-										/* multi-day event instance start times need to be changed to _this_ date */
249
-										$start = new DateTime(iCalUtilityFunctions::_date2strdate($event->getProperty('DTSTART')));
250
-										$end = new DateTime(iCalUtilityFunctions::_date2strdate($event->getProperty('DTEND')));
246
+                                    /* otherwise, add this new event and cache it */
247
+                                    } else {
248
+                                        /* multi-day event instance start times need to be changed to _this_ date */
249
+                                        $start = new DateTime(iCalUtilityFunctions::_date2strdate($event->getProperty('DTSTART')));
250
+                                        $end = new DateTime(iCalUtilityFunctions::_date2strdate($event->getProperty('DTEND')));
251 251
                                                                                 if ($event->getProperty('X-RECURRENCE')) {
252
-											$start = new DateTime($event->getProperty('X-CURRENT-DTSTART')[1]);
253
-											$end = new DateTime($event->getProperty('X-CURRENT-DTEND')[1]);
254
-										}
255
-										$start->setTimeZone(new DateTimeZone(LOCAL_TIMEZONE));
256
-										$end->setTimeZone(new DateTimeZone(LOCAL_TIMEZONE));
252
+                                            $start = new DateTime($event->getProperty('X-CURRENT-DTSTART')[1]);
253
+                                            $end = new DateTime($event->getProperty('X-CURRENT-DTEND')[1]);
254
+                                        }
255
+                                        $start->setTimeZone(new DateTimeZone(LOCAL_TIMEZONE));
256
+                                        $end->setTimeZone(new DateTimeZone(LOCAL_TIMEZONE));
257 257
 
258 258
                                         try {
259 259
                                             $calendarEvent = $api->post("/calendar_events",
260
-    											array(
261
-    												'calendar_event[context_code]' => "{$canvasContext['context']}_{$canvasObject['id']}",
262
-    												'calendar_event[title]' => preg_replace('%^([^\]]+)(\s*\[[^\]]+\]\s*)+$%', '\\1', strip_tags($event->getProperty('SUMMARY'))),
263
-    												'calendar_event[description]' => \Michelf\Markdown::defaultTransform(str_replace('\n', "\n\n", $event->getProperty('DESCRIPTION', 1))),
264
-    												'calendar_event[start_at]' => $start->format(CANVAS_TIMESTAMP_FORMAT),
265
-    												'calendar_event[end_at]' => $end->format(CANVAS_TIMESTAMP_FORMAT),
266
-    												'calendar_event[location_name]' => $event->getProperty('LOCATION')
267
-    											)
268
-    										);
260
+                                                array(
261
+                                                    'calendar_event[context_code]' => "{$canvasContext['context']}_{$canvasObject['id']}",
262
+                                                    'calendar_event[title]' => preg_replace('%^([^\]]+)(\s*\[[^\]]+\]\s*)+$%', '\\1', strip_tags($event->getProperty('SUMMARY'))),
263
+                                                    'calendar_event[description]' => \Michelf\Markdown::defaultTransform(str_replace('\n', "\n\n", $event->getProperty('DESCRIPTION', 1))),
264
+                                                    'calendar_event[start_at]' => $start->format(CANVAS_TIMESTAMP_FORMAT),
265
+                                                    'calendar_event[end_at]' => $end->format(CANVAS_TIMESTAMP_FORMAT),
266
+                                                    'calendar_event[location_name]' => $event->getProperty('LOCATION')
267
+                                                )
268
+                                            );
269 269
                                             $sql->query("
270 270
     											INSERT INTO `events`
271 271
     												(
@@ -284,102 +284,102 @@  discard block
 block discarded – undo
284 284
                                         } catch (Exception $e) {
285 285
                                             postMessage('Error creating calendar event', $eventHash, NotificationMessage::ERROR);
286 286
                                         }
287
-									}
288
-								}
289
-							}
290
-						}
291
-					}
292
-				}
293
-
294
-				/* clean out previously synced events that are no longer correct */
295
-				$deletedEventsResponse = $sql->query("
287
+                                    }
288
+                                }
289
+                            }
290
+                        }
291
+                    }
292
+                }
293
+
294
+                /* clean out previously synced events that are no longer correct */
295
+                $deletedEventsResponse = $sql->query("
296 296
 					SELECT * FROM `events`
297 297
 						WHERE
298 298
 							`calendar` = '{$calendarCache['id']}' AND
299 299
 							`synced` != '" . getSyncTimestamp() . "'
300 300
 				");
301
-				while ($deletedEventCache = $deletedEventsResponse->fetch_assoc()) {
302
-					try {
303
-						$deletedEvent = $api->delete("calendar_events/{$deletedEventCache['calendar_event[id]']}",
304
-							array(
305
-								'cancel_reason' => getSyncTimestamp(),
306
-								'as_user_id' => ($canvasContext['context'] == 'user' ? $canvasObject['id'] : '') // TODO: this feels skeevy -- like the empty string will break
307
-							)
308
-						);
309
-					} catch (Pest_Unauthorized $e) {
310
-						/* if the event has been deleted in Canvas, we'll get an error when
301
+                while ($deletedEventCache = $deletedEventsResponse->fetch_assoc()) {
302
+                    try {
303
+                        $deletedEvent = $api->delete("calendar_events/{$deletedEventCache['calendar_event[id]']}",
304
+                            array(
305
+                                'cancel_reason' => getSyncTimestamp(),
306
+                                'as_user_id' => ($canvasContext['context'] == 'user' ? $canvasObject['id'] : '') // TODO: this feels skeevy -- like the empty string will break
307
+                            )
308
+                        );
309
+                    } catch (Pest_Unauthorized $e) {
310
+                        /* if the event has been deleted in Canvas, we'll get an error when
311 311
 						   we try to delete it a second time. We still need to delete it from
312 312
 						   our cache database, however */
313
-						postMessage('Cache out-of-sync', "calendar_event[{$deletedEventCache['calendar_event[id]']}] no longer exists and will be purged from cache.", NotificationMessage::INFO);
314
-					} catch (Pest_ClientError $e) {
315
-						postMessage(
316
-							'API Client Error',
317
-							'<pre>' . print_r(array(
318
-								'Status' => $PEST->lastStatus(),
319
-								'Error' => $PEST->lastBody(),
320
-								'Verb' => $verb,
321
-								'URL' => $url,
322
-								'Data' => $data
323
-							), false) . '</pre>',
324
-							NotificationMessage::ERROR
325
-						);
326
-						if (php_sapi_name() != 'cli') $smarty->display('page.tpl');
327
-						exit;
328
-					}
329
-					$sql->query("
313
+                        postMessage('Cache out-of-sync', "calendar_event[{$deletedEventCache['calendar_event[id]']}] no longer exists and will be purged from cache.", NotificationMessage::INFO);
314
+                    } catch (Pest_ClientError $e) {
315
+                        postMessage(
316
+                            'API Client Error',
317
+                            '<pre>' . print_r(array(
318
+                                'Status' => $PEST->lastStatus(),
319
+                                'Error' => $PEST->lastBody(),
320
+                                'Verb' => $verb,
321
+                                'URL' => $url,
322
+                                'Data' => $data
323
+                            ), false) . '</pre>',
324
+                            NotificationMessage::ERROR
325
+                        );
326
+                        if (php_sapi_name() != 'cli') $smarty->display('page.tpl');
327
+                        exit;
328
+                    }
329
+                    $sql->query("
330 330
 						DELETE FROM `events`
331 331
 							WHERE
332 332
 								`id` = '{$deletedEventCache['id']}'
333 333
 					");
334
-				}
334
+                }
335 335
 
336
-				/* if this was a scheduled import (i.e. a sync), update that schedule */
337
-				if (isset($_REQUEST['schedule'])) {
338
-					$sql->query("
336
+                /* if this was a scheduled import (i.e. a sync), update that schedule */
337
+                if (isset($_REQUEST['schedule'])) {
338
+                    $sql->query("
339 339
 						UPDATE `schedules`
340 340
 							SET
341 341
 								`synced` = '" . getSyncTimestamp() . "'
342 342
 							WHERE
343 343
 								`id` = '{$_REQUEST['schedule']}'
344 344
 					");
345
-				}
346
-				/* are we setting up a regular synchronization? */
347
-				if (isset($_REQUEST['sync']) && $_REQUEST['sync'] != SCHEDULE_ONCE) {
345
+                }
346
+                /* are we setting up a regular synchronization? */
347
+                if (isset($_REQUEST['sync']) && $_REQUEST['sync'] != SCHEDULE_ONCE) {
348 348
 
349
-					// FIXME CRON SYNC SETUP GOES HERE
349
+                    // FIXME CRON SYNC SETUP GOES HERE
350 350
 
351
-					/* add to the cache database schedule, replacing any schedules for this
351
+                    /* add to the cache database schedule, replacing any schedules for this
352 352
 					   calendar that are already there */
353
-					$schedulesResponse = $sql->query("
353
+                    $schedulesResponse = $sql->query("
354 354
 						SELECT *
355 355
 							FROM `schedules`
356 356
 							WHERE
357 357
 								`calendar` = '{$calendarCache['id']}'
358 358
 					");
359 359
 
360
-					if ($schedule = $schedulesResponse->fetch_assoc()) {
360
+                    if ($schedule = $schedulesResponse->fetch_assoc()) {
361 361
 
362
-						/* only need to worry if the cached schedule is different from the
362
+                        /* only need to worry if the cached schedule is different from the
363 363
 						   new one we just set */
364
-						if ($shellArguments[INDEX_SCHEDULE] != $schedule['schedule']) {
365
-							/* was this the last schedule to require this trigger? */
366
-							$schedulesResponse = $sql->query("
364
+                        if ($shellArguments[INDEX_SCHEDULE] != $schedule['schedule']) {
365
+                            /* was this the last schedule to require this trigger? */
366
+                            $schedulesResponse = $sql->query("
367 367
 								SELECT *
368 368
 									FROM `schedules`
369 369
 									WHERE
370 370
 										`calendar` != '{$calendarCache['id']}' AND
371 371
 										`schedule` == '{$schedule['schedule']}'
372 372
 							");
373
-							/* we're the last one, delete it from crontab */
374
-							if ($schedulesResponse->num_rows == 0) {
375
-								$crontabs = preg_replace("%^.*{$schedule['schedule']}.*" . PHP_EOL . '%', '', shell_exec('crontab -l'));
376
-								$filename = md5(getSyncTimestamp()) . '.txt';
377
-								file_put_contents("/tmp/$filename", $crontabs);
378
-								shell_exec("crontab /tmp/$filename");
379
-								postMessage('Unused schedule', "removed schedule '{$schedule['schedule']}' from crontab", NotificationMessage::INFO);
380
-							}
381
-
382
-							$sql->query("
373
+                            /* we're the last one, delete it from crontab */
374
+                            if ($schedulesResponse->num_rows == 0) {
375
+                                $crontabs = preg_replace("%^.*{$schedule['schedule']}.*" . PHP_EOL . '%', '', shell_exec('crontab -l'));
376
+                                $filename = md5(getSyncTimestamp()) . '.txt';
377
+                                file_put_contents("/tmp/$filename", $crontabs);
378
+                                shell_exec("crontab /tmp/$filename");
379
+                                postMessage('Unused schedule', "removed schedule '{$schedule['schedule']}' from crontab", NotificationMessage::INFO);
380
+                            }
381
+
382
+                            $sql->query("
383 383
 								UPDATE `schedules`
384 384
 									SET
385 385
 										`schedule` = '" . $shellArguments[INDEX_SCHEDULE] . "',
@@ -387,9 +387,9 @@  discard block
 block discarded – undo
387 387
 									WHERE
388 388
 										`calendar` = '{$calendarCache['id']}'
389 389
 							");
390
-						}
391
-					} else {
392
-						$sql->query("
390
+                        }
391
+                    } else {
392
+                        $sql->query("
393 393
 							INSERT INTO `schedules`
394 394
 								(
395 395
 									`calendar`,
@@ -402,46 +402,46 @@  discard block
 block discarded – undo
402 402
 									'" . getSyncTimestamp() . "'
403 403
 								)
404 404
 						");
405
-					}
406
-				}
405
+                    }
406
+                }
407 407
 
408
-				/* if we're ovewriting data (for example, if this is a recurring sync, we
408
+                /* if we're ovewriting data (for example, if this is a recurring sync, we
409 409
 				   need to remove the events that were _not_ synced this in this round */
410
-				if (isset($_REQUEST['overwrite']) && $_REQUEST['overwrite'] == VALUE_OVERWRITE_CANVAS_CALENDAR) {
411
-					// TODO: actually deal with this
412
-				}
413
-
414
-				// TODO: deal with messaging based on context
415
-
416
-				postMessage('Finished sync', getSyncTimestamp(), NotificationMessage::INFO);
417
-				exit;
418
-			} else {
419
-				postMessage(
420
-					'Canvas Object  Not Found',
421
-					'The object whose URL you submitted could not be found.<pre>' . print_r(array(
422
-						'Canvas URL' => $_REQUEST['canvas_url'],
423
-						'Canvas Context' => $canvasContext,
424
-						'Canvas Object' => $canvasObject
425
-					), false) . '</pre>',
426
-					NotificationMessage::ERROR
427
-				);
428
-			}
429
-		} else {
430
-			postMessage(
431
-				'ICS feed  Not Found',
432
-				'The calendar whose URL you submitted could not be found.<pre>' . $_REQUEST['cal'] . '</pre>',
433
-				NotificationMessage::ERROR
434
-			);
435
-		}
436
-	} else {
437
-		postMessage(
438
-			'Invalid Canvas URL',
439
-			'The Canvas URL you submitted could not be parsed.<pre>' . $_REQUEST['canvas_url'] . '</pre>',
440
-			NotificationMessage::ERROR
441
-		);
442
-		if (php_sapi_name() != 'cli') $smarty->display('page.tpl');
443
-		exit;
444
-	}
410
+                if (isset($_REQUEST['overwrite']) && $_REQUEST['overwrite'] == VALUE_OVERWRITE_CANVAS_CALENDAR) {
411
+                    // TODO: actually deal with this
412
+                }
413
+
414
+                // TODO: deal with messaging based on context
415
+
416
+                postMessage('Finished sync', getSyncTimestamp(), NotificationMessage::INFO);
417
+                exit;
418
+            } else {
419
+                postMessage(
420
+                    'Canvas Object  Not Found',
421
+                    'The object whose URL you submitted could not be found.<pre>' . print_r(array(
422
+                        'Canvas URL' => $_REQUEST['canvas_url'],
423
+                        'Canvas Context' => $canvasContext,
424
+                        'Canvas Object' => $canvasObject
425
+                    ), false) . '</pre>',
426
+                    NotificationMessage::ERROR
427
+                );
428
+            }
429
+        } else {
430
+            postMessage(
431
+                'ICS feed  Not Found',
432
+                'The calendar whose URL you submitted could not be found.<pre>' . $_REQUEST['cal'] . '</pre>',
433
+                NotificationMessage::ERROR
434
+            );
435
+        }
436
+    } else {
437
+        postMessage(
438
+            'Invalid Canvas URL',
439
+            'The Canvas URL you submitted could not be parsed.<pre>' . $_REQUEST['canvas_url'] . '</pre>',
440
+            NotificationMessage::ERROR
441
+        );
442
+        if (php_sapi_name() != 'cli') $smarty->display('page.tpl');
443
+        exit;
444
+    }
445 445
 }
446 446
 
447 447
 ?>
Please login to merge, or discard this patch.