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
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
|
<?php
namespace app\controllers;
use Registry;
use Render;
use app\controllers\Auth;
use app\extends\App_manager;
use app\models\Cms_model;
use app\extends\Cache_service;
/** Office class
*
* Manages all requests (front/back-office)
*/
class Office {
## -------------------------------------------------------------------------
##
## SERVE METHODS (selects)
##
## -------------------------------------------------------------------------
## PERMITION
## -------------------------------------------------------------------------
/** is admin or permited
*
* shortcut method for checking access authorization
*
* returns true if user belogns to the admin group
* OR has the specified permition/privilege
*
* @param $privilege_id (int)
*
* NOTE:
* unlike the other authorization methods ...
* $privilege_id is NOT an array but a single privilege id
*
* @return true|false
*/
private static function is_admin_or_permited( $privilege_id )
{
return (
Auth::in_admin_group()
|| Auth::hasPermition([ $privilege_id ])
);
}
## SERVE FILE
## -------------------------------------------------------------------------
/** serve file by file_path
* (request is valid only for admin users)
*
* @param $file_path (string): relative file path
* GET @param type (string) : media-type of file
*/
public static function serve_file($file_path)
{
$file = self::get_file_attributes($file_path);
// if user is authorized
if (self::is_admin_or_permited($file['privilege_id'])) {
$media_type = Registry::get('REQUEST')->GET['type']; // get media-type
$real_path = MEDIA_STORAGE_ROOT . $file_path; // construct real path
if (!file_exists($real_path)) {
Render::view('error/404');
} else {
Render::file($real_path, $media_type);
}
} else {
Render::view('error/404', [
'error_code' => 403,
'moto' => 'Forbidden',
'message' => ''
]);
}
}
/** get_file_attributes
*
* returns attributes of a file
* (medias are proxied for speed optimization)
*
* @param $path (string) : file path
* @return $file attributes --or-- false
*/
private static function get_file_attributes($path)
{
$medias = Cache_service::files_attributes();
foreach($medias as $key => $medi) {
if ($medi['path'] == $path) {
return $medi;
}
}
return false;
}
## PETITIONS
## -------------------------------------------------------------------------
## secretarial support / teachers' requests and applications
/** (any) petition
*
* check if user is authorized to view the content;
* if so, prepare and render the petition view
*
* @param $petition_type (string): [common|penalty]
*/
public static function request_petition($petition_tag)
{
// get current user
$manager = new App_manager();
if (!$manager->hasUserToken()) { // if user is not connected
Render::view('error/404', [
'error_code' => 403, // serve forbidden
'moto' => 'Forbidden',
'message' => 'Για να έχετε πρόσβαση, θα πρέπει πρώτα να συνδεθείτε'
]);
die(); // then end;
}
$token = $manager->getUserToken(); // from token
$user = $token->getUser(); // create user
$id = $user->getID(); // keep id user
switch ($petition_tag) { // route to specific type of petition
case 'application':
self::render_application_form(['user' => $user]);
break;
case 'penalty':
self::render_penalty_form(['user' => $user]);
break;
default: // if not a known petition type
Render::view('error/404', [ // then serve not-found
'message' => 'Δεν βρέθηκε το είδος της αίτησης ή του εγγράφου που ζητήσατε.'
]);
}
}
private static function render_application_form($opts)
{
// #1: user-id ---------------------------------------------------------
$user_id = $opts['user']->getID();
// #2: form template ---------------------------------------------------
$form_setup = json_decode(json_encode(APPLICATION_FORM, JSON_UNESCAPED_UNICODE));
// #3: inject default values -------------------------------------------
// #3.1: inject user data
$form_setup->defaults = json_decode( json_encode(
Auth::user_data(), JSON_UNESCAPED_UNICODE
));
// #3.2 inject `sector` and `position` <option>s
// #4: get Form's HTML and Javascript ----------------------------------
$form = JsonToForm::json_form($form_setup, [
['name' => 'user_id', 'value' => $user_id] // pass user identity
]);
// #5: render the view -------------------------------------------------
Render::view('templates/application', ['form' => $form]);
}
/** render penalty form
*
*/
private static function render_penalty_form($opts)
{
// #1: user-id ---------------------------------------------------------
$user_id = $opts['user']->getID();
// #2: form template ---------------------------------------------------
$form_setup = json_decode(json_encode(PENALTY_FORM, JSON_UNESCAPED_UNICODE));
// #3: prepare values to inject; then inject ---------------------------
// #3.1: get all teachers
$teachers_array = Registry::use('database')->runQuery(
"SELECT concat(last_name, ' ', first_name) as TeacherName
FROM user ORDER BY TeacherName", []
);
$teachers = []; // constuct teacher names as a simple array
foreach($teachers_array as $key => $person) {
$teachers[] = $person['TeacherName'];
}
// #3.2: get $key of rapporteur, president and members <select>s
for($i=0; $i < sizeof($form_setup->form) ; $i++) {
if (isset($form_setup->form[$i]->name)) {
if ($form_setup->form[$i]->name == 'rapporteur') { $keyRapporteur = $i; }
if ($form_setup->form[$i]->name == 'president') { $keyPresident = $i; }
if ($form_setup->form[$i]->name == 'members') { $keyMembers = $i; }
}
}
// #3.3: inject <option>s for `rapporteur`, `president` and `members`
$form_setup->form[$keyRapporteur]->options = $teachers;
$form_setup->form[$keyPresident]->options = $teachers;
$form_setup->form[$keyMembers]->options = $teachers;
// #4: get Form's HTML and Javascript ----------------------------------
$form = JsonToForm::json_form($form_setup, [
['name' => 'user_id', 'value' => $user_id] // pass user identity
]);
// #5: render the view -------------------------------------------------
Render::view('templates/penalty', ['form' => $form]);
}
## -------------------------------------------------------------------------
##
## ADMIN METHODS (insert, updated etc.)
##
## -------------------------------------------------------------------------
/** files
* echo all files
*
* @return (array)
*/
public static function files()
{
return Cache_service::files_attributes();
}
/** upload_file
* upload the file to the file system
*
* the method reads the POST and FILES array
* to retrieve all needed parametres
*
* FILES @param file
* POST @param folder : petition's ID or somthing random
* SESSION @param user_id
*/
public static function upload_file()
{
$request = Registry::get('REQUEST');
$uploaded = self::upload_to_fs(); // upload file to file-system
if ($uploaded['success']) {
$media_id = self::define_media([ // define media in database; get id
'title' => $request->POST['title'],
'type' => $uploaded['type'],
'path' => $uploaded['path']
]);
Render::json([ // render results as json
'success' => true,
'id' => $media_id,
'title' => $request->POST['title'],
'path' => $uploaded['path'],
'type' => $uploaded['type']
]);
} else {
Render::json(['success' => false ]);
}
}
/** upload to fs
* upload file to File-System
*
* POST @param folder
* FILES @param file
*/
private static function upload_to_fs()
{
$post = Registry::get('REQUEST')->POST;
$files = Registry::get('REQUEST')->FILES;
// Checks before uploading the file
////////////////////////////////////////////////////////////////////////
// ** 1: file is upladed to temporary folder ---------------------------
if (! is_uploaded_file($files['file']['tmp_name'])) {
return ['success' => false]; // bye!
}
// ** 2: File belongs to the allowed MIME types ------------------------
$allowed_file_types = [
// pdf
'application/pdf',
// images
'image/png', 'image/jpeg',
// word
'application/msword', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
// excel
'application/vnd.ms-excel', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
// rar
'application/vnd.rar', 'application/x-rar-compressed', 'application/octet-stream',
// zip
'application/zip', 'application/x-zip-compressed', 'multipart/x-zip'
// 'application/octet-stream' refers to zip; also to rar (no-need to re-include)
];
// Recomended MIME type checking via mime_content_type():
$mime_type = mime_content_type($files['file']['tmp_name']);
if (! in_array($mime_type, $allowed_file_types)) { // File type NOT allowed ...
return ['success' => false]; // bye!
}
$file_name = $files['file']['name'];
$file_type = $files['file']['type']; // do not take it for granted
$file_size = $files['file']['size'];
$file_tmp = $files['file']['tmp_name'];
$bare_name = pathinfo($file_name, PATHINFO_FILENAME);
$file_ext = pathinfo($file_name, PATHINFO_EXTENSION);
// ** 3: filename or size checks may be added --------------------------
if ($file_name == "") {
return ['success' => false]; // bye!
}
// READY to finaly save/upload the file to CDN /////////////////////////
$folder = MEDIA_STORAGE_ROOT . $post['folder'];
if (!file_exists($folder)) { // create folder if not exists
mkdir($folder, 0757, true);
}
// print_r([
// 'dir' => $folder,
// 'file' => $bare_name,
// 'ext' => $file_ext,
// 'type' => $file_type
// ]); die();
$relative_filename = $post['folder']
.'/'
. strtolower(self::clear_file_name($bare_name) .'.'. $file_ext);
$store_filename = MEDIA_STORAGE_ROOT . $relative_filename;
if (move_uploaded_file($files["file"]["tmp_name"], $store_filename)) {
return [
'success' => true,
'path' => $relative_filename,
'type' => $mime_type
];
} else { return ['success' => false]; }
}
/** clear_file_name
* replace greek characters and strip symbols
*/
private static function clear_file_name($str)
{
$el = mb_split( "ΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡΣΤΥΦΧΨΩαβγδεζηθικλμνξοπρστυφχψωάέήίόύώϊϋς ", "");
$en = str_split("ABGDEZHUIKLMNJOPRSTYFXCVabgdezhuiklmnjoprstyfxcvaehioyviys-");
$strip = str_split("!@#$%^&*()+~`[]{};'/<>?=\"");
return str_replace($strip, '', str_replace($el, $en, $str));
}
/** define_media
*
* create a record in media table
*
* @param $data (array): [title => , path => , type => mime-type]
* @return id (int): id of created media record
*/
private static function define_media($data)
{
$request = Registry::get('REQUEST');
$media_id = Registry::use('database')->query(
"INSERT INTO media (label, `type`, `path`)
VALUES (:label, :mimetype, :filepath)",
[
'label' => $data['title'],
'mimetype' => $data['type'],
'filepath' => $data['path']
]
)->lastInsertID();
return $media_id;
}
/** create media for petition
*
* links petition to each media-file of the media `id`s array
*
* @param $media (array): a list of media-file `id`s
* @param $petition_id (int)
*/
private static function create_medias_for_petition($medias, $petition_id)
{
foreach($medias as $key => $medi) {
self::link_media_to_petition($medi, $petition_id); // link to petition
}
return true;
}
/** link one media-file to a specific post
*
* NOTE:
* the method does not check if media is linked already
* so be sure that the pair of (media_id,post_id) not exist
*
* @param $media_id (int)
* @param $petition_id (int)
*/
private static function link_media_to_petition( $media_id, $petition_id )
{
Registry::use('database')->runQuery(
"INSERT INTO petition_media (petition_id, media_id)
VALUES (:petition, :media)",
[
'petition' => $petition_id,
'media' => $media_id,
]
);
return true;
}
}
|