Completed
Push — develop ( 5bc2b0...db625e )
by Seth
04:17
created
classes/CanvasAPIviaLTI_Installer.php 3 patches
Doc Comments   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -20,7 +20,7 @@  discard block
 block discarded – undo
20 20
 	/**
21 21
 	 * Generate a SECRETS_FILE from user input.
22 22
 	 *
23
-	 * @param scalar $step optional Where are we in the SECRETS_FILE creation workflow? (defaults to SECRETS_NEEDED_STEP -- the beginning)
23
+	 * @param integer $step optional Where are we in the SECRETS_FILE creation workflow? (defaults to SECRETS_NEEDED_STEP -- the beginning)
24 24
 	 *
25 25
 	 * @throws CanvasAPIviaLTI_Installer_Exception If form submission does not contain all required MySQL credentals (host, username, password and database)
26 26
 	 * @throws CanvasAPIviaLTI_Installer_Exception If SECRETS_FILE cannot be created
@@ -261,7 +261,7 @@  discard block
 block discarded – undo
261 261
 	/**
262 262
 	 * Obtain a Canvas API token, if needed.
263 263
 	 *
264
-	 * @param scalar $step optional Where are we in the API token negotiation workflow? (defaults to API_DECISION_NEEDED_STEP -- the beginning)
264
+	 * @param integer $step optional Where are we in the API token negotiation workflow? (defaults to API_DECISION_NEEDED_STEP -- the beginning)
265 265
 	 * @param boolean $skip optional Skip this step (defaults to FALSE)
266 266
 	 *
267 267
 	 * @throws CanvasAPIviaLTI_Installer_Exception If $step is not a pre-defined *_STEP constant
Please login to merge, or discard this patch.
Indentation   +277 added lines, -277 removed lines patch added patch discarded remove patch
@@ -11,28 +11,28 @@  discard block
 block discarded – undo
11 11
  * @author Seth Battis <[email protected]>
12 12
  **/	
