Completed
Push — master ( 505b4c...62d9c0 )
by Seth
05:17 queued 03:12
created

common.inc.php (8 issues)

Upgrade to new PHP Analysis Engine

These results are based on our legacy PHP analysis, consider migrating to our new PHP analysis engine instead. Learn more

1
<?php
0 ignored issues
show
Coding Style Compatibility introduced by
For compatibility and reusability of your code, PSR1 recommends that a file should introduce either new symbols (like classes, functions, etc.) or have side-effects (like outputting something, or including other files), but not both at the same time. The first symbol is defined on line 5 and the first side effect is on line 3.

The PSR-1: Basic Coding Standard recommends that a file should either introduce new symbols, that is classes, functions, constants or similar, or have side effects. Side effects are anything that executes logic, like for example printing output, changing ini settings or writing to a file.

The idea behind this recommendation is that merely auto-loading a class should not change the state of an application. It also promotes a cleaner style of programming and makes your code less prone to errors, because the logic is not spread out all over the place.

To learn more about the PSR-1, please see the PHP-FIG site on the PSR-1.

Loading history...
2
3
require_once(__DIR__ . '/vendor/autoload.php');
4
5
define('SECRETS_FILE', __DIR__ . '/secrets.xml');
6
define('SCHEMA_FILE', __DIR__ . '/admin/schema-app.sql');
7
define('MYSQL_PREFIX', '');
8
9
use Battis\AppMetadata;
10
use smtech\StMarksSmarty\StMarksSmarty;
11
12
/**
13
 * Test if the app is in the middle of launching
14
 *
15
 * Wait for $toolProvider to be fully initialized before starting the app logic.
16
 *
17
 * @return boolean
18
 **/
