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
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
|
<?php //----------------------------------------------------------------------------- // Define //----------------------------------------------------------------------------- define('PROJECT_FOLDER', 'MIS'); define('PROJECT_PATH', '/MIS/'); define('PROJECT_ROOT', $_SERVER['DOCUMENT_ROOT'] . PROJECT_PATH);
//----------------------------------------------------------------------------- // Error reporting level //----------------------------------------------------------------------------- //TODO: Production should comment the next line error_reporting(E_ALL ^ E_NOTICE);
//----------------------------------------------------------------------------- // Timezone //----------------------------------------------------------------------------- date_default_timezone_set('Asia/Hong_Kong'); //date_default_timezone_set('HKT/8.0/no DST');
//----------------------------------------------------------------------------- // Underscore //----------------------------------------------------------------------------- require_once(__DIR__ . '/underscore.php');
//----------------------------------------------------------------------------- // Session //----------------------------------------------------------------------------- if ($without_session_start !== true) { session_start(); }
//----------------------------------------------------------------------------- // Send default header //----------------------------------------------------------------------------- if ($without_send_header !== true) { // IE use last version if ($without_use_last_ie_version !== true) { header('X-UA-Compatible: IE=edge,chrome=1'); } // Powered by if ($without_x_powered_by !== true) { header('X-Powered-By: OneSolution'); } // No cache if ($without_no_cache_header !== true) { // Expires in the past header('Expires: Mon, 26 Jul 1990 05:00:00 GMT'); // Always modified header('Last-Modified: ' . gmdate("D, d M Y H:i:s") . ' GMT'); // HTTP/1.1 header('Cache-Control: no-store, no-cache, must-revalidate'); header('Cache-control: private', false); // IE 6 FIX header('Cache-Control: post-check=0, pre-check=0', false); // HTTP/1.0 header('Pragma: no-cache'); } }
//----------------------------------------------------------------------------- // Connections //----------------------------------------------------------------------------- require_once(__DIR__ . '/db.php'); if ($without_connection !== true) { $PDO_OPTIONS = array( PDO::ATTR_CASE => PDO::CASE_LOWER, PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::ATTR_ORACLE_NULLS => PDO::NULL_NATURAL, PDO::ATTR_STRINGIFY_FETCHES => false, );
//----------------------------------------------------------------------------- // MySQL //----------------------------------------------------------------------------- // development // $dbh = new PDO("mysql:host=127.0.0.1;dbname=pathwaysmisdb", 'pathwayssa', 'df3S8230', $PDO_OPTIONS); // production $dbh = new PDO("mysql:host=192.168.171.21;dbname=pathwaysmisdb", 'pathwayssa', 'df3S8230', $PDO_OPTIONS); $sql = "SET NAMES ?"; $parameters = array('utf8'); $sth = Db\Util::execute($dbh, $sql, $parameters);
//----------------------------------------------------------------------------- // SQL Server //----------------------------------------------------------------------------- // $sqlsrv_dbh = new PDO("sqlsrv:Server=127.0.0.1;Database=DB", 'sa', 'password', $PDO_OPTIONS); }
//----------------------------------------------------------------------------- // Global functions //----------------------------------------------------------------------------- function redirectAndExit($url) { header('Location: ' . $url); exit; }
function isPost() { return strtoupper($_SERVER['REQUEST_METHOD']) == 'POST'; }
function isGet() { return strtoupper($_SERVER['REQUEST_METHOD']) == 'GET'; }
/** * Wrapper of htmlspecialchars() * @param string $text * @param string $charset * @return string */ function h($text, $charset = null) { // return htmlspecialchars($text, ENT_QUOTES | ENT_HTML401, isset($charset) ? $charset : 'UTF-8'); return htmlspecialchars($text, ENT_QUOTES, isset($charset) ? $charset : 'UTF-8'); }
/** * Helper class - Util */ class Util { public static function isAdmin() { $roles = array( 1, // SuperAdmin 2, // Admin ); return in_array($_SESSION['webadmin']['role'], $roles); } public static function getSortDirection(array &$sort, $column) { foreach ($sort as $index => $info) { if (!empty($info['column']) && !empty($info['option']) && $info['column'] == $column) { return $info['option']; } } return null; } public static function getSortDirectionCaretHtml(array &$sort, $column) { $direction = static::getSortDirection($sort, $column); if (isset($direction)) { switch (strtoupper($direction)) { case 'ASC': { return '<span class="dropdown"><i class="caret"></i></span>'; } case 'DESC': { return '<span class="dropdown dropup"><i class="caret"></i></span>'; } } } return ''; } public static function date_to_string(DateTime $datetime, $format = 'Y-m-d') { return $datetime->format($format); } public static function time_to_string(DateTime $datetime, $format = 'H:i:s') { return $datetime->format($format); } public static function value_to_date_string($value, $format = 'Y-m-d') { $output = ''; if (!empty($value)) { $date = DateTime::createFromFormat('Y-m-d', $value); $output = $date->format($format); } return $output; } public static function value_to_time_string($value, $format = 'H:i') { $output = ''; if (!empty($value)) { $date = DateTime::createFromFormat('H:i:s', $value); $output = $date->format($format); } return $output; } // Calculate the age from a given birth date // Example: getAge("1986-06-18"); public static function getAge($birthdate) { $yearDiff = NULL; if ($birthdate != NULL) { // Explode the date into meaningful variables list($birthYear,$birthMonth,$birthDay) = explode("-", $birthdate); // Find the differences $yearDiff = date("Y") - $birthYear; $monthDiff = date("m") - $birthMonth; $dayDiff = date("d") - $birthDay; // If the birthday has not occured this year if ($dayDiff < 0 || $monthDiff < 0) { $yearDiff--; } } return $yearDiff; } /** * This will give * * $a="/home/a.php"; * $b="/home/root/b/b.php"; * echo getRelativePath($a,$b), PHP_EOL; // ./root/b/b.php * and * * $a="/home/apache/a/a.php"; * $b="/home/root/b/b.php"; * echo getRelativePath($a,$b), PHP_EOL; // ../../root/b/b.php * and * * $a="/home/root/a/a.php"; * $b="/home/apache/htdocs/b/en/b.php"; * echo getRelativePath($a,$b), PHP_EOL; // ../../apache/htdocs/b/en/b.php * and * * $a="/home/apache/htdocs/b/en/b.php"; * $b="/home/root/a/a.php"; * echo getRelativePath($a,$b), PHP_EOL; // ../../../../root/a/a.php * * @param type $from * @param type $to * @return type */ public static function getRelativePath($from, $to) { $from = explode('/', $from); $to = explode('/', $to); $relPath = $to;
foreach ($from as $depth => $dir) { // find first non-matching dir if ($dir === $to[$depth]) { // ignore this directory array_shift($relPath); } else { // get number of remaining dirs to $from $remaining = count($from) - $depth; if ($remaining > 1) { // add traversals up to first matching dir $padLength = (count($relPath) + $remaining - 1) * -1; $relPath = array_pad($relPath, $padLength, '..'); break; } else { $relPath[0] = './' . $relPath[0]; } } } return implode('/', $relPath); }
public static function link($filepath) { $from = $_SERVER['SCRIPT_FILENAME']; $to = realpath($filepath); $from = str_replace('\\', '/', $from); $to = str_replace('\\', '/', $to); $link = $from == $to ? '' : Util::getRelativePath($from, $to); if (empty($link) && $from == $to) { $parts = explode('/', $from); $count = count($parts); $link = $parts[$count - 1]; } return $link; } }
class UploadedFiles extends ArrayObject { public function current() { return $this->_normalize(parent::current()); }
public function offsetGet($offset) { return $this->_normalize(parent::offsetGet($offset)); }
protected function _normalize($entry) { if(isset($entry['name']) && is_array($entry['name'])) { $files = array(); foreach($entry['name'] as $k => $name) { $files[$k] = array( 'name' => $name, 'tmp_name' => $entry['tmp_name'][$k], 'size' => $entry['size'][$k], 'type' => $entry['type'][$k], 'error' => $entry['error'][$k] ); } return new self($files); } return $entry; }
public static function codeToMessage($code) { switch ($code) { case UPLOAD_ERR_INI_SIZE: $message = "The uploaded file exceeds the upload_max_filesize directive in php.ini"; break; case UPLOAD_ERR_FORM_SIZE: $message = "The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form"; break; case UPLOAD_ERR_PARTIAL: $message = "The uploaded file was only partially uploaded"; break; case UPLOAD_ERR_NO_FILE: $message = "No file was uploaded"; break; case UPLOAD_ERR_NO_TMP_DIR: $message = "Missing a temporary folder"; break; case UPLOAD_ERR_CANT_WRITE: $message = "Failed to write file to disk"; break; case UPLOAD_ERR_EXTENSION: $message = "File upload stopped by extension"; break;
default: $message = "Unknown upload error"; break; } return $message; } }
//----------------------------------------------------------------------------- // Pagination //----------------------------------------------------------------------------- abstract class Pagination { private $number_per_page = 10; private $show_near_pages = 6; public function setNumberPerPage($number_per_page) { $this->number_per_page = $number_per_page; } public function getNumberPerPage() { return $this->number_per_page; } abstract protected function count(); public function getOffset() { return ($this->getCurrentPage() - 1) * $this->number_per_page; } public function getLimit() { return $this->number_per_page; } public function getCurrentPage() { return max(intval($_GET['page']), 1); } private function getQueryString($cleanPage = true) { $get = $_GET; unset($get['page']); return $get; }
protected function getPrevLink() { $page = $this->getCurrentPage() - 1; return $this->getPageLink($page); }
protected function getNextLink() { $page = $this->getCurrentPage() + 1; return $this->getPageLink($page); }
protected function getPageLink($page) { $get = $this->getQueryString(); $get['page'] = max($page, 1); return '?' . http_build_query($get); } public function pageCount() { $count = $this->count(); $page = $count / floatval($this->number_per_page); if (floor($page) < $page) { $page = floor($page) + 1; } return $page; } private $_cache_to_string; public function toString() { if (!empty($this->_cache_to_string)) { return $this->_cache_to_string; } $pageCount = $this->pageCount(); $currentPage = $this->getCurrentPage(); ob_start(); ?> <div class="pagination"> <ul> <li<?=$currentPage == 1 ? ' class="disabled"' : ''?>><a href="<?=$this->getPrevLink()?>">«</a></li> <?php $is_dot = false; for ($i = 1; $i <= max($pageCount, 1); $i++): $is_show = $i == 1 || $i == $pageCount || abs($currentPage - $i) < $this->show_near_pages; if ($is_show): $is_dot = true; ?> <li<?=$currentPage == $i ? ' class="active"' : ''?>><a href="<?=$this->getPageLink($i)?>"><?=$i?></a></li> <?php elseif ($is_dot): $is_dot = false; ?> <li class="disabled"><a href="javascript:void(0)">...</a></li> <?php endif; endfor; ?> <li<?=$currentPage >= $pageCount ? ' class="disabled"' : ''?>><a href="<?=$this->getNextLink()?>">»</a></li> </ul> </div> <?php $this->_cache_to_string = ob_get_contents(); ob_end_clean(); return $this->_cache_to_string; } }
class MySqlPagination extends Pagination { private $sql; private $parameters; private $dbh; function __construct($sql, $parameters) { global $dbh; $this->sql = $sql; $this->parameters = $parameters; $this->dbh = $dbh; }
protected function count() { $sql = $this->sql; $sql = "SELECT COUNT(*) AS count FROM ( $sql ) t"; if (!($sth = $this->dbh->prepare($sql))) { throw new Exception("sql prepare statement failure: $sql"); } $sth->setFetchMode(PDO::FETCH_ASSOC); if (!$sth->execute($this->parameters)) { throw new Exception("sql execute statement failure: $sql"); } $record = $sth->fetch(PDO::FETCH_ASSOC); return $record['count']; } public function getSqlLimitAndOffset() { $limit = $this->getLimit(); $offset = $this->getOffset(); return " LIMIT $limit OFFSET $offset "; } }
class SqlsrvPagination extends Pagination { private $sql; private $parameters; private $dbh; function __construct($sql, $parameters) { global $sqlsrv_dbh; $this->sql = $sql; $this->parameters = $parameters; $this->dbh = $sqlsrv_dbh; }
protected function count() { $sql = $this->sql; $pos = strpos($sql, "ORDER BY"); if ($pos !== false) { $sql = substr($sql, 0, $pos); } $sql = "SELECT COUNT(*) AS count FROM ( $sql ) t"; if (!($sth = $this->dbh->prepare($sql))) { throw new Exception("sql prepare statement failure: $sql"); } $sth->setFetchMode(PDO::FETCH_ASSOC); if (!$sth->execute($this->parameters)) { throw new Exception("sql execute statement failure: $sql"); } $record = $sth->fetch(PDO::FETCH_ASSOC); return $record['count']; } public function getSql() { $sql = $this->sql; $limit = $this->getLimit(); $offset = $this->getOffset(); $limit = intval($limit); $offset = intval($offset);
if ($offset == 0) return preg_replace('/^SELECT\s/i', 'SELECT TOP ' . $limit . ' ', $sql);
$orderby = stristr($sql, 'ORDER BY'); $over = $orderby ? preg_replace('/\"[^,]*\".\"([^,]*)\"/i', '"inner_tbl"."$1"', $orderby) : 'ORDER BY (SELECT 0)';
// Remove ORDER BY clause from $sql $sql = preg_replace('/\s+ORDER BY(.*)/', '', $sql);
// Add ORDER BY clause as an argument for ROW_NUMBER() $sql = "SELECT ROW_NUMBER() OVER ($over) AS \"AR_ROWNUM\", * FROM ($sql) AS inner_tbl";
$start = $offset + 1; $end = $offset + $limit; return "WITH outer_tbl AS ($sql) SELECT * FROM outer_tbl WHERE \"AR_ROWNUM\" BETWEEN $start AND $end"; } }
//----------------------------------------------------------------------------- // Sign in //----------------------------------------------------------------------------- class SigninController { public function isLogin() { return isset($_SESSION['webadmin']['id']) && strlen($_SESSION['webadmin']['id']); } protected function redirectMain() { redirectAndExit(Util::link(__DIR__ . '/../main.php') . '?' . http_build_query($_GET)); } protected function redirectLogin() { redirectAndExit(Util::link(__DIR__ . '/../login.php') . '?' . http_build_query($_GET)); } public function checkLogin() { if (!$this->isLogin()) { $this->redirectLogin(); } } public function login() { global $dbh; if ($this->isLogin()) { $this->redirectMain(); } $message = null; if (!empty($_GET['message'])) { $message = $_GET['message']; } $message_heading = 'Error!'; if (!empty($_GET['message_heading'])) { $message_heading = $_GET['message_heading']; } $message_css_class = 'alert-error'; if (!empty($_GET['message_css_class'])) { $message_css_class = $_GET['message_css_class']; } if (isPost()) { $name = $_POST['name']; $password = $_POST['password']; $sql = "SELECT * FROM sys_login WHERE loginname = ? AND loginpw = ? AND actived = ? AND deleted = ?"; $parameters = array($name, md5($password), 1, 0); $sth = Db\Util::execute($dbh, $sql, $parameters); $staff = $sth->fetch(PDO::FETCH_ASSOC); if (!empty($staff)) { // Assign webadmin session $_SESSION['webadmin'] = $staff;
// Redirect to job $this->redirectMain(); } $message = 'User name or password not correct.'; $message_heading = 'Error!'; $message_css_class = 'alert-error'; } return array( 'message' => $message, 'message_heading' => $message_heading, 'message_css_class' => $message_css_class, ); } public function logout() { // Clear webadmin session unset($_SESSION['webadmin']); // Redirect to login $this->redirectLogin(); } }
//----------------------------------------------------------------------------- // Static values //----------------------------------------------------------------------------- class General { public static function fields() { return array( 'id', 'createby', 'createdate', 'lastupby', 'lastupdate', ); } public static function genderOptions() { return array( 1 => 'Male', 2 => 'Female', ); } }
class User { public static function roleOptions() { return array( 1 => 'SuperAdmin', 2 => 'Admin', 3 => 'Staff', ); } }
class Staff { public static function statusOptions() { return array( 1 => 'Current', 2 => 'Disable', ); } public static function workingModeOptions() { return array( 1 => 'Full Time', 2 => 'Part Time', ); } public static function attendanceLeaveOptions() { return array( 1 => 'Teacher Sick Leave', 2 => 'Annual Leave', 3 => 'Casual Leave', 4 => 'Students absent', 5 => 'No pay Lesson', ); } }
class Student { public static function statusOptions() { return array( 1 => 'Active', 2 => 'Disable', ); } public static function attendanceLeaveOptions() { return array( 1 => 'Personal Leave', 2 => 'Student Sick Leave', 3 => 'School Event Leave', 4 => 'Makeup class', ); } }
class Event { public static function programmeFeeTypeOptions() { return array( 1 => 'Hourly', 2 => 'Package', ); } public static function schoolTypeOptions() { return array( 1 => 'In-school', 2 => 'Outside school', ); } }
class Lesson { public static function typeOptions() { return array( 1 => 'Learning', 2 => 'Counseling', 3 => 'Consultation', 4 => 'Meeting', 5 => 'Pre-assessment', 6 => 'Post-assessment', ); } }
class Subsidy { public static function typeOptions() { return array( 1 => 'None', 2 => 'Low income family', 3 => 'Family with government subsidy', ); } public static function getAll($dbh) { $sql = "SELECT * FROM mis_subsidy WHERE deleted = ? ORDER BY sort"; $parameters = array(0); $sth = Db\Util::execute($dbh, $sql, $parameters); $subsidies = $sth->fetchAll(); $subsidies2 = array(); foreach ($subsidies as $subsidy) { $subsidies2[$subsidy['type']][] = $subsidy; } return $subsidies2; } }
|