13 13
 class CanvasAPIviaLTI_Installer {
14
-	const SECRETS_NEEDED_STEP = 1;
15
-	const SECRETS_ENTERED_STEP = 2;
16
-	const API_DECISION_NEEDED_STEP = 3;
17
-	const API_DECISION_ENTERED_STEP = 4;
18
-	const API_TOKEN_PROVIDED_STEP = 5;
14
+    const SECRETS_NEEDED_STEP = 1;
15
+    const SECRETS_ENTERED_STEP = 2;
16
+    const API_DECISION_NEEDED_STEP = 3;
17
+    const API_DECISION_ENTERED_STEP = 4;
18
+    const API_TOKEN_PROVIDED_STEP = 5;
19 19
 		
20
-	/**
21
-	 * Generate a SECRETS_FILE from user input.
22
-	 *
23
-	 * @param scalar $step optional Where are we in the SECRETS_FILE creation workflow? (defaults to SECRETS_NEEDED_STEP -- the beginning)
24
-	 *
25
-	 * @throws CanvasAPIviaLTI_Installer_Exception If form submission does not contain all required MySQL credentals (host, username, password and database)
26
-	 * @throws CanvasAPIviaLTI_Installer_Exception If SECRETS_FILE cannot be created
27
-	 * @throws CanvasAPIviaLTI_Installer_Exception If $step is not a pre-defined *_STEP constant
28
-	 **/
29
-	public static function createSecretsFile($step = self::SECRETS_NEEDED_STEP) {
30
-		global $smarty; // FIXME:0 grown-ups don't program like this issue:17
20
+    /**
21
+     * Generate a SECRETS_FILE from user input.
22
+     *
23
+     * @param scalar $step optional Where are we in the SECRETS_FILE creation workflow? (defaults to SECRETS_NEEDED_STEP -- the beginning)
24
+     *
25
+     * @throws CanvasAPIviaLTI_Installer_Exception If form submission does not contain all required MySQL credentals (host, username, password and database)
26
+     * @throws CanvasAPIviaLTI_Installer_Exception If SECRETS_FILE cannot be created
27
+     * @throws CanvasAPIviaLTI_Installer_Exception If $step is not a pre-defined *_STEP constant
28
+     **/
29
+    public static function createSecretsFile($step = self::SECRETS_NEEDED_STEP) {
30
+        global $smarty; // FIXME:0 grown-ups don't program like this issue:17
31 31
 		
32
-		switch ($step) {
33
-			case self::SECRETS_NEEDED_STEP: {
34
-				// FIXME:0 passwords in clear text? oy. issue:17
35
-				$smarty->assign('content', '
32
+        switch ($step) {
33
+            case self::SECRETS_NEEDED_STEP: {
34
+                // FIXME:0 passwords in clear text? oy. issue:17
35
+                $smarty->assign('content', '
36 36
 					<form action="' . $_SERVER['PHP_SELF'] . '" method="post">
37 37
 						<section>
38 38
 							<h3>Application Information</h3>
@@ -57,242 +57,242 @@  discard block
 block discarded – undo
57 57
 						<input type="submit" value="Create Secrets File" />
58 58
 					</form>
59 59
 				');
60
-				$smarty->display();
61
-				exit;
62
-			}
60
+                $smarty->display();
61
+                exit;
62
+            }
63 63
 			
64
-			case self::SECRETS_ENTERED_STEP: {
65
-				if (isset($_REQUEST['name']) && isset($_REQUEST['id']) && isset($_REQUEST['admin_username']) && isset($_REQUEST['admin_password'])) {
66
-					if (isset($_REQUEST['host']) && isset($_REQUEST['username']) && isset($_REQUEST['password']) && isset($_REQUEST['database'])) {
67
-						$secrets = new SimpleXMLElement('<secrets />');
68
-						$app = $secrets->addChild('app');
69
-						$app->addChild('name', $_REQUEST['name']);
70
-						$app->addChild('id', $_REQUEST['id']);
71
-						$admin = $app->addChild('admin');
72
-						$admin->addChild('username', $_REQUEST['admin_username']);
73
-						$admin->addChild('password', $_REQUEST['admin_password']);
74
-						$mysql = $secrets->addChild('mysql');
75
-						$mysql->addChild('host', $_REQUEST['host']);
76
-						$mysql->addChild('username', $_REQUEST['username']);
77
-						$mysql->addChild('password', $_REQUEST['password']);
78
-						$mysql->addChild('database', $_REQUEST['database']);
79
-						$oauth = $secrets->addChild('oauth');
80
-						$oauth->addChild('id', $_REQUEST['oauth_id']);
81
-						$oauth->addChild('key', $_REQUEST['oauth_key']);
82
-						if ($secrets->asXML(SECRETS_FILE) == false) {
83
-							throw new CanvasAPIviaLTI_Exception(
84
-								'Failed to create ' . SECRETS_FILE,
85
-								CanvasAPIviaLTI_Installer_Exception::SECRETS_FILE_CREATION
86
-							);
87
-						}
64
+            case self::SECRETS_ENTERED_STEP: {
65
+                if (isset($_REQUEST['name']) && isset($_REQUEST['id']) && isset($_REQUEST['admin_username']) && isset($_REQUEST['admin_password'])) {
66
+                    if (isset($_REQUEST['host']) && isset($_REQUEST['username']) && isset($_REQUEST['password']) && isset($_REQUEST['database'])) {
67
+                        $secrets = new SimpleXMLElement('<secrets />');
68
+                        $app = $secrets->addChild('app');
69
+                        $app->addChild('name', $_REQUEST['name']);
70
+                        $app->addChild('id', $_REQUEST['id']);
71
+                        $admin = $app->addChild('admin');
72
+                        $admin->addChild('username', $_REQUEST['admin_username']);
73
+                        $admin->addChild('password', $_REQUEST['admin_password']);
74
+                        $mysql = $secrets->addChild('mysql');
75
+                        $mysql->addChild('host', $_REQUEST['host']);
76
+                        $mysql->addChild('username', $_REQUEST['username']);
77
+                        $mysql->addChild('password', $_REQUEST['password']);
78
+                        $mysql->addChild('database', $_REQUEST['database']);
79
+                        $oauth = $secrets->addChild('oauth');
80
+                        $oauth->addChild('id', $_REQUEST['oauth_id']);
81
+                        $oauth->addChild('key', $_REQUEST['oauth_key']);
82
+                        if ($secrets->asXML(SECRETS_FILE) == false) {
83
+                            throw new CanvasAPIviaLTI_Exception(
84
+                                'Failed to create ' . SECRETS_FILE,
85
+                                CanvasAPIviaLTI_Installer_Exception::SECRETS_FILE_CREATION
86
+                            );
87
+                        }
88 88
 						
89
-						$htpasswdFile = __DIR__ . '/.htpasswd';
90
-						shell_exec("htpasswd -bc $htpasswdFile {$_REQUEST['admin_username']} {$_REQUEST['admin_password']}");
91
-						if (!file_exists($htpasswdFile)) {
92
-							throw new CanvasAPIviaLTI_Installer_Exception(
93
-								"Failed to create $htpasswdFile",
94
-								CanvasAPIviaLTI_Installer_Exception::HTPASSWD_FILE
95
-							);
96
-						}
89
+                        $htpasswdFile = __DIR__ . '/.htpasswd';
90
+                        shell_exec("htpasswd -bc $htpasswdFile {$_REQUEST['admin_username']} {$_REQUEST['admin_password']}");
91
+                        if (!file_exists($htpasswdFile)) {
92
+                            throw new CanvasAPIviaLTI_Installer_Exception(
93
+                                "Failed to create $htpasswdFile",
94
+                                CanvasAPIviaLTI_Installer_Exception::HTPASSWD_FILE
95
+                            );
96
+                        }
97 97
 						
98
-						$htaccessFile = __DIR__ . '/.htaccess';
99
-						if(!file_put_contents($htaccessFile, "AuthType Basic\nAuthName \"{$secrets->app->name} Admin\"\nAuthUserFile $htpasswdFile\nRequire valid-user\n")) {
100
-							throw new CanvasAPIviaLTI_Installer_Exception(
101
-								"Failed to create $htaccessFile",
102
-								CanvasAPIviaLTI_Installer_Exception::HTACCESS_FILE
103
-							);
104
-						}
105
-					} else {
106
-						throw new CanvasAPIviaLTI_Installer_Exception(
107
-							'Missing a required mysql credential (host, username, password and database all required).',
108
-							CanvasAPIviaLTI_Installer_Exception::SECRETS_FILE_MYSQL
109
-						);
110
-					}
111
-					$smarty->addMessage(
112
-						'Secrets file created',
113
-						"<code>secrets.xml</code> contains your authentication credentials and
98
+                        $htaccessFile = __DIR__ . '/.htaccess';
99
+                        if(!file_put_contents($htaccessFile, "AuthType Basic\nAuthName \"{$secrets->app->name} Admin\"\nAuthUserFile $htpasswdFile\nRequire valid-user\n")) {
100
+                            throw new CanvasAPIviaLTI_Installer_Exception(
101
+                                "Failed to create $htaccessFile",
102
+                                CanvasAPIviaLTI_Installer_Exception::HTACCESS_FILE
103
+                            );
104
+                        }
105
+                    } else {
106
+                        throw new CanvasAPIviaLTI_Installer_Exception(
107
+                            'Missing a required mysql credential (host, username, password and database all required).',
108
+                            CanvasAPIviaLTI_Installer_Exception::SECRETS_FILE_MYSQL
109
+                        );
110
+                    }
111
+                    $smarty->addMessage(
112
+                        'Secrets file created',
113
+                        "<code>secrets.xml</code> contains your authentication credentials and
114 114
 						 should be carefully protected. Be sure not to commit it to a public
115 115
 						 repository!",
116
-						NotificationMessage::GOOD
117
-					);
118
-				} else {
119
-					throw new CanvasAPIviaLTI_Installer_Exception(
120
-						'Missing a required app identity (name, id, admin username and admin password all required).',
121
-						CanvasAPIviaLTI_Installer_Exception::SECRETS_FILE_APP
122
-					);
123
-				}
116
+                        NotificationMessage::GOOD
117
+                    );
118
+                } else {
119
+                    throw new CanvasAPIviaLTI_Installer_Exception(
120
+                        'Missing a required app identity (name, id, admin username and admin password all required).',
121
+                        CanvasAPIviaLTI_Installer_Exception::SECRETS_FILE_APP
122
+                    );
123
+                }
124 124
 				
125
-				/* clear the processed step */
126
-				unset($_REQUEST['step']);
125
+                /* clear the processed step */
126
+                unset($_REQUEST['step']);
127 127
 
128
-				break;
129
-			}
128
+                break;
129
+            }
130 130
 			
131
-			default: {
132
-				throw new CanvasAPIviaLTI_Installer_Exception(
133
-					"Unknown step ($step) in SECRETS_FILE creation.",
134
-					CanvasAPIviaLTI_Installer_Exception::SECRETS_NEEDED_STEP
135
-				);
136
-			}
137
-		}
138
-	}
131
+            default: {
132
+                throw new CanvasAPIviaLTI_Installer_Exception(
133
+                    "Unknown step ($step) in SECRETS_FILE creation.",
134
+                    CanvasAPIviaLTI_Installer_Exception::SECRETS_NEEDED_STEP
135
+                );
136
+            }
137
+        }
138
+    }
139 139
 	
140
-	/**
141
-	 * Create database tables to back LTI_Tool_Provider
142
-	 *
143
-	 * @throws CanvasAPIviaLTI_Installer_Exception If database schema not found in vendors directory
144
-	 * @throws CanvasAPIviaLTI_Installer_Exception If database tables are not created
145
-	 **/
146
-	public static function createLTIDatabaseTables() {
147
-		global $sql; // FIXME:0 grown-ups don't program like this issue:17
148
-		global $smarty; // FIXME:0 grown-ups don't program like this issue:17
140
+    /**
141
+     * Create database tables to back LTI_Tool_Provider
142
+     *
143
+     * @throws CanvasAPIviaLTI_Installer_Exception If database schema not found in vendors directory
144
+     * @throws CanvasAPIviaLTI_Installer_Exception If database tables are not created
145
+     **/
146
+    public static function createLTIDatabaseTables() {
147
+        global $sql; // FIXME:0 grown-ups don't program like this issue:17
148
+        global $smarty; // FIXME:0 grown-ups don't program like this issue:17
149 149
 		
150
-		$ltiSchema = realpath(__DIR__ . '/../vendor/spvsoftwareproducts/LTI_Tool_Provider/lti-tables-mysql.sql');
150
+        $ltiSchema = realpath(__DIR__ . '/../vendor/spvsoftwareproducts/LTI_Tool_Provider/lti-tables-mysql.sql');
151 151
 		
152
-		if ($sql->query("SHOW TABLES LIKE 'lti_%'")->num_rows >= 5) {
153
-			$smarty->addMessage('LTI database tables exist', 'Database tables to support the LTI Tool Provider (TP) already exist and have not been re-created.');
154
-		} elseif (file_exists($ltiSchema)) {
155
-			$queries = explode(";", file_get_contents($ltiSchema));
156
-			$created = true;
157
-			foreach($queries as $query) {
158
-				if (!empty(trim($query))) {
159
-					if (!$sql->query($query)) {
160
-						throw new CanvasAPIviaLTI_Installer_Exception(
161
-							"Error creating LTI database tables: {$sql->error}",
162
-							CanvasAPIviaLTI_Installer_Exception::LTI_PREPARE_DATABASE
163
-						);
164
-					}
165
-				}
166
-			}
152
+        if ($sql->query("SHOW TABLES LIKE 'lti_%'")->num_rows >= 5) {
153
+            $smarty->addMessage('LTI database tables exist', 'Database tables to support the LTI Tool Provider (TP) already exist and have not been re-created.');
154
+        } elseif (file_exists($ltiSchema)) {
155
+            $queries = explode(";", file_get_contents($ltiSchema));
156
+            $created = true;
157
+            foreach($queries as $query) {
158
+                if (!empty(trim($query))) {
159
+                    if (!$sql->query($query)) {
160
+                        throw new CanvasAPIviaLTI_Installer_Exception(
161
+                            "Error creating LTI database tables: {$sql->error}",
162
+                            CanvasAPIviaLTI_Installer_Exception::LTI_PREPARE_DATABASE
163
+                        );
164
+                    }
165
+                }
166
+            }
167 167
 			
168
-			$smarty->addMessage(
169
-				'LTI database tables created',
170
-				'Database tables to support the LTI Tool Provider (TP) have been created in
168
+            $smarty->addMessage(
169
+                'LTI database tables created',
170
+                'Database tables to support the LTI Tool Provider (TP) have been created in
171 171
 				 your MySQL database.',
172
-				NotificationMessage::GOOD
173
-			);
174
-		} else {
175
-			throw new CanvasAPIviaLTI_Exception("$ltiSchema not found.");
176
-		}
177
-	}
172
+                NotificationMessage::GOOD
173
+            );
174
+        } else {
175
+            throw new CanvasAPIviaLTI_Exception("$ltiSchema not found.");
176
+        }
177
+    }
178 178
 	
179
-	/**
180
-	 * Create database tables to back app
181
-	 *
182
-	 * @throws CanvasAPIviaLTI_Installer_Exception If database tables are not created
183
-	 **/
184
-	public static function createAppDatabaseTables() {
185
-		global $sql; // FIXME:0 grown-ups don't program like this issue:17
186
-		global $smarty; // FIXME:0 grown-ups don't program like this issue:17
179
+    /**
180
+     * Create database tables to back app
181
+     *
182
+     * @throws CanvasAPIviaLTI_Installer_Exception If database tables are not created
183
+     **/
184
+    public static function createAppDatabaseTables() {
185
+        global $sql; // FIXME:0 grown-ups don't program like this issue:17
186
+        global $smarty; // FIXME:0 grown-ups don't program like this issue:17
187 187
 		
188
-		if (file_exists(SCHEMA_FILE)) {
189
-			$queries = explode(";", file_get_contents(SCHEMA_FILE));
190
-			$created = true;
191
-			foreach ($queries as $query) {
192
-				if (!empty(trim($query))) {
193
-					if (preg_match('/CREATE\s+TABLE\s+(`([^`]+)`|\w+)/i', $query, $tableName)) {
194
-						$tableName = (empty($tableName[2]) ? $tableName[1] : $tableName[2]);
195
-						if ($sql->query("SHOW TABLES LIKE '$tableName'")->num_rows > 0) {
196
-							$created = false;
197
-						} else {
198
-							if (!$sql->query($query)) {
199
-								throw new CanvasAPIviaLTI_Installer_Exception(
200
-									"Error creating app database tables: {$sql->error}",
201
-									CanvasAPIviaLTI_Installer_Exception::APP_CREATE_TABLE
202
-								);
203
-							}
204
-						}
205
-					} else {
206
-						if (!$sql->query($query)) {
207
-							throw new CanvasAPIviaLTI_Installer_Exception(
208
-								"Error creating app database tables: {$sql->error}",
209
-								CanvasAPIviaLTI_Installer_Exception::APP_PREPARE_DATABASE
210
-							);
211
-						}
212
-					}
213
-				}
214
-			}
188
+        if (file_exists(SCHEMA_FILE)) {
189
+            $queries = explode(";", file_get_contents(SCHEMA_FILE));
190
+            $created = true;
191
+            foreach ($queries as $query) {
192
+                if (!empty(trim($query))) {
193
+                    if (preg_match('/CREATE\s+TABLE\s+(`([^`]+)`|\w+)/i', $query, $tableName)) {
194
+                        $tableName = (empty($tableName[2]) ? $tableName[1] : $tableName[2]);
195
+                        if ($sql->query("SHOW TABLES LIKE '$tableName'")->num_rows > 0) {
196
+                            $created = false;
197
+                        } else {
198
+                            if (!$sql->query($query)) {
199
+                                throw new CanvasAPIviaLTI_Installer_Exception(
200
+                                    "Error creating app database tables: {$sql->error}",
201
+                                    CanvasAPIviaLTI_Installer_Exception::APP_CREATE_TABLE
202
+                                );
203
+                            }
204
+                        }
205
+                    } else {
206
+                        if (!$sql->query($query)) {
207
+                            throw new CanvasAPIviaLTI_Installer_Exception(
208
+                                "Error creating app database tables: {$sql->error}",
209
+                                CanvasAPIviaLTI_Installer_Exception::APP_PREPARE_DATABASE
210
+                            );
211
+                        }
212
+                    }
213
+                }
214
+            }
215 215
 			
216
-			if ($created) {
217
-				$smarty->addMessage(
218
-					'App database tables created',
219
-					'Database tables to support the application have been created in your
216
+            if ($created) {
217
+                $smarty->addMessage(
218
+                    'App database tables created',
219
+                    'Database tables to support the application have been created in your
220 220
 					 MySQL database.',
221
-					NotificationMessage::GOOD
222
-				);
223
-			} else {
224
-				$smarty->addMessage(
225
-					'App database tables exist',
226
-					'Database tables to support the application already exist and have not
221
+                    NotificationMessage::GOOD
222
+                );
223
+            } else {
224
+                $smarty->addMessage(
225
+                    'App database tables exist',
226
+                    'Database tables to support the application already exist and have not
227 227
 					 been re-created.'
228
-				);
229
-			}
230
-		}
231
-	}
228
+                );
229
+            }
230
+        }
231
+    }
232 232
 	
233
-	/**
234
-	 * Initialize the app metadata store, especially the APP_PATH and APP_URL
235
-	 *
236
-	 * @return AppMetadata
237
-	 **/
238
-	public static function createAppMetadata() {
239
-		global $secrets; // FIXME:0 grown-ups don't program like this issue:17
240
-		global $sql; // FIXME:0 grown-ups don't program like this issue:17
241
-		global $metadata; // FIXME:0 grown-ups don't program like this issue:17
242
-		global $smarty; // FIXME:0 grown-ups don't program like this issue:17
233
+    /**
234
+     * Initialize the app metadata store, especially the APP_PATH and APP_URL
235
+     *
236
+     * @return AppMetadata
237
+     **/
238
+    public static function createAppMetadata() {
239
+        global $secrets; // FIXME:0 grown-ups don't program like this issue:17
240
+        global $sql; // FIXME:0 grown-ups don't program like this issue:17
241
+        global $metadata; // FIXME:0 grown-ups don't program like this issue:17
242
+        global $smarty; // FIXME:0 grown-ups don't program like this issue:17
243 243
 				
244
-		$metadata = initAppMetadata();
245
-		$metadata['APP_PATH'] = preg_replace('/\/classes$/', '', __DIR__);
246
-		$metadata['APP_URL'] = (!isset($_SERVER['HTTPS']) || $_SERVER['HTTPS'] != 'on' ? 'http://' : 'https://') . $_SERVER['SERVER_NAME'] . preg_replace("|^{$_SERVER['DOCUMENT_ROOT']}(.*)$|", '$1', $metadata['APP_PATH']);
247
-		$metadata['APP_NAME'] = (string) $secrets->app->name;
248
-		$metadata['APP_ID'] = (string) $secrets->app->id;
249
-		$metadata['CANVAS_INSTANCE_URL_PLACEHOLDER'] = 'https://canvas.instructure.com';
250
-		$smarty->assign('metadata', $metadata);
244
+        $metadata = initAppMetadata();
245
+        $metadata['APP_PATH'] = preg_replace('/\/classes$/', '', __DIR__);
246
+        $metadata['APP_URL'] = (!isset($_SERVER['HTTPS']) || $_SERVER['HTTPS'] != 'on' ? 'http://' : 'https://') . $_SERVER['SERVER_NAME'] . preg_replace("|^{$_SERVER['DOCUMENT_ROOT']}(.*)$|", '$1', $metadata['APP_PATH']);
247
+        $metadata['APP_NAME'] = (string) $secrets->app->name;
248
+        $metadata['APP_ID'] = (string) $secrets->app->id;
249
+        $metadata['CANVAS_INSTANCE_URL_PLACEHOLDER'] = 'https://canvas.instructure.com';
250
+        $smarty->assign('metadata', $metadata);
251 251
 
252
-		$smarty->addMessage(
253
-			'App metadata initialized',
254
-			'Basic application metadata has been updated, including APP_PATH and APP_URL',
255
-			NotificationMessage::GOOD
256
-		);
252
+        $smarty->addMessage(
253
+            'App metadata initialized',
254
+            'Basic application metadata has been updated, including APP_PATH and APP_URL',
255
+            NotificationMessage::GOOD
256
+        );
257 257
 		
258
-		return $metadata;
259
-	}
258
+        return $metadata;
259
+    }
260 260
 	
261
-	/**
262
-	 * Obtain a Canvas API token, if needed.
263
-	 *
264
-	 * @param scalar $step optional Where are we in the API token negotiation workflow? (defaults to API_DECISION_NEEDED_STEP -- the beginning)
265
-	 * @param boolean $skip optional Skip this step (defaults to FALSE)
266
-	 *
267
-	 * @throws CanvasAPIviaLTI_Installer_Exception If $step is not a pre-defined *_STEP constant
268
-	 **/
269
-	public static function acquireAPIToken($step = self::API_DECISION_NEEDED_STEP, $skip = false) {
270
-		global $secrets; // FIXME:0 grown-ups don't program like this issue:17
271
-		global $metadata; // FIXME:0 grown-ups don't program like this issue:17
272
-		global $smarty; // FIXME:0 grown-ups don't program like this issue:17
261
+    /**
262
+     * Obtain a Canvas API token, if needed.
263
+     *
264
+     * @param scalar $step optional Where are we in the API token negotiation workflow? (defaults to API_DECISION_NEEDED_STEP -- the beginning)
265
+     * @param boolean $skip optional Skip this step (defaults to FALSE)
266
+     *
267
+     * @throws CanvasAPIviaLTI_Installer_Exception If $step is not a pre-defined *_STEP constant
268
+     **/
269
+    public static function acquireAPIToken($step = self::API_DECISION_NEEDED_STEP, $skip = false) {
270
+        global $secrets; // FIXME:0 grown-ups don't program like this issue:17
271
+        global $metadata; // FIXME:0 grown-ups don't program like this issue:17
272
+        global $smarty; // FIXME:0 grown-ups don't program like this issue:17
273 273
 		
274
-		if ($skip) {
275
-			if (isset($metadata['CANVAS_API_TOKEN']) || isset($metadata['CANVAS_API_USER'])) {
276
-				$api = new CanvasPest("{$metadata['CANVAS_INSTANCE_URL']}/login/oauth2", $metadata['CANVAS_API_TOKEN']);
277
-				$api->delete('token');
278
-				unset($metadata['CANVAS_API_TOKEN']);
279
-				unset($metadata['CANVAS_API_USER']);
280
-				$smarty->addMessage(
281
-					'Existing admin Canvas API token information expunged',
282
-					'There was already an administrative access token stored in your
274
+        if ($skip) {
275
+            if (isset($metadata['CANVAS_API_TOKEN']) || isset($metadata['CANVAS_API_USER'])) {
276
+                $api = new CanvasPest("{$metadata['CANVAS_INSTANCE_URL']}/login/oauth2", $metadata['CANVAS_API_TOKEN']);
277
+                $api->delete('token');
278
+                unset($metadata['CANVAS_API_TOKEN']);
279
+                unset($metadata['CANVAS_API_USER']);
280
+                $smarty->addMessage(
281
+                    'Existing admin Canvas API token information expunged',
282
+                    'There was already an administrative access token stored in your
283 283
 					 application metadata, and it has now been expunged.'
284
-				);
285
-			} else {
286
-				$smarty->addMessage(
287
-					'No admin Canvas API token acquired',
288
-					'An administrative API token has not been acquired. Users will be asked to
284
+                );
285
+            } else {
286
+                $smarty->addMessage(
287
+                    'No admin Canvas API token acquired',
288
+                    'An administrative API token has not been acquired. Users will be asked to
289 289
 					 acquire their own API tokens on their first use of the LTI.'
290
-				);
291
-			}
292
-		} else {
293
-			switch ($step) {
294
-				case self::API_DECISION_NEEDED_STEP: {
295
-					$smarty->assign('content', '
290
+                );
291
+            }
292
+        } else {
293
+            switch ($step) {
294
+                case self::API_DECISION_NEEDED_STEP: {
295
+                    $smarty->assign('content', '
296 296
 						<form action="' . $metadata['APP_URL'] . '/admin/oauth.php" method="post">
297 297
 							<label for="url"> Canvas Instance URL <input type="text" name="url" id="url" placeholder="' . $metadata['CANVAS_INSTANCE_URL_PLACEHOLDER'] . '" value="' . (isset($metadata['CANVAS_INSTANCE_URL']) ? $metadata['CANVAS_INSTANCE_URL'] : '') . '" /></label>
298 298
 							<label for="token"> API Access Token <input type="text" name="token" id="token" placeholder="Leave blank to acquire a token interactively" /></label>
@@ -307,43 +307,43 @@  discard block
 block discarded – undo
307 307
 							<input type="submit" value="Require users to acquire individual tokens" />
308 308
 						</form>
309 309
 					');
310
-					$smarty->display();
311
-					exit;
312
-				}
313
-				case self::API_DECISION_ENTERED_STEP: {
314
-					$oauth = new OAuthNegotiator();
310
+                    $smarty->display();
311
+                    exit;
312
+                }
313
+                case self::API_DECISION_ENTERED_STEP: {
314
+                    $oauth = new OAuthNegotiator();
315 315
 					
316
-					if ($oauth->isAPIToken()) {
317
-						$metadata['CANVAS_API_TOKEN'] = $oauth->getToken();
316
+                    if ($oauth->isAPIToken()) {
317
+                        $metadata['CANVAS_API_TOKEN'] = $oauth->getToken();
318 318
 						
319
-						$smarty->addMessage(
320
-							'Admin Canvas API token acquired',
321
-							'An administrative API access token has been acquired and stored in your application metadata.',
322
-							NotificationMessage::GOOD
323
-						);
324
-					}
319
+                        $smarty->addMessage(
320
+                            'Admin Canvas API token acquired',
321
+                            'An administrative API access token has been acquired and stored in your application metadata.',
322
+                            NotificationMessage::GOOD
323
+                        );
324
+                    }
325 325
 					
326
-					/* clear the processed step */
327
-					unset($_REQUEST['step']);
326
+                    /* clear the processed step */
327
+                    unset($_REQUEST['step']);
328 328
 					
329
-					break;
330
-				}
331
-				case self::API_TOKEN_PROVIDED_STEP: {
332
-					$smarty->addMessage(
333
-						'Admin Canvas API token provided',
334
-						'You provided an API access token and it has been stored in your application metadata.' 
335
-					);
336
-					break;
337
-				}
338
-				default: {
339
-					throw new CanvasAPIviaLTI_Installer_Exception(
340
-						"Unknown step ($step) in obtaining API token.",
341
-						CanvasAPIviaLTI_Installer_Exception::API_STEP_MISMATCH
342
-					);
343
-				}
344
-			}
345
-		}
346
-	}
329
+                    break;
330
+                }
331
+                case self::API_TOKEN_PROVIDED_STEP: {
332
+                    $smarty->addMessage(
333
+                        'Admin Canvas API token provided',
334
+                        'You provided an API access token and it has been stored in your application metadata.' 
335
+                    );
336
+                    break;
337
+                }
338
+                default: {
339
+                    throw new CanvasAPIviaLTI_Installer_Exception(
340
+                        "Unknown step ($step) in obtaining API token.",
341
+                        CanvasAPIviaLTI_Installer_Exception::API_STEP_MISMATCH
342
+                    );
343
+                }
344
+            }
345
+        }
346
+    }
347 347
 }
348 348
 
349 349
 /**
@@ -352,20 +352,20 @@  discard block
 block discarded – undo
352 352
  * @author Seth Battis <[email protected]>
353 353
  **/
354 354
 class CanvasAPIviaLTI_Installer_Exception extends CanvasAPIviaLTI_Exception {
355
-	const SECRETS_FILE_CREATION = 1;
356
-	const SECRETS_FILE_APP = 2;
357
-	const SECRETS_FILE_MYSQL = 3;
358
-	const LTI_SCHEMA = 4;
359
-	const LTI_PREPARE_DATABASE = 5;
360
-	const LTI_CREATE_TABLE = 6;
361
-	const APP_SCHEMA = 7;
362
-	const APP_PREPARE_DATABASE = 8;
363
-	const APP_CREATE_TABLE = 9;
364
-	const API_STEP_MISMATCH = 10;
365
-	const API_URL = 14;
366
-	const API_TOKEN = 11;
367
-	const HTPASSWD_FILE = 12;
368
-	const HTACCESS_FILE = 13;
355
+    const SECRETS_FILE_CREATION = 1;
356
+    const SECRETS_FILE_APP = 2;
357
+    const SECRETS_FILE_MYSQL = 3;
358
+    const LTI_SCHEMA = 4;
359
+    const LTI_PREPARE_DATABASE = 5;
360
+    const LTI_CREATE_TABLE = 6;
361
+    const APP_SCHEMA = 7;
362
+    const APP_PREPARE_DATABASE = 8;
363
+    const APP_CREATE_TABLE = 9;
364
+    const API_STEP_MISMATCH = 10;
365
+    const API_URL = 14;
366
+    const API_TOKEN = 11;
367
+    const HTPASSWD_FILE = 12;
368
+    const HTACCESS_FILE = 13;
369 369
 }
370 370
 
371 371
 ?>
372 372
\ No newline at end of file
Please login to merge, or discard this patch.
Spacing   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -96,7 +96,7 @@  discard block
 block discarded – undo
96 96
 						}
97 97
 						
98 98
 						$htaccessFile = __DIR__ . '/.htaccess';
99
-						if(!file_put_contents($htaccessFile, "AuthType Basic\nAuthName \"{$secrets->app->name} Admin\"\nAuthUserFile $htpasswdFile\nRequire valid-user\n")) {
99
+						if (!file_put_contents($htaccessFile, "AuthType Basic\nAuthName \"{$secrets->app->name} Admin\"\nAuthUserFile $htpasswdFile\nRequire valid-user\n")) {
100 100
 							throw new CanvasAPIviaLTI_Installer_Exception(
101 101
 								"Failed to create $htaccessFile",
102 102
 								CanvasAPIviaLTI_Installer_Exception::HTACCESS_FILE
@@ -154,7 +154,7 @@  discard block
 block discarded – undo
154 154
 		} elseif (file_exists($ltiSchema)) {
155 155
 			$queries = explode(";", file_get_contents($ltiSchema));
156 156
 			$created = true;
157
-			foreach($queries as $query) {
157
+			foreach ($queries as $query) {
158 158
 				if (!empty(trim($query))) {
159 159
 					if (!$sql->query($query)) {
160 160
 						throw new CanvasAPIviaLTI_Installer_Exception(
Please login to merge, or discard this patch.
classes/UserAPIToken.php 3 patches
Doc Comments   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -91,7 +91,7 @@  discard block
 block discarded – undo
91 91
 	}
92 92
 	
93 93
 	/**
94
-	 * @return string|boolean The API access token for this user, or FALSE if no token has been acquired
94
+	 * @return string|false The API access token for this user, or FALSE if no token has been acquired
95 95
 	 **/
96 96
 	public function getToken() {
97 97
 		if ($this->token) {
@@ -133,7 +133,7 @@  discard block
 block discarded – undo
133 133
 	}
134 134
 	
135 135
 	/**
136
-	 * @return string|boolean The URL of the API for which the user's API token is valid, or FALSE if no token has been acquired
136
+	 * @return string|false The URL of the API for which the user's API token is valid, or FALSE if no token has been acquired
137 137
 	 **/
138 138
 	function getAPIUrl() {
139 139
 		if ($this->apiUrl) {
Please login to merge, or discard this patch.
Indentation   +152 added lines, -152 removed lines patch added patch discarded remove patch
@@ -8,170 +8,170 @@  discard block
 block discarded – undo
8 8
  **/
9 9
 class UserAPIToken {
10 10
 
11
-	const USER_TOKENS_TABLE = 'user_tokens';
11
+    const USER_TOKENS_TABLE = 'user_tokens';
12 12
 	
13
-	/**
14
-	 * @var string $consumerKey The unique ID of the tool consumer from whence the user is making requests to the LTI
15
-	 **/	
16
-	private $consumerKey;
13
+    /**
14
+     * @var string $consumerKey The unique ID of the tool consumer from whence the user is making requests to the LTI
15
+     **/	
16
+    private $consumerKey;
17 17
 	
18
-	/**
19
-	 * @var string $id The unique ID (within the context of a particular Tool Consumer) of a particular user
20
-	 **/
21
-	private $id;
18
+    /**
19
+     * @var string $id The unique ID (within the context of a particular Tool Consumer) of a particular user
20
+     **/
21
+    private $id;
22 22
 	
23
-	/**
24
-	 * @var mysqli $sql A MySQL connection
25
-	 **/
26
-	private $sql;
23
+    /**
24
+     * @var mysqli $sql A MySQL connection
25
+     **/
26
+    private $sql;
27 27
 	
28
-	/**
29
-	 * @var string|null $token This user's API access token (if acquired) or NULL if not yet acquired
30
-	 **/
31
-	private $token = null;
28
+    /**
29
+     * @var string|null $token This user's API access token (if acquired) or NULL if not yet acquired
30
+     **/
31
+    private $token = null;
32 32
 	
33
-	/**
34
-	 * @var string|null $apiUrl The URL of the API for which this user's token is valid, NULL if no token
35
-	 **/
36
-	private $apiUrl = null;
33
+    /**
34
+     * @var string|null $apiUrl The URL of the API for which this user's token is valid, NULL if no token
35
+     **/
36
+    private $apiUrl = null;
37 37
 
38
-	/**
39
-	 * Create a new UserAPIToken to either register a new user in the
40
-	 * USER_TOKENS_TABLE or	look up an existing user.
41
-	 *
42
-	 * @param string $consumerKey The unique ID of the Tool Consumer from whence the user is making requests to the LTI
43
-	 * @param string $userId The unique ID of the user within that Tool Consumer
44
-	 * @param mysqli $mysqli An active MySQL database connection to update USER_TOKEN_TABLE
45
-	 *
46
-	 * @throws UserAPIToken_Exception CONSUMER_KEY_REQUIRED If no consumer key is provided
47
-	 * @throws UserAPIToken_Exception USER_ID_REQUIRED If no user ID is provided
48
-	 * @throws UserAPIToken_Exception MYSQLI_REQUIRED If no MySQL database connection is provided
49
-	 * @throws UserAPIToken_Excpetion MYSQLI_ERROR If the user cannot be found or inserted in USER_TOKEN_TABLE
50
-	 **/
51
-	public function __construct($consumerKey, $userId, $mysqli) {
38
+    /**
39
+     * Create a new UserAPIToken to either register a new user in the
40
+     * USER_TOKENS_TABLE or	look up an existing user.
41
+     *
42
+     * @param string $consumerKey The unique ID of the Tool Consumer from whence the user is making requests to the LTI
43
+     * @param string $userId The unique ID of the user within that Tool Consumer
44
+     * @param mysqli $mysqli An active MySQL database connection to update USER_TOKEN_TABLE
45
+     *
46
+     * @throws UserAPIToken_Exception CONSUMER_KEY_REQUIRED If no consumer key is provided
47
+     * @throws UserAPIToken_Exception USER_ID_REQUIRED If no user ID is provided
48
+     * @throws UserAPIToken_Exception MYSQLI_REQUIRED If no MySQL database connection is provided
49
+     * @throws UserAPIToken_Excpetion MYSQLI_ERROR If the user cannot be found or inserted in USER_TOKEN_TABLE
50
+     **/
51
+    public function __construct($consumerKey, $userId, $mysqli) {
52 52
 		
53
-		if (empty((string) $consumerKey)) {
54
-			throw new UserAPIToken_Exception(
55
-				'A consumer key is required',
56
-				UserAPIToken_Exception::CONSUMER_KEY_REQUIRED
57
-			);
58
-		}
53
+        if (empty((string) $consumerKey)) {
54
+            throw new UserAPIToken_Exception(
55
+                'A consumer key is required',
56
+                UserAPIToken_Exception::CONSUMER_KEY_REQUIRED
57
+            );
58
+        }
59 59
 		
60
-		if (empty((string) $userId)) {
61
-			throw new UserAPIToken_Exception(
62
-				'A user ID is required',
63
-				UserAPIToken_Exception::USER_ID_REQUIRED
64
-			);
65
-		}
60
+        if (empty((string) $userId)) {
61
+            throw new UserAPIToken_Exception(
62
+                'A user ID is required',
63
+                UserAPIToken_Exception::USER_ID_REQUIRED
64
+            );
65
+        }
66 66
 		
67
-		if (!($mysqli instanceof mysqli)) {
68
-			throw new UserAPIToken_Exception(
69
-				'A valid mysqli object is required',
70
-				UserAPIToken_Exception::MYSQLI_REQUIRED
71
-			);
72
-		}
67
+        if (!($mysqli instanceof mysqli)) {
68
+            throw new UserAPIToken_Exception(
69
+                'A valid mysqli object is required',
70
+                UserAPIToken_Exception::MYSQLI_REQUIRED
71
+            );
72
+        }
73 73
 		
74
-		$this->sql = $mysqli;
75
-		$this->consumerKey = $this->sql->real_escape_string($consumerKey);
76
-		$this->id = $this->sql->real_escape_string($userId);
74
+        $this->sql = $mysqli;
75
+        $this->consumerKey = $this->sql->real_escape_string($consumerKey);
76
+        $this->id = $this->sql->real_escape_string($userId);
77 77
 				
78
-		$result = $this->sql->query("SELECT * FROM `" . self::USER_TOKENS_TABLE . "` WHERE `consumer_key` = '{$this->consumerKey}' AND `id` = '{$this->id}'");
79
-		$row = $result->fetch_assoc();
80
-		if ($row) {
81
-			$this->token = $row['token'];
82
-			$this->apiUrl = $row['api_url'];
83
-		} else {
84
-			if (!$this->sql->query("INSERT INTO `" . self::USER_TOKENS_TABLE . "` (`consumer_key`, `id`) VALUES ('{$this->consumerKey}', '{$this->id}')")) {
85
-				throw new UserAPIToken_Exception(
86
-					"Error inserting a new user: {$this->sql->error}",
87
-					UserAPIToken_Exception::MYSQLI_ERROR
88
-				);
89
-			}
90
-		}
91
-	}
78
+        $result = $this->sql->query("SELECT * FROM `" . self::USER_TOKENS_TABLE . "` WHERE `consumer_key` = '{$this->consumerKey}' AND `id` = '{$this->id}'");
79
+        $row = $result->fetch_assoc();
80
+        if ($row) {
81
+            $this->token = $row['token'];
82
+            $this->apiUrl = $row['api_url'];
83
+        } else {
84
+            if (!$this->sql->query("INSERT INTO `" . self::USER_TOKENS_TABLE . "` (`consumer_key`, `id`) VALUES ('{$this->consumerKey}', '{$this->id}')")) {
85
+                throw new UserAPIToken_Exception(
86
+                    "Error inserting a new user: {$this->sql->error}",
87
+                    UserAPIToken_Exception::MYSQLI_ERROR
88
+                );
89
+            }
90
+        }
91
+    }
92 92
 	
93
-	/**
94
-	 * @return string|boolean The API access token for this user, or FALSE if no token has been acquired
95
-	 **/
96
-	public function getToken() {
97
-		if ($this->token) {
98
-			return $this->token;
99
-		}
100
-		return false;
101
-	}
93
+    /**
94
+     * @return string|boolean The API access token for this user, or FALSE if no token has been acquired
95
+     **/
96
+    public function getToken() {
97
+        if ($this->token) {
98
+            return $this->token;
99
+        }
100
+        return false;
101
+    }
102 102
 	
103
-	/**
104
-	 * Stores a new API Token into USER_TOKEN_TABLE for this user
105
-	 *
106
-	 * @param string $token A new API access token for this user
107
-	 *
108
-	 * @return boolean Returns TRUE if the token is successfully stored in USER_TOKEN_TABLE, FALSE otherwise
109
-	 *
110
-	 * @throws UserAPIToken_Exception TOKEN_REQUIRED If no token is provided
111
-	 **/
112
-	public function setToken($token) {
113
-		if (empty($token)) {
114
-			throw new UserAPIToken_Exception(
115
-				'A token is required',
116
-				UserAPIToken_Exception::TOKEN_REQUIRED
117
-			);
118
-		}
119
-		if($this->consumerKey && $this->id && $this->sql) {
120
-			$_token = $this->sql->real_escape_string($token);
121
-			if (!$this->sql->query("UPDATE `" . self::USER_TOKENS_TABLE . "` set `token` = '$_token' WHERE `consumer_key` = '{$this->consumerKey}' AND `id` = '{$this->id}'")) {
122
-				throw new UserAPIToken_Exception(
123
-					"Error updating token: {$this->sql->error}",
124
-					UserAPIToken_Exception::MYSQLI_ERROR
125
-				);
126
-			}
127
-			$this->token = $token;
103
+    /**
104
+     * Stores a new API Token into USER_TOKEN_TABLE for this user
105
+     *
106
+     * @param string $token A new API access token for this user
107
+     *
108
+     * @return boolean Returns TRUE if the token is successfully stored in USER_TOKEN_TABLE, FALSE otherwise
109
+     *
110
+     * @throws UserAPIToken_Exception TOKEN_REQUIRED If no token is provided
111
+     **/
112
+    public function setToken($token) {
113
+        if (empty($token)) {
114
+            throw new UserAPIToken_Exception(
115
+                'A token is required',
116
+                UserAPIToken_Exception::TOKEN_REQUIRED
117
+            );
118
+        }
119
+        if($this->consumerKey && $this->id && $this->sql) {
120
+            $_token = $this->sql->real_escape_string($token);
121
+            if (!$this->sql->query("UPDATE `" . self::USER_TOKENS_TABLE . "` set `token` = '$_token' WHERE `consumer_key` = '{$this->consumerKey}' AND `id` = '{$this->id}'")) {
122
+                throw new UserAPIToken_Exception(
123
+                    "Error updating token: {$this->sql->error}",
124
+                    UserAPIToken_Exception::MYSQLI_ERROR
125
+                );
126
+            }
127
+            $this->token = $token;
128 128
 			
129
-			return true;
130
-		}
129
+            return true;
130
+        }
131 131
 		
132
-		return false;
133
-	}
132
+        return false;
133
+    }
134 134
 	
135
-	/**
136
-	 * @return string|boolean The URL of the API for which the user's API token is valid, or FALSE if no token has been acquired
137
-	 **/
138
-	function getAPIUrl() {
139
-		if ($this->apiUrl) {
140
-			return $this->apiUrl;
141
-		}
142
-		return false;
143
-	}
135
+    /**
136
+     * @return string|boolean The URL of the API for which the user's API token is valid, or FALSE if no token has been acquired
137
+     **/
138
+    function getAPIUrl() {
139
+        if ($this->apiUrl) {
140
+            return $this->apiUrl;
141
+        }
142
+        return false;
143
+    }
144 144
 	
145
-	/**
146
-	 * Stores a new URL for the API URL for which the user's API access token is valid in USER_TOKEN_TABLE
147
-	 *
148
-	 * @param string $apiUrl The URL of the API
149
-	 *
150
-	 * @return boolean TRUE if the URL of the API is stored in USER_TOKEN_TABLE, FALSE otherwise
151
-	 *
152
-	 * @throws UserAPITokenException API_URL_REQUIRED If no URL is provided
153
-	 **/
154
-	public function setAPIUrl($apiUrl) {
155
-		if (empty($apiUrl)) {
156
-			throw new UserAPIToken_Exception(
157
-				'API URL is required',
158
-				UserAPIToken_Exception::API_URL_REQUIRED
159
-			);
160
-		}
145
+    /**
146
+     * Stores a new URL for the API URL for which the user's API access token is valid in USER_TOKEN_TABLE
147
+     *
148
+     * @param string $apiUrl The URL of the API
149
+     *
150
+     * @return boolean TRUE if the URL of the API is stored in USER_TOKEN_TABLE, FALSE otherwise
151
+     *
152
+     * @throws UserAPITokenException API_URL_REQUIRED If no URL is provided
153
+     **/
154
+    public function setAPIUrl($apiUrl) {
155
+        if (empty($apiUrl)) {
156
+            throw new UserAPIToken_Exception(
157
+                'API URL is required',
158
+                UserAPIToken_Exception::API_URL_REQUIRED
159
+            );
160
+        }
161 161
 		
162
-		if ($this->consumerKey && $this->id && $this->sql) {
163
-			$_apiUrl = $this->sql->real_escape_string($apiUrl);
164
-			if (!$this->sql->query("UPDATE `" . self::USER_TOKENS_TABLE . "` set `api_url` = '$_apiUrl' WHERE `consumer_key` = '{$this->consumerKey}' AND `id` = '{$this->id}'")) {
165
-				throw new UserAPIToken_Exception(
166
-					"Error updating API URL for user token: {$this->sql->error}",
167
-					UserAPIToken_Exception::MYSQLI_ERROR
168
-				);
169
-			}
170
-			$this->apiUrl = $apiUrl;
171
-			return true;
172
-		}
173
-		return false;
174
-	}
162
+        if ($this->consumerKey && $this->id && $this->sql) {
163
+            $_apiUrl = $this->sql->real_escape_string($apiUrl);
164
+            if (!$this->sql->query("UPDATE `" . self::USER_TOKENS_TABLE . "` set `api_url` = '$_apiUrl' WHERE `consumer_key` = '{$this->consumerKey}' AND `id` = '{$this->id}'")) {
165
+                throw new UserAPIToken_Exception(
166
+                    "Error updating API URL for user token: {$this->sql->error}",
167
+                    UserAPIToken_Exception::MYSQLI_ERROR
168
+                );
169
+            }
170
+            $this->apiUrl = $apiUrl;
171
+            return true;
172
+        }
173
+        return false;
174
+    }
175 175
 }
176 176
 
177 177
 /**
@@ -180,12 +180,12 @@  discard block
 block discarded – undo
180 180
  * @author Seth Battis <[email protected]>
181 181
  **/
182 182
 class UserAPIToken_Exception extends CanvasAPIviaLTI_Exception {
183
-	const CONSUMER_KEY_REQUIRED = 1;
184
-	const USER_ID_REQUIRED = 2;
185
-	const MYSQLI_REQUIRED = 3;
186
-	const MYSQLI_ERROR = 4;
187
-	const TOKEN_REQUIRED = 5;
188
-	const API_URL_REQUIRED = 6;
183
+    const CONSUMER_KEY_REQUIRED = 1;
184
+    const USER_ID_REQUIRED = 2;
185
+    const MYSQLI_REQUIRED = 3;
186
+    const MYSQLI_ERROR = 4;
187
+    const TOKEN_REQUIRED = 5;
188
+    const API_URL_REQUIRED = 6;
189 189
 }
190 190
 
191 191
 ?>
192 192
\ No newline at end of file
Please login to merge, or discard this patch.
Spacing   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -116,7 +116,7 @@
 block discarded – undo
116 116
 				UserAPIToken_Exception::TOKEN_REQUIRED
117 117
 			);
118 118
 		}
119
-		if($this->consumerKey && $this->id && $this->sql) {
119
+		if ($this->consumerKey && $this->id && $this->sql) {
120 120
 			$_token = $this->sql->real_escape_string($token);
121 121
 			if (!$this->sql->query("UPDATE `" . self::USER_TOKENS_TABLE . "` set `token` = '$_token' WHERE `consumer_key` = '{$this->consumerKey}' AND `id` = '{$this->id}'")) {
122 122
 				throw new UserAPIToken_Exception(
Please login to merge, or discard this patch.
import.php 4 patches
Unused Use Statements   -1 removed lines patch added patch discarded remove patch
@@ -11,7 +11,6 @@
 block discarded – undo
11 11
 
12 12
 require_once 'common.inc.php';
13 13
 
14
-use smtech\CanvasPest\CanvasPest;
15 14
 use Battis\BootstrapSmarty\NotificationMessage;
16 15
 
17 16
 /**
Please login to merge, or discard this patch.
Spacing   +4 added lines, -4 removed lines patch added patch discarded remove patch
@@ -6,7 +6,7 @@  discard block
 block discarded – undo
6 6
 	$_REQUEST['canvas_url'] = $argv[2];
7 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';
@@ -99,7 +99,7 @@  discard block
 block discarded – undo
99 99
 
100 100
 	if ($canvasContext = getCanvasContext($_REQUEST['canvas_url'])) {
101 101
 		/* check ICS feed to be sure it exists */
102
-		if(urlExists($_REQUEST['cal'])) {
102
+		if (urlExists($_REQUEST['cal'])) {
103 103
 			/* look up the canvas object -- mostly to make sure that it exists! */
104 104
 			if ($canvasObject = $api->get($canvasContext['verification_url'])) {
105 105
 
@@ -185,10 +185,10 @@  discard block
 block discarded – undo
185 185
 				// TODO:0 the best window for syncing would be the term of the course in question, right? issue:12
186 186
 				// TODO:0 Arbitrarily selecting events in for a year on either side of today's date, probably a better system? issue:12
187 187
 				foreach ($ics->selectComponents(
188
-					date('Y')-1, // startYear
188
+					date('Y') - 1, // startYear
189 189
 					date('m'), // startMonth
190 190
 					date('d'), // startDay
191
-					date('Y')+1, // endYEar
191
+					date('Y') + 1, // endYEar
192 192
 					date('m'), // endMonth
193 193
 					date('d'), // endDay
194 194
 					'vevent', // cType
Please login to merge, or discard this patch.
Braces   +6 added lines, -2 removed lines patch added patch discarded remove patch
@@ -305,7 +305,9 @@  discard block
 block discarded – undo
305 305
 							), false) . '</pre>',
306 306
 							NotificationMessage::ERROR
307 307
 						);
308
-						if (php_sapi_name() != 'cli') $smarty->display('page.tpl');
308
+						if (php_sapi_name() != 'cli') {
309
+						    $smarty->display('page.tpl');
310
+						}
309 311
 						exit;
310 312
 					}
311 313
 					$sql->query("
@@ -421,7 +423,9 @@  discard block
 block discarded – undo
421 423
 			'The Canvas URL you submitted could not be parsed.<pre>' . $_REQUEST['canvas_url'] . '</pre>',
422 424
 			NotificationMessage::ERROR
423 425
 		);
424
-		if (php_sapi_name() != 'cli') $smarty->display('page.tpl');
426
+		if (php_sapi_name() != 'cli') {
427
+		    $smarty->display('page.tpl');
428
+		}
425 429
 		exit;
426 430
 	}
427 431
 }
Please login to merge, or discard this 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.
classes/CanvasAPIviaLTI.php 1 patch
Indentation   +79 added lines, -79 removed lines patch added patch discarded remove patch
@@ -7,98 +7,98 @@  discard block
 block discarded – undo
7 7
  **/	
8 8
 class CanvasAPIviaLTI extends LTI_Tool_Provider {
9 9
 	
10
-	/**
11
-	 * Handle launch requests, which start the application running
12
-	 **/
13
-	public function onLaunch() {
14
-		global $metadata; // FIXME:0 grown-ups don't program like this issue:17
15
-		global $sql; // FIXME:0 grown-ups don't program like this issue:17
10
+    /**
11
+     * Handle launch requests, which start the application running
12
+     **/
13
+    public function onLaunch() {
14
+        global $metadata; // FIXME:0 grown-ups don't program like this issue:17
15
+        global $sql; // FIXME:0 grown-ups don't program like this issue:17
16 16
 				
17
-		/* is this user in a role that can use this app? */
18
-		if ($this->user->isAdmin()) {
17
+        /* is this user in a role that can use this app? */
18
+        if ($this->user->isAdmin()) {
19 19
 			
20
-			/* set up any needed session variables */
21
-	        $_SESSION['consumer_key'] = $this->consumer->getKey();
22
-	        $_SESSION['resource_id'] = $this->resource_link->getId();
23
-	        $_SESSION['user_consumer_key'] = $this->user->getResourceLink()->getConsumer()->getKey();
24
-	        $_SESSION['user_id'] = $this->user->getId();
25
-	        $_SESSION['isStudent'] = $this->user->isLearner();
26
-	        $_SESSION['isContentItem'] = FALSE;	   
20
+            /* set up any needed session variables */
21
+            $_SESSION['consumer_key'] = $this->consumer->getKey();
22
+            $_SESSION['resource_id'] = $this->resource_link->getId();
23
+            $_SESSION['user_consumer_key'] = $this->user->getResourceLink()->getConsumer()->getKey();
24
+            $_SESSION['user_id'] = $this->user->getId();
25
+            $_SESSION['isStudent'] = $this->user->isLearner();
26
+            $_SESSION['isContentItem'] = FALSE;	   
27 27
 			
28
-			/* do we have an admin API access token? */
29
-			$haveToken = true;
30
-			if (empty($metadata['CANVAS_API_TOKEN'])) {
28
+            /* do we have an admin API access token? */
29
+            $haveToken = true;
30
+            if (empty($metadata['CANVAS_API_TOKEN'])) {
31 31
 				
32
-				/* ...if not, do we have a user API access token for this user? */
33
-				$userToken = new UserAPIToken($_SESSION['user_consumer_key'], $_SESSION['user_id'], $sql);			
34
-				if (empty($userToken->getToken())) {
32
+                /* ...if not, do we have a user API access token for this user? */
33
+                $userToken = new UserAPIToken($_SESSION['user_consumer_key'], $_SESSION['user_id'], $sql);			
34
+                if (empty($userToken->getToken())) {
35 35
 					
36
-					/* ...if this user has no token, let's start by getting one */
37
-					$haveToken = false;
38
-					$this->redirectURL = "{$metadata['APP_URL']}/lti/token_request.php?oauth=request";
39
-				} else {
36
+                    /* ...if this user has no token, let's start by getting one */
37
+                    $haveToken = false;
38
+                    $this->redirectURL = "{$metadata['APP_URL']}/lti/token_request.php?oauth=request";
39
+                } else {
40 40
 					
41
-					/* ...but if the user does have a token, rock on! */
42
-					$_SESSION['isUserToken'] = true;
43
-					$_SESSION['apiToken'] = $userToken->getToken();
44
-					//$_SESSION['apiUrl'] = $userToken->getAPIUrl();
45
-				}
46
-			} else {
41
+                    /* ...but if the user does have a token, rock on! */
42
+                    $_SESSION['isUserToken'] = true;
43
+                    $_SESSION['apiToken'] = $userToken->getToken();
44
+                    //$_SESSION['apiUrl'] = $userToken->getAPIUrl();
45
+                }
46
+            } else {
47 47
 				
48
-				/* ...if we have an admin API token, rock on! */
49
-				$_SESSION['isUserToken'] = false;
50
-				$_SESSION['apiToken'] = $metadata['CANVAS_API_TOKEN'];
51
-				//$_SESSION['apiUrl'] = $metadata['CANVAS_API_URL'];
52
-			}
53
-			$_SESSION['apiUrl'] = 'https://' . $this->user->getResourceLink()->settings['custom_canvas_api_domain'] . '/api/v1';
48
+                /* ...if we have an admin API token, rock on! */
49
+                $_SESSION['isUserToken'] = false;
50
+                $_SESSION['apiToken'] = $metadata['CANVAS_API_TOKEN'];
51
+                //$_SESSION['apiUrl'] = $metadata['CANVAS_API_URL'];
52
+            }
53
+            $_SESSION['apiUrl'] = 'https://' . $this->user->getResourceLink()->settings['custom_canvas_api_domain'] . '/api/v1';
54 54
 			
55
-	        /* pass control off to the app */
56
-	        if ($haveToken) {
57
-		        $this->redirectURL = "{$metadata['APP_URL']}/app.php?lti-request=launch";
58
-	        }
55
+            /* pass control off to the app */
56
+            if ($haveToken) {
57
+                $this->redirectURL = "{$metadata['APP_URL']}/app.php?lti-request=launch";
58
+            }
59 59
 
60
-		/* ...otherwise set an appropriate error message and fail */
61
-		} else {
62
-			$this->reason = 'Invalid role';
63
-			$this->isOK = false;
64
-		}
65
-	}
60
+        /* ...otherwise set an appropriate error message and fail */
61
+        } else {
62
+            $this->reason = 'Invalid role';
63
+            $this->isOK = false;
64
+        }
65
+    }
66 66
 	
67
-	/**
68
-	 * Handle errors created while processing the LTI request
69
-	 **/
70
-	public function onError() {
71
-		global $metadata; // FIXME:0 grown-ups don't program like this issue:17
67
+    /**
68
+     * Handle errors created while processing the LTI request
69
+     **/
70
+    public function onError() {
71
+        global $metadata; // FIXME:0 grown-ups don't program like this issue:17
72 72
 		
73
-		$this->redirectURL = "{$metadata['APP_URL']}/app.php?lti-request=error&reason={$this->reason}";
74
-	}
73
+        $this->redirectURL = "{$metadata['APP_URL']}/app.php?lti-request=error&reason={$this->reason}";
74
+    }
75 75
 	
76
-	/**
77
-	 * Handle dashboard requests (coming in LTI v2.0, I guess)
78
-	 **/
79
-	public function onDashboard() {
80
-		global $metadata; // FIXME:0 grown-ups don't program like this issue:17
76
+    /**
77
+     * Handle dashboard requests (coming in LTI v2.0, I guess)
78
+     **/
79
+    public function onDashboard() {
80
+        global $metadata; // FIXME:0 grown-ups don't program like this issue:17
81 81
 		
82
-		$this->redirectURL = "{$metadata['APP_URL']}/app.php?lti-request=dashboard";
83
-	}
82
+        $this->redirectURL = "{$metadata['APP_URL']}/app.php?lti-request=dashboard";
83
+    }
84 84
 	
85
-	/**
86
-	 * Handle configure requests (coming in LTI v2.0, I guess)
87
-	 **/
88
-	public function onConfigure() {
89
-		global $metadata; // FIXME:0 grown-ups don't program like this issue:17
85
+    /**
86
+     * Handle configure requests (coming in LTI v2.0, I guess)
87
+     **/
88
+    public function onConfigure() {
89
+        global $metadata; // FIXME:0 grown-ups don't program like this issue:17
90 90
 		
91
-		$this->redirectURL = "{$metadata['APP_URL']}/app.php?lti-request=configure";
92
-	}
91
+        $this->redirectURL = "{$metadata['APP_URL']}/app.php?lti-request=configure";
92
+    }
93 93
 	
94
-	/**
95
-	 * Handle content-item requests (that is we're a tool provider that adds a button in the content editor)
96
-	 **/
97
-	public function onContentItem() {
98
-		global $metadata; // FIXME:0 grown-ups don't program like this issue:17
94
+    /**
95
+     * Handle content-item requests (that is we're a tool provider that adds a button in the content editor)
96
+     **/
97
+    public function onContentItem() {
98
+        global $metadata; // FIXME:0 grown-ups don't program like this issue:17
99 99
 		
100
-		$this->redirectURL = "{$metadata['APP_URL']}/app.php?lti-request=content-item";
101
-	}
100
+        $this->redirectURL = "{$metadata['APP_URL']}/app.php?lti-request=content-item";
101
+    }
102 102
 }
103 103
 
104 104
 /**
@@ -107,10 +107,10 @@  discard block
 block discarded – undo
107 107
  * @author Seth Battis <[email protected]>
108 108
  **/
109 109
 class CanvasAPIviaLTI_Exception extends Exception {
110
-	const MISSING_SECRETS_FILE = 1;
111
-	const INVALID_SECRETS_FILE = 2;
112
-	const MYSQL_CONNECTION = 3;
113
-	const LAUNCH_REQUEST = 4;
110
+    const MISSING_SECRETS_FILE = 1;
111
+    const INVALID_SECRETS_FILE = 2;
112
+    const MYSQL_CONNECTION = 3;
113
+    const LAUNCH_REQUEST = 4;
114 114
 }
115 115
 
116 116
 ?>
117 117
\ No newline at end of file
Please login to merge, or discard this patch.
sync.php 2 patches
Indentation   +4 added lines, -4 removed lines patch added patch discarded remove patch
@@ -15,15 +15,15 @@
 block discarded – undo
15 15
 ");
16 16
 
17 17
 while($schedule = $schedulesResponse->fetch_assoc()) {
18
-	$calendarResponse = $sql->query("
18
+    $calendarResponse = $sql->query("
19 19
 		SELECT *
20 20
 			FROM `calendars`
21 21
 			WHERE
22 22
 				`id` = '{$schedule['calendar']}'
23 23
 	");
24
-	if ($calendar = $calendarResponse->fetch_assoc()) {
25
-		echo shell_exec('php ' . __DIR__ . '/import.php ' . $calendar['ics_url'] . ' ' . $calendar['canvas_url'] . ' ' . $schedule['id']);
26
-	}
24
+    if ($calendar = $calendarResponse->fetch_assoc()) {
25
+        echo shell_exec('php ' . __DIR__ . '/import.php ' . $calendar['ics_url'] . ' ' . $calendar['canvas_url'] . ' ' . $schedule['id']);
26
+    }
27 27
 }
28 28
 
29 29
 ?>
30 30
\ No newline at end of file
Please login to merge, or discard this patch.
Spacing   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -14,7 +14,7 @@
 block discarded – undo
14 14
 			`synced` ASC
15 15
 ");
16 16
 
17
-while($schedule = $schedulesResponse->fetch_assoc()) {
17
+while ($schedule = $schedulesResponse->fetch_assoc()) {
18 18
 	$calendarResponse = $sql->query("
19 19
 		SELECT *
20 20
 			FROM `calendars`
Please login to merge, or discard this patch.
app.php 2 patches
Indentation   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -6,7 +6,7 @@
 block discarded – undo
6 6
 $smarty->assign('category', '');
7 7
 $smarty->assign('formAction', $metadata['APP_URL'] . '/import.php');
8 8
 $smarty->assign('formHidden', array(
9
-	'canvas_url' => $_SESSION['canvasInstanceUrl']. '/courses/' . $_SESSION['toolProvider']->user->getResourceLink()->settings['custom_canvas_course_id']
9
+    'canvas_url' => $_SESSION['canvasInstanceUrl']. '/courses/' . $_SESSION['toolProvider']->user->getResourceLink()->settings['custom_canvas_course_id']
10 10
 ));
11 11
 $smarty->display('course.tpl');
12 12
 
Please login to merge, or discard this patch.
Spacing   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -6,7 +6,7 @@
 block discarded – undo
6 6
 $smarty->assign('category', '');
7 7
 $smarty->assign('formAction', $metadata['APP_URL'] . '/import.php');
8 8
 $smarty->assign('formHidden', array(
9
-	'canvas_url' => $_SESSION['canvasInstanceUrl']. '/courses/' . $_SESSION['toolProvider']->user->getResourceLink()->settings['custom_canvas_course_id']
9
+	'canvas_url' => $_SESSION['canvasInstanceUrl'] . '/courses/' . $_SESSION['toolProvider']->user->getResourceLink()->settings['custom_canvas_course_id']
10 10
 ));
11 11
 $smarty->display('course.tpl');
12 12
 
Please login to merge, or discard this patch.
common.inc.php 1 patch
Indentation   +97 added lines, -97 removed lines patch added patch discarded remove patch
@@ -18,8 +18,8 @@  discard block
 block discarded – undo
18 18
  * @return boolean
19 19
  **/
20 20
 function midLaunch() {
21
-	global $metadata; // FIXME:0 grown-ups don't program like this issue:17
22
-	return $metadata['APP_LAUNCH_URL'] === (($_SERVER['HTTPS'] === 'on' ? 'https://' : 'http://') . $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI']);
21
+    global $metadata; // FIXME:0 grown-ups don't program like this issue:17
22
+    return $metadata['APP_LAUNCH_URL'] === (($_SERVER['HTTPS'] === 'on' ? 'https://' : 'http://') . $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI']);
23 23
 }
24 24
 
25 25
 /**
@@ -31,22 +31,22 @@  discard block
 block discarded – undo
31 31
  * @throws CanvasAPIviaLTI_Exception INVALID_SECRETS_FILE if the SECRETS_FILE exists, but cannot be parsed
32 32
  **/
33 33
 function initSecrets() {
34
-	if (file_exists(SECRETS_FILE)) {
35
-		// http://stackoverflow.com/a/24760909 (oy!)
36
-		if (($secrets = simplexml_load_string(file_get_contents(SECRETS_FILE))) !== false) {
37
-			return $secrets;
38
-		} else {
39
-			throw new CanvasAPIviaLTI_Exception(
40
-				SECRETS_FILE . ' could not be loaded. ',
41
-				CanvasAPIviaLTI_Exception::INVALID_SECRETS_FILE
42
-			);
43
-		}
44
-	} else {
45
-		throw new CanvasAPIviaLTI_Exception(
46
-			SECRETS_FILE . " could not be found.",
47
-			CanvasAPIviaLTI_Exception::MISSING_SECRETS_FILE
48
-		);
49
-	}
34
+    if (file_exists(SECRETS_FILE)) {
35
+        // http://stackoverflow.com/a/24760909 (oy!)
36
+        if (($secrets = simplexml_load_string(file_get_contents(SECRETS_FILE))) !== false) {
37
+            return $secrets;
38
+        } else {
39
+            throw new CanvasAPIviaLTI_Exception(
40
+                SECRETS_FILE . ' could not be loaded. ',
41
+                CanvasAPIviaLTI_Exception::INVALID_SECRETS_FILE
42
+            );
43
+        }
44
+    } else {
45
+        throw new CanvasAPIviaLTI_Exception(
46
+            SECRETS_FILE . " could not be found.",
47
+            CanvasAPIviaLTI_Exception::MISSING_SECRETS_FILE
48
+        );
49
+    }
50 50
 }
51 51
 
52 52
 /**
@@ -59,28 +59,28 @@  discard block
 block discarded – undo
59 59
  * @throws CanvasAPIviaLTI_Exception MYSQL_CONNECTION if a mysqli connection cannot be established
60 60
  **/
61 61
 function initMySql() {
62
-	global $secrets; // FIXME:0 grown-ups don't program like this issue:17
63
-	if (!($secrets instanceof SimpleXMLElement)) {
64
-		$secrets = initSecrets();
65
-	}
66
-
67
-	/* turn off warnings, since we're going to test the connection ourselves */
68
-	set_error_handler(function() {});
69
-	$sql = new mysqli(
70
-		(string) $secrets->mysql->host,
71
-		(string) $secrets->mysql->username,
72
-		(string) $secrets->mysql->password,
73
-		(string) $secrets->mysql->database
74
-	);
75
-	restore_error_handler();
76
-
77
-	if ($sql->connect_error) {
78
-		throw new CanvasAPIviaLTI_Exception(
79
-			$sql->connect_error,
80
-			CanvasAPIviaLTI_Exception::MYSQL_CONNECTION
81
-		);
82
-	}
83
-	return $sql;
62
+    global $secrets; // FIXME:0 grown-ups don't program like this issue:17
63
+    if (!($secrets instanceof SimpleXMLElement)) {
64
+        $secrets = initSecrets();
65
+    }
66
+
67
+    /* turn off warnings, since we're going to test the connection ourselves */
68
+    set_error_handler(function() {});
69
+    $sql = new mysqli(
70
+        (string) $secrets->mysql->host,
71
+        (string) $secrets->mysql->username,
72
+        (string) $secrets->mysql->password,
73
+        (string) $secrets->mysql->database
74
+    );
75
+    restore_error_handler();
76
+
77
+    if ($sql->connect_error) {
78
+        throw new CanvasAPIviaLTI_Exception(
79
+            $sql->connect_error,
80
+            CanvasAPIviaLTI_Exception::MYSQL_CONNECTION
81
+        );
82
+    }
83
+    return $sql;
84 84
 }
85 85
 
86 86
 /**
@@ -89,12 +89,12 @@  discard block
 block discarded – undo
89 89
  * @return \Battis\AppMetadata
90 90
  **/
91 91
 function initAppMetadata() {
92
-	global $secrets; // FIXME:0 grown-ups don't program like this issue:17
93
-	global $sql; // FIXME:0 grown-ups don't program like this issue:17
92
+    global $secrets; // FIXME:0 grown-ups don't program like this issue:17
93
+    global $sql; // FIXME:0 grown-ups don't program like this issue:17
94 94
 
95
-	$metadata = new AppMetadata($sql, (string) $secrets->app->id);
95
+    $metadata = new AppMetadata($sql, (string) $secrets->app->id);
96 96
 
97
-	return $metadata;
97
+    return $metadata;
98 98
 }
99 99
 
100 100
 /**
@@ -105,9 +105,9 @@  discard block
 block discarded – undo
105 105
  * @return void
106 106
  **/
107 107
 function html_var_dump($var) {
108
-	echo '<pre>';
109
-	var_dump($var);
110
-	echo '</pre>';
108
+    echo '<pre>';
109
+    var_dump($var);
110
+    echo '</pre>';
111 111
 }
112 112
 
113 113
 /*****************************************************************************
@@ -121,68 +121,68 @@  discard block
 block discarded – undo
121 121
 
122 122
 /* preliminary interactive only initialization */
123 123
 if (php_sapi_name() != 'cli') {
124
-	session_start();
124
+    session_start();
125 125
 
126
-	/* fire up the templating engine for interactive scripts */
127
-	$smarty = StMarksSmarty::getSmarty();
128
-	$smarty->addTemplateDir(__DIR__ . '/templates', 'starter-canvas-api-via-lti');
129
-	$smarty->setFramed(true);
126
+    /* fire up the templating engine for interactive scripts */
127
+    $smarty = StMarksSmarty::getSmarty();
128
+    $smarty->addTemplateDir(__DIR__ . '/templates', 'starter-canvas-api-via-lti');
129
+    $smarty->setFramed(true);
130 130
 }
131 131
 
132 132
 /* initialization that needs to happen for interactive and CLI scripts */
133 133
 try {
134
-	/* initialize global variables */
135
-	$secrets = initSecrets();
136
-	$sql = initMySql();
137
-	$metadata = initAppMetadata();
134
+    /* initialize global variables */
135
+    $secrets = initSecrets();
136
+    $sql = initMySql();
137
+    $metadata = initAppMetadata();
138 138
 } catch (CanvasAPIviaLTI_Exception $e) {
139
-	if (php_sapi_name() == 'cli') {
140
-		echo 'Initialization Failure [' . $e->getCode() . ']' . PHP_EOL . $e->getMessage() . PHP_EOL;
141
-		exit;
142
-	} else {
143
-		$smarty->addMessage(
144
-			'Initialization Failure [' . $e->getCode() . ']',
145
-			$e->getMessage(),
146
-			NotificationMessage::ERROR
147
-		);
148
-		$smarty->display();
149
-		exit;
150
-	}
139
+    if (php_sapi_name() == 'cli') {
140
+        echo 'Initialization Failure [' . $e->getCode() . ']' . PHP_EOL . $e->getMessage() . PHP_EOL;
141
+        exit;
142
+    } else {
143
+        $smarty->addMessage(
144
+            'Initialization Failure [' . $e->getCode() . ']',
145
+            $e->getMessage(),
146
+            NotificationMessage::ERROR
147
+        );
148
+        $smarty->display();
149
+        exit;
150
+    }
151 151
 }
152 152
 
153 153
 /* interactive initialization only */
154 154
 if ($ready && php_sapi_name() != 'cli') {
155 155
 
156
-	/* allow web apps to use common.inc.php without LTI authentication */
157
-	if (!defined('IGNORE_LTI')) {
158
-
159
-		try {
160
-			if (midLaunch()) {
161
-				$ready = false;
162
-			} elseif (isset($_SESSION['toolProvider'])) {
163
-				$toolProvider = $_SESSION['toolProvider'];
164
-			} else {
165
-				throw new CanvasAPIviaLTI_Exception(
166
-					'The LTI launch request is missing',
167
-					CanvasAPIviaLTI_Exception::LAUNCH_REQUEST
168
-				);
169
-			}
170
-
171
-		} catch (CanvasAPIviaLTI_Exception $e) {
172
-			$ready = false;
173
-		}
174
-	}
175
-
176
-	if ($ready) {
177
-		$smarty->addStylesheet($metadata['APP_URL'] . '/css/canvas-api-via-lti.css', 'starter-canvas-api-via-lti');
178
-		$smarty->addStylesheet($metadata['APP_URL'] . '/css/app.css');
179
-
180
-		if (!midLaunch() || !defined('IGNORE_LTI')) {
181
-			require_once(__DIR__ . '/common-app.inc.php');
182
-		}
183
-	}
156
+    /* allow web apps to use common.inc.php without LTI authentication */
157
+    if (!defined('IGNORE_LTI')) {
158
+
159
+        try {
160
+            if (midLaunch()) {
161
+                $ready = false;
162
+            } elseif (isset($_SESSION['toolProvider'])) {
163
+                $toolProvider = $_SESSION['toolProvider'];
164
+            } else {
165
+                throw new CanvasAPIviaLTI_Exception(
166
+                    'The LTI launch request is missing',
167
+                    CanvasAPIviaLTI_Exception::LAUNCH_REQUEST
168
+                );
169
+            }
170
+
171
+        } catch (CanvasAPIviaLTI_Exception $e) {
172
+            $ready = false;
173
+        }
174
+    }
175
+
176
+    if ($ready) {
177
+        $smarty->addStylesheet($metadata['APP_URL'] . '/css/canvas-api-via-lti.css', 'starter-canvas-api-via-lti');
178
+        $smarty->addStylesheet($metadata['APP_URL'] . '/css/app.css');
179
+
180
+        if (!midLaunch() || !defined('IGNORE_LTI')) {
181
+            require_once(__DIR__ . '/common-app.inc.php');
182
+        }
183
+    }
184 184
 } elseif (php_sapi_name() == 'cli') {
185
-	require_once(__DIR__ . '/common-app.inc.php');
185
+    require_once(__DIR__ . '/common-app.inc.php');
186 186
 }
187 187
 
188 188
 
Please login to merge, or discard this patch.
admin/install-app.inc.php 1 patch
Indentation   +3 added lines, -3 removed lines patch added patch discarded remove patch
@@ -29,9 +29,9 @@
 block discarded – undo
29 29
 $metadata['USER_NAVIGATION_LINK_TEXT'] = '@ACCOUNT_NAVIGATION_LINK_TEXT';
30 30
 
31 31
 $smarty->addMessage(
32
-	'App metadata updated',
33
-	'Application metadata has been updated to create config.xml',
34
-	NotificationMessage::GOOD
32
+    'App metadata updated',
33
+    'Application metadata has been updated to create config.xml',
34
+    NotificationMessage::GOOD
35 35
 );
36 36
 
37 37
 ?>
Please login to merge, or discard this patch.
admin/install.php 2 patches
Indentation   +38 added lines, -38 removed lines patch added patch discarded remove patch
@@ -7,21 +7,21 @@  discard block
 block discarded – undo
7 7
 
8 8
 /* test if we already have a working install... */
9 9
 if ($ready && (!isset($_REQUEST['step']))) {
10
-	$smarty->addMessage(
11
-		'App already installed',
12
-		'It appears that the application has already been installed and is ready for
10
+    $smarty->addMessage(
11
+        'App already installed',
12
+        'It appears that the application has already been installed and is ready for
13 13
 		 use.'
14
-	);
14
+    );
15 15
 	
16 16
 /* ...otherwise, let's start with the SECRETS_FILE */
17 17
 } else {
18
-	if(!file_exists(SECRETS_FILE)) {
19
-		if (isset($_REQUEST['step']) && $_REQUEST['step'] == CanvasAPIviaLTI_Installer::SECRETS_ENTERED_STEP) {
20
-			CanvasAPIviaLTI_Installer::createSecretsFile(CanvasAPIviaLTI_Installer::SECRETS_ENTERED_STEP);
21
-		} else {
22
-			CanvasAPIviaLTI_Installer::createSecretsFile();
23
-		}
24
-	}
18
+    if(!file_exists(SECRETS_FILE)) {
19
+        if (isset($_REQUEST['step']) && $_REQUEST['step'] == CanvasAPIviaLTI_Installer::SECRETS_ENTERED_STEP) {
20
+            CanvasAPIviaLTI_Installer::createSecretsFile(CanvasAPIviaLTI_Installer::SECRETS_ENTERED_STEP);
21
+        } else {
22
+            CanvasAPIviaLTI_Installer::createSecretsFile();
23
+        }
24
+    }
25 25
 }
26 26
 
27 27
 /* establish our database connection */
@@ -29,40 +29,40 @@  discard block
 block discarded – undo
29 29
 $sql = initMySql();
30 30
 
31 31
 try {	
32
-	if (!isset($_REQUEST['step'])) {
33
-		/* load all of our various schema into the database... */
34
-		CanvasAPIviaLTI_Installer::createLTIDatabaseTables();
35
-		CanvasAPIviaLTI_Installer::createAppDatabaseTables();
32
+    if (!isset($_REQUEST['step'])) {
33
+        /* load all of our various schema into the database... */
34
+        CanvasAPIviaLTI_Installer::createLTIDatabaseTables();
35
+        CanvasAPIviaLTI_Installer::createAppDatabaseTables();
36 36
 		
37
-		/* ...and initialize the app metadata... */
38
-		$metadata = CanvasAPIviaLTI_Installer::createAppMetadata();
37
+        /* ...and initialize the app metadata... */
38
+        $metadata = CanvasAPIviaLTI_Installer::createAppMetadata();
39 39
 
40
-		/* ...optionally, acquire an API token for the app */
41
-		CanvasAPIviaLTI_Installer::acquireAPIToken(CanvasAPIviaLTI_Installer::API_DECISION_NEEDED_STEP);
42
-	} else {
43
-		$metadata = new AppMetadata($sql, $secrets->app->id);
44
-		$skip = (isset($_REQUEST['skip']) ? $_REQUEST['skip'] : false);
45
-		CanvasAPIviaLTI_Installer::acquireAPIToken($_REQUEST['step'], $skip);
46
-	}
40
+        /* ...optionally, acquire an API token for the app */
41
+        CanvasAPIviaLTI_Installer::acquireAPIToken(CanvasAPIviaLTI_Installer::API_DECISION_NEEDED_STEP);
42
+    } else {
43
+        $metadata = new AppMetadata($sql, $secrets->app->id);
44
+        $skip = (isset($_REQUEST['skip']) ? $_REQUEST['skip'] : false);
45
+        CanvasAPIviaLTI_Installer::acquireAPIToken($_REQUEST['step'], $skip);
46
+    }
47 47
 } catch (CanvasAPIviaLTI_Installer_Exception $e) {
48
-	$smarty->addMessage(
49
-		'LTI Installer error',
50
-		$e->getMessage() . ' [Error ' . $e->getCode() . ']',
51
-		NotificationMessage::ERROR
52
-	);
53
-	$smarty->display();
54
-	exit;
48
+    $smarty->addMessage(
49
+        'LTI Installer error',
50
+        $e->getMessage() . ' [Error ' . $e->getCode() . ']',
51
+        NotificationMessage::ERROR
52
+    );
53
+    $smarty->display();
54
+    exit;
55 55
 }
56 56
 
57 57
 try {
58
-	/* any additional app-specific install steps */
59
-	require_once('install-app.inc.php');
58
+    /* any additional app-specific install steps */
59
+    require_once('install-app.inc.php');
60 60
 } catch (CanvasAPIviaLTI_Installer_Exception $e) {
61
-	$smarty->addMessage(
62
-		'App Installer error',
63
-		$e->getMessage() . ' [Error ' . $e->getCode() . ']',
64
-		NotificationMessage::ERROR
65
-	);
61
+    $smarty->addMessage(
62
+        'App Installer error',
63
+        $e->getMessage() . ' [Error ' . $e->getCode() . ']',
64
+        NotificationMessage::ERROR
65
+    );
66 66
 }
67 67
 
68 68
 /* reset $metadata to get update any computed values */
Please login to merge, or discard this patch.
Spacing   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -15,7 +15,7 @@
 block discarded – undo
15 15
 	
16 16
 /* ...otherwise, let's start with the SECRETS_FILE */
17 17
 } else {
18
-	if(!file_exists(SECRETS_FILE)) {
18
+	if (!file_exists(SECRETS_FILE)) {
19 19
 		if (isset($_REQUEST['step']) && $_REQUEST['step'] == CanvasAPIviaLTI_Installer::SECRETS_ENTERED_STEP) {
20 20
 			CanvasAPIviaLTI_Installer::createSecretsFile(CanvasAPIviaLTI_Installer::SECRETS_ENTERED_STEP);
21 21
 		} else {
Please login to merge, or discard this patch.