{{ message }}
Repository navigation
Expand file tree
/
Copy pathfunctions.php
More file actions
305 lines (259 loc) · 9.06 KB
/
Copy pathfunctions.php
File metadata and controls
305 lines (259 loc) · 9.06 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
<?php
/*
|--------------------------------------------------------------------------
| BasicPHP Functions Library
|--------------------------------------------------------------------------
|
| These are core functions necessary to run the nano-framework:
|
| 1. url_value() - retrieves the URL path substring separated by '/'
| 2. route_rpc() - JSON-RPC v2.0 compatibility layer
| 3. route_auto() - automatic routing of URL path to Class and method
| 4. route_class() - routes URL path request to Controllers
| 5. view() - passes data and renders the View
| 6. pdo_conn() - PHP Data Objects (PDO) database connection
| 7. api_response() - handles API response
| 8. api_call() - handles API call
| 9. esc() - uses htmlspecialchars() to prevent XSS
| 10. csrf_token() - uses sessions to create per request CSRF token
|
*/
/**
* Get URL path string value after the BASE_URL.
*
* @param integer $order - URL substring position from the BASE_URL
* - url_value(1) as first string after BASE_URL
*/
function url_value($order)
{
if (isset($_SERVER[URL_PARSE])) {
$url = explode('/', $_SERVER[URL_PARSE]);
}
if (isset($url[$order+SUB_DIR]) || ! empty($url[$order+SUB_DIR])) {
return $url[$order+SUB_DIR];
} else {
return false;
}
}
/**
* JSON-RPC v2.0 Compatibility Layer with 'method' member as 'class.method'
*/
function route_rpc()
{
// Check if HTTP request method is 'POST', if there is POSTed data, and the POSTed data is in JSON format.
if ($_SERVER['REQUEST_METHOD'] == 'POST' && file_get_contents('php://input') !== false && json_decode(file_get_contents('php://input'), true) !== null) {
$json_rpc = json_decode(file_get_contents('php://input'), true);
// Requires the 'jsonrpc', 'method' and 'id' members of the request object
if (isset($json_rpc['jsonrpc']) && isset($json_rpc['method']) && isset($json_rpc['id'])) {
if (strstr($json_rpc['method'], '.') == false) {
exit(json_encode(['jsonrpc' => '2.0', 'error' => ['code' => 32600, 'message' => "The JSON-RPC 'method' member should have the format 'class.method'."], 'id' => $json_rpc['id']]));
}
list($class, $method) = explode('.', $json_rpc['method']);
$class = ucfirst($class) . CONTROLLER_SUFFIX;
$method = lcfirst($method);
if (class_exists($class)) {
$object = new $class();
if (method_exists($object, $method)) {
$object->$method();
exit();
} else {
exit(json_encode(['jsonrpc' => '2.0', 'error' => ['code' => 32601, 'message' => "Method not found."], 'id' => $json_rpc['id']]));
}
} else {
exit(json_encode(['jsonrpc' => '2.0', 'error' => ['code' => 32601, 'message' => "Class not found."], 'id' => $json_rpc['id']]));
}
}
}
}
/**
* Automatic routing of url_value(1) and (2) as Class and method
*/
function route_auto()
{
if (url_value(1) !== false) {
$class = ucfirst(url_value(1)) . CONTROLLER_SUFFIX;
}
if (url_value(2) !== false) {
$method = lcfirst(url_value(2));
} else {
$method = METHOD_DEFAULT;
}
if (class_exists($class)) {
$object = new $class();
if (method_exists($object, $method)) {
$object->$method();
} else {
header($_SERVER["SERVER_PROTOCOL"]." 404 Not Found");
exit();
}
}
}
/**
* Load Controller based on URL path string and HTTP method
*
* @param string $http_method - HTTP method (e.g. GET, POST, PUT, DELETE)
* @param string $string - URL path in the format '/url/string'
* - Wildcard convention from Codeigniter 3
* - (:num) for number and (:any) for string
* @param string $class_method - ClassController@method format
*/
function route_class($http_method, $path, $class_method)
{
if ($_SERVER['REQUEST_METHOD'] == $http_method) {
// Convert '/' and wilcards (:num) and (:any) to RegEx
$pattern = str_ireplace('/', '\/', $path);
$pattern = str_ireplace('(:num)', '[0-9]+', $pattern);
$pattern = str_ireplace('(:any)', '[^\/]+', $pattern);
if (URL_PARSE == 'REQUEST_URI') {
$sub = explode('/', BASE_URL);
// Support for upto five (5) subdirectories - index.php from DocumentRoot
if (! empty($sub[3])) {
$sub_1 = '\/' . $sub[3];
} else {
$sub_1 = '';
}
if (! empty($sub[4])) {
$sub_2 = '\/' . $sub[4];
} else {
$sub_2 = '';
}
if (! empty($sub[5])) {
$sub_3 = '\/' . $sub[5];
} else {
$sub_3 = '';
}
if (! empty($sub[6])) {
$sub_4 = '\/' . $sub[6];
} else {
$sub_4 = '';
}
if (! empty($sub[7])) {
$sub_5 = '\/' . $sub[7];
} else {
$sub_5 = '';
}
if (preg_match('/^' . $sub_1.$sub_2.$sub_3.$sub_4.$sub_5 . $pattern . '+$/i', $_SERVER[URL_PARSE])) {
list($class, $method) = explode('@', $class_method);
$object = new $class();
$object->$method();
}
} elseif (URL_PARSE == 'PATH_INFO') {
if (preg_match('/^' . $pattern . '+$/i', $_SERVER[URL_PARSE])) {
list($class, $method) = explode('@', $class_method);
$object = new $class();
$object->$method();
}
}
}
}
/**
* Passes data and renders the View
*
* @param string $view - View file, excluding .php extension
* @param array $data - Data as an array to pass to the View
*/
function view($view, $data=null)
{
// Convert array keys to variables
if (isset($data)) {
extract($data);
}
// Render Page View
require_once '../views/' . $view . '.php';
}
/**
* PHP Data Objects (PDO) database connection
*
* @param string $database - Database (e.g. mysql)
* @param string $servername - Server Name (e.g localhost)
* @param string $dbname - Database Name
* @param string $username - Username
* @param string $password - Password
*/
function pdo_conn($database, $servername, $dbname, $username, $password)
{
$conn = new PDO("$database:host=$servername;dbname=$dbname", $username, $password, array(
PDO::ATTR_PERSISTENT => true
));
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return $conn;
}
/**
* Handles the HTTP REST API Response
*
* @param array $data - Array to be encoded to JSON
* @param string $message - Message to send with response
*/
function api_response($data, $message=null)
{
// Define content type as JSON data through the header
header("Content-Type: application/json; charset=utf-8");
// Data and message as arrays to send with response
$response['data'] = $data;
$response['message'] = $message;
// Encode $response array to JSON
echo json_encode($response);
}
/**
* Handles the HTTP REST API Calls
*
* @param string $http_method - HTTP request method (e.g. 'GET', 'POST')
* @param string $url - URL of external server API
* @param string $data - POST fields in array
* @param string $username - Username
* @param string $password - Password
*/
function api_call($http_method, $url, $data=null, $username=null, $password=null)
{
// Initialize cURL
$ch = curl_init();
// Convert $data array parameter to JSON
$data_json = json_encode($data);
// Set cURL options
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $http_method);
// curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_json);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_USERPWD, "$username:$password");
curl_setopt(
$ch,
CURLOPT_HTTPHEADER,
array(
'Content-Type: application/json',
'Content-Length: ' . strlen($data_json))
);
// Execute cURL
$result = curl_exec($ch);
// Close cURL connection
curl_close($ch);
// Convert JSON response from external server to an array
$data_output = json_decode($result, true);
return $data_output;
}
/**
* Helper function to prevent Cross-Site Scripting (XSS)
* Uses htmlspecialchars() to prevent XSS
*
* @param string $string - String to escape
*/
function esc($string)
{
return htmlspecialchars($string, ENT_QUOTES, 'UTF-8');
}
/**
* Helper function to prevent Cross-Site Request Forgery (CSRF)
* Creates a per request token to handle CSRF using sessions
*/
function csrf_token()
{
if (isset($_SESSION)) {
$_SESSION['csrf-token'] = bin2hex(random_bytes(32));
return $_SESSION['csrf-token'];
} else {
$error_message = 'Please initialize Sessions.';
$page_title = 'Sessions Error';
$data = compact('error_message', 'page_title');
view('error', $data);
}
}
You can’t perform that action at this time.
