-
Notifications
You must be signed in to change notification settings - Fork 0
/
forms_process.class.php
758 lines (673 loc) · 17.2 KB
/
forms_process.class.php
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
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
<?php
error_reporting( E_ALL );
ini_set( 'display_errors', 1 );
class ErrorMessages {
const PHONE_FORMAT = 'Error: Format invalid! Phone number should be between %d and %d characteres. Also the format should be as following +33123456789, your is as following %d';
const EMAIL_FORMAT = 'Error: Email format is invalid';
const METHOD_DOESNT_EXIST = 'Error: There is no method %s!';
const ALREADY_EXIST = 'Error: %s already exist';
const COLUMN_DOESNT_EXIST = 'Error: %s column do not exist in the database!';
const IS_NOT_STRING = 'Error: Please enter a string separated by space.<br>i.e: email phone lastname';
const COMBINE_IMPOSSIBLE = 'Error: There is %d values and %d columns. There should have the same number';
const MAX_MIN_LENGTH_ERROR = '%s contains %d characteres, while it should contains %d characteres!';
}
class Form {
/**
* $post
*
* @var mixed
*
* @access private
*/
public $aFields, $aColumns, $sTable, $currentValue, $currentColumn, $aCombined;
public static $post;
/**
* $flag
*
* @var mixed
*
* @access private
*/
private $flag = true;
/**
* $dbProcess
*
* @var mixed
*
* @access private
*/
private $dbProcess = null;
// if the method doesnt exist the method is called in the DbProcess Class
/**
* __call
*
* @param mixed $method Description.
* @param mixed $arguments Description.
*
* @access public
*
* @return mixed Value.
*/
public function __call( $method, $arguments ) {
if ( !$this->dbProcess )
$this->dbProcess = new DbProcess();
// prepare the array for call_user_func_array
$handler = array( $this->dbProcess, $method );
$argv = $arguments;
if ( !is_callable( $handler ) )
exit( printf( ErrorMessages::METHOD_DOESNT_EXIST, $method ) );
else {
call_user_func_array( $handler, $argv );
}
}
// Constructor
/**
* __construct
*
* @param array $post Description.
*
* @access public
*
* @return mixed Value.
*/
public function __construct( $post = array() ) {
self::$post = $post;
if ( !$this->dbProcess )
$this->dbProcess = new DbProcess();
if ( count( $post ) === 0 ) {
throw new Exception( 'POST is empty!' );
}
}
/**
* create an array containing all
*
* @param mixed $fields Description.
*
* @access public
*
* @return mixed Value.
*/
public function setFields( $fields = null ) {
if ( gettype( $fields ) != 'string' || func_num_args() > 1 || empty( $fields ) )
throw new Exception( ErrorMessages::IS_NOT_STRING );
$this->aFields = array_merge((array)$this->aFields, explode( ' ', $fields ));
// if columns are also defined then combine them
if ( $this->aColumns )
$this->combine();
return $this;
}
/**
* alias for setFields
*
* @access public
*
* @return mixed Value.
*/
public function setValues( $values ) {
return $this->setFields( $values );
}
// Set the columns name from the database
/**
* setColumns
*
* @param string $columns Description.
*
* @access public
*
* @return mixed Value.
*/
public function setColumns( $columns = '' ) {
if ( gettype( $columns ) != 'string' || func_num_args() > 1 || empty( $columns ) )
throw new Exception( ErrorMessages::IS_NOT_STRING );
// select the columns where will be saved the data
$this->aColumns = array_merge( (array)$this->aColumns, explode( ' ', $columns ) );
if ( $this->aFields )
$this->combine();
return $this;
}
/**
* setTable
*
* @param mixed $table Description.
*
* @access public
*
* @return mixed Value.
*/
public function setTable( $table ) {
$this->sTable = DbProcess::$sTable = $table;
return $this;
}
// Save
/**
* save
*
* @access public
*
* @return mixed Value.
*/
public function save() {
$validData = array_map( "self::getValidFields", $this->aFields );
return DbProcess::insert( $validData, $this->aColumns );
}
// check whether the value exist
/**
* exist
*
* @access public
*
* @return mixed Value.
*/
public function exist() {
DbProcess::exist( $this->currentValue, array_search( $this->currentColumn, $this->aCombined ) );
return $this;
}
/**
* fixe a typo
*
* @access public
*
* @return bool return whether .
*/
public function exists() {
return $this->exist();
}
// Call to check the data received
/**
* Output the data received from the form
*
* @access public
*
* @return mixed Value.
*/
public function received() {
echo '<pre>';
echo var_dump( self::$post );
echo '</pre>';
}
/**
* get the ip of the user and set it to a defined column
*
* @param string $str name of the column.
*
* @access public
*
* @return mixed Value.
*/
public function addIP( $str = 'user_ip' ) {
$this->add( $str, Extras::getIp() );
return $this;
}
/**
* addDate
*
* @param string $str Description.
* @param string $format Description.
*
* @access public
*
* @return mixed Value.
*/
public function addDate( $str = 'created_at', $format = "Y-m-d H:i:s" ) {
$this->add( $str, date( $format ) );
return $this;
}
/**
* add
*
* @param string $str Description.
* @param string $value Description.
*
* @access public
*
* @return mixed Value.
*/
public function add( $str = '', $value = '' ) {
if ( gettype( $str ) == 'array' ) {
foreach ( $str as $column => $field ) {
$this->setColumns( $column );
$this->setFields( $column );
self::$post[$column] = $str[$column];
}
}else {
$this->setColumns( $str );
$this->setFields( $str );
self::$post[$str] = $value;
}
return $this;
}
// set the value and the column name
/**
* check
*
* @param mixed $str Description.
*
* @access public
*
* @return mixed Value.
*/
public function check( $str ) {
$this->currentValue = self::$post[$str];
$this->currentColumn = $str;
return $this;
}
// Check whether it's an email formatted
/**
* isEmail
*
* @access public
*
* @return mixed Value.
*/
public function isEmail() {
$email = $this->currentValue;
$reg = "/^[^@]*@[^@]*\.[^@]*$/";
if ( !preg_match( $reg, $email, $m ) ) {
exit( ErrorMessages::EMAIL_FORMAT );
}
return $this;
}
// Check whether it's a phone type
/**
* isPhone
*
* @param int $minlength Description.
* @param int $maxlength Description.
*
* @access public
*
* @return mixed Value.
*/
public function isPhone( $minlength = 5, $maxlength = 50 ) {
$phone = $this->currentValue;
$error = sprintf( ErrorMessages::PHONE_FORMAT, $minlength, $maxlength, $this->currentValue );
$reg = "/^(([0\+]\d{2,5}-?)?\d{5,20}|\d{5,15})$/";
if ( !preg_match( $reg, $phone, $match ) || ( strlen( $phone ) < $minlength || strlen( $phone ) > $maxlength ) ) {
exit( Extras::wrap( $error, 'span', 'phoneError' ) );
}
return $this;
}
// check the max size
/**
* maxLength
*
* @param int $length Description.
*
* @access public
*
* @return mixed Value.
*/
public function maxLength( $length = 10 ) {
$str = $this->currentValue;
if ( strlen( $str ) > $length ) {
exit( printf( ErrorMessages::MAX_MIN_LENGTH_ERROR, $str, strlen( $str ), $length ) );
}
return $this;
}
// check the min size
/**
* minLength
*
* @param int $length Description.
*
* @access public
*
* @return mixed Value.
*/
public function minLength( $length = 10 ) {
$str = $this->currentValue;
if ( strlen( $str ) < $length ) {
exit( printf( ErrorMessages::MAX_MIN_LENGTH_ERROR, $str, strlen( $str ), $length ) );
}
return $this;
}
// combine the fields and column into one array with key
/**
* combine
*
* @access private
*
* @return mixed Value.
*/
private function combine() {
if ( count( $this->aColumns ) != count( $this->aFields ) ){
return;
exit( printf( ErrorMessages::COMBINE_IMPOSSIBLE, count( $this->aFields ), count( $this->aColumns ) ) );
}
$this->aCombined = array_combine( $this->aColumns, $this->aFields );
}
//
/**
* getValidFields
*
* @param mixed $str Description.
*
* @access private
*
* @return mixed Value.
*/
private function getValidFields( $str ) {
$str = ltrim($str);
if ( !isset( self::$post[$str] ) || gettype( self::$post[$str] ) != 'string' ) {
$error = "Error: <b class='missing'> {strtoupper($str)} </b> does not exist, here is the list of received <b>"
. "{count(self::post)}</b> variables:<br />"
. implode('<br />', array_keys(self::$post))
. "<br />While it should receive those <b>".count($this->aFields)."</b> variables:<br />"
. implode('<br />', $this->aFields);
Extras::wrap( $error, "div", "error" );
}
return self::$post[$str];
}
}
class DbProcess {
/**
* $host
*
* @var string Must be kept static because the method setting it is called from an other class
*
* @access public
* @static
*/
public static $host = null;
/**
* $username
*
* @var string
*
* @access public
* @static
*/
/**
* $username
*
* @var string
*
* @access public
* @static
*/
public static $username = null;
/**
* $password
*
* @var string
*
* @access public
* @static
*/
public static $password = null;
/**
* $database
*
* @var string
*
* @access public
* @static
*/
public static $database = null;
/**
* $conf_file
*
* @var string
*
* @access public
* @static
*/
public static $conf_file = 'conf.php';
/**
* $sTable
*
* @var mixed
*
* @access public
* @static
*/
public static $sTable;
/**
* __construct
*
* @access public
*
* @return mixed Value.
*/
public function __construct() {
if ( !isset( $this->connection ) ) {
try{
self::setCredential();
}
catch(Exception $e){
echo $e;
}
$this->connection = $this->dbConnect();
}
}
/**
* dbConnect
*
* @access private
*
* @return mixed Value.
*/
private static function dbConnect() {
try{
$bdd = new PDO( "mysql:host=".self::$host.";dbname=".self::$database, self::$username, self::$password, array( PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8' ) );
}
catch( Exception $e ) {
die( "error: ".$e->getMessage() );
}
return $bdd;
}
public function setConnection( $host = '', $user = '', $password = '', $database = '' ) {
self::$host = $host;
self::$username = $user;
self::$password = $password;
self::$database = $database;
return self::dbConnect();
}
/**
* setCredential
*
* @access private
*
* @return mixed Value.
*/
private function setCredential() {
$conf_file = self::$conf_file;
if ( file_exists( dirname(__FILE__).'/'.$conf_file ) ) {
$config = require_once $conf_file;
}
else{
throw new Exception('Configuration file does not exists');
}
if ( is_null( self::$host ) ) {
self::$host = $config['db']['host'];
}
if ( is_null( self::$username ) ) {
self::$username = $config['db']['username'];
}
if ( is_null( self::$password ) ) {
self::$password = $config['db']['password'];
}
if ( is_null( self::$database ) ) {
self::$database = $config['db']['database'];
}
}
/**
* insert data in DB
*
* @param mixed $fields Description.
* @param mixed $columns Description.
*
* @access public
*
* @return mixed Value.
*/
public static function insert( $fields, $columns ) {
$table = self::$sTable;
$bdd = self::dbConnect();
$fields = get_magic_quotes_gpc() ? array_map( 'stripslashes', $fields ) : $fields;
$columns = get_magic_quotes_gpc() ? array_map( 'stripslashes', $columns ) : $columns;
$sql = "INSERT INTO $table (".implode( ', ', $columns ).") VALUES (".implode( ',', array_fill( 0, count( $fields ), '?' ) ).")";
$response = $bdd->prepare( $sql );
$saved = $response->execute( $fields );
return $saved;
// $arr = $response->errorInfo();
// print_r($arr);
}
/**
* exist
*
* @param mixed $val Description.
* @param mixed $col Description.
*
* @access public
*
* @return mixed Value.
*/
public static function exist( $val, $col ) {
$table = self::$sTable;
$bdd = self::dbConnect();
$sql = "SELECT count(*) AS total FROM $table WHERE $col=:val";
$response = $bdd->prepare( $sql );
$response->bindParam( ':val', $val, PDO::PARAM_STR );
$response->execute();
$row = $response->fetch();
if ( $row['total'] > 0 ) {
exit( printf( ErrorMessages::ALREADY_EXIST, $val ) );
}
// debug
// $arr = $response->errorInfo();
// print_r($arr);
}
public function tableExists( $tableName = '' ) {
if ( $tableName === '' ) {
$tableName = self::$sTable;
}
$bdd = self::dbConnect();
return gettype( $bdd->exec( "SELECT count(*) FROM $tableName" ) ) == "integer";
}
/**
* getStructure
*
* @param mixed $table Description.
* @param mixed $io Description.
*
* @access public
*
* @return mixed Value.
*/
public function getStructure( $table = null, $io = true ) {
if ( gettype( $table ) === 'NULL' ) {
exit( 'No table defined' );
}
$bdd = self::dbConnect();
if ( self::tableExists( $table ) ) {
$response = $bdd->prepare( "DESCRIBE {$table}" );
$response->execute();
while ( $row = $response->fetch( PDO::FETCH_ASSOC ) ) {
$total = Extras::pluralize( 'column', count( $row ) );
$rows[] = $row;
$fields[] = $row['Field'];
}
if ( $io ) {
print "There is <b>{$total}</b> in <b>{$table}</b> table.<br />";
// print_r($fields);
print implode( "<br>", array_map( function( $str, $row ) {
return Extras::wrapper( $str, 'input', array(), true ).$row['Type'];
}, $fields, $rows ) );
}
return $fields;
}
else {
exit( "Table `{$table}` doesn't exist" );
}
}
/**
* showTables
*
* @param mixed $io Description.
*
* @access public
*
* @return mixed Value.
*/
public function showTables( $io = true ) {
$bdd = self::dbConnect();
$sql = 'SHOW TABLES';
$response = $bdd->prepare( $sql );
$response->execute();
while ( $row = $response->fetch() ) {
$tables[] = $row[0];
}
if ( $io ) {
echo 'There is '
// total number of tables
. Extras::pluralize( "table", count( $tables ) )
// database name
. ' into the '.self::DATABASE.' database:<br />'
// liste of the tables
. implode( '<br />', $tables ).'<br />';
}
return implode( ', ', $tables );
}
}
class Extras {
public function __construct() {
exit( 'Fobidden Access!' );
}
/**
* pluralize
*
* @param mixed $str Description.
* @param mixed $count Description.
*
* @access public
*
* @return mixed Value.
*/
public static function pluralize( $str, $count ) {
return $count > 1 ? "$count {$str}s" : "$count $str";
}
/**
* wrap
*
* @param mixed $str Description.
* @param string $tag Description.
* @param string $id Description.
* @param string $class Description.
*
* @access public
*
* @return mixed Value.
*/
public static function wrap( $str, $tag = 'span', $id = '', $class = '' ) {
return "<$tag id='$id' class='$class'>$str</$tag>";
}
public static function wrapper( $str, $tag, $attributes = array(), $selfclose = false ) {
if ( !$selfclose )
return "<$tag ".implode( ' ', $attributes ).">$str</$tag>";
return "<$tag ".implode( ' ', $attributes )." value='$str'/>";
}
/**
* getIp
*
* @access public
*
* @return mixed Value.
*/
public static function getIp() {
$ip = $_SERVER['REMOTE_ADDR'];
if ( !empty( $_SERVER['HTTP_CLIENT_IP'] ) )
$ip = $_SERVER['HTTP_CLIENT_IP'];
elseif ( !empty( $_SERVER['HTTP_X_FORWARDED_FOR'] ) )
$ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
return $ip;
}
public static function printVarName( $v ) {
$trace = debug_backtrace();
$vLine = file( __FILE__ );
$fLine = $vLine[ $trace[0]['line'] - 1 ];
preg_match( "#\\$(\w+)#", $fLine, $match );
print_r( $match );
}
}
?>