19
function midLaunch() {
0 ignored issues
show
midLaunch uses the super-global variable $_SERVER which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
20
	global $metadata; // FIXME grown-ups don't program like this
0 ignored issues
show
Compatibility Best Practice introduced by
Use of global functionality is not recommended; it makes your code harder to test, and less reusable.

Instead of relying on global state, we recommend one of these alternatives:

1. Pass all data via parameters

function myFunction($a, $b) {
    // Do something
}

2. Create a class that maintains your state

class MyClass {
    private $a;
    private $b;

    public function __construct($a, $b) {
        $this->a = $a;
        $this->b = $b;
    }

    public function myFunction() {
        // Do something
    }
}
Loading history...
21
	return $metadata['APP_LAUNCH_URL'] === (($_SERVER['HTTPS'] === 'on' ? 'https://' : 'http://') . $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI']);
22
}
23
24
/**
25
 * Initialize a SimpleXMLElement from the SECRETS_FILE
26
 *
27
 * @return SimpleXMLElement
28
 *
29
 * @throws CanvasAPIviaLTI_Exception MISSING_SECRETS_FILE if the SECRETS_FILE cannot be found
30
 * @throws CanvasAPIviaLTI_Exception INVALID_SECRETS_FILE if the SECRETS_FILE exists, but cannot be parsed
31
 **/
32
function initSecrets() {
33
	if (file_exists(SECRETS_FILE)) {
34
		// http://stackoverflow.com/a/24760909 (oy!)
35
		if (($secrets = simplexml_load_string(file_get_contents(SECRETS_FILE))) !== false) {
36
			return $secrets;
37
		} else {
38
			throw new CanvasAPIviaLTI_Exception(
39
				SECRETS_FILE . ' could not be loaded. ',
40
				CanvasAPIviaLTI_Exception::INVALID_SECRETS_FILE
41
			);
42
		}
43
	} else {
44
		throw new CanvasAPIviaLTI_Exception(
45
			SECRETS_FILE . " could not be found.",
46
			CanvasAPIviaLTI_Exception::MISSING_SECRETS_FILE
47
		);
48
	}
49
}
50
51
/**
52
 * Initialize a mysqli connector using the credentials stored in SECRETS_FILE
53
 *
54
 * @uses initSecrets() If $secrets is not already initialized
55
 *
56
 * @return mysqli A valid mysqli connector to the database backing the CanvasAPIviaLTI instance
57
 *
58
 * @throws CanvasAPIviaLTI_Exception MYSQL_CONNECTION if a mysqli connection cannot be established
59
 **/
60
function initMySql() {
61
	global $secrets; // FIXME grown-ups don't program like this
0 ignored issues
show
Compatibility Best Practice introduced by
Use of global functionality is not recommended; it makes your code harder to test, and less reusable.

Instead of relying on global state, we recommend one of these alternatives:

1. Pass all data via parameters

function myFunction($a, $b) {
    // Do something
}

2. Create a class that maintains your state

class MyClass {
    private $a;
    private $b;

    public function __construct($a, $b) {
        $this->a = $a;
        $this->b = $b;
    }

    public function myFunction() {
        // Do something
    }
}
Loading history...
62
	if (!($secrets instanceof SimpleXMLElement)) {
63
		$secrets = initSecrets();
64
	}
65
	
66
	/* turn off warnings, since we're going to test the connection ourselves */
67
	set_error_handler(function() {});
68
	$sql = new mysqli(
69
		(string) $secrets->mysql->host,
70
		(string) $secrets->mysql->username,
71
		(string) $secrets->mysql->password,
72
		(string) $secrets->mysql->database
73
	);
74
	restore_error_handler();
75
	
76
	if ($sql->connect_error) {
77
		throw new CanvasAPIviaLTI_Exception(
78
			$sql->connect_error,
79
			CanvasAPIviaLTI_Exception::MYSQL_CONNECTION
80
		);
81
	}
82
	return $sql;
83
}
84
85
/**
86
 * Initialize AppMetadata
87
 *
88
 * @return \Battis\AppMetadata
89
 **/
90
function initAppMetadata() {
91
	global $secrets; // FIXME grown-ups don't program like this
0 ignored issues
show
Compatibility Best Practice introduced by
Use of global functionality is not recommended; it makes your code harder to test, and less reusable.

Instead of relying on global state, we recommend one of these alternatives:

1. Pass all data via parameters

function myFunction($a, $b) {
    // Do something
}

2. Create a class that maintains your state

class MyClass {
    private $a;
    private $b;

    public function __construct($a, $b) {
        $this->a = $a;
        $this->b = $b;
    }

    public function myFunction() {
        // Do something
    }
}
Loading history...
92
	global $sql; // FIXME grown-ups don't program like this
0 ignored issues
show
Compatibility Best Practice introduced by
Use of global functionality is not recommended; it makes your code harder to test, and less reusable.

Instead of relying on global state, we recommend one of these alternatives:

1. Pass all data via parameters

function myFunction($a, $b) {
    // Do something
}

2. Create a class that maintains your state

class MyClass {
    private $a;
    private $b;

    public function __construct($a, $b) {
        $this->a = $a;
        $this->b = $b;
    }

    public function myFunction() {
        // Do something
    }
}
Loading history...
93
	
94
	$metadata = new AppMetadata($sql, (string) $secrets->app->id);
95
	
96
	return $metadata;
97
}
98
99
/**
100
 * Preformat `var_dump()`
101
 *
102
 * @param mixed $var
103
 *
104
 * @return void
105
 **/
106
function html_var_dump($var) {
107
	echo '<pre>';
108
	var_dump($var);
0 ignored issues
show
Security Debugging Code introduced by
var_dump($var); looks like debug code. Are you sure you do not want to remove it? This might expose sensitive data.
Loading history...
109
	echo '</pre>';
110
}
111
112
/*****************************************************************************
113
 *                                                                           *
114
 * The script begins here                                                    *
115
 *                                                                           *
116
 *****************************************************************************/
117
118
/* assume everything's going to be fine... */
119
$ready = true;
120
121
/* preliminary interactive only initialization */
122
if (php_sapi_name() != 'cli') {
123
	session_start(); 
124
125
	/* fire up the templating engine for interactive scripts */
126
	$smarty = StMarksSmarty::getSmarty();
127
	$smarty->addTemplateDir(__DIR__ . '/templates', 'starter-canvas-api-via-lti');
128
	$smarty->setFramed(true);
129
}
130
131
/* initialization that needs to happen for interactive and CLI scripts */
132
try {
133
	/* initialize global variables */
134
	$secrets = initSecrets();
135
	$sql = initMySql();
136
	$metadata = initAppMetadata();
137
} catch (CanvasAPIviaLTI_Exception $e) {
138
	$smarty->addMessage(
139
		'Initialization Failure',
140
		$e->getMessage(),
141
		NotificationMessage::ERROR
142
	);
143
	$smarty->display();
144
	exit;
145
}
146
147
/* interactive initialization only */
148
if ($ready && php_sapi_name() != 'cli') {
149
		
150
	/* allow web apps to use common.inc.php without LTI authentication */
151
	if (!defined('IGNORE_LTI')) {
152
		
153
		try {
154
			if (midLaunch()) {
155
				$ready = false;
156
			} elseif (isset($_SESSION['toolProvider'])) {
157
				$toolProvider = $_SESSION['toolProvider'];
158
			} else {
159
				throw new CanvasAPIviaLTI_Exception(
160
					'The LTI launch request is missing',
161
					CanvasAPIviaLTI_Exception::LAUNCH_REQUEST
162
				);
163
			}
164
			
165
		} catch (CanvasAPIviaLTI_Exception $e) {
166
			$ready = false;
167
		}
168
	}
169
170
	if ($ready) {
171
		$smarty->addStylesheet($metadata['APP_URL'] . '/css/canvas-api-via-lti.css', 'starter-canvas-api-via-lti');
172
		$smarty->addStylesheet($metadata['APP_URL'] . '/css/app.css');
173
		
174
		if (!midLaunch() || !defined('IGNORE_LTI')) {
175
			require_once(__DIR__ . '/common-app.inc.php');
176
		}
177
	}
178
}
179
180
181
?>
0 ignored issues
show
It is not recommended to use PHP's closing tag ?> in files other than templates.

Using a closing tag in PHP files that only contain PHP code is not recommended as you might accidentally add whitespace after the closing tag which would then be output by PHP. This can cause severe problems, for example headers cannot be sent anymore.

A simple precaution is to leave off the closing tag as it is not required, and it also has no negative effects whatsoever.

Loading history...