Passed
Branch 1.0.0-dev (c78053)
by nguereza
04:10 queued 15s
created
core/classes/model/Model.php 3 patches
Indentation   +928 added lines, -928 removed lines patch added patch discarded remove patch
@@ -1,595 +1,595 @@  discard block
 block discarded – undo
1 1
 <?php
2
-    defined('ROOT_PATH') || exit('Access denied');
3
-    /**
4
-     * TNH Framework
5
-     *
6
-     * A simple PHP framework using HMVC architecture
7
-     *
8
-     * This content is released under the GNU GPL License (GPL)
9
-     *
10
-     * Copyright (C) 2017 Tony NGUEREZA
11
-     *
12
-     * This program is free software; you can redistribute it and/or
13
-     * modify it under the terms of the GNU General Public License
14
-     * as published by the Free Software Foundation; either version 3
15
-     * of the License, or (at your option) any later version.
16
-     *
17
-     * This program is distributed in the hope that it will be useful,
18
-     * but WITHOUT ANY WARRANTY; without even the implied warranty of
19
-     * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20
-     * GNU General Public License for more details.
21
-     *
22
-     * You should have received a copy of the GNU General Public License
23
-     * along with this program; if not, write to the Free Software
24
-     * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
25
-    */
26
-
27
-
28
-    /**
29
-     * A base model with a series of CRUD functions (powered by CI's query builder),
30
-     * validation-in-model support, event callbacks and more.
31
-     *
32
-     * @link http://github.com/jamierumbelow/codeigniter-base-model
33
-     * @copyright Copyright (c) 2012, Jamie Rumbelow <http://jamierumbelow.net>
34
-     */
35
-
36
-    class Model{
37
-
38
-        /* --------------------------------------------------------------
2
+	defined('ROOT_PATH') || exit('Access denied');
3
+	/**
4
+	 * TNH Framework
5
+	 *
6
+	 * A simple PHP framework using HMVC architecture
7
+	 *
8
+	 * This content is released under the GNU GPL License (GPL)
9
+	 *
10
+	 * Copyright (C) 2017 Tony NGUEREZA
11
+	 *
12
+	 * This program is free software; you can redistribute it and/or
13
+	 * modify it under the terms of the GNU General Public License
14
+	 * as published by the Free Software Foundation; either version 3
15
+	 * of the License, or (at your option) any later version.
16
+	 *
17
+	 * This program is distributed in the hope that it will be useful,
18
+	 * but WITHOUT ANY WARRANTY; without even the implied warranty of
19
+	 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20
+	 * GNU General Public License for more details.
21
+	 *
22
+	 * You should have received a copy of the GNU General Public License
23
+	 * along with this program; if not, write to the Free Software
24
+	 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
25
+	 */
26
+
27
+
28
+	/**
29
+	 * A base model with a series of CRUD functions (powered by CI's query builder),
30
+	 * validation-in-model support, event callbacks and more.
31
+	 *
32
+	 * @link http://github.com/jamierumbelow/codeigniter-base-model
33
+	 * @copyright Copyright (c) 2012, Jamie Rumbelow <http://jamierumbelow.net>
34
+	 */
35
+
36
+	class Model{
37
+
38
+		/* --------------------------------------------------------------
39 39
          * VARIABLES
40 40
          * ------------------------------------------------------------ */
41 41
 
42
-        /**
43
-         * This model's default database table. Automatically
44
-         * guessed by pluralising the model name.
45
-         */
46
-        protected $_table;
47
-
48
-        /**
49
-         * The database connection object. Will be set to the default
50
-         * connection. This allows individual models to use different DBs
51
-         * without overwriting the global database connection.
52
-         */
53
-        protected $_database;
54
-
55
-        /**
56
-         * This model's default primary key or unique identifier.
57
-         * Used by the get(), update() and delete() functions.
58
-         */
59
-        protected $primary_key = 'id';
60
-
61
-        /**
62
-         * Support for soft deletes and this model's 'deleted' key
63
-         */
64
-        protected $soft_delete = false;
65
-        protected $soft_delete_key = 'is_deleted';
66
-        protected $_temporary_with_deleted = FALSE;
67
-        protected $_temporary_only_deleted = FALSE;
68
-
69
-        /**
70
-         * The various callbacks available to the model. Each are
71
-         * simple lists of method names (methods will be run on $this).
72
-         */
73
-        protected $before_create = array();
74
-        protected $after_create = array();
75
-        protected $before_update = array();
76
-        protected $after_update = array();
77
-        protected $before_get = array();
78
-        protected $after_get = array();
79
-        protected $before_delete = array();
80
-        protected $after_delete = array();
81
-
82
-        protected $callback_parameters = array();
83
-
84
-        /**
85
-         * Protected, non-modifiable attributes
86
-         */
87
-        protected $protected_attributes = array();
88
-
89
-        /**
90
-         * Relationship arrays. Use flat strings for defaults or string
91
-         * => array to customise the class name and primary key
92
-         */
93
-        protected $belongs_to = array();
94
-        protected $has_many = array();
95
-
96
-        protected $_with = array();
97
-
98
-        /**
99
-         * An array of validation rules. This needs to be the same format
100
-         * as validation rules passed to the FormValidation library.
101
-         */
102
-        protected $validate = array();
103
-
104
-        /**
105
-         * Optionally skip the validation. Used in conjunction with
106
-         * skip_validation() to skip data validation for any future calls.
107
-         */
108
-        protected $skip_validation = FALSE;
109
-
110
-        /**
111
-         * By default we return our results as objects. If we need to override
112
-         * this, we can, or, we could use the `as_array()` and `as_object()` scopes.
113
-         */
114
-        protected $return_type = 'object';
115
-        protected $_temporary_return_type = NULL;
42
+		/**
43
+		 * This model's default database table. Automatically
44
+		 * guessed by pluralising the model name.
45
+		 */
46
+		protected $_table;
47
+
48
+		/**
49
+		 * The database connection object. Will be set to the default
50
+		 * connection. This allows individual models to use different DBs
51
+		 * without overwriting the global database connection.
52
+		 */
53
+		protected $_database;
54
+
55
+		/**
56
+		 * This model's default primary key or unique identifier.
57
+		 * Used by the get(), update() and delete() functions.
58
+		 */
59
+		protected $primary_key = 'id';
60
+
61
+		/**
62
+		 * Support for soft deletes and this model's 'deleted' key
63
+		 */
64
+		protected $soft_delete = false;
65
+		protected $soft_delete_key = 'is_deleted';
66
+		protected $_temporary_with_deleted = FALSE;
67
+		protected $_temporary_only_deleted = FALSE;
68
+
69
+		/**
70
+		 * The various callbacks available to the model. Each are
71
+		 * simple lists of method names (methods will be run on $this).
72
+		 */
73
+		protected $before_create = array();
74
+		protected $after_create = array();
75
+		protected $before_update = array();
76
+		protected $after_update = array();
77
+		protected $before_get = array();
78
+		protected $after_get = array();
79
+		protected $before_delete = array();
80
+		protected $after_delete = array();
81
+
82
+		protected $callback_parameters = array();
83
+
84
+		/**
85
+		 * Protected, non-modifiable attributes
86
+		 */
87
+		protected $protected_attributes = array();
88
+
89
+		/**
90
+		 * Relationship arrays. Use flat strings for defaults or string
91
+		 * => array to customise the class name and primary key
92
+		 */
93
+		protected $belongs_to = array();
94
+		protected $has_many = array();
95
+
96
+		protected $_with = array();
97
+
98
+		/**
99
+		 * An array of validation rules. This needs to be the same format
100
+		 * as validation rules passed to the FormValidation library.
101
+		 */
102
+		protected $validate = array();
103
+
104
+		/**
105
+		 * Optionally skip the validation. Used in conjunction with
106
+		 * skip_validation() to skip data validation for any future calls.
107
+		 */
108
+		protected $skip_validation = FALSE;
109
+
110
+		/**
111
+		 * By default we return our results as objects. If we need to override
112
+		 * this, we can, or, we could use the `as_array()` and `as_object()` scopes.
113
+		 */
114
+		protected $return_type = 'object';
115
+		protected $_temporary_return_type = NULL;
116 116
     	
117 117
     	
118
-    	/**
118
+		/**
119 119
     		The database cache time 
120
-    	*/
121
-    	protected $dbCacheTime = 0;
122
-
123
-        /**
124
-         * Instance of the Loader class
125
-         * @var Loader
126
-         */
127
-        protected $loaderInstance = null;
128
-
129
-        /**
130
-         * Instance of the FormValidation library
131
-         * @var FormValidation
132
-         */
133
-        protected $formValidationInstance = null;
134
-
135
-        /* --------------------------------------------------------------
120
+		 */
121
+		protected $dbCacheTime = 0;
122
+
123
+		/**
124
+		 * Instance of the Loader class
125
+		 * @var Loader
126
+		 */
127
+		protected $loaderInstance = null;
128
+
129
+		/**
130
+		 * Instance of the FormValidation library
131
+		 * @var FormValidation
132
+		 */
133
+		protected $formValidationInstance = null;
134
+
135
+		/* --------------------------------------------------------------
136 136
          * GENERIC METHODS
137 137
          * ------------------------------------------------------------ */
138 138
 
139
-        /**
140
-         * Initialise the model, tie into the CodeIgniter superobject and
141
-         * try our best to guess the table name.
142
-         */
143
-        public function __construct(Database $db = null){
144
-            if(is_object($db)){
145
-                $this->setDatabaseInstance($db);
146
-            }
147
-            else{
148
-                $obj = & get_instance();
149
-        		if(isset($obj->database) && is_object($obj->database)){
150
-                    /**
151
-                    * NOTE: Need use "clone" because some Model need have the personal instance of the database library
152
-                    * to prevent duplication
153
-                    */
154
-        			$this->setDatabaseInstance(clone $obj->database);
155
-                }
156
-            }
157
-
158
-            array_unshift($this->before_create, 'protect_attributes');
159
-            array_unshift($this->before_update, 'protect_attributes');
160
-            $this->_temporary_return_type = $this->return_type;
161
-        }
162
-
163
-        /* --------------------------------------------------------------
139
+		/**
140
+		 * Initialise the model, tie into the CodeIgniter superobject and
141
+		 * try our best to guess the table name.
142
+		 */
143
+		public function __construct(Database $db = null){
144
+			if(is_object($db)){
145
+				$this->setDatabaseInstance($db);
146
+			}
147
+			else{
148
+				$obj = & get_instance();
149
+				if(isset($obj->database) && is_object($obj->database)){
150
+					/**
151
+					 * NOTE: Need use "clone" because some Model need have the personal instance of the database library
152
+					 * to prevent duplication
153
+					 */
154
+					$this->setDatabaseInstance(clone $obj->database);
155
+				}
156
+			}
157
+
158
+			array_unshift($this->before_create, 'protect_attributes');
159
+			array_unshift($this->before_update, 'protect_attributes');
160
+			$this->_temporary_return_type = $this->return_type;
161
+		}
162
+
163
+		/* --------------------------------------------------------------
164 164
          * CRUD INTERFACE
165 165
          * ------------------------------------------------------------ */
166 166
 
167
-        /**
168
-         * Fetch a single record based on the primary key. Returns an object.
169
-         */
170
-        public function get($primary_value)
171
-        {
172
-    		return $this->get_by($this->primary_key, $primary_value);
173
-        }
174
-
175
-        /**
176
-         * Fetch a single record based on an arbitrary WHERE call. Can be
177
-         * any valid value to $this->_database->where().
178
-         */
179
-        public function get_by()
180
-        {
181
-            $where = func_get_args();
182
-
183
-            if ($this->soft_delete && $this->_temporary_with_deleted !== TRUE)
184
-            {
185
-                $this->_database->where($this->soft_delete_key, (bool)$this->_temporary_only_deleted);
186
-            }
187
-
188
-    		$this->_set_where($where);
189
-
190
-            $this->trigger('before_get');
167
+		/**
168
+		 * Fetch a single record based on the primary key. Returns an object.
169
+		 */
170
+		public function get($primary_value)
171
+		{
172
+			return $this->get_by($this->primary_key, $primary_value);
173
+		}
174
+
175
+		/**
176
+		 * Fetch a single record based on an arbitrary WHERE call. Can be
177
+		 * any valid value to $this->_database->where().
178
+		 */
179
+		public function get_by()
180
+		{
181
+			$where = func_get_args();
182
+
183
+			if ($this->soft_delete && $this->_temporary_with_deleted !== TRUE)
184
+			{
185
+				$this->_database->where($this->soft_delete_key, (bool)$this->_temporary_only_deleted);
186
+			}
187
+
188
+			$this->_set_where($where);
189
+
190
+			$this->trigger('before_get');
191 191
 			$type = $this->_temporary_return_type == 'array' ? 'array' : false;
192
-            $row = $this->_database->from($this->_table)->get($type);
193
-            $this->_temporary_return_type = $this->return_type;
194
-            $row = $this->trigger('after_get', $row);
195
-            $this->_with = array();
196
-            return $row;
197
-        }
198
-
199
-        /**
200
-         * Fetch an array of records based on an array of primary values.
201
-         */
202
-        public function get_many($values)
203
-        {
204
-            $this->_database->in($this->primary_key, $values);
205
-            return $this->get_all();
206
-        }
207
-
208
-        /**
209
-         * Fetch an array of records based on an arbitrary WHERE call.
210
-         */
211
-        public function get_many_by()
212
-        {
213
-            $where = func_get_args();
214
-            $this->_set_where($where);
215
-            return $this->get_all();
216
-        }
217
-
218
-        /**
219
-         * Fetch all the records in the table. Can be used as a generic call
220
-         * to $this->_database->get() with scoped methods.
221
-         */
222
-        public function get_all()
223
-        {
224
-            $this->trigger('before_get');
225
-            if ($this->soft_delete && $this->_temporary_with_deleted !== TRUE)
226
-            {
227
-                $this->_database->where($this->soft_delete_key, (bool)$this->_temporary_only_deleted);
228
-            }
192
+			$row = $this->_database->from($this->_table)->get($type);
193
+			$this->_temporary_return_type = $this->return_type;
194
+			$row = $this->trigger('after_get', $row);
195
+			$this->_with = array();
196
+			return $row;
197
+		}
198
+
199
+		/**
200
+		 * Fetch an array of records based on an array of primary values.
201
+		 */
202
+		public function get_many($values)
203
+		{
204
+			$this->_database->in($this->primary_key, $values);
205
+			return $this->get_all();
206
+		}
207
+
208
+		/**
209
+		 * Fetch an array of records based on an arbitrary WHERE call.
210
+		 */
211
+		public function get_many_by()
212
+		{
213
+			$where = func_get_args();
214
+			$this->_set_where($where);
215
+			return $this->get_all();
216
+		}
217
+
218
+		/**
219
+		 * Fetch all the records in the table. Can be used as a generic call
220
+		 * to $this->_database->get() with scoped methods.
221
+		 */
222
+		public function get_all()
223
+		{
224
+			$this->trigger('before_get');
225
+			if ($this->soft_delete && $this->_temporary_with_deleted !== TRUE)
226
+			{
227
+				$this->_database->where($this->soft_delete_key, (bool)$this->_temporary_only_deleted);
228
+			}
229 229
 			$type = $this->_temporary_return_type == 'array' ? 'array':false;
230
-            $result = $this->_database->from($this->_table)->getAll($type);
231
-            $this->_temporary_return_type = $this->return_type;
232
-
233
-            foreach ($result as $key => &$row)
234
-            {
235
-                $row = $this->trigger('after_get', $row, ($key == count($result) - 1));
236
-            }
237
-            $this->_with = array();
238
-            return $result;
239
-        }
240
-
241
-        /**
242
-         * Insert a new row into the table. $data should be an associative array
243
-         * of data to be inserted. Returns newly created ID.
244
-         */
245
-        public function insert($data = array(), $skip_validation = FALSE, $escape = true)
246
-        {
247
-            if ($skip_validation === FALSE)
248
-            {
249
-                $data = $this->validate($data);
250
-            }
251
-
252
-            if ($data !== FALSE)
253
-            {
254
-                $data = $this->trigger('before_create', $data);
255
-                $this->_database->from($this->_table)->insert($data, $escape);
256
-                $insert_id = $this->_database->insertId();
257
-                $this->trigger('after_create', $insert_id);
258
-                return $insert_id;
259
-            }
260
-            else
261
-            {
262
-                return FALSE;
263
-            }
264
-        }
265
-
266
-        /**
267
-         * Insert multiple rows into the table. Returns an array of multiple IDs.
268
-         */
269
-        public function insert_many($data = array(), $skip_validation = FALSE, $escape = true)
270
-        {
271
-            $ids = array();
272
-            foreach ($data as $key => $row)
273
-            {
274
-                $ids[] = $this->insert($row, $skip_validation, $escape);
275
-            }
276
-            return $ids;
277
-        }
278
-
279
-        /**
280
-         * Updated a record based on the primary value.
281
-         */
282
-        public function update($primary_value, $data = array(), $skip_validation = FALSE, $escape = true)
283
-        {
284
-            $data = $this->trigger('before_update', $data);
285
-            if ($skip_validation === FALSE)
286
-            {
287
-                $data = $this->validate($data);
288
-            }
289
-
290
-            if ($data !== FALSE)
291
-            {
292
-                $result = $this->_database->where($this->primary_key, $primary_value)
293
-                                   ->from($this->_table)
294
-                                   ->update($data, $escape);
295
-                $this->trigger('after_update', array($data, $result));
296
-                return $result;
297
-            }
298
-            else
299
-            {
300
-                return FALSE;
301
-            }
302
-        }
303
-
304
-        /**
305
-         * Update many records, based on an array of primary values.
306
-         */
307
-        public function update_many($primary_values, $data = array(), $skip_validation = FALSE, $escape = true)
308
-        {
309
-            $data = $this->trigger('before_update', $data);
310
-            if ($skip_validation === FALSE)
311
-            {
312
-                $data = $this->validate($data);
313
-            }
314
-            if ($data !== FALSE)
315
-            {
316
-                $result = $this->_database->in($this->primary_key, $primary_values)
317
-                                   ->from($this->_table)
318
-                                   ->update($data, $escape);
319
-                $this->trigger('after_update', array($data, $result));
320
-                return $result;
321
-            }
322
-            else
323
-            {
324
-                return FALSE;
325
-            }
326
-        }
327
-
328
-        /**
329
-         * Updated a record based on an arbitrary WHERE clause.
330
-         */
331
-        public function update_by()
332
-        {
333
-            $args = func_get_args();
334
-            $data = array();
335
-            if(count($args) == 2){
336
-                if(is_array($args[1])){
337
-                    $data = array_pop($args);
338
-                }
339
-            }
340
-            else if(count($args) == 3){
341
-                if(is_array($args[2])){
342
-                    $data = array_pop($args);
343
-                }
344
-            }
345
-            $data = $this->trigger('before_update', $data);
346
-            if ($this->validate($data) !== FALSE)
347
-            {
348
-                $this->_set_where($args);
349
-                $result = $this->_database->from($this->_table)->update($data);
350
-                $this->trigger('after_update', array($data, $result));
351
-                return $result;
352
-            }
353
-            else
354
-            {
355
-                return FALSE;
356
-            }
357
-        }
358
-
359
-        /**
360
-         * Update all records
361
-         */
362
-        public function update_all($data = array(), $escape = true)
363
-        {
364
-            $data = $this->trigger('before_update', $data);
365
-            $result = $this->_database->from($this->_table)->update($data, $escape);
366
-            $this->trigger('after_update', array($data, $result));
367
-            return $result;
368
-        }
369
-
370
-        /**
371
-         * Delete a row from the table by the primary value
372
-         */
373
-        public function delete($id)
374
-        {
375
-            $this->trigger('before_delete', $id);
376
-            $this->_database->where($this->primary_key, $id);
377
-            if ($this->soft_delete)
378
-            {
379
-                $result = $this->_database->from($this->_table)->update(array( $this->soft_delete_key => TRUE ));
380
-            }
381
-            else
382
-            {
383
-                $result = $this->_database->from($this->_table)->delete();
384
-            }
385
-
386
-            $this->trigger('after_delete', $result);
387
-            return $result;
388
-        }
389
-
390
-        /**
391
-         * Delete a row from the database table by an arbitrary WHERE clause
392
-         */
393
-        public function delete_by()
394
-        {
395
-            $where = func_get_args();
396
-    	    $where = $this->trigger('before_delete', $where);
397
-            $this->_set_where($where);
398
-            if ($this->soft_delete)
399
-            {
400
-                $result = $this->_database->from($this->_table)->update(array( $this->soft_delete_key => TRUE ));
401
-            }
402
-            else
403
-            {
404
-                $result = $this->_database->from($this->_table)->delete();
405
-            }
406
-            $this->trigger('after_delete', $result);
407
-            return $result;
408
-        }
409
-
410
-        /**
411
-         * Delete many rows from the database table by multiple primary values
412
-         */
413
-        public function delete_many($primary_values)
414
-        {
415
-            $primary_values = $this->trigger('before_delete', $primary_values);
416
-            $this->_database->in($this->primary_key, $primary_values);
417
-            if ($this->soft_delete)
418
-            {
419
-                $result = $this->_database->from($this->_table)->update(array( $this->soft_delete_key => TRUE ));
420
-            }
421
-            else
422
-            {
423
-                $result = $this->_database->from($this->_table)->delete();
424
-            }
425
-            $this->trigger('after_delete', $result);
426
-            return $result;
427
-        }
428
-
429
-
430
-        /**
431
-         * Truncates the table
432
-         */
433
-        public function truncate()
434
-        {
435
-            $result = $this->_database->from($this->_table)->delete();
436
-            return $result;
437
-        }
438
-
439
-        /* --------------------------------------------------------------
230
+			$result = $this->_database->from($this->_table)->getAll($type);
231
+			$this->_temporary_return_type = $this->return_type;
232
+
233
+			foreach ($result as $key => &$row)
234
+			{
235
+				$row = $this->trigger('after_get', $row, ($key == count($result) - 1));
236
+			}
237
+			$this->_with = array();
238
+			return $result;
239
+		}
240
+
241
+		/**
242
+		 * Insert a new row into the table. $data should be an associative array
243
+		 * of data to be inserted. Returns newly created ID.
244
+		 */
245
+		public function insert($data = array(), $skip_validation = FALSE, $escape = true)
246
+		{
247
+			if ($skip_validation === FALSE)
248
+			{
249
+				$data = $this->validate($data);
250
+			}
251
+
252
+			if ($data !== FALSE)
253
+			{
254
+				$data = $this->trigger('before_create', $data);
255
+				$this->_database->from($this->_table)->insert($data, $escape);
256
+				$insert_id = $this->_database->insertId();
257
+				$this->trigger('after_create', $insert_id);
258
+				return $insert_id;
259
+			}
260
+			else
261
+			{
262
+				return FALSE;
263
+			}
264
+		}
265
+
266
+		/**
267
+		 * Insert multiple rows into the table. Returns an array of multiple IDs.
268
+		 */
269
+		public function insert_many($data = array(), $skip_validation = FALSE, $escape = true)
270
+		{
271
+			$ids = array();
272
+			foreach ($data as $key => $row)
273
+			{
274
+				$ids[] = $this->insert($row, $skip_validation, $escape);
275
+			}
276
+			return $ids;
277
+		}
278
+
279
+		/**
280
+		 * Updated a record based on the primary value.
281
+		 */
282
+		public function update($primary_value, $data = array(), $skip_validation = FALSE, $escape = true)
283
+		{
284
+			$data = $this->trigger('before_update', $data);
285
+			if ($skip_validation === FALSE)
286
+			{
287
+				$data = $this->validate($data);
288
+			}
289
+
290
+			if ($data !== FALSE)
291
+			{
292
+				$result = $this->_database->where($this->primary_key, $primary_value)
293
+								   ->from($this->_table)
294
+								   ->update($data, $escape);
295
+				$this->trigger('after_update', array($data, $result));
296
+				return $result;
297
+			}
298
+			else
299
+			{
300
+				return FALSE;
301
+			}
302
+		}
303
+
304
+		/**
305
+		 * Update many records, based on an array of primary values.
306
+		 */
307
+		public function update_many($primary_values, $data = array(), $skip_validation = FALSE, $escape = true)
308
+		{
309
+			$data = $this->trigger('before_update', $data);
310
+			if ($skip_validation === FALSE)
311
+			{
312
+				$data = $this->validate($data);
313
+			}
314
+			if ($data !== FALSE)
315
+			{
316
+				$result = $this->_database->in($this->primary_key, $primary_values)
317
+								   ->from($this->_table)
318
+								   ->update($data, $escape);
319
+				$this->trigger('after_update', array($data, $result));
320
+				return $result;
321
+			}
322
+			else
323
+			{
324
+				return FALSE;
325
+			}
326
+		}
327
+
328
+		/**
329
+		 * Updated a record based on an arbitrary WHERE clause.
330
+		 */
331
+		public function update_by()
332
+		{
333
+			$args = func_get_args();
334
+			$data = array();
335
+			if(count($args) == 2){
336
+				if(is_array($args[1])){
337
+					$data = array_pop($args);
338
+				}
339
+			}
340
+			else if(count($args) == 3){
341
+				if(is_array($args[2])){
342
+					$data = array_pop($args);
343
+				}
344
+			}
345
+			$data = $this->trigger('before_update', $data);
346
+			if ($this->validate($data) !== FALSE)
347
+			{
348
+				$this->_set_where($args);
349
+				$result = $this->_database->from($this->_table)->update($data);
350
+				$this->trigger('after_update', array($data, $result));
351
+				return $result;
352
+			}
353
+			else
354
+			{
355
+				return FALSE;
356
+			}
357
+		}
358
+
359
+		/**
360
+		 * Update all records
361
+		 */
362
+		public function update_all($data = array(), $escape = true)
363
+		{
364
+			$data = $this->trigger('before_update', $data);
365
+			$result = $this->_database->from($this->_table)->update($data, $escape);
366
+			$this->trigger('after_update', array($data, $result));
367
+			return $result;
368
+		}
369
+
370
+		/**
371
+		 * Delete a row from the table by the primary value
372
+		 */
373
+		public function delete($id)
374
+		{
375
+			$this->trigger('before_delete', $id);
376
+			$this->_database->where($this->primary_key, $id);
377
+			if ($this->soft_delete)
378
+			{
379
+				$result = $this->_database->from($this->_table)->update(array( $this->soft_delete_key => TRUE ));
380
+			}
381
+			else
382
+			{
383
+				$result = $this->_database->from($this->_table)->delete();
384
+			}
385
+
386
+			$this->trigger('after_delete', $result);
387
+			return $result;
388
+		}
389
+
390
+		/**
391
+		 * Delete a row from the database table by an arbitrary WHERE clause
392
+		 */
393
+		public function delete_by()
394
+		{
395
+			$where = func_get_args();
396
+			$where = $this->trigger('before_delete', $where);
397
+			$this->_set_where($where);
398
+			if ($this->soft_delete)
399
+			{
400
+				$result = $this->_database->from($this->_table)->update(array( $this->soft_delete_key => TRUE ));
401
+			}
402
+			else
403
+			{
404
+				$result = $this->_database->from($this->_table)->delete();
405
+			}
406
+			$this->trigger('after_delete', $result);
407
+			return $result;
408
+		}
409
+
410
+		/**
411
+		 * Delete many rows from the database table by multiple primary values
412
+		 */
413
+		public function delete_many($primary_values)
414
+		{
415
+			$primary_values = $this->trigger('before_delete', $primary_values);
416
+			$this->_database->in($this->primary_key, $primary_values);
417
+			if ($this->soft_delete)
418
+			{
419
+				$result = $this->_database->from($this->_table)->update(array( $this->soft_delete_key => TRUE ));
420
+			}
421
+			else
422
+			{
423
+				$result = $this->_database->from($this->_table)->delete();
424
+			}
425
+			$this->trigger('after_delete', $result);
426
+			return $result;
427
+		}
428
+
429
+
430
+		/**
431
+		 * Truncates the table
432
+		 */
433
+		public function truncate()
434
+		{
435
+			$result = $this->_database->from($this->_table)->delete();
436
+			return $result;
437
+		}
438
+
439
+		/* --------------------------------------------------------------
440 440
          * RELATIONSHIPS
441 441
          * ------------------------------------------------------------ */
442 442
 
443
-        public function with($relationship)
444
-        {
445
-            $this->_with[] = $relationship;
446
-            if (!in_array('relate', $this->after_get))
447
-            {
448
-                $this->after_get[] = 'relate';
449
-            }
450
-            return $this;
451
-        }
452
-
453
-        public function relate($row)
454
-        {
455
-    		if (empty($row))
456
-            {
457
-    		    return $row;
458
-            }
459
-
460
-            foreach ($this->belongs_to as $key => $value)
461
-            {
462
-                if (is_string($value))
463
-                {
464
-                    $relationship = $value;
465
-                    $options = array( 'primary_key' => $value . '_id', 'model' => $value . '_model' );
466
-                }
467
-                else
468
-                {
469
-                    $relationship = $key;
470
-                    $options = $value;
471
-                }
472
-
473
-                if (in_array($relationship, $this->_with))
474
-                {
475
-                    if(is_object($this->loaderInstance)){
476
-                        $this->loaderInstance->model($options['model'], $relationship . '_model');
477
-                    }
478
-                    else{
479
-                        Loader::model($options['model'], $relationship . '_model');    
480
-                    }
481
-                    if (is_object($row))
482
-                    {
483
-                        $row->{$relationship} = $this->{$relationship . '_model'}->get($row->{$options['primary_key']});
484
-                    }
485
-                    else
486
-                    {
487
-                        $row[$relationship] = $this->{$relationship . '_model'}->get($row[$options['primary_key']]);
488
-                    }
489
-                }
490
-            }
491
-
492
-            foreach ($this->has_many as $key => $value)
493
-            {
494
-                if (is_string($value))
495
-                {
496
-                    $relationship = $value;
497
-                    $options = array( 'primary_key' => $this->_table . '_id', 'model' => $value . '_model' );
498
-                }
499
-                else
500
-                {
501
-                    $relationship = $key;
502
-                    $options = $value;
503
-                }
504
-
505
-                if (in_array($relationship, $this->_with))
506
-                {
507
-                    if(is_object($this->loaderInstance)){
508
-                        $this->loaderInstance->model($options['model'], $relationship . '_model');
509
-                    }
510
-                    else{
511
-                        Loader::model($options['model'], $relationship . '_model');    
512
-                    }
513
-                    if (is_object($row))
514
-                    {
515
-                        $row->{$relationship} = $this->{$relationship . '_model'}->get_many_by($options['primary_key'], $row->{$this->primary_key});
516
-                    }
517
-                    else
518
-                    {
519
-                        $row[$relationship] = $this->{$relationship . '_model'}->get_many_by($options['primary_key'], $row[$this->primary_key]);
520
-                    }
521
-                }
522
-            }
523
-            return $row;
524
-        }
525
-
526
-        /* --------------------------------------------------------------
443
+		public function with($relationship)
444
+		{
445
+			$this->_with[] = $relationship;
446
+			if (!in_array('relate', $this->after_get))
447
+			{
448
+				$this->after_get[] = 'relate';
449
+			}
450
+			return $this;
451
+		}
452
+
453
+		public function relate($row)
454
+		{
455
+			if (empty($row))
456
+			{
457
+				return $row;
458
+			}
459
+
460
+			foreach ($this->belongs_to as $key => $value)
461
+			{
462
+				if (is_string($value))
463
+				{
464
+					$relationship = $value;
465
+					$options = array( 'primary_key' => $value . '_id', 'model' => $value . '_model' );
466
+				}
467
+				else
468
+				{
469
+					$relationship = $key;
470
+					$options = $value;
471
+				}
472
+
473
+				if (in_array($relationship, $this->_with))
474
+				{
475
+					if(is_object($this->loaderInstance)){
476
+						$this->loaderInstance->model($options['model'], $relationship . '_model');
477
+					}
478
+					else{
479
+						Loader::model($options['model'], $relationship . '_model');    
480
+					}
481
+					if (is_object($row))
482
+					{
483
+						$row->{$relationship} = $this->{$relationship . '_model'}->get($row->{$options['primary_key']});
484
+					}
485
+					else
486
+					{
487
+						$row[$relationship] = $this->{$relationship . '_model'}->get($row[$options['primary_key']]);
488
+					}
489
+				}
490
+			}
491
+
492
+			foreach ($this->has_many as $key => $value)
493
+			{
494
+				if (is_string($value))
495
+				{
496
+					$relationship = $value;
497
+					$options = array( 'primary_key' => $this->_table . '_id', 'model' => $value . '_model' );
498
+				}
499
+				else
500
+				{
501
+					$relationship = $key;
502
+					$options = $value;
503
+				}
504
+
505
+				if (in_array($relationship, $this->_with))
506
+				{
507
+					if(is_object($this->loaderInstance)){
508
+						$this->loaderInstance->model($options['model'], $relationship . '_model');
509
+					}
510
+					else{
511
+						Loader::model($options['model'], $relationship . '_model');    
512
+					}
513
+					if (is_object($row))
514
+					{
515
+						$row->{$relationship} = $this->{$relationship . '_model'}->get_many_by($options['primary_key'], $row->{$this->primary_key});
516
+					}
517
+					else
518
+					{
519
+						$row[$relationship] = $this->{$relationship . '_model'}->get_many_by($options['primary_key'], $row[$this->primary_key]);
520
+					}
521
+				}
522
+			}
523
+			return $row;
524
+		}
525
+
526
+		/* --------------------------------------------------------------
527 527
          * UTILITY METHODS
528 528
          * ------------------------------------------------------------ */
529 529
 
530
-        /**
531
-         * Retrieve and generate a form_dropdown friendly array
532
-         */
533
-        public function dropdown()
534
-        {
535
-            $args = func_get_args();
536
-            if(count($args) == 2)
537
-            {
538
-                list($key, $value) = $args;
539
-            }
540
-            else
541
-            {
542
-                $key = $this->primary_key;
543
-                $value = $args[0];
544
-            }
545
-            $this->trigger('before_dropdown', array( $key, $value ));
546
-            if ($this->soft_delete && $this->_temporary_with_deleted !== TRUE)
547
-            {
548
-                $this->_database->where($this->soft_delete_key, FALSE);
549
-            }
550
-            $result = $this->_database->select(array($key, $value))
551
-                               ->from($this->_table)
552
-                               ->getAll();
553
-            $options = array();
554
-            foreach ($result as $row)
555
-            {
556
-                $options[$row->{$key}] = $row->{$value};
557
-            }
558
-            $options = $this->trigger('after_dropdown', $options);
559
-            return $options;
560
-        }
561
-
562
-        /**
563
-         * Fetch a count of rows based on an arbitrary WHERE call.
564
-         */
565
-        public function count_by()
566
-        {
567
-            if ($this->soft_delete && $this->_temporary_with_deleted !== TRUE)
568
-            {
569
-                $this->_database->where($this->soft_delete_key, (bool)$this->_temporary_only_deleted);
570
-            }
571
-            $where = func_get_args();
572
-            $this->_set_where($where);
573
-            $this->_database->from($this->_table)->getAll();
574
-            return $this->_database->numRows();
575
-        }
576
-
577
-        /**
578
-         * Fetch a total count of rows, disregarding any previous conditions
579
-         */
580
-        public function count_all()
581
-        {
582
-            if ($this->soft_delete && $this->_temporary_with_deleted !== TRUE)
583
-            {
584
-                $this->_database->where($this->soft_delete_key, (bool)$this->_temporary_only_deleted);
585
-            }
586
-            $this->_database->from($this->_table)->getAll();
587
-            return $this->_database->numRows();
588
-        }
530
+		/**
531
+		 * Retrieve and generate a form_dropdown friendly array
532
+		 */
533
+		public function dropdown()
534
+		{
535
+			$args = func_get_args();
536
+			if(count($args) == 2)
537
+			{
538
+				list($key, $value) = $args;
539
+			}
540
+			else
541
+			{
542
+				$key = $this->primary_key;
543
+				$value = $args[0];
544
+			}
545
+			$this->trigger('before_dropdown', array( $key, $value ));
546
+			if ($this->soft_delete && $this->_temporary_with_deleted !== TRUE)
547
+			{
548
+				$this->_database->where($this->soft_delete_key, FALSE);
549
+			}
550
+			$result = $this->_database->select(array($key, $value))
551
+							   ->from($this->_table)
552
+							   ->getAll();
553
+			$options = array();
554
+			foreach ($result as $row)
555
+			{
556
+				$options[$row->{$key}] = $row->{$value};
557
+			}
558
+			$options = $this->trigger('after_dropdown', $options);
559
+			return $options;
560
+		}
561
+
562
+		/**
563
+		 * Fetch a count of rows based on an arbitrary WHERE call.
564
+		 */
565
+		public function count_by()
566
+		{
567
+			if ($this->soft_delete && $this->_temporary_with_deleted !== TRUE)
568
+			{
569
+				$this->_database->where($this->soft_delete_key, (bool)$this->_temporary_only_deleted);
570
+			}
571
+			$where = func_get_args();
572
+			$this->_set_where($where);
573
+			$this->_database->from($this->_table)->getAll();
574
+			return $this->_database->numRows();
575
+		}
576
+
577
+		/**
578
+		 * Fetch a total count of rows, disregarding any previous conditions
579
+		 */
580
+		public function count_all()
581
+		{
582
+			if ($this->soft_delete && $this->_temporary_with_deleted !== TRUE)
583
+			{
584
+				$this->_database->where($this->soft_delete_key, (bool)$this->_temporary_only_deleted);
585
+			}
586
+			$this->_database->from($this->_table)->getAll();
587
+			return $this->_database->numRows();
588
+		}
589 589
 		
590 590
 		/**
591
-		* Enabled cache temporary
592
-		*/
591
+		 * Enabled cache temporary
592
+		 */
593 593
 		public function cached($ttl = 0){
594 594
 		  if($ttl > 0){
595 595
 			$this->_database = $this->_database->cached($ttl);
@@ -597,385 +597,385 @@  discard block
 block discarded – undo
597 597
 		  return $this;
598 598
 		}
599 599
 
600
-        /**
601
-         * Tell the class to skip the insert validation
602
-         */
603
-        public function skip_validation()
604
-        {
605
-            $this->skip_validation = TRUE;
606
-            return $this;
607
-        }
608
-
609
-        /**
610
-         * Get the skip validation status
611
-         */
612
-        public function get_skip_validation()
613
-        {
614
-            return $this->skip_validation;
615
-        }
616
-
617
-        /**
618
-         * Return the next auto increment of the table. Only tested on MySQL.
619
-         */
620
-        public function get_next_id()
621
-        {
622
-            return (int) $this->_database->select('AUTO_INCREMENT')
623
-                ->from('information_schema.TABLES')
624
-                ->where('TABLE_NAME', $this->_table)
625
-                ->where('TABLE_SCHEMA', $this->_database->getDatabaseName())->get()->AUTO_INCREMENT;
626
-        }
627
-
628
-        /**
629
-         * Getter for the table name
630
-         */
631
-        public function table()
632
-        {
633
-            return $this->_table;
634
-        }
635
-
636
-        /* --------------------------------------------------------------
600
+		/**
601
+		 * Tell the class to skip the insert validation
602
+		 */
603
+		public function skip_validation()
604
+		{
605
+			$this->skip_validation = TRUE;
606
+			return $this;
607
+		}
608
+
609
+		/**
610
+		 * Get the skip validation status
611
+		 */
612
+		public function get_skip_validation()
613
+		{
614
+			return $this->skip_validation;
615
+		}
616
+
617
+		/**
618
+		 * Return the next auto increment of the table. Only tested on MySQL.
619
+		 */
620
+		public function get_next_id()
621
+		{
622
+			return (int) $this->_database->select('AUTO_INCREMENT')
623
+				->from('information_schema.TABLES')
624
+				->where('TABLE_NAME', $this->_table)
625
+				->where('TABLE_SCHEMA', $this->_database->getDatabaseName())->get()->AUTO_INCREMENT;
626
+		}
627
+
628
+		/**
629
+		 * Getter for the table name
630
+		 */
631
+		public function table()
632
+		{
633
+			return $this->_table;
634
+		}
635
+
636
+		/* --------------------------------------------------------------
637 637
          * GLOBAL SCOPES
638 638
          * ------------------------------------------------------------ */
639 639
 
640
-        /**
641
-         * Return the next call as an array rather than an object
642
-         */
643
-        public function as_array()
644
-        {
645
-            $this->_temporary_return_type = 'array';
646
-            return $this;
647
-        }
648
-
649
-        /**
650
-         * Return the next call as an object rather than an array
651
-         */
652
-        public function as_object()
653
-        {
654
-            $this->_temporary_return_type = 'object';
655
-            return $this;
656
-        }
657
-
658
-        /**
659
-         * Don't care about soft deleted rows on the next call
660
-         */
661
-        public function with_deleted()
662
-        {
663
-            $this->_temporary_with_deleted = TRUE;
664
-            return $this;
665
-        }
666
-
667
-        /**
668
-         * Only get deleted rows on the next call
669
-         */
670
-        public function only_deleted()
671
-        {
672
-            $this->_temporary_only_deleted = TRUE;
673
-            return $this;
674
-        }
675
-
676
-        /* --------------------------------------------------------------
640
+		/**
641
+		 * Return the next call as an array rather than an object
642
+		 */
643
+		public function as_array()
644
+		{
645
+			$this->_temporary_return_type = 'array';
646
+			return $this;
647
+		}
648
+
649
+		/**
650
+		 * Return the next call as an object rather than an array
651
+		 */
652
+		public function as_object()
653
+		{
654
+			$this->_temporary_return_type = 'object';
655
+			return $this;
656
+		}
657
+
658
+		/**
659
+		 * Don't care about soft deleted rows on the next call
660
+		 */
661
+		public function with_deleted()
662
+		{
663
+			$this->_temporary_with_deleted = TRUE;
664
+			return $this;
665
+		}
666
+
667
+		/**
668
+		 * Only get deleted rows on the next call
669
+		 */
670
+		public function only_deleted()
671
+		{
672
+			$this->_temporary_only_deleted = TRUE;
673
+			return $this;
674
+		}
675
+
676
+		/* --------------------------------------------------------------
677 677
          * OBSERVERS
678 678
          * ------------------------------------------------------------ */
679 679
 
680
-        /**
681
-         * MySQL DATETIME created_at and updated_at
682
-         */
683
-        public function created_at($row)
684
-        {
685
-            if (is_object($row))
686
-            {
687
-                $row->created_at = date('Y-m-d H:i:s');
688
-            }
689
-            else
690
-            {
691
-                $row['created_at'] = date('Y-m-d H:i:s');
692
-            }
693
-
694
-            return $row;
695
-        }
696
-
697
-        public function updated_at($row)
698
-        {
699
-            if (is_object($row))
700
-            {
701
-                $row->updated_at = date('Y-m-d H:i:s');
702
-            }
703
-            else
704
-            {
705
-                $row['updated_at'] = date('Y-m-d H:i:s');
706
-            }
707
-            return $row;
708
-        }
709
-
710
-        /**
711
-         * Serialises data for you automatically, allowing you to pass
712
-         * through objects and let it handle the serialisation in the background
713
-         */
714
-        public function serialize($row)
715
-        {
716
-            foreach ($this->callback_parameters as $column)
717
-            {
718
-                $row[$column] = serialize($row[$column]);
719
-            }
720
-            return $row;
721
-        }
722
-
723
-        public function unserialize($row)
724
-        {
725
-            foreach ($this->callback_parameters as $column)
726
-            {
727
-                if (is_array($row))
728
-                {
729
-                    $row[$column] = unserialize($row[$column]);
730
-                }
731
-                else
732
-                {
733
-                    $row->$column = unserialize($row->$column);
734
-                }
735
-            }
736
-            return $row;
737
-        }
738
-
739
-        /**
740
-         * Protect attributes by removing them from $row array
741
-         */
742
-        public function protect_attributes($row)
743
-        {
744
-            foreach ($this->protected_attributes as $attr)
745
-            {
746
-                if (is_object($row))
747
-                {
680
+		/**
681
+		 * MySQL DATETIME created_at and updated_at
682
+		 */
683
+		public function created_at($row)
684
+		{
685
+			if (is_object($row))
686
+			{
687
+				$row->created_at = date('Y-m-d H:i:s');
688
+			}
689
+			else
690
+			{
691
+				$row['created_at'] = date('Y-m-d H:i:s');
692
+			}
693
+
694
+			return $row;
695
+		}
696
+
697
+		public function updated_at($row)
698
+		{
699
+			if (is_object($row))
700
+			{
701
+				$row->updated_at = date('Y-m-d H:i:s');
702
+			}
703
+			else
704
+			{
705
+				$row['updated_at'] = date('Y-m-d H:i:s');
706
+			}
707
+			return $row;
708
+		}
709
+
710
+		/**
711
+		 * Serialises data for you automatically, allowing you to pass
712
+		 * through objects and let it handle the serialisation in the background
713
+		 */
714
+		public function serialize($row)
715
+		{
716
+			foreach ($this->callback_parameters as $column)
717
+			{
718
+				$row[$column] = serialize($row[$column]);
719
+			}
720
+			return $row;
721
+		}
722
+
723
+		public function unserialize($row)
724
+		{
725
+			foreach ($this->callback_parameters as $column)
726
+			{
727
+				if (is_array($row))
728
+				{
729
+					$row[$column] = unserialize($row[$column]);
730
+				}
731
+				else
732
+				{
733
+					$row->$column = unserialize($row->$column);
734
+				}
735
+			}
736
+			return $row;
737
+		}
738
+
739
+		/**
740
+		 * Protect attributes by removing them from $row array
741
+		 */
742
+		public function protect_attributes($row)
743
+		{
744
+			foreach ($this->protected_attributes as $attr)
745
+			{
746
+				if (is_object($row))
747
+				{
748 748
 					if(isset($row->$attr)){
749 749
 						unset($row->$attr);
750 750
 					}
751
-                }
752
-                else
753
-                {
751
+				}
752
+				else
753
+				{
754 754
 					if(isset($row[$attr])){
755 755
 						unset($row[$attr]);
756 756
 					}
757
-                }
758
-            }
759
-            return $row;
760
-        }
757
+				}
758
+			}
759
+			return $row;
760
+		}
761 761
 		
762 762
 		 /**
763
-         * Return the database instance
764
-         * @return Database the database instance
765
-         */
766
-        public function getDatabaseInstance(){
767
-            return $this->_database;
768
-        }
769
-
770
-        /**
771
-         * set the Database instance for future use
772
-         * @param Database $db the database object
773
-         */
774
-         public function setDatabaseInstance($db){
775
-            $this->_database = $db;
776
-            if($this->dbCacheTime > 0){
777
-                $this->_database->setCache($this->dbCacheTime);
778
-            }
779
-            return $this;
780
-        }
781
-
782
-        /**
783
-         * Return the loader instance
784
-         * @return Loader the loader instance
785
-         */
786
-        public function getLoader(){
787
-            return $this->loaderInstance;
788
-        }
789
-
790
-        /**
791
-         * set the loader instance for future use
792
-         * @param Loader $loader the loader object
793
-         */
794
-         public function setLoader($loader){
795
-            $this->loaderInstance = $loader;
796
-            return $this;
797
-        }
798
-
799
-        /**
800
-         * Return the FormValidation instance
801
-         * @return FormValidation the form validation instance
802
-         */
803
-        public function getFormValidation(){
804
-            return $this->formValidationInstance;
805
-        }
806
-
807
-        /**
808
-         * set the form validation instance for future use
809
-         * @param FormValidation $fv the form validation object
810
-         */
811
-         public function setFormValidation($fv){
812
-            $this->formValidationInstance = $fv;
813
-            return $this;
814
-        }
815
-
816
-        /* --------------------------------------------------------------
763
+		  * Return the database instance
764
+		  * @return Database the database instance
765
+		  */
766
+		public function getDatabaseInstance(){
767
+			return $this->_database;
768
+		}
769
+
770
+		/**
771
+		 * set the Database instance for future use
772
+		 * @param Database $db the database object
773
+		 */
774
+		 public function setDatabaseInstance($db){
775
+			$this->_database = $db;
776
+			if($this->dbCacheTime > 0){
777
+				$this->_database->setCache($this->dbCacheTime);
778
+			}
779
+			return $this;
780
+		}
781
+
782
+		/**
783
+		 * Return the loader instance
784
+		 * @return Loader the loader instance
785
+		 */
786
+		public function getLoader(){
787
+			return $this->loaderInstance;
788
+		}
789
+
790
+		/**
791
+		 * set the loader instance for future use
792
+		 * @param Loader $loader the loader object
793
+		 */
794
+		 public function setLoader($loader){
795
+			$this->loaderInstance = $loader;
796
+			return $this;
797
+		}
798
+
799
+		/**
800
+		 * Return the FormValidation instance
801
+		 * @return FormValidation the form validation instance
802
+		 */
803
+		public function getFormValidation(){
804
+			return $this->formValidationInstance;
805
+		}
806
+
807
+		/**
808
+		 * set the form validation instance for future use
809
+		 * @param FormValidation $fv the form validation object
810
+		 */
811
+		 public function setFormValidation($fv){
812
+			$this->formValidationInstance = $fv;
813
+			return $this;
814
+		}
815
+
816
+		/* --------------------------------------------------------------
817 817
          * QUERY BUILDER DIRECT ACCESS METHODS
818 818
          * ------------------------------------------------------------ */
819 819
 
820
-        /**
821
-         * A wrapper to $this->_database->orderBy()
822
-         */
823
-        public function order_by($criteria, $order = 'ASC')
824
-        {
825
-            if ( is_array($criteria) )
826
-            {
827
-                foreach ($criteria as $key => $value)
828
-                {
829
-                    $this->_database->orderBy($key, $value);
830
-                }
831
-            }
832
-            else
833
-            {
834
-                $this->_database->orderBy($criteria, $order);
835
-            }
836
-            return $this;
837
-        }
838
-
839
-        /**
840
-         * A wrapper to $this->_database->limit()
841
-         */
842
-        public function limit($offset = 0, $limit = 10)
843
-        {
844
-            $this->_database->limit($offset, $limit);
845
-            return $this;
846
-        }
847
-
848
-        /* --------------------------------------------------------------
820
+		/**
821
+		 * A wrapper to $this->_database->orderBy()
822
+		 */
823
+		public function order_by($criteria, $order = 'ASC')
824
+		{
825
+			if ( is_array($criteria) )
826
+			{
827
+				foreach ($criteria as $key => $value)
828
+				{
829
+					$this->_database->orderBy($key, $value);
830
+				}
831
+			}
832
+			else
833
+			{
834
+				$this->_database->orderBy($criteria, $order);
835
+			}
836
+			return $this;
837
+		}
838
+
839
+		/**
840
+		 * A wrapper to $this->_database->limit()
841
+		 */
842
+		public function limit($offset = 0, $limit = 10)
843
+		{
844
+			$this->_database->limit($offset, $limit);
845
+			return $this;
846
+		}
847
+
848
+		/* --------------------------------------------------------------
849 849
          * INTERNAL METHODS
850 850
          * ------------------------------------------------------------ */
851 851
 
852
-        /**
853
-         * Trigger an event and call its observers. Pass through the event name
854
-         * (which looks for an instance variable $this->event_name), an array of
855
-         * parameters to pass through and an optional 'last in interation' boolean
856
-         */
857
-        protected function trigger($event, $data = FALSE, $last = TRUE)
858
-        {
859
-            if (isset($this->$event) && is_array($this->$event))
860
-            {
861
-                foreach ($this->$event as $method)
862
-                {
863
-                    if (strpos($method, '('))
864
-                    {
865
-                        preg_match('/([a-zA-Z0-9\_\-]+)(\(([a-zA-Z0-9\_\-\., ]+)\))?/', $method, $matches);
866
-
867
-                        $method = $matches[1];
868
-                        $this->callback_parameters = explode(',', $matches[3]);
869
-                    }
870
-                    $data = call_user_func_array(array($this, $method), array($data, $last));
871
-                }
872
-            }
873
-            return $data;
874
-        }
875
-
876
-        /**
877
-         * Run validation on the passed data
878
-         */
879
-        protected function validate(array $data)
880
-        {
881
-            if($this->skip_validation)
882
-            {
883
-                return $data;
884
-            }
885
-            if(!empty($this->validate))
886
-            {
887
-                $fv = null;
888
-                if(is_object($this->formValidationInstance)){
889
-                    $fv = $this->formValidationInstance;
890
-                }
891
-                else{
892
-                    Loader::library('FormValidation');
893
-                    $fv = $this->formvalidation;
894
-                    $this->setFormValidation($fv);
895
-                }
852
+		/**
853
+		 * Trigger an event and call its observers. Pass through the event name
854
+		 * (which looks for an instance variable $this->event_name), an array of
855
+		 * parameters to pass through and an optional 'last in interation' boolean
856
+		 */
857
+		protected function trigger($event, $data = FALSE, $last = TRUE)
858
+		{
859
+			if (isset($this->$event) && is_array($this->$event))
860
+			{
861
+				foreach ($this->$event as $method)
862
+				{
863
+					if (strpos($method, '('))
864
+					{
865
+						preg_match('/([a-zA-Z0-9\_\-]+)(\(([a-zA-Z0-9\_\-\., ]+)\))?/', $method, $matches);
866
+
867
+						$method = $matches[1];
868
+						$this->callback_parameters = explode(',', $matches[3]);
869
+					}
870
+					$data = call_user_func_array(array($this, $method), array($data, $last));
871
+				}
872
+			}
873
+			return $data;
874
+		}
875
+
876
+		/**
877
+		 * Run validation on the passed data
878
+		 */
879
+		protected function validate(array $data)
880
+		{
881
+			if($this->skip_validation)
882
+			{
883
+				return $data;
884
+			}
885
+			if(!empty($this->validate))
886
+			{
887
+				$fv = null;
888
+				if(is_object($this->formValidationInstance)){
889
+					$fv = $this->formValidationInstance;
890
+				}
891
+				else{
892
+					Loader::library('FormValidation');
893
+					$fv = $this->formvalidation;
894
+					$this->setFormValidation($fv);
895
+				}
896 896
                
897
-                $fv->setData($data);
898
-                $fv->setRules($this->validate);
899
-
900
-                if ($fv->run())
901
-                {
902
-                    return $data;
903
-                }
904
-                else
905
-                {
906
-                    return FALSE;
907
-                }
908
-            }
909
-            else
910
-            {
911
-                return $data;
912
-            }
913
-        }
914
-
915
-
916
-        /**
917
-         * Set WHERE parameters, cleverly
918
-         */
919
-        protected function _set_where($params)
920
-        {
921
-            if (count($params) == 1 && is_array($params[0]))
922
-            {
923
-                foreach ($params[0] as $field => $filter)
924
-                {
925
-                    if (is_array($filter))
926
-                    {
927
-                        $this->_database->in($field, $filter);
928
-                    }
929
-                    else
930
-                    {
931
-                        if (is_int($field))
932
-                        {
933
-                            $this->_database->where($filter);
934
-                        }
935
-                        else
936
-                        {
937
-                            $this->_database->where($field, $filter);
938
-                        }
939
-                    }
940
-                }
941
-            }
942
-            else if (count($params) == 1)
943
-            {
944
-                $this->_database->where($params[0]);
945
-            }
946
-        	else if(count($params) == 2)
947
-    		{
948
-                if (is_array($params[1]))
949
-                {
950
-                    $this->_database->in($params[0], $params[1]);
951
-                }
952
-                else
953
-                {
954
-                    $this->_database->where($params[0], $params[1]);
955
-                }
956
-    		}
957
-    		else if(count($params) == 3)
958
-    		{
959
-    			$this->_database->where($params[0], $params[1], $params[2]);
960
-    		}
961
-            else
962
-            {
963
-                if (is_array($params[1]))
964
-                {
965
-                    $this->_database->in($params[0], $params[1]);
966
-                }
967
-                else
968
-                {
969
-                    $this->_database->where($params[0], $params[1]);
970
-                }
971
-            }
972
-        }
973
-
974
-        /**
897
+				$fv->setData($data);
898
+				$fv->setRules($this->validate);
899
+
900
+				if ($fv->run())
901
+				{
902
+					return $data;
903
+				}
904
+				else
905
+				{
906
+					return FALSE;
907
+				}
908
+			}
909
+			else
910
+			{
911
+				return $data;
912
+			}
913
+		}
914
+
915
+
916
+		/**
917
+		 * Set WHERE parameters, cleverly
918
+		 */
919
+		protected function _set_where($params)
920
+		{
921
+			if (count($params) == 1 && is_array($params[0]))
922
+			{
923
+				foreach ($params[0] as $field => $filter)
924
+				{
925
+					if (is_array($filter))
926
+					{
927
+						$this->_database->in($field, $filter);
928
+					}
929
+					else
930
+					{
931
+						if (is_int($field))
932
+						{
933
+							$this->_database->where($filter);
934
+						}
935
+						else
936
+						{
937
+							$this->_database->where($field, $filter);
938
+						}
939
+					}
940
+				}
941
+			}
942
+			else if (count($params) == 1)
943
+			{
944
+				$this->_database->where($params[0]);
945
+			}
946
+			else if(count($params) == 2)
947
+			{
948
+				if (is_array($params[1]))
949
+				{
950
+					$this->_database->in($params[0], $params[1]);
951
+				}
952
+				else
953
+				{
954
+					$this->_database->where($params[0], $params[1]);
955
+				}
956
+			}
957
+			else if(count($params) == 3)
958
+			{
959
+				$this->_database->where($params[0], $params[1], $params[2]);
960
+			}
961
+			else
962
+			{
963
+				if (is_array($params[1]))
964
+				{
965
+					$this->_database->in($params[0], $params[1]);
966
+				}
967
+				else
968
+				{
969
+					$this->_database->where($params[0], $params[1]);
970
+				}
971
+			}
972
+		}
973
+
974
+		/**
975 975
             Shortcut to controller
976
-        */
977
-        public function __get($key){
978
-            return get_instance()->{$key};
979
-        }
976
+		 */
977
+		public function __get($key){
978
+			return get_instance()->{$key};
979
+		}
980 980
 
981
-    }
981
+	}
Please login to merge, or discard this patch.
Spacing   +44 added lines, -44 removed lines patch added patch discarded remove patch
@@ -33,7 +33,7 @@  discard block
 block discarded – undo
33 33
      * @copyright Copyright (c) 2012, Jamie Rumbelow <http://jamierumbelow.net>
34 34
      */
35 35
 
36
-    class Model{
36
+    class Model {
37 37
 
38 38
         /* --------------------------------------------------------------
39 39
          * VARIABLES
@@ -140,13 +140,13 @@  discard block
 block discarded – undo
140 140
          * Initialise the model, tie into the CodeIgniter superobject and
141 141
          * try our best to guess the table name.
142 142
          */
143
-        public function __construct(Database $db = null){
144
-            if(is_object($db)){
143
+        public function __construct(Database $db = null) {
144
+            if (is_object($db)) {
145 145
                 $this->setDatabaseInstance($db);
146 146
             }
147
-            else{
147
+            else {
148 148
                 $obj = & get_instance();
149
-        		if(isset($obj->database) && is_object($obj->database)){
149
+        		if (isset($obj->database) && is_object($obj->database)) {
150 150
                     /**
151 151
                     * NOTE: Need use "clone" because some Model need have the personal instance of the database library
152 152
                     * to prevent duplication
@@ -182,7 +182,7 @@  discard block
 block discarded – undo
182 182
 
183 183
             if ($this->soft_delete && $this->_temporary_with_deleted !== TRUE)
184 184
             {
185
-                $this->_database->where($this->soft_delete_key, (bool)$this->_temporary_only_deleted);
185
+                $this->_database->where($this->soft_delete_key, (bool) $this->_temporary_only_deleted);
186 186
             }
187 187
 
188 188
     		$this->_set_where($where);
@@ -224,9 +224,9 @@  discard block
 block discarded – undo
224 224
             $this->trigger('before_get');
225 225
             if ($this->soft_delete && $this->_temporary_with_deleted !== TRUE)
226 226
             {
227
-                $this->_database->where($this->soft_delete_key, (bool)$this->_temporary_only_deleted);
227
+                $this->_database->where($this->soft_delete_key, (bool) $this->_temporary_only_deleted);
228 228
             }
229
-			$type = $this->_temporary_return_type == 'array' ? 'array':false;
229
+			$type = $this->_temporary_return_type == 'array' ? 'array' : false;
230 230
             $result = $this->_database->from($this->_table)->getAll($type);
231 231
             $this->_temporary_return_type = $this->return_type;
232 232
 
@@ -332,13 +332,13 @@  discard block
 block discarded – undo
332 332
         {
333 333
             $args = func_get_args();
334 334
             $data = array();
335
-            if(count($args) == 2){
336
-                if(is_array($args[1])){
335
+            if (count($args) == 2) {
336
+                if (is_array($args[1])) {
337 337
                     $data = array_pop($args);
338 338
                 }
339 339
             }
340
-            else if(count($args) == 3){
341
-                if(is_array($args[2])){
340
+            else if (count($args) == 3) {
341
+                if (is_array($args[2])) {
342 342
                     $data = array_pop($args);
343 343
                 }
344 344
             }
@@ -376,7 +376,7 @@  discard block
 block discarded – undo
376 376
             $this->_database->where($this->primary_key, $id);
377 377
             if ($this->soft_delete)
378 378
             {
379
-                $result = $this->_database->from($this->_table)->update(array( $this->soft_delete_key => TRUE ));
379
+                $result = $this->_database->from($this->_table)->update(array($this->soft_delete_key => TRUE));
380 380
             }
381 381
             else
382 382
             {
@@ -397,7 +397,7 @@  discard block
 block discarded – undo
397 397
             $this->_set_where($where);
398 398
             if ($this->soft_delete)
399 399
             {
400
-                $result = $this->_database->from($this->_table)->update(array( $this->soft_delete_key => TRUE ));
400
+                $result = $this->_database->from($this->_table)->update(array($this->soft_delete_key => TRUE));
401 401
             }
402 402
             else
403 403
             {
@@ -416,7 +416,7 @@  discard block
 block discarded – undo
416 416
             $this->_database->in($this->primary_key, $primary_values);
417 417
             if ($this->soft_delete)
418 418
             {
419
-                $result = $this->_database->from($this->_table)->update(array( $this->soft_delete_key => TRUE ));
419
+                $result = $this->_database->from($this->_table)->update(array($this->soft_delete_key => TRUE));
420 420
             }
421 421
             else
422 422
             {
@@ -462,7 +462,7 @@  discard block
 block discarded – undo
462 462
                 if (is_string($value))
463 463
                 {
464 464
                     $relationship = $value;
465
-                    $options = array( 'primary_key' => $value . '_id', 'model' => $value . '_model' );
465
+                    $options = array('primary_key' => $value . '_id', 'model' => $value . '_model');
466 466
                 }
467 467
                 else
468 468
                 {
@@ -472,10 +472,10 @@  discard block
 block discarded – undo
472 472
 
473 473
                 if (in_array($relationship, $this->_with))
474 474
                 {
475
-                    if(is_object($this->loaderInstance)){
475
+                    if (is_object($this->loaderInstance)) {
476 476
                         $this->loaderInstance->model($options['model'], $relationship . '_model');
477 477
                     }
478
-                    else{
478
+                    else {
479 479
                         Loader::model($options['model'], $relationship . '_model');    
480 480
                     }
481 481
                     if (is_object($row))
@@ -494,7 +494,7 @@  discard block
 block discarded – undo
494 494
                 if (is_string($value))
495 495
                 {
496 496
                     $relationship = $value;
497
-                    $options = array( 'primary_key' => $this->_table . '_id', 'model' => $value . '_model' );
497
+                    $options = array('primary_key' => $this->_table . '_id', 'model' => $value . '_model');
498 498
                 }
499 499
                 else
500 500
                 {
@@ -504,10 +504,10 @@  discard block
 block discarded – undo
504 504
 
505 505
                 if (in_array($relationship, $this->_with))
506 506
                 {
507
-                    if(is_object($this->loaderInstance)){
507
+                    if (is_object($this->loaderInstance)) {
508 508
                         $this->loaderInstance->model($options['model'], $relationship . '_model');
509 509
                     }
510
-                    else{
510
+                    else {
511 511
                         Loader::model($options['model'], $relationship . '_model');    
512 512
                     }
513 513
                     if (is_object($row))
@@ -533,7 +533,7 @@  discard block
 block discarded – undo
533 533
         public function dropdown()
534 534
         {
535 535
             $args = func_get_args();
536
-            if(count($args) == 2)
536
+            if (count($args) == 2)
537 537
             {
538 538
                 list($key, $value) = $args;
539 539
             }
@@ -542,7 +542,7 @@  discard block
 block discarded – undo
542 542
                 $key = $this->primary_key;
543 543
                 $value = $args[0];
544 544
             }
545
-            $this->trigger('before_dropdown', array( $key, $value ));
545
+            $this->trigger('before_dropdown', array($key, $value));
546 546
             if ($this->soft_delete && $this->_temporary_with_deleted !== TRUE)
547 547
             {
548 548
                 $this->_database->where($this->soft_delete_key, FALSE);
@@ -566,7 +566,7 @@  discard block
 block discarded – undo
566 566
         {
567 567
             if ($this->soft_delete && $this->_temporary_with_deleted !== TRUE)
568 568
             {
569
-                $this->_database->where($this->soft_delete_key, (bool)$this->_temporary_only_deleted);
569
+                $this->_database->where($this->soft_delete_key, (bool) $this->_temporary_only_deleted);
570 570
             }
571 571
             $where = func_get_args();
572 572
             $this->_set_where($where);
@@ -581,7 +581,7 @@  discard block
 block discarded – undo
581 581
         {
582 582
             if ($this->soft_delete && $this->_temporary_with_deleted !== TRUE)
583 583
             {
584
-                $this->_database->where($this->soft_delete_key, (bool)$this->_temporary_only_deleted);
584
+                $this->_database->where($this->soft_delete_key, (bool) $this->_temporary_only_deleted);
585 585
             }
586 586
             $this->_database->from($this->_table)->getAll();
587 587
             return $this->_database->numRows();
@@ -590,8 +590,8 @@  discard block
 block discarded – undo
590 590
 		/**
591 591
 		* Enabled cache temporary
592 592
 		*/
593
-		public function cached($ttl = 0){
594
-		  if($ttl > 0){
593
+		public function cached($ttl = 0) {
594
+		  if ($ttl > 0) {
595 595
 			$this->_database = $this->_database->cached($ttl);
596 596
 		  }
597 597
 		  return $this;
@@ -745,13 +745,13 @@  discard block
 block discarded – undo
745 745
             {
746 746
                 if (is_object($row))
747 747
                 {
748
-					if(isset($row->$attr)){
748
+					if (isset($row->$attr)) {
749 749
 						unset($row->$attr);
750 750
 					}
751 751
                 }
752 752
                 else
753 753
                 {
754
-					if(isset($row[$attr])){
754
+					if (isset($row[$attr])) {
755 755
 						unset($row[$attr]);
756 756
 					}
757 757
                 }
@@ -763,7 +763,7 @@  discard block
 block discarded – undo
763 763
          * Return the database instance
764 764
          * @return Database the database instance
765 765
          */
766
-        public function getDatabaseInstance(){
766
+        public function getDatabaseInstance() {
767 767
             return $this->_database;
768 768
         }
769 769
 
@@ -771,9 +771,9 @@  discard block
 block discarded – undo
771 771
          * set the Database instance for future use
772 772
          * @param Database $db the database object
773 773
          */
774
-         public function setDatabaseInstance($db){
774
+         public function setDatabaseInstance($db) {
775 775
             $this->_database = $db;
776
-            if($this->dbCacheTime > 0){
776
+            if ($this->dbCacheTime > 0) {
777 777
                 $this->_database->setCache($this->dbCacheTime);
778 778
             }
779 779
             return $this;
@@ -783,7 +783,7 @@  discard block
 block discarded – undo
783 783
          * Return the loader instance
784 784
          * @return Loader the loader instance
785 785
          */
786
-        public function getLoader(){
786
+        public function getLoader() {
787 787
             return $this->loaderInstance;
788 788
         }
789 789
 
@@ -791,7 +791,7 @@  discard block
 block discarded – undo
791 791
          * set the loader instance for future use
792 792
          * @param Loader $loader the loader object
793 793
          */
794
-         public function setLoader($loader){
794
+         public function setLoader($loader) {
795 795
             $this->loaderInstance = $loader;
796 796
             return $this;
797 797
         }
@@ -800,7 +800,7 @@  discard block
 block discarded – undo
800 800
          * Return the FormValidation instance
801 801
          * @return FormValidation the form validation instance
802 802
          */
803
-        public function getFormValidation(){
803
+        public function getFormValidation() {
804 804
             return $this->formValidationInstance;
805 805
         }
806 806
 
@@ -808,7 +808,7 @@  discard block
 block discarded – undo
808 808
          * set the form validation instance for future use
809 809
          * @param FormValidation $fv the form validation object
810 810
          */
811
-         public function setFormValidation($fv){
811
+         public function setFormValidation($fv) {
812 812
             $this->formValidationInstance = $fv;
813 813
             return $this;
814 814
         }
@@ -822,7 +822,7 @@  discard block
 block discarded – undo
822 822
          */
823 823
         public function order_by($criteria, $order = 'ASC')
824 824
         {
825
-            if ( is_array($criteria) )
825
+            if (is_array($criteria))
826 826
             {
827 827
                 foreach ($criteria as $key => $value)
828 828
                 {
@@ -878,17 +878,17 @@  discard block
 block discarded – undo
878 878
          */
879 879
         protected function validate(array $data)
880 880
         {
881
-            if($this->skip_validation)
881
+            if ($this->skip_validation)
882 882
             {
883 883
                 return $data;
884 884
             }
885
-            if(!empty($this->validate))
885
+            if (!empty($this->validate))
886 886
             {
887 887
                 $fv = null;
888
-                if(is_object($this->formValidationInstance)){
888
+                if (is_object($this->formValidationInstance)) {
889 889
                     $fv = $this->formValidationInstance;
890 890
                 }
891
-                else{
891
+                else {
892 892
                     Loader::library('FormValidation');
893 893
                     $fv = $this->formvalidation;
894 894
                     $this->setFormValidation($fv);
@@ -943,7 +943,7 @@  discard block
 block discarded – undo
943 943
             {
944 944
                 $this->_database->where($params[0]);
945 945
             }
946
-        	else if(count($params) == 2)
946
+        	else if (count($params) == 2)
947 947
     		{
948 948
                 if (is_array($params[1]))
949 949
                 {
@@ -954,7 +954,7 @@  discard block
 block discarded – undo
954 954
                     $this->_database->where($params[0], $params[1]);
955 955
                 }
956 956
     		}
957
-    		else if(count($params) == 3)
957
+    		else if (count($params) == 3)
958 958
     		{
959 959
     			$this->_database->where($params[0], $params[1], $params[2]);
960 960
     		}
@@ -974,7 +974,7 @@  discard block
 block discarded – undo
974 974
         /**
975 975
             Shortcut to controller
976 976
         */
977
-        public function __get($key){
977
+        public function __get($key) {
978 978
             return get_instance()->{$key};
979 979
         }
980 980
 
Please login to merge, or discard this patch.
Braces   +32 added lines, -64 removed lines patch added patch discarded remove patch
@@ -143,8 +143,7 @@  discard block
 block discarded – undo
143 143
         public function __construct(Database $db = null){
144 144
             if(is_object($db)){
145 145
                 $this->setDatabaseInstance($db);
146
-            }
147
-            else{
146
+            } else{
148 147
                 $obj = & get_instance();
149 148
         		if(isset($obj->database) && is_object($obj->database)){
150 149
                     /**
@@ -256,8 +255,7 @@  discard block
 block discarded – undo
256 255
                 $insert_id = $this->_database->insertId();
257 256
                 $this->trigger('after_create', $insert_id);
258 257
                 return $insert_id;
259
-            }
260
-            else
258
+            } else
261 259
             {
262 260
                 return FALSE;
263 261
             }
@@ -294,8 +292,7 @@  discard block
 block discarded – undo
294 292
                                    ->update($data, $escape);
295 293
                 $this->trigger('after_update', array($data, $result));
296 294
                 return $result;
297
-            }
298
-            else
295
+            } else
299 296
             {
300 297
                 return FALSE;
301 298
             }
@@ -318,8 +315,7 @@  discard block
 block discarded – undo
318 315
                                    ->update($data, $escape);
319 316
                 $this->trigger('after_update', array($data, $result));
320 317
                 return $result;
321
-            }
322
-            else
318
+            } else
323 319
             {
324 320
                 return FALSE;
325 321
             }
@@ -336,8 +332,7 @@  discard block
 block discarded – undo
336 332
                 if(is_array($args[1])){
337 333
                     $data = array_pop($args);
338 334
                 }
339
-            }
340
-            else if(count($args) == 3){
335
+            } else if(count($args) == 3){
341 336
                 if(is_array($args[2])){
342 337
                     $data = array_pop($args);
343 338
                 }
@@ -349,8 +344,7 @@  discard block
 block discarded – undo
349 344
                 $result = $this->_database->from($this->_table)->update($data);
350 345
                 $this->trigger('after_update', array($data, $result));
351 346
                 return $result;
352
-            }
353
-            else
347
+            } else
354 348
             {
355 349
                 return FALSE;
356 350
             }
@@ -377,8 +371,7 @@  discard block
 block discarded – undo
377 371
             if ($this->soft_delete)
378 372
             {
379 373
                 $result = $this->_database->from($this->_table)->update(array( $this->soft_delete_key => TRUE ));
380
-            }
381
-            else
374
+            } else
382 375
             {
383 376
                 $result = $this->_database->from($this->_table)->delete();
384 377
             }
@@ -398,8 +391,7 @@  discard block
 block discarded – undo
398 391
             if ($this->soft_delete)
399 392
             {
400 393
                 $result = $this->_database->from($this->_table)->update(array( $this->soft_delete_key => TRUE ));
401
-            }
402
-            else
394
+            } else
403 395
             {
404 396
                 $result = $this->_database->from($this->_table)->delete();
405 397
             }
@@ -417,8 +409,7 @@  discard block
 block discarded – undo
417 409
             if ($this->soft_delete)
418 410
             {
419 411
                 $result = $this->_database->from($this->_table)->update(array( $this->soft_delete_key => TRUE ));
420
-            }
421
-            else
412
+            } else
422 413
             {
423 414
                 $result = $this->_database->from($this->_table)->delete();
424 415
             }
@@ -463,8 +454,7 @@  discard block
 block discarded – undo
463 454
                 {
464 455
                     $relationship = $value;
465 456
                     $options = array( 'primary_key' => $value . '_id', 'model' => $value . '_model' );
466
-                }
467
-                else
457
+                } else
468 458
                 {
469 459
                     $relationship = $key;
470 460
                     $options = $value;
@@ -474,15 +464,13 @@  discard block
 block discarded – undo
474 464
                 {
475 465
                     if(is_object($this->loaderInstance)){
476 466
                         $this->loaderInstance->model($options['model'], $relationship . '_model');
477
-                    }
478
-                    else{
467
+                    } else{
479 468
                         Loader::model($options['model'], $relationship . '_model');    
480 469
                     }
481 470
                     if (is_object($row))
482 471
                     {
483 472
                         $row->{$relationship} = $this->{$relationship . '_model'}->get($row->{$options['primary_key']});
484
-                    }
485
-                    else
473
+                    } else
486 474
                     {
487 475
                         $row[$relationship] = $this->{$relationship . '_model'}->get($row[$options['primary_key']]);
488 476
                     }
@@ -495,8 +483,7 @@  discard block
 block discarded – undo
495 483
                 {
496 484
                     $relationship = $value;
497 485
                     $options = array( 'primary_key' => $this->_table . '_id', 'model' => $value . '_model' );
498
-                }
499
-                else
486
+                } else
500 487
                 {
501 488
                     $relationship = $key;
502 489
                     $options = $value;
@@ -506,15 +493,13 @@  discard block
 block discarded – undo
506 493
                 {
507 494
                     if(is_object($this->loaderInstance)){
508 495
                         $this->loaderInstance->model($options['model'], $relationship . '_model');
509
-                    }
510
-                    else{
496
+                    } else{
511 497
                         Loader::model($options['model'], $relationship . '_model');    
512 498
                     }
513 499
                     if (is_object($row))
514 500
                     {
515 501
                         $row->{$relationship} = $this->{$relationship . '_model'}->get_many_by($options['primary_key'], $row->{$this->primary_key});
516
-                    }
517
-                    else
502
+                    } else
518 503
                     {
519 504
                         $row[$relationship] = $this->{$relationship . '_model'}->get_many_by($options['primary_key'], $row[$this->primary_key]);
520 505
                     }
@@ -536,8 +521,7 @@  discard block
 block discarded – undo
536 521
             if(count($args) == 2)
537 522
             {
538 523
                 list($key, $value) = $args;
539
-            }
540
-            else
524
+            } else
541 525
             {
542 526
                 $key = $this->primary_key;
543 527
                 $value = $args[0];
@@ -685,8 +669,7 @@  discard block
 block discarded – undo
685 669
             if (is_object($row))
686 670
             {
687 671
                 $row->created_at = date('Y-m-d H:i:s');
688
-            }
689
-            else
672
+            } else
690 673
             {
691 674
                 $row['created_at'] = date('Y-m-d H:i:s');
692 675
             }
@@ -699,8 +682,7 @@  discard block
 block discarded – undo
699 682
             if (is_object($row))
700 683
             {
701 684
                 $row->updated_at = date('Y-m-d H:i:s');
702
-            }
703
-            else
685
+            } else
704 686
             {
705 687
                 $row['updated_at'] = date('Y-m-d H:i:s');
706 688
             }
@@ -727,8 +709,7 @@  discard block
 block discarded – undo
727 709
                 if (is_array($row))
728 710
                 {
729 711
                     $row[$column] = unserialize($row[$column]);
730
-                }
731
-                else
712
+                } else
732 713
                 {
733 714
                     $row->$column = unserialize($row->$column);
734 715
                 }
@@ -748,8 +729,7 @@  discard block
 block discarded – undo
748 729
 					if(isset($row->$attr)){
749 730
 						unset($row->$attr);
750 731
 					}
751
-                }
752
-                else
732
+                } else
753 733
                 {
754 734
 					if(isset($row[$attr])){
755 735
 						unset($row[$attr]);
@@ -828,8 +808,7 @@  discard block
 block discarded – undo
828 808
                 {
829 809
                     $this->_database->orderBy($key, $value);
830 810
                 }
831
-            }
832
-            else
811
+            } else
833 812
             {
834 813
                 $this->_database->orderBy($criteria, $order);
835 814
             }
@@ -887,8 +866,7 @@  discard block
 block discarded – undo
887 866
                 $fv = null;
888 867
                 if(is_object($this->formValidationInstance)){
889 868
                     $fv = $this->formValidationInstance;
890
-                }
891
-                else{
869
+                } else{
892 870
                     Loader::library('FormValidation');
893 871
                     $fv = $this->formvalidation;
894 872
                     $this->setFormValidation($fv);
@@ -900,13 +878,11 @@  discard block
 block discarded – undo
900 878
                 if ($fv->run())
901 879
                 {
902 880
                     return $data;
903
-                }
904
-                else
881
+                } else
905 882
                 {
906 883
                     return FALSE;
907 884
                 }
908
-            }
909
-            else
885
+            } else
910 886
             {
911 887
                 return $data;
912 888
             }
@@ -925,46 +901,38 @@  discard block
 block discarded – undo
925 901
                     if (is_array($filter))
926 902
                     {
927 903
                         $this->_database->in($field, $filter);
928
-                    }
929
-                    else
904
+                    } else
930 905
                     {
931 906
                         if (is_int($field))
932 907
                         {
933 908
                             $this->_database->where($filter);
934
-                        }
935
-                        else
909
+                        } else
936 910
                         {
937 911
                             $this->_database->where($field, $filter);
938 912
                         }
939 913
                     }
940 914
                 }
941
-            }
942
-            else if (count($params) == 1)
915
+            } else if (count($params) == 1)
943 916
             {
944 917
                 $this->_database->where($params[0]);
945
-            }
946
-        	else if(count($params) == 2)
918
+            } else if(count($params) == 2)
947 919
     		{
948 920
                 if (is_array($params[1]))
949 921
                 {
950 922
                     $this->_database->in($params[0], $params[1]);
951
-                }
952
-                else
923
+                } else
953 924
                 {
954 925
                     $this->_database->where($params[0], $params[1]);
955 926
                 }
956
-    		}
957
-    		else if(count($params) == 3)
927
+    		} else if(count($params) == 3)
958 928
     		{
959 929
     			$this->_database->where($params[0], $params[1], $params[2]);
960
-    		}
961
-            else
930
+    		} else
962 931
             {
963 932
                 if (is_array($params[1]))
964 933
                 {
965 934
                     $this->_database->in($params[0], $params[1]);
966
-                }
967
-                else
935
+                } else
968 936
                 {
969 937
                     $this->_database->where($params[0], $params[1]);
970 938
                 }
Please login to merge, or discard this patch.
core/classes/Response.php 3 patches
Indentation   +11 added lines, -11 removed lines patch added patch discarded remove patch
@@ -22,7 +22,7 @@  discard block
 block discarded – undo
22 22
 	 * You should have received a copy of the GNU General Public License
23 23
 	 * along with this program; if not, write to the Free Software
24 24
 	 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
25
-	*/
25
+	 */
26 26
 
27 27
 	class Response{
28 28
 
@@ -57,9 +57,9 @@  discard block
 block discarded – undo
57 57
 		private $_currentUrlCacheKey = null;
58 58
 		
59 59
 		/**
60
-		* Whether we can compress the output using Gzip
61
-		* @var boolean
62
-		*/
60
+		 * Whether we can compress the output using Gzip
61
+		 * @var boolean
62
+		 */
63 63
 		private static $_canCompressOutput = false;
64 64
 		
65 65
 		/**
@@ -236,8 +236,8 @@  discard block
 block discarded – undo
236 236
 		}
237 237
 		
238 238
 		/**
239
-		* Send the final page output to user
240
-		*/
239
+		 * Send the final page output to user
240
+		 */
241 241
 		public function renderFinalPage(){
242 242
 			$logger = self::getLogger();
243 243
 			$obj = & get_instance();
@@ -301,8 +301,8 @@  discard block
 block discarded – undo
301 301
 		}
302 302
 		
303 303
 		/**
304
-		* Send the final page output to user if is cached
305
-		*/
304
+		 * Send the final page output to user if is cached
305
+		 */
306 306
 		public function renderFinalPageFromCache(&$cache){
307 307
 			$logger = self::getLogger();
308 308
 			$url = $this->_currentUrl;					
@@ -362,9 +362,9 @@  discard block
 block discarded – undo
362 362
 		}
363 363
 		
364 364
 		/**
365
-		* Get the final page to be rendered
366
-		* @return string
367
-		*/
365
+		 * Get the final page to be rendered
366
+		 * @return string
367
+		 */
368 368
 		public function getFinalPageRendered(){
369 369
 			return $this->_pageRender;
370 370
 		}
Please login to merge, or discard this patch.
Braces   +11 added lines, -22 removed lines patch added patch discarded remove patch
@@ -152,8 +152,7 @@  discard block
 block discarded – undo
152 152
 			if(! headers_sent()){
153 153
 				header('Location: '.$url);
154 154
 				exit;
155
-			}
156
-			else{
155
+			} else{
157 156
 				echo '<script>
158 157
 						location.href = "'.$url.'";
159 158
 					</script>';
@@ -202,12 +201,10 @@  discard block
 block discarded – undo
202 201
 					if($moduleViewPath){
203 202
 						$path = $moduleViewPath;
204 203
 						$logger->info('Found view [' . $view . '] in module [' .$mod. '], the file path is [' .$moduleViewPath. '] we will used it');
205
-					}
206
-					else{
204
+					} else{
207 205
 						$logger->info('Cannot find view [' . $view . '] in module [' .$mod. '] using the default location');
208 206
 					}
209
-				}
210
-				else{
207
+				} else{
211 208
 					$logger->info('The current request does not use module using the default location.');
212 209
 				}
213 210
 			}
@@ -291,8 +288,7 @@  discard block
 block discarded – undo
291 288
 			//compress the output if is available
292 289
 			if (self::$_canCompressOutput){
293 290
 				ob_start('ob_gzhandler');
294
-			}
295
-			else{
291
+			} else{
296 292
 				ob_start();
297 293
 			}
298 294
 			self::sendHeaders(200);
@@ -324,8 +320,7 @@  discard block
 block discarded – undo
324 320
 					$logger->info('The cache page content is not yet expire for the URL [' . $url . '] send 304 header to browser');
325 321
 					self::sendHeaders(304);
326 322
 					return;
327
-				}
328
-				else{
323
+				} else{
329 324
 					$logger->info('The cache page content is expired or the browser don\'t send the HTTP_IF_MODIFIED_SINCE header for the URL [' . $url . '] send cache headers to tell the browser');
330 325
 					self::sendHeaders(200);
331 326
 					//get the cache content
@@ -345,15 +340,13 @@  discard block
 block discarded – undo
345 340
 						//compress the output if is available
346 341
 						if (self::$_canCompressOutput){
347 342
 							ob_start('ob_gzhandler');
348
-						}
349
-						else{
343
+						} else{
350 344
 							ob_start();
351 345
 						}
352 346
 						echo $content;
353 347
 						ob_end_flush();
354 348
 						return;
355
-					}
356
-					else{
349
+					} else{
357 350
 						$logger->info('The page cache content for the URL [' . $url . '] is not valid may be already expired');
358 351
 						$cache->delete($pageCacheKey);
359 352
 					}
@@ -394,16 +387,14 @@  discard block
 block discarded – undo
394 387
 				//compress the output if is available
395 388
 				if (self::$_canCompressOutput){
396 389
 					ob_start('ob_gzhandler');
397
-				}
398
-				else{
390
+				} else{
399 391
 					ob_start();
400 392
 				}
401 393
 				require_once $path;
402 394
 				$output = ob_get_clean();
403 395
 				self::sendHeaders(404);
404 396
 				echo $output;
405
-			}
406
-			else{
397
+			} else{
407 398
 				show_error('The 404 view [' .$path. '] does not exist');
408 399
 			}
409 400
 		}
@@ -418,8 +409,7 @@  discard block
 block discarded – undo
418 409
 				//compress the output if exists
419 410
 				if (self::$_canCompressOutput){
420 411
 					ob_start('ob_gzhandler');
421
-				}
422
-				else{
412
+				} else{
423 413
 					ob_start();
424 414
 				}
425 415
 				extract($data);
@@ -427,8 +417,7 @@  discard block
 block discarded – undo
427 417
 				$output = ob_get_clean();
428 418
 				self::sendHeaders(503);
429 419
 				echo $output;
430
-			}
431
-			else{
420
+			} else{
432 421
 				//can't use show_error() at this time because some dependencies not yet loaded and to prevent loop
433 422
 				set_http_status_header(503);
434 423
 				echo 'The error view [' . $path . '] does not exist';
Please login to merge, or discard this patch.
Spacing   +74 added lines, -74 removed lines patch added patch discarded remove patch
@@ -24,7 +24,7 @@  discard block
 block discarded – undo
24 24
 	 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
25 25
 	*/
26 26
 
27
-	class Response{
27
+	class Response {
28 28
 
29 29
 		/**
30 30
 		 * The list of request header to send with response
@@ -65,9 +65,9 @@  discard block
 block discarded – undo
65 65
 		/**
66 66
 		 * Construct new response instance
67 67
 		 */
68
-		public function __construct(){
69
-			$this->_currentUrl =  (! empty($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : '' )
70
-					. (! empty($_SERVER['QUERY_STRING']) ? ('?' . $_SERVER['QUERY_STRING']) : '' );
68
+		public function __construct() {
69
+			$this->_currentUrl = (!empty($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : '')
70
+					. (!empty($_SERVER['QUERY_STRING']) ? ('?' . $_SERVER['QUERY_STRING']) : '');
71 71
 					
72 72
 			$this->_currentUrlCacheKey = md5($this->_currentUrl);
73 73
 			
@@ -82,9 +82,9 @@  discard block
 block discarded – undo
82 82
 		 * Get the logger singleton instance
83 83
 		 * @return Log the logger instance
84 84
 		 */
85
-		private static function getLogger(){
86
-			if(self::$logger == null){
87
-				self::$logger[0] =& class_loader('Log', 'classes');
85
+		private static function getLogger() {
86
+			if (self::$logger == null) {
87
+				self::$logger[0] = & class_loader('Log', 'classes');
88 88
 				self::$logger[0]->setLogger('Library::Response');
89 89
 			}
90 90
 			return self::$logger[0];
@@ -95,12 +95,12 @@  discard block
 block discarded – undo
95 95
 		 * @param  integer $httpCode the HTTP status code
96 96
 		 * @param  array   $headers   the additional headers to add to the existing headers list
97 97
 		 */
98
-		public static function sendHeaders($httpCode = 200, array $headers = array()){
98
+		public static function sendHeaders($httpCode = 200, array $headers = array()) {
99 99
 			set_http_status_header($httpCode);
100 100
 			self::setHeaders($headers);
101
-			if(! headers_sent()){
102
-				foreach(self::getHeaders() as $key => $value){
103
-					header($key .': '.$value);
101
+			if (!headers_sent()) {
102
+				foreach (self::getHeaders() as $key => $value) {
103
+					header($key . ': ' . $value);
104 104
 				}
105 105
 			}
106 106
 		}
@@ -109,7 +109,7 @@  discard block
 block discarded – undo
109 109
 		 * Get the list of the headers
110 110
 		 * @return array the headers list
111 111
 		 */
112
-		public static function getHeaders(){
112
+		public static function getHeaders() {
113 113
 			return self::$headers;
114 114
 		}
115 115
 
@@ -118,7 +118,7 @@  discard block
 block discarded – undo
118 118
 		 * @param  string $name the header name
119 119
 		 * @return string       the header value
120 120
 		 */
121
-		public static function getHeader($name){
121
+		public static function getHeader($name) {
122 122
 			return array_key_exists($name, self::$headers) ? self::$headers[$name] : null;
123 123
 		}
124 124
 
@@ -128,7 +128,7 @@  discard block
 block discarded – undo
128 128
 		 * @param string $name  the header name
129 129
 		 * @param string $value the header value to be set
130 130
 		 */
131
-		public static function setHeader($name, $value){
131
+		public static function setHeader($name, $value) {
132 132
 			self::$headers[$name] = $value;
133 133
 		}
134 134
 
@@ -137,7 +137,7 @@  discard block
 block discarded – undo
137 137
 		 * @param array $headers the list of the headers to set. 
138 138
 		 * Note: this will merge with the existing headers
139 139
 		 */
140
-		public static function setHeaders(array $headers){
140
+		public static function setHeaders(array $headers) {
141 141
 			self::$headers = array_merge(self::getHeaders(), $headers);
142 142
 		}
143 143
 		
@@ -145,17 +145,17 @@  discard block
 block discarded – undo
145 145
 		 * Redirect user in the specified page
146 146
 		 * @param  string $path the URL or URI to be redirect to
147 147
 		 */
148
-		public static function redirect($path = ''){
148
+		public static function redirect($path = '') {
149 149
 			$logger = self::getLogger();
150 150
 			$url = Url::site_url($path);
151
-			$logger->info('Redirect to URL [' .$url. ']');
152
-			if(! headers_sent()){
153
-				header('Location: '.$url);
151
+			$logger->info('Redirect to URL [' . $url . ']');
152
+			if (!headers_sent()) {
153
+				header('Location: ' . $url);
154 154
 				exit;
155 155
 			}
156
-			else{
156
+			else {
157 157
 				echo '<script>
158
-						location.href = "'.$url.'";
158
+						location.href = "'.$url . '";
159 159
 					</script>';
160 160
 			}
161 161
 		}
@@ -168,10 +168,10 @@  discard block
 block discarded – undo
168 168
 		 * @return void|string          if $return is true will return the view content otherwise
169 169
 		 * will display the view content.
170 170
 		 */
171
-		public function render($view, $data = null, $return = false){
171
+		public function render($view, $data = null, $return = false) {
172 172
 			$logger = self::getLogger();
173 173
 			//convert data to an array
174
-			$data = ! is_array($data) ? (array) $data : $data;
174
+			$data = !is_array($data) ? (array) $data : $data;
175 175
 			$view = str_ireplace('.php', '', $view);
176 176
 			$view = trim($view, '/\\');
177 177
 			$viewFile = $view . '.php';
@@ -180,42 +180,42 @@  discard block
 block discarded – undo
180 180
 			//super instance
181 181
 			$obj = & get_instance();
182 182
 			
183
-			if(Module::hasModule()){
183
+			if (Module::hasModule()) {
184 184
 				//check in module first
185 185
 				$logger->debug('Checking the view [' . $view . '] from module list ...');
186 186
 				$mod = null;
187 187
 				//check if the request class contains module name
188
-				if(strpos($view, '/') !== false){
188
+				if (strpos($view, '/') !== false) {
189 189
 					$viewPath = explode('/', $view);
190
-					if(isset($viewPath[0]) && in_array($viewPath[0], Module::getModuleList())){
190
+					if (isset($viewPath[0]) && in_array($viewPath[0], Module::getModuleList())) {
191 191
 						$mod = $viewPath[0];
192 192
 						array_shift($viewPath);
193 193
 						$view = implode('/', $viewPath);
194 194
 						$viewFile = $view . '.php';
195 195
 					}
196 196
 				}
197
-				if(! $mod && !empty($obj->moduleName)){
197
+				if (!$mod && !empty($obj->moduleName)) {
198 198
 					$mod = $obj->moduleName;
199 199
 				}
200
-				if($mod){
200
+				if ($mod) {
201 201
 					$moduleViewPath = Module::findViewFullPath($view, $mod);
202
-					if($moduleViewPath){
202
+					if ($moduleViewPath) {
203 203
 						$path = $moduleViewPath;
204
-						$logger->info('Found view [' . $view . '] in module [' .$mod. '], the file path is [' .$moduleViewPath. '] we will used it');
204
+						$logger->info('Found view [' . $view . '] in module [' . $mod . '], the file path is [' . $moduleViewPath . '] we will used it');
205 205
 					}
206
-					else{
207
-						$logger->info('Cannot find view [' . $view . '] in module [' .$mod. '] using the default location');
206
+					else {
207
+						$logger->info('Cannot find view [' . $view . '] in module [' . $mod . '] using the default location');
208 208
 					}
209 209
 				}
210
-				else{
210
+				else {
211 211
 					$logger->info('The current request does not use module using the default location.');
212 212
 				}
213 213
 			}
214 214
 			$logger->info('The view file path to be loaded is [' . $path . ']');
215 215
 			$found = false;
216
-			if(file_exists($path)){
217
-				foreach(get_object_vars($obj) as $key => $value){
218
-					if(! isset($this->{$key})){
216
+			if (file_exists($path)) {
217
+				foreach (get_object_vars($obj) as $key => $value) {
218
+					if (!isset($this->{$key})) {
219 219
 						$this->{$key} = & $obj->{$key};
220 220
 					}
221 221
 				}
@@ -224,39 +224,39 @@  discard block
 block discarded – undo
224 224
 				//need use require() instead of require_once because can load this view many time
225 225
 				require $path;
226 226
 				$content = ob_get_clean();
227
-				if($return){
227
+				if ($return) {
228 228
 					return $content;
229 229
 				}
230 230
 				$this->_pageRender .= $content;
231 231
 				$found = true;
232 232
 			}
233
-			if(! $found){
234
-				show_error('Unable to find view [' .$view . ']');
233
+			if (!$found) {
234
+				show_error('Unable to find view [' . $view . ']');
235 235
 			}
236 236
 		}
237 237
 		
238 238
 		/**
239 239
 		* Send the final page output to user
240 240
 		*/
241
-		public function renderFinalPage(){
241
+		public function renderFinalPage() {
242 242
 			$logger = self::getLogger();
243 243
 			$obj = & get_instance();
244 244
 			$cachePageStatus = get_config('cache_enable', false) && !empty($obj->view_cache_enable);
245 245
 			$dispatcher = $obj->eventdispatcher;
246 246
 			$content = $this->_pageRender;
247
-			if(! $content){
247
+			if (!$content) {
248 248
 				$logger->warning('The final view content is empty.');
249 249
 				return;
250 250
 			}
251 251
 			//dispatch
252 252
 			$event = $dispatcher->dispatch(new EventInfo('FINAL_VIEW_READY', $content, true));
253
-			$content = ! empty($event->payload) ? $event->payload : null;
254
-			if(empty($content)){
253
+			$content = !empty($event->payload) ? $event->payload : null;
254
+			if (empty($content)) {
255 255
 				$logger->warning('The view content is empty after dispatch to event listeners.');
256 256
 			}
257 257
 			
258 258
 			//check whether need save the page into cache.
259
-			if($cachePageStatus){
259
+			if ($cachePageStatus) {
260 260
 				//current page URL
261 261
 				$url = $this->_currentUrl;
262 262
 				//Cache view Time to live in second
@@ -271,14 +271,14 @@  discard block
 block discarded – undo
271 271
 				
272 272
 				//get the cache information to prepare header to send to browser
273 273
 				$cacheInfo = $cacheInstance->getInfo($cacheKey);
274
-				if($cacheInfo){
274
+				if ($cacheInfo) {
275 275
 					$lastModified = $cacheInfo['mtime'];
276 276
 					$expire = $cacheInfo['expire'];
277 277
 					$maxAge = $expire - time();
278 278
 					self::setHeader('Pragma', 'public');
279 279
 					self::setHeader('Cache-Control', 'max-age=' . $maxAge . ', public');
280
-					self::setHeader('Expires', gmdate('D, d M Y H:i:s', $expire).' GMT');
281
-					self::setHeader('Last-modified', gmdate('D, d M Y H:i:s', $lastModified).' GMT');	
280
+					self::setHeader('Expires', gmdate('D, d M Y H:i:s', $expire) . ' GMT');
281
+					self::setHeader('Last-modified', gmdate('D, d M Y H:i:s', $lastModified) . ' GMT');	
282 282
 				}
283 283
 			}
284 284
 			
@@ -289,10 +289,10 @@  discard block
 block discarded – undo
289 289
 			$content = str_replace(array('{elapsed_time}', '{memory_usage}'), array($elapsedTime, $memoryUsage), $content);
290 290
 			
291 291
 			//compress the output if is available
292
-			if (self::$_canCompressOutput){
292
+			if (self::$_canCompressOutput) {
293 293
 				ob_start('ob_gzhandler');
294 294
 			}
295
-			else{
295
+			else {
296 296
 				ob_start();
297 297
 			}
298 298
 			self::sendHeaders(200);
@@ -303,7 +303,7 @@  discard block
 block discarded – undo
303 303
 		/**
304 304
 		* Send the final page output to user if is cached
305 305
 		*/
306
-		public function renderFinalPageFromCache(&$cache){
306
+		public function renderFinalPageFromCache(&$cache) {
307 307
 			$logger = self::getLogger();
308 308
 			$url = $this->_currentUrl;					
309 309
 			//the current page cache key for identification
@@ -312,25 +312,25 @@  discard block
 block discarded – undo
312 312
 			$logger->debug('Checking if the page content for the URL [' . $url . '] is cached ...');
313 313
 			//get the cache information to prepare header to send to browser
314 314
 			$cacheInfo = $cache->getInfo($pageCacheKey);
315
-			if($cacheInfo){
315
+			if ($cacheInfo) {
316 316
 				$lastModified = $cacheInfo['mtime'];
317 317
 				$expire = $cacheInfo['expire'];
318 318
 				$maxAge = $expire - $_SERVER['REQUEST_TIME'];
319 319
 				self::setHeader('Pragma', 'public');
320 320
 				self::setHeader('Cache-Control', 'max-age=' . $maxAge . ', public');
321
-				self::setHeader('Expires', gmdate('D, d M Y H:i:s', $expire).' GMT');
322
-				self::setHeader('Last-modified', gmdate('D, d M Y H:i:s', $lastModified).' GMT');
323
-				if (isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) && $lastModified <= strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE'])){
321
+				self::setHeader('Expires', gmdate('D, d M Y H:i:s', $expire) . ' GMT');
322
+				self::setHeader('Last-modified', gmdate('D, d M Y H:i:s', $lastModified) . ' GMT');
323
+				if (isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) && $lastModified <= strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE'])) {
324 324
 					$logger->info('The cache page content is not yet expire for the URL [' . $url . '] send 304 header to browser');
325 325
 					self::sendHeaders(304);
326 326
 					return;
327 327
 				}
328
-				else{
328
+				else {
329 329
 					$logger->info('The cache page content is expired or the browser don\'t send the HTTP_IF_MODIFIED_SINCE header for the URL [' . $url . '] send cache headers to tell the browser');
330 330
 					self::sendHeaders(200);
331 331
 					//get the cache content
332 332
 					$content = $cache->get($pageCacheKey);
333
-					if($content){
333
+					if ($content) {
334 334
 						$logger->info('The page content for the URL [' . $url . '] already cached just display it');
335 335
 						//load benchmark class
336 336
 						$benchmark = & class_loader('Benchmark');
@@ -343,17 +343,17 @@  discard block
 block discarded – undo
343 343
 						
344 344
 						///display the final output
345 345
 						//compress the output if is available
346
-						if (self::$_canCompressOutput){
346
+						if (self::$_canCompressOutput) {
347 347
 							ob_start('ob_gzhandler');
348 348
 						}
349
-						else{
349
+						else {
350 350
 							ob_start();
351 351
 						}
352 352
 						echo $content;
353 353
 						ob_end_flush();
354 354
 						return;
355 355
 					}
356
-					else{
356
+					else {
357 357
 						$logger->info('The page cache content for the URL [' . $url . '] is not valid may be already expired');
358 358
 						$cache->delete($pageCacheKey);
359 359
 					}
@@ -365,7 +365,7 @@  discard block
 block discarded – undo
365 365
 		* Get the final page to be rendered
366 366
 		* @return string
367 367
 		*/
368
-		public function getFinalPageRendered(){
368
+		public function getFinalPageRendered() {
369 369
 			return $this->_pageRender;
370 370
 		}
371 371
 
@@ -373,14 +373,14 @@  discard block
 block discarded – undo
373 373
 		 * Send the HTTP 404 error if can not found the 
374 374
 		 * routing information for the current request
375 375
 		 */
376
-		public static function send404(){
376
+		public static function send404() {
377 377
 			/********* for logs **************/
378 378
 			//can't use $obj = & get_instance()  here because the global super object will be available until
379 379
 			//the main controller is loaded even for Loader::library('xxxx');
380 380
 			$logger = self::getLogger();
381
-			$request =& class_loader('Request', 'classes');
382
-			$userAgent =& class_loader('Browser');
383
-			$browser = $userAgent->getPlatform().', '.$userAgent->getBrowser().' '.$userAgent->getVersion();
381
+			$request = & class_loader('Request', 'classes');
382
+			$userAgent = & class_loader('Browser');
383
+			$browser = $userAgent->getPlatform() . ', ' . $userAgent->getBrowser() . ' ' . $userAgent->getVersion();
384 384
 			
385 385
 			//here can't use Loader::functions just include the helper manually
386 386
 			require_once CORE_FUNCTIONS_PATH . 'function_user_agent.php';
@@ -390,12 +390,12 @@  discard block
 block discarded – undo
390 390
 			$logger->error($str);
391 391
 			/***********************************/
392 392
 			$path = CORE_VIEWS_PATH . '404.php';
393
-			if(file_exists($path)){
393
+			if (file_exists($path)) {
394 394
 				//compress the output if is available
395
-				if (self::$_canCompressOutput){
395
+				if (self::$_canCompressOutput) {
396 396
 					ob_start('ob_gzhandler');
397 397
 				}
398
-				else{
398
+				else {
399 399
 					ob_start();
400 400
 				}
401 401
 				require_once $path;
@@ -403,8 +403,8 @@  discard block
 block discarded – undo
403 403
 				self::sendHeaders(404);
404 404
 				echo $output;
405 405
 			}
406
-			else{
407
-				show_error('The 404 view [' .$path. '] does not exist');
406
+			else {
407
+				show_error('The 404 view [' . $path . '] does not exist');
408 408
 			}
409 409
 		}
410 410
 
@@ -412,14 +412,14 @@  discard block
 block discarded – undo
412 412
 		 * Display the error to user
413 413
 		 * @param  array  $data the error information
414 414
 		 */
415
-		public static function sendError(array $data = array()){
415
+		public static function sendError(array $data = array()) {
416 416
 			$path = CORE_VIEWS_PATH . 'errors.php';
417
-			if(file_exists($path)){
417
+			if (file_exists($path)) {
418 418
 				//compress the output if exists
419
-				if (self::$_canCompressOutput){
419
+				if (self::$_canCompressOutput) {
420 420
 					ob_start('ob_gzhandler');
421 421
 				}
422
-				else{
422
+				else {
423 423
 					ob_start();
424 424
 				}
425 425
 				extract($data);
@@ -428,7 +428,7 @@  discard block
 block discarded – undo
428 428
 				self::sendHeaders(503);
429 429
 				echo $output;
430 430
 			}
431
-			else{
431
+			else {
432 432
 				//can't use show_error() at this time because some dependencies not yet loaded and to prevent loop
433 433
 				set_http_status_header(503);
434 434
 				echo 'The error view [' . $path . '] does not exist';
Please login to merge, or discard this patch.
core/classes/EventInfo.php 2 patches
Indentation   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -22,7 +22,7 @@
 block discarded – undo
22 22
 	 * You should have received a copy of the GNU General Public License
23 23
 	 * along with this program; if not, write to the Free Software
24 24
 	 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
25
-	*/
25
+	 */
26 26
 
27 27
 	/**
28 28
 	 * This class represent the event detail to dispatch to correspond listener
Please login to merge, or discard this patch.
Spacing   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -27,7 +27,7 @@  discard block
 block discarded – undo
27 27
 	/**
28 28
 	 * This class represent the event detail to dispatch to correspond listener
29 29
 	 */
30
-	class EventInfo{
30
+	class EventInfo {
31 31
 		
32 32
 		/**
33 33
 		 * The event name
@@ -54,7 +54,7 @@  discard block
 block discarded – undo
54 54
 		 */
55 55
 		public $stop;
56 56
 		
57
-		public function __construct($name, $payload = array(), $returnBack = false, $stop = false){
57
+		public function __construct($name, $payload = array(), $returnBack = false, $stop = false) {
58 58
 			$this->name = $name;
59 59
 			$this->payload = $payload;
60 60
 			$this->returnBack = $returnBack;
Please login to merge, or discard this patch.
core/classes/Controller.php 3 patches
Indentation   +6 added lines, -6 removed lines patch added patch discarded remove patch
@@ -22,7 +22,7 @@  discard block
 block discarded – undo
22 22
 	 * You should have received a copy of the GNU General Public License
23 23
 	 * along with this program; if not, write to the Free Software
24 24
 	 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
25
-	*/
25
+	 */
26 26
 
27 27
 	class Controller{
28 28
 		
@@ -114,12 +114,12 @@  discard block
 block discarded – undo
114 114
 		 */
115 115
 		protected function setLoggerFromParamOrCreateNewInstance(Log $logger = null){
116 116
 			if($logger !== null){
117
-	          $this->logger = $logger;
118
-	        }
119
-	        else{
120
-	            $this->logger =& class_loader('Log', 'classes');
117
+			  $this->logger = $logger;
118
+			}
119
+			else{
120
+				$this->logger =& class_loader('Log', 'classes');
121 121
 				$this->logger->setLogger('MainController');
122
-	        }
122
+			}
123 123
 		}
124 124
 
125 125
 		/**
Please login to merge, or discard this patch.
Braces   +1 added lines, -2 removed lines patch added patch discarded remove patch
@@ -115,8 +115,7 @@
 block discarded – undo
115 115
 		protected function setLoggerFromParamOrCreateNewInstance(Log $logger = null){
116 116
 			if($logger !== null){
117 117
 	          $this->logger = $logger;
118
-	        }
119
-	        else{
118
+	        } else{
120 119
 	            $this->logger =& class_loader('Log', 'classes');
121 120
 				$this->logger->setLogger('MainController');
122 121
 	        }
Please login to merge, or discard this patch.
Spacing   +20 added lines, -20 removed lines patch added patch discarded remove patch
@@ -24,7 +24,7 @@  discard block
 block discarded – undo
24 24
 	 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
25 25
 	*/
26 26
 
27
-	class Controller{
27
+	class Controller {
28 28
 		
29 29
 		/**
30 30
 		 * The name of the module if this controller belong to an module
@@ -48,7 +48,7 @@  discard block
 block discarded – undo
48 48
 		 * Class constructor
49 49
 		 * @param object $logger the Log instance to use if is null will create one
50 50
 		 */
51
-		public function __construct(Log $logger = null){
51
+		public function __construct(Log $logger = null) {
52 52
 			//setting the Log instance
53 53
 			$this->setLoggerFromParamOrCreateNewInstance($logger);
54 54
 			
@@ -84,9 +84,9 @@  discard block
 block discarded – undo
84 84
 		/**
85 85
 		 * This method is used to set the module name
86 86
 		 */
87
-		protected function setModuleNameFromRouter(){
87
+		protected function setModuleNameFromRouter() {
88 88
 			//determine the current module
89
-			if(isset($this->router) && $this->router->getModule()){
89
+			if (isset($this->router) && $this->router->getModule()) {
90 90
 				$this->moduleName = $this->router->getModule();
91 91
 			}
92 92
 		}
@@ -95,13 +95,13 @@  discard block
 block discarded – undo
95 95
 		 * Set the cache using the argument otherwise will use the configuration
96 96
 		 * @param CacheInterface $cache the implementation of CacheInterface if null will use the configured
97 97
 		 */
98
-		protected function setCacheFromParamOrConfig(CacheInterface $cache = null){
98
+		protected function setCacheFromParamOrConfig(CacheInterface $cache = null) {
99 99
 			$this->logger->debug('Setting the cache handler instance');
100 100
 			//set cache handler instance
101
-			if(get_config('cache_enable', false)){
102
-				if ($cache !== null){
101
+			if (get_config('cache_enable', false)) {
102
+				if ($cache !== null) {
103 103
 					$this->cache = $cache;
104
-				} else if (isset($this->{strtolower(get_config('cache_handler'))})){
104
+				} else if (isset($this->{strtolower(get_config('cache_handler'))})) {
105 105
 					$this->cache = $this->{strtolower(get_config('cache_handler'))};
106 106
 					unset($this->{strtolower(get_config('cache_handler'))});
107 107
 				} 
@@ -112,12 +112,12 @@  discard block
 block discarded – undo
112 112
 		 * Set the Log instance using argument or create new instance
113 113
 		 * @param object $logger the Log instance if not null
114 114
 		 */
115
-		protected function setLoggerFromParamOrCreateNewInstance(Log $logger = null){
116
-			if($logger !== null){
115
+		protected function setLoggerFromParamOrCreateNewInstance(Log $logger = null) {
116
+			if ($logger !== null) {
117 117
 	          $this->logger = $logger;
118 118
 	        }
119
-	        else{
120
-	            $this->logger =& class_loader('Log', 'classes');
119
+	        else {
120
+	            $this->logger = & class_loader('Log', 'classes');
121 121
 				$this->logger->setLogger('MainController');
122 122
 	        }
123 123
 		}
@@ -126,20 +126,20 @@  discard block
 block discarded – undo
126 126
 		 * This method is used to load the required resources for framework to work
127 127
 		 * @return void 
128 128
 		 */
129
-		private function loadRequiredResources(){
129
+		private function loadRequiredResources() {
130 130
 			$this->logger->debug('Adding the loaded classes to the super instance');
131
-			foreach (class_loaded() as $var => $class){
132
-				$this->$var =& class_loader($class);
131
+			foreach (class_loaded() as $var => $class) {
132
+				$this->$var = & class_loader($class);
133 133
 			}
134 134
 
135 135
 			$this->logger->debug('Loading the required classes into super instance');
136
-			$this->eventdispatcher =& class_loader('EventDispatcher', 'classes');
137
-			$this->loader =& class_loader('Loader', 'classes');
138
-			$this->lang =& class_loader('Lang', 'classes');
139
-			$this->request =& class_loader('Request', 'classes');
136
+			$this->eventdispatcher = & class_loader('EventDispatcher', 'classes');
137
+			$this->loader = & class_loader('Loader', 'classes');
138
+			$this->lang = & class_loader('Lang', 'classes');
139
+			$this->request = & class_loader('Request', 'classes');
140 140
 			//dispatch the request instance created event
141 141
 			$this->eventdispatcher->dispatch('REQUEST_CREATED');
142
-			$this->response =& class_loader('Response', 'classes', 'classes');
142
+			$this->response = & class_loader('Response', 'classes', 'classes');
143 143
 		}
144 144
 
145 145
 	}
Please login to merge, or discard this patch.
tests/tnhfw/classes/EventInfoTest.php 1 patch
Spacing   +4 added lines, -4 removed lines patch added patch discarded remove patch
@@ -25,7 +25,7 @@  discard block
 block discarded – undo
25 25
 
26 26
 		
27 27
 		
28
-		public function testDefaultValue(){
28
+		public function testDefaultValue() {
29 29
 			$e = new EventInfo('foo');
30 30
 			$this->assertSame($e->name, 'foo');
31 31
 			$this->assertSame($e->payload, array());
@@ -33,7 +33,7 @@  discard block
 block discarded – undo
33 33
 			$this->assertFalse($e->stop);
34 34
 		}
35 35
 		
36
-		public function testPayloadValueIsSet(){
36
+		public function testPayloadValueIsSet() {
37 37
 			$e = new EventInfo('foo', array('bar'));
38 38
 			$this->assertSame($e->name, 'foo');
39 39
 			$this->assertSame($e->payload, array('bar'));
@@ -41,7 +41,7 @@  discard block
 block discarded – undo
41 41
 			$this->assertFalse($e->stop);
42 42
 		}
43 43
 		
44
-		public function testReturnBackValueIsSetToTrue(){
44
+		public function testReturnBackValueIsSetToTrue() {
45 45
 			$e = new EventInfo('foo', array('bar'), true);
46 46
 			$this->assertSame($e->name, 'foo');
47 47
 			$this->assertSame($e->payload, array('bar'));
@@ -49,7 +49,7 @@  discard block
 block discarded – undo
49 49
 			$this->assertFalse($e->stop);
50 50
 		}
51 51
 		
52
-		public function testStopValueIsSetToTue(){
52
+		public function testStopValueIsSetToTue() {
53 53
 			$e = new EventInfo('foo', array('bar'), true, true);
54 54
 			$this->assertSame($e->name, 'foo');
55 55
 			$this->assertSame($e->payload, array('bar'));
Please login to merge, or discard this patch.
core/libraries/FormValidation.php 3 patches
Indentation   +872 added lines, -872 removed lines patch added patch discarded remove patch
@@ -1,914 +1,914 @@
 block discarded – undo
1 1
 <?php
2
-    defined('ROOT_PATH') || exit('Access denied');
3
-    /**
4
-     * TNH Framework
5
-     *
6
-     * A simple PHP framework using HMVC architecture
7
-     *
8
-     * This content is released under the GNU GPL License (GPL)
9
-     *
10
-     * Copyright (C) 2017 Tony NGUEREZA
11
-     *
12
-     * This program is free software; you can redistribute it and/or
13
-     * modify it under the terms of the GNU General Public License
14
-     * as published by the Free Software Foundation; either version 3
15
-     * of the License, or (at your option) any later version.
16
-     *
17
-     * This program is distributed in the hope that it will be useful,
18
-     * but WITHOUT ANY WARRANTY; without even the implied warranty of
19
-     * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20
-     * GNU General Public License for more details.
21
-     *
22
-     * You should have received a copy of the GNU General Public License
23
-     * along with this program; if not, write to the Free Software
24
-     * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
25
-    */
26
-
27
-
28
-     class FormValidation{
2
+	defined('ROOT_PATH') || exit('Access denied');
3
+	/**
4
+	 * TNH Framework
5
+	 *
6
+	 * A simple PHP framework using HMVC architecture
7
+	 *
8
+	 * This content is released under the GNU GPL License (GPL)
9
+	 *
10
+	 * Copyright (C) 2017 Tony NGUEREZA
11
+	 *
12
+	 * This program is free software; you can redistribute it and/or
13
+	 * modify it under the terms of the GNU General Public License
14
+	 * as published by the Free Software Foundation; either version 3
15
+	 * of the License, or (at your option) any later version.
16
+	 *
17
+	 * This program is distributed in the hope that it will be useful,
18
+	 * but WITHOUT ANY WARRANTY; without even the implied warranty of
19
+	 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20
+	 * GNU General Public License for more details.
21
+	 *
22
+	 * You should have received a copy of the GNU General Public License
23
+	 * along with this program; if not, write to the Free Software
24
+	 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
25
+	 */
26
+
27
+
28
+	 class FormValidation{
29 29
 		 
30
-        /**
31
-         * The form validation status
32
-         * @var boolean
33
-         */
34
-        protected $_success  = false;
35
-
36
-        /**
37
-         * The list of errors messages
38
-         * @var array
39
-         */
40
-        protected $_errorsMessages = array();
30
+		/**
31
+		 * The form validation status
32
+		 * @var boolean
33
+		 */
34
+		protected $_success  = false;
35
+
36
+		/**
37
+		 * The list of errors messages
38
+		 * @var array
39
+		 */
40
+		protected $_errorsMessages = array();
41 41
         
42
-        // Array of rule sets, fieldName => PIPE seperated ruleString
43
-        protected $_rules             = array();
42
+		// Array of rule sets, fieldName => PIPE seperated ruleString
43
+		protected $_rules             = array();
44 44
         
45
-        // Array of errors, niceName => Error Message
46
-        protected $_errors             = array();
45
+		// Array of errors, niceName => Error Message
46
+		protected $_errors             = array();
47 47
         
48
-        // Array of post Key => Nice name labels
49
-        protected $_labels          = array();
48
+		// Array of post Key => Nice name labels
49
+		protected $_labels          = array();
50 50
         
51
-        /**
52
-         * The errors delimiters
53
-         * @var array
54
-         */
55
-        protected $_allErrorsDelimiter   = array('<div class="error">', '</div>');
56
-
57
-        /**
58
-         * The each error delimiter
59
-         * @var array
60
-         */
61
-        protected $_eachErrorDelimiter   = array('<p class="error">', '</p>');
51
+		/**
52
+		 * The errors delimiters
53
+		 * @var array
54
+		 */
55
+		protected $_allErrorsDelimiter   = array('<div class="error">', '</div>');
56
+
57
+		/**
58
+		 * The each error delimiter
59
+		 * @var array
60
+		 */
61
+		protected $_eachErrorDelimiter   = array('<p class="error">', '</p>');
62 62
         
63 63
 		/**
64
-         * Indicated if need force the validation to be failed
65
-         * @var boolean
66
-         */
67
-        protected $_forceFail            = false;
68
-
69
-        /**
70
-         * The list of the error messages overrides by the original
71
-         * @var array
72
-         */
73
-        protected $_errorPhraseOverrides = array();
74
-
75
-        /**
76
-         * The logger instance
77
-         * @var Log
78
-         */
79
-        private $logger;
80
-
81
-        /**
82
-         * The data to be validated, the default is to use $_POST
83
-         * @var array
84
-         */
85
-        private $data = array();
86
-
87
-        /**
88
-         * Whether to check the CSRF. This attribute is just a way to allow custom change of the 
64
+		 * Indicated if need force the validation to be failed
65
+		 * @var boolean
66
+		 */
67
+		protected $_forceFail            = false;
68
+
69
+		/**
70
+		 * The list of the error messages overrides by the original
71
+		 * @var array
72
+		 */
73
+		protected $_errorPhraseOverrides = array();
74
+
75
+		/**
76
+		 * The logger instance
77
+		 * @var Log
78
+		 */
79
+		private $logger;
80
+
81
+		/**
82
+		 * The data to be validated, the default is to use $_POST
83
+		 * @var array
84
+		 */
85
+		private $data = array();
86
+
87
+		/**
88
+		 * Whether to check the CSRF. This attribute is just a way to allow custom change of the 
89 89
 		 * CSRF global configuration
90 90
 		 *
91
-         * @var boolean
92
-         */
93
-        public $enableCsrfCheck = false;
94
-
95
-        /**
96
-         * Set all errors and rule sets empty, and sets success to false.
97
-         *
98
-         * @return void
99
-         */
100
-        public function __construct() {
101
-            $this->logger =& class_loader('Log', 'classes');
102
-            $this->logger->setLogger('Library::FormValidation');
91
+		 * @var boolean
92
+		 */
93
+		public $enableCsrfCheck = false;
94
+
95
+		/**
96
+		 * Set all errors and rule sets empty, and sets success to false.
97
+		 *
98
+		 * @return void
99
+		 */
100
+		public function __construct() {
101
+			$this->logger =& class_loader('Log', 'classes');
102
+			$this->logger->setLogger('Library::FormValidation');
103 103
            
104 104
 		   //Load form validation language message
105
-            Loader::lang('form_validation');
106
-            $obj = & get_instance();
107
-            $this->_errorsMessages  = array(
108
-                        'required'         => $obj->lang->get('fv_required'),
109
-                        'min_length'       => $obj->lang->get('fv_min_length'),
110
-                        'max_length'       => $obj->lang->get('fv_max_length'),
111
-                        'exact_length'     => $obj->lang->get('fv_exact_length'),
112
-                        'less_than'        => $obj->lang->get('fv_less_than'),
113
-                        'greater_than'     => $obj->lang->get('fv_greater_than'),
114
-                        'matches'          => $obj->lang->get('fv_matches'),
115
-                        'valid_email'      => $obj->lang->get('fv_valid_email'),
116
-                        'not_equal'        => array(
117
-                                                'post:key' => $obj->lang->get('fv_not_equal_post_key'),
118
-                                                'string'   => $obj->lang->get('fv_not_equal_string')
119
-                                            ),
120
-                        'depends'          => $obj->lang->get('fv_depends'),
121
-                        'is_unique'        => $obj->lang->get('fv_is_unique'),
122
-                        'is_unique_update' => $obj->lang->get('fv_is_unique_update'),
123
-                        'exists'           => $obj->lang->get('fv_exists'),
124
-                        'regex'            => $obj->lang->get('fv_regex'),
125
-                        'in_list'          => $obj->lang->get('fv_in_list'),
126
-                        'numeric'          => $obj->lang->get('fv_numeric'),
127
-                        'callback'         => $obj->lang->get('fv_callback'),
128
-                    );
129
-            $this->_resetValidation();
130
-            $this->setData($obj->request->post(null));
131
-        }
132
-
133
-        /**
134
-         * Reset the form validation instance
135
-         */
136
-        protected function _resetValidation() {
137
-            $this->_rules                = array();
138
-            $this->_labels               = array();
139
-            $this->_errorPhraseOverrides = array();
140
-            $this->_errors               = array();
141
-            $this->_success              = false;
142
-            $this->_forceFail            = false;
143
-            $this->data                  = array();
105
+			Loader::lang('form_validation');
106
+			$obj = & get_instance();
107
+			$this->_errorsMessages  = array(
108
+						'required'         => $obj->lang->get('fv_required'),
109
+						'min_length'       => $obj->lang->get('fv_min_length'),
110
+						'max_length'       => $obj->lang->get('fv_max_length'),
111
+						'exact_length'     => $obj->lang->get('fv_exact_length'),
112
+						'less_than'        => $obj->lang->get('fv_less_than'),
113
+						'greater_than'     => $obj->lang->get('fv_greater_than'),
114
+						'matches'          => $obj->lang->get('fv_matches'),
115
+						'valid_email'      => $obj->lang->get('fv_valid_email'),
116
+						'not_equal'        => array(
117
+												'post:key' => $obj->lang->get('fv_not_equal_post_key'),
118
+												'string'   => $obj->lang->get('fv_not_equal_string')
119
+											),
120
+						'depends'          => $obj->lang->get('fv_depends'),
121
+						'is_unique'        => $obj->lang->get('fv_is_unique'),
122
+						'is_unique_update' => $obj->lang->get('fv_is_unique_update'),
123
+						'exists'           => $obj->lang->get('fv_exists'),
124
+						'regex'            => $obj->lang->get('fv_regex'),
125
+						'in_list'          => $obj->lang->get('fv_in_list'),
126
+						'numeric'          => $obj->lang->get('fv_numeric'),
127
+						'callback'         => $obj->lang->get('fv_callback'),
128
+					);
129
+			$this->_resetValidation();
130
+			$this->setData($obj->request->post(null));
131
+		}
132
+
133
+		/**
134
+		 * Reset the form validation instance
135
+		 */
136
+		protected function _resetValidation() {
137
+			$this->_rules                = array();
138
+			$this->_labels               = array();
139
+			$this->_errorPhraseOverrides = array();
140
+			$this->_errors               = array();
141
+			$this->_success              = false;
142
+			$this->_forceFail            = false;
143
+			$this->data                  = array();
144 144
 			$this->enableCsrfCheck       = false;
145
-        }
145
+		}
146 146
 
147
-        /**
148
-         * Set the form validation data
149
-         * @param array $data the values to be validated
147
+		/**
148
+		 * Set the form validation data
149
+		 * @param array $data the values to be validated
150 150
 		 *
151
-         * @return FormValidation Current instance of object.
152
-         */
153
-        public function setData(array $data){
154
-            $this->logger->debug('Setting the form validation data, the values are: ' . stringfy_vars($data));
155
-            $this->data = $data;
151
+		 * @return FormValidation Current instance of object.
152
+		 */
153
+		public function setData(array $data){
154
+			$this->logger->debug('Setting the form validation data, the values are: ' . stringfy_vars($data));
155
+			$this->data = $data;
156 156
 			return $this;
157
-        }
158
-
159
-        /**
160
-         * Get the form validation data
161
-         * @return array the form validation data to be validated
162
-         */
163
-        public function getData(){
164
-            return $this->data;
165
-        }
166
-
167
-		/**
168
-		* Get the validation function name to validate a rule
169
-		*
170
-		* @return string the function name
171
-		*/
172
-        protected function _toCallCase($funcName, $prefix='_validate') {
173
-            $funcName = strtolower($funcName);
174
-            $finalFuncName = $prefix;
175
-            foreach (explode('_', $funcName) as $funcNamePart) {
176
-                $finalFuncName .= strtoupper($funcNamePart[0]) . substr($funcNamePart, 1);
177
-            }
178
-            return $finalFuncName;
179
-        }
180
-
181
-        /**
182
-         * Returns the boolean of the data status success. It goes by the simple
183
-         *
184
-         * @return boolean Whether or not the data validation has succeeded
185
-         */
186
-        public function isSuccess() {
187
-            return $this->_success;
188
-        }
189
-
190
-        /**
191
-         * Checks if the request method is POST or the Data to be validated is set
192
-         *
193
-         * @return boolean Whether or not the form has been submitted or the data is available for validation.
194
-         */
195
-        public function canDoValidation() {
196
-            return get_instance()->request->method() === 'POST' || ! empty($this->data);
197
-        }
198
-
199
-        /**
200
-         * Runs _run once POST data has been submitted or data is set manually.
201
-         *
202
-         * @return boolean
203
-         */
204
-        public function run() {
205
-            if ($this->canDoValidation()) {
206
-                $this->logger->info('The data to validate are listed below: ' . stringfy_vars($this->getData()));
207
-                $this->_run();
208
-            }
209
-            return $this->isSuccess();
210
-        }
211
-
212
-        /**
213
-         * Takes and trims each data, if it has any rules, we parse the rule string and run
214
-         * each rule against the data value. Sets _success to true if there are no errors
215
-         * afterwards.
216
-         */
217
-        protected function _run() {
218
-            if(get_instance()->request->method() == 'POST' || $this->enableCsrfCheck){
219
-                $this->logger->debug('Check if CSRF is enabled in configuration');
220
-                //first check for CSRF
221
-                if ((get_config('csrf_enable', false) || $this->enableCsrfCheck) && ! Security::validateCSRF()){
222
-                    show_error('Invalide data, Cross Site Request Forgery do his job, the data to validate is corrupted.');
223
-                }
224
-                else{
225
-                    $this->logger->info('CSRF is not enabled in configuration or not set manully, no need to check it');
226
-                }
227
-            }
228
-            /////////////////////////////////////////////
229
-            $this->_forceFail = false;
230
-
231
-            foreach ($this->getData() as $inputName => $inputVal) {
232
-    			if(is_array($this->data[$inputName])){
233
-    				$this->data[$inputName] = array_map('trim', $this->data[$inputName]);
234
-    			}
235
-    			else{
236
-    				$this->data[$inputName] = trim($this->data[$inputName]);
237
-    			}
238
-
239
-                if (array_key_exists($inputName, $this->_rules)) {
240
-                    foreach ($this->_parseRuleString($this->_rules[$inputName]) as $eachRule) {
241
-                        $this->_validateRule($inputName, $this->data[$inputName], $eachRule);
242
-                    }
243
-                }
244
-            }
245
-
246
-            if (empty($this->_errors) && $this->_forceFail === false) {
247
-                $this->_success = true;
248
-            }
249
-        }
250
-
251
-        /**
252
-         * Adds a rule to a form data validation field.
253
-         *
254
-         * @param string $inputField Name of the field or the data key to add a rule to
255
-         * @param string $ruleSets PIPE seperated string of rules
256
-		 *
257
-         * @return FormValidation Current instance of object.
258
-         */
259
-        public function setRule($inputField, $inputLabel, $ruleSets) {
260
-            $this->_rules[$inputField] = $ruleSets;
261
-            $this->_labels[$inputField] = $inputLabel;
262
-            $this->logger->info('Set the field rule: name [' .$inputField. '], label [' .$inputLabel. '], rules [' .$ruleSets. ']');
263
-            return $this;
264
-        }
265
-
266
-        /**
267
-         * Takes an array of rules and uses setRule() to set them, accepts an array
268
-         * of rule names rather than a pipe-delimited string as well.
269
-         * @param array $ruleSets
157
+		}
158
+
159
+		/**
160
+		 * Get the form validation data
161
+		 * @return array the form validation data to be validated
162
+		 */
163
+		public function getData(){
164
+			return $this->data;
165
+		}
166
+
167
+		/**
168
+		 * Get the validation function name to validate a rule
169
+		 *
170
+		 * @return string the function name
171
+		 */
172
+		protected function _toCallCase($funcName, $prefix='_validate') {
173
+			$funcName = strtolower($funcName);
174
+			$finalFuncName = $prefix;
175
+			foreach (explode('_', $funcName) as $funcNamePart) {
176
+				$finalFuncName .= strtoupper($funcNamePart[0]) . substr($funcNamePart, 1);
177
+			}
178
+			return $finalFuncName;
179
+		}
180
+
181
+		/**
182
+		 * Returns the boolean of the data status success. It goes by the simple
183
+		 *
184
+		 * @return boolean Whether or not the data validation has succeeded
185
+		 */
186
+		public function isSuccess() {
187
+			return $this->_success;
188
+		}
189
+
190
+		/**
191
+		 * Checks if the request method is POST or the Data to be validated is set
192
+		 *
193
+		 * @return boolean Whether or not the form has been submitted or the data is available for validation.
194
+		 */
195
+		public function canDoValidation() {
196
+			return get_instance()->request->method() === 'POST' || ! empty($this->data);
197
+		}
198
+
199
+		/**
200
+		 * Runs _run once POST data has been submitted or data is set manually.
201
+		 *
202
+		 * @return boolean
203
+		 */
204
+		public function run() {
205
+			if ($this->canDoValidation()) {
206
+				$this->logger->info('The data to validate are listed below: ' . stringfy_vars($this->getData()));
207
+				$this->_run();
208
+			}
209
+			return $this->isSuccess();
210
+		}
211
+
212
+		/**
213
+		 * Takes and trims each data, if it has any rules, we parse the rule string and run
214
+		 * each rule against the data value. Sets _success to true if there are no errors
215
+		 * afterwards.
216
+		 */
217
+		protected function _run() {
218
+			if(get_instance()->request->method() == 'POST' || $this->enableCsrfCheck){
219
+				$this->logger->debug('Check if CSRF is enabled in configuration');
220
+				//first check for CSRF
221
+				if ((get_config('csrf_enable', false) || $this->enableCsrfCheck) && ! Security::validateCSRF()){
222
+					show_error('Invalide data, Cross Site Request Forgery do his job, the data to validate is corrupted.');
223
+				}
224
+				else{
225
+					$this->logger->info('CSRF is not enabled in configuration or not set manully, no need to check it');
226
+				}
227
+			}
228
+			/////////////////////////////////////////////
229
+			$this->_forceFail = false;
230
+
231
+			foreach ($this->getData() as $inputName => $inputVal) {
232
+				if(is_array($this->data[$inputName])){
233
+					$this->data[$inputName] = array_map('trim', $this->data[$inputName]);
234
+				}
235
+				else{
236
+					$this->data[$inputName] = trim($this->data[$inputName]);
237
+				}
238
+
239
+				if (array_key_exists($inputName, $this->_rules)) {
240
+					foreach ($this->_parseRuleString($this->_rules[$inputName]) as $eachRule) {
241
+						$this->_validateRule($inputName, $this->data[$inputName], $eachRule);
242
+					}
243
+				}
244
+			}
245
+
246
+			if (empty($this->_errors) && $this->_forceFail === false) {
247
+				$this->_success = true;
248
+			}
249
+		}
250
+
251
+		/**
252
+		 * Adds a rule to a form data validation field.
253
+		 *
254
+		 * @param string $inputField Name of the field or the data key to add a rule to
255
+		 * @param string $ruleSets PIPE seperated string of rules
270 256
 		 *
271 257
 		 * @return FormValidation Current instance of object.
272
-         */
273
-        public function setRules(array $ruleSets) {
274
-            foreach ($ruleSets as $ruleSet) {
275
-                $pipeDelimitedRules = null;
276
-                if (is_array($ruleSet['rules'])) {
277
-                    $pipeDelimitedRules = implode('|', $ruleSet['rules']);
278
-                } else {
279
-                    $pipeDelimitedRules = $ruleSet['rules'];
280
-                }
281
-                $this->setRule($ruleSet['name'], $ruleSet['label'], $pipeDelimitedRules);
282
-            }
283
-            return $this;
284
-        }
285
-
286
-        /**
287
-         * This method creates the global errors delimiter, each argument occurs once, at the beginning, and
288
-         * end of the errors block respectively.
289
-         *
290
-         * @param string $start Before block of errors gets displayed, HTML allowed.
291
-         * @param string $end After the block of errors gets displayed, HTML allowed.
292
-         *
258
+		 */
259
+		public function setRule($inputField, $inputLabel, $ruleSets) {
260
+			$this->_rules[$inputField] = $ruleSets;
261
+			$this->_labels[$inputField] = $inputLabel;
262
+			$this->logger->info('Set the field rule: name [' .$inputField. '], label [' .$inputLabel. '], rules [' .$ruleSets. ']');
263
+			return $this;
264
+		}
265
+
266
+		/**
267
+		 * Takes an array of rules and uses setRule() to set them, accepts an array
268
+		 * of rule names rather than a pipe-delimited string as well.
269
+		 * @param array $ruleSets
270
+		 *
293 271
 		 * @return FormValidation Current instance of object.
294
-         */
295
-        public function setErrorsDelimiter($start, $end) {
296
-            $this->_allErrorsDelimiter[0] = $start;
297
-            $this->_allErrorsDelimiter[1] = $end;
298
-            return $this;
299
-        }
300
-
301
-        /**
302
-         * This is the individual error delimiter, each argument occurs once before and after
303
-         * each individual error listed.
304
-         *
305
-         * @param string $start Displayed before each error.
306
-         * @param string $end Displayed after each error.
307
-         * 
272
+		 */
273
+		public function setRules(array $ruleSets) {
274
+			foreach ($ruleSets as $ruleSet) {
275
+				$pipeDelimitedRules = null;
276
+				if (is_array($ruleSet['rules'])) {
277
+					$pipeDelimitedRules = implode('|', $ruleSet['rules']);
278
+				} else {
279
+					$pipeDelimitedRules = $ruleSet['rules'];
280
+				}
281
+				$this->setRule($ruleSet['name'], $ruleSet['label'], $pipeDelimitedRules);
282
+			}
283
+			return $this;
284
+		}
285
+
286
+		/**
287
+		 * This method creates the global errors delimiter, each argument occurs once, at the beginning, and
288
+		 * end of the errors block respectively.
289
+		 *
290
+		 * @param string $start Before block of errors gets displayed, HTML allowed.
291
+		 * @param string $end After the block of errors gets displayed, HTML allowed.
292
+		 *
308 293
 		 * @return FormValidation Current instance of object.
309
-         */
310
-        public function setErrorDelimiter($start, $end) {
311
-            $this->_eachErrorDelimiter[0] = $start;
312
-            $this->_eachErrorDelimiter[1] = $end;
313
-            return $this;
314
-        }
315
-
316
-		/**
317
-		* Get the each errors delimiters
318
-		*
319
-		* @return array
320
-		*/
321
-    	public function getErrorDelimiter() {
322
-            return $this->_eachErrorDelimiter;
323
-        }
324
-
325
-		/**
326
-		* Get the all errors delimiters
327
-		*
328
-		* @return array
329
-		*/
330
-    	public function getErrorsDelimiter() {
331
-            return $this->_allErrorsDelimiter;
332
-        }
333
-
334
-        /**
335
-         * This sets a custom error message that can override the default error phrase provided
336
-         * by FormValidation, it can be used in the format of setMessage('rule', 'error phrase')
337
-         * which will globally change the error phrase of that rule, or in the format of:
338
-         * setMessage('rule', 'fieldname', 'error phrase') - which will only change the error phrase for
339
-         * that rule, applied on that field.
340
-         *
341
-         * @return boolean True on success, false on failure.
342
-         */
343
-        public function setMessage() {
344
-            $numArgs = func_num_args();
345
-            switch ($numArgs) {
346
-                default:
347
-                    return false;
348
-                // A global rule error message
349
-                case 2:
350
-                    foreach ($this->post(null) as $key => $val) {
351
-                        $this->_errorPhraseOverrides[$key][func_get_arg(0)] = func_get_arg(1);
352
-                    }
353
-                    break;
354
-                // Field specific rule error message
355
-                case 3:
356
-                    $this->_errorPhraseOverrides[func_get_arg(1)][func_get_arg(0)] = func_get_arg(2);
357
-                    break;
358
-            }
359
-            return true;
360
-        }
361
-
362
-        /**
363
-         * Adds a custom error message in the errorSet array, that will
364
-         * forcibly display it.
365
-         *
366
-         * @param string $inputName The form input name or data key
367
-         * @param string $errorMessage Error to display
368
-		 *
369
-         * @return formValidation Current instance of the object
370
-         */
371
-        public function setCustomError($inputName, $errorMessage) {
372
-            $errorMessage = str_replace('%1', $this->_labels[$inputName], $errorMessage);
373
-            $this->_errors[$inputName] = $errorMessage;
374
-            return $this;
375
-        }
376
-
377
-        /**
378
-         * Allows for an accesor to any/all post values, if a value of null is passed as the key, it
379
-         * will recursively find all keys/values of the $_POST array or data array. It also automatically trims
380
-         * all values.
381
-         *
382
-         * @param string $key Key of $this->data to be found, pass null for all Key => Val pairs.
383
-         * @param boolean $trim Defaults to true, trims all $this->data values.
384
-         * @return string|array Array of post or data values if null is passed as key, string if only one key is desired.
385
-         */
386
-        public function post($key = null, $trim = true) {
387
-            $returnValue = null;
388
-            if (is_null($key)) {
389
-                $returnValue = array();
390
-                foreach ($this->getData()  as $key => $val) {
391
-                    $returnValue[$key] = $this->post($key, $trim);
392
-                }
393
-            } else {
394
-                $returnValue = (array_key_exists($key, $this->getData())) ? (($trim) ? trim($this->data[$key]) : $this->data[$key]) : null;
395
-            }
396
-            return $returnValue;
397
-        }
398
-
399
-        /**
400
-         * Gets all errors from errorSet and displays them, can be echo out from the
401
-         * function or just returned.
402
-         *
403
-         * @param boolean $limit number of error to display or return
404
-         * @param boolean $echo Whether or not the values are to be returned or displayed
405
-		 *
406
-         * @return string Errors formatted for output
407
-         */
408
-        public function displayErrors($limit = null, $echo = true) {
409
-            list($errorsStart, $errorsEnd) = $this->_allErrorsDelimiter;
410
-            list($errorStart, $errorEnd) = $this->_eachErrorDelimiter;
411
-            $errorOutput = $errorsStart;
412
-    		$i = 0;
413
-            if (!empty($this->_errors)) {
414
-                foreach ($this->_errors as $fieldName => $error) {
415
-        	    	if ($i === $limit) { 
416
-                        break; 
417
-                    }
418
-                    $errorOutput .= $errorStart;
419
-                    $errorOutput .= $error;
420
-                    $errorOutput .= $errorEnd;
421
-                    $i++;
422
-                }
423
-            }
424
-            $errorOutput .= $errorsEnd;
425
-            echo ($echo) ? $errorOutput : '';
426
-            return (! $echo) ? $errorOutput : null;
427
-        }
428
-
429
-        /**
430
-         * Returns raw array of errors in no format instead of displaying them
431
-         * formatted.
432
-         *
433
-         * @return array
434
-         */
435
-        public function returnErrors() {
436
-            return $this->_errors;
437
-        }
438
-
439
-        /**
440
-         * Breaks up a PIPE seperated string of rules, and puts them into an array.
441
-         *
442
-         * @param string $ruleString String to be parsed.
443
-		 *
444
-         * @return array Array of each value in original string.
445
-         */
446
-        protected function _parseRuleString($ruleString) {
447
-            $ruleSets = array();
448
-            /*
294
+		 */
295
+		public function setErrorsDelimiter($start, $end) {
296
+			$this->_allErrorsDelimiter[0] = $start;
297
+			$this->_allErrorsDelimiter[1] = $end;
298
+			return $this;
299
+		}
300
+
301
+		/**
302
+		 * This is the individual error delimiter, each argument occurs once before and after
303
+		 * each individual error listed.
304
+		 *
305
+		 * @param string $start Displayed before each error.
306
+		 * @param string $end Displayed after each error.
307
+		 * 
308
+		 * @return FormValidation Current instance of object.
309
+		 */
310
+		public function setErrorDelimiter($start, $end) {
311
+			$this->_eachErrorDelimiter[0] = $start;
312
+			$this->_eachErrorDelimiter[1] = $end;
313
+			return $this;
314
+		}
315
+
316
+		/**
317
+		 * Get the each errors delimiters
318
+		 *
319
+		 * @return array
320
+		 */
321
+		public function getErrorDelimiter() {
322
+			return $this->_eachErrorDelimiter;
323
+		}
324
+
325
+		/**
326
+		 * Get the all errors delimiters
327
+		 *
328
+		 * @return array
329
+		 */
330
+		public function getErrorsDelimiter() {
331
+			return $this->_allErrorsDelimiter;
332
+		}
333
+
334
+		/**
335
+		 * This sets a custom error message that can override the default error phrase provided
336
+		 * by FormValidation, it can be used in the format of setMessage('rule', 'error phrase')
337
+		 * which will globally change the error phrase of that rule, or in the format of:
338
+		 * setMessage('rule', 'fieldname', 'error phrase') - which will only change the error phrase for
339
+		 * that rule, applied on that field.
340
+		 *
341
+		 * @return boolean True on success, false on failure.
342
+		 */
343
+		public function setMessage() {
344
+			$numArgs = func_num_args();
345
+			switch ($numArgs) {
346
+				default:
347
+					return false;
348
+				// A global rule error message
349
+				case 2:
350
+					foreach ($this->post(null) as $key => $val) {
351
+						$this->_errorPhraseOverrides[$key][func_get_arg(0)] = func_get_arg(1);
352
+					}
353
+					break;
354
+				// Field specific rule error message
355
+				case 3:
356
+					$this->_errorPhraseOverrides[func_get_arg(1)][func_get_arg(0)] = func_get_arg(2);
357
+					break;
358
+			}
359
+			return true;
360
+		}
361
+
362
+		/**
363
+		 * Adds a custom error message in the errorSet array, that will
364
+		 * forcibly display it.
365
+		 *
366
+		 * @param string $inputName The form input name or data key
367
+		 * @param string $errorMessage Error to display
368
+		 *
369
+		 * @return formValidation Current instance of the object
370
+		 */
371
+		public function setCustomError($inputName, $errorMessage) {
372
+			$errorMessage = str_replace('%1', $this->_labels[$inputName], $errorMessage);
373
+			$this->_errors[$inputName] = $errorMessage;
374
+			return $this;
375
+		}
376
+
377
+		/**
378
+		 * Allows for an accesor to any/all post values, if a value of null is passed as the key, it
379
+		 * will recursively find all keys/values of the $_POST array or data array. It also automatically trims
380
+		 * all values.
381
+		 *
382
+		 * @param string $key Key of $this->data to be found, pass null for all Key => Val pairs.
383
+		 * @param boolean $trim Defaults to true, trims all $this->data values.
384
+		 * @return string|array Array of post or data values if null is passed as key, string if only one key is desired.
385
+		 */
386
+		public function post($key = null, $trim = true) {
387
+			$returnValue = null;
388
+			if (is_null($key)) {
389
+				$returnValue = array();
390
+				foreach ($this->getData()  as $key => $val) {
391
+					$returnValue[$key] = $this->post($key, $trim);
392
+				}
393
+			} else {
394
+				$returnValue = (array_key_exists($key, $this->getData())) ? (($trim) ? trim($this->data[$key]) : $this->data[$key]) : null;
395
+			}
396
+			return $returnValue;
397
+		}
398
+
399
+		/**
400
+		 * Gets all errors from errorSet and displays them, can be echo out from the
401
+		 * function or just returned.
402
+		 *
403
+		 * @param boolean $limit number of error to display or return
404
+		 * @param boolean $echo Whether or not the values are to be returned or displayed
405
+		 *
406
+		 * @return string Errors formatted for output
407
+		 */
408
+		public function displayErrors($limit = null, $echo = true) {
409
+			list($errorsStart, $errorsEnd) = $this->_allErrorsDelimiter;
410
+			list($errorStart, $errorEnd) = $this->_eachErrorDelimiter;
411
+			$errorOutput = $errorsStart;
412
+			$i = 0;
413
+			if (!empty($this->_errors)) {
414
+				foreach ($this->_errors as $fieldName => $error) {
415
+					if ($i === $limit) { 
416
+						break; 
417
+					}
418
+					$errorOutput .= $errorStart;
419
+					$errorOutput .= $error;
420
+					$errorOutput .= $errorEnd;
421
+					$i++;
422
+				}
423
+			}
424
+			$errorOutput .= $errorsEnd;
425
+			echo ($echo) ? $errorOutput : '';
426
+			return (! $echo) ? $errorOutput : null;
427
+		}
428
+
429
+		/**
430
+		 * Returns raw array of errors in no format instead of displaying them
431
+		 * formatted.
432
+		 *
433
+		 * @return array
434
+		 */
435
+		public function returnErrors() {
436
+			return $this->_errors;
437
+		}
438
+
439
+		/**
440
+		 * Breaks up a PIPE seperated string of rules, and puts them into an array.
441
+		 *
442
+		 * @param string $ruleString String to be parsed.
443
+		 *
444
+		 * @return array Array of each value in original string.
445
+		 */
446
+		protected function _parseRuleString($ruleString) {
447
+			$ruleSets = array();
448
+			/*
449 449
             //////////////// hack for regex rule that can contain "|"
450 450
             */
451
-            if(strpos($ruleString, 'regex') !== false){
452
-                $regexRule = array();
453
-                $rule = '#regex\[\/(.*)\/([a-zA-Z0-9]?)\]#';
454
-                preg_match($rule, $ruleString, $regexRule);
455
-                $ruleStringTemp = preg_replace($rule, '', $ruleString);
456
-                 if(!empty($regexRule[0])){
457
-                     $ruleSets[] = $regexRule[0];
458
-                 }
459
-                 $ruleStringRegex = explode('|', $ruleStringTemp);
460
-                foreach ($ruleStringRegex as $rule) {
461
-                    $rule = trim($rule);
462
-                    if($rule){
463
-                        $ruleSets[] = $rule;
464
-                    }
465
-                }
451
+			if(strpos($ruleString, 'regex') !== false){
452
+				$regexRule = array();
453
+				$rule = '#regex\[\/(.*)\/([a-zA-Z0-9]?)\]#';
454
+				preg_match($rule, $ruleString, $regexRule);
455
+				$ruleStringTemp = preg_replace($rule, '', $ruleString);
456
+				 if(!empty($regexRule[0])){
457
+					 $ruleSets[] = $regexRule[0];
458
+				 }
459
+				 $ruleStringRegex = explode('|', $ruleStringTemp);
460
+				foreach ($ruleStringRegex as $rule) {
461
+					$rule = trim($rule);
462
+					if($rule){
463
+						$ruleSets[] = $rule;
464
+					}
465
+				}
466 466
                  
467
-            }
468
-            /***********************************/
469
-            else{
470
-                if (strpos($ruleString, '|') !== FALSE) {
471
-                    $ruleSets = explode('|', $ruleString);
472
-                } else {
473
-                    $ruleSets[] = $ruleString;
474
-                }
475
-             }
476
-            return $ruleSets;
477
-        }
478
-
479
-        /**
480
-         * Returns whether or not a field obtains the rule "required".
481
-         *
482
-         * @param string $fieldName Field to check if required.
483
-		 *
484
-         * @return boolean Whether or not the field is required.
485
-         */
486
-        protected function _fieldIsRequired($fieldName) {
487
-            $rules = $this->_parseRuleString($this->_rules[$fieldName]);
488
-            return (in_array('required', $rules));
489
-        }
490
-
491
-        /**
492
-         * Takes a data input name, it's value, and the rule it's being validated against (ex: max_length[16])
493
-         * and adds an error to the errorSet if it fails validation of the rule.
494
-         *
495
-         * @param string $inputName Name or key of the validation data
496
-         * @param string $inputVal Value of the validation data
497
-         * @param string $ruleName Rule to be validated against, including args (exact_length[5])
498
-         * @return void
499
-         */
500
-        protected function _validateRule($inputName, $inputVal, $ruleName) {
501
-            $this->logger->debug('Rule validation of field [' .$inputName. '], value [' .$inputVal. '], rule [' .$ruleName. ']');
502
-            // Array to store args
503
-            $ruleArgs = array();
504
-
505
-            preg_match('/\[(.*)\]/', $ruleName, $ruleArgs);
506
-
507
-            // Get the rule arguments, realRule is just the base rule name
508
-            // Like min_length instead of min_length[3]
509
-            $ruleName = preg_replace('/\[(.*)\]/', '', $ruleName);
467
+			}
468
+			/***********************************/
469
+			else{
470
+				if (strpos($ruleString, '|') !== FALSE) {
471
+					$ruleSets = explode('|', $ruleString);
472
+				} else {
473
+					$ruleSets[] = $ruleString;
474
+				}
475
+			 }
476
+			return $ruleSets;
477
+		}
478
+
479
+		/**
480
+		 * Returns whether or not a field obtains the rule "required".
481
+		 *
482
+		 * @param string $fieldName Field to check if required.
483
+		 *
484
+		 * @return boolean Whether or not the field is required.
485
+		 */
486
+		protected function _fieldIsRequired($fieldName) {
487
+			$rules = $this->_parseRuleString($this->_rules[$fieldName]);
488
+			return (in_array('required', $rules));
489
+		}
490
+
491
+		/**
492
+		 * Takes a data input name, it's value, and the rule it's being validated against (ex: max_length[16])
493
+		 * and adds an error to the errorSet if it fails validation of the rule.
494
+		 *
495
+		 * @param string $inputName Name or key of the validation data
496
+		 * @param string $inputVal Value of the validation data
497
+		 * @param string $ruleName Rule to be validated against, including args (exact_length[5])
498
+		 * @return void
499
+		 */
500
+		protected function _validateRule($inputName, $inputVal, $ruleName) {
501
+			$this->logger->debug('Rule validation of field [' .$inputName. '], value [' .$inputVal. '], rule [' .$ruleName. ']');
502
+			// Array to store args
503
+			$ruleArgs = array();
504
+
505
+			preg_match('/\[(.*)\]/', $ruleName, $ruleArgs);
506
+
507
+			// Get the rule arguments, realRule is just the base rule name
508
+			// Like min_length instead of min_length[3]
509
+			$ruleName = preg_replace('/\[(.*)\]/', '', $ruleName);
510 510
             
511
-            if (method_exists($this, $this->_toCallCase($ruleName))) {
512
-                $methodToCall = $this->_toCallCase($ruleName);
513
-                call_user_func(array($this, $methodToCall), $inputName, $ruleName, $ruleArgs);
514
-            }
515
-            return;
516
-        }
517
-
518
-		/**
519
-		* Set error for the given field or key
520
-		*
521
-		* @param string $inputName the input or key name
522
-		* @param string $ruleName the rule name
523
-		* @param array|string $replacements
524
-		*/
525
-        protected function _setError($inputName, $ruleName, $replacements = array()) {
526
-            $rulePhraseKeyParts = explode(',', $ruleName);
527
-            $rulePhrase = null;
528
-            foreach ($rulePhraseKeyParts as $rulePhraseKeyPart) {
529
-                if (array_key_exists($rulePhraseKeyPart, $this->_errorsMessages)) {
530
-                    $rulePhrase = $this->_errorsMessages[$rulePhraseKeyPart];
531
-                } else {
532
-                    $rulePhrase = $rulePhrase[$rulePhraseKeyPart];
533
-                }
534
-            }
535
-            // Any overrides?
536
-            if (array_key_exists($inputName, $this->_errorPhraseOverrides) && array_key_exists($ruleName, $this->_errorPhraseOverrides[$inputName])) {
537
-                $rulePhrase = $this->_errorPhraseOverrides[$inputName][$ruleName];
538
-            }
539
-            // Type cast to array in case it's a string
540
-            $replacements = (array) $replacements;
511
+			if (method_exists($this, $this->_toCallCase($ruleName))) {
512
+				$methodToCall = $this->_toCallCase($ruleName);
513
+				call_user_func(array($this, $methodToCall), $inputName, $ruleName, $ruleArgs);
514
+			}
515
+			return;
516
+		}
517
+
518
+		/**
519
+		 * Set error for the given field or key
520
+		 *
521
+		 * @param string $inputName the input or key name
522
+		 * @param string $ruleName the rule name
523
+		 * @param array|string $replacements
524
+		 */
525
+		protected function _setError($inputName, $ruleName, $replacements = array()) {
526
+			$rulePhraseKeyParts = explode(',', $ruleName);
527
+			$rulePhrase = null;
528
+			foreach ($rulePhraseKeyParts as $rulePhraseKeyPart) {
529
+				if (array_key_exists($rulePhraseKeyPart, $this->_errorsMessages)) {
530
+					$rulePhrase = $this->_errorsMessages[$rulePhraseKeyPart];
531
+				} else {
532
+					$rulePhrase = $rulePhrase[$rulePhraseKeyPart];
533
+				}
534
+			}
535
+			// Any overrides?
536
+			if (array_key_exists($inputName, $this->_errorPhraseOverrides) && array_key_exists($ruleName, $this->_errorPhraseOverrides[$inputName])) {
537
+				$rulePhrase = $this->_errorPhraseOverrides[$inputName][$ruleName];
538
+			}
539
+			// Type cast to array in case it's a string
540
+			$replacements = (array) $replacements;
541 541
 			$replacementCount = count($replacements);
542
-            for ($i = 1; $i <= $replacementCount; $i++) {
543
-                $key = $i - 1;
544
-                $rulePhrase = str_replace('%' . $i, $replacements[$key], $rulePhrase);
545
-            }
546
-            if (! array_key_exists($inputName, $this->_errors)) {
547
-                $this->_errors[$inputName] = $rulePhrase;
548
-            }
549
-        }
550
-
551
-        /**
552
-         * Used to run a callback for the callback rule, as well as pass in a default
553
-         * argument of the post value. For example the username field having a rule:
554
-         * callback[userExists] will eval userExists(data[username]) - Note the use
555
-         * of eval over call_user_func is in case the function is not user defined.
556
-         *
557
-         * @param type $inputArg
558
-         * @param string $callbackFunc
559
-		 *
560
-         * @return mixed
561
-         */
562
-        protected function _runCallback($inputArg, $callbackFunc) {
542
+			for ($i = 1; $i <= $replacementCount; $i++) {
543
+				$key = $i - 1;
544
+				$rulePhrase = str_replace('%' . $i, $replacements[$key], $rulePhrase);
545
+			}
546
+			if (! array_key_exists($inputName, $this->_errors)) {
547
+				$this->_errors[$inputName] = $rulePhrase;
548
+			}
549
+		}
550
+
551
+		/**
552
+		 * Used to run a callback for the callback rule, as well as pass in a default
553
+		 * argument of the post value. For example the username field having a rule:
554
+		 * callback[userExists] will eval userExists(data[username]) - Note the use
555
+		 * of eval over call_user_func is in case the function is not user defined.
556
+		 *
557
+		 * @param type $inputArg
558
+		 * @param string $callbackFunc
559
+		 *
560
+		 * @return mixed
561
+		 */
562
+		protected function _runCallback($inputArg, $callbackFunc) {
563 563
 			return eval('return ' . $callbackFunc . '("' . $inputArg . '");');
564
-        }
565
-
566
-        /**
567
-         * Used for applying a rule only if the empty callback evaluates to true,
568
-         * for example required[funcName] - This runs funcName without passing any
569
-         * arguments.
570
-         *
571
-         * @param string $callbackFunc
572
-		 *
573
-         * @return anything
574
-         */
575
-        protected function _runEmptyCallback($callbackFunc) {
576
-            return eval('return ' . $callbackFunc . '();');
577
-        }
578
-
579
-        /**
580
-         * Gets a specific label of a specific field input name.
581
-         *
582
-         * @param string $inputName
583
-		 *
584
-         * @return string
585
-         */
586
-        protected function _getLabel($inputName) {
587
-            return (array_key_exists($inputName, $this->_labels)) ? $this->_labels[$inputName] : $inputName;
588
-        }
564
+		}
565
+
566
+		/**
567
+		 * Used for applying a rule only if the empty callback evaluates to true,
568
+		 * for example required[funcName] - This runs funcName without passing any
569
+		 * arguments.
570
+		 *
571
+		 * @param string $callbackFunc
572
+		 *
573
+		 * @return anything
574
+		 */
575
+		protected function _runEmptyCallback($callbackFunc) {
576
+			return eval('return ' . $callbackFunc . '();');
577
+		}
578
+
579
+		/**
580
+		 * Gets a specific label of a specific field input name.
581
+		 *
582
+		 * @param string $inputName
583
+		 *
584
+		 * @return string
585
+		 */
586
+		protected function _getLabel($inputName) {
587
+			return (array_key_exists($inputName, $this->_labels)) ? $this->_labels[$inputName] : $inputName;
588
+		}
589 589
 		
590
-        /**
591
-         * Peform validation for the rule "required"
592
-         * @param  string $inputName the form field or data key name used
593
-         * @param  string $ruleName  the rule name for this validation ("required")
594
-         * @param  array  $ruleArgs  the rules argument
595
-         */
590
+		/**
591
+		 * Peform validation for the rule "required"
592
+		 * @param  string $inputName the form field or data key name used
593
+		 * @param  string $ruleName  the rule name for this validation ("required")
594
+		 * @param  array  $ruleArgs  the rules argument
595
+		 */
596 596
 		protected function _validateRequired($inputName, $ruleName, array $ruleArgs) {
597
-            $inputVal = $this->post($inputName);
598
-            if(array_key_exists(1, $ruleArgs) && function_exists($ruleArgs[1])) {
599
-                $callbackReturn = $this->_runEmptyCallback($ruleArgs[1]);
600
-                if ($inputVal == '' && $callbackReturn == true) {
601
-                    $this->_setError($inputName, $ruleName, $this->_getLabel($inputName));
602
-                }
603
-            } 
597
+			$inputVal = $this->post($inputName);
598
+			if(array_key_exists(1, $ruleArgs) && function_exists($ruleArgs[1])) {
599
+				$callbackReturn = $this->_runEmptyCallback($ruleArgs[1]);
600
+				if ($inputVal == '' && $callbackReturn == true) {
601
+					$this->_setError($inputName, $ruleName, $this->_getLabel($inputName));
602
+				}
603
+			} 
604 604
 			else if($inputVal == '') {
605 605
 				$this->_setError($inputName, $ruleName, $this->_getLabel($inputName));
606
-            }
607
-        }
608
-
609
-        /**
610
-         * Perform validation for the honey pot so means for the validation to be failed
611
-         * @param  string $inputName the form field or data key name used
612
-         * @param  string $ruleName  the rule name for this validation
613
-         * @param  array  $ruleArgs  the rules argument
614
-         */
615
-        protected function _validateHoneypot($inputName, $ruleName, array $ruleArgs) {
616
-            if ($this->data[$inputName] != '') {
617
-                $this->_forceFail = true;
618
-            }
619
-        }
620
-
621
-        /**
622
-         * Peform validation for the rule "callback"
623
-         * @param  string $inputName the form field or data key name used
624
-         * @param  string $ruleName  the rule name for this validation ("callback")
625
-         * @param  array  $ruleArgs  the rules argument
626
-         */
627
-        protected function _validateCallback($inputName, $ruleName, array $ruleArgs) {
628
-            if (function_exists($ruleArgs[1]) && !empty($this->data[$inputName])) {
606
+			}
607
+		}
608
+
609
+		/**
610
+		 * Perform validation for the honey pot so means for the validation to be failed
611
+		 * @param  string $inputName the form field or data key name used
612
+		 * @param  string $ruleName  the rule name for this validation
613
+		 * @param  array  $ruleArgs  the rules argument
614
+		 */
615
+		protected function _validateHoneypot($inputName, $ruleName, array $ruleArgs) {
616
+			if ($this->data[$inputName] != '') {
617
+				$this->_forceFail = true;
618
+			}
619
+		}
620
+
621
+		/**
622
+		 * Peform validation for the rule "callback"
623
+		 * @param  string $inputName the form field or data key name used
624
+		 * @param  string $ruleName  the rule name for this validation ("callback")
625
+		 * @param  array  $ruleArgs  the rules argument
626
+		 */
627
+		protected function _validateCallback($inputName, $ruleName, array $ruleArgs) {
628
+			if (function_exists($ruleArgs[1]) && !empty($this->data[$inputName])) {
629 629
 				$result = $this->_runCallback($this->data[$inputName], $ruleArgs[1]);
630 630
 				if(! $result){
631 631
 					$this->_setError($inputName, $ruleName, array($this->_getLabel($inputName)));
632 632
 				}
633
-            }
634
-        }
635
-
636
-        /**
637
-         * Peform validation for the rule "depends"
638
-         * @param  string $inputName the form field or data key name used
639
-         * @param  string $ruleName  the rule name for this validation ("depends")
640
-         * @param  array  $ruleArgs  the rules argument
641
-         */
642
-        protected function _validateDepends($inputName, $ruleName, array $ruleArgs) {
643
-            if (array_key_exists($ruleArgs[1], $this->_errors)) {
644
-                $this->_setError($inputName, $ruleName, array($this->_getLabel($inputName), $this->_getLabel($ruleArgs[1])));
645
-            }
646
-        }
647
-
648
-        /**
649
-         * Peform validation for the rule "not_equal"
650
-         * @param  string $inputName the form field or data key name used
651
-         * @param  string $ruleName  the rule name for this validation ("not_equal")
652
-         * @param  array  $ruleArgs  the rules argument
653
-         */
654
-        protected function _validateNotEqual($inputName, $ruleName, array $ruleArgs) {
655
-            $canNotEqual = explode(',', $ruleArgs[1]);
656
-            foreach ($canNotEqual as $doNotEqual) {
657
-                $inputVal = $this->post($inputName);
658
-                if (preg_match('/post:(.*)/', $doNotEqual)) {
659
-                    if ($inputVal == $this->data[str_replace('post:', '', $doNotEqual)]) {
660
-                        $this->_setError($inputName, $ruleName . ',post:key', array($this->_getLabel($inputName), $this->_getLabel(str_replace('post:', '', $doNotEqual))));
661
-                        continue;
662
-                    }
663
-                } 
633
+			}
634
+		}
635
+
636
+		/**
637
+		 * Peform validation for the rule "depends"
638
+		 * @param  string $inputName the form field or data key name used
639
+		 * @param  string $ruleName  the rule name for this validation ("depends")
640
+		 * @param  array  $ruleArgs  the rules argument
641
+		 */
642
+		protected function _validateDepends($inputName, $ruleName, array $ruleArgs) {
643
+			if (array_key_exists($ruleArgs[1], $this->_errors)) {
644
+				$this->_setError($inputName, $ruleName, array($this->_getLabel($inputName), $this->_getLabel($ruleArgs[1])));
645
+			}
646
+		}
647
+
648
+		/**
649
+		 * Peform validation for the rule "not_equal"
650
+		 * @param  string $inputName the form field or data key name used
651
+		 * @param  string $ruleName  the rule name for this validation ("not_equal")
652
+		 * @param  array  $ruleArgs  the rules argument
653
+		 */
654
+		protected function _validateNotEqual($inputName, $ruleName, array $ruleArgs) {
655
+			$canNotEqual = explode(',', $ruleArgs[1]);
656
+			foreach ($canNotEqual as $doNotEqual) {
657
+				$inputVal = $this->post($inputName);
658
+				if (preg_match('/post:(.*)/', $doNotEqual)) {
659
+					if ($inputVal == $this->data[str_replace('post:', '', $doNotEqual)]) {
660
+						$this->_setError($inputName, $ruleName . ',post:key', array($this->_getLabel($inputName), $this->_getLabel(str_replace('post:', '', $doNotEqual))));
661
+						continue;
662
+					}
663
+				} 
664 664
 				else{
665
-                    if ($inputVal == $doNotEqual) {
666
-                        $this->_setError($inputName, $ruleName . ',string', array($this->_getLabel($inputName), $doNotEqual));
667
-                        continue;
668
-                    }
669
-                }
670
-            }
671
-        }
672
-
673
-        /**
674
-         * Peform validation for the rule "matches"
675
-         * @param  string $inputName the form field or data key name used
676
-         * @param  string $ruleName  the rule name for this validation ("matches")
677
-         * @param  array  $ruleArgs  the rules argument
678
-         */
679
-        protected function _validateMatches($inputName, $ruleName, array $ruleArgs) {
680
-            $inputVal = $this->post($inputName);
681
-            if ($inputVal != $this->data[$ruleArgs[1]]) {
682
-                $this->_setError($inputName, $ruleName, array($this->_getLabel($inputName), $this->_getLabel($ruleArgs[1])));
683
-            }
684
-        }
685
-
686
-        /**
687
-         * Peform validation for the rule "valid_email"
688
-         * @param  string $inputName the form field or data key name used
689
-         * @param  string $ruleName  the rule name for this validation ("valid_email")
690
-         * @param  array  $ruleArgs  the rules argument
691
-         */
692
-        protected function _validateValidEmail($inputName, $ruleName, array $ruleArgs) {
693
-            $inputVal = $this->post($inputName);
694
-            if (! preg_match("/^([\w\!\#$\%\&\'\*\+\-\/\=\?\^\`{\|\}\~]+\.)*[\w\!\#$\%\&\'\*\+\-\/\=\?\^\`{\|\}\~]+@((((([a-z0-9]{1}[a-z0-9\-]{0,62}[a-z0-9]{1})|[a-z])\.)+[a-z]{2,6})|(\d{1,3}\.){3}\d{1,3}(\:\d{1,5})?)$/i", $inputVal)) {
695
-                if (! $this->_fieldIsRequired($inputName) && empty($this->data[$inputName])) {
696
-                    return;
697
-                }
698
-                $this->_setError($inputName, $ruleName, $this->_getLabel($inputName));
699
-            }
700
-        }
701
-
702
-        /**
703
-         * Peform validation for the rule "exact_length"
704
-         * @param  string $inputName the form field or data key name used
705
-         * @param  string $ruleName  the rule name for this validation ("exact_length")
706
-         * @param  array  $ruleArgs  the rules argument
707
-         */
708
-        protected function _validateExactLength($inputName, $ruleName, array $ruleArgs) {
709
-            $inputVal = $this->post($inputName);
710
-            if (strlen($inputVal) != $ruleArgs[1]) { // $ruleArgs[0] is [length] $rulesArgs[1] is just length
711
-                if (! $this->_fieldIsRequired($inputName) && empty($this->data[$inputName])) {
712
-                    return;
713
-                }
714
-                $this->_setError($inputName, $ruleName, array($this->_getLabel($inputName), $this->_getLabel($ruleArgs[1])));
715
-            }
716
-        }
717
-
718
-        /**
719
-         * Peform validation for the rule "max_length"
720
-         * @param  string $inputName the form field or data key name used
721
-         * @param  string $ruleName  the rule name for this validation ("max_length")
722
-         * @param  array  $ruleArgs  the rules argument
723
-         */
724
-        protected function _validateMaxLength($inputName, $ruleName, array $ruleArgs) {
725
-            $inputVal = $this->post($inputName);
726
-            if (strlen($inputVal) > $ruleArgs[1]) { // $ruleArgs[0] is [length] $rulesArgs[1] is just length
727
-                if (! $this->_fieldIsRequired($inputName) && empty($this->data[$inputName])) {
728
-                    return;
729
-                }
730
-                $this->_setError($inputName, $ruleName, array($this->_getLabel($inputName), $this->_getLabel($ruleArgs[1])));
731
-            }
732
-        }
733
-
734
-        /**
735
-         * Peform validation for the rule "min_length"
736
-         * @param  string $inputName the form field or data key name used
737
-         * @param  string $ruleName  the rule name for this validation ("min_length")
738
-         * @param  array  $ruleArgs  the rules argument
739
-         */
740
-        protected function _validateMinLength($inputName, $ruleName, array $ruleArgs) {
741
-            $inputVal = $this->post($inputName);
742
-            if (strlen($inputVal) < $ruleArgs[1]) { // $ruleArgs[0] is [length] $rulesArgs[1] is just length
743
-                if (! $this->_fieldIsRequired($inputName) && empty($this->data[$inputName])) {
744
-                    return;
745
-                }
746
-                $this->_setError($inputName, $ruleName, array($this->_getLabel($inputName), $this->_getLabel($ruleArgs[1])));
747
-            }
748
-        }
665
+					if ($inputVal == $doNotEqual) {
666
+						$this->_setError($inputName, $ruleName . ',string', array($this->_getLabel($inputName), $doNotEqual));
667
+						continue;
668
+					}
669
+				}
670
+			}
671
+		}
672
+
673
+		/**
674
+		 * Peform validation for the rule "matches"
675
+		 * @param  string $inputName the form field or data key name used
676
+		 * @param  string $ruleName  the rule name for this validation ("matches")
677
+		 * @param  array  $ruleArgs  the rules argument
678
+		 */
679
+		protected function _validateMatches($inputName, $ruleName, array $ruleArgs) {
680
+			$inputVal = $this->post($inputName);
681
+			if ($inputVal != $this->data[$ruleArgs[1]]) {
682
+				$this->_setError($inputName, $ruleName, array($this->_getLabel($inputName), $this->_getLabel($ruleArgs[1])));
683
+			}
684
+		}
685
+
686
+		/**
687
+		 * Peform validation for the rule "valid_email"
688
+		 * @param  string $inputName the form field or data key name used
689
+		 * @param  string $ruleName  the rule name for this validation ("valid_email")
690
+		 * @param  array  $ruleArgs  the rules argument
691
+		 */
692
+		protected function _validateValidEmail($inputName, $ruleName, array $ruleArgs) {
693
+			$inputVal = $this->post($inputName);
694
+			if (! preg_match("/^([\w\!\#$\%\&\'\*\+\-\/\=\?\^\`{\|\}\~]+\.)*[\w\!\#$\%\&\'\*\+\-\/\=\?\^\`{\|\}\~]+@((((([a-z0-9]{1}[a-z0-9\-]{0,62}[a-z0-9]{1})|[a-z])\.)+[a-z]{2,6})|(\d{1,3}\.){3}\d{1,3}(\:\d{1,5})?)$/i", $inputVal)) {
695
+				if (! $this->_fieldIsRequired($inputName) && empty($this->data[$inputName])) {
696
+					return;
697
+				}
698
+				$this->_setError($inputName, $ruleName, $this->_getLabel($inputName));
699
+			}
700
+		}
701
+
702
+		/**
703
+		 * Peform validation for the rule "exact_length"
704
+		 * @param  string $inputName the form field or data key name used
705
+		 * @param  string $ruleName  the rule name for this validation ("exact_length")
706
+		 * @param  array  $ruleArgs  the rules argument
707
+		 */
708
+		protected function _validateExactLength($inputName, $ruleName, array $ruleArgs) {
709
+			$inputVal = $this->post($inputName);
710
+			if (strlen($inputVal) != $ruleArgs[1]) { // $ruleArgs[0] is [length] $rulesArgs[1] is just length
711
+				if (! $this->_fieldIsRequired($inputName) && empty($this->data[$inputName])) {
712
+					return;
713
+				}
714
+				$this->_setError($inputName, $ruleName, array($this->_getLabel($inputName), $this->_getLabel($ruleArgs[1])));
715
+			}
716
+		}
717
+
718
+		/**
719
+		 * Peform validation for the rule "max_length"
720
+		 * @param  string $inputName the form field or data key name used
721
+		 * @param  string $ruleName  the rule name for this validation ("max_length")
722
+		 * @param  array  $ruleArgs  the rules argument
723
+		 */
724
+		protected function _validateMaxLength($inputName, $ruleName, array $ruleArgs) {
725
+			$inputVal = $this->post($inputName);
726
+			if (strlen($inputVal) > $ruleArgs[1]) { // $ruleArgs[0] is [length] $rulesArgs[1] is just length
727
+				if (! $this->_fieldIsRequired($inputName) && empty($this->data[$inputName])) {
728
+					return;
729
+				}
730
+				$this->_setError($inputName, $ruleName, array($this->_getLabel($inputName), $this->_getLabel($ruleArgs[1])));
731
+			}
732
+		}
733
+
734
+		/**
735
+		 * Peform validation for the rule "min_length"
736
+		 * @param  string $inputName the form field or data key name used
737
+		 * @param  string $ruleName  the rule name for this validation ("min_length")
738
+		 * @param  array  $ruleArgs  the rules argument
739
+		 */
740
+		protected function _validateMinLength($inputName, $ruleName, array $ruleArgs) {
741
+			$inputVal = $this->post($inputName);
742
+			if (strlen($inputVal) < $ruleArgs[1]) { // $ruleArgs[0] is [length] $rulesArgs[1] is just length
743
+				if (! $this->_fieldIsRequired($inputName) && empty($this->data[$inputName])) {
744
+					return;
745
+				}
746
+				$this->_setError($inputName, $ruleName, array($this->_getLabel($inputName), $this->_getLabel($ruleArgs[1])));
747
+			}
748
+		}
749 749
     	
750
-        /**
751
-         * Peform validation for the rule "less_than"
752
-         * @param  string $inputName the form field or data key name used
753
-         * @param  string $ruleName  the rule name for this validation ("less_than")
754
-         * @param  array  $ruleArgs  the rules argument
755
-         */
756
-    	protected function _validateLessThan($inputName, $ruleName, array $ruleArgs) {
757
-            $inputVal = $this->post($inputName);
758
-            if ($inputVal >= $ruleArgs[1]) { 
759
-                if (! $this->_fieldIsRequired($inputName) && empty($this->data[$inputName])) {
760
-                    return;
761
-                }
762
-                $this->_setError($inputName, $ruleName, array($this->_getLabel($inputName), $this->_getLabel($ruleArgs[1])));
763
-            }
764
-        }
750
+		/**
751
+		 * Peform validation for the rule "less_than"
752
+		 * @param  string $inputName the form field or data key name used
753
+		 * @param  string $ruleName  the rule name for this validation ("less_than")
754
+		 * @param  array  $ruleArgs  the rules argument
755
+		 */
756
+		protected function _validateLessThan($inputName, $ruleName, array $ruleArgs) {
757
+			$inputVal = $this->post($inputName);
758
+			if ($inputVal >= $ruleArgs[1]) { 
759
+				if (! $this->_fieldIsRequired($inputName) && empty($this->data[$inputName])) {
760
+					return;
761
+				}
762
+				$this->_setError($inputName, $ruleName, array($this->_getLabel($inputName), $this->_getLabel($ruleArgs[1])));
763
+			}
764
+		}
765 765
     	
766
-        /**
767
-         * Peform validation for the rule "greater_than"
768
-         * @param  string $inputName the form field or data key name used
769
-         * @param  string $ruleName  the rule name for this validation ("greater_than")
770
-         * @param  array  $ruleArgs  the rules argument
771
-         */
772
-    	protected function _validateGreaterThan($inputName, $ruleName, array $ruleArgs) {
773
-            $inputVal = $this->post($inputName);
774
-            if ($inputVal <= $ruleArgs[1]) {
775
-                if (! $this->_fieldIsRequired($inputName) && empty($this->data[$inputName])) {
776
-                    return;
777
-                }
778
-                $this->_setError($inputName, $ruleName, array($this->_getLabel($inputName), $this->_getLabel($ruleArgs[1])));
779
-            }
780
-        }
766
+		/**
767
+		 * Peform validation for the rule "greater_than"
768
+		 * @param  string $inputName the form field or data key name used
769
+		 * @param  string $ruleName  the rule name for this validation ("greater_than")
770
+		 * @param  array  $ruleArgs  the rules argument
771
+		 */
772
+		protected function _validateGreaterThan($inputName, $ruleName, array $ruleArgs) {
773
+			$inputVal = $this->post($inputName);
774
+			if ($inputVal <= $ruleArgs[1]) {
775
+				if (! $this->_fieldIsRequired($inputName) && empty($this->data[$inputName])) {
776
+					return;
777
+				}
778
+				$this->_setError($inputName, $ruleName, array($this->_getLabel($inputName), $this->_getLabel($ruleArgs[1])));
779
+			}
780
+		}
781 781
     	
782
-        /**
783
-         * Peform validation for the rule "numeric"
784
-         * @param  string $inputName the form field or data key name used
785
-         * @param  string $ruleName  the rule name for this validation ("numeric")
786
-         * @param  array  $ruleArgs  the rules argument
787
-         */
788
-    	protected function _validateNumeric($inputName, $ruleName, array $ruleArgs) {
789
-            $inputVal = $this->post($inputName);
790
-            if (! is_numeric($inputVal)) {
791
-                if (! $this->_fieldIsRequired($inputName) && empty($this->data[$inputName])) {
792
-                    return;
793
-                }
794
-                $this->_setError($inputName, $ruleName, array($this->_getLabel($inputName)));
795
-            }
796
-        }
782
+		/**
783
+		 * Peform validation for the rule "numeric"
784
+		 * @param  string $inputName the form field or data key name used
785
+		 * @param  string $ruleName  the rule name for this validation ("numeric")
786
+		 * @param  array  $ruleArgs  the rules argument
787
+		 */
788
+		protected function _validateNumeric($inputName, $ruleName, array $ruleArgs) {
789
+			$inputVal = $this->post($inputName);
790
+			if (! is_numeric($inputVal)) {
791
+				if (! $this->_fieldIsRequired($inputName) && empty($this->data[$inputName])) {
792
+					return;
793
+				}
794
+				$this->_setError($inputName, $ruleName, array($this->_getLabel($inputName)));
795
+			}
796
+		}
797 797
 		
798
-        /**
799
-         * Peform validation for the rule "exists"
800
-         * @param  string $inputName the form field or data key name used
801
-         * @param  string $ruleName  the rule name for this validation ("exists")
802
-         * @param  array  $ruleArgs  the rules argument
803
-         */
798
+		/**
799
+		 * Peform validation for the rule "exists"
800
+		 * @param  string $inputName the form field or data key name used
801
+		 * @param  string $ruleName  the rule name for this validation ("exists")
802
+		 * @param  array  $ruleArgs  the rules argument
803
+		 */
804 804
 		protected function _validateExists($inputName, $ruleName, array $ruleArgs) {
805
-            $inputVal = $this->post($inputName);
806
-    		$obj = & get_instance();
807
-    		if(! isset($obj->database)){
808
-    			return;
809
-    		}
810
-    		list($table, $column) = explode('.', $ruleArgs[1]);
811
-    		$obj->database->from($table)
812
-    			          ->where($column, $inputVal)
813
-    			          ->get();
814
-    		$nb = $obj->database->numRows();
815
-            if ($nb == 0) {
816
-                if (! $this->_fieldIsRequired($inputName) && empty($this->data[$inputName])) {
817
-                    return;
818
-                }
819
-                $this->_setError($inputName, $ruleName, array($this->_getLabel($inputName)));
820
-            }
821
-        }
822
-
823
-        /**
824
-         * Peform validation for the rule "is_unique"
825
-         * @param  string $inputName the form field or data key name used
826
-         * @param  string $ruleName  the rule name for this validation ("is_unique")
827
-         * @param  array  $ruleArgs  the rules argument
828
-         */
829
-    	protected function _validateIsUnique($inputName, $ruleName, array $ruleArgs) {
830
-            $inputVal = $this->post($inputName);
831
-    		$obj = & get_instance();
832
-    		if(! isset($obj->database)){
833
-    			return;
834
-    		}
835
-    		list($table, $column) = explode('.', $ruleArgs[1]);
836
-    		$obj->database->from($table)
837
-    			          ->where($column, $inputVal)
838
-    			          ->get();
839
-    		$nb = $obj->database->numRows();
840
-            if ($nb != 0) {
841
-                if (! $this->_fieldIsRequired($inputName) && empty($this->data[$inputName])) {
842
-                    return;
843
-                }
844
-                $this->_setError($inputName, $ruleName, array($this->_getLabel($inputName)));
845
-            }
846
-        }
805
+			$inputVal = $this->post($inputName);
806
+			$obj = & get_instance();
807
+			if(! isset($obj->database)){
808
+				return;
809
+			}
810
+			list($table, $column) = explode('.', $ruleArgs[1]);
811
+			$obj->database->from($table)
812
+						  ->where($column, $inputVal)
813
+						  ->get();
814
+			$nb = $obj->database->numRows();
815
+			if ($nb == 0) {
816
+				if (! $this->_fieldIsRequired($inputName) && empty($this->data[$inputName])) {
817
+					return;
818
+				}
819
+				$this->_setError($inputName, $ruleName, array($this->_getLabel($inputName)));
820
+			}
821
+		}
822
+
823
+		/**
824
+		 * Peform validation for the rule "is_unique"
825
+		 * @param  string $inputName the form field or data key name used
826
+		 * @param  string $ruleName  the rule name for this validation ("is_unique")
827
+		 * @param  array  $ruleArgs  the rules argument
828
+		 */
829
+		protected function _validateIsUnique($inputName, $ruleName, array $ruleArgs) {
830
+			$inputVal = $this->post($inputName);
831
+			$obj = & get_instance();
832
+			if(! isset($obj->database)){
833
+				return;
834
+			}
835
+			list($table, $column) = explode('.', $ruleArgs[1]);
836
+			$obj->database->from($table)
837
+						  ->where($column, $inputVal)
838
+						  ->get();
839
+			$nb = $obj->database->numRows();
840
+			if ($nb != 0) {
841
+				if (! $this->_fieldIsRequired($inputName) && empty($this->data[$inputName])) {
842
+					return;
843
+				}
844
+				$this->_setError($inputName, $ruleName, array($this->_getLabel($inputName)));
845
+			}
846
+		}
847 847
     	
848
-        /**
849
-         * Peform validation for the rule "is_unique_update"
850
-         * @param  string $inputName the form field or data key name used
851
-         * @param  string $ruleName  the rule name for this validation ("is_unique_update")
852
-         * @param  array  $ruleArgs  the rules argument
853
-         */
854
-    	protected function _validateIsUniqueUpdate($inputName, $ruleName, array $ruleArgs) {
855
-            $inputVal = $this->post($inputName);
856
-    		$obj = & get_instance();
857
-    		if(! isset($obj->database)){
858
-    			return;
859
-    		}
860
-    		$data = explode(',', $ruleArgs[1]);
861
-    		if(count($data) < 2){
862
-    			return;
863
-    		}
864
-    		list($table, $column) = explode('.', $data[0]);
865
-    		list($field, $val) = explode('=', $data[1]);
866
-    		$obj->database->from($table)
867
-    			          ->where($column, $inputVal)
868
-                		  ->where($field, '!=', trim($val))
869
-                		  ->get();
870
-    		$nb = $obj->database->numRows();
871
-            if ($nb != 0) {
872
-                if (! $this->_fieldIsRequired($inputName) && empty($this->data[$inputName])) {
873
-                    return;
874
-                }
875
-                $this->_setError($inputName, $ruleName, array($this->_getLabel($inputName)));
876
-            }
877
-        }
878
-
879
-        /**
880
-         * Peform validation for the rule "in_list"
881
-         * @param  string $inputName the form field or data key name used
882
-         * @param  string $ruleName  the rule name for this validation ("in_list")
883
-         * @param  array  $ruleArgs  the rules argument
884
-         */
885
-        protected function _validateInList($inputName, $ruleName, array $ruleArgs) {
886
-            $inputVal = $this->post($inputName);
887
-    		$list = explode(',', $ruleArgs[1]);
888
-            $list = array_map('trim', $list);
889
-            if (! in_array($inputVal, $list)) {
890
-                if (! $this->_fieldIsRequired($inputName) && empty($this->data[$inputName])) {
891
-                    return;
892
-                }
893
-                $this->_setError($inputName, $ruleName, array($this->_getLabel($inputName), $this->_getLabel($ruleArgs[1])));
894
-            }
895
-        }
896
-
897
-        /**
898
-         * Peform validation for the rule "regex"
899
-         * @param  string $inputName the form field or data key name used
900
-         * @param  string $ruleName  the rule name for this validation ("regex")
901
-         * @param  array  $ruleArgs  the rules argument
902
-         */
903
-        protected function _validateRegex($inputName, $ruleName, array $ruleArgs) {
904
-            $inputVal = $this->post($inputName);
905
-    		$regex = $ruleArgs[1];
906
-            if (! preg_match($regex, $inputVal)) {
907
-                if (! $this->_fieldIsRequired($inputName) && empty($this->data[$inputName])) {
908
-                    return;
909
-                }
910
-                $this->_setError($inputName, $ruleName, array($this->_getLabel($inputName)));
911
-            }
912
-        }
848
+		/**
849
+		 * Peform validation for the rule "is_unique_update"
850
+		 * @param  string $inputName the form field or data key name used
851
+		 * @param  string $ruleName  the rule name for this validation ("is_unique_update")
852
+		 * @param  array  $ruleArgs  the rules argument
853
+		 */
854
+		protected function _validateIsUniqueUpdate($inputName, $ruleName, array $ruleArgs) {
855
+			$inputVal = $this->post($inputName);
856
+			$obj = & get_instance();
857
+			if(! isset($obj->database)){
858
+				return;
859
+			}
860
+			$data = explode(',', $ruleArgs[1]);
861
+			if(count($data) < 2){
862
+				return;
863
+			}
864
+			list($table, $column) = explode('.', $data[0]);
865
+			list($field, $val) = explode('=', $data[1]);
866
+			$obj->database->from($table)
867
+						  ->where($column, $inputVal)
868
+						  ->where($field, '!=', trim($val))
869
+						  ->get();
870
+			$nb = $obj->database->numRows();
871
+			if ($nb != 0) {
872
+				if (! $this->_fieldIsRequired($inputName) && empty($this->data[$inputName])) {
873
+					return;
874
+				}
875
+				$this->_setError($inputName, $ruleName, array($this->_getLabel($inputName)));
876
+			}
877
+		}
878
+
879
+		/**
880
+		 * Peform validation for the rule "in_list"
881
+		 * @param  string $inputName the form field or data key name used
882
+		 * @param  string $ruleName  the rule name for this validation ("in_list")
883
+		 * @param  array  $ruleArgs  the rules argument
884
+		 */
885
+		protected function _validateInList($inputName, $ruleName, array $ruleArgs) {
886
+			$inputVal = $this->post($inputName);
887
+			$list = explode(',', $ruleArgs[1]);
888
+			$list = array_map('trim', $list);
889
+			if (! in_array($inputVal, $list)) {
890
+				if (! $this->_fieldIsRequired($inputName) && empty($this->data[$inputName])) {
891
+					return;
892
+				}
893
+				$this->_setError($inputName, $ruleName, array($this->_getLabel($inputName), $this->_getLabel($ruleArgs[1])));
894
+			}
895
+		}
896
+
897
+		/**
898
+		 * Peform validation for the rule "regex"
899
+		 * @param  string $inputName the form field or data key name used
900
+		 * @param  string $ruleName  the rule name for this validation ("regex")
901
+		 * @param  array  $ruleArgs  the rules argument
902
+		 */
903
+		protected function _validateRegex($inputName, $ruleName, array $ruleArgs) {
904
+			$inputVal = $this->post($inputName);
905
+			$regex = $ruleArgs[1];
906
+			if (! preg_match($regex, $inputVal)) {
907
+				if (! $this->_fieldIsRequired($inputName) && empty($this->data[$inputName])) {
908
+					return;
909
+				}
910
+				$this->_setError($inputName, $ruleName, array($this->_getLabel($inputName)));
911
+			}
912
+		}
913 913
         
914
-    }
914
+	}
Please login to merge, or discard this patch.
Spacing   +52 added lines, -52 removed lines patch added patch discarded remove patch
@@ -25,13 +25,13 @@  discard block
 block discarded – undo
25 25
     */
26 26
 
27 27
 
28
-     class FormValidation{
28
+     class FormValidation {
29 29
 		 
30 30
         /**
31 31
          * The form validation status
32 32
          * @var boolean
33 33
          */
34
-        protected $_success  = false;
34
+        protected $_success = false;
35 35
 
36 36
         /**
37 37
          * The list of errors messages
@@ -40,31 +40,31 @@  discard block
 block discarded – undo
40 40
         protected $_errorsMessages = array();
41 41
         
42 42
         // Array of rule sets, fieldName => PIPE seperated ruleString
43
-        protected $_rules             = array();
43
+        protected $_rules = array();
44 44
         
45 45
         // Array of errors, niceName => Error Message
46
-        protected $_errors             = array();
46
+        protected $_errors = array();
47 47
         
48 48
         // Array of post Key => Nice name labels
49
-        protected $_labels          = array();
49
+        protected $_labels = array();
50 50
         
51 51
         /**
52 52
          * The errors delimiters
53 53
          * @var array
54 54
          */
55
-        protected $_allErrorsDelimiter   = array('<div class="error">', '</div>');
55
+        protected $_allErrorsDelimiter = array('<div class="error">', '</div>');
56 56
 
57 57
         /**
58 58
          * The each error delimiter
59 59
          * @var array
60 60
          */
61
-        protected $_eachErrorDelimiter   = array('<p class="error">', '</p>');
61
+        protected $_eachErrorDelimiter = array('<p class="error">', '</p>');
62 62
         
63 63
 		/**
64 64
          * Indicated if need force the validation to be failed
65 65
          * @var boolean
66 66
          */
67
-        protected $_forceFail            = false;
67
+        protected $_forceFail = false;
68 68
 
69 69
         /**
70 70
          * The list of the error messages overrides by the original
@@ -98,13 +98,13 @@  discard block
 block discarded – undo
98 98
          * @return void
99 99
          */
100 100
         public function __construct() {
101
-            $this->logger =& class_loader('Log', 'classes');
101
+            $this->logger = & class_loader('Log', 'classes');
102 102
             $this->logger->setLogger('Library::FormValidation');
103 103
            
104 104
 		   //Load form validation language message
105 105
             Loader::lang('form_validation');
106 106
             $obj = & get_instance();
107
-            $this->_errorsMessages  = array(
107
+            $this->_errorsMessages = array(
108 108
                         'required'         => $obj->lang->get('fv_required'),
109 109
                         'min_length'       => $obj->lang->get('fv_min_length'),
110 110
                         'max_length'       => $obj->lang->get('fv_max_length'),
@@ -141,7 +141,7 @@  discard block
 block discarded – undo
141 141
             $this->_success              = false;
142 142
             $this->_forceFail            = false;
143 143
             $this->data                  = array();
144
-			$this->enableCsrfCheck       = false;
144
+			$this->enableCsrfCheck = false;
145 145
         }
146 146
 
147 147
         /**
@@ -150,7 +150,7 @@  discard block
 block discarded – undo
150 150
 		 *
151 151
          * @return FormValidation Current instance of object.
152 152
          */
153
-        public function setData(array $data){
153
+        public function setData(array $data) {
154 154
             $this->logger->debug('Setting the form validation data, the values are: ' . stringfy_vars($data));
155 155
             $this->data = $data;
156 156
 			return $this;
@@ -160,7 +160,7 @@  discard block
 block discarded – undo
160 160
          * Get the form validation data
161 161
          * @return array the form validation data to be validated
162 162
          */
163
-        public function getData(){
163
+        public function getData() {
164 164
             return $this->data;
165 165
         }
166 166
 
@@ -169,7 +169,7 @@  discard block
 block discarded – undo
169 169
 		*
170 170
 		* @return string the function name
171 171
 		*/
172
-        protected function _toCallCase($funcName, $prefix='_validate') {
172
+        protected function _toCallCase($funcName, $prefix = '_validate') {
173 173
             $funcName = strtolower($funcName);
174 174
             $finalFuncName = $prefix;
175 175
             foreach (explode('_', $funcName) as $funcNamePart) {
@@ -193,7 +193,7 @@  discard block
 block discarded – undo
193 193
          * @return boolean Whether or not the form has been submitted or the data is available for validation.
194 194
          */
195 195
         public function canDoValidation() {
196
-            return get_instance()->request->method() === 'POST' || ! empty($this->data);
196
+            return get_instance()->request->method() === 'POST' || !empty($this->data);
197 197
         }
198 198
 
199 199
         /**
@@ -215,13 +215,13 @@  discard block
 block discarded – undo
215 215
          * afterwards.
216 216
          */
217 217
         protected function _run() {
218
-            if(get_instance()->request->method() == 'POST' || $this->enableCsrfCheck){
218
+            if (get_instance()->request->method() == 'POST' || $this->enableCsrfCheck) {
219 219
                 $this->logger->debug('Check if CSRF is enabled in configuration');
220 220
                 //first check for CSRF
221
-                if ((get_config('csrf_enable', false) || $this->enableCsrfCheck) && ! Security::validateCSRF()){
221
+                if ((get_config('csrf_enable', false) || $this->enableCsrfCheck) && !Security::validateCSRF()) {
222 222
                     show_error('Invalide data, Cross Site Request Forgery do his job, the data to validate is corrupted.');
223 223
                 }
224
-                else{
224
+                else {
225 225
                     $this->logger->info('CSRF is not enabled in configuration or not set manully, no need to check it');
226 226
                 }
227 227
             }
@@ -229,10 +229,10 @@  discard block
 block discarded – undo
229 229
             $this->_forceFail = false;
230 230
 
231 231
             foreach ($this->getData() as $inputName => $inputVal) {
232
-    			if(is_array($this->data[$inputName])){
232
+    			if (is_array($this->data[$inputName])) {
233 233
     				$this->data[$inputName] = array_map('trim', $this->data[$inputName]);
234 234
     			}
235
-    			else{
235
+    			else {
236 236
     				$this->data[$inputName] = trim($this->data[$inputName]);
237 237
     			}
238 238
 
@@ -259,7 +259,7 @@  discard block
 block discarded – undo
259 259
         public function setRule($inputField, $inputLabel, $ruleSets) {
260 260
             $this->_rules[$inputField] = $ruleSets;
261 261
             $this->_labels[$inputField] = $inputLabel;
262
-            $this->logger->info('Set the field rule: name [' .$inputField. '], label [' .$inputLabel. '], rules [' .$ruleSets. ']');
262
+            $this->logger->info('Set the field rule: name [' . $inputField . '], label [' . $inputLabel . '], rules [' . $ruleSets . ']');
263 263
             return $this;
264 264
         }
265 265
 
@@ -423,7 +423,7 @@  discard block
 block discarded – undo
423 423
             }
424 424
             $errorOutput .= $errorsEnd;
425 425
             echo ($echo) ? $errorOutput : '';
426
-            return (! $echo) ? $errorOutput : null;
426
+            return (!$echo) ? $errorOutput : null;
427 427
         }
428 428
 
429 429
         /**
@@ -448,25 +448,25 @@  discard block
 block discarded – undo
448 448
             /*
449 449
             //////////////// hack for regex rule that can contain "|"
450 450
             */
451
-            if(strpos($ruleString, 'regex') !== false){
451
+            if (strpos($ruleString, 'regex') !== false) {
452 452
                 $regexRule = array();
453 453
                 $rule = '#regex\[\/(.*)\/([a-zA-Z0-9]?)\]#';
454 454
                 preg_match($rule, $ruleString, $regexRule);
455 455
                 $ruleStringTemp = preg_replace($rule, '', $ruleString);
456
-                 if(!empty($regexRule[0])){
456
+                 if (!empty($regexRule[0])) {
457 457
                      $ruleSets[] = $regexRule[0];
458 458
                  }
459 459
                  $ruleStringRegex = explode('|', $ruleStringTemp);
460 460
                 foreach ($ruleStringRegex as $rule) {
461 461
                     $rule = trim($rule);
462
-                    if($rule){
462
+                    if ($rule) {
463 463
                         $ruleSets[] = $rule;
464 464
                     }
465 465
                 }
466 466
                  
467 467
             }
468 468
             /***********************************/
469
-            else{
469
+            else {
470 470
                 if (strpos($ruleString, '|') !== FALSE) {
471 471
                     $ruleSets = explode('|', $ruleString);
472 472
                 } else {
@@ -498,7 +498,7 @@  discard block
 block discarded – undo
498 498
          * @return void
499 499
          */
500 500
         protected function _validateRule($inputName, $inputVal, $ruleName) {
501
-            $this->logger->debug('Rule validation of field [' .$inputName. '], value [' .$inputVal. '], rule [' .$ruleName. ']');
501
+            $this->logger->debug('Rule validation of field [' . $inputName . '], value [' . $inputVal . '], rule [' . $ruleName . ']');
502 502
             // Array to store args
503 503
             $ruleArgs = array();
504 504
 
@@ -543,7 +543,7 @@  discard block
 block discarded – undo
543 543
                 $key = $i - 1;
544 544
                 $rulePhrase = str_replace('%' . $i, $replacements[$key], $rulePhrase);
545 545
             }
546
-            if (! array_key_exists($inputName, $this->_errors)) {
546
+            if (!array_key_exists($inputName, $this->_errors)) {
547 547
                 $this->_errors[$inputName] = $rulePhrase;
548 548
             }
549 549
         }
@@ -595,13 +595,13 @@  discard block
 block discarded – undo
595 595
          */
596 596
 		protected function _validateRequired($inputName, $ruleName, array $ruleArgs) {
597 597
             $inputVal = $this->post($inputName);
598
-            if(array_key_exists(1, $ruleArgs) && function_exists($ruleArgs[1])) {
598
+            if (array_key_exists(1, $ruleArgs) && function_exists($ruleArgs[1])) {
599 599
                 $callbackReturn = $this->_runEmptyCallback($ruleArgs[1]);
600 600
                 if ($inputVal == '' && $callbackReturn == true) {
601 601
                     $this->_setError($inputName, $ruleName, $this->_getLabel($inputName));
602 602
                 }
603 603
             } 
604
-			else if($inputVal == '') {
604
+			else if ($inputVal == '') {
605 605
 				$this->_setError($inputName, $ruleName, $this->_getLabel($inputName));
606 606
             }
607 607
         }
@@ -627,7 +627,7 @@  discard block
 block discarded – undo
627 627
         protected function _validateCallback($inputName, $ruleName, array $ruleArgs) {
628 628
             if (function_exists($ruleArgs[1]) && !empty($this->data[$inputName])) {
629 629
 				$result = $this->_runCallback($this->data[$inputName], $ruleArgs[1]);
630
-				if(! $result){
630
+				if (!$result) {
631 631
 					$this->_setError($inputName, $ruleName, array($this->_getLabel($inputName)));
632 632
 				}
633 633
             }
@@ -661,7 +661,7 @@  discard block
 block discarded – undo
661 661
                         continue;
662 662
                     }
663 663
                 } 
664
-				else{
664
+				else {
665 665
                     if ($inputVal == $doNotEqual) {
666 666
                         $this->_setError($inputName, $ruleName . ',string', array($this->_getLabel($inputName), $doNotEqual));
667 667
                         continue;
@@ -691,8 +691,8 @@  discard block
 block discarded – undo
691 691
          */
692 692
         protected function _validateValidEmail($inputName, $ruleName, array $ruleArgs) {
693 693
             $inputVal = $this->post($inputName);
694
-            if (! preg_match("/^([\w\!\#$\%\&\'\*\+\-\/\=\?\^\`{\|\}\~]+\.)*[\w\!\#$\%\&\'\*\+\-\/\=\?\^\`{\|\}\~]+@((((([a-z0-9]{1}[a-z0-9\-]{0,62}[a-z0-9]{1})|[a-z])\.)+[a-z]{2,6})|(\d{1,3}\.){3}\d{1,3}(\:\d{1,5})?)$/i", $inputVal)) {
695
-                if (! $this->_fieldIsRequired($inputName) && empty($this->data[$inputName])) {
694
+            if (!preg_match("/^([\w\!\#$\%\&\'\*\+\-\/\=\?\^\`{\|\}\~]+\.)*[\w\!\#$\%\&\'\*\+\-\/\=\?\^\`{\|\}\~]+@((((([a-z0-9]{1}[a-z0-9\-]{0,62}[a-z0-9]{1})|[a-z])\.)+[a-z]{2,6})|(\d{1,3}\.){3}\d{1,3}(\:\d{1,5})?)$/i", $inputVal)) {
695
+                if (!$this->_fieldIsRequired($inputName) && empty($this->data[$inputName])) {
696 696
                     return;
697 697
                 }
698 698
                 $this->_setError($inputName, $ruleName, $this->_getLabel($inputName));
@@ -708,7 +708,7 @@  discard block
 block discarded – undo
708 708
         protected function _validateExactLength($inputName, $ruleName, array $ruleArgs) {
709 709
             $inputVal = $this->post($inputName);
710 710
             if (strlen($inputVal) != $ruleArgs[1]) { // $ruleArgs[0] is [length] $rulesArgs[1] is just length
711
-                if (! $this->_fieldIsRequired($inputName) && empty($this->data[$inputName])) {
711
+                if (!$this->_fieldIsRequired($inputName) && empty($this->data[$inputName])) {
712 712
                     return;
713 713
                 }
714 714
                 $this->_setError($inputName, $ruleName, array($this->_getLabel($inputName), $this->_getLabel($ruleArgs[1])));
@@ -724,7 +724,7 @@  discard block
 block discarded – undo
724 724
         protected function _validateMaxLength($inputName, $ruleName, array $ruleArgs) {
725 725
             $inputVal = $this->post($inputName);
726 726
             if (strlen($inputVal) > $ruleArgs[1]) { // $ruleArgs[0] is [length] $rulesArgs[1] is just length
727
-                if (! $this->_fieldIsRequired($inputName) && empty($this->data[$inputName])) {
727
+                if (!$this->_fieldIsRequired($inputName) && empty($this->data[$inputName])) {
728 728
                     return;
729 729
                 }
730 730
                 $this->_setError($inputName, $ruleName, array($this->_getLabel($inputName), $this->_getLabel($ruleArgs[1])));
@@ -740,7 +740,7 @@  discard block
 block discarded – undo
740 740
         protected function _validateMinLength($inputName, $ruleName, array $ruleArgs) {
741 741
             $inputVal = $this->post($inputName);
742 742
             if (strlen($inputVal) < $ruleArgs[1]) { // $ruleArgs[0] is [length] $rulesArgs[1] is just length
743
-                if (! $this->_fieldIsRequired($inputName) && empty($this->data[$inputName])) {
743
+                if (!$this->_fieldIsRequired($inputName) && empty($this->data[$inputName])) {
744 744
                     return;
745 745
                 }
746 746
                 $this->_setError($inputName, $ruleName, array($this->_getLabel($inputName), $this->_getLabel($ruleArgs[1])));
@@ -756,7 +756,7 @@  discard block
 block discarded – undo
756 756
     	protected function _validateLessThan($inputName, $ruleName, array $ruleArgs) {
757 757
             $inputVal = $this->post($inputName);
758 758
             if ($inputVal >= $ruleArgs[1]) { 
759
-                if (! $this->_fieldIsRequired($inputName) && empty($this->data[$inputName])) {
759
+                if (!$this->_fieldIsRequired($inputName) && empty($this->data[$inputName])) {
760 760
                     return;
761 761
                 }
762 762
                 $this->_setError($inputName, $ruleName, array($this->_getLabel($inputName), $this->_getLabel($ruleArgs[1])));
@@ -772,7 +772,7 @@  discard block
 block discarded – undo
772 772
     	protected function _validateGreaterThan($inputName, $ruleName, array $ruleArgs) {
773 773
             $inputVal = $this->post($inputName);
774 774
             if ($inputVal <= $ruleArgs[1]) {
775
-                if (! $this->_fieldIsRequired($inputName) && empty($this->data[$inputName])) {
775
+                if (!$this->_fieldIsRequired($inputName) && empty($this->data[$inputName])) {
776 776
                     return;
777 777
                 }
778 778
                 $this->_setError($inputName, $ruleName, array($this->_getLabel($inputName), $this->_getLabel($ruleArgs[1])));
@@ -787,8 +787,8 @@  discard block
 block discarded – undo
787 787
          */
788 788
     	protected function _validateNumeric($inputName, $ruleName, array $ruleArgs) {
789 789
             $inputVal = $this->post($inputName);
790
-            if (! is_numeric($inputVal)) {
791
-                if (! $this->_fieldIsRequired($inputName) && empty($this->data[$inputName])) {
790
+            if (!is_numeric($inputVal)) {
791
+                if (!$this->_fieldIsRequired($inputName) && empty($this->data[$inputName])) {
792 792
                     return;
793 793
                 }
794 794
                 $this->_setError($inputName, $ruleName, array($this->_getLabel($inputName)));
@@ -804,7 +804,7 @@  discard block
 block discarded – undo
804 804
 		protected function _validateExists($inputName, $ruleName, array $ruleArgs) {
805 805
             $inputVal = $this->post($inputName);
806 806
     		$obj = & get_instance();
807
-    		if(! isset($obj->database)){
807
+    		if (!isset($obj->database)) {
808 808
     			return;
809 809
     		}
810 810
     		list($table, $column) = explode('.', $ruleArgs[1]);
@@ -813,7 +813,7 @@  discard block
 block discarded – undo
813 813
     			          ->get();
814 814
     		$nb = $obj->database->numRows();
815 815
             if ($nb == 0) {
816
-                if (! $this->_fieldIsRequired($inputName) && empty($this->data[$inputName])) {
816
+                if (!$this->_fieldIsRequired($inputName) && empty($this->data[$inputName])) {
817 817
                     return;
818 818
                 }
819 819
                 $this->_setError($inputName, $ruleName, array($this->_getLabel($inputName)));
@@ -829,7 +829,7 @@  discard block
 block discarded – undo
829 829
     	protected function _validateIsUnique($inputName, $ruleName, array $ruleArgs) {
830 830
             $inputVal = $this->post($inputName);
831 831
     		$obj = & get_instance();
832
-    		if(! isset($obj->database)){
832
+    		if (!isset($obj->database)) {
833 833
     			return;
834 834
     		}
835 835
     		list($table, $column) = explode('.', $ruleArgs[1]);
@@ -838,7 +838,7 @@  discard block
 block discarded – undo
838 838
     			          ->get();
839 839
     		$nb = $obj->database->numRows();
840 840
             if ($nb != 0) {
841
-                if (! $this->_fieldIsRequired($inputName) && empty($this->data[$inputName])) {
841
+                if (!$this->_fieldIsRequired($inputName) && empty($this->data[$inputName])) {
842 842
                     return;
843 843
                 }
844 844
                 $this->_setError($inputName, $ruleName, array($this->_getLabel($inputName)));
@@ -854,11 +854,11 @@  discard block
 block discarded – undo
854 854
     	protected function _validateIsUniqueUpdate($inputName, $ruleName, array $ruleArgs) {
855 855
             $inputVal = $this->post($inputName);
856 856
     		$obj = & get_instance();
857
-    		if(! isset($obj->database)){
857
+    		if (!isset($obj->database)) {
858 858
     			return;
859 859
     		}
860 860
     		$data = explode(',', $ruleArgs[1]);
861
-    		if(count($data) < 2){
861
+    		if (count($data) < 2) {
862 862
     			return;
863 863
     		}
864 864
     		list($table, $column) = explode('.', $data[0]);
@@ -869,7 +869,7 @@  discard block
 block discarded – undo
869 869
                 		  ->get();
870 870
     		$nb = $obj->database->numRows();
871 871
             if ($nb != 0) {
872
-                if (! $this->_fieldIsRequired($inputName) && empty($this->data[$inputName])) {
872
+                if (!$this->_fieldIsRequired($inputName) && empty($this->data[$inputName])) {
873 873
                     return;
874 874
                 }
875 875
                 $this->_setError($inputName, $ruleName, array($this->_getLabel($inputName)));
@@ -886,8 +886,8 @@  discard block
 block discarded – undo
886 886
             $inputVal = $this->post($inputName);
887 887
     		$list = explode(',', $ruleArgs[1]);
888 888
             $list = array_map('trim', $list);
889
-            if (! in_array($inputVal, $list)) {
890
-                if (! $this->_fieldIsRequired($inputName) && empty($this->data[$inputName])) {
889
+            if (!in_array($inputVal, $list)) {
890
+                if (!$this->_fieldIsRequired($inputName) && empty($this->data[$inputName])) {
891 891
                     return;
892 892
                 }
893 893
                 $this->_setError($inputName, $ruleName, array($this->_getLabel($inputName), $this->_getLabel($ruleArgs[1])));
@@ -903,8 +903,8 @@  discard block
 block discarded – undo
903 903
         protected function _validateRegex($inputName, $ruleName, array $ruleArgs) {
904 904
             $inputVal = $this->post($inputName);
905 905
     		$regex = $ruleArgs[1];
906
-            if (! preg_match($regex, $inputVal)) {
907
-                if (! $this->_fieldIsRequired($inputName) && empty($this->data[$inputName])) {
906
+            if (!preg_match($regex, $inputVal)) {
907
+                if (!$this->_fieldIsRequired($inputName) && empty($this->data[$inputName])) {
908 908
                     return;
909 909
                 }
910 910
                 $this->_setError($inputName, $ruleName, array($this->_getLabel($inputName)));
Please login to merge, or discard this patch.
Braces   +4 added lines, -8 removed lines patch added patch discarded remove patch
@@ -220,8 +220,7 @@  discard block
 block discarded – undo
220 220
                 //first check for CSRF
221 221
                 if ((get_config('csrf_enable', false) || $this->enableCsrfCheck) && ! Security::validateCSRF()){
222 222
                     show_error('Invalide data, Cross Site Request Forgery do his job, the data to validate is corrupted.');
223
-                }
224
-                else{
223
+                } else{
225 224
                     $this->logger->info('CSRF is not enabled in configuration or not set manully, no need to check it');
226 225
                 }
227 226
             }
@@ -231,8 +230,7 @@  discard block
 block discarded – undo
231 230
             foreach ($this->getData() as $inputName => $inputVal) {
232 231
     			if(is_array($this->data[$inputName])){
233 232
     				$this->data[$inputName] = array_map('trim', $this->data[$inputName]);
234
-    			}
235
-    			else{
233
+    			} else{
236 234
     				$this->data[$inputName] = trim($this->data[$inputName]);
237 235
     			}
238 236
 
@@ -600,8 +598,7 @@  discard block
 block discarded – undo
600 598
                 if ($inputVal == '' && $callbackReturn == true) {
601 599
                     $this->_setError($inputName, $ruleName, $this->_getLabel($inputName));
602 600
                 }
603
-            } 
604
-			else if($inputVal == '') {
601
+            } else if($inputVal == '') {
605 602
 				$this->_setError($inputName, $ruleName, $this->_getLabel($inputName));
606 603
             }
607 604
         }
@@ -660,8 +657,7 @@  discard block
 block discarded – undo
660 657
                         $this->_setError($inputName, $ruleName . ',post:key', array($this->_getLabel($inputName), $this->_getLabel(str_replace('post:', '', $doNotEqual))));
661 658
                         continue;
662 659
                     }
663
-                } 
664
-				else{
660
+                } else{
665 661
                     if ($inputVal == $doNotEqual) {
666 662
                         $this->_setError($inputName, $ruleName . ',string', array($this->_getLabel($inputName), $doNotEqual));
667 663
                         continue;
Please login to merge, or discard this patch.
core/libraries/Upload.php 3 patches
Indentation   +780 added lines, -780 removed lines patch added patch discarded remove patch
@@ -1,786 +1,786 @@
 block discarded – undo
1 1
 <?php
2
-    defined('ROOT_PATH') or exit('Access denied');
3
-    /**
4
-     * TNH Framework
5
-     *
6
-     * A simple PHP framework using HMVC architecture
7
-     *
8
-     * This content is released under the GNU GPL License (GPL)
9
-     *
10
-     * Copyright (C) 2017 Tony NGUEREZA
11
-     *
12
-     * This program is free software; you can redistribute it and/or
13
-     * modify it under the terms of the GNU General Public License
14
-     * as published by the Free Software Foundation; either version 3
15
-     * of the License, or (at your option) any later version.
16
-     *
17
-     * This program is distributed in the hope that it will be useful,
18
-     * but WITHOUT ANY WARRANTY; without even the implied warranty of
19
-     * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20
-     * GNU General Public License for more details.
21
-     *
22
-     * You should have received a copy of the GNU General Public License
23
-     * along with this program; if not, write to the Free Software
24
-     * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
25
-    */
26
-
27
-
28
-
29
-    /**
30
-    *    Upload
31
-    *
32
-    *    A complete class to upload files with php 5 or higher, but the best: very simple to use.
33
-    *
34
-    *    @author Olaf Erlandsen <[email protected]>
35
-    *    @author http://www.webdevfreelance.com/
36
-    *
37
-    *    @package FileUpload
38
-    *    @version 1.5
39
-    */
40
-    class Upload{
41
-
42
-        /**
43
-        *   Version
44
-        *
45
-        *   @since      1.5
46
-        *   @version    1.0
47
-        */
48
-        const VERSION = '1.5';
49
-
50
-        /**
51
-        *    Upload function name
52
-        *    Remember:
53
-        *        Default function: move_uploaded_file
54
-        *        Native options:
55
-        *            - move_uploaded_file (Default and best option)
56
-        *            - copy
57
-        *
58
-        *    @since        1.0
59
-        *    @version    1.0
60
-        *    @var        string
61
-        */
62
-        private $upload_function = 'move_uploaded_file';
63
-
64
-        /**
65
-        *    Array with the information obtained from the
66
-        *    variable $_FILES or $HTTP_POST_FILES.
67
-        *
68
-        *    @since        1.0
69
-        *    @version    1.0
70
-        *    @var        array
71
-        */
72
-        private $file_array    = array();
73
-
74
-        /**
75
-        *    If the file you are trying to upload already exists it will
76
-        *    be overwritten if you set the variable to true.
77
-        *
78
-        *    @since        1.0
79
-        *    @version    1.0
80
-        *    @var        boolean
81
-        */
82
-        private $overwrite_file = false;
83
-
84
-        /**
85
-        *    Input element
86
-        *    Example:
87
-        *        <input type="file" name="file" />
88
-        *    Result:
89
-        *        FileUpload::$input = file
90
-        *
91
-        *    @since        1.0
92
-        *    @version    1.0
93
-        *    @var        string
94
-        */
95
-        private $input;
96
-
97
-        /**
98
-        *    Path output
99
-        *
100
-        *    @since        1.0
101
-        *    @version    1.0
102
-        *    @var        string
103
-        */
104
-        private $destination_directory;
105
-
106
-        /**
107
-        *    Output filename
108
-        *
109
-        *    @since        1.0
110
-        *    @version    1.0
111
-        *    @var        string
112
-        */
113
-        private $filename;
114
-
115
-        /**
116
-        *    Max file size
117
-        *
118
-        *    @since        1.0
119
-        *    @version    1.0
120
-        *    @var        float
121
-        */
122
-        private $max_file_size= 0.0;
123
-
124
-        /**
125
-        *    List of allowed mime types
126
-        *
127
-        *    @since        1.0
128
-        *    @version    1.0
129
-        *    @var        array
130
-        */
131
-        private $allowed_mime_types = array();
132
-
133
-        /**
134
-        *    Callbacks
135
-        *
136
-        *    @since        1.0
137
-        *    @version    1.0
138
-        *    @var        array
139
-        */
140
-        private $callbacks = array('before' => null, 'after' => null);
141
-
142
-        /**
143
-        *    File object
144
-        *
145
-        *    @since        1.0
146
-        *    @version    1.0
147
-        *    @var        object
148
-        */
149
-        private $file;
150
-
151
-        /**
152
-        *    Helping mime types
153
-        *
154
-        *    @since        1.0
155
-        *    @version    1.0
156
-        *    @var        array
157
-        */
158
-        private $mime_helping = array(
159
-            'text'      =>    array('text/plain',),
160
-            'image'     =>    array(
161
-                'image/jpeg',
162
-                'image/jpg',
163
-                'image/pjpeg',
164
-                'image/png',
165
-                'image/gif',
166
-            ),
167
-            'document'  =>    array(
168
-                'application/pdf',
169
-                'application/msword',
170
-                'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
171
-                'application/vnd.openxmlformats-officedocument.presentationml.presentation',
172
-                'application/vnd.ms-powerpoint',
173
-                'application/vnd.ms-excel',
174
-                'application/vnd.oasis.opendocument.spreadsheet',
175
-                'application/vnd.oasis.opendocument.presentation',
176
-            ),
177
-            'video'    =>    array(
178
-                'video/3gpp',
179
-                'video/3gpp',
180
-                'video/x-msvideo',
181
-                'video/avi',
182
-                'video/mpeg4',
183
-                'video/mp4',
184
-                'video/mpeg',
185
-                'video/mpg',
186
-                'video/quicktime',
187
-                'video/x-sgi-movie',
188
-                'video/x-ms-wmv',
189
-                'video/x-flv',
190
-            ),
191
-        );
192
-
193
-        /**
194
-         * The upload error message
195
-         * @var array
196
-         */
197
-        public $error_messages = array();
198
-
199
-        /**
200
-         * The upload error message
201
-         * @var string
202
-         */
203
-        protected $error = null;
204
-
205
-        /**
206
-         * The logger instance
207
-         * @var Log
208
-         */
209
-        private $logger;
210
-
211
-
212
-        /**
213
-        *    Construct
214
-        *
215
-        *    @since     0.1
216
-        *    @version   1.0.1
217
-        *    @return    object
218
-        *    @method    object    __construct
219
-        */
220
-        public function __construct(){
221
-            $this->logger =& class_loader('Log', 'classes');
222
-            $this->logger->setLogger('Library::Upload');
223
-
224
-            Loader::lang('file_upload');
225
-            $obj =& get_instance();
226
-
227
-            $this->error_messages = array(
228
-                'upload_err_ini_size' => $obj->lang->get('fu_upload_err_ini_size'),
229
-                'upload_err_form_size' => $obj->lang->get('fu_upload_err_form_size'),
230
-                'upload_err_partial' => $obj->lang->get('fu_upload_err_partial'),
231
-                'upload_err_no_file' => $obj->lang->get('fu_upload_err_no_file'),
232
-                'upload_err_no_tmp_dir' => $obj->lang->get('fu_upload_err_no_tmp_dir'),
233
-                'upload_err_cant_write' => $obj->lang->get('fu_upload_err_cant_write'),
234
-                'upload_err_extension' => $obj->lang->get('fu_upload_err_extension'),
235
-                'accept_file_types' => $obj->lang->get('fu_accept_file_types'),
236
-                'file_uploads' => $obj->lang->get('fu_file_uploads_disabled'),
237
-                'max_file_size' => $obj->lang->get('fu_max_file_size'),
238
-                'overwritten_not_allowed' => $obj->lang->get('fu_overwritten_not_allowed'),
239
-            );
240
-
241
-            $this->file = array(
242
-                'status'                =>    false,    // True: success upload
243
-                'mime'                  =>    '',       // Empty string
244
-                'filename'              =>    '',       // Empty string
245
-                'original'              =>    '',       // Empty string
246
-                'size'                  =>    0,        // 0 Bytes
247
-                'sizeFormated'          =>    '0B',     // 0 Bytes
248
-                'destination'           =>    './',     // Default: ./
249
-                'allowed_mime_types'    =>    array(),  // Allowed mime types
250
-                'error'                 =>    null,        // File error
251
-            );
252
-
253
-            // Change dir to current dir
254
-            $this->destination_directory = dirname(__FILE__) . DIRECTORY_SEPARATOR;
255
-
256
-            // Set file array
257
-            if (isset($_FILES) && is_array($_FILES)) {
258
-                $this->file_array = $_FILES;
259
-            } elseif (isset($HTTP_POST_FILES) && is_array($HTTP_POST_FILES)) {
260
-                $this->file_array = $HTTP_POST_FILES;
261
-            }
262
-            $this->logger->info('The upload file information are : ' .stringfy_vars($this->file_array));
263
-        }
264
-        /**
265
-        *    Set input.
266
-        *    If you have $_FILES["file"], you must use the key "file"
267
-        *    Example:
268
-        *        $object->setInput("file");
269
-        *
270
-        *    @since     1.0
271
-        *    @version   1.0
272
-        *    @param     string      $input
273
-        *    @return    object
274
-        *    @method    boolean     setInput
275
-        */
276
-        public function setInput($input)
277
-        {
278
-            if (!empty($input) && (is_string($input) || is_numeric($input) )) {
279
-                $this->input = $input;
280
-            }
281
-            return $this;
282
-        }
283
-        /**
284
-        *    Set new filename
285
-        *    Example:
286
-        *        FileUpload::setFilename("new file.txt")
287
-        *    Remember:
288
-        *        Use %s to retrive file extension
289
-        *
290
-        *    @since     1.0
291
-        *    @version   1.0
292
-        *    @param     string      $filename
293
-        *    @return    object
294
-        *    @method    boolean     setFilename
295
-        */
296
-        public function setFilename($filename)
297
-        {
298
-            if ($this->isFilename($filename)) {
299
-                $this->filename = $filename;
300
-            }
301
-            return $this;
302
-        }
303
-        /**
304
-        *    Set automatic filename
305
-        *
306
-        *    @since     1.0
307
-        *    @version   1.5
308
-        *    @param     string      $extension
309
-        *    @return    object
310
-        *    @method    boolean     setAutoFilename
311
-        */
312
-        public function setAutoFilename()
313
-        {
314
-            $this->filename = sha1(mt_rand(1, 9999).uniqid());
315
-            $this->filename .= time();
316
-            return $this;
317
-        }
318
-        /**
319
-        *    Set file size limit
320
-        *
321
-        *    @since     1.0
322
-        *    @version   1.0
323
-        *    @param     double     $file_size
324
-        *    @return    object
325
-        *    @method    boolean     setMaxFileSize
326
-        */
327
-        public function setMaxFileSize($file_size)
328
-        {
329
-            $file_size = $this->sizeInBytes($file_size);
330
-            if (is_numeric($file_size) && $file_size > -1) {
331
-                // Get php config
332
-                $php_size = $this->sizeInBytes((int) ini_get('upload_max_filesize'));
333
-                // Calculate difference
334
-                if ($php_size < $file_size) {
335
-                    $this->logger->warning('The upload max file size you set [' .$file_size. '] is greather than the PHP configuration for upload max file size [' .$php_size. ']');
336
-                }
337
-                $this->max_file_size = $file_size;
338
-            }
339
-            return $this;
340
-        }
341
-        /**
342
-        *    Set array mime types
343
-        *
344
-        *    @since     1.0
345
-        *    @version   1.0
346
-        *    @param     array       $mimes
347
-        *    @return    object
348
-        *    @method    boolean     setAllowedMimeTypes
349
-        */
350
-        public function setAllowedMimeTypes(array $mimes)
351
-        {
352
-            if (count($mimes) > 0) {
353
-                array_map(array($this , 'setAllowMimeType'), $mimes);
354
-            }
355
-            return $this;
356
-        }
357
-        /**
358
-        *    Set input callback
359
-        *
360
-        *    @since     1.0
361
-        *    @version   1.0
362
-        *    @param     mixed       $callback
363
-        *    @return    object
364
-        *    @method    boolean     setCallbackInput
365
-        */
366
-        public function setCallbackInput($callback)
367
-        {
368
-            if (is_callable($callback, false)) {
369
-                $this->callbacks['input'] = $callback;
370
-            }
371
-            return $this;
372
-        }
373
-        /**
374
-        *    Set output callback
375
-        *
376
-        *    @since     1.0
377
-        *    @version   1.0
378
-        *    @param     mixed       $callback
379
-        *    @return    object
380
-        *    @method    boolean     setCallbackOutput
381
-        */
382
-        public function setCallbackOutput($callback)
383
-        {
384
-            if (is_callable($callback, false)) {
385
-                $this->callbacks['output'] = $callback;
386
-            }
387
-            return $this;
388
-        }
389
-        /**
390
-        *    Append a mime type to allowed mime types
391
-        *
392
-        *    @since     1.0
393
-        *    @version   1.0.1
394
-        *    @param     string      $mime
395
-        *    @return    object
396
-        *    @method    boolean     setAllowMimeType
397
-        */
398
-        public function setAllowMimeType($mime)
399
-        {
400
-            if (!empty($mime) && is_string($mime)) {
401
-                $this->allowed_mime_types[] = strtolower($mime);
402
-                $this->file['allowed_mime_types'][] = strtolower($mime);
403
-            } 
404
-            return $this;
405
-        }
406
-        /**
407
-        *    Set allowed mime types from mime helping
408
-        *
409
-        *    @since     1.0.1
410
-        *    @version   1.0.1
411
-        *    @return    object
412
-        *    @method    boolean    setMimeHelping
413
-        */
414
-        public function setMimeHelping($name)
415
-        {
416
-            if (!empty($name) && is_string($name)) {
417
-                if (array_key_exists($name, $this->mime_helping)) {
418
-                    return $this->setAllowedMimeTypes($this->mime_helping[ $name ]);
419
-                }
420
-            }
421
-            return $this;
422
-        }
423
-        /**
424
-        *    Set function to upload file
425
-        *    Examples:
426
-        *        1.- FileUpload::setUploadFunction("move_uploaded_file");
427
-        *        2.- FileUpload::setUploadFunction("copy");
428
-        *
429
-        *    @since     1.0
430
-        *    @version   1.0
431
-        *    @param     string      $function
432
-        *    @return    object
433
-        *    @method    boolean     setUploadFunction
434
-        */
435
-        public function setUploadFunction($function)
436
-        {
437
-            if (!empty($function) && (is_array($function) || is_string($function) )) {
438
-                if (is_callable( $function)) {
439
-                    $this->upload_function = $function;
440
-                }
441
-            }
442
-            return $this;
443
-        }
444
-        /**
445
-        *    Clear allowed mime types cache
446
-        *
447
-        *    @since     1.0
448
-        *    @version   1.0
449
-        *    @return    object
450
-        *    @method    boolean    clearAllowedMimeTypes
451
-        */
452
-        public function clearAllowedMimeTypes()
453
-        {
454
-            $this->allowed_mime_types = array();
455
-            $this->file['allowed_mime_types'] = array();
456
-            return $this;
457
-        }
458
-        /**
459
-        *    Set destination output
460
-        *
461
-        *    @since     1.0
462
-        *    @version   1.0
463
-        *    @param     string      $destination_directory      Destination path
464
-        *    @param     boolean     $create_if_not_exist
465
-        *    @return    object
466
-        *    @method    boolean     setDestinationDirectory
467
-        */
468
-        public function setDestinationDirectory($destination_directory, $create_if_not_exist = false) {
469
-            $destination_directory = realpath($destination_directory);
470
-            if (substr($destination_directory, -1) != DIRECTORY_SEPARATOR) {
471
-                $destination_directory .= DIRECTORY_SEPARATOR;
472
-            }
473
-
474
-            if ($this->isDirpath($destination_directory)) {
475
-                if ($this->dirExists($destination_directory)) {
476
-                    $this->destination_directory = $destination_directory;
477
-                    chdir($destination_directory);
478
-                } else if ($create_if_not_exist === true) {
479
-                    if (mkdir($destination_directory, 0775, true)) {
480
-                        $this->destination_directory = $destination_directory;
481
-                        chdir($destination_directory);
482
-                    }
483
-                    else{
484
-                        $this->logger->warning('Can not create the upload directory [' .$destination_directory. ']');
485
-                    }
486
-                }
487
-            }
488
-            return $this;
489
-        }
490
-        /**
491
-        *    Check file exists
492
-        *
493
-        *    @since      1.0
494
-        *    @version    1.0.1
495
-        *    @param      string     $file_destination
496
-        *    @return     boolean
497
-        *    @method     boolean    fileExists
498
-        */
499
-        public function fileExists($file_destination)
500
-        {
501
-            if ($this->isFilename($file_destination)) {
502
-                return (file_exists($file_destination) && is_file($file_destination));
503
-            }
504
-            return false;
505
-        }
506
-        /**
507
-        *    Check dir exists
508
-        *
509
-        *    @since        1.0
510
-        *    @version    1.0.1
511
-        *    @param      string     $path
512
-        *    @return     boolean
513
-        *    @method     boolean    dirExists
514
-        */
515
-        public function dirExists($path)
516
-        {
517
-            if ($this->isDirpath($path)) {
518
-                return (file_exists($path) && is_dir($path));
519
-            }
520
-            return false;
521
-        }
522
-        /**
523
-        *    Check valid filename
524
-        *
525
-        *    @since     1.0
526
-        *    @version   1.0.1
527
-        *    @param     string      $filename
528
-        *    @return    boolean
529
-        *    @method    boolean     isFilename
530
-        */
531
-        public function isFilename($filename)
532
-        {
533
-            $filename = basename($filename);
534
-            return (!empty($filename) && (is_string( $filename) || is_numeric($filename)));
535
-        }
536
-        /**
537
-        *    Validate mime type with allowed mime types,
538
-        *    but if allowed mime types is empty, this method return true
539
-        *
540
-        *    @since     1.0
541
-        *    @version   1.0
542
-        *    @param     string      $mime
543
-        *    @return    boolean
544
-        *    @method    boolean     checkMimeType
545
-        */
546
-        public function checkMimeType($mime)
547
-        {
548
-            if (count($this->allowed_mime_types) == 0) {
549
-                return true;
550
-            }
551
-            return in_array(strtolower($mime), $this->allowed_mime_types);
552
-        }
553
-        /**
554
-        *    Retrive status of upload
555
-        *
556
-        *    @since     1.0
557
-        *    @version   1.0
558
-        *    @return    boolean
559
-        *    @method    boolean    getStatus
560
-        */
561
-        public function getStatus()
562
-        {
563
-            return $this->file['status'];
564
-        }
565
-        /**
566
-        *    Check valid path
567
-        *
568
-        *    @since        1.0
569
-        *    @version    1.0.1
570
-        *    @param        string    $filename
571
-        *    @return     boolean
572
-        *    @method     boolean    isDirpath
573
-        */
574
-        public function isDirpath($path)
575
-        {
576
-            if (!empty( $path) && (is_string( $path) || is_numeric($path) )) {
577
-                if (DIRECTORY_SEPARATOR == '/') {
578
-                    return (preg_match( '/^[^*?"<>|:]*$/' , $path) == 1 );
579
-                } else {
580
-                    return (preg_match( "/^[^*?\"<>|:]*$/" , substr($path,2) ) == 1);
581
-                }
582
-            }
583
-            return false;
584
-        }
585
-        /**
586
-        *    Allow overwriting files
587
-        *
588
-        *    @since      1.0
589
-        *    @version    1.0
590
-        *    @return     object
591
-        *    @method     boolean    allowOverwriting
592
-        */
593
-        public function allowOverwriting()
594
-        {
595
-            $this->overwrite_file = true;
596
-            return $this;
597
-        }
598
-        /**
599
-        *    File info
600
-        *
601
-        *    @since      1.0
602
-        *    @version    1.0
603
-        *    @return     object
604
-        *    @method     object    getInfo
605
-        */
606
-        public function getInfo()
607
-        {
608
-            return (object)$this->file;
609
-        }
610
-
611
-        public function isUploaded(){
612
-            return isset($this->file_array[$this->input])
613
-            &&
614
-            is_uploaded_file($this->file_array[$this->input]['tmp_name']);
615
-        }
616
-        /**
617
-        *    Upload file
618
-        *
619
-        *    @since     1.0
620
-        *    @version   1.0.1
621
-        *    @return    boolean
622
-        *    @method    boolean    save
623
-        */
624
-        public function save(){
625
-            //check if file upload is  allowed in the configuration
626
-            if(! ini_get('file_uploads')){
627
-                $this->setError($this->error_messages['file_uploads']);
628
-                return false;
629
-            }
630
-            if (count($this->file_array) > 0) {
631
-                if (array_key_exists($this->input, $this->file_array)) {
632
-                    // set original filename if not have a new name
633
-                    if (empty($this->filename)) {
634
-                        $this->filename = $this->file_array[$this->input]['name'];
635
-                    }
636
-                    else{
637
-                        // Replace %s for extension in filename
638
-                        // Before: /[\w\d]*(.[\d\w]+)$/i
639
-                        // After: /^[\s[:alnum:]\-\_\.]*\.([\d\w]+)$/iu
640
-                        // Support unicode(utf-8) characters
641
-                        // Example: "русские.jpeg" is valid; "Zhōngguó.jpeg" is valid; "Tønsberg.jpeg" is valid
642
-                        $extension = preg_replace(
643
-                            '/^[\p{L}\d\s\-\_\.\(\)]*\.([\d\w]+)$/iu',
644
-                            '$1',
645
-                            $this->file_array[$this->input]['name']
646
-                        );
647
-                        $this->filename = $this->filename . '.' . $extension;
648
-                    }
649
-
650
-                    // set file info
651
-                    $this->file['mime']         = $this->file_array[$this->input]['type'];
652
-                    $this->file['tmp']          = $this->file_array[$this->input]['tmp_name'];
653
-                    $this->file['original']     = $this->file_array[$this->input]['name'];
654
-                    $this->file['size']         = $this->file_array[$this->input]['size'];
655
-                    $this->file['sizeFormated'] = $this->sizeFormat($this->file['size']);
656
-                    $this->file['destination']  = $this->destination_directory . $this->filename;
657
-                    $this->file['filename']     = $this->filename;
658
-                    $this->file['error']        = $this->file_array[$this->input]['error'];
659
-
660
-                    $this->logger->info('The upload file information to process is : ' .stringfy_vars($this->file));
661
-
662
-                    //check for php upload error
663
-                    if(is_numeric($this->file['error']) && $this->file['error'] > 0){
664
-                        $this->setError($this->getPhpUploadErrorMessageByCode($this->file['error']));
665
-                        return false;
666
-                    }
2
+	defined('ROOT_PATH') or exit('Access denied');
3
+	/**
4
+	 * TNH Framework
5
+	 *
6
+	 * A simple PHP framework using HMVC architecture
7
+	 *
8
+	 * This content is released under the GNU GPL License (GPL)
9
+	 *
10
+	 * Copyright (C) 2017 Tony NGUEREZA
11
+	 *
12
+	 * This program is free software; you can redistribute it and/or
13
+	 * modify it under the terms of the GNU General Public License
14
+	 * as published by the Free Software Foundation; either version 3
15
+	 * of the License, or (at your option) any later version.
16
+	 *
17
+	 * This program is distributed in the hope that it will be useful,
18
+	 * but WITHOUT ANY WARRANTY; without even the implied warranty of
19
+	 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20
+	 * GNU General Public License for more details.
21
+	 *
22
+	 * You should have received a copy of the GNU General Public License
23
+	 * along with this program; if not, write to the Free Software
24
+	 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
25
+	 */
26
+
27
+
28
+
29
+	/**
30
+	 *    Upload
31
+	 *
32
+	 *    A complete class to upload files with php 5 or higher, but the best: very simple to use.
33
+	 *
34
+	 *    @author Olaf Erlandsen <[email protected]>
35
+	 *    @author http://www.webdevfreelance.com/
36
+	 *
37
+	 *    @package FileUpload
38
+	 *    @version 1.5
39
+	 */
40
+	class Upload{
41
+
42
+		/**
43
+		 *   Version
44
+		 *
45
+		 *   @since      1.5
46
+		 *   @version    1.0
47
+		 */
48
+		const VERSION = '1.5';
49
+
50
+		/**
51
+		 *    Upload function name
52
+		 *    Remember:
53
+		 *        Default function: move_uploaded_file
54
+		 *        Native options:
55
+		 *            - move_uploaded_file (Default and best option)
56
+		 *            - copy
57
+		 *
58
+		 *    @since        1.0
59
+		 *    @version    1.0
60
+		 *    @var        string
61
+		 */
62
+		private $upload_function = 'move_uploaded_file';
63
+
64
+		/**
65
+		 *    Array with the information obtained from the
66
+		 *    variable $_FILES or $HTTP_POST_FILES.
67
+		 *
68
+		 *    @since        1.0
69
+		 *    @version    1.0
70
+		 *    @var        array
71
+		 */
72
+		private $file_array    = array();
73
+
74
+		/**
75
+		 *    If the file you are trying to upload already exists it will
76
+		 *    be overwritten if you set the variable to true.
77
+		 *
78
+		 *    @since        1.0
79
+		 *    @version    1.0
80
+		 *    @var        boolean
81
+		 */
82
+		private $overwrite_file = false;
83
+
84
+		/**
85
+		 *    Input element
86
+		 *    Example:
87
+		 *        <input type="file" name="file" />
88
+		 *    Result:
89
+		 *        FileUpload::$input = file
90
+		 *
91
+		 *    @since        1.0
92
+		 *    @version    1.0
93
+		 *    @var        string
94
+		 */
95
+		private $input;
96
+
97
+		/**
98
+		 *    Path output
99
+		 *
100
+		 *    @since        1.0
101
+		 *    @version    1.0
102
+		 *    @var        string
103
+		 */
104
+		private $destination_directory;
105
+
106
+		/**
107
+		 *    Output filename
108
+		 *
109
+		 *    @since        1.0
110
+		 *    @version    1.0
111
+		 *    @var        string
112
+		 */
113
+		private $filename;
114
+
115
+		/**
116
+		 *    Max file size
117
+		 *
118
+		 *    @since        1.0
119
+		 *    @version    1.0
120
+		 *    @var        float
121
+		 */
122
+		private $max_file_size= 0.0;
123
+
124
+		/**
125
+		 *    List of allowed mime types
126
+		 *
127
+		 *    @since        1.0
128
+		 *    @version    1.0
129
+		 *    @var        array
130
+		 */
131
+		private $allowed_mime_types = array();
132
+
133
+		/**
134
+		 *    Callbacks
135
+		 *
136
+		 *    @since        1.0
137
+		 *    @version    1.0
138
+		 *    @var        array
139
+		 */
140
+		private $callbacks = array('before' => null, 'after' => null);
141
+
142
+		/**
143
+		 *    File object
144
+		 *
145
+		 *    @since        1.0
146
+		 *    @version    1.0
147
+		 *    @var        object
148
+		 */
149
+		private $file;
150
+
151
+		/**
152
+		 *    Helping mime types
153
+		 *
154
+		 *    @since        1.0
155
+		 *    @version    1.0
156
+		 *    @var        array
157
+		 */
158
+		private $mime_helping = array(
159
+			'text'      =>    array('text/plain',),
160
+			'image'     =>    array(
161
+				'image/jpeg',
162
+				'image/jpg',
163
+				'image/pjpeg',
164
+				'image/png',
165
+				'image/gif',
166
+			),
167
+			'document'  =>    array(
168
+				'application/pdf',
169
+				'application/msword',
170
+				'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
171
+				'application/vnd.openxmlformats-officedocument.presentationml.presentation',
172
+				'application/vnd.ms-powerpoint',
173
+				'application/vnd.ms-excel',
174
+				'application/vnd.oasis.opendocument.spreadsheet',
175
+				'application/vnd.oasis.opendocument.presentation',
176
+			),
177
+			'video'    =>    array(
178
+				'video/3gpp',
179
+				'video/3gpp',
180
+				'video/x-msvideo',
181
+				'video/avi',
182
+				'video/mpeg4',
183
+				'video/mp4',
184
+				'video/mpeg',
185
+				'video/mpg',
186
+				'video/quicktime',
187
+				'video/x-sgi-movie',
188
+				'video/x-ms-wmv',
189
+				'video/x-flv',
190
+			),
191
+		);
192
+
193
+		/**
194
+		 * The upload error message
195
+		 * @var array
196
+		 */
197
+		public $error_messages = array();
198
+
199
+		/**
200
+		 * The upload error message
201
+		 * @var string
202
+		 */
203
+		protected $error = null;
204
+
205
+		/**
206
+		 * The logger instance
207
+		 * @var Log
208
+		 */
209
+		private $logger;
210
+
211
+
212
+		/**
213
+		 *    Construct
214
+		 *
215
+		 *    @since     0.1
216
+		 *    @version   1.0.1
217
+		 *    @return    object
218
+		 *    @method    object    __construct
219
+		 */
220
+		public function __construct(){
221
+			$this->logger =& class_loader('Log', 'classes');
222
+			$this->logger->setLogger('Library::Upload');
223
+
224
+			Loader::lang('file_upload');
225
+			$obj =& get_instance();
226
+
227
+			$this->error_messages = array(
228
+				'upload_err_ini_size' => $obj->lang->get('fu_upload_err_ini_size'),
229
+				'upload_err_form_size' => $obj->lang->get('fu_upload_err_form_size'),
230
+				'upload_err_partial' => $obj->lang->get('fu_upload_err_partial'),
231
+				'upload_err_no_file' => $obj->lang->get('fu_upload_err_no_file'),
232
+				'upload_err_no_tmp_dir' => $obj->lang->get('fu_upload_err_no_tmp_dir'),
233
+				'upload_err_cant_write' => $obj->lang->get('fu_upload_err_cant_write'),
234
+				'upload_err_extension' => $obj->lang->get('fu_upload_err_extension'),
235
+				'accept_file_types' => $obj->lang->get('fu_accept_file_types'),
236
+				'file_uploads' => $obj->lang->get('fu_file_uploads_disabled'),
237
+				'max_file_size' => $obj->lang->get('fu_max_file_size'),
238
+				'overwritten_not_allowed' => $obj->lang->get('fu_overwritten_not_allowed'),
239
+			);
240
+
241
+			$this->file = array(
242
+				'status'                =>    false,    // True: success upload
243
+				'mime'                  =>    '',       // Empty string
244
+				'filename'              =>    '',       // Empty string
245
+				'original'              =>    '',       // Empty string
246
+				'size'                  =>    0,        // 0 Bytes
247
+				'sizeFormated'          =>    '0B',     // 0 Bytes
248
+				'destination'           =>    './',     // Default: ./
249
+				'allowed_mime_types'    =>    array(),  // Allowed mime types
250
+				'error'                 =>    null,        // File error
251
+			);
252
+
253
+			// Change dir to current dir
254
+			$this->destination_directory = dirname(__FILE__) . DIRECTORY_SEPARATOR;
255
+
256
+			// Set file array
257
+			if (isset($_FILES) && is_array($_FILES)) {
258
+				$this->file_array = $_FILES;
259
+			} elseif (isset($HTTP_POST_FILES) && is_array($HTTP_POST_FILES)) {
260
+				$this->file_array = $HTTP_POST_FILES;
261
+			}
262
+			$this->logger->info('The upload file information are : ' .stringfy_vars($this->file_array));
263
+		}
264
+		/**
265
+		 *    Set input.
266
+		 *    If you have $_FILES["file"], you must use the key "file"
267
+		 *    Example:
268
+		 *        $object->setInput("file");
269
+		 *
270
+		 *    @since     1.0
271
+		 *    @version   1.0
272
+		 *    @param     string      $input
273
+		 *    @return    object
274
+		 *    @method    boolean     setInput
275
+		 */
276
+		public function setInput($input)
277
+		{
278
+			if (!empty($input) && (is_string($input) || is_numeric($input) )) {
279
+				$this->input = $input;
280
+			}
281
+			return $this;
282
+		}
283
+		/**
284
+		 *    Set new filename
285
+		 *    Example:
286
+		 *        FileUpload::setFilename("new file.txt")
287
+		 *    Remember:
288
+		 *        Use %s to retrive file extension
289
+		 *
290
+		 *    @since     1.0
291
+		 *    @version   1.0
292
+		 *    @param     string      $filename
293
+		 *    @return    object
294
+		 *    @method    boolean     setFilename
295
+		 */
296
+		public function setFilename($filename)
297
+		{
298
+			if ($this->isFilename($filename)) {
299
+				$this->filename = $filename;
300
+			}
301
+			return $this;
302
+		}
303
+		/**
304
+		 *    Set automatic filename
305
+		 *
306
+		 *    @since     1.0
307
+		 *    @version   1.5
308
+		 *    @param     string      $extension
309
+		 *    @return    object
310
+		 *    @method    boolean     setAutoFilename
311
+		 */
312
+		public function setAutoFilename()
313
+		{
314
+			$this->filename = sha1(mt_rand(1, 9999).uniqid());
315
+			$this->filename .= time();
316
+			return $this;
317
+		}
318
+		/**
319
+		 *    Set file size limit
320
+		 *
321
+		 *    @since     1.0
322
+		 *    @version   1.0
323
+		 *    @param     double     $file_size
324
+		 *    @return    object
325
+		 *    @method    boolean     setMaxFileSize
326
+		 */
327
+		public function setMaxFileSize($file_size)
328
+		{
329
+			$file_size = $this->sizeInBytes($file_size);
330
+			if (is_numeric($file_size) && $file_size > -1) {
331
+				// Get php config
332
+				$php_size = $this->sizeInBytes((int) ini_get('upload_max_filesize'));
333
+				// Calculate difference
334
+				if ($php_size < $file_size) {
335
+					$this->logger->warning('The upload max file size you set [' .$file_size. '] is greather than the PHP configuration for upload max file size [' .$php_size. ']');
336
+				}
337
+				$this->max_file_size = $file_size;
338
+			}
339
+			return $this;
340
+		}
341
+		/**
342
+		 *    Set array mime types
343
+		 *
344
+		 *    @since     1.0
345
+		 *    @version   1.0
346
+		 *    @param     array       $mimes
347
+		 *    @return    object
348
+		 *    @method    boolean     setAllowedMimeTypes
349
+		 */
350
+		public function setAllowedMimeTypes(array $mimes)
351
+		{
352
+			if (count($mimes) > 0) {
353
+				array_map(array($this , 'setAllowMimeType'), $mimes);
354
+			}
355
+			return $this;
356
+		}
357
+		/**
358
+		 *    Set input callback
359
+		 *
360
+		 *    @since     1.0
361
+		 *    @version   1.0
362
+		 *    @param     mixed       $callback
363
+		 *    @return    object
364
+		 *    @method    boolean     setCallbackInput
365
+		 */
366
+		public function setCallbackInput($callback)
367
+		{
368
+			if (is_callable($callback, false)) {
369
+				$this->callbacks['input'] = $callback;
370
+			}
371
+			return $this;
372
+		}
373
+		/**
374
+		 *    Set output callback
375
+		 *
376
+		 *    @since     1.0
377
+		 *    @version   1.0
378
+		 *    @param     mixed       $callback
379
+		 *    @return    object
380
+		 *    @method    boolean     setCallbackOutput
381
+		 */
382
+		public function setCallbackOutput($callback)
383
+		{
384
+			if (is_callable($callback, false)) {
385
+				$this->callbacks['output'] = $callback;
386
+			}
387
+			return $this;
388
+		}
389
+		/**
390
+		 *    Append a mime type to allowed mime types
391
+		 *
392
+		 *    @since     1.0
393
+		 *    @version   1.0.1
394
+		 *    @param     string      $mime
395
+		 *    @return    object
396
+		 *    @method    boolean     setAllowMimeType
397
+		 */
398
+		public function setAllowMimeType($mime)
399
+		{
400
+			if (!empty($mime) && is_string($mime)) {
401
+				$this->allowed_mime_types[] = strtolower($mime);
402
+				$this->file['allowed_mime_types'][] = strtolower($mime);
403
+			} 
404
+			return $this;
405
+		}
406
+		/**
407
+		 *    Set allowed mime types from mime helping
408
+		 *
409
+		 *    @since     1.0.1
410
+		 *    @version   1.0.1
411
+		 *    @return    object
412
+		 *    @method    boolean    setMimeHelping
413
+		 */
414
+		public function setMimeHelping($name)
415
+		{
416
+			if (!empty($name) && is_string($name)) {
417
+				if (array_key_exists($name, $this->mime_helping)) {
418
+					return $this->setAllowedMimeTypes($this->mime_helping[ $name ]);
419
+				}
420
+			}
421
+			return $this;
422
+		}
423
+		/**
424
+		 *    Set function to upload file
425
+		 *    Examples:
426
+		 *        1.- FileUpload::setUploadFunction("move_uploaded_file");
427
+		 *        2.- FileUpload::setUploadFunction("copy");
428
+		 *
429
+		 *    @since     1.0
430
+		 *    @version   1.0
431
+		 *    @param     string      $function
432
+		 *    @return    object
433
+		 *    @method    boolean     setUploadFunction
434
+		 */
435
+		public function setUploadFunction($function)
436
+		{
437
+			if (!empty($function) && (is_array($function) || is_string($function) )) {
438
+				if (is_callable( $function)) {
439
+					$this->upload_function = $function;
440
+				}
441
+			}
442
+			return $this;
443
+		}
444
+		/**
445
+		 *    Clear allowed mime types cache
446
+		 *
447
+		 *    @since     1.0
448
+		 *    @version   1.0
449
+		 *    @return    object
450
+		 *    @method    boolean    clearAllowedMimeTypes
451
+		 */
452
+		public function clearAllowedMimeTypes()
453
+		{
454
+			$this->allowed_mime_types = array();
455
+			$this->file['allowed_mime_types'] = array();
456
+			return $this;
457
+		}
458
+		/**
459
+		 *    Set destination output
460
+		 *
461
+		 *    @since     1.0
462
+		 *    @version   1.0
463
+		 *    @param     string      $destination_directory      Destination path
464
+		 *    @param     boolean     $create_if_not_exist
465
+		 *    @return    object
466
+		 *    @method    boolean     setDestinationDirectory
467
+		 */
468
+		public function setDestinationDirectory($destination_directory, $create_if_not_exist = false) {
469
+			$destination_directory = realpath($destination_directory);
470
+			if (substr($destination_directory, -1) != DIRECTORY_SEPARATOR) {
471
+				$destination_directory .= DIRECTORY_SEPARATOR;
472
+			}
473
+
474
+			if ($this->isDirpath($destination_directory)) {
475
+				if ($this->dirExists($destination_directory)) {
476
+					$this->destination_directory = $destination_directory;
477
+					chdir($destination_directory);
478
+				} else if ($create_if_not_exist === true) {
479
+					if (mkdir($destination_directory, 0775, true)) {
480
+						$this->destination_directory = $destination_directory;
481
+						chdir($destination_directory);
482
+					}
483
+					else{
484
+						$this->logger->warning('Can not create the upload directory [' .$destination_directory. ']');
485
+					}
486
+				}
487
+			}
488
+			return $this;
489
+		}
490
+		/**
491
+		 *    Check file exists
492
+		 *
493
+		 *    @since      1.0
494
+		 *    @version    1.0.1
495
+		 *    @param      string     $file_destination
496
+		 *    @return     boolean
497
+		 *    @method     boolean    fileExists
498
+		 */
499
+		public function fileExists($file_destination)
500
+		{
501
+			if ($this->isFilename($file_destination)) {
502
+				return (file_exists($file_destination) && is_file($file_destination));
503
+			}
504
+			return false;
505
+		}
506
+		/**
507
+		 *    Check dir exists
508
+		 *
509
+		 *    @since        1.0
510
+		 *    @version    1.0.1
511
+		 *    @param      string     $path
512
+		 *    @return     boolean
513
+		 *    @method     boolean    dirExists
514
+		 */
515
+		public function dirExists($path)
516
+		{
517
+			if ($this->isDirpath($path)) {
518
+				return (file_exists($path) && is_dir($path));
519
+			}
520
+			return false;
521
+		}
522
+		/**
523
+		 *    Check valid filename
524
+		 *
525
+		 *    @since     1.0
526
+		 *    @version   1.0.1
527
+		 *    @param     string      $filename
528
+		 *    @return    boolean
529
+		 *    @method    boolean     isFilename
530
+		 */
531
+		public function isFilename($filename)
532
+		{
533
+			$filename = basename($filename);
534
+			return (!empty($filename) && (is_string( $filename) || is_numeric($filename)));
535
+		}
536
+		/**
537
+		 *    Validate mime type with allowed mime types,
538
+		 *    but if allowed mime types is empty, this method return true
539
+		 *
540
+		 *    @since     1.0
541
+		 *    @version   1.0
542
+		 *    @param     string      $mime
543
+		 *    @return    boolean
544
+		 *    @method    boolean     checkMimeType
545
+		 */
546
+		public function checkMimeType($mime)
547
+		{
548
+			if (count($this->allowed_mime_types) == 0) {
549
+				return true;
550
+			}
551
+			return in_array(strtolower($mime), $this->allowed_mime_types);
552
+		}
553
+		/**
554
+		 *    Retrive status of upload
555
+		 *
556
+		 *    @since     1.0
557
+		 *    @version   1.0
558
+		 *    @return    boolean
559
+		 *    @method    boolean    getStatus
560
+		 */
561
+		public function getStatus()
562
+		{
563
+			return $this->file['status'];
564
+		}
565
+		/**
566
+		 *    Check valid path
567
+		 *
568
+		 *    @since        1.0
569
+		 *    @version    1.0.1
570
+		 *    @param        string    $filename
571
+		 *    @return     boolean
572
+		 *    @method     boolean    isDirpath
573
+		 */
574
+		public function isDirpath($path)
575
+		{
576
+			if (!empty( $path) && (is_string( $path) || is_numeric($path) )) {
577
+				if (DIRECTORY_SEPARATOR == '/') {
578
+					return (preg_match( '/^[^*?"<>|:]*$/' , $path) == 1 );
579
+				} else {
580
+					return (preg_match( "/^[^*?\"<>|:]*$/" , substr($path,2) ) == 1);
581
+				}
582
+			}
583
+			return false;
584
+		}
585
+		/**
586
+		 *    Allow overwriting files
587
+		 *
588
+		 *    @since      1.0
589
+		 *    @version    1.0
590
+		 *    @return     object
591
+		 *    @method     boolean    allowOverwriting
592
+		 */
593
+		public function allowOverwriting()
594
+		{
595
+			$this->overwrite_file = true;
596
+			return $this;
597
+		}
598
+		/**
599
+		 *    File info
600
+		 *
601
+		 *    @since      1.0
602
+		 *    @version    1.0
603
+		 *    @return     object
604
+		 *    @method     object    getInfo
605
+		 */
606
+		public function getInfo()
607
+		{
608
+			return (object)$this->file;
609
+		}
610
+
611
+		public function isUploaded(){
612
+			return isset($this->file_array[$this->input])
613
+			&&
614
+			is_uploaded_file($this->file_array[$this->input]['tmp_name']);
615
+		}
616
+		/**
617
+		 *    Upload file
618
+		 *
619
+		 *    @since     1.0
620
+		 *    @version   1.0.1
621
+		 *    @return    boolean
622
+		 *    @method    boolean    save
623
+		 */
624
+		public function save(){
625
+			//check if file upload is  allowed in the configuration
626
+			if(! ini_get('file_uploads')){
627
+				$this->setError($this->error_messages['file_uploads']);
628
+				return false;
629
+			}
630
+			if (count($this->file_array) > 0) {
631
+				if (array_key_exists($this->input, $this->file_array)) {
632
+					// set original filename if not have a new name
633
+					if (empty($this->filename)) {
634
+						$this->filename = $this->file_array[$this->input]['name'];
635
+					}
636
+					else{
637
+						// Replace %s for extension in filename
638
+						// Before: /[\w\d]*(.[\d\w]+)$/i
639
+						// After: /^[\s[:alnum:]\-\_\.]*\.([\d\w]+)$/iu
640
+						// Support unicode(utf-8) characters
641
+						// Example: "русские.jpeg" is valid; "Zhōngguó.jpeg" is valid; "Tønsberg.jpeg" is valid
642
+						$extension = preg_replace(
643
+							'/^[\p{L}\d\s\-\_\.\(\)]*\.([\d\w]+)$/iu',
644
+							'$1',
645
+							$this->file_array[$this->input]['name']
646
+						);
647
+						$this->filename = $this->filename . '.' . $extension;
648
+					}
649
+
650
+					// set file info
651
+					$this->file['mime']         = $this->file_array[$this->input]['type'];
652
+					$this->file['tmp']          = $this->file_array[$this->input]['tmp_name'];
653
+					$this->file['original']     = $this->file_array[$this->input]['name'];
654
+					$this->file['size']         = $this->file_array[$this->input]['size'];
655
+					$this->file['sizeFormated'] = $this->sizeFormat($this->file['size']);
656
+					$this->file['destination']  = $this->destination_directory . $this->filename;
657
+					$this->file['filename']     = $this->filename;
658
+					$this->file['error']        = $this->file_array[$this->input]['error'];
659
+
660
+					$this->logger->info('The upload file information to process is : ' .stringfy_vars($this->file));
661
+
662
+					//check for php upload error
663
+					if(is_numeric($this->file['error']) && $this->file['error'] > 0){
664
+						$this->setError($this->getPhpUploadErrorMessageByCode($this->file['error']));
665
+						return false;
666
+					}
667 667
                     
668
-                    //check for mime type
669
-                    if (!$this->checkMimeType($this->file['mime'])) {
670
-                        $this->setError($this->error_messages['accept_file_types']);
671
-                        return false;
672
-                    }
673
-
674
-                     // Check file size
675
-                    if ($this->max_file_size > 0) {
676
-                        if ($this->max_file_size < $this->file['size']) {
677
-                            $this->setError(sprintf($this->error_messages['max_file_size'], $this->sizeFormat($this->max_file_size)));
678
-                            return false;
679
-                        }
680
-                    }
681
-
682
-                    // Check if exists file
683
-                    if ($this->fileExists($this->destination_directory . $this->filename) && $this->overwrite_file === false) {
684
-                        $this->setError($this->error_messages['overwritten_not_allowed']);
685
-                        return false;
686
-                    }
687
-
688
-                    // Execute input callback
689
-                    if (!empty( $this->callbacks['input'])) {
690
-                        call_user_func($this->callbacks['input'], (object)$this->file);
691
-                    }
668
+					//check for mime type
669
+					if (!$this->checkMimeType($this->file['mime'])) {
670
+						$this->setError($this->error_messages['accept_file_types']);
671
+						return false;
672
+					}
673
+
674
+					 // Check file size
675
+					if ($this->max_file_size > 0) {
676
+						if ($this->max_file_size < $this->file['size']) {
677
+							$this->setError(sprintf($this->error_messages['max_file_size'], $this->sizeFormat($this->max_file_size)));
678
+							return false;
679
+						}
680
+					}
681
+
682
+					// Check if exists file
683
+					if ($this->fileExists($this->destination_directory . $this->filename) && $this->overwrite_file === false) {
684
+						$this->setError($this->error_messages['overwritten_not_allowed']);
685
+						return false;
686
+					}
687
+
688
+					// Execute input callback
689
+					if (!empty( $this->callbacks['input'])) {
690
+						call_user_func($this->callbacks['input'], (object)$this->file);
691
+					}
692 692
                    
693 693
 
694
-                    $this->file['status'] = call_user_func_array(
695
-                        $this->upload_function, array(
696
-                            $this->file_array[$this->input]['tmp_name'],
697
-                            $this->destination_directory . $this->filename
698
-                        )
699
-                    );
700
-
701
-                    // Execute output callback
702
-                    if (!empty( $this->callbacks['output'])) {
703
-                        call_user_func($this->callbacks['output'], (object)$this->file);
704
-                    }
705
-                    return $this->file['status'];
706
-                }
707
-            }
708
-        }
709
-
710
-        /**
711
-        *    File size for humans.
712
-        *
713
-        *    @since      1.0
714
-        *    @version    1.0
715
-        *    @param      integer    $bytes
716
-        *    @param      integer    $precision
717
-        *    @return     string
718
-        *    @method     string     sizeFormat
719
-        */
720
-        public function sizeFormat($size, $precision = 2)
721
-        {
722
-            if($size > 0){
723
-                $base       = log($size) / log(1024);
724
-                $suffixes   = array('B', 'K', 'M', 'G', 'T');
725
-                return round(pow(1024, $base - floor($base)), $precision) . ( isset($suffixes[floor($base)]) ? $suffixes[floor($base)] : '');
726
-            }
727
-            return null;
728
-        }
694
+					$this->file['status'] = call_user_func_array(
695
+						$this->upload_function, array(
696
+							$this->file_array[$this->input]['tmp_name'],
697
+							$this->destination_directory . $this->filename
698
+						)
699
+					);
700
+
701
+					// Execute output callback
702
+					if (!empty( $this->callbacks['output'])) {
703
+						call_user_func($this->callbacks['output'], (object)$this->file);
704
+					}
705
+					return $this->file['status'];
706
+				}
707
+			}
708
+		}
709
+
710
+		/**
711
+		 *    File size for humans.
712
+		 *
713
+		 *    @since      1.0
714
+		 *    @version    1.0
715
+		 *    @param      integer    $bytes
716
+		 *    @param      integer    $precision
717
+		 *    @return     string
718
+		 *    @method     string     sizeFormat
719
+		 */
720
+		public function sizeFormat($size, $precision = 2)
721
+		{
722
+			if($size > 0){
723
+				$base       = log($size) / log(1024);
724
+				$suffixes   = array('B', 'K', 'M', 'G', 'T');
725
+				return round(pow(1024, $base - floor($base)), $precision) . ( isset($suffixes[floor($base)]) ? $suffixes[floor($base)] : '');
726
+			}
727
+			return null;
728
+		}
729 729
 
730 730
         
731
-        /**
732
-        *    Convert human file size to bytes
733
-        *
734
-        *    @since      1.0
735
-        *    @version    1.0.1
736
-        *    @param      integer|double    $size
737
-        *    @return     integer|double
738
-        *    @method     string     sizeInBytes
739
-        */
740
-        public function sizeInBytes($size)
741
-        {
742
-            $unit = 'B';
743
-            $units = array('B' => 0, 'K' => 1, 'M' => 2, 'G' => 3, 'T' => 4);
744
-            $matches = array();
745
-            preg_match('/(?<size>[\d\.]+)\s*(?<unit>b|k|m|g|t)?/i', $size, $matches);
746
-            if (array_key_exists('unit', $matches)) {
747
-                $unit = strtoupper($matches['unit']);
748
-            }
749
-            return (floatval($matches['size']) * pow(1024, $units[$unit]) ) ;
750
-        }
751
-
752
-        /**
753
-         * Get the upload error message
754
-         * @return string
755
-         */
756
-        public function getError(){
757
-            return $this->error;
758
-        }
759
-
760
-        /**
761
-         * Set the upload error message
762
-         * @param string $message the upload error message to set
763
-         */
764
-        public function setError($message){
765
-            $this->logger->info('The upload got error : ' . $message);
766
-            $this->error = $message;
767
-        }
768
-
769
-        /**
770
-         * Get the PHP upload error message for the given code
771
-         * @param  int $code the error code
772
-         * @return string the error message
773
-         */
774
-        private function getPhpUploadErrorMessageByCode($code){
775
-            $codeMessageMaps = array(
776
-                1 => $this->error_messages['upload_err_ini_size'],
777
-                2 => $this->error_messages['upload_err_form_size'],
778
-                3 => $this->error_messages['upload_err_partial'],
779
-                4 => $this->error_messages['upload_err_no_file'],
780
-                6 => $this->error_messages['upload_err_no_tmp_dir'],
781
-                7 => $this->error_messages['upload_err_cant_write'],
782
-                8 => $this->error_messages['upload_err_extension'],
783
-            );
784
-            return isset($codeMessageMaps[$code]) ? $codeMessageMaps[$code] : null;
785
-        }
786
-    }
731
+		/**
732
+		 *    Convert human file size to bytes
733
+		 *
734
+		 *    @since      1.0
735
+		 *    @version    1.0.1
736
+		 *    @param      integer|double    $size
737
+		 *    @return     integer|double
738
+		 *    @method     string     sizeInBytes
739
+		 */
740
+		public function sizeInBytes($size)
741
+		{
742
+			$unit = 'B';
743
+			$units = array('B' => 0, 'K' => 1, 'M' => 2, 'G' => 3, 'T' => 4);
744
+			$matches = array();
745
+			preg_match('/(?<size>[\d\.]+)\s*(?<unit>b|k|m|g|t)?/i', $size, $matches);
746
+			if (array_key_exists('unit', $matches)) {
747
+				$unit = strtoupper($matches['unit']);
748
+			}
749
+			return (floatval($matches['size']) * pow(1024, $units[$unit]) ) ;
750
+		}
751
+
752
+		/**
753
+		 * Get the upload error message
754
+		 * @return string
755
+		 */
756
+		public function getError(){
757
+			return $this->error;
758
+		}
759
+
760
+		/**
761
+		 * Set the upload error message
762
+		 * @param string $message the upload error message to set
763
+		 */
764
+		public function setError($message){
765
+			$this->logger->info('The upload got error : ' . $message);
766
+			$this->error = $message;
767
+		}
768
+
769
+		/**
770
+		 * Get the PHP upload error message for the given code
771
+		 * @param  int $code the error code
772
+		 * @return string the error message
773
+		 */
774
+		private function getPhpUploadErrorMessageByCode($code){
775
+			$codeMessageMaps = array(
776
+				1 => $this->error_messages['upload_err_ini_size'],
777
+				2 => $this->error_messages['upload_err_form_size'],
778
+				3 => $this->error_messages['upload_err_partial'],
779
+				4 => $this->error_messages['upload_err_no_file'],
780
+				6 => $this->error_messages['upload_err_no_tmp_dir'],
781
+				7 => $this->error_messages['upload_err_cant_write'],
782
+				8 => $this->error_messages['upload_err_extension'],
783
+			);
784
+			return isset($codeMessageMaps[$code]) ? $codeMessageMaps[$code] : null;
785
+		}
786
+	}
Please login to merge, or discard this patch.
Spacing   +46 added lines, -46 removed lines patch added patch discarded remove patch
@@ -37,7 +37,7 @@  discard block
 block discarded – undo
37 37
     *    @package FileUpload
38 38
     *    @version 1.5
39 39
     */
40
-    class Upload{
40
+    class Upload {
41 41
 
42 42
         /**
43 43
         *   Version
@@ -69,7 +69,7 @@  discard block
 block discarded – undo
69 69
         *    @version    1.0
70 70
         *    @var        array
71 71
         */
72
-        private $file_array    = array();
72
+        private $file_array = array();
73 73
 
74 74
         /**
75 75
         *    If the file you are trying to upload already exists it will
@@ -119,7 +119,7 @@  discard block
 block discarded – undo
119 119
         *    @version    1.0
120 120
         *    @var        float
121 121
         */
122
-        private $max_file_size= 0.0;
122
+        private $max_file_size = 0.0;
123 123
 
124 124
         /**
125 125
         *    List of allowed mime types
@@ -217,12 +217,12 @@  discard block
 block discarded – undo
217 217
         *    @return    object
218 218
         *    @method    object    __construct
219 219
         */
220
-        public function __construct(){
221
-            $this->logger =& class_loader('Log', 'classes');
220
+        public function __construct() {
221
+            $this->logger = & class_loader('Log', 'classes');
222 222
             $this->logger->setLogger('Library::Upload');
223 223
 
224 224
             Loader::lang('file_upload');
225
-            $obj =& get_instance();
225
+            $obj = & get_instance();
226 226
 
227 227
             $this->error_messages = array(
228 228
                 'upload_err_ini_size' => $obj->lang->get('fu_upload_err_ini_size'),
@@ -239,15 +239,15 @@  discard block
 block discarded – undo
239 239
             );
240 240
 
241 241
             $this->file = array(
242
-                'status'                =>    false,    // True: success upload
243
-                'mime'                  =>    '',       // Empty string
244
-                'filename'              =>    '',       // Empty string
245
-                'original'              =>    '',       // Empty string
246
-                'size'                  =>    0,        // 0 Bytes
247
-                'sizeFormated'          =>    '0B',     // 0 Bytes
248
-                'destination'           =>    './',     // Default: ./
249
-                'allowed_mime_types'    =>    array(),  // Allowed mime types
250
-                'error'                 =>    null,        // File error
242
+                'status'                =>    false, // True: success upload
243
+                'mime'                  =>    '', // Empty string
244
+                'filename'              =>    '', // Empty string
245
+                'original'              =>    '', // Empty string
246
+                'size'                  =>    0, // 0 Bytes
247
+                'sizeFormated'          =>    '0B', // 0 Bytes
248
+                'destination'           =>    './', // Default: ./
249
+                'allowed_mime_types'    =>    array(), // Allowed mime types
250
+                'error'                 =>    null, // File error
251 251
             );
252 252
 
253 253
             // Change dir to current dir
@@ -259,7 +259,7 @@  discard block
 block discarded – undo
259 259
             } elseif (isset($HTTP_POST_FILES) && is_array($HTTP_POST_FILES)) {
260 260
                 $this->file_array = $HTTP_POST_FILES;
261 261
             }
262
-            $this->logger->info('The upload file information are : ' .stringfy_vars($this->file_array));
262
+            $this->logger->info('The upload file information are : ' . stringfy_vars($this->file_array));
263 263
         }
264 264
         /**
265 265
         *    Set input.
@@ -275,7 +275,7 @@  discard block
 block discarded – undo
275 275
         */
276 276
         public function setInput($input)
277 277
         {
278
-            if (!empty($input) && (is_string($input) || is_numeric($input) )) {
278
+            if (!empty($input) && (is_string($input) || is_numeric($input))) {
279 279
                 $this->input = $input;
280 280
             }
281 281
             return $this;
@@ -311,7 +311,7 @@  discard block
 block discarded – undo
311 311
         */
312 312
         public function setAutoFilename()
313 313
         {
314
-            $this->filename = sha1(mt_rand(1, 9999).uniqid());
314
+            $this->filename = sha1(mt_rand(1, 9999) . uniqid());
315 315
             $this->filename .= time();
316 316
             return $this;
317 317
         }
@@ -332,7 +332,7 @@  discard block
 block discarded – undo
332 332
                 $php_size = $this->sizeInBytes((int) ini_get('upload_max_filesize'));
333 333
                 // Calculate difference
334 334
                 if ($php_size < $file_size) {
335
-                    $this->logger->warning('The upload max file size you set [' .$file_size. '] is greather than the PHP configuration for upload max file size [' .$php_size. ']');
335
+                    $this->logger->warning('The upload max file size you set [' . $file_size . '] is greather than the PHP configuration for upload max file size [' . $php_size . ']');
336 336
                 }
337 337
                 $this->max_file_size = $file_size;
338 338
             }
@@ -350,7 +350,7 @@  discard block
 block discarded – undo
350 350
         public function setAllowedMimeTypes(array $mimes)
351 351
         {
352 352
             if (count($mimes) > 0) {
353
-                array_map(array($this , 'setAllowMimeType'), $mimes);
353
+                array_map(array($this, 'setAllowMimeType'), $mimes);
354 354
             }
355 355
             return $this;
356 356
         }
@@ -415,7 +415,7 @@  discard block
 block discarded – undo
415 415
         {
416 416
             if (!empty($name) && is_string($name)) {
417 417
                 if (array_key_exists($name, $this->mime_helping)) {
418
-                    return $this->setAllowedMimeTypes($this->mime_helping[ $name ]);
418
+                    return $this->setAllowedMimeTypes($this->mime_helping[$name]);
419 419
                 }
420 420
             }
421 421
             return $this;
@@ -434,8 +434,8 @@  discard block
 block discarded – undo
434 434
         */
435 435
         public function setUploadFunction($function)
436 436
         {
437
-            if (!empty($function) && (is_array($function) || is_string($function) )) {
438
-                if (is_callable( $function)) {
437
+            if (!empty($function) && (is_array($function) || is_string($function))) {
438
+                if (is_callable($function)) {
439 439
                     $this->upload_function = $function;
440 440
                 }
441 441
             }
@@ -480,8 +480,8 @@  discard block
 block discarded – undo
480 480
                         $this->destination_directory = $destination_directory;
481 481
                         chdir($destination_directory);
482 482
                     }
483
-                    else{
484
-                        $this->logger->warning('Can not create the upload directory [' .$destination_directory. ']');
483
+                    else {
484
+                        $this->logger->warning('Can not create the upload directory [' . $destination_directory . ']');
485 485
                     }
486 486
                 }
487 487
             }
@@ -531,7 +531,7 @@  discard block
 block discarded – undo
531 531
         public function isFilename($filename)
532 532
         {
533 533
             $filename = basename($filename);
534
-            return (!empty($filename) && (is_string( $filename) || is_numeric($filename)));
534
+            return (!empty($filename) && (is_string($filename) || is_numeric($filename)));
535 535
         }
536 536
         /**
537 537
         *    Validate mime type with allowed mime types,
@@ -573,11 +573,11 @@  discard block
 block discarded – undo
573 573
         */
574 574
         public function isDirpath($path)
575 575
         {
576
-            if (!empty( $path) && (is_string( $path) || is_numeric($path) )) {
576
+            if (!empty($path) && (is_string($path) || is_numeric($path))) {
577 577
                 if (DIRECTORY_SEPARATOR == '/') {
578
-                    return (preg_match( '/^[^*?"<>|:]*$/' , $path) == 1 );
578
+                    return (preg_match('/^[^*?"<>|:]*$/', $path) == 1);
579 579
                 } else {
580
-                    return (preg_match( "/^[^*?\"<>|:]*$/" , substr($path,2) ) == 1);
580
+                    return (preg_match("/^[^*?\"<>|:]*$/", substr($path, 2)) == 1);
581 581
                 }
582 582
             }
583 583
             return false;
@@ -605,10 +605,10 @@  discard block
 block discarded – undo
605 605
         */
606 606
         public function getInfo()
607 607
         {
608
-            return (object)$this->file;
608
+            return (object) $this->file;
609 609
         }
610 610
 
611
-        public function isUploaded(){
611
+        public function isUploaded() {
612 612
             return isset($this->file_array[$this->input])
613 613
             &&
614 614
             is_uploaded_file($this->file_array[$this->input]['tmp_name']);
@@ -621,9 +621,9 @@  discard block
 block discarded – undo
621 621
         *    @return    boolean
622 622
         *    @method    boolean    save
623 623
         */
624
-        public function save(){
624
+        public function save() {
625 625
             //check if file upload is  allowed in the configuration
626
-            if(! ini_get('file_uploads')){
626
+            if (!ini_get('file_uploads')) {
627 627
                 $this->setError($this->error_messages['file_uploads']);
628 628
                 return false;
629 629
             }
@@ -633,7 +633,7 @@  discard block
 block discarded – undo
633 633
                     if (empty($this->filename)) {
634 634
                         $this->filename = $this->file_array[$this->input]['name'];
635 635
                     }
636
-                    else{
636
+                    else {
637 637
                         // Replace %s for extension in filename
638 638
                         // Before: /[\w\d]*(.[\d\w]+)$/i
639 639
                         // After: /^[\s[:alnum:]\-\_\.]*\.([\d\w]+)$/iu
@@ -657,10 +657,10 @@  discard block
 block discarded – undo
657 657
                     $this->file['filename']     = $this->filename;
658 658
                     $this->file['error']        = $this->file_array[$this->input]['error'];
659 659
 
660
-                    $this->logger->info('The upload file information to process is : ' .stringfy_vars($this->file));
660
+                    $this->logger->info('The upload file information to process is : ' . stringfy_vars($this->file));
661 661
 
662 662
                     //check for php upload error
663
-                    if(is_numeric($this->file['error']) && $this->file['error'] > 0){
663
+                    if (is_numeric($this->file['error']) && $this->file['error'] > 0) {
664 664
                         $this->setError($this->getPhpUploadErrorMessageByCode($this->file['error']));
665 665
                         return false;
666 666
                     }
@@ -686,8 +686,8 @@  discard block
 block discarded – undo
686 686
                     }
687 687
 
688 688
                     // Execute input callback
689
-                    if (!empty( $this->callbacks['input'])) {
690
-                        call_user_func($this->callbacks['input'], (object)$this->file);
689
+                    if (!empty($this->callbacks['input'])) {
690
+                        call_user_func($this->callbacks['input'], (object) $this->file);
691 691
                     }
692 692
                    
693 693
 
@@ -699,8 +699,8 @@  discard block
 block discarded – undo
699 699
                     );
700 700
 
701 701
                     // Execute output callback
702
-                    if (!empty( $this->callbacks['output'])) {
703
-                        call_user_func($this->callbacks['output'], (object)$this->file);
702
+                    if (!empty($this->callbacks['output'])) {
703
+                        call_user_func($this->callbacks['output'], (object) $this->file);
704 704
                     }
705 705
                     return $this->file['status'];
706 706
                 }
@@ -719,10 +719,10 @@  discard block
 block discarded – undo
719 719
         */
720 720
         public function sizeFormat($size, $precision = 2)
721 721
         {
722
-            if($size > 0){
722
+            if ($size > 0) {
723 723
                 $base       = log($size) / log(1024);
724 724
                 $suffixes   = array('B', 'K', 'M', 'G', 'T');
725
-                return round(pow(1024, $base - floor($base)), $precision) . ( isset($suffixes[floor($base)]) ? $suffixes[floor($base)] : '');
725
+                return round(pow(1024, $base - floor($base)), $precision) . (isset($suffixes[floor($base)]) ? $suffixes[floor($base)] : '');
726 726
             }
727 727
             return null;
728 728
         }
@@ -746,14 +746,14 @@  discard block
 block discarded – undo
746 746
             if (array_key_exists('unit', $matches)) {
747 747
                 $unit = strtoupper($matches['unit']);
748 748
             }
749
-            return (floatval($matches['size']) * pow(1024, $units[$unit]) ) ;
749
+            return (floatval($matches['size']) * pow(1024, $units[$unit]));
750 750
         }
751 751
 
752 752
         /**
753 753
          * Get the upload error message
754 754
          * @return string
755 755
          */
756
-        public function getError(){
756
+        public function getError() {
757 757
             return $this->error;
758 758
         }
759 759
 
@@ -761,7 +761,7 @@  discard block
 block discarded – undo
761 761
          * Set the upload error message
762 762
          * @param string $message the upload error message to set
763 763
          */
764
-        public function setError($message){
764
+        public function setError($message) {
765 765
             $this->logger->info('The upload got error : ' . $message);
766 766
             $this->error = $message;
767 767
         }
@@ -771,7 +771,7 @@  discard block
 block discarded – undo
771 771
          * @param  int $code the error code
772 772
          * @return string the error message
773 773
          */
774
-        private function getPhpUploadErrorMessageByCode($code){
774
+        private function getPhpUploadErrorMessageByCode($code) {
775 775
             $codeMessageMaps = array(
776 776
                 1 => $this->error_messages['upload_err_ini_size'],
777 777
                 2 => $this->error_messages['upload_err_form_size'],
Please login to merge, or discard this patch.
Braces   +2 added lines, -4 removed lines patch added patch discarded remove patch
@@ -479,8 +479,7 @@  discard block
 block discarded – undo
479 479
                     if (mkdir($destination_directory, 0775, true)) {
480 480
                         $this->destination_directory = $destination_directory;
481 481
                         chdir($destination_directory);
482
-                    }
483
-                    else{
482
+                    } else{
484 483
                         $this->logger->warning('Can not create the upload directory [' .$destination_directory. ']');
485 484
                     }
486 485
                 }
@@ -632,8 +631,7 @@  discard block
 block discarded – undo
632 631
                     // set original filename if not have a new name
633 632
                     if (empty($this->filename)) {
634 633
                         $this->filename = $this->file_array[$this->input]['name'];
635
-                    }
636
-                    else{
634
+                    } else{
637 635
                         // Replace %s for extension in filename
638 636
                         // Before: /[\w\d]*(.[\d\w]+)$/i
639 637
                         // After: /^[\s[:alnum:]\-\_\.]*\.([\d\w]+)$/iu
Please login to merge, or discard this patch.
core/classes/Database.php 3 patches
Indentation   +1356 added lines, -1356 removed lines patch added patch discarded remove patch
@@ -1,5 +1,5 @@  discard block
 block discarded – undo
1 1
 <?php
2
-    defined('ROOT_PATH') || exit('Access denied');
2
+	defined('ROOT_PATH') || exit('Access denied');
3 3
   /**
4 4
    * TNH Framework
5 5
    *
@@ -22,939 +22,939 @@  discard block
 block discarded – undo
22 22
    * You should have received a copy of the GNU General Public License
23 23
    * along with this program; if not, write to the Free Software
24 24
    * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
25
-  */
25
+   */
26 26
   class Database{
27 27
 	
28 28
 	/**
29 29
 	 * The PDO instance
30 30
 	 * @var object
31
-	*/
32
-    private $pdo                 = null;
31
+	 */
32
+	private $pdo                 = null;
33 33
     
34 34
 	/**
35 35
 	 * The database name used for the application
36 36
 	 * @var string
37
-	*/
37
+	 */
38 38
 	private $databaseName        = null;
39 39
     
40 40
 	/**
41 41
 	 * The SQL SELECT statment
42 42
 	 * @var string
43
-	*/
43
+	 */
44 44
 	private $select              = '*';
45 45
 	
46 46
 	/**
47 47
 	 * The SQL FROM statment
48 48
 	 * @var string
49
-	*/
50
-    private $from                = null;
49
+	 */
50
+	private $from                = null;
51 51
 	
52 52
 	/**
53 53
 	 * The SQL WHERE statment
54 54
 	 * @var string
55
-	*/
56
-    private $where               = null;
55
+	 */
56
+	private $where               = null;
57 57
 	
58 58
 	/**
59 59
 	 * The SQL LIMIT statment
60 60
 	 * @var string
61
-	*/
62
-    private $limit               = null;
61
+	 */
62
+	private $limit               = null;
63 63
 	
64 64
 	/**
65 65
 	 * The SQL JOIN statment
66 66
 	 * @var string
67
-	*/
68
-    private $join                = null;
67
+	 */
68
+	private $join                = null;
69 69
 	
70 70
 	/**
71 71
 	 * The SQL ORDER BY statment
72 72
 	 * @var string
73
-	*/
74
-    private $orderBy             = null;
73
+	 */
74
+	private $orderBy             = null;
75 75
 	
76 76
 	/**
77 77
 	 * The SQL GROUP BY statment
78 78
 	 * @var string
79
-	*/
80
-    private $groupBy             = null;
79
+	 */
80
+	private $groupBy             = null;
81 81
 	
82 82
 	/**
83 83
 	 * The SQL HAVING statment
84 84
 	 * @var string
85
-	*/
86
-    private $having              = null;
85
+	 */
86
+	private $having              = null;
87 87
 	
88 88
 	/**
89 89
 	 * The number of rows returned by the last query
90 90
 	 * @var int
91
-	*/
92
-    private $numRows             = 0;
91
+	 */
92
+	private $numRows             = 0;
93 93
 	
94 94
 	/**
95 95
 	 * The last insert id for the primary key column that have auto increment or sequence
96 96
 	 * @var mixed
97
-	*/
98
-    private $insertId            = null;
97
+	 */
98
+	private $insertId            = null;
99 99
 	
100 100
 	/**
101 101
 	 * The full SQL query statment after build for each command
102 102
 	 * @var string
103
-	*/
104
-    private $query               = null;
103
+	 */
104
+	private $query               = null;
105 105
 	
106 106
 	/**
107 107
 	 * The error returned for the last query
108 108
 	 * @var string
109
-	*/
110
-    private $error               = null;
109
+	 */
110
+	private $error               = null;
111 111
 	
112 112
 	/**
113 113
 	 * The result returned for the last query
114 114
 	 * @var mixed
115
-	*/
116
-    private $result              = array();
115
+	 */
116
+	private $result              = array();
117 117
 	
118 118
 	/**
119 119
 	 * The prefix used in each database table
120 120
 	 * @var string
121
-	*/
122
-    private $prefix              = null;
121
+	 */
122
+	private $prefix              = null;
123 123
 	
124 124
 	/**
125 125
 	 * The list of SQL valid operators
126 126
 	 * @var array
127
-	*/
128
-    private $operatorList        = array('=','!=','<','>','<=','>=','<>');
127
+	 */
128
+	private $operatorList        = array('=','!=','<','>','<=','>=','<>');
129 129
     
130 130
 	/**
131 131
 	 * The cache default time to live in second. 0 means no need to use the cache feature
132 132
 	 * @var int
133
-	*/
133
+	 */
134 134
 	private $cacheTtl              = 0;
135 135
 	
136 136
 	/**
137 137
 	 * The cache current time to live. 0 means no need to use the cache feature
138 138
 	 * @var int
139
-	*/
140
-    private $temporaryCacheTtl   = 0;
139
+	 */
140
+	private $temporaryCacheTtl   = 0;
141 141
 	
142 142
 	/**
143 143
 	 * The number of executed query for the current request
144 144
 	 * @var int
145
-	*/
146
-    private $queryCount          = 0;
145
+	 */
146
+	private $queryCount          = 0;
147 147
 	
148 148
 	/**
149 149
 	 * The default data to be used in the statments query INSERT, UPDATE
150 150
 	 * @var array
151
-	*/
152
-    private $data                = array();
151
+	 */
152
+	private $data                = array();
153 153
 	
154 154
 	/**
155 155
 	 * The database configuration
156 156
 	 * @var array
157
-	*/
158
-    private $config              = array();
157
+	 */
158
+	private $config              = array();
159 159
 	
160 160
 	/**
161 161
 	 * The logger instance
162 162
 	 * @var Log
163 163
 	 */
164
-    private $logger              = null;
164
+	private $logger              = null;
165 165
 
166 166
 
167
-    /**
168
-    * The cache instance
169
-    * @var CacheInterface
170
-    */
171
-    private $cacheInstance       = null;
167
+	/**
168
+	 * The cache instance
169
+	 * @var CacheInterface
170
+	 */
171
+	private $cacheInstance       = null;
172 172
 
173
-     /**
174
-    * The benchmark instance
175
-    * @var Benchmark
176
-    */
177
-    private $benchmarkInstance   = null;
173
+	 /**
174
+	  * The benchmark instance
175
+	  * @var Benchmark
176
+	  */
177
+	private $benchmarkInstance   = null;
178 178
 
179 179
 
180
-    /**
181
-     * Construct new database
182
-     * @param array $overwriteConfig the config to overwrite with the config set in database.php
183
-     */
184
-    public function __construct($overwriteConfig = array()){
185
-        //Set Log instance to use
186
-        $this->setLoggerFromParamOrCreateNewInstance(null);
180
+	/**
181
+	 * Construct new database
182
+	 * @param array $overwriteConfig the config to overwrite with the config set in database.php
183
+	 */
184
+	public function __construct($overwriteConfig = array()){
185
+		//Set Log instance to use
186
+		$this->setLoggerFromParamOrCreateNewInstance(null);
187 187
 
188
-        //Set global configuration using the config file
189
-        $this->setDatabaseConfigurationFromConfigFile($overwriteConfig);
188
+		//Set global configuration using the config file
189
+		$this->setDatabaseConfigurationFromConfigFile($overwriteConfig);
190 190
 
191 191
 
192 192
         
193
-    		$this->temporaryCacheTtl = $this->cacheTtl;
194
-    }
195
-
196
-    /**
197
-     * This is used to connect to database
198
-     * @return bool 
199
-     */
200
-    public function connect(){
201
-      $config = $this->getDatabaseConfiguration();
202
-      if (! empty($config)){
203
-        try{
204
-            $this->pdo = new PDO($this->getDsnFromDriver(), $config['username'], $config['password']);
205
-            $this->pdo->exec("SET NAMES '" . $config['charset'] . "' COLLATE '" . $config['collation'] . "'");
206
-            $this->pdo->exec("SET CHARACTER SET '" . $config['charset'] . "'");
207
-            $this->pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_OBJ);
208
-            return true;
209
-          }
210
-          catch (PDOException $e){
211
-            $this->logger->fatal($e->getMessage());
212
-            show_error('Cannot connect to Database.');
213
-            return false;
214
-          }
215
-      }
216
-      else{
217
-        show_error('Database configuration is not set.');
218
-        return false;
219
-      }
220
-    }
221
-
222
-    /**
223
-     * Set the SQL FROM statment
224
-     * @param  string|array $table the table name or array of table list
225
-     * @return object        the current Database instance
226
-     */
227
-    public function from($table){
228
-      if (is_array($table)){
229
-        $froms = '';
230
-        foreach($table as $key){
231
-          $froms .= $this->prefix . $key . ', ';
232
-        }
233
-        $this->from = rtrim($froms, ', ');
234
-      }
235
-      else{
236
-        $this->from = $this->prefix . $table;
237
-      }
238
-      return $this;
239
-    }
240
-
241
-    /**
242
-     * Set the SQL SELECT statment
243
-     * @param  string|array $fields the field name or array of field list
244
-     * @return object        the current Database instance
245
-     */
246
-    public function select($fields){
247
-      $select = (is_array($fields) ? implode(', ', $fields) : $fields);
248
-      $this->select = ($this->select == '*' ? $select : $this->select . ', ' . $select);
249
-      return $this;
250
-    }
251
-
252
-    /**
253
-     * Set the SQL SELECT DISTINCT statment
254
-     * @param  string $field the field name to distinct
255
-     * @return object        the current Database instance
256
-     */
257
-    public function distinct($field){
258
-      $distinct = ' DISTINCT ' . $field;
259
-      $this->select = ($this->select == '*' ? $distinct : $this->select . ', ' . $distinct);
260
-
261
-      return $this;
262
-    }
263
-
264
-    /**
265
-     * Set the SQL function MAX in SELECT statment
266
-     * @param  string $field the field name
267
-     * @param  string $name  if is not null represent the alias used for this field in the result
268
-     * @return object        the current Database instance
269
-     */
270
-    public function max($field, $name = null){
271
-      $func = 'MAX(' . $field . ')' . (!is_null($name) ? ' AS ' . $name : '');
272
-      $this->select = ($this->select == '*' ? $func : $this->select . ', ' . $func);
273
-      return $this;
274
-    }
275
-
276
-    /**
277
-     * Set the SQL function MIN in SELECT statment
278
-     * @param  string $field the field name
279
-     * @param  string $name  if is not null represent the alias used for this field in the result
280
-     * @return object        the current Database instance
281
-     */
282
-    public function min($field, $name = null){
283
-      $func = 'MIN(' . $field . ')' . (!is_null($name) ? ' AS ' . $name : '');
284
-      $this->select = ($this->select == '*' ? $func : $this->select . ', ' . $func);
285
-      return $this;
286
-    }
287
-
288
-    /**
289
-     * Set the SQL function SUM in SELECT statment
290
-     * @param  string $field the field name
291
-     * @param  string $name  if is not null represent the alias used for this field in the result
292
-     * @return object        the current Database instance
293
-     */
294
-    public function sum($field, $name = null){
295
-      $func = 'SUM(' . $field . ')' . (!is_null($name) ? ' AS ' . $name : '');
296
-      $this->select = ($this->select == '*' ? $func : $this->select . ', ' . $func);
297
-      return $this;
298
-    }
299
-
300
-    /**
301
-     * Set the SQL function COUNT in SELECT statment
302
-     * @param  string $field the field name
303
-     * @param  string $name  if is not null represent the alias used for this field in the result
304
-     * @return object        the current Database instance
305
-     */
306
-    public function count($field = '*', $name = null){
307
-      $func = 'COUNT(' . $field . ')' . (!is_null($name) ? ' AS ' . $name : '');
308
-      $this->select = ($this->select == '*' ? $func : $this->select . ', ' . $func);
309
-      return $this;
310
-    }
311
-
312
-    /**
313
-     * Set the SQL function AVG in SELECT statment
314
-     * @param  string $field the field name
315
-     * @param  string $name  if is not null represent the alias used for this field in the result
316
-     * @return object        the current Database instance
317
-     */
318
-    public function avg($field, $name = null){
319
-      $func = 'AVG(' . $field . ')' . (!is_null($name) ? ' AS ' . $name : '');
320
-      $this->select = ($this->select == '*' ? $func : $this->select . ', ' . $func);
321
-      return $this;
322
-    }
323
-
324
-    /**
325
-     * Set the SQL JOIN statment
326
-     * @param  string $table  the join table name
327
-     * @param  string $field1 the first field for join conditions	
328
-     * @param  string $op     the join condition operator. If is null the default will be "="
329
-     * @param  string $field2 the second field for join conditions
330
-     * @param  string $type   the type of join (INNER, LEFT, RIGHT)
331
-     * @return object        the current Database instance
332
-     */
333
-    public function join($table, $field1 = null, $op = null, $field2 = null, $type = ''){
334
-      $on = $field1;
335
-      $table = $this->prefix . $table;
336
-      if (! is_null($op)){
337
-        $on = (! in_array($op, $this->operatorList) ? $this->prefix . $field1 . ' = ' . $this->prefix . $op : $this->prefix . $field1 . ' ' . $op . ' ' . $this->prefix . $field2);
338
-      }
339
-      if (empty($this->join)){
340
-        $this->join = ' ' . $type . 'JOIN' . ' ' . $table . ' ON ' . $on;
341
-      }
342
-      else{
343
-        $this->join = $this->join . ' ' . $type . 'JOIN' . ' ' . $table . ' ON ' . $on;
344
-      }
345
-      return $this;
346
-    }
347
-
348
-    /**
349
-     * Set the SQL INNER JOIN statment
350
-     * @see  Database::join()
351
-     * @return object        the current Database instance
352
-     */
353
-    public function innerJoin($table, $field1, $op = null, $field2 = ''){
354
-      return $this->join($table, $field1, $op, $field2, 'INNER ');
355
-    }
356
-
357
-    /**
358
-     * Set the SQL LEFT JOIN statment
359
-     * @see  Database::join()
360
-     * @return object        the current Database instance
361
-     */
362
-    public function leftJoin($table, $field1, $op = null, $field2 = ''){
363
-      return $this->join($table, $field1, $op, $field2, 'LEFT ');
364
-	}
365
-
366
-	/**
367
-     * Set the SQL RIGHT JOIN statment
368
-     * @see  Database::join()
369
-     * @return object        the current Database instance
370
-     */
371
-    public function rightJoin($table, $field1, $op = null, $field2 = ''){
372
-      return $this->join($table, $field1, $op, $field2, 'RIGHT ');
373
-    }
374
-
375
-    /**
376
-     * Set the SQL FULL OUTER JOIN statment
377
-     * @see  Database::join()
378
-     * @return object        the current Database instance
379
-     */
380
-    public function fullOuterJoin($table, $field1, $op = null, $field2 = ''){
381
-    	return $this->join($table, $field1, $op, $field2, 'FULL OUTER ');
382
-    }
383
-
384
-    /**
385
-     * Set the SQL LEFT OUTER JOIN statment
386
-     * @see  Database::join()
387
-     * @return object        the current Database instance
388
-     */
389
-    public function leftOuterJoin($table, $field1, $op = null, $field2 = ''){
390
-      return $this->join($table, $field1, $op, $field2, 'LEFT OUTER ');
391
-    }
392
-
393
-    /**
394
-     * Set the SQL RIGHT OUTER JOIN statment
395
-     * @see  Database::join()
396
-     * @return object        the current Database instance
397
-     */
398
-    public function rightOuterJoin($table, $field1, $op = null, $field2 = ''){
399
-      return $this->join($table, $field1, $op, $field2, 'RIGHT OUTER ');
400
-    }
401
-
402
-    /**
403
-     * Set the SQL WHERE CLAUSE for IS NULL
404
-     * @param  string|array $field  the field name or array of field list
405
-     * @param  string $andOr the separator type used 'AND', 'OR', etc.
406
-     * @return object        the current Database instance
407
-     */
408
-    public function whereIsNull($field, $andOr = 'AND'){
409
-      if (is_array($field)){
410
-        foreach($field as $f){
411
-        	$this->whereIsNull($f, $andOr);
412
-        }
413
-      }
414
-      else{
415
-           $this->setWhereStr($field.' IS NULL ', $andOr);
416
-      }
417
-      return $this;
418
-    }
419
-
420
-    /**
421
-     * Set the SQL WHERE CLAUSE for IS NOT NULL
422
-     * @param  string|array $field  the field name or array of field list
423
-     * @param  string $andOr the separator type used 'AND', 'OR', etc.
424
-     * @return object        the current Database instance
425
-     */
426
-    public function whereIsNotNull($field, $andOr = 'AND'){
427
-      if (is_array($field)){
428
-        foreach($field as $f){
429
-          $this->whereIsNotNull($f, $andOr);
430
-        }
431
-      }
432
-      else{
433
-          $this->setWhereStr($field.' IS NOT NULL ', $andOr);
434
-      }
435
-      return $this;
436
-    }
193
+			$this->temporaryCacheTtl = $this->cacheTtl;
194
+	}
195
+
196
+	/**
197
+	 * This is used to connect to database
198
+	 * @return bool 
199
+	 */
200
+	public function connect(){
201
+	  $config = $this->getDatabaseConfiguration();
202
+	  if (! empty($config)){
203
+		try{
204
+			$this->pdo = new PDO($this->getDsnFromDriver(), $config['username'], $config['password']);
205
+			$this->pdo->exec("SET NAMES '" . $config['charset'] . "' COLLATE '" . $config['collation'] . "'");
206
+			$this->pdo->exec("SET CHARACTER SET '" . $config['charset'] . "'");
207
+			$this->pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_OBJ);
208
+			return true;
209
+		  }
210
+		  catch (PDOException $e){
211
+			$this->logger->fatal($e->getMessage());
212
+			show_error('Cannot connect to Database.');
213
+			return false;
214
+		  }
215
+	  }
216
+	  else{
217
+		show_error('Database configuration is not set.');
218
+		return false;
219
+	  }
220
+	}
221
+
222
+	/**
223
+	 * Set the SQL FROM statment
224
+	 * @param  string|array $table the table name or array of table list
225
+	 * @return object        the current Database instance
226
+	 */
227
+	public function from($table){
228
+	  if (is_array($table)){
229
+		$froms = '';
230
+		foreach($table as $key){
231
+		  $froms .= $this->prefix . $key . ', ';
232
+		}
233
+		$this->from = rtrim($froms, ', ');
234
+	  }
235
+	  else{
236
+		$this->from = $this->prefix . $table;
237
+	  }
238
+	  return $this;
239
+	}
240
+
241
+	/**
242
+	 * Set the SQL SELECT statment
243
+	 * @param  string|array $fields the field name or array of field list
244
+	 * @return object        the current Database instance
245
+	 */
246
+	public function select($fields){
247
+	  $select = (is_array($fields) ? implode(', ', $fields) : $fields);
248
+	  $this->select = ($this->select == '*' ? $select : $this->select . ', ' . $select);
249
+	  return $this;
250
+	}
251
+
252
+	/**
253
+	 * Set the SQL SELECT DISTINCT statment
254
+	 * @param  string $field the field name to distinct
255
+	 * @return object        the current Database instance
256
+	 */
257
+	public function distinct($field){
258
+	  $distinct = ' DISTINCT ' . $field;
259
+	  $this->select = ($this->select == '*' ? $distinct : $this->select . ', ' . $distinct);
260
+
261
+	  return $this;
262
+	}
263
+
264
+	/**
265
+	 * Set the SQL function MAX in SELECT statment
266
+	 * @param  string $field the field name
267
+	 * @param  string $name  if is not null represent the alias used for this field in the result
268
+	 * @return object        the current Database instance
269
+	 */
270
+	public function max($field, $name = null){
271
+	  $func = 'MAX(' . $field . ')' . (!is_null($name) ? ' AS ' . $name : '');
272
+	  $this->select = ($this->select == '*' ? $func : $this->select . ', ' . $func);
273
+	  return $this;
274
+	}
275
+
276
+	/**
277
+	 * Set the SQL function MIN in SELECT statment
278
+	 * @param  string $field the field name
279
+	 * @param  string $name  if is not null represent the alias used for this field in the result
280
+	 * @return object        the current Database instance
281
+	 */
282
+	public function min($field, $name = null){
283
+	  $func = 'MIN(' . $field . ')' . (!is_null($name) ? ' AS ' . $name : '');
284
+	  $this->select = ($this->select == '*' ? $func : $this->select . ', ' . $func);
285
+	  return $this;
286
+	}
287
+
288
+	/**
289
+	 * Set the SQL function SUM in SELECT statment
290
+	 * @param  string $field the field name
291
+	 * @param  string $name  if is not null represent the alias used for this field in the result
292
+	 * @return object        the current Database instance
293
+	 */
294
+	public function sum($field, $name = null){
295
+	  $func = 'SUM(' . $field . ')' . (!is_null($name) ? ' AS ' . $name : '');
296
+	  $this->select = ($this->select == '*' ? $func : $this->select . ', ' . $func);
297
+	  return $this;
298
+	}
299
+
300
+	/**
301
+	 * Set the SQL function COUNT in SELECT statment
302
+	 * @param  string $field the field name
303
+	 * @param  string $name  if is not null represent the alias used for this field in the result
304
+	 * @return object        the current Database instance
305
+	 */
306
+	public function count($field = '*', $name = null){
307
+	  $func = 'COUNT(' . $field . ')' . (!is_null($name) ? ' AS ' . $name : '');
308
+	  $this->select = ($this->select == '*' ? $func : $this->select . ', ' . $func);
309
+	  return $this;
310
+	}
311
+
312
+	/**
313
+	 * Set the SQL function AVG in SELECT statment
314
+	 * @param  string $field the field name
315
+	 * @param  string $name  if is not null represent the alias used for this field in the result
316
+	 * @return object        the current Database instance
317
+	 */
318
+	public function avg($field, $name = null){
319
+	  $func = 'AVG(' . $field . ')' . (!is_null($name) ? ' AS ' . $name : '');
320
+	  $this->select = ($this->select == '*' ? $func : $this->select . ', ' . $func);
321
+	  return $this;
322
+	}
323
+
324
+	/**
325
+	 * Set the SQL JOIN statment
326
+	 * @param  string $table  the join table name
327
+	 * @param  string $field1 the first field for join conditions	
328
+	 * @param  string $op     the join condition operator. If is null the default will be "="
329
+	 * @param  string $field2 the second field for join conditions
330
+	 * @param  string $type   the type of join (INNER, LEFT, RIGHT)
331
+	 * @return object        the current Database instance
332
+	 */
333
+	public function join($table, $field1 = null, $op = null, $field2 = null, $type = ''){
334
+	  $on = $field1;
335
+	  $table = $this->prefix . $table;
336
+	  if (! is_null($op)){
337
+		$on = (! in_array($op, $this->operatorList) ? $this->prefix . $field1 . ' = ' . $this->prefix . $op : $this->prefix . $field1 . ' ' . $op . ' ' . $this->prefix . $field2);
338
+	  }
339
+	  if (empty($this->join)){
340
+		$this->join = ' ' . $type . 'JOIN' . ' ' . $table . ' ON ' . $on;
341
+	  }
342
+	  else{
343
+		$this->join = $this->join . ' ' . $type . 'JOIN' . ' ' . $table . ' ON ' . $on;
344
+	  }
345
+	  return $this;
346
+	}
347
+
348
+	/**
349
+	 * Set the SQL INNER JOIN statment
350
+	 * @see  Database::join()
351
+	 * @return object        the current Database instance
352
+	 */
353
+	public function innerJoin($table, $field1, $op = null, $field2 = ''){
354
+	  return $this->join($table, $field1, $op, $field2, 'INNER ');
355
+	}
356
+
357
+	/**
358
+	 * Set the SQL LEFT JOIN statment
359
+	 * @see  Database::join()
360
+	 * @return object        the current Database instance
361
+	 */
362
+	public function leftJoin($table, $field1, $op = null, $field2 = ''){
363
+	  return $this->join($table, $field1, $op, $field2, 'LEFT ');
364
+	}
365
+
366
+	/**
367
+	 * Set the SQL RIGHT JOIN statment
368
+	 * @see  Database::join()
369
+	 * @return object        the current Database instance
370
+	 */
371
+	public function rightJoin($table, $field1, $op = null, $field2 = ''){
372
+	  return $this->join($table, $field1, $op, $field2, 'RIGHT ');
373
+	}
374
+
375
+	/**
376
+	 * Set the SQL FULL OUTER JOIN statment
377
+	 * @see  Database::join()
378
+	 * @return object        the current Database instance
379
+	 */
380
+	public function fullOuterJoin($table, $field1, $op = null, $field2 = ''){
381
+		return $this->join($table, $field1, $op, $field2, 'FULL OUTER ');
382
+	}
383
+
384
+	/**
385
+	 * Set the SQL LEFT OUTER JOIN statment
386
+	 * @see  Database::join()
387
+	 * @return object        the current Database instance
388
+	 */
389
+	public function leftOuterJoin($table, $field1, $op = null, $field2 = ''){
390
+	  return $this->join($table, $field1, $op, $field2, 'LEFT OUTER ');
391
+	}
392
+
393
+	/**
394
+	 * Set the SQL RIGHT OUTER JOIN statment
395
+	 * @see  Database::join()
396
+	 * @return object        the current Database instance
397
+	 */
398
+	public function rightOuterJoin($table, $field1, $op = null, $field2 = ''){
399
+	  return $this->join($table, $field1, $op, $field2, 'RIGHT OUTER ');
400
+	}
401
+
402
+	/**
403
+	 * Set the SQL WHERE CLAUSE for IS NULL
404
+	 * @param  string|array $field  the field name or array of field list
405
+	 * @param  string $andOr the separator type used 'AND', 'OR', etc.
406
+	 * @return object        the current Database instance
407
+	 */
408
+	public function whereIsNull($field, $andOr = 'AND'){
409
+	  if (is_array($field)){
410
+		foreach($field as $f){
411
+			$this->whereIsNull($f, $andOr);
412
+		}
413
+	  }
414
+	  else{
415
+		   $this->setWhereStr($field.' IS NULL ', $andOr);
416
+	  }
417
+	  return $this;
418
+	}
419
+
420
+	/**
421
+	 * Set the SQL WHERE CLAUSE for IS NOT NULL
422
+	 * @param  string|array $field  the field name or array of field list
423
+	 * @param  string $andOr the separator type used 'AND', 'OR', etc.
424
+	 * @return object        the current Database instance
425
+	 */
426
+	public function whereIsNotNull($field, $andOr = 'AND'){
427
+	  if (is_array($field)){
428
+		foreach($field as $f){
429
+		  $this->whereIsNotNull($f, $andOr);
430
+		}
431
+	  }
432
+	  else{
433
+		  $this->setWhereStr($field.' IS NOT NULL ', $andOr);
434
+	  }
435
+	  return $this;
436
+	}
437 437
     
438
-    /**
439
-     * Set the SQL WHERE CLAUSE statment
440
-     * @param  string|array  $where the where field or array of field list
441
-     * @param  array|string  $op     the condition operator. If is null the default will be "="
442
-     * @param  mixed  $val    the where value
443
-     * @param  string  $type   the type used for this where clause (NOT, etc.)
444
-     * @param  string  $andOr the separator type used 'AND', 'OR', etc.
445
-     * @param  boolean $escape whether to escape or not the $val
446
-     * @return object        the current Database instance
447
-     */
448
-    public function where($where, $op = null, $val = null, $type = '', $andOr = 'AND', $escape = true){
449
-      $whereStr = '';
450
-      if (is_array($where)){
451
-        $whereStr = $this->getWhereStrIfIsArray($where, $type, $andOr, $escape);
452
-      }
453
-      else{
454
-        if (is_array($op)){
455
-          $whereStr = $this->getWhereStrIfOperatorIsArray($where, $op, $type, $escape);
456
-        } else {
457
-          $whereStr = $this->getWhereStrForOperator($where, $op, $val, $type, $escape = true);
458
-        }
459
-      }
460
-      $this->setWhereStr($whereStr, $andOr);
461
-      return $this;
462
-    }
463
-
464
-    /**
465
-     * Set the SQL WHERE CLAUSE statment using OR
466
-     * @see  Database::where()
467
-     * @return object        the current Database instance
468
-     */
469
-    public function orWhere($where, $op = null, $val = null, $escape = true){
470
-      return $this->where($where, $op, $val, '', 'OR', $escape);
471
-    }
472
-
473
-
474
-    /**
475
-     * Set the SQL WHERE CLAUSE statment using AND and NOT
476
-     * @see  Database::where()
477
-     * @return object        the current Database instance
478
-     */
479
-    public function notWhere($where, $op = null, $val = null, $escape = true){
480
-      return $this->where($where, $op, $val, 'NOT ', 'AND', $escape);
481
-    }
482
-
483
-    /**
484
-     * Set the SQL WHERE CLAUSE statment using OR and NOT
485
-     * @see  Database::where()
486
-     * @return object        the current Database instance
487
-     */
488
-    public function orNotWhere($where, $op = null, $val = null, $escape = true){
489
-    	return $this->where($where, $op, $val, 'NOT ', 'OR', $escape);
490
-    }
491
-
492
-    /**
493
-     * Set the opened parenthesis for the complex SQL query
494
-     * @param  string $type   the type of this grouped (NOT, etc.)
495
-     * @param  string $andOr the multiple conditions separator (AND, OR, etc.)
496
-     * @return object        the current Database instance
497
-     */
498
-    public function groupStart($type = '', $andOr = ' AND'){
499
-      if (empty($this->where)){
500
-        $this->where = $type . ' (';
501
-      }
502
-      else{
503
-          if (substr($this->where, -1) == '('){
504
-            $this->where .= $type . ' (';
505
-          }
506
-          else{
507
-          	$this->where .= $andOr . ' ' . $type . ' (';
508
-          }
509
-      }
510
-      return $this;
511
-    }
512
-
513
-    /**
514
-     * Set the opened parenthesis for the complex SQL query using NOT type
515
-     * @see  Database::groupStart()
516
-     * @return object        the current Database instance
517
-     */
518
-    public function notGroupStart(){
519
-      return $this->groupStart('NOT');
520
-    }
521
-
522
-    /**
523
-     * Set the opened parenthesis for the complex SQL query using OR for separator
524
-     * @see  Database::groupStart()
525
-     * @return object        the current Database instance
526
-     */
527
-    public function orGroupStart(){
528
-      return $this->groupStart('', ' OR');
529
-    }
530
-
531
-     /**
532
-     * Set the opened parenthesis for the complex SQL query using OR for separator and NOT for type
533
-     * @see  Database::groupStart()
534
-     * @return object        the current Database instance
535
-     */
536
-    public function orNotGroupStart(){
537
-      return $this->groupStart('NOT', ' OR');
538
-    }
539
-
540
-    /**
541
-     * Close the parenthesis for the grouped SQL
542
-     * @return object        the current Database instance
543
-     */
544
-    public function groupEnd(){
545
-      $this->where .= ')';
546
-      return $this;
547
-    }
548
-
549
-    /**
550
-     * Set the SQL WHERE CLAUSE statment for IN
551
-     * @param  string  $field  the field name for IN statment
552
-     * @param  array   $keys   the list of values used
553
-     * @param  string  $type   the condition separator type (NOT)
554
-     * @param  string  $andOr the multiple conditions separator (OR, AND)
555
-     * @param  boolean $escape whether to escape or not the values
556
-     * @return object        the current Database instance
557
-     */
558
-    public function in($field, array $keys, $type = '', $andOr = 'AND', $escape = true){
559
-      $_keys = array();
560
-      foreach ($keys as $k => $v){
561
-        if (is_null($v)){
562
-          $v = '';
563
-        }
564
-        $_keys[] = (is_numeric($v) ? $v : $this->escape($v, $escape));
565
-      }
566
-      $keys = implode(', ', $_keys);
567
-      $whereStr = $field . ' ' . $type . ' IN (' . $keys . ')';
568
-      $this->setWhereStr($whereStr, $andOr);
569
-      return $this;
570
-    }
571
-
572
-    /**
573
-     * Set the SQL WHERE CLAUSE statment for NOT IN with AND separator
574
-     * @see  Database::in()
575
-     * @return object        the current Database instance
576
-     */
577
-    public function notIn($field, array $keys, $escape = true){
578
-      return $this->in($field, $keys, 'NOT ', 'AND', $escape);
579
-    }
580
-
581
-    /**
582
-     * Set the SQL WHERE CLAUSE statment for IN with OR separator
583
-     * @see  Database::in()
584
-     * @return object        the current Database instance
585
-     */
586
-    public function orIn($field, array $keys, $escape = true){
587
-      return $this->in($field, $keys, '', 'OR', $escape);
588
-    }
589
-
590
-    /**
591
-     * Set the SQL WHERE CLAUSE statment for NOT IN with OR separator
592
-     * @see  Database::in()
593
-     * @return object        the current Database instance
594
-     */
595
-    public function orNotIn($field, array $keys, $escape = true){
596
-      return $this->in($field, $keys, 'NOT ', 'OR', $escape);
597
-    }
598
-
599
-    /**
600
-     * Set the SQL WHERE CLAUSE statment for BETWEEN
601
-     * @param  string  $field  the field used for the BETWEEN statment
602
-     * @param  mixed  $value1 the BETWEEN begin value
603
-     * @param  mixed  $value2 the BETWEEN end value
604
-     * @param  string  $type   the condition separator type (NOT)
605
-     * @param  string  $andOr the multiple conditions separator (OR, AND)
606
-     * @param  boolean $escape whether to escape or not the values
607
-     * @return object        the current Database instance
608
-     */
609
-    public function between($field, $value1, $value2, $type = '', $andOr = 'AND', $escape = true){
610
-      if (is_null($value1)){
611
-        $value1 = '';
612
-      }
613
-      if (is_null($value2)){
614
-        $value2 = '';
615
-      }
616
-      $whereStr = $field . ' ' . $type . ' BETWEEN ' . $this->escape($value1, $escape) . ' AND ' . $this->escape($value2, $escape);
617
-      $this->setWhereStr($whereStr, $andOr);
618
-      return $this;
619
-    }
620
-
621
-    /**
622
-     * Set the SQL WHERE CLAUSE statment for BETWEEN with NOT type and AND separator
623
-     * @see  Database::between()
624
-     * @return object        the current Database instance
625
-     */
626
-    public function notBetween($field, $value1, $value2, $escape = true){
627
-      return $this->between($field, $value1, $value2, 'NOT ', 'AND', $escape);
628
-    }
629
-
630
-    /**
631
-     * Set the SQL WHERE CLAUSE statment for BETWEEN with OR separator
632
-     * @see  Database::between()
633
-     * @return object        the current Database instance
634
-     */
635
-    public function orBetween($field, $value1, $value2, $escape = true){
636
-      return $this->between($field, $value1, $value2, '', 'OR', $escape);
637
-    }
638
-
639
-    /**
640
-     * Set the SQL WHERE CLAUSE statment for BETWEEN with NOT type and OR separator
641
-     * @see  Database::between()
642
-     * @return object        the current Database instance
643
-     */
644
-    public function orNotBetween($field, $value1, $value2, $escape = true){
645
-      return $this->between($field, $value1, $value2, 'NOT ', 'OR', $escape);
646
-    }
647
-
648
-    /**
649
-     * Set the SQL WHERE CLAUSE statment for LIKE
650
-     * @param  string  $field  the field name used in LIKE statment
651
-     * @param  string  $data   the LIKE value for this field including the '%', and '_' part
652
-     * @param  string  $type   the condition separator type (NOT)
653
-     * @param  string  $andOr the multiple conditions separator (OR, AND)
654
-     * @param  boolean $escape whether to escape or not the values
655
-     * @return object        the current Database instance
656
-     */
657
-    public function like($field, $data, $type = '', $andOr = 'AND', $escape = true){
658
-      if (empty($data)){
659
-        $data = '';
660
-      }
661
-      $this->setWhereStr($field . ' ' . $type . ' LIKE ' . ($this->escape($data, $escape)), $andOr);
662
-      return $this;
663
-    }
664
-
665
-    /**
666
-     * Set the SQL WHERE CLAUSE statment for LIKE with OR separator
667
-     * @see  Database::like()
668
-     * @return object        the current Database instance
669
-     */
670
-    public function orLike($field, $data, $escape = true){
671
-      return $this->like($field, $data, '', 'OR', $escape);
672
-    }
673
-
674
-    /**
675
-     * Set the SQL WHERE CLAUSE statment for LIKE with NOT type and AND separator
676
-     * @see  Database::like()
677
-     * @return object        the current Database instance
678
-     */
679
-    public function notLike($field, $data, $escape = true){
680
-      return $this->like($field, $data, 'NOT ', 'AND', $escape);
681
-    }
682
-
683
-    /**
684
-     * Set the SQL WHERE CLAUSE statment for LIKE with NOT type and OR separator
685
-     * @see  Database::like()
686
-     * @return object        the current Database instance
687
-     */
688
-    public function orNotLike($field, $data, $escape = true){
689
-      return $this->like($field, $data, 'NOT ', 'OR', $escape);
690
-    }
691
-
692
-    /**
693
-     * Set the SQL LIMIT statment
694
-     * @param  int $limit    the limit offset. If $limitEnd is null this will be the limit count
695
-     * like LIMIT n;
696
-     * @param  int $limitEnd the limit count
697
-     * @return object        the current Database instance
698
-     */
699
-    public function limit($limit, $limitEnd = null){
700
-      if (empty($limit)){
701
-        return;
702
-      }
703
-      if (! is_null($limitEnd)){
704
-        $this->limit = $limit . ', ' . $limitEnd;
705
-      }
706
-      else{
707
-        $this->limit = $limit;
708
-      }
709
-      return $this;
710
-    }
711
-
712
-    /**
713
-     * Set the SQL ORDER BY CLAUSE statment
714
-     * @param  string $orderBy   the field name used for order
715
-     * @param  string $orderDir the order direction (ASC or DESC)
716
-     * @return object        the current Database instance
717
-     */
718
-    public function orderBy($orderBy, $orderDir = ' ASC'){
719
-        if (stristr($orderBy, ' ') || $orderBy == 'rand()'){
720
-          $this->orderBy = empty($this->orderBy) ? $orderBy : $this->orderBy . ', ' . $orderBy;
721
-        }
722
-        else{
723
-          $this->orderBy = empty($this->orderBy) ? ($orderBy . ' ' 
724
-                            . strtoupper($orderDir)) : $this->orderBy 
725
-                            . ', ' . $orderBy . ' ' . strtoupper($orderDir);
726
-        }
727
-      return $this;
728
-    }
729
-
730
-    /**
731
-     * Set the SQL GROUP BY CLAUSE statment
732
-     * @param  string|array $field the field name used or array of field list
733
-     * @return object        the current Database instance
734
-     */
735
-    public function groupBy($field){
736
-      if (is_array($field)){
737
-        $this->groupBy = implode(', ', $field);
738
-      }
739
-      else{
740
-        $this->groupBy = $field;
741
-      }
742
-      return $this;
743
-    }
744
-
745
-    /**
746
-     * Set the SQL HAVING CLAUSE statment
747
-     * @param  string  $field  the field name used for HAVING statment
748
-     * @param  string|array  $op     the operator used or array
749
-     * @param  mixed  $val    the value for HAVING comparaison
750
-     * @param  boolean $escape whether to escape or not the values
751
-     * @return object        the current Database instance
752
-     */
753
-    public function having($field, $op = null, $val = null, $escape = true){
754
-      if (is_array($op)){
755
-        $x = explode('?', $field);
756
-        $w = '';
757
-        foreach($x as $k => $v){
758
-  	      if (!empty($v)){
759
-            if (! isset($op[$k])){
760
-              $op[$k] = '';
761
-            }
762
-  	      	$w .= $v . (isset($op[$k]) ? $this->escape($op[$k], $escape) : '');
763
-  	      }
764
-      	}
765
-        $this->having = $w;
766
-      }
767
-      else if (! in_array($op, $this->operatorList)){
768
-        if (is_null($op)){
769
-          $op = '';
770
-        }
771
-        $this->having = $field . ' > ' . ($this->escape($op, $escape));
772
-      }
773
-      else{
774
-        if (is_null($val)){
775
-          $val = '';
776
-        }
777
-        $this->having = $field . ' ' . $op . ' ' . ($this->escape($val, $escape));
778
-      }
779
-      return $this;
780
-    }
781
-
782
-    /**
783
-     * Return the number of rows returned by the current query
784
-     * @return int
785
-     */
786
-    public function numRows(){
787
-      return $this->numRows;
788
-    }
789
-
790
-    /**
791
-     * Return the last insert id value
792
-     * @return mixed
793
-     */
794
-    public function insertId(){
795
-      return $this->insertId;
796
-    }
797
-
798
-    /**
799
-     * Show an error got from the current query (SQL command synthax error, database driver returned error, etc.)
800
-     */
801
-    public function error(){
438
+	/**
439
+	 * Set the SQL WHERE CLAUSE statment
440
+	 * @param  string|array  $where the where field or array of field list
441
+	 * @param  array|string  $op     the condition operator. If is null the default will be "="
442
+	 * @param  mixed  $val    the where value
443
+	 * @param  string  $type   the type used for this where clause (NOT, etc.)
444
+	 * @param  string  $andOr the separator type used 'AND', 'OR', etc.
445
+	 * @param  boolean $escape whether to escape or not the $val
446
+	 * @return object        the current Database instance
447
+	 */
448
+	public function where($where, $op = null, $val = null, $type = '', $andOr = 'AND', $escape = true){
449
+	  $whereStr = '';
450
+	  if (is_array($where)){
451
+		$whereStr = $this->getWhereStrIfIsArray($where, $type, $andOr, $escape);
452
+	  }
453
+	  else{
454
+		if (is_array($op)){
455
+		  $whereStr = $this->getWhereStrIfOperatorIsArray($where, $op, $type, $escape);
456
+		} else {
457
+		  $whereStr = $this->getWhereStrForOperator($where, $op, $val, $type, $escape = true);
458
+		}
459
+	  }
460
+	  $this->setWhereStr($whereStr, $andOr);
461
+	  return $this;
462
+	}
463
+
464
+	/**
465
+	 * Set the SQL WHERE CLAUSE statment using OR
466
+	 * @see  Database::where()
467
+	 * @return object        the current Database instance
468
+	 */
469
+	public function orWhere($where, $op = null, $val = null, $escape = true){
470
+	  return $this->where($where, $op, $val, '', 'OR', $escape);
471
+	}
472
+
473
+
474
+	/**
475
+	 * Set the SQL WHERE CLAUSE statment using AND and NOT
476
+	 * @see  Database::where()
477
+	 * @return object        the current Database instance
478
+	 */
479
+	public function notWhere($where, $op = null, $val = null, $escape = true){
480
+	  return $this->where($where, $op, $val, 'NOT ', 'AND', $escape);
481
+	}
482
+
483
+	/**
484
+	 * Set the SQL WHERE CLAUSE statment using OR and NOT
485
+	 * @see  Database::where()
486
+	 * @return object        the current Database instance
487
+	 */
488
+	public function orNotWhere($where, $op = null, $val = null, $escape = true){
489
+		return $this->where($where, $op, $val, 'NOT ', 'OR', $escape);
490
+	}
491
+
492
+	/**
493
+	 * Set the opened parenthesis for the complex SQL query
494
+	 * @param  string $type   the type of this grouped (NOT, etc.)
495
+	 * @param  string $andOr the multiple conditions separator (AND, OR, etc.)
496
+	 * @return object        the current Database instance
497
+	 */
498
+	public function groupStart($type = '', $andOr = ' AND'){
499
+	  if (empty($this->where)){
500
+		$this->where = $type . ' (';
501
+	  }
502
+	  else{
503
+		  if (substr($this->where, -1) == '('){
504
+			$this->where .= $type . ' (';
505
+		  }
506
+		  else{
507
+		  	$this->where .= $andOr . ' ' . $type . ' (';
508
+		  }
509
+	  }
510
+	  return $this;
511
+	}
512
+
513
+	/**
514
+	 * Set the opened parenthesis for the complex SQL query using NOT type
515
+	 * @see  Database::groupStart()
516
+	 * @return object        the current Database instance
517
+	 */
518
+	public function notGroupStart(){
519
+	  return $this->groupStart('NOT');
520
+	}
521
+
522
+	/**
523
+	 * Set the opened parenthesis for the complex SQL query using OR for separator
524
+	 * @see  Database::groupStart()
525
+	 * @return object        the current Database instance
526
+	 */
527
+	public function orGroupStart(){
528
+	  return $this->groupStart('', ' OR');
529
+	}
530
+
531
+	 /**
532
+	  * Set the opened parenthesis for the complex SQL query using OR for separator and NOT for type
533
+	  * @see  Database::groupStart()
534
+	  * @return object        the current Database instance
535
+	  */
536
+	public function orNotGroupStart(){
537
+	  return $this->groupStart('NOT', ' OR');
538
+	}
539
+
540
+	/**
541
+	 * Close the parenthesis for the grouped SQL
542
+	 * @return object        the current Database instance
543
+	 */
544
+	public function groupEnd(){
545
+	  $this->where .= ')';
546
+	  return $this;
547
+	}
548
+
549
+	/**
550
+	 * Set the SQL WHERE CLAUSE statment for IN
551
+	 * @param  string  $field  the field name for IN statment
552
+	 * @param  array   $keys   the list of values used
553
+	 * @param  string  $type   the condition separator type (NOT)
554
+	 * @param  string  $andOr the multiple conditions separator (OR, AND)
555
+	 * @param  boolean $escape whether to escape or not the values
556
+	 * @return object        the current Database instance
557
+	 */
558
+	public function in($field, array $keys, $type = '', $andOr = 'AND', $escape = true){
559
+	  $_keys = array();
560
+	  foreach ($keys as $k => $v){
561
+		if (is_null($v)){
562
+		  $v = '';
563
+		}
564
+		$_keys[] = (is_numeric($v) ? $v : $this->escape($v, $escape));
565
+	  }
566
+	  $keys = implode(', ', $_keys);
567
+	  $whereStr = $field . ' ' . $type . ' IN (' . $keys . ')';
568
+	  $this->setWhereStr($whereStr, $andOr);
569
+	  return $this;
570
+	}
571
+
572
+	/**
573
+	 * Set the SQL WHERE CLAUSE statment for NOT IN with AND separator
574
+	 * @see  Database::in()
575
+	 * @return object        the current Database instance
576
+	 */
577
+	public function notIn($field, array $keys, $escape = true){
578
+	  return $this->in($field, $keys, 'NOT ', 'AND', $escape);
579
+	}
580
+
581
+	/**
582
+	 * Set the SQL WHERE CLAUSE statment for IN with OR separator
583
+	 * @see  Database::in()
584
+	 * @return object        the current Database instance
585
+	 */
586
+	public function orIn($field, array $keys, $escape = true){
587
+	  return $this->in($field, $keys, '', 'OR', $escape);
588
+	}
589
+
590
+	/**
591
+	 * Set the SQL WHERE CLAUSE statment for NOT IN with OR separator
592
+	 * @see  Database::in()
593
+	 * @return object        the current Database instance
594
+	 */
595
+	public function orNotIn($field, array $keys, $escape = true){
596
+	  return $this->in($field, $keys, 'NOT ', 'OR', $escape);
597
+	}
598
+
599
+	/**
600
+	 * Set the SQL WHERE CLAUSE statment for BETWEEN
601
+	 * @param  string  $field  the field used for the BETWEEN statment
602
+	 * @param  mixed  $value1 the BETWEEN begin value
603
+	 * @param  mixed  $value2 the BETWEEN end value
604
+	 * @param  string  $type   the condition separator type (NOT)
605
+	 * @param  string  $andOr the multiple conditions separator (OR, AND)
606
+	 * @param  boolean $escape whether to escape or not the values
607
+	 * @return object        the current Database instance
608
+	 */
609
+	public function between($field, $value1, $value2, $type = '', $andOr = 'AND', $escape = true){
610
+	  if (is_null($value1)){
611
+		$value1 = '';
612
+	  }
613
+	  if (is_null($value2)){
614
+		$value2 = '';
615
+	  }
616
+	  $whereStr = $field . ' ' . $type . ' BETWEEN ' . $this->escape($value1, $escape) . ' AND ' . $this->escape($value2, $escape);
617
+	  $this->setWhereStr($whereStr, $andOr);
618
+	  return $this;
619
+	}
620
+
621
+	/**
622
+	 * Set the SQL WHERE CLAUSE statment for BETWEEN with NOT type and AND separator
623
+	 * @see  Database::between()
624
+	 * @return object        the current Database instance
625
+	 */
626
+	public function notBetween($field, $value1, $value2, $escape = true){
627
+	  return $this->between($field, $value1, $value2, 'NOT ', 'AND', $escape);
628
+	}
629
+
630
+	/**
631
+	 * Set the SQL WHERE CLAUSE statment for BETWEEN with OR separator
632
+	 * @see  Database::between()
633
+	 * @return object        the current Database instance
634
+	 */
635
+	public function orBetween($field, $value1, $value2, $escape = true){
636
+	  return $this->between($field, $value1, $value2, '', 'OR', $escape);
637
+	}
638
+
639
+	/**
640
+	 * Set the SQL WHERE CLAUSE statment for BETWEEN with NOT type and OR separator
641
+	 * @see  Database::between()
642
+	 * @return object        the current Database instance
643
+	 */
644
+	public function orNotBetween($field, $value1, $value2, $escape = true){
645
+	  return $this->between($field, $value1, $value2, 'NOT ', 'OR', $escape);
646
+	}
647
+
648
+	/**
649
+	 * Set the SQL WHERE CLAUSE statment for LIKE
650
+	 * @param  string  $field  the field name used in LIKE statment
651
+	 * @param  string  $data   the LIKE value for this field including the '%', and '_' part
652
+	 * @param  string  $type   the condition separator type (NOT)
653
+	 * @param  string  $andOr the multiple conditions separator (OR, AND)
654
+	 * @param  boolean $escape whether to escape or not the values
655
+	 * @return object        the current Database instance
656
+	 */
657
+	public function like($field, $data, $type = '', $andOr = 'AND', $escape = true){
658
+	  if (empty($data)){
659
+		$data = '';
660
+	  }
661
+	  $this->setWhereStr($field . ' ' . $type . ' LIKE ' . ($this->escape($data, $escape)), $andOr);
662
+	  return $this;
663
+	}
664
+
665
+	/**
666
+	 * Set the SQL WHERE CLAUSE statment for LIKE with OR separator
667
+	 * @see  Database::like()
668
+	 * @return object        the current Database instance
669
+	 */
670
+	public function orLike($field, $data, $escape = true){
671
+	  return $this->like($field, $data, '', 'OR', $escape);
672
+	}
673
+
674
+	/**
675
+	 * Set the SQL WHERE CLAUSE statment for LIKE with NOT type and AND separator
676
+	 * @see  Database::like()
677
+	 * @return object        the current Database instance
678
+	 */
679
+	public function notLike($field, $data, $escape = true){
680
+	  return $this->like($field, $data, 'NOT ', 'AND', $escape);
681
+	}
682
+
683
+	/**
684
+	 * Set the SQL WHERE CLAUSE statment for LIKE with NOT type and OR separator
685
+	 * @see  Database::like()
686
+	 * @return object        the current Database instance
687
+	 */
688
+	public function orNotLike($field, $data, $escape = true){
689
+	  return $this->like($field, $data, 'NOT ', 'OR', $escape);
690
+	}
691
+
692
+	/**
693
+	 * Set the SQL LIMIT statment
694
+	 * @param  int $limit    the limit offset. If $limitEnd is null this will be the limit count
695
+	 * like LIMIT n;
696
+	 * @param  int $limitEnd the limit count
697
+	 * @return object        the current Database instance
698
+	 */
699
+	public function limit($limit, $limitEnd = null){
700
+	  if (empty($limit)){
701
+		return;
702
+	  }
703
+	  if (! is_null($limitEnd)){
704
+		$this->limit = $limit . ', ' . $limitEnd;
705
+	  }
706
+	  else{
707
+		$this->limit = $limit;
708
+	  }
709
+	  return $this;
710
+	}
711
+
712
+	/**
713
+	 * Set the SQL ORDER BY CLAUSE statment
714
+	 * @param  string $orderBy   the field name used for order
715
+	 * @param  string $orderDir the order direction (ASC or DESC)
716
+	 * @return object        the current Database instance
717
+	 */
718
+	public function orderBy($orderBy, $orderDir = ' ASC'){
719
+		if (stristr($orderBy, ' ') || $orderBy == 'rand()'){
720
+		  $this->orderBy = empty($this->orderBy) ? $orderBy : $this->orderBy . ', ' . $orderBy;
721
+		}
722
+		else{
723
+		  $this->orderBy = empty($this->orderBy) ? ($orderBy . ' ' 
724
+							. strtoupper($orderDir)) : $this->orderBy 
725
+							. ', ' . $orderBy . ' ' . strtoupper($orderDir);
726
+		}
727
+	  return $this;
728
+	}
729
+
730
+	/**
731
+	 * Set the SQL GROUP BY CLAUSE statment
732
+	 * @param  string|array $field the field name used or array of field list
733
+	 * @return object        the current Database instance
734
+	 */
735
+	public function groupBy($field){
736
+	  if (is_array($field)){
737
+		$this->groupBy = implode(', ', $field);
738
+	  }
739
+	  else{
740
+		$this->groupBy = $field;
741
+	  }
742
+	  return $this;
743
+	}
744
+
745
+	/**
746
+	 * Set the SQL HAVING CLAUSE statment
747
+	 * @param  string  $field  the field name used for HAVING statment
748
+	 * @param  string|array  $op     the operator used or array
749
+	 * @param  mixed  $val    the value for HAVING comparaison
750
+	 * @param  boolean $escape whether to escape or not the values
751
+	 * @return object        the current Database instance
752
+	 */
753
+	public function having($field, $op = null, $val = null, $escape = true){
754
+	  if (is_array($op)){
755
+		$x = explode('?', $field);
756
+		$w = '';
757
+		foreach($x as $k => $v){
758
+  		  if (!empty($v)){
759
+			if (! isset($op[$k])){
760
+			  $op[$k] = '';
761
+			}
762
+  		  	$w .= $v . (isset($op[$k]) ? $this->escape($op[$k], $escape) : '');
763
+  		  }
764
+	  	}
765
+		$this->having = $w;
766
+	  }
767
+	  else if (! in_array($op, $this->operatorList)){
768
+		if (is_null($op)){
769
+		  $op = '';
770
+		}
771
+		$this->having = $field . ' > ' . ($this->escape($op, $escape));
772
+	  }
773
+	  else{
774
+		if (is_null($val)){
775
+		  $val = '';
776
+		}
777
+		$this->having = $field . ' ' . $op . ' ' . ($this->escape($val, $escape));
778
+	  }
779
+	  return $this;
780
+	}
781
+
782
+	/**
783
+	 * Return the number of rows returned by the current query
784
+	 * @return int
785
+	 */
786
+	public function numRows(){
787
+	  return $this->numRows;
788
+	}
789
+
790
+	/**
791
+	 * Return the last insert id value
792
+	 * @return mixed
793
+	 */
794
+	public function insertId(){
795
+	  return $this->insertId;
796
+	}
797
+
798
+	/**
799
+	 * Show an error got from the current query (SQL command synthax error, database driver returned error, etc.)
800
+	 */
801
+	public function error(){
802 802
   		if ($this->error){
803 803
   			show_error('Query: "' . $this->query . '" Error: ' . $this->error, 'Database Error');
804 804
   		}
805
-    }
806
-
807
-    /**
808
-     * Get the result of one record rows returned by the current query
809
-     * @param  boolean $returnSQLQueryOrResultType if is boolean and true will return the SQL query string.
810
-     * If is string will determine the result type "array" or "object"
811
-     * @return mixed       the query SQL string or the record result
812
-     */
813
-    public function get($returnSQLQueryOrResultType = false){
814
-      $this->limit = 1;
815
-      $query = $this->getAll(true);
816
-      if ($returnSQLQueryOrResultType === true){
817
-        return $query;
818
-      }
819
-      else{
820
-        return $this->query( $query, false, (($returnSQLQueryOrResultType == 'array') ? true : false) );
821
-      }
822
-    }
823
-
824
-    /**
825
-     * Get the result of record rows list returned by the current query
826
-     * @param  boolean|string $returnSQLQueryOrResultType if is boolean and true will return the SQL query string.
827
-     * If is string will determine the result type "array" or "object"
828
-     * @return mixed       the query SQL string or the record result
829
-     */
830
-    public function getAll($returnSQLQueryOrResultType = false){
831
-      $query = 'SELECT ' . $this->select . ' FROM ' . $this->from;
832
-      if (! empty($this->join)){
833
-        $query .= $this->join;
834
-      }
805
+	}
806
+
807
+	/**
808
+	 * Get the result of one record rows returned by the current query
809
+	 * @param  boolean $returnSQLQueryOrResultType if is boolean and true will return the SQL query string.
810
+	 * If is string will determine the result type "array" or "object"
811
+	 * @return mixed       the query SQL string or the record result
812
+	 */
813
+	public function get($returnSQLQueryOrResultType = false){
814
+	  $this->limit = 1;
815
+	  $query = $this->getAll(true);
816
+	  if ($returnSQLQueryOrResultType === true){
817
+		return $query;
818
+	  }
819
+	  else{
820
+		return $this->query( $query, false, (($returnSQLQueryOrResultType == 'array') ? true : false) );
821
+	  }
822
+	}
823
+
824
+	/**
825
+	 * Get the result of record rows list returned by the current query
826
+	 * @param  boolean|string $returnSQLQueryOrResultType if is boolean and true will return the SQL query string.
827
+	 * If is string will determine the result type "array" or "object"
828
+	 * @return mixed       the query SQL string or the record result
829
+	 */
830
+	public function getAll($returnSQLQueryOrResultType = false){
831
+	  $query = 'SELECT ' . $this->select . ' FROM ' . $this->from;
832
+	  if (! empty($this->join)){
833
+		$query .= $this->join;
834
+	  }
835 835
 	  
836
-      if (! empty($this->where)){
837
-        $query .= ' WHERE ' . $this->where;
838
-      }
836
+	  if (! empty($this->where)){
837
+		$query .= ' WHERE ' . $this->where;
838
+	  }
839 839
 
840
-      if (! empty($this->groupBy)){
841
-        $query .= ' GROUP BY ' . $this->groupBy;
842
-      }
840
+	  if (! empty($this->groupBy)){
841
+		$query .= ' GROUP BY ' . $this->groupBy;
842
+	  }
843 843
 
844
-      if (! empty($this->having)){
845
-        $query .= ' HAVING ' . $this->having;
846
-      }
844
+	  if (! empty($this->having)){
845
+		$query .= ' HAVING ' . $this->having;
846
+	  }
847 847
 
848
-      if (! empty($this->orderBy)){
849
-          $query .= ' ORDER BY ' . $this->orderBy;
850
-      }
848
+	  if (! empty($this->orderBy)){
849
+		  $query .= ' ORDER BY ' . $this->orderBy;
850
+	  }
851 851
 
852
-      if (! empty($this->limit)){
853
-      	$query .= ' LIMIT ' . $this->limit;
854
-      }
852
+	  if (! empty($this->limit)){
853
+	  	$query .= ' LIMIT ' . $this->limit;
854
+	  }
855 855
 	  
856 856
 	   if ($returnSQLQueryOrResultType === true){
857
-      	return $query;
858
-      }
859
-    	return $this->query($query, true, $returnSQLQueryOrResultType == 'array');
860
-    }
861
-
862
-    /**
863
-     * Insert new record in the database
864
-     * @param  array   $data   the record data if is empty will use the $this->data array.
865
-     * @param  boolean $escape  whether to escape or not the values
866
-     * @return mixed          the insert id of the new record or null
867
-     */
868
-    public function insert($data = array(), $escape = true){
869
-      if (empty($data) && $this->getData()){
870
-        //as when using $this->setData() the data already escaped
871
-        $escape = false;
872
-        $data = $this->getData();
873
-      }
874
-
875
-      $columns = array_keys($data);
876
-      $column = implode(',', $columns);
877
-      $val = implode(', ', ($escape ? array_map(array($this, 'escape'), $data) : $data));
878
-
879
-      $query = 'INSERT INTO ' . $this->from . ' (' . $column . ') VALUES (' . $val . ')';
880
-      $query = $this->query($query);
881
-
882
-      if ($query){
883
-        $this->insertId = $this->pdo->lastInsertId();
884
-        return $this->insertId();
885
-      }
886
-      return false;
887
-    }
888
-
889
-    /**
890
-     * Update record in the database
891
-     * @param  array   $data   the record data if is empty will use the $this->data array.
892
-     * @param  boolean $escape  whether to escape or not the values
893
-     * @return mixed          the update status
894
-     */
895
-    public function update($data = array(), $escape = true){
896
-      $query = 'UPDATE ' . $this->from . ' SET ';
897
-      $values = array();
898
-      if (empty($data) && $this->getData()){
899
-        //as when using $this->setData() the data already escaped
900
-        $escape = false;
901
-        $data = $this->getData();
902
-      }
903
-      foreach ($data as $column => $val){
904
-        $values[] = $column . ' = ' . ($this->escape($val, $escape));
905
-      }
906
-      $query .= implode(', ', $values);
907
-      if (! empty($this->where)){
908
-        $query .= ' WHERE ' . $this->where;
909
-      }
910
-
911
-      if (! empty($this->orderBy)){
912
-        $query .= ' ORDER BY ' . $this->orderBy;
913
-      }
914
-
915
-      if (! empty($this->limit)){
916
-        $query .= ' LIMIT ' . $this->limit;
917
-      }
918
-      return $this->query($query);
919
-    }
920
-
921
-    /**
922
-     * Delete the record in database
923
-     * @return mixed the delete status
924
-     */
925
-    public function delete(){
926
-    	$query = 'DELETE FROM ' . $this->from;
927
-
928
-    	if (! empty($this->where)){
929
-    		$query .= ' WHERE ' . $this->where;
930
-      	}
931
-
932
-    	if (! empty($this->orderBy)){
933
-    	  $query .= ' ORDER BY ' . $this->orderBy;
934
-      	}
935
-
936
-    	if (! empty($this->limit)){
937
-    		$query .= ' LIMIT ' . $this->limit;
938
-      	}
939
-
940
-    	if ($query == 'DELETE FROM ' . $this->from && $this->config['driver'] != 'sqlite'){  
941
-    		$query = 'TRUNCATE TABLE ' . $this->from;
942
-      }
943
-    	return $this->query($query);
944
-    }
945
-
946
-    /**
947
-     * Set database cache time to live
948
-     * @param integer $ttl the cache time to live in second
949
-     * @return object        the current Database instance
950
-     */
951
-    public function setCache($ttl = 0){
952
-      if ($ttl > 0){
953
-        $this->cacheTtl = $ttl;
954
-		    $this->temporaryCacheTtl = $ttl;
955
-      }
956
-      return $this;
957
-    }
857
+	  	return $query;
858
+	  }
859
+		return $this->query($query, true, $returnSQLQueryOrResultType == 'array');
860
+	}
861
+
862
+	/**
863
+	 * Insert new record in the database
864
+	 * @param  array   $data   the record data if is empty will use the $this->data array.
865
+	 * @param  boolean $escape  whether to escape or not the values
866
+	 * @return mixed          the insert id of the new record or null
867
+	 */
868
+	public function insert($data = array(), $escape = true){
869
+	  if (empty($data) && $this->getData()){
870
+		//as when using $this->setData() the data already escaped
871
+		$escape = false;
872
+		$data = $this->getData();
873
+	  }
874
+
875
+	  $columns = array_keys($data);
876
+	  $column = implode(',', $columns);
877
+	  $val = implode(', ', ($escape ? array_map(array($this, 'escape'), $data) : $data));
878
+
879
+	  $query = 'INSERT INTO ' . $this->from . ' (' . $column . ') VALUES (' . $val . ')';
880
+	  $query = $this->query($query);
881
+
882
+	  if ($query){
883
+		$this->insertId = $this->pdo->lastInsertId();
884
+		return $this->insertId();
885
+	  }
886
+	  return false;
887
+	}
888
+
889
+	/**
890
+	 * Update record in the database
891
+	 * @param  array   $data   the record data if is empty will use the $this->data array.
892
+	 * @param  boolean $escape  whether to escape or not the values
893
+	 * @return mixed          the update status
894
+	 */
895
+	public function update($data = array(), $escape = true){
896
+	  $query = 'UPDATE ' . $this->from . ' SET ';
897
+	  $values = array();
898
+	  if (empty($data) && $this->getData()){
899
+		//as when using $this->setData() the data already escaped
900
+		$escape = false;
901
+		$data = $this->getData();
902
+	  }
903
+	  foreach ($data as $column => $val){
904
+		$values[] = $column . ' = ' . ($this->escape($val, $escape));
905
+	  }
906
+	  $query .= implode(', ', $values);
907
+	  if (! empty($this->where)){
908
+		$query .= ' WHERE ' . $this->where;
909
+	  }
910
+
911
+	  if (! empty($this->orderBy)){
912
+		$query .= ' ORDER BY ' . $this->orderBy;
913
+	  }
914
+
915
+	  if (! empty($this->limit)){
916
+		$query .= ' LIMIT ' . $this->limit;
917
+	  }
918
+	  return $this->query($query);
919
+	}
920
+
921
+	/**
922
+	 * Delete the record in database
923
+	 * @return mixed the delete status
924
+	 */
925
+	public function delete(){
926
+		$query = 'DELETE FROM ' . $this->from;
927
+
928
+		if (! empty($this->where)){
929
+			$query .= ' WHERE ' . $this->where;
930
+	  	}
931
+
932
+		if (! empty($this->orderBy)){
933
+		  $query .= ' ORDER BY ' . $this->orderBy;
934
+	  	}
935
+
936
+		if (! empty($this->limit)){
937
+			$query .= ' LIMIT ' . $this->limit;
938
+	  	}
939
+
940
+		if ($query == 'DELETE FROM ' . $this->from && $this->config['driver'] != 'sqlite'){  
941
+			$query = 'TRUNCATE TABLE ' . $this->from;
942
+	  }
943
+		return $this->query($query);
944
+	}
945
+
946
+	/**
947
+	 * Set database cache time to live
948
+	 * @param integer $ttl the cache time to live in second
949
+	 * @return object        the current Database instance
950
+	 */
951
+	public function setCache($ttl = 0){
952
+	  if ($ttl > 0){
953
+		$this->cacheTtl = $ttl;
954
+			$this->temporaryCacheTtl = $ttl;
955
+	  }
956
+	  return $this;
957
+	}
958 958
 	
959 959
 	/**
960 960
 	 * Enabled cache temporary for the current query not globally	
@@ -962,564 +962,564 @@  discard block
 block discarded – undo
962 962
 	 * @return object        the current Database instance
963 963
 	 */
964 964
 	public function cached($ttl = 0){
965
-      if ($ttl > 0){
966
-        $this->temporaryCacheTtl = $ttl;
967
-      }
965
+	  if ($ttl > 0){
966
+		$this->temporaryCacheTtl = $ttl;
967
+	  }
968 968
 	  return $this;
969
-    }
970
-
971
-    /**
972
-     * Escape the data before execute query useful for security.
973
-     * @param  mixed $data the data to be escaped
974
-     * @param boolean $escaped whether we can do escape of not 
975
-     * @return mixed       the data after escaped or the same data if not
976
-     */
977
-    public function escape($data, $escaped = true){
978
-      if ($escaped){
979
-        if (! $this->pdo){
980
-          $this->connect();
981
-        }
982
-        return $this->pdo->quote(trim($data)); 
983
-      }
984
-      return $data;
985
-    }
986
-
987
-    /**
988
-     * Return the number query executed count for the current request
989
-     * @return int
990
-     */
991
-    public function queryCount(){
992
-      return $this->queryCount;
993
-    }
994
-
995
-    /**
996
-     * Return the current query SQL string
997
-     * @return string
998
-     */
999
-    public function getQuery(){
1000
-      return $this->query;
1001
-    }
1002
-
1003
-    /**
1004
-     * Return the application database name
1005
-     * @return string
1006
-     */
1007
-    public function getDatabaseName(){
1008
-      return $this->databaseName;
1009
-    }
1010
-
1011
-     /**
1012
-     * Return the database configuration
1013
-     * @return array
1014
-     */
1015
-    public  function getDatabaseConfiguration(){
1016
-      return $this->config;
1017
-    }
1018
-
1019
-    /**
1020
-     * set the database configuration
1021
-     * @param array $config the configuration
1022
-     */
1023
-    public function setDatabaseConfiguration(array $config){
1024
-      $this->config = array_merge($this->config, $config);
1025
-      $this->prefix = $this->config['prefix'];
1026
-      $this->databaseName = $this->config['database'];
1027
-      $this->logger->info('The database configuration are listed below: ' . stringfy_vars(array_merge($this->config, array('password' => string_hidden($this->config['password'])))));
1028
-      return $this;
1029
-    }
1030
-
1031
-    /**
1032
-     * Return the PDO instance
1033
-     * @return PDO
1034
-     */
1035
-    public function getPdo(){
1036
-      return $this->pdo;
1037
-    }
1038
-
1039
-    /**
1040
-     * Set the PDO instance
1041
-     * @param PDO $pdo the pdo object
1042
-     */
1043
-    public function setPdo(PDO $pdo){
1044
-      $this->pdo = $pdo;
1045
-      return $this;
1046
-    }
1047
-
1048
-
1049
-    /**
1050
-     * Return the Log instance
1051
-     * @return Log
1052
-     */
1053
-    public function getLogger(){
1054
-      return $this->logger;
1055
-    }
1056
-
1057
-    /**
1058
-     * Set the log instance
1059
-     * @param Log $logger the log object
1060
-     */
1061
-    public function setLogger($logger){
1062
-      $this->logger = $logger;
1063
-      return $this;
1064
-    }
1065
-
1066
-     /**
1067
-     * Return the cache instance
1068
-     * @return CacheInterface
1069
-     */
1070
-    public function getCacheInstance(){
1071
-      return $this->cacheInstance;
1072
-    }
1073
-
1074
-    /**
1075
-     * Set the cache instance
1076
-     * @param CacheInterface $cache the cache object
1077
-     */
1078
-    public function setCacheInstance($cache){
1079
-      $this->cacheInstance = $cache;
1080
-      return $this;
1081
-    }
1082
-
1083
-    /**
1084
-     * Return the benchmark instance
1085
-     * @return Benchmark
1086
-     */
1087
-    public function getBenchmark(){
1088
-      return $this->benchmarkInstance;
1089
-    }
1090
-
1091
-    /**
1092
-     * Set the benchmark instance
1093
-     * @param Benchmark $cache the cache object
1094
-     */
1095
-    public function setBenchmark($benchmark){
1096
-      $this->benchmarkInstance = $benchmark;
1097
-      return $this;
1098
-    }
1099
-
1100
-    /**
1101
-     * Return the data to be used for insert, update, etc.
1102
-     * @return array
1103
-     */
1104
-    public function getData(){
1105
-      return $this->data;
1106
-    }
1107
-
1108
-    /**
1109
-     * Set the data to be used for insert, update, etc.
1110
-     * @param string $key the data key identified
1111
-     * @param mixed $value the data value
1112
-     * @param boolean $escape whether to escape or not the $value
1113
-     * @return object        the current Database instance
1114
-     */
1115
-    public function setData($key, $value, $escape = true){
1116
-      $this->data[$key] = $this->escape($value, $escape);
1117
-      return $this;
1118
-    }
1119
-
1120
-     /**
1121
-     * Execute an SQL query
1122
-     * @param  string  $query the query SQL string
1123
-     * @param  boolean|array $all  if boolean this indicate whether to return all record or not, if array 
1124
-     * will 
1125
-     * @param  boolean $array return the result as array
1126
-     * @return mixed         the query result
1127
-     */
1128
-    public function query($query, $all = true, $array = false){
1129
-      $this->reset();
1130
-      $query = $this->transformPreparedQuery($query, $all);
1131
-      $this->query = preg_replace('/\s\s+|\t\t+/', ' ', trim($query));
969
+	}
970
+
971
+	/**
972
+	 * Escape the data before execute query useful for security.
973
+	 * @param  mixed $data the data to be escaped
974
+	 * @param boolean $escaped whether we can do escape of not 
975
+	 * @return mixed       the data after escaped or the same data if not
976
+	 */
977
+	public function escape($data, $escaped = true){
978
+	  if ($escaped){
979
+		if (! $this->pdo){
980
+		  $this->connect();
981
+		}
982
+		return $this->pdo->quote(trim($data)); 
983
+	  }
984
+	  return $data;
985
+	}
986
+
987
+	/**
988
+	 * Return the number query executed count for the current request
989
+	 * @return int
990
+	 */
991
+	public function queryCount(){
992
+	  return $this->queryCount;
993
+	}
994
+
995
+	/**
996
+	 * Return the current query SQL string
997
+	 * @return string
998
+	 */
999
+	public function getQuery(){
1000
+	  return $this->query;
1001
+	}
1002
+
1003
+	/**
1004
+	 * Return the application database name
1005
+	 * @return string
1006
+	 */
1007
+	public function getDatabaseName(){
1008
+	  return $this->databaseName;
1009
+	}
1010
+
1011
+	 /**
1012
+	  * Return the database configuration
1013
+	  * @return array
1014
+	  */
1015
+	public  function getDatabaseConfiguration(){
1016
+	  return $this->config;
1017
+	}
1018
+
1019
+	/**
1020
+	 * set the database configuration
1021
+	 * @param array $config the configuration
1022
+	 */
1023
+	public function setDatabaseConfiguration(array $config){
1024
+	  $this->config = array_merge($this->config, $config);
1025
+	  $this->prefix = $this->config['prefix'];
1026
+	  $this->databaseName = $this->config['database'];
1027
+	  $this->logger->info('The database configuration are listed below: ' . stringfy_vars(array_merge($this->config, array('password' => string_hidden($this->config['password'])))));
1028
+	  return $this;
1029
+	}
1030
+
1031
+	/**
1032
+	 * Return the PDO instance
1033
+	 * @return PDO
1034
+	 */
1035
+	public function getPdo(){
1036
+	  return $this->pdo;
1037
+	}
1038
+
1039
+	/**
1040
+	 * Set the PDO instance
1041
+	 * @param PDO $pdo the pdo object
1042
+	 */
1043
+	public function setPdo(PDO $pdo){
1044
+	  $this->pdo = $pdo;
1045
+	  return $this;
1046
+	}
1047
+
1048
+
1049
+	/**
1050
+	 * Return the Log instance
1051
+	 * @return Log
1052
+	 */
1053
+	public function getLogger(){
1054
+	  return $this->logger;
1055
+	}
1056
+
1057
+	/**
1058
+	 * Set the log instance
1059
+	 * @param Log $logger the log object
1060
+	 */
1061
+	public function setLogger($logger){
1062
+	  $this->logger = $logger;
1063
+	  return $this;
1064
+	}
1065
+
1066
+	 /**
1067
+	  * Return the cache instance
1068
+	  * @return CacheInterface
1069
+	  */
1070
+	public function getCacheInstance(){
1071
+	  return $this->cacheInstance;
1072
+	}
1073
+
1074
+	/**
1075
+	 * Set the cache instance
1076
+	 * @param CacheInterface $cache the cache object
1077
+	 */
1078
+	public function setCacheInstance($cache){
1079
+	  $this->cacheInstance = $cache;
1080
+	  return $this;
1081
+	}
1082
+
1083
+	/**
1084
+	 * Return the benchmark instance
1085
+	 * @return Benchmark
1086
+	 */
1087
+	public function getBenchmark(){
1088
+	  return $this->benchmarkInstance;
1089
+	}
1090
+
1091
+	/**
1092
+	 * Set the benchmark instance
1093
+	 * @param Benchmark $cache the cache object
1094
+	 */
1095
+	public function setBenchmark($benchmark){
1096
+	  $this->benchmarkInstance = $benchmark;
1097
+	  return $this;
1098
+	}
1099
+
1100
+	/**
1101
+	 * Return the data to be used for insert, update, etc.
1102
+	 * @return array
1103
+	 */
1104
+	public function getData(){
1105
+	  return $this->data;
1106
+	}
1107
+
1108
+	/**
1109
+	 * Set the data to be used for insert, update, etc.
1110
+	 * @param string $key the data key identified
1111
+	 * @param mixed $value the data value
1112
+	 * @param boolean $escape whether to escape or not the $value
1113
+	 * @return object        the current Database instance
1114
+	 */
1115
+	public function setData($key, $value, $escape = true){
1116
+	  $this->data[$key] = $this->escape($value, $escape);
1117
+	  return $this;
1118
+	}
1119
+
1120
+	 /**
1121
+	  * Execute an SQL query
1122
+	  * @param  string  $query the query SQL string
1123
+	  * @param  boolean|array $all  if boolean this indicate whether to return all record or not, if array 
1124
+	  * will 
1125
+	  * @param  boolean $array return the result as array
1126
+	  * @return mixed         the query result
1127
+	  */
1128
+	public function query($query, $all = true, $array = false){
1129
+	  $this->reset();
1130
+	  $query = $this->transformPreparedQuery($query, $all);
1131
+	  $this->query = preg_replace('/\s\s+|\t\t+/', ' ', trim($query));
1132 1132
       
1133
-      $isSqlSELECTQuery = stristr($this->query, 'SELECT');
1133
+	  $isSqlSELECTQuery = stristr($this->query, 'SELECT');
1134 1134
 
1135
-      $this->logger->info('Execute SQL query ['.$this->query.'], return type: ' . ($array?'ARRAY':'OBJECT') .', return as list: ' . (is_bool($all) && $all ? 'YES':'NO'));
1136
-      //cache expire time
1137
-      $cacheExpire = $this->temporaryCacheTtl;
1135
+	  $this->logger->info('Execute SQL query ['.$this->query.'], return type: ' . ($array?'ARRAY':'OBJECT') .', return as list: ' . (is_bool($all) && $all ? 'YES':'NO'));
1136
+	  //cache expire time
1137
+	  $cacheExpire = $this->temporaryCacheTtl;
1138 1138
       
1139
-      //return to the initial cache time
1140
-      $this->temporaryCacheTtl = $this->cacheTtl;
1139
+	  //return to the initial cache time
1140
+	  $this->temporaryCacheTtl = $this->cacheTtl;
1141 1141
       
1142
-      //config for cache
1143
-      $cacheEnable = get_config('cache_enable');
1142
+	  //config for cache
1143
+	  $cacheEnable = get_config('cache_enable');
1144 1144
       
1145
-      //the database cache content
1146
-      $cacheContent = null;
1145
+	  //the database cache content
1146
+	  $cacheContent = null;
1147 1147
 
1148
-      //if can use cache feature for this query
1149
-      $dbCacheStatus = $cacheEnable && $cacheExpire > 0;
1148
+	  //if can use cache feature for this query
1149
+	  $dbCacheStatus = $cacheEnable && $cacheExpire > 0;
1150 1150
     
1151
-      if ($dbCacheStatus && $isSqlSELECTQuery){
1152
-          $this->logger->info('The cache is enabled for this query, try to get result from cache'); 
1153
-          $cacheContent = $this->getCacheContentForQuery($query, $all, $array);  
1154
-      }
1151
+	  if ($dbCacheStatus && $isSqlSELECTQuery){
1152
+		  $this->logger->info('The cache is enabled for this query, try to get result from cache'); 
1153
+		  $cacheContent = $this->getCacheContentForQuery($query, $all, $array);  
1154
+	  }
1155 1155
       
1156
-      if ( !$cacheContent){
1157
-        $sqlQuery = $this->runSqlQuery($query, $all, $array);
1158
-        if (is_object($sqlQuery)){
1159
-          if ($isSqlSELECTQuery){
1160
-            $this->setQueryResultForSelect($sqlQuery, $all, $array);
1161
-            $this->setCacheContentForQuery(
1162
-                                            $this->query, 
1163
-                                            $this->getCacheBenchmarkKeyForQuery($this->query, $all, $array), 
1164
-                                            $this->result, 
1165
-                                            $dbCacheStatus && $isSqlSELECTQuery, 
1166
-                                            $this->temporaryCacheTtl
1167
-                                          );
1168
-          }
1169
-          else{
1170
-              $this->setQueryResultForNonSelect($sqlQuery);
1171
-              if (! $this->result){
1172
-                $this->setQueryError();
1173
-              }
1174
-          }
1175
-        }
1176
-      } else if ($isSqlSELECTQuery){
1177
-          $this->logger->info('The result for query [' .$this->query. '] already cached use it');
1178
-          $this->result = $cacheContent;
1179
-          $this->numRows = count($this->result);
1180
-      }
1181
-      $this->queryCount++;
1182
-      if (! $this->result){
1183
-        $this->logger->info('No result where found for the query [' . $query . ']');
1184
-      }
1185
-      return $this->result;
1186
-    }
1187
-
1188
-
1189
-    /**
1190
-     * Set the Log instance using argument or create new instance
1191
-     * @param object $logger the Log instance if not null
1192
-     */
1193
-    protected function setLoggerFromParamOrCreateNewInstance(Log $logger = null){
1194
-      if ($logger !== null){
1195
-        $this->logger = $logger;
1196
-      }
1197
-      else{
1198
-          $this->logger =& class_loader('Log', 'classes');
1199
-          $this->logger->setLogger('Library::Database');
1200
-      }
1201
-    }
1156
+	  if ( !$cacheContent){
1157
+		$sqlQuery = $this->runSqlQuery($query, $all, $array);
1158
+		if (is_object($sqlQuery)){
1159
+		  if ($isSqlSELECTQuery){
1160
+			$this->setQueryResultForSelect($sqlQuery, $all, $array);
1161
+			$this->setCacheContentForQuery(
1162
+											$this->query, 
1163
+											$this->getCacheBenchmarkKeyForQuery($this->query, $all, $array), 
1164
+											$this->result, 
1165
+											$dbCacheStatus && $isSqlSELECTQuery, 
1166
+											$this->temporaryCacheTtl
1167
+										  );
1168
+		  }
1169
+		  else{
1170
+			  $this->setQueryResultForNonSelect($sqlQuery);
1171
+			  if (! $this->result){
1172
+				$this->setQueryError();
1173
+			  }
1174
+		  }
1175
+		}
1176
+	  } else if ($isSqlSELECTQuery){
1177
+		  $this->logger->info('The result for query [' .$this->query. '] already cached use it');
1178
+		  $this->result = $cacheContent;
1179
+		  $this->numRows = count($this->result);
1180
+	  }
1181
+	  $this->queryCount++;
1182
+	  if (! $this->result){
1183
+		$this->logger->info('No result where found for the query [' . $query . ']');
1184
+	  }
1185
+	  return $this->result;
1186
+	}
1187
+
1188
+
1189
+	/**
1190
+	 * Set the Log instance using argument or create new instance
1191
+	 * @param object $logger the Log instance if not null
1192
+	 */
1193
+	protected function setLoggerFromParamOrCreateNewInstance(Log $logger = null){
1194
+	  if ($logger !== null){
1195
+		$this->logger = $logger;
1196
+	  }
1197
+	  else{
1198
+		  $this->logger =& class_loader('Log', 'classes');
1199
+		  $this->logger->setLogger('Library::Database');
1200
+	  }
1201
+	}
1202 1202
 
1203 1203
    /**
1204 1204
     * Setting the database configuration using the configuration file
1205 1205
     * @param array $overwriteConfig the additional configuration to overwrite with the existing one
1206 1206
     */
1207
-    protected function setDatabaseConfigurationFromConfigFile(array $overwriteConfig = array()){
1208
-        $db = array();
1209
-        if (file_exists(CONFIG_PATH . 'database.php')){
1210
-            //here don't use require_once because somewhere user can create database instance directly
1211
-            require CONFIG_PATH . 'database.php';
1212
-        }
1207
+	protected function setDatabaseConfigurationFromConfigFile(array $overwriteConfig = array()){
1208
+		$db = array();
1209
+		if (file_exists(CONFIG_PATH . 'database.php')){
1210
+			//here don't use require_once because somewhere user can create database instance directly
1211
+			require CONFIG_PATH . 'database.php';
1212
+		}
1213 1213
           
1214
-        if (! empty($overwriteConfig)){
1215
-          $db = array_merge($db, $overwriteConfig);
1216
-        }
1217
-        $config = array(
1218
-          'driver' => 'mysql',
1219
-          'username' => 'root',
1220
-          'password' => '',
1221
-          'database' => '',
1222
-          'hostname' => 'localhost',
1223
-          'charset' => 'utf8',
1224
-          'collation' => 'utf8_general_ci',
1225
-          'prefix' => '',
1226
-          'port' => ''
1227
-        );
1228
-        $this->setDatabaseConfiguration(array_merge($config, $db));
1229
-        $this->setPortConfigurationFromHostname();  
1230
-    }
1231
-
1232
-    /**
1233
-     * This method is used to get the PDO DSN string using th configured driver
1234
-     * @return string the DSN string
1235
-     */
1236
-    protected function getDsnFromDriver(){
1237
-      $config = $this->getDatabaseConfiguration();
1238
-      if (! empty($config)){
1239
-            $driverDsnMap = array(
1240
-                                    'mysql' => 'mysql:host=' . $config['hostname'] . ';' 
1241
-                                                . (($config['port']) != '' ? 'port=' . $config['port'] . ';' : '') 
1242
-                                                . 'dbname=' . $config['database'],
1243
-                                    'pgsql' => 'pgsql:host=' . $config['hostname'] . ';' 
1244
-                                                . (($config['port']) != '' ? 'port=' . $config['port'] . ';' : '')
1245
-                                                . 'dbname=' . $config['database'],
1246
-                                    'sqlite' => 'sqlite:' . $config['database'],
1247
-                                    'oracle' => 'oci:dbname=' . $config['hostname'] 
1248
-                                                . (($config['port']) != '' ? ':' . $config['port'] : '')
1249
-                                                . '/' . $config['database']
1250
-                                  );
1251
-            return isset($driverDsnMap[$config['driver']]) ? $driverDsnMap[$config['driver']] : '';
1252
-      }                   
1253
-      return null;
1254
-    }
1255
-
1256
-    /**
1257
-     * Set the database server port configuration using the current hostname like localhost:3309 
1258
-     * @return void
1259
-     */
1260
-    protected function setPortConfigurationFromHostname(){
1261
-      if (strstr($this->config['hostname'], ':')){
1262
-        $p = explode(':', $this->config['hostname']);
1263
-        if (count($p) >= 2){
1264
-          $this->setDatabaseConfiguration(array(
1265
-            'hostname' => $p[0],
1266
-            'port' => $p[1]
1267
-          ));
1268
-        }
1269
-      }
1270
-    }
1214
+		if (! empty($overwriteConfig)){
1215
+		  $db = array_merge($db, $overwriteConfig);
1216
+		}
1217
+		$config = array(
1218
+		  'driver' => 'mysql',
1219
+		  'username' => 'root',
1220
+		  'password' => '',
1221
+		  'database' => '',
1222
+		  'hostname' => 'localhost',
1223
+		  'charset' => 'utf8',
1224
+		  'collation' => 'utf8_general_ci',
1225
+		  'prefix' => '',
1226
+		  'port' => ''
1227
+		);
1228
+		$this->setDatabaseConfiguration(array_merge($config, $db));
1229
+		$this->setPortConfigurationFromHostname();  
1230
+	}
1231
+
1232
+	/**
1233
+	 * This method is used to get the PDO DSN string using th configured driver
1234
+	 * @return string the DSN string
1235
+	 */
1236
+	protected function getDsnFromDriver(){
1237
+	  $config = $this->getDatabaseConfiguration();
1238
+	  if (! empty($config)){
1239
+			$driverDsnMap = array(
1240
+									'mysql' => 'mysql:host=' . $config['hostname'] . ';' 
1241
+												. (($config['port']) != '' ? 'port=' . $config['port'] . ';' : '') 
1242
+												. 'dbname=' . $config['database'],
1243
+									'pgsql' => 'pgsql:host=' . $config['hostname'] . ';' 
1244
+												. (($config['port']) != '' ? 'port=' . $config['port'] . ';' : '')
1245
+												. 'dbname=' . $config['database'],
1246
+									'sqlite' => 'sqlite:' . $config['database'],
1247
+									'oracle' => 'oci:dbname=' . $config['hostname'] 
1248
+												. (($config['port']) != '' ? ':' . $config['port'] : '')
1249
+												. '/' . $config['database']
1250
+								  );
1251
+			return isset($driverDsnMap[$config['driver']]) ? $driverDsnMap[$config['driver']] : '';
1252
+	  }                   
1253
+	  return null;
1254
+	}
1255
+
1256
+	/**
1257
+	 * Set the database server port configuration using the current hostname like localhost:3309 
1258
+	 * @return void
1259
+	 */
1260
+	protected function setPortConfigurationFromHostname(){
1261
+	  if (strstr($this->config['hostname'], ':')){
1262
+		$p = explode(':', $this->config['hostname']);
1263
+		if (count($p) >= 2){
1264
+		  $this->setDatabaseConfiguration(array(
1265
+			'hostname' => $p[0],
1266
+			'port' => $p[1]
1267
+		  ));
1268
+		}
1269
+	  }
1270
+	}
1271 1271
 
1272 1272
    /**
1273
-     * Get the SQL WHERE clause using array column => value
1274
-     * @see Database::where
1275
-     *
1276
-     * @return string
1277
-     */
1278
-    protected function getWhereStrIfIsArray(array $where, $type = '', $andOr = 'AND', $escape = true){
1279
-        $_where = array();
1280
-        foreach ($where as $column => $data){
1281
-          if (is_null($data)){
1282
-            $data = '';
1283
-          }
1284
-          $_where[] = $type . $column . ' = ' . ($this->escape($data, $escape));
1285
-        }
1286
-        $where = implode(' '.$andOr.' ', $_where);
1287
-        return $where;
1288
-    }
1289
-
1290
-     /**
1291
-     * Get the SQL WHERE clause when operator argument is an array
1292
-     * @see Database::where
1293
-     *
1294
-     * @return string
1295
-     */
1296
-    protected function getWhereStrIfOperatorIsArray($where, array $op, $type = '', $escape = true){
1297
-       $x = explode('?', $where);
1298
-       $w = '';
1299
-        foreach($x as $k => $v){
1300
-          if (! empty($v)){
1301
-              if (isset($op[$k]) && is_null($op[$k])){
1302
-                $op[$k] = '';
1303
-              }
1304
-              $w .= $type . $v . (isset($op[$k]) ? ($this->escape($op[$k], $escape)) : '');
1305
-          }
1306
-        }
1307
-        return $w;
1308
-    }
1309
-
1310
-    /**
1311
-     * Get the default SQL WHERE clause using operator = or the operator argument
1312
-     * @see Database::where
1313
-     *
1314
-     * @return string
1315
-     */
1316
-    protected function getWhereStrForOperator($where, $op = null, $val = null, $type = '', $escape = true){
1317
-       $w = '';
1318
-       if (! in_array((string)$op, $this->operatorList)){
1319
-          if (is_null($op)){
1320
-            $op = '';
1321
-          }
1322
-          $w = $type . $where . ' = ' . ($this->escape($op, $escape));
1323
-        }
1324
-        else{
1325
-          if (is_null($val)){
1326
-            $val = '';
1327
-          }
1328
-          $w = $type . $where . $op . ($this->escape($val, $escape));
1329
-        }
1330
-        return $w;
1331
-      }
1332
-
1333
-      /**
1334
-       * Set the $this->where property 
1335
-       * @param string $whereStr the WHERE clause string
1336
-       * @param  string  $andOr the separator type used 'AND', 'OR', etc.
1337
-       */
1338
-      protected function setWhereStr($whereStr, $andOr = 'AND'){
1339
-        if (empty($this->where)){
1340
-          $this->where = $whereStr;
1341
-        }
1342
-        else{
1343
-          if (substr($this->where, -1) == '('){
1344
-            $this->where = $this->where . ' ' . $whereStr;
1345
-          }
1346
-          else{
1347
-            $this->where = $this->where . ' '.$andOr.' ' . $whereStr;
1348
-          }
1349
-        }
1350
-      }
1351
-
1352
-        /**
1353
-     * Transform the prepared query like (?, ?, ?) into string format
1354
-     * @see Database::query
1355
-     *
1356
-     * @return string
1357
-     */
1358
-    protected function transformPreparedQuery($query, $data){
1359
-      if (is_array($data)){
1360
-        $x = explode('?', $query);
1361
-        $q = '';
1362
-        foreach($x as $k => $v){
1363
-          if (! empty($v)){
1364
-            $q .= $v . (isset($data[$k]) ? $this->escape($data[$k]) : '');
1365
-          }
1366
-        }
1367
-        return $q;
1368
-      }
1369
-      return $query;
1370
-    }
1371
-
1372
-    /**
1373
-     * Return the cache key for the query
1374
-     * @see Database::query
1375
-     * 
1376
-     *  @return string
1377
-     */
1378
-    protected function getCacheBenchmarkKeyForQuery($query, $all, $array){
1379
-      if (is_array($all)){
1380
-        $all = 'array';
1381
-      }
1382
-      return md5($query . $all . $array);
1383
-    }
1384
-
1385
-    /**
1386
-     * Get the cache content for this query
1387
-     * @see Database::query
1388
-     *      
1389
-     * @return mixed
1390
-     */
1391
-    protected function getCacheContentForQuery($query, $all, $array){
1392
-        $cacheKey = $this->getCacheBenchmarkKeyForQuery($query, $all, $array);
1393
-        if (is_object($this->cacheInstance)){
1394
-          return $this->cacheInstance->get($cacheKey);
1395
-        }
1396
-        $instance = & get_instance()->cache;
1397
-        $this->setCacheInstance($instance);
1398
-        return $instance->get($cacheKey);
1399
-    }
1400
-
1401
-    /**
1402
-     * Save the result of query into cache
1403
-     * @param string $query  the SQL query
1404
-     * @param string $key    the cache key
1405
-     * @param mixed $result the query result to save
1406
-     * @param boolean $status whether can save the query result into cache
1407
-     * @param int $expire the cache TTL
1408
-     */
1409
-     protected function setCacheContentForQuery($query, $key, $result, $status, $expire){
1410
-        if ($status){
1411
-            $this->logger->info('Save the result for query [' .$query. '] into cache for future use');
1412
-            $this->getCacheInstance()->set($key, $result, $expire);
1413
-        }
1414
-     }
1415
-
1416
-    /**
1417
-     * Set the result for SELECT query using PDOStatment
1418
-     * @see Database::query
1419
-     */
1420
-    protected function setQueryResultForSelect($pdoStatment, $all, $array){
1421
-      //if need return all result like list of record
1422
-      if (is_bool($all) && $all){
1423
-          $this->result = ($array === false) ? $pdoStatment->fetchAll(PDO::FETCH_OBJ) : $pdoStatment->fetchAll(PDO::FETCH_ASSOC);
1424
-      }
1425
-      else{
1426
-          $this->result = ($array === false) ? $pdoStatment->fetch(PDO::FETCH_OBJ) : $pdoStatment->fetch(PDO::FETCH_ASSOC);
1427
-      }
1428
-      //Sqlite and pgsql always return 0 when using rowCount()
1429
-      if (in_array($this->config['driver'], array('sqlite', 'pgsql'))){
1430
-        $this->numRows = count($this->result);  
1431
-      }
1432
-      else{
1433
-        $this->numRows = $pdoStatment->rowCount(); 
1434
-      }
1435
-    }
1436
-
1437
-    /**
1438
-     * Set the result for other command than SELECT query using PDOStatment
1439
-     * @see Database::query
1440
-     */
1441
-    protected function setQueryResultForNonSelect($pdoStatment){
1442
-      //Sqlite and pgsql always return 0 when using rowCount()
1443
-      if (in_array($this->config['driver'], array('sqlite', 'pgsql'))){
1444
-        $this->result = 1; //to test the result for the query like UPDATE, INSERT, DELETE
1445
-        $this->numRows = 1;  
1446
-      }
1447
-      else{
1448
-          $this->result = $pdoStatment->rowCount() >= 0; //to test the result for the query like UPDATE, INSERT, DELETE
1449
-          $this->numRows = $pdoStatment->rowCount(); 
1450
-      }
1451
-    }
1452
-
1453
-    /**
1454
-     * Set error for database query execution
1455
-     */
1456
-    protected function setQueryError(){
1457
-      $error = $this->pdo->errorInfo();
1458
-      $this->error = isset($error[2]) ? $error[2] : '';
1459
-      $this->logger->error('The database query execution got error: ' . stringfy_vars($error));
1460
-      $this->error();
1461
-    }
1462
-
1463
-    /**
1464
-     * Run the database SQL query and return the PDOStatment object
1465
-     * @see Database::query
1466
-     * 
1467
-     * @return object|void
1468
-     */
1469
-    protected function runSqlQuery($query, $all, $array){
1470
-       //for database query execution time
1471
-        $benchmarkMarkerKey = $this->getCacheBenchmarkKeyForQuery($query, $all, $array);
1472
-        $benchmarkInstance = $this->getBenchmark();
1473
-        if (! is_object($benchmarkInstance)){
1474
-          $obj = & get_instance();
1475
-          $benchmarkInstance = $obj->benchmark; 
1476
-          $this->setBenchmark($benchmarkInstance);
1477
-        }
1478
-        if (! $this->pdo){
1479
-            $this->connect();
1480
-        }
1273
+    * Get the SQL WHERE clause using array column => value
1274
+    * @see Database::where
1275
+    *
1276
+    * @return string
1277
+    */
1278
+	protected function getWhereStrIfIsArray(array $where, $type = '', $andOr = 'AND', $escape = true){
1279
+		$_where = array();
1280
+		foreach ($where as $column => $data){
1281
+		  if (is_null($data)){
1282
+			$data = '';
1283
+		  }
1284
+		  $_where[] = $type . $column . ' = ' . ($this->escape($data, $escape));
1285
+		}
1286
+		$where = implode(' '.$andOr.' ', $_where);
1287
+		return $where;
1288
+	}
1289
+
1290
+	 /**
1291
+	  * Get the SQL WHERE clause when operator argument is an array
1292
+	  * @see Database::where
1293
+	  *
1294
+	  * @return string
1295
+	  */
1296
+	protected function getWhereStrIfOperatorIsArray($where, array $op, $type = '', $escape = true){
1297
+	   $x = explode('?', $where);
1298
+	   $w = '';
1299
+		foreach($x as $k => $v){
1300
+		  if (! empty($v)){
1301
+			  if (isset($op[$k]) && is_null($op[$k])){
1302
+				$op[$k] = '';
1303
+			  }
1304
+			  $w .= $type . $v . (isset($op[$k]) ? ($this->escape($op[$k], $escape)) : '');
1305
+		  }
1306
+		}
1307
+		return $w;
1308
+	}
1309
+
1310
+	/**
1311
+	 * Get the default SQL WHERE clause using operator = or the operator argument
1312
+	 * @see Database::where
1313
+	 *
1314
+	 * @return string
1315
+	 */
1316
+	protected function getWhereStrForOperator($where, $op = null, $val = null, $type = '', $escape = true){
1317
+	   $w = '';
1318
+	   if (! in_array((string)$op, $this->operatorList)){
1319
+		  if (is_null($op)){
1320
+			$op = '';
1321
+		  }
1322
+		  $w = $type . $where . ' = ' . ($this->escape($op, $escape));
1323
+		}
1324
+		else{
1325
+		  if (is_null($val)){
1326
+			$val = '';
1327
+		  }
1328
+		  $w = $type . $where . $op . ($this->escape($val, $escape));
1329
+		}
1330
+		return $w;
1331
+	  }
1332
+
1333
+	  /**
1334
+	   * Set the $this->where property 
1335
+	   * @param string $whereStr the WHERE clause string
1336
+	   * @param  string  $andOr the separator type used 'AND', 'OR', etc.
1337
+	   */
1338
+	  protected function setWhereStr($whereStr, $andOr = 'AND'){
1339
+		if (empty($this->where)){
1340
+		  $this->where = $whereStr;
1341
+		}
1342
+		else{
1343
+		  if (substr($this->where, -1) == '('){
1344
+			$this->where = $this->where . ' ' . $whereStr;
1345
+		  }
1346
+		  else{
1347
+			$this->where = $this->where . ' '.$andOr.' ' . $whereStr;
1348
+		  }
1349
+		}
1350
+	  }
1351
+
1352
+		/**
1353
+		 * Transform the prepared query like (?, ?, ?) into string format
1354
+		 * @see Database::query
1355
+		 *
1356
+		 * @return string
1357
+		 */
1358
+	protected function transformPreparedQuery($query, $data){
1359
+	  if (is_array($data)){
1360
+		$x = explode('?', $query);
1361
+		$q = '';
1362
+		foreach($x as $k => $v){
1363
+		  if (! empty($v)){
1364
+			$q .= $v . (isset($data[$k]) ? $this->escape($data[$k]) : '');
1365
+		  }
1366
+		}
1367
+		return $q;
1368
+	  }
1369
+	  return $query;
1370
+	}
1371
+
1372
+	/**
1373
+	 * Return the cache key for the query
1374
+	 * @see Database::query
1375
+	 * 
1376
+	 *  @return string
1377
+	 */
1378
+	protected function getCacheBenchmarkKeyForQuery($query, $all, $array){
1379
+	  if (is_array($all)){
1380
+		$all = 'array';
1381
+	  }
1382
+	  return md5($query . $all . $array);
1383
+	}
1384
+
1385
+	/**
1386
+	 * Get the cache content for this query
1387
+	 * @see Database::query
1388
+	 *      
1389
+	 * @return mixed
1390
+	 */
1391
+	protected function getCacheContentForQuery($query, $all, $array){
1392
+		$cacheKey = $this->getCacheBenchmarkKeyForQuery($query, $all, $array);
1393
+		if (is_object($this->cacheInstance)){
1394
+		  return $this->cacheInstance->get($cacheKey);
1395
+		}
1396
+		$instance = & get_instance()->cache;
1397
+		$this->setCacheInstance($instance);
1398
+		return $instance->get($cacheKey);
1399
+	}
1400
+
1401
+	/**
1402
+	 * Save the result of query into cache
1403
+	 * @param string $query  the SQL query
1404
+	 * @param string $key    the cache key
1405
+	 * @param mixed $result the query result to save
1406
+	 * @param boolean $status whether can save the query result into cache
1407
+	 * @param int $expire the cache TTL
1408
+	 */
1409
+	 protected function setCacheContentForQuery($query, $key, $result, $status, $expire){
1410
+		if ($status){
1411
+			$this->logger->info('Save the result for query [' .$query. '] into cache for future use');
1412
+			$this->getCacheInstance()->set($key, $result, $expire);
1413
+		}
1414
+	 }
1415
+
1416
+	/**
1417
+	 * Set the result for SELECT query using PDOStatment
1418
+	 * @see Database::query
1419
+	 */
1420
+	protected function setQueryResultForSelect($pdoStatment, $all, $array){
1421
+	  //if need return all result like list of record
1422
+	  if (is_bool($all) && $all){
1423
+		  $this->result = ($array === false) ? $pdoStatment->fetchAll(PDO::FETCH_OBJ) : $pdoStatment->fetchAll(PDO::FETCH_ASSOC);
1424
+	  }
1425
+	  else{
1426
+		  $this->result = ($array === false) ? $pdoStatment->fetch(PDO::FETCH_OBJ) : $pdoStatment->fetch(PDO::FETCH_ASSOC);
1427
+	  }
1428
+	  //Sqlite and pgsql always return 0 when using rowCount()
1429
+	  if (in_array($this->config['driver'], array('sqlite', 'pgsql'))){
1430
+		$this->numRows = count($this->result);  
1431
+	  }
1432
+	  else{
1433
+		$this->numRows = $pdoStatment->rowCount(); 
1434
+	  }
1435
+	}
1436
+
1437
+	/**
1438
+	 * Set the result for other command than SELECT query using PDOStatment
1439
+	 * @see Database::query
1440
+	 */
1441
+	protected function setQueryResultForNonSelect($pdoStatment){
1442
+	  //Sqlite and pgsql always return 0 when using rowCount()
1443
+	  if (in_array($this->config['driver'], array('sqlite', 'pgsql'))){
1444
+		$this->result = 1; //to test the result for the query like UPDATE, INSERT, DELETE
1445
+		$this->numRows = 1;  
1446
+	  }
1447
+	  else{
1448
+		  $this->result = $pdoStatment->rowCount() >= 0; //to test the result for the query like UPDATE, INSERT, DELETE
1449
+		  $this->numRows = $pdoStatment->rowCount(); 
1450
+	  }
1451
+	}
1452
+
1453
+	/**
1454
+	 * Set error for database query execution
1455
+	 */
1456
+	protected function setQueryError(){
1457
+	  $error = $this->pdo->errorInfo();
1458
+	  $this->error = isset($error[2]) ? $error[2] : '';
1459
+	  $this->logger->error('The database query execution got error: ' . stringfy_vars($error));
1460
+	  $this->error();
1461
+	}
1462
+
1463
+	/**
1464
+	 * Run the database SQL query and return the PDOStatment object
1465
+	 * @see Database::query
1466
+	 * 
1467
+	 * @return object|void
1468
+	 */
1469
+	protected function runSqlQuery($query, $all, $array){
1470
+	   //for database query execution time
1471
+		$benchmarkMarkerKey = $this->getCacheBenchmarkKeyForQuery($query, $all, $array);
1472
+		$benchmarkInstance = $this->getBenchmark();
1473
+		if (! is_object($benchmarkInstance)){
1474
+		  $obj = & get_instance();
1475
+		  $benchmarkInstance = $obj->benchmark; 
1476
+		  $this->setBenchmark($benchmarkInstance);
1477
+		}
1478
+		if (! $this->pdo){
1479
+			$this->connect();
1480
+		}
1481 1481
         
1482
-        $benchmarkInstance->mark('DATABASE_QUERY_START(' . $benchmarkMarkerKey . ')');
1483
-        //Now execute the query
1484
-        $sqlQuery = $this->pdo->query($query);
1482
+		$benchmarkInstance->mark('DATABASE_QUERY_START(' . $benchmarkMarkerKey . ')');
1483
+		//Now execute the query
1484
+		$sqlQuery = $this->pdo->query($query);
1485 1485
         
1486
-        //get response time for this query
1487
-        $responseTime = $benchmarkInstance->elapsedTime('DATABASE_QUERY_START(' . $benchmarkMarkerKey . ')', 'DATABASE_QUERY_END(' . $benchmarkMarkerKey . ')');
1488
-        //TODO use the configuration value for the high response time currently is 1 second
1489
-        if ($responseTime >= 1 ){
1490
-            $this->logger->warning('High response time while processing database query [' .$query. ']. The response time is [' .$responseTime. '] sec.');
1491
-        }
1492
-        if ($sqlQuery){
1493
-          return $sqlQuery;
1494
-        }
1495
-        $this->setQueryError();
1496
-    }
1497
-
1498
-    /**
1499
-     * Reset the database class attributs to the initail values before each query.
1500
-     */
1501
-    private function reset(){
1502
-      $this->select   = '*';
1503
-      $this->from     = null;
1504
-      $this->where    = null;
1505
-      $this->limit    = null;
1506
-      $this->orderBy  = null;
1507
-      $this->groupBy  = null;
1508
-      $this->having   = null;
1509
-      $this->join     = null;
1510
-      $this->numRows  = 0;
1511
-      $this->insertId = null;
1512
-      $this->query    = null;
1513
-      $this->error    = null;
1514
-      $this->result   = array();
1515
-      $this->data     = array();
1516
-    }
1517
-
1518
-    /**
1519
-     * The class destructor
1520
-     */
1521
-    public function __destruct(){
1522
-      $this->pdo = null;
1486
+		//get response time for this query
1487
+		$responseTime = $benchmarkInstance->elapsedTime('DATABASE_QUERY_START(' . $benchmarkMarkerKey . ')', 'DATABASE_QUERY_END(' . $benchmarkMarkerKey . ')');
1488
+		//TODO use the configuration value for the high response time currently is 1 second
1489
+		if ($responseTime >= 1 ){
1490
+			$this->logger->warning('High response time while processing database query [' .$query. ']. The response time is [' .$responseTime. '] sec.');
1491
+		}
1492
+		if ($sqlQuery){
1493
+		  return $sqlQuery;
1494
+		}
1495
+		$this->setQueryError();
1496
+	}
1497
+
1498
+	/**
1499
+	 * Reset the database class attributs to the initail values before each query.
1500
+	 */
1501
+	private function reset(){
1502
+	  $this->select   = '*';
1503
+	  $this->from     = null;
1504
+	  $this->where    = null;
1505
+	  $this->limit    = null;
1506
+	  $this->orderBy  = null;
1507
+	  $this->groupBy  = null;
1508
+	  $this->having   = null;
1509
+	  $this->join     = null;
1510
+	  $this->numRows  = 0;
1511
+	  $this->insertId = null;
1512
+	  $this->query    = null;
1513
+	  $this->error    = null;
1514
+	  $this->result   = array();
1515
+	  $this->data     = array();
1516
+	}
1517
+
1518
+	/**
1519
+	 * The class destructor
1520
+	 */
1521
+	public function __destruct(){
1522
+	  $this->pdo = null;
1523 1523
   }
1524 1524
 
1525 1525
 }
Please login to merge, or discard this patch.
Spacing   +238 added lines, -238 removed lines patch added patch discarded remove patch
@@ -23,165 +23,165 @@  discard block
 block discarded – undo
23 23
    * along with this program; if not, write to the Free Software
24 24
    * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
25 25
   */
26
-  class Database{
26
+  class Database {
27 27
 	
28 28
 	/**
29 29
 	 * The PDO instance
30 30
 	 * @var object
31 31
 	*/
32
-    private $pdo                 = null;
32
+    private $pdo = null;
33 33
     
34 34
 	/**
35 35
 	 * The database name used for the application
36 36
 	 * @var string
37 37
 	*/
38
-	private $databaseName        = null;
38
+	private $databaseName = null;
39 39
     
40 40
 	/**
41 41
 	 * The SQL SELECT statment
42 42
 	 * @var string
43 43
 	*/
44
-	private $select              = '*';
44
+	private $select = '*';
45 45
 	
46 46
 	/**
47 47
 	 * The SQL FROM statment
48 48
 	 * @var string
49 49
 	*/
50
-    private $from                = null;
50
+    private $from = null;
51 51
 	
52 52
 	/**
53 53
 	 * The SQL WHERE statment
54 54
 	 * @var string
55 55
 	*/
56
-    private $where               = null;
56
+    private $where = null;
57 57
 	
58 58
 	/**
59 59
 	 * The SQL LIMIT statment
60 60
 	 * @var string
61 61
 	*/
62
-    private $limit               = null;
62
+    private $limit = null;
63 63
 	
64 64
 	/**
65 65
 	 * The SQL JOIN statment
66 66
 	 * @var string
67 67
 	*/
68
-    private $join                = null;
68
+    private $join = null;
69 69
 	
70 70
 	/**
71 71
 	 * The SQL ORDER BY statment
72 72
 	 * @var string
73 73
 	*/
74
-    private $orderBy             = null;
74
+    private $orderBy = null;
75 75
 	
76 76
 	/**
77 77
 	 * The SQL GROUP BY statment
78 78
 	 * @var string
79 79
 	*/
80
-    private $groupBy             = null;
80
+    private $groupBy = null;
81 81
 	
82 82
 	/**
83 83
 	 * The SQL HAVING statment
84 84
 	 * @var string
85 85
 	*/
86
-    private $having              = null;
86
+    private $having = null;
87 87
 	
88 88
 	/**
89 89
 	 * The number of rows returned by the last query
90 90
 	 * @var int
91 91
 	*/
92
-    private $numRows             = 0;
92
+    private $numRows = 0;
93 93
 	
94 94
 	/**
95 95
 	 * The last insert id for the primary key column that have auto increment or sequence
96 96
 	 * @var mixed
97 97
 	*/
98
-    private $insertId            = null;
98
+    private $insertId = null;
99 99
 	
100 100
 	/**
101 101
 	 * The full SQL query statment after build for each command
102 102
 	 * @var string
103 103
 	*/
104
-    private $query               = null;
104
+    private $query = null;
105 105
 	
106 106
 	/**
107 107
 	 * The error returned for the last query
108 108
 	 * @var string
109 109
 	*/
110
-    private $error               = null;
110
+    private $error = null;
111 111
 	
112 112
 	/**
113 113
 	 * The result returned for the last query
114 114
 	 * @var mixed
115 115
 	*/
116
-    private $result              = array();
116
+    private $result = array();
117 117
 	
118 118
 	/**
119 119
 	 * The prefix used in each database table
120 120
 	 * @var string
121 121
 	*/
122
-    private $prefix              = null;
122
+    private $prefix = null;
123 123
 	
124 124
 	/**
125 125
 	 * The list of SQL valid operators
126 126
 	 * @var array
127 127
 	*/
128
-    private $operatorList        = array('=','!=','<','>','<=','>=','<>');
128
+    private $operatorList = array('=', '!=', '<', '>', '<=', '>=', '<>');
129 129
     
130 130
 	/**
131 131
 	 * The cache default time to live in second. 0 means no need to use the cache feature
132 132
 	 * @var int
133 133
 	*/
134
-	private $cacheTtl              = 0;
134
+	private $cacheTtl = 0;
135 135
 	
136 136
 	/**
137 137
 	 * The cache current time to live. 0 means no need to use the cache feature
138 138
 	 * @var int
139 139
 	*/
140
-    private $temporaryCacheTtl   = 0;
140
+    private $temporaryCacheTtl = 0;
141 141
 	
142 142
 	/**
143 143
 	 * The number of executed query for the current request
144 144
 	 * @var int
145 145
 	*/
146
-    private $queryCount          = 0;
146
+    private $queryCount = 0;
147 147
 	
148 148
 	/**
149 149
 	 * The default data to be used in the statments query INSERT, UPDATE
150 150
 	 * @var array
151 151
 	*/
152
-    private $data                = array();
152
+    private $data = array();
153 153
 	
154 154
 	/**
155 155
 	 * The database configuration
156 156
 	 * @var array
157 157
 	*/
158
-    private $config              = array();
158
+    private $config = array();
159 159
 	
160 160
 	/**
161 161
 	 * The logger instance
162 162
 	 * @var Log
163 163
 	 */
164
-    private $logger              = null;
164
+    private $logger = null;
165 165
 
166 166
 
167 167
     /**
168 168
     * The cache instance
169 169
     * @var CacheInterface
170 170
     */
171
-    private $cacheInstance       = null;
171
+    private $cacheInstance = null;
172 172
 
173 173
      /**
174 174
     * The benchmark instance
175 175
     * @var Benchmark
176 176
     */
177
-    private $benchmarkInstance   = null;
177
+    private $benchmarkInstance = null;
178 178
 
179 179
 
180 180
     /**
181 181
      * Construct new database
182 182
      * @param array $overwriteConfig the config to overwrite with the config set in database.php
183 183
      */
184
-    public function __construct($overwriteConfig = array()){
184
+    public function __construct($overwriteConfig = array()) {
185 185
         //Set Log instance to use
186 186
         $this->setLoggerFromParamOrCreateNewInstance(null);
187 187
 
@@ -197,23 +197,23 @@  discard block
 block discarded – undo
197 197
      * This is used to connect to database
198 198
      * @return bool 
199 199
      */
200
-    public function connect(){
200
+    public function connect() {
201 201
       $config = $this->getDatabaseConfiguration();
202
-      if (! empty($config)){
203
-        try{
202
+      if (!empty($config)) {
203
+        try {
204 204
             $this->pdo = new PDO($this->getDsnFromDriver(), $config['username'], $config['password']);
205 205
             $this->pdo->exec("SET NAMES '" . $config['charset'] . "' COLLATE '" . $config['collation'] . "'");
206 206
             $this->pdo->exec("SET CHARACTER SET '" . $config['charset'] . "'");
207 207
             $this->pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_OBJ);
208 208
             return true;
209 209
           }
210
-          catch (PDOException $e){
210
+          catch (PDOException $e) {
211 211
             $this->logger->fatal($e->getMessage());
212 212
             show_error('Cannot connect to Database.');
213 213
             return false;
214 214
           }
215 215
       }
216
-      else{
216
+      else {
217 217
         show_error('Database configuration is not set.');
218 218
         return false;
219 219
       }
@@ -224,15 +224,15 @@  discard block
 block discarded – undo
224 224
      * @param  string|array $table the table name or array of table list
225 225
      * @return object        the current Database instance
226 226
      */
227
-    public function from($table){
228
-      if (is_array($table)){
227
+    public function from($table) {
228
+      if (is_array($table)) {
229 229
         $froms = '';
230
-        foreach($table as $key){
230
+        foreach ($table as $key) {
231 231
           $froms .= $this->prefix . $key . ', ';
232 232
         }
233 233
         $this->from = rtrim($froms, ', ');
234 234
       }
235
-      else{
235
+      else {
236 236
         $this->from = $this->prefix . $table;
237 237
       }
238 238
       return $this;
@@ -243,7 +243,7 @@  discard block
 block discarded – undo
243 243
      * @param  string|array $fields the field name or array of field list
244 244
      * @return object        the current Database instance
245 245
      */
246
-    public function select($fields){
246
+    public function select($fields) {
247 247
       $select = (is_array($fields) ? implode(', ', $fields) : $fields);
248 248
       $this->select = ($this->select == '*' ? $select : $this->select . ', ' . $select);
249 249
       return $this;
@@ -254,7 +254,7 @@  discard block
 block discarded – undo
254 254
      * @param  string $field the field name to distinct
255 255
      * @return object        the current Database instance
256 256
      */
257
-    public function distinct($field){
257
+    public function distinct($field) {
258 258
       $distinct = ' DISTINCT ' . $field;
259 259
       $this->select = ($this->select == '*' ? $distinct : $this->select . ', ' . $distinct);
260 260
 
@@ -267,7 +267,7 @@  discard block
 block discarded – undo
267 267
      * @param  string $name  if is not null represent the alias used for this field in the result
268 268
      * @return object        the current Database instance
269 269
      */
270
-    public function max($field, $name = null){
270
+    public function max($field, $name = null) {
271 271
       $func = 'MAX(' . $field . ')' . (!is_null($name) ? ' AS ' . $name : '');
272 272
       $this->select = ($this->select == '*' ? $func : $this->select . ', ' . $func);
273 273
       return $this;
@@ -279,7 +279,7 @@  discard block
 block discarded – undo
279 279
      * @param  string $name  if is not null represent the alias used for this field in the result
280 280
      * @return object        the current Database instance
281 281
      */
282
-    public function min($field, $name = null){
282
+    public function min($field, $name = null) {
283 283
       $func = 'MIN(' . $field . ')' . (!is_null($name) ? ' AS ' . $name : '');
284 284
       $this->select = ($this->select == '*' ? $func : $this->select . ', ' . $func);
285 285
       return $this;
@@ -291,7 +291,7 @@  discard block
 block discarded – undo
291 291
      * @param  string $name  if is not null represent the alias used for this field in the result
292 292
      * @return object        the current Database instance
293 293
      */
294
-    public function sum($field, $name = null){
294
+    public function sum($field, $name = null) {
295 295
       $func = 'SUM(' . $field . ')' . (!is_null($name) ? ' AS ' . $name : '');
296 296
       $this->select = ($this->select == '*' ? $func : $this->select . ', ' . $func);
297 297
       return $this;
@@ -303,7 +303,7 @@  discard block
 block discarded – undo
303 303
      * @param  string $name  if is not null represent the alias used for this field in the result
304 304
      * @return object        the current Database instance
305 305
      */
306
-    public function count($field = '*', $name = null){
306
+    public function count($field = '*', $name = null) {
307 307
       $func = 'COUNT(' . $field . ')' . (!is_null($name) ? ' AS ' . $name : '');
308 308
       $this->select = ($this->select == '*' ? $func : $this->select . ', ' . $func);
309 309
       return $this;
@@ -315,7 +315,7 @@  discard block
 block discarded – undo
315 315
      * @param  string $name  if is not null represent the alias used for this field in the result
316 316
      * @return object        the current Database instance
317 317
      */
318
-    public function avg($field, $name = null){
318
+    public function avg($field, $name = null) {
319 319
       $func = 'AVG(' . $field . ')' . (!is_null($name) ? ' AS ' . $name : '');
320 320
       $this->select = ($this->select == '*' ? $func : $this->select . ', ' . $func);
321 321
       return $this;
@@ -330,16 +330,16 @@  discard block
 block discarded – undo
330 330
      * @param  string $type   the type of join (INNER, LEFT, RIGHT)
331 331
      * @return object        the current Database instance
332 332
      */
333
-    public function join($table, $field1 = null, $op = null, $field2 = null, $type = ''){
333
+    public function join($table, $field1 = null, $op = null, $field2 = null, $type = '') {
334 334
       $on = $field1;
335 335
       $table = $this->prefix . $table;
336
-      if (! is_null($op)){
337
-        $on = (! in_array($op, $this->operatorList) ? $this->prefix . $field1 . ' = ' . $this->prefix . $op : $this->prefix . $field1 . ' ' . $op . ' ' . $this->prefix . $field2);
336
+      if (!is_null($op)) {
337
+        $on = (!in_array($op, $this->operatorList) ? $this->prefix . $field1 . ' = ' . $this->prefix . $op : $this->prefix . $field1 . ' ' . $op . ' ' . $this->prefix . $field2);
338 338
       }
339
-      if (empty($this->join)){
339
+      if (empty($this->join)) {
340 340
         $this->join = ' ' . $type . 'JOIN' . ' ' . $table . ' ON ' . $on;
341 341
       }
342
-      else{
342
+      else {
343 343
         $this->join = $this->join . ' ' . $type . 'JOIN' . ' ' . $table . ' ON ' . $on;
344 344
       }
345 345
       return $this;
@@ -350,7 +350,7 @@  discard block
 block discarded – undo
350 350
      * @see  Database::join()
351 351
      * @return object        the current Database instance
352 352
      */
353
-    public function innerJoin($table, $field1, $op = null, $field2 = ''){
353
+    public function innerJoin($table, $field1, $op = null, $field2 = '') {
354 354
       return $this->join($table, $field1, $op, $field2, 'INNER ');
355 355
     }
356 356
 
@@ -359,7 +359,7 @@  discard block
 block discarded – undo
359 359
      * @see  Database::join()
360 360
      * @return object        the current Database instance
361 361
      */
362
-    public function leftJoin($table, $field1, $op = null, $field2 = ''){
362
+    public function leftJoin($table, $field1, $op = null, $field2 = '') {
363 363
       return $this->join($table, $field1, $op, $field2, 'LEFT ');
364 364
 	}
365 365
 
@@ -368,7 +368,7 @@  discard block
 block discarded – undo
368 368
      * @see  Database::join()
369 369
      * @return object        the current Database instance
370 370
      */
371
-    public function rightJoin($table, $field1, $op = null, $field2 = ''){
371
+    public function rightJoin($table, $field1, $op = null, $field2 = '') {
372 372
       return $this->join($table, $field1, $op, $field2, 'RIGHT ');
373 373
     }
374 374
 
@@ -377,7 +377,7 @@  discard block
 block discarded – undo
377 377
      * @see  Database::join()
378 378
      * @return object        the current Database instance
379 379
      */
380
-    public function fullOuterJoin($table, $field1, $op = null, $field2 = ''){
380
+    public function fullOuterJoin($table, $field1, $op = null, $field2 = '') {
381 381
     	return $this->join($table, $field1, $op, $field2, 'FULL OUTER ');
382 382
     }
383 383
 
@@ -386,7 +386,7 @@  discard block
 block discarded – undo
386 386
      * @see  Database::join()
387 387
      * @return object        the current Database instance
388 388
      */
389
-    public function leftOuterJoin($table, $field1, $op = null, $field2 = ''){
389
+    public function leftOuterJoin($table, $field1, $op = null, $field2 = '') {
390 390
       return $this->join($table, $field1, $op, $field2, 'LEFT OUTER ');
391 391
     }
392 392
 
@@ -395,7 +395,7 @@  discard block
 block discarded – undo
395 395
      * @see  Database::join()
396 396
      * @return object        the current Database instance
397 397
      */
398
-    public function rightOuterJoin($table, $field1, $op = null, $field2 = ''){
398
+    public function rightOuterJoin($table, $field1, $op = null, $field2 = '') {
399 399
       return $this->join($table, $field1, $op, $field2, 'RIGHT OUTER ');
400 400
     }
401 401
 
@@ -405,14 +405,14 @@  discard block
 block discarded – undo
405 405
      * @param  string $andOr the separator type used 'AND', 'OR', etc.
406 406
      * @return object        the current Database instance
407 407
      */
408
-    public function whereIsNull($field, $andOr = 'AND'){
409
-      if (is_array($field)){
410
-        foreach($field as $f){
408
+    public function whereIsNull($field, $andOr = 'AND') {
409
+      if (is_array($field)) {
410
+        foreach ($field as $f) {
411 411
         	$this->whereIsNull($f, $andOr);
412 412
         }
413 413
       }
414
-      else{
415
-           $this->setWhereStr($field.' IS NULL ', $andOr);
414
+      else {
415
+           $this->setWhereStr($field . ' IS NULL ', $andOr);
416 416
       }
417 417
       return $this;
418 418
     }
@@ -423,14 +423,14 @@  discard block
 block discarded – undo
423 423
      * @param  string $andOr the separator type used 'AND', 'OR', etc.
424 424
      * @return object        the current Database instance
425 425
      */
426
-    public function whereIsNotNull($field, $andOr = 'AND'){
427
-      if (is_array($field)){
428
-        foreach($field as $f){
426
+    public function whereIsNotNull($field, $andOr = 'AND') {
427
+      if (is_array($field)) {
428
+        foreach ($field as $f) {
429 429
           $this->whereIsNotNull($f, $andOr);
430 430
         }
431 431
       }
432
-      else{
433
-          $this->setWhereStr($field.' IS NOT NULL ', $andOr);
432
+      else {
433
+          $this->setWhereStr($field . ' IS NOT NULL ', $andOr);
434 434
       }
435 435
       return $this;
436 436
     }
@@ -445,13 +445,13 @@  discard block
 block discarded – undo
445 445
      * @param  boolean $escape whether to escape or not the $val
446 446
      * @return object        the current Database instance
447 447
      */
448
-    public function where($where, $op = null, $val = null, $type = '', $andOr = 'AND', $escape = true){
448
+    public function where($where, $op = null, $val = null, $type = '', $andOr = 'AND', $escape = true) {
449 449
       $whereStr = '';
450
-      if (is_array($where)){
450
+      if (is_array($where)) {
451 451
         $whereStr = $this->getWhereStrIfIsArray($where, $type, $andOr, $escape);
452 452
       }
453
-      else{
454
-        if (is_array($op)){
453
+      else {
454
+        if (is_array($op)) {
455 455
           $whereStr = $this->getWhereStrIfOperatorIsArray($where, $op, $type, $escape);
456 456
         } else {
457 457
           $whereStr = $this->getWhereStrForOperator($where, $op, $val, $type, $escape = true);
@@ -466,7 +466,7 @@  discard block
 block discarded – undo
466 466
      * @see  Database::where()
467 467
      * @return object        the current Database instance
468 468
      */
469
-    public function orWhere($where, $op = null, $val = null, $escape = true){
469
+    public function orWhere($where, $op = null, $val = null, $escape = true) {
470 470
       return $this->where($where, $op, $val, '', 'OR', $escape);
471 471
     }
472 472
 
@@ -476,7 +476,7 @@  discard block
 block discarded – undo
476 476
      * @see  Database::where()
477 477
      * @return object        the current Database instance
478 478
      */
479
-    public function notWhere($where, $op = null, $val = null, $escape = true){
479
+    public function notWhere($where, $op = null, $val = null, $escape = true) {
480 480
       return $this->where($where, $op, $val, 'NOT ', 'AND', $escape);
481 481
     }
482 482
 
@@ -485,7 +485,7 @@  discard block
 block discarded – undo
485 485
      * @see  Database::where()
486 486
      * @return object        the current Database instance
487 487
      */
488
-    public function orNotWhere($where, $op = null, $val = null, $escape = true){
488
+    public function orNotWhere($where, $op = null, $val = null, $escape = true) {
489 489
     	return $this->where($where, $op, $val, 'NOT ', 'OR', $escape);
490 490
     }
491 491
 
@@ -495,15 +495,15 @@  discard block
 block discarded – undo
495 495
      * @param  string $andOr the multiple conditions separator (AND, OR, etc.)
496 496
      * @return object        the current Database instance
497 497
      */
498
-    public function groupStart($type = '', $andOr = ' AND'){
499
-      if (empty($this->where)){
498
+    public function groupStart($type = '', $andOr = ' AND') {
499
+      if (empty($this->where)) {
500 500
         $this->where = $type . ' (';
501 501
       }
502
-      else{
503
-          if (substr($this->where, -1) == '('){
502
+      else {
503
+          if (substr($this->where, -1) == '(') {
504 504
             $this->where .= $type . ' (';
505 505
           }
506
-          else{
506
+          else {
507 507
           	$this->where .= $andOr . ' ' . $type . ' (';
508 508
           }
509 509
       }
@@ -515,7 +515,7 @@  discard block
 block discarded – undo
515 515
      * @see  Database::groupStart()
516 516
      * @return object        the current Database instance
517 517
      */
518
-    public function notGroupStart(){
518
+    public function notGroupStart() {
519 519
       return $this->groupStart('NOT');
520 520
     }
521 521
 
@@ -524,7 +524,7 @@  discard block
 block discarded – undo
524 524
      * @see  Database::groupStart()
525 525
      * @return object        the current Database instance
526 526
      */
527
-    public function orGroupStart(){
527
+    public function orGroupStart() {
528 528
       return $this->groupStart('', ' OR');
529 529
     }
530 530
 
@@ -533,7 +533,7 @@  discard block
 block discarded – undo
533 533
      * @see  Database::groupStart()
534 534
      * @return object        the current Database instance
535 535
      */
536
-    public function orNotGroupStart(){
536
+    public function orNotGroupStart() {
537 537
       return $this->groupStart('NOT', ' OR');
538 538
     }
539 539
 
@@ -541,7 +541,7 @@  discard block
 block discarded – undo
541 541
      * Close the parenthesis for the grouped SQL
542 542
      * @return object        the current Database instance
543 543
      */
544
-    public function groupEnd(){
544
+    public function groupEnd() {
545 545
       $this->where .= ')';
546 546
       return $this;
547 547
     }
@@ -555,10 +555,10 @@  discard block
 block discarded – undo
555 555
      * @param  boolean $escape whether to escape or not the values
556 556
      * @return object        the current Database instance
557 557
      */
558
-    public function in($field, array $keys, $type = '', $andOr = 'AND', $escape = true){
558
+    public function in($field, array $keys, $type = '', $andOr = 'AND', $escape = true) {
559 559
       $_keys = array();
560
-      foreach ($keys as $k => $v){
561
-        if (is_null($v)){
560
+      foreach ($keys as $k => $v) {
561
+        if (is_null($v)) {
562 562
           $v = '';
563 563
         }
564 564
         $_keys[] = (is_numeric($v) ? $v : $this->escape($v, $escape));
@@ -574,7 +574,7 @@  discard block
 block discarded – undo
574 574
      * @see  Database::in()
575 575
      * @return object        the current Database instance
576 576
      */
577
-    public function notIn($field, array $keys, $escape = true){
577
+    public function notIn($field, array $keys, $escape = true) {
578 578
       return $this->in($field, $keys, 'NOT ', 'AND', $escape);
579 579
     }
580 580
 
@@ -583,7 +583,7 @@  discard block
 block discarded – undo
583 583
      * @see  Database::in()
584 584
      * @return object        the current Database instance
585 585
      */
586
-    public function orIn($field, array $keys, $escape = true){
586
+    public function orIn($field, array $keys, $escape = true) {
587 587
       return $this->in($field, $keys, '', 'OR', $escape);
588 588
     }
589 589
 
@@ -592,7 +592,7 @@  discard block
 block discarded – undo
592 592
      * @see  Database::in()
593 593
      * @return object        the current Database instance
594 594
      */
595
-    public function orNotIn($field, array $keys, $escape = true){
595
+    public function orNotIn($field, array $keys, $escape = true) {
596 596
       return $this->in($field, $keys, 'NOT ', 'OR', $escape);
597 597
     }
598 598
 
@@ -606,11 +606,11 @@  discard block
 block discarded – undo
606 606
      * @param  boolean $escape whether to escape or not the values
607 607
      * @return object        the current Database instance
608 608
      */
609
-    public function between($field, $value1, $value2, $type = '', $andOr = 'AND', $escape = true){
610
-      if (is_null($value1)){
609
+    public function between($field, $value1, $value2, $type = '', $andOr = 'AND', $escape = true) {
610
+      if (is_null($value1)) {
611 611
         $value1 = '';
612 612
       }
613
-      if (is_null($value2)){
613
+      if (is_null($value2)) {
614 614
         $value2 = '';
615 615
       }
616 616
       $whereStr = $field . ' ' . $type . ' BETWEEN ' . $this->escape($value1, $escape) . ' AND ' . $this->escape($value2, $escape);
@@ -623,7 +623,7 @@  discard block
 block discarded – undo
623 623
      * @see  Database::between()
624 624
      * @return object        the current Database instance
625 625
      */
626
-    public function notBetween($field, $value1, $value2, $escape = true){
626
+    public function notBetween($field, $value1, $value2, $escape = true) {
627 627
       return $this->between($field, $value1, $value2, 'NOT ', 'AND', $escape);
628 628
     }
629 629
 
@@ -632,7 +632,7 @@  discard block
 block discarded – undo
632 632
      * @see  Database::between()
633 633
      * @return object        the current Database instance
634 634
      */
635
-    public function orBetween($field, $value1, $value2, $escape = true){
635
+    public function orBetween($field, $value1, $value2, $escape = true) {
636 636
       return $this->between($field, $value1, $value2, '', 'OR', $escape);
637 637
     }
638 638
 
@@ -641,7 +641,7 @@  discard block
 block discarded – undo
641 641
      * @see  Database::between()
642 642
      * @return object        the current Database instance
643 643
      */
644
-    public function orNotBetween($field, $value1, $value2, $escape = true){
644
+    public function orNotBetween($field, $value1, $value2, $escape = true) {
645 645
       return $this->between($field, $value1, $value2, 'NOT ', 'OR', $escape);
646 646
     }
647 647
 
@@ -654,8 +654,8 @@  discard block
 block discarded – undo
654 654
      * @param  boolean $escape whether to escape or not the values
655 655
      * @return object        the current Database instance
656 656
      */
657
-    public function like($field, $data, $type = '', $andOr = 'AND', $escape = true){
658
-      if (empty($data)){
657
+    public function like($field, $data, $type = '', $andOr = 'AND', $escape = true) {
658
+      if (empty($data)) {
659 659
         $data = '';
660 660
       }
661 661
       $this->setWhereStr($field . ' ' . $type . ' LIKE ' . ($this->escape($data, $escape)), $andOr);
@@ -667,7 +667,7 @@  discard block
 block discarded – undo
667 667
      * @see  Database::like()
668 668
      * @return object        the current Database instance
669 669
      */
670
-    public function orLike($field, $data, $escape = true){
670
+    public function orLike($field, $data, $escape = true) {
671 671
       return $this->like($field, $data, '', 'OR', $escape);
672 672
     }
673 673
 
@@ -676,7 +676,7 @@  discard block
 block discarded – undo
676 676
      * @see  Database::like()
677 677
      * @return object        the current Database instance
678 678
      */
679
-    public function notLike($field, $data, $escape = true){
679
+    public function notLike($field, $data, $escape = true) {
680 680
       return $this->like($field, $data, 'NOT ', 'AND', $escape);
681 681
     }
682 682
 
@@ -685,7 +685,7 @@  discard block
 block discarded – undo
685 685
      * @see  Database::like()
686 686
      * @return object        the current Database instance
687 687
      */
688
-    public function orNotLike($field, $data, $escape = true){
688
+    public function orNotLike($field, $data, $escape = true) {
689 689
       return $this->like($field, $data, 'NOT ', 'OR', $escape);
690 690
     }
691 691
 
@@ -696,14 +696,14 @@  discard block
 block discarded – undo
696 696
      * @param  int $limitEnd the limit count
697 697
      * @return object        the current Database instance
698 698
      */
699
-    public function limit($limit, $limitEnd = null){
700
-      if (empty($limit)){
699
+    public function limit($limit, $limitEnd = null) {
700
+      if (empty($limit)) {
701 701
         return;
702 702
       }
703
-      if (! is_null($limitEnd)){
703
+      if (!is_null($limitEnd)) {
704 704
         $this->limit = $limit . ', ' . $limitEnd;
705 705
       }
706
-      else{
706
+      else {
707 707
         $this->limit = $limit;
708 708
       }
709 709
       return $this;
@@ -715,11 +715,11 @@  discard block
 block discarded – undo
715 715
      * @param  string $orderDir the order direction (ASC or DESC)
716 716
      * @return object        the current Database instance
717 717
      */
718
-    public function orderBy($orderBy, $orderDir = ' ASC'){
719
-        if (stristr($orderBy, ' ') || $orderBy == 'rand()'){
718
+    public function orderBy($orderBy, $orderDir = ' ASC') {
719
+        if (stristr($orderBy, ' ') || $orderBy == 'rand()') {
720 720
           $this->orderBy = empty($this->orderBy) ? $orderBy : $this->orderBy . ', ' . $orderBy;
721 721
         }
722
-        else{
722
+        else {
723 723
           $this->orderBy = empty($this->orderBy) ? ($orderBy . ' ' 
724 724
                             . strtoupper($orderDir)) : $this->orderBy 
725 725
                             . ', ' . $orderBy . ' ' . strtoupper($orderDir);
@@ -732,11 +732,11 @@  discard block
 block discarded – undo
732 732
      * @param  string|array $field the field name used or array of field list
733 733
      * @return object        the current Database instance
734 734
      */
735
-    public function groupBy($field){
736
-      if (is_array($field)){
735
+    public function groupBy($field) {
736
+      if (is_array($field)) {
737 737
         $this->groupBy = implode(', ', $field);
738 738
       }
739
-      else{
739
+      else {
740 740
         $this->groupBy = $field;
741 741
       }
742 742
       return $this;
@@ -750,13 +750,13 @@  discard block
 block discarded – undo
750 750
      * @param  boolean $escape whether to escape or not the values
751 751
      * @return object        the current Database instance
752 752
      */
753
-    public function having($field, $op = null, $val = null, $escape = true){
754
-      if (is_array($op)){
753
+    public function having($field, $op = null, $val = null, $escape = true) {
754
+      if (is_array($op)) {
755 755
         $x = explode('?', $field);
756 756
         $w = '';
757
-        foreach($x as $k => $v){
758
-  	      if (!empty($v)){
759
-            if (! isset($op[$k])){
757
+        foreach ($x as $k => $v) {
758
+  	      if (!empty($v)) {
759
+            if (!isset($op[$k])) {
760 760
               $op[$k] = '';
761 761
             }
762 762
   	      	$w .= $v . (isset($op[$k]) ? $this->escape($op[$k], $escape) : '');
@@ -764,14 +764,14 @@  discard block
 block discarded – undo
764 764
       	}
765 765
         $this->having = $w;
766 766
       }
767
-      else if (! in_array($op, $this->operatorList)){
768
-        if (is_null($op)){
767
+      else if (!in_array($op, $this->operatorList)) {
768
+        if (is_null($op)) {
769 769
           $op = '';
770 770
         }
771 771
         $this->having = $field . ' > ' . ($this->escape($op, $escape));
772 772
       }
773
-      else{
774
-        if (is_null($val)){
773
+      else {
774
+        if (is_null($val)) {
775 775
           $val = '';
776 776
         }
777 777
         $this->having = $field . ' ' . $op . ' ' . ($this->escape($val, $escape));
@@ -783,7 +783,7 @@  discard block
 block discarded – undo
783 783
      * Return the number of rows returned by the current query
784 784
      * @return int
785 785
      */
786
-    public function numRows(){
786
+    public function numRows() {
787 787
       return $this->numRows;
788 788
     }
789 789
 
@@ -791,15 +791,15 @@  discard block
 block discarded – undo
791 791
      * Return the last insert id value
792 792
      * @return mixed
793 793
      */
794
-    public function insertId(){
794
+    public function insertId() {
795 795
       return $this->insertId;
796 796
     }
797 797
 
798 798
     /**
799 799
      * Show an error got from the current query (SQL command synthax error, database driver returned error, etc.)
800 800
      */
801
-    public function error(){
802
-  		if ($this->error){
801
+    public function error() {
802
+  		if ($this->error) {
803 803
   			show_error('Query: "' . $this->query . '" Error: ' . $this->error, 'Database Error');
804 804
   		}
805 805
     }
@@ -810,14 +810,14 @@  discard block
 block discarded – undo
810 810
      * If is string will determine the result type "array" or "object"
811 811
      * @return mixed       the query SQL string or the record result
812 812
      */
813
-    public function get($returnSQLQueryOrResultType = false){
813
+    public function get($returnSQLQueryOrResultType = false) {
814 814
       $this->limit = 1;
815 815
       $query = $this->getAll(true);
816
-      if ($returnSQLQueryOrResultType === true){
816
+      if ($returnSQLQueryOrResultType === true) {
817 817
         return $query;
818 818
       }
819
-      else{
820
-        return $this->query( $query, false, (($returnSQLQueryOrResultType == 'array') ? true : false) );
819
+      else {
820
+        return $this->query($query, false, (($returnSQLQueryOrResultType == 'array') ? true : false));
821 821
       }
822 822
     }
823 823
 
@@ -827,33 +827,33 @@  discard block
 block discarded – undo
827 827
      * If is string will determine the result type "array" or "object"
828 828
      * @return mixed       the query SQL string or the record result
829 829
      */
830
-    public function getAll($returnSQLQueryOrResultType = false){
830
+    public function getAll($returnSQLQueryOrResultType = false) {
831 831
       $query = 'SELECT ' . $this->select . ' FROM ' . $this->from;
832
-      if (! empty($this->join)){
832
+      if (!empty($this->join)) {
833 833
         $query .= $this->join;
834 834
       }
835 835
 	  
836
-      if (! empty($this->where)){
836
+      if (!empty($this->where)) {
837 837
         $query .= ' WHERE ' . $this->where;
838 838
       }
839 839
 
840
-      if (! empty($this->groupBy)){
840
+      if (!empty($this->groupBy)) {
841 841
         $query .= ' GROUP BY ' . $this->groupBy;
842 842
       }
843 843
 
844
-      if (! empty($this->having)){
844
+      if (!empty($this->having)) {
845 845
         $query .= ' HAVING ' . $this->having;
846 846
       }
847 847
 
848
-      if (! empty($this->orderBy)){
848
+      if (!empty($this->orderBy)) {
849 849
           $query .= ' ORDER BY ' . $this->orderBy;
850 850
       }
851 851
 
852
-      if (! empty($this->limit)){
852
+      if (!empty($this->limit)) {
853 853
       	$query .= ' LIMIT ' . $this->limit;
854 854
       }
855 855
 	  
856
-	   if ($returnSQLQueryOrResultType === true){
856
+	   if ($returnSQLQueryOrResultType === true) {
857 857
       	return $query;
858 858
       }
859 859
     	return $this->query($query, true, $returnSQLQueryOrResultType == 'array');
@@ -865,8 +865,8 @@  discard block
 block discarded – undo
865 865
      * @param  boolean $escape  whether to escape or not the values
866 866
      * @return mixed          the insert id of the new record or null
867 867
      */
868
-    public function insert($data = array(), $escape = true){
869
-      if (empty($data) && $this->getData()){
868
+    public function insert($data = array(), $escape = true) {
869
+      if (empty($data) && $this->getData()) {
870 870
         //as when using $this->setData() the data already escaped
871 871
         $escape = false;
872 872
         $data = $this->getData();
@@ -879,7 +879,7 @@  discard block
 block discarded – undo
879 879
       $query = 'INSERT INTO ' . $this->from . ' (' . $column . ') VALUES (' . $val . ')';
880 880
       $query = $this->query($query);
881 881
 
882
-      if ($query){
882
+      if ($query) {
883 883
         $this->insertId = $this->pdo->lastInsertId();
884 884
         return $this->insertId();
885 885
       }
@@ -892,27 +892,27 @@  discard block
 block discarded – undo
892 892
      * @param  boolean $escape  whether to escape or not the values
893 893
      * @return mixed          the update status
894 894
      */
895
-    public function update($data = array(), $escape = true){
895
+    public function update($data = array(), $escape = true) {
896 896
       $query = 'UPDATE ' . $this->from . ' SET ';
897 897
       $values = array();
898
-      if (empty($data) && $this->getData()){
898
+      if (empty($data) && $this->getData()) {
899 899
         //as when using $this->setData() the data already escaped
900 900
         $escape = false;
901 901
         $data = $this->getData();
902 902
       }
903
-      foreach ($data as $column => $val){
903
+      foreach ($data as $column => $val) {
904 904
         $values[] = $column . ' = ' . ($this->escape($val, $escape));
905 905
       }
906 906
       $query .= implode(', ', $values);
907
-      if (! empty($this->where)){
907
+      if (!empty($this->where)) {
908 908
         $query .= ' WHERE ' . $this->where;
909 909
       }
910 910
 
911
-      if (! empty($this->orderBy)){
911
+      if (!empty($this->orderBy)) {
912 912
         $query .= ' ORDER BY ' . $this->orderBy;
913 913
       }
914 914
 
915
-      if (! empty($this->limit)){
915
+      if (!empty($this->limit)) {
916 916
         $query .= ' LIMIT ' . $this->limit;
917 917
       }
918 918
       return $this->query($query);
@@ -922,22 +922,22 @@  discard block
 block discarded – undo
922 922
      * Delete the record in database
923 923
      * @return mixed the delete status
924 924
      */
925
-    public function delete(){
925
+    public function delete() {
926 926
     	$query = 'DELETE FROM ' . $this->from;
927 927
 
928
-    	if (! empty($this->where)){
928
+    	if (!empty($this->where)) {
929 929
     		$query .= ' WHERE ' . $this->where;
930 930
       	}
931 931
 
932
-    	if (! empty($this->orderBy)){
932
+    	if (!empty($this->orderBy)) {
933 933
     	  $query .= ' ORDER BY ' . $this->orderBy;
934 934
       	}
935 935
 
936
-    	if (! empty($this->limit)){
936
+    	if (!empty($this->limit)) {
937 937
     		$query .= ' LIMIT ' . $this->limit;
938 938
       	}
939 939
 
940
-    	if ($query == 'DELETE FROM ' . $this->from && $this->config['driver'] != 'sqlite'){  
940
+    	if ($query == 'DELETE FROM ' . $this->from && $this->config['driver'] != 'sqlite') {  
941 941
     		$query = 'TRUNCATE TABLE ' . $this->from;
942 942
       }
943 943
     	return $this->query($query);
@@ -948,8 +948,8 @@  discard block
 block discarded – undo
948 948
      * @param integer $ttl the cache time to live in second
949 949
      * @return object        the current Database instance
950 950
      */
951
-    public function setCache($ttl = 0){
952
-      if ($ttl > 0){
951
+    public function setCache($ttl = 0) {
952
+      if ($ttl > 0) {
953 953
         $this->cacheTtl = $ttl;
954 954
 		    $this->temporaryCacheTtl = $ttl;
955 955
       }
@@ -961,8 +961,8 @@  discard block
 block discarded – undo
961 961
 	 * @param  integer $ttl the cache time to live in second
962 962
 	 * @return object        the current Database instance
963 963
 	 */
964
-	public function cached($ttl = 0){
965
-      if ($ttl > 0){
964
+	public function cached($ttl = 0) {
965
+      if ($ttl > 0) {
966 966
         $this->temporaryCacheTtl = $ttl;
967 967
       }
968 968
 	  return $this;
@@ -974,9 +974,9 @@  discard block
 block discarded – undo
974 974
      * @param boolean $escaped whether we can do escape of not 
975 975
      * @return mixed       the data after escaped or the same data if not
976 976
      */
977
-    public function escape($data, $escaped = true){
978
-      if ($escaped){
979
-        if (! $this->pdo){
977
+    public function escape($data, $escaped = true) {
978
+      if ($escaped) {
979
+        if (!$this->pdo) {
980 980
           $this->connect();
981 981
         }
982 982
         return $this->pdo->quote(trim($data)); 
@@ -988,7 +988,7 @@  discard block
 block discarded – undo
988 988
      * Return the number query executed count for the current request
989 989
      * @return int
990 990
      */
991
-    public function queryCount(){
991
+    public function queryCount() {
992 992
       return $this->queryCount;
993 993
     }
994 994
 
@@ -996,7 +996,7 @@  discard block
 block discarded – undo
996 996
      * Return the current query SQL string
997 997
      * @return string
998 998
      */
999
-    public function getQuery(){
999
+    public function getQuery() {
1000 1000
       return $this->query;
1001 1001
     }
1002 1002
 
@@ -1004,7 +1004,7 @@  discard block
 block discarded – undo
1004 1004
      * Return the application database name
1005 1005
      * @return string
1006 1006
      */
1007
-    public function getDatabaseName(){
1007
+    public function getDatabaseName() {
1008 1008
       return $this->databaseName;
1009 1009
     }
1010 1010
 
@@ -1012,7 +1012,7 @@  discard block
 block discarded – undo
1012 1012
      * Return the database configuration
1013 1013
      * @return array
1014 1014
      */
1015
-    public  function getDatabaseConfiguration(){
1015
+    public  function getDatabaseConfiguration() {
1016 1016
       return $this->config;
1017 1017
     }
1018 1018
 
@@ -1020,7 +1020,7 @@  discard block
 block discarded – undo
1020 1020
      * set the database configuration
1021 1021
      * @param array $config the configuration
1022 1022
      */
1023
-    public function setDatabaseConfiguration(array $config){
1023
+    public function setDatabaseConfiguration(array $config) {
1024 1024
       $this->config = array_merge($this->config, $config);
1025 1025
       $this->prefix = $this->config['prefix'];
1026 1026
       $this->databaseName = $this->config['database'];
@@ -1032,7 +1032,7 @@  discard block
 block discarded – undo
1032 1032
      * Return the PDO instance
1033 1033
      * @return PDO
1034 1034
      */
1035
-    public function getPdo(){
1035
+    public function getPdo() {
1036 1036
       return $this->pdo;
1037 1037
     }
1038 1038
 
@@ -1040,7 +1040,7 @@  discard block
 block discarded – undo
1040 1040
      * Set the PDO instance
1041 1041
      * @param PDO $pdo the pdo object
1042 1042
      */
1043
-    public function setPdo(PDO $pdo){
1043
+    public function setPdo(PDO $pdo) {
1044 1044
       $this->pdo = $pdo;
1045 1045
       return $this;
1046 1046
     }
@@ -1050,7 +1050,7 @@  discard block
 block discarded – undo
1050 1050
      * Return the Log instance
1051 1051
      * @return Log
1052 1052
      */
1053
-    public function getLogger(){
1053
+    public function getLogger() {
1054 1054
       return $this->logger;
1055 1055
     }
1056 1056
 
@@ -1058,7 +1058,7 @@  discard block
 block discarded – undo
1058 1058
      * Set the log instance
1059 1059
      * @param Log $logger the log object
1060 1060
      */
1061
-    public function setLogger($logger){
1061
+    public function setLogger($logger) {
1062 1062
       $this->logger = $logger;
1063 1063
       return $this;
1064 1064
     }
@@ -1067,7 +1067,7 @@  discard block
 block discarded – undo
1067 1067
      * Return the cache instance
1068 1068
      * @return CacheInterface
1069 1069
      */
1070
-    public function getCacheInstance(){
1070
+    public function getCacheInstance() {
1071 1071
       return $this->cacheInstance;
1072 1072
     }
1073 1073
 
@@ -1075,7 +1075,7 @@  discard block
 block discarded – undo
1075 1075
      * Set the cache instance
1076 1076
      * @param CacheInterface $cache the cache object
1077 1077
      */
1078
-    public function setCacheInstance($cache){
1078
+    public function setCacheInstance($cache) {
1079 1079
       $this->cacheInstance = $cache;
1080 1080
       return $this;
1081 1081
     }
@@ -1084,7 +1084,7 @@  discard block
 block discarded – undo
1084 1084
      * Return the benchmark instance
1085 1085
      * @return Benchmark
1086 1086
      */
1087
-    public function getBenchmark(){
1087
+    public function getBenchmark() {
1088 1088
       return $this->benchmarkInstance;
1089 1089
     }
1090 1090
 
@@ -1092,7 +1092,7 @@  discard block
 block discarded – undo
1092 1092
      * Set the benchmark instance
1093 1093
      * @param Benchmark $cache the cache object
1094 1094
      */
1095
-    public function setBenchmark($benchmark){
1095
+    public function setBenchmark($benchmark) {
1096 1096
       $this->benchmarkInstance = $benchmark;
1097 1097
       return $this;
1098 1098
     }
@@ -1101,7 +1101,7 @@  discard block
 block discarded – undo
1101 1101
      * Return the data to be used for insert, update, etc.
1102 1102
      * @return array
1103 1103
      */
1104
-    public function getData(){
1104
+    public function getData() {
1105 1105
       return $this->data;
1106 1106
     }
1107 1107
 
@@ -1112,7 +1112,7 @@  discard block
 block discarded – undo
1112 1112
      * @param boolean $escape whether to escape or not the $value
1113 1113
      * @return object        the current Database instance
1114 1114
      */
1115
-    public function setData($key, $value, $escape = true){
1115
+    public function setData($key, $value, $escape = true) {
1116 1116
       $this->data[$key] = $this->escape($value, $escape);
1117 1117
       return $this;
1118 1118
     }
@@ -1125,14 +1125,14 @@  discard block
 block discarded – undo
1125 1125
      * @param  boolean $array return the result as array
1126 1126
      * @return mixed         the query result
1127 1127
      */
1128
-    public function query($query, $all = true, $array = false){
1128
+    public function query($query, $all = true, $array = false) {
1129 1129
       $this->reset();
1130 1130
       $query = $this->transformPreparedQuery($query, $all);
1131 1131
       $this->query = preg_replace('/\s\s+|\t\t+/', ' ', trim($query));
1132 1132
       
1133 1133
       $isSqlSELECTQuery = stristr($this->query, 'SELECT');
1134 1134
 
1135
-      $this->logger->info('Execute SQL query ['.$this->query.'], return type: ' . ($array?'ARRAY':'OBJECT') .', return as list: ' . (is_bool($all) && $all ? 'YES':'NO'));
1135
+      $this->logger->info('Execute SQL query [' . $this->query . '], return type: ' . ($array ? 'ARRAY' : 'OBJECT') . ', return as list: ' . (is_bool($all) && $all ? 'YES' : 'NO'));
1136 1136
       //cache expire time
1137 1137
       $cacheExpire = $this->temporaryCacheTtl;
1138 1138
       
@@ -1148,15 +1148,15 @@  discard block
 block discarded – undo
1148 1148
       //if can use cache feature for this query
1149 1149
       $dbCacheStatus = $cacheEnable && $cacheExpire > 0;
1150 1150
     
1151
-      if ($dbCacheStatus && $isSqlSELECTQuery){
1151
+      if ($dbCacheStatus && $isSqlSELECTQuery) {
1152 1152
           $this->logger->info('The cache is enabled for this query, try to get result from cache'); 
1153 1153
           $cacheContent = $this->getCacheContentForQuery($query, $all, $array);  
1154 1154
       }
1155 1155
       
1156
-      if ( !$cacheContent){
1156
+      if (!$cacheContent) {
1157 1157
         $sqlQuery = $this->runSqlQuery($query, $all, $array);
1158
-        if (is_object($sqlQuery)){
1159
-          if ($isSqlSELECTQuery){
1158
+        if (is_object($sqlQuery)) {
1159
+          if ($isSqlSELECTQuery) {
1160 1160
             $this->setQueryResultForSelect($sqlQuery, $all, $array);
1161 1161
             $this->setCacheContentForQuery(
1162 1162
                                             $this->query, 
@@ -1166,20 +1166,20 @@  discard block
 block discarded – undo
1166 1166
                                             $this->temporaryCacheTtl
1167 1167
                                           );
1168 1168
           }
1169
-          else{
1169
+          else {
1170 1170
               $this->setQueryResultForNonSelect($sqlQuery);
1171
-              if (! $this->result){
1171
+              if (!$this->result) {
1172 1172
                 $this->setQueryError();
1173 1173
               }
1174 1174
           }
1175 1175
         }
1176
-      } else if ($isSqlSELECTQuery){
1177
-          $this->logger->info('The result for query [' .$this->query. '] already cached use it');
1176
+      } else if ($isSqlSELECTQuery) {
1177
+          $this->logger->info('The result for query [' . $this->query . '] already cached use it');
1178 1178
           $this->result = $cacheContent;
1179 1179
           $this->numRows = count($this->result);
1180 1180
       }
1181 1181
       $this->queryCount++;
1182
-      if (! $this->result){
1182
+      if (!$this->result) {
1183 1183
         $this->logger->info('No result where found for the query [' . $query . ']');
1184 1184
       }
1185 1185
       return $this->result;
@@ -1190,12 +1190,12 @@  discard block
 block discarded – undo
1190 1190
      * Set the Log instance using argument or create new instance
1191 1191
      * @param object $logger the Log instance if not null
1192 1192
      */
1193
-    protected function setLoggerFromParamOrCreateNewInstance(Log $logger = null){
1194
-      if ($logger !== null){
1193
+    protected function setLoggerFromParamOrCreateNewInstance(Log $logger = null) {
1194
+      if ($logger !== null) {
1195 1195
         $this->logger = $logger;
1196 1196
       }
1197
-      else{
1198
-          $this->logger =& class_loader('Log', 'classes');
1197
+      else {
1198
+          $this->logger = & class_loader('Log', 'classes');
1199 1199
           $this->logger->setLogger('Library::Database');
1200 1200
       }
1201 1201
     }
@@ -1204,14 +1204,14 @@  discard block
 block discarded – undo
1204 1204
     * Setting the database configuration using the configuration file
1205 1205
     * @param array $overwriteConfig the additional configuration to overwrite with the existing one
1206 1206
     */
1207
-    protected function setDatabaseConfigurationFromConfigFile(array $overwriteConfig = array()){
1207
+    protected function setDatabaseConfigurationFromConfigFile(array $overwriteConfig = array()) {
1208 1208
         $db = array();
1209
-        if (file_exists(CONFIG_PATH . 'database.php')){
1209
+        if (file_exists(CONFIG_PATH . 'database.php')) {
1210 1210
             //here don't use require_once because somewhere user can create database instance directly
1211 1211
             require CONFIG_PATH . 'database.php';
1212 1212
         }
1213 1213
           
1214
-        if (! empty($overwriteConfig)){
1214
+        if (!empty($overwriteConfig)) {
1215 1215
           $db = array_merge($db, $overwriteConfig);
1216 1216
         }
1217 1217
         $config = array(
@@ -1233,9 +1233,9 @@  discard block
 block discarded – undo
1233 1233
      * This method is used to get the PDO DSN string using th configured driver
1234 1234
      * @return string the DSN string
1235 1235
      */
1236
-    protected function getDsnFromDriver(){
1236
+    protected function getDsnFromDriver() {
1237 1237
       $config = $this->getDatabaseConfiguration();
1238
-      if (! empty($config)){
1238
+      if (!empty($config)) {
1239 1239
             $driverDsnMap = array(
1240 1240
                                     'mysql' => 'mysql:host=' . $config['hostname'] . ';' 
1241 1241
                                                 . (($config['port']) != '' ? 'port=' . $config['port'] . ';' : '') 
@@ -1257,10 +1257,10 @@  discard block
 block discarded – undo
1257 1257
      * Set the database server port configuration using the current hostname like localhost:3309 
1258 1258
      * @return void
1259 1259
      */
1260
-    protected function setPortConfigurationFromHostname(){
1261
-      if (strstr($this->config['hostname'], ':')){
1260
+    protected function setPortConfigurationFromHostname() {
1261
+      if (strstr($this->config['hostname'], ':')) {
1262 1262
         $p = explode(':', $this->config['hostname']);
1263
-        if (count($p) >= 2){
1263
+        if (count($p) >= 2) {
1264 1264
           $this->setDatabaseConfiguration(array(
1265 1265
             'hostname' => $p[0],
1266 1266
             'port' => $p[1]
@@ -1275,15 +1275,15 @@  discard block
 block discarded – undo
1275 1275
      *
1276 1276
      * @return string
1277 1277
      */
1278
-    protected function getWhereStrIfIsArray(array $where, $type = '', $andOr = 'AND', $escape = true){
1278
+    protected function getWhereStrIfIsArray(array $where, $type = '', $andOr = 'AND', $escape = true) {
1279 1279
         $_where = array();
1280
-        foreach ($where as $column => $data){
1281
-          if (is_null($data)){
1280
+        foreach ($where as $column => $data) {
1281
+          if (is_null($data)) {
1282 1282
             $data = '';
1283 1283
           }
1284 1284
           $_where[] = $type . $column . ' = ' . ($this->escape($data, $escape));
1285 1285
         }
1286
-        $where = implode(' '.$andOr.' ', $_where);
1286
+        $where = implode(' ' . $andOr . ' ', $_where);
1287 1287
         return $where;
1288 1288
     }
1289 1289
 
@@ -1293,12 +1293,12 @@  discard block
 block discarded – undo
1293 1293
      *
1294 1294
      * @return string
1295 1295
      */
1296
-    protected function getWhereStrIfOperatorIsArray($where, array $op, $type = '', $escape = true){
1296
+    protected function getWhereStrIfOperatorIsArray($where, array $op, $type = '', $escape = true) {
1297 1297
        $x = explode('?', $where);
1298 1298
        $w = '';
1299
-        foreach($x as $k => $v){
1300
-          if (! empty($v)){
1301
-              if (isset($op[$k]) && is_null($op[$k])){
1299
+        foreach ($x as $k => $v) {
1300
+          if (!empty($v)) {
1301
+              if (isset($op[$k]) && is_null($op[$k])) {
1302 1302
                 $op[$k] = '';
1303 1303
               }
1304 1304
               $w .= $type . $v . (isset($op[$k]) ? ($this->escape($op[$k], $escape)) : '');
@@ -1313,16 +1313,16 @@  discard block
 block discarded – undo
1313 1313
      *
1314 1314
      * @return string
1315 1315
      */
1316
-    protected function getWhereStrForOperator($where, $op = null, $val = null, $type = '', $escape = true){
1316
+    protected function getWhereStrForOperator($where, $op = null, $val = null, $type = '', $escape = true) {
1317 1317
        $w = '';
1318
-       if (! in_array((string)$op, $this->operatorList)){
1319
-          if (is_null($op)){
1318
+       if (!in_array((string) $op, $this->operatorList)) {
1319
+          if (is_null($op)) {
1320 1320
             $op = '';
1321 1321
           }
1322 1322
           $w = $type . $where . ' = ' . ($this->escape($op, $escape));
1323 1323
         }
1324
-        else{
1325
-          if (is_null($val)){
1324
+        else {
1325
+          if (is_null($val)) {
1326 1326
             $val = '';
1327 1327
           }
1328 1328
           $w = $type . $where . $op . ($this->escape($val, $escape));
@@ -1335,16 +1335,16 @@  discard block
 block discarded – undo
1335 1335
        * @param string $whereStr the WHERE clause string
1336 1336
        * @param  string  $andOr the separator type used 'AND', 'OR', etc.
1337 1337
        */
1338
-      protected function setWhereStr($whereStr, $andOr = 'AND'){
1339
-        if (empty($this->where)){
1338
+      protected function setWhereStr($whereStr, $andOr = 'AND') {
1339
+        if (empty($this->where)) {
1340 1340
           $this->where = $whereStr;
1341 1341
         }
1342
-        else{
1343
-          if (substr($this->where, -1) == '('){
1342
+        else {
1343
+          if (substr($this->where, -1) == '(') {
1344 1344
             $this->where = $this->where . ' ' . $whereStr;
1345 1345
           }
1346
-          else{
1347
-            $this->where = $this->where . ' '.$andOr.' ' . $whereStr;
1346
+          else {
1347
+            $this->where = $this->where . ' ' . $andOr . ' ' . $whereStr;
1348 1348
           }
1349 1349
         }
1350 1350
       }
@@ -1355,12 +1355,12 @@  discard block
 block discarded – undo
1355 1355
      *
1356 1356
      * @return string
1357 1357
      */
1358
-    protected function transformPreparedQuery($query, $data){
1359
-      if (is_array($data)){
1358
+    protected function transformPreparedQuery($query, $data) {
1359
+      if (is_array($data)) {
1360 1360
         $x = explode('?', $query);
1361 1361
         $q = '';
1362
-        foreach($x as $k => $v){
1363
-          if (! empty($v)){
1362
+        foreach ($x as $k => $v) {
1363
+          if (!empty($v)) {
1364 1364
             $q .= $v . (isset($data[$k]) ? $this->escape($data[$k]) : '');
1365 1365
           }
1366 1366
         }
@@ -1375,8 +1375,8 @@  discard block
 block discarded – undo
1375 1375
      * 
1376 1376
      *  @return string
1377 1377
      */
1378
-    protected function getCacheBenchmarkKeyForQuery($query, $all, $array){
1379
-      if (is_array($all)){
1378
+    protected function getCacheBenchmarkKeyForQuery($query, $all, $array) {
1379
+      if (is_array($all)) {
1380 1380
         $all = 'array';
1381 1381
       }
1382 1382
       return md5($query . $all . $array);
@@ -1388,9 +1388,9 @@  discard block
 block discarded – undo
1388 1388
      *      
1389 1389
      * @return mixed
1390 1390
      */
1391
-    protected function getCacheContentForQuery($query, $all, $array){
1391
+    protected function getCacheContentForQuery($query, $all, $array) {
1392 1392
         $cacheKey = $this->getCacheBenchmarkKeyForQuery($query, $all, $array);
1393
-        if (is_object($this->cacheInstance)){
1393
+        if (is_object($this->cacheInstance)) {
1394 1394
           return $this->cacheInstance->get($cacheKey);
1395 1395
         }
1396 1396
         $instance = & get_instance()->cache;
@@ -1406,9 +1406,9 @@  discard block
 block discarded – undo
1406 1406
      * @param boolean $status whether can save the query result into cache
1407 1407
      * @param int $expire the cache TTL
1408 1408
      */
1409
-     protected function setCacheContentForQuery($query, $key, $result, $status, $expire){
1410
-        if ($status){
1411
-            $this->logger->info('Save the result for query [' .$query. '] into cache for future use');
1409
+     protected function setCacheContentForQuery($query, $key, $result, $status, $expire) {
1410
+        if ($status) {
1411
+            $this->logger->info('Save the result for query [' . $query . '] into cache for future use');
1412 1412
             $this->getCacheInstance()->set($key, $result, $expire);
1413 1413
         }
1414 1414
      }
@@ -1417,19 +1417,19 @@  discard block
 block discarded – undo
1417 1417
      * Set the result for SELECT query using PDOStatment
1418 1418
      * @see Database::query
1419 1419
      */
1420
-    protected function setQueryResultForSelect($pdoStatment, $all, $array){
1420
+    protected function setQueryResultForSelect($pdoStatment, $all, $array) {
1421 1421
       //if need return all result like list of record
1422
-      if (is_bool($all) && $all){
1422
+      if (is_bool($all) && $all) {
1423 1423
           $this->result = ($array === false) ? $pdoStatment->fetchAll(PDO::FETCH_OBJ) : $pdoStatment->fetchAll(PDO::FETCH_ASSOC);
1424 1424
       }
1425
-      else{
1425
+      else {
1426 1426
           $this->result = ($array === false) ? $pdoStatment->fetch(PDO::FETCH_OBJ) : $pdoStatment->fetch(PDO::FETCH_ASSOC);
1427 1427
       }
1428 1428
       //Sqlite and pgsql always return 0 when using rowCount()
1429
-      if (in_array($this->config['driver'], array('sqlite', 'pgsql'))){
1429
+      if (in_array($this->config['driver'], array('sqlite', 'pgsql'))) {
1430 1430
         $this->numRows = count($this->result);  
1431 1431
       }
1432
-      else{
1432
+      else {
1433 1433
         $this->numRows = $pdoStatment->rowCount(); 
1434 1434
       }
1435 1435
     }
@@ -1438,13 +1438,13 @@  discard block
 block discarded – undo
1438 1438
      * Set the result for other command than SELECT query using PDOStatment
1439 1439
      * @see Database::query
1440 1440
      */
1441
-    protected function setQueryResultForNonSelect($pdoStatment){
1441
+    protected function setQueryResultForNonSelect($pdoStatment) {
1442 1442
       //Sqlite and pgsql always return 0 when using rowCount()
1443
-      if (in_array($this->config['driver'], array('sqlite', 'pgsql'))){
1443
+      if (in_array($this->config['driver'], array('sqlite', 'pgsql'))) {
1444 1444
         $this->result = 1; //to test the result for the query like UPDATE, INSERT, DELETE
1445 1445
         $this->numRows = 1;  
1446 1446
       }
1447
-      else{
1447
+      else {
1448 1448
           $this->result = $pdoStatment->rowCount() >= 0; //to test the result for the query like UPDATE, INSERT, DELETE
1449 1449
           $this->numRows = $pdoStatment->rowCount(); 
1450 1450
       }
@@ -1453,7 +1453,7 @@  discard block
 block discarded – undo
1453 1453
     /**
1454 1454
      * Set error for database query execution
1455 1455
      */
1456
-    protected function setQueryError(){
1456
+    protected function setQueryError() {
1457 1457
       $error = $this->pdo->errorInfo();
1458 1458
       $this->error = isset($error[2]) ? $error[2] : '';
1459 1459
       $this->logger->error('The database query execution got error: ' . stringfy_vars($error));
@@ -1466,16 +1466,16 @@  discard block
 block discarded – undo
1466 1466
      * 
1467 1467
      * @return object|void
1468 1468
      */
1469
-    protected function runSqlQuery($query, $all, $array){
1469
+    protected function runSqlQuery($query, $all, $array) {
1470 1470
        //for database query execution time
1471 1471
         $benchmarkMarkerKey = $this->getCacheBenchmarkKeyForQuery($query, $all, $array);
1472 1472
         $benchmarkInstance = $this->getBenchmark();
1473
-        if (! is_object($benchmarkInstance)){
1473
+        if (!is_object($benchmarkInstance)) {
1474 1474
           $obj = & get_instance();
1475 1475
           $benchmarkInstance = $obj->benchmark; 
1476 1476
           $this->setBenchmark($benchmarkInstance);
1477 1477
         }
1478
-        if (! $this->pdo){
1478
+        if (!$this->pdo) {
1479 1479
             $this->connect();
1480 1480
         }
1481 1481
         
@@ -1486,10 +1486,10 @@  discard block
 block discarded – undo
1486 1486
         //get response time for this query
1487 1487
         $responseTime = $benchmarkInstance->elapsedTime('DATABASE_QUERY_START(' . $benchmarkMarkerKey . ')', 'DATABASE_QUERY_END(' . $benchmarkMarkerKey . ')');
1488 1488
         //TODO use the configuration value for the high response time currently is 1 second
1489
-        if ($responseTime >= 1 ){
1490
-            $this->logger->warning('High response time while processing database query [' .$query. ']. The response time is [' .$responseTime. '] sec.');
1489
+        if ($responseTime >= 1) {
1490
+            $this->logger->warning('High response time while processing database query [' . $query . ']. The response time is [' . $responseTime . '] sec.');
1491 1491
         }
1492
-        if ($sqlQuery){
1492
+        if ($sqlQuery) {
1493 1493
           return $sqlQuery;
1494 1494
         }
1495 1495
         $this->setQueryError();
@@ -1498,7 +1498,7 @@  discard block
 block discarded – undo
1498 1498
     /**
1499 1499
      * Reset the database class attributs to the initail values before each query.
1500 1500
      */
1501
-    private function reset(){
1501
+    private function reset() {
1502 1502
       $this->select   = '*';
1503 1503
       $this->from     = null;
1504 1504
       $this->where    = null;
@@ -1518,7 +1518,7 @@  discard block
 block discarded – undo
1518 1518
     /**
1519 1519
      * The class destructor
1520 1520
      */
1521
-    public function __destruct(){
1521
+    public function __destruct() {
1522 1522
       $this->pdo = null;
1523 1523
   }
1524 1524
 
Please login to merge, or discard this patch.
Braces   +23 added lines, -46 removed lines patch added patch discarded remove patch
@@ -206,14 +206,12 @@  discard block
 block discarded – undo
206 206
             $this->pdo->exec("SET CHARACTER SET '" . $config['charset'] . "'");
207 207
             $this->pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_OBJ);
208 208
             return true;
209
-          }
210
-          catch (PDOException $e){
209
+          } catch (PDOException $e){
211 210
             $this->logger->fatal($e->getMessage());
212 211
             show_error('Cannot connect to Database.');
213 212
             return false;
214 213
           }
215
-      }
216
-      else{
214
+      } else{
217 215
         show_error('Database configuration is not set.');
218 216
         return false;
219 217
       }
@@ -231,8 +229,7 @@  discard block
 block discarded – undo
231 229
           $froms .= $this->prefix . $key . ', ';
232 230
         }
233 231
         $this->from = rtrim($froms, ', ');
234
-      }
235
-      else{
232
+      } else{
236 233
         $this->from = $this->prefix . $table;
237 234
       }
238 235
       return $this;
@@ -338,8 +335,7 @@  discard block
 block discarded – undo
338 335
       }
339 336
       if (empty($this->join)){
340 337
         $this->join = ' ' . $type . 'JOIN' . ' ' . $table . ' ON ' . $on;
341
-      }
342
-      else{
338
+      } else{
343 339
         $this->join = $this->join . ' ' . $type . 'JOIN' . ' ' . $table . ' ON ' . $on;
344 340
       }
345 341
       return $this;
@@ -410,8 +406,7 @@  discard block
 block discarded – undo
410 406
         foreach($field as $f){
411 407
         	$this->whereIsNull($f, $andOr);
412 408
         }
413
-      }
414
-      else{
409
+      } else{
415 410
            $this->setWhereStr($field.' IS NULL ', $andOr);
416 411
       }
417 412
       return $this;
@@ -428,8 +423,7 @@  discard block
 block discarded – undo
428 423
         foreach($field as $f){
429 424
           $this->whereIsNotNull($f, $andOr);
430 425
         }
431
-      }
432
-      else{
426
+      } else{
433 427
           $this->setWhereStr($field.' IS NOT NULL ', $andOr);
434 428
       }
435 429
       return $this;
@@ -449,8 +443,7 @@  discard block
 block discarded – undo
449 443
       $whereStr = '';
450 444
       if (is_array($where)){
451 445
         $whereStr = $this->getWhereStrIfIsArray($where, $type, $andOr, $escape);
452
-      }
453
-      else{
446
+      } else{
454 447
         if (is_array($op)){
455 448
           $whereStr = $this->getWhereStrIfOperatorIsArray($where, $op, $type, $escape);
456 449
         } else {
@@ -498,12 +491,10 @@  discard block
 block discarded – undo
498 491
     public function groupStart($type = '', $andOr = ' AND'){
499 492
       if (empty($this->where)){
500 493
         $this->where = $type . ' (';
501
-      }
502
-      else{
494
+      } else{
503 495
           if (substr($this->where, -1) == '('){
504 496
             $this->where .= $type . ' (';
505
-          }
506
-          else{
497
+          } else{
507 498
           	$this->where .= $andOr . ' ' . $type . ' (';
508 499
           }
509 500
       }
@@ -702,8 +693,7 @@  discard block
 block discarded – undo
702 693
       }
703 694
       if (! is_null($limitEnd)){
704 695
         $this->limit = $limit . ', ' . $limitEnd;
705
-      }
706
-      else{
696
+      } else{
707 697
         $this->limit = $limit;
708 698
       }
709 699
       return $this;
@@ -718,8 +708,7 @@  discard block
 block discarded – undo
718 708
     public function orderBy($orderBy, $orderDir = ' ASC'){
719 709
         if (stristr($orderBy, ' ') || $orderBy == 'rand()'){
720 710
           $this->orderBy = empty($this->orderBy) ? $orderBy : $this->orderBy . ', ' . $orderBy;
721
-        }
722
-        else{
711
+        } else{
723 712
           $this->orderBy = empty($this->orderBy) ? ($orderBy . ' ' 
724 713
                             . strtoupper($orderDir)) : $this->orderBy 
725 714
                             . ', ' . $orderBy . ' ' . strtoupper($orderDir);
@@ -735,8 +724,7 @@  discard block
 block discarded – undo
735 724
     public function groupBy($field){
736 725
       if (is_array($field)){
737 726
         $this->groupBy = implode(', ', $field);
738
-      }
739
-      else{
727
+      } else{
740 728
         $this->groupBy = $field;
741 729
       }
742 730
       return $this;
@@ -763,14 +751,12 @@  discard block
 block discarded – undo
763 751
   	      }
764 752
       	}
765 753
         $this->having = $w;
766
-      }
767
-      else if (! in_array($op, $this->operatorList)){
754
+      } else if (! in_array($op, $this->operatorList)){
768 755
         if (is_null($op)){
769 756
           $op = '';
770 757
         }
771 758
         $this->having = $field . ' > ' . ($this->escape($op, $escape));
772
-      }
773
-      else{
759
+      } else{
774 760
         if (is_null($val)){
775 761
           $val = '';
776 762
         }
@@ -815,8 +801,7 @@  discard block
 block discarded – undo
815 801
       $query = $this->getAll(true);
816 802
       if ($returnSQLQueryOrResultType === true){
817 803
         return $query;
818
-      }
819
-      else{
804
+      } else{
820 805
         return $this->query( $query, false, (($returnSQLQueryOrResultType == 'array') ? true : false) );
821 806
       }
822 807
     }
@@ -1165,8 +1150,7 @@  discard block
 block discarded – undo
1165 1150
                                             $dbCacheStatus && $isSqlSELECTQuery, 
1166 1151
                                             $this->temporaryCacheTtl
1167 1152
                                           );
1168
-          }
1169
-          else{
1153
+          } else{
1170 1154
               $this->setQueryResultForNonSelect($sqlQuery);
1171 1155
               if (! $this->result){
1172 1156
                 $this->setQueryError();
@@ -1193,8 +1177,7 @@  discard block
 block discarded – undo
1193 1177
     protected function setLoggerFromParamOrCreateNewInstance(Log $logger = null){
1194 1178
       if ($logger !== null){
1195 1179
         $this->logger = $logger;
1196
-      }
1197
-      else{
1180
+      } else{
1198 1181
           $this->logger =& class_loader('Log', 'classes');
1199 1182
           $this->logger->setLogger('Library::Database');
1200 1183
       }
@@ -1320,8 +1303,7 @@  discard block
 block discarded – undo
1320 1303
             $op = '';
1321 1304
           }
1322 1305
           $w = $type . $where . ' = ' . ($this->escape($op, $escape));
1323
-        }
1324
-        else{
1306
+        } else{
1325 1307
           if (is_null($val)){
1326 1308
             $val = '';
1327 1309
           }
@@ -1338,12 +1320,10 @@  discard block
 block discarded – undo
1338 1320
       protected function setWhereStr($whereStr, $andOr = 'AND'){
1339 1321
         if (empty($this->where)){
1340 1322
           $this->where = $whereStr;
1341
-        }
1342
-        else{
1323
+        } else{
1343 1324
           if (substr($this->where, -1) == '('){
1344 1325
             $this->where = $this->where . ' ' . $whereStr;
1345
-          }
1346
-          else{
1326
+          } else{
1347 1327
             $this->where = $this->where . ' '.$andOr.' ' . $whereStr;
1348 1328
           }
1349 1329
         }
@@ -1421,15 +1401,13 @@  discard block
 block discarded – undo
1421 1401
       //if need return all result like list of record
1422 1402
       if (is_bool($all) && $all){
1423 1403
           $this->result = ($array === false) ? $pdoStatment->fetchAll(PDO::FETCH_OBJ) : $pdoStatment->fetchAll(PDO::FETCH_ASSOC);
1424
-      }
1425
-      else{
1404
+      } else{
1426 1405
           $this->result = ($array === false) ? $pdoStatment->fetch(PDO::FETCH_OBJ) : $pdoStatment->fetch(PDO::FETCH_ASSOC);
1427 1406
       }
1428 1407
       //Sqlite and pgsql always return 0 when using rowCount()
1429 1408
       if (in_array($this->config['driver'], array('sqlite', 'pgsql'))){
1430 1409
         $this->numRows = count($this->result);  
1431
-      }
1432
-      else{
1410
+      } else{
1433 1411
         $this->numRows = $pdoStatment->rowCount(); 
1434 1412
       }
1435 1413
     }
@@ -1443,8 +1421,7 @@  discard block
 block discarded – undo
1443 1421
       if (in_array($this->config['driver'], array('sqlite', 'pgsql'))){
1444 1422
         $this->result = 1; //to test the result for the query like UPDATE, INSERT, DELETE
1445 1423
         $this->numRows = 1;  
1446
-      }
1447
-      else{
1424
+      } else{
1448 1425
           $this->result = $pdoStatment->rowCount() >= 0; //to test the result for the query like UPDATE, INSERT, DELETE
1449 1426
           $this->numRows = $pdoStatment->rowCount(); 
1450 1427
       }
Please login to merge, or discard this patch.