Passed
Branch 1.0.0-dev (958860)
by nguereza
06:24
created
core/classes/Database.php 1 patch
Indentation   +626 added lines, -626 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,266 +22,266 @@  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 number of rows returned by the last query
42 42
 	 * @var int
43
-	*/
44
-    private $numRows             = 0;
43
+	 */
44
+	private $numRows             = 0;
45 45
 	
46 46
 	/**
47 47
 	 * The last insert id for the primary key column that have auto increment or sequence
48 48
 	 * @var mixed
49
-	*/
50
-    private $insertId            = null;
49
+	 */
50
+	private $insertId            = null;
51 51
 	
52 52
 	/**
53 53
 	 * The full SQL query statment after build for each command
54 54
 	 * @var string
55
-	*/
56
-    private $query               = null;
55
+	 */
56
+	private $query               = null;
57 57
 	
58 58
 	/**
59 59
 	 * The error returned for the last query
60 60
 	 * @var string
61
-	*/
62
-    private $error               = null;
61
+	 */
62
+	private $error               = null;
63 63
 	
64 64
 	/**
65 65
 	 * The result returned for the last query
66 66
 	 * @var mixed
67
-	*/
68
-    private $result              = array();
67
+	 */
68
+	private $result              = array();
69 69
 	
70 70
 	/**
71 71
 	 * The cache default time to live in second. 0 means no need to use the cache feature
72 72
 	 * @var int
73
-	*/
73
+	 */
74 74
 	private $cacheTtl              = 0;
75 75
 	
76 76
 	/**
77 77
 	 * The cache current time to live. 0 means no need to use the cache feature
78 78
 	 * @var int
79
-	*/
80
-    private $temporaryCacheTtl   = 0;
79
+	 */
80
+	private $temporaryCacheTtl   = 0;
81 81
 	
82 82
 	/**
83 83
 	 * The number of executed query for the current request
84 84
 	 * @var int
85
-	*/
86
-    private $queryCount          = 0;
85
+	 */
86
+	private $queryCount          = 0;
87 87
 	
88 88
 	/**
89 89
 	 * The default data to be used in the statments query INSERT, UPDATE
90 90
 	 * @var array
91
-	*/
92
-    private $data                = array();
91
+	 */
92
+	private $data                = array();
93 93
 	
94 94
 	/**
95 95
 	 * The database configuration
96 96
 	 * @var array
97
-	*/
98
-    private $config              = array();
97
+	 */
98
+	private $config              = array();
99 99
 	
100 100
 	/**
101 101
 	 * The logger instance
102 102
 	 * @var object
103 103
 	 */
104
-    private $logger              = null;
104
+	private $logger              = null;
105 105
 
106
-    /**
107
-    * The cache instance
108
-    * @var object
109
-    */
110
-    private $cacheInstance       = null;
106
+	/**
107
+	 * The cache instance
108
+	 * @var object
109
+	 */
110
+	private $cacheInstance       = null;
111 111
 
112
-    /**
113
-    * The benchmark instance
114
-    * @var object
115
-    */
116
-    private $benchmarkInstance   = null;
112
+	/**
113
+	 * The benchmark instance
114
+	 * @var object
115
+	 */
116
+	private $benchmarkInstance   = null;
117 117
 	
118 118
 	/**
119
-    * The DatabaseQueryBuilder instance
120
-    * @var object
121
-    */
122
-    private $queryBuilder        = null;
119
+	 * The DatabaseQueryBuilder instance
120
+	 * @var object
121
+	 */
122
+	private $queryBuilder        = null;
123 123
 
124 124
 
125
-    /**
126
-     * Construct new database
127
-     * @param array $overwriteConfig the config to overwrite with the config set in database.php
128
-     */
129
-    public function __construct($overwriteConfig = array()){
130
-        //Set Log instance to use
131
-        $this->setLoggerFromParamOrCreateNewInstance(null);
125
+	/**
126
+	 * Construct new database
127
+	 * @param array $overwriteConfig the config to overwrite with the config set in database.php
128
+	 */
129
+	public function __construct($overwriteConfig = array()){
130
+		//Set Log instance to use
131
+		$this->setLoggerFromParamOrCreateNewInstance(null);
132 132
 		
133
-		    //Set DatabaseQueryBuilder instance to use
134
-		    $this->setQueryBuilderFromParamOrCreateNewInstance(null);
133
+			//Set DatabaseQueryBuilder instance to use
134
+			$this->setQueryBuilderFromParamOrCreateNewInstance(null);
135 135
 
136
-        //Set database configuration
137
-        $this->setDatabaseConfiguration($overwriteConfig);
136
+		//Set database configuration
137
+		$this->setDatabaseConfiguration($overwriteConfig);
138 138
 	
139
-		    //cache time to live
140
-    	  $this->temporaryCacheTtl = $this->cacheTtl;
141
-    }
142
-
143
-    /**
144
-     * This is used to connect to database
145
-     * @return bool 
146
-     */
147
-    public function connect(){
148
-      $config = $this->getDatabaseConfiguration();
149
-      if (! empty($config)){
150
-        try{
151
-            $this->pdo = new PDO($this->getDsnFromDriver(), $config['username'], $config['password']);
152
-            $this->pdo->exec("SET NAMES '" . $config['charset'] . "' COLLATE '" . $config['collation'] . "'");
153
-            $this->pdo->exec("SET CHARACTER SET '" . $config['charset'] . "'");
154
-            $this->pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_OBJ);
155
-            return true;
156
-          }
157
-          catch (PDOException $e){
158
-            $this->logger->fatal($e->getMessage());
159
-            show_error('Cannot connect to Database.');
160
-            return false;
161
-          }
162
-      }
163
-      else{
164
-        show_error('Database configuration is not set.');
165
-        return false;
166
-      }
167
-    }
168
-
169
-
170
-    /**
171
-     * Return the number of rows returned by the current query
172
-     * @return int
173
-     */
174
-    public function numRows(){
175
-      return $this->numRows;
176
-    }
177
-
178
-    /**
179
-     * Return the last insert id value
180
-     * @return mixed
181
-     */
182
-    public function insertId(){
183
-      return $this->insertId;
184
-    }
185
-
186
-    /**
187
-     * Show an error got from the current query (SQL command synthax error, database driver returned error, etc.)
188
-     */
189
-    public function error(){
139
+			//cache time to live
140
+		  $this->temporaryCacheTtl = $this->cacheTtl;
141
+	}
142
+
143
+	/**
144
+	 * This is used to connect to database
145
+	 * @return bool 
146
+	 */
147
+	public function connect(){
148
+	  $config = $this->getDatabaseConfiguration();
149
+	  if (! empty($config)){
150
+		try{
151
+			$this->pdo = new PDO($this->getDsnFromDriver(), $config['username'], $config['password']);
152
+			$this->pdo->exec("SET NAMES '" . $config['charset'] . "' COLLATE '" . $config['collation'] . "'");
153
+			$this->pdo->exec("SET CHARACTER SET '" . $config['charset'] . "'");
154
+			$this->pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_OBJ);
155
+			return true;
156
+		  }
157
+		  catch (PDOException $e){
158
+			$this->logger->fatal($e->getMessage());
159
+			show_error('Cannot connect to Database.');
160
+			return false;
161
+		  }
162
+	  }
163
+	  else{
164
+		show_error('Database configuration is not set.');
165
+		return false;
166
+	  }
167
+	}
168
+
169
+
170
+	/**
171
+	 * Return the number of rows returned by the current query
172
+	 * @return int
173
+	 */
174
+	public function numRows(){
175
+	  return $this->numRows;
176
+	}
177
+
178
+	/**
179
+	 * Return the last insert id value
180
+	 * @return mixed
181
+	 */
182
+	public function insertId(){
183
+	  return $this->insertId;
184
+	}
185
+
186
+	/**
187
+	 * Show an error got from the current query (SQL command synthax error, database driver returned error, etc.)
188
+	 */
189
+	public function error(){
190 190
   		if ($this->error){
191 191
   			show_error('Query: "' . $this->query . '" Error: ' . $this->error, 'Database Error');
192 192
   		}
193
-    }
194
-
195
-    /**
196
-     * Get the result of one record rows returned by the current query
197
-     * @param  boolean $returnSQLQueryOrResultType if is boolean and true will return the SQL query string.
198
-     * If is string will determine the result type "array" or "object"
199
-     * @return mixed       the query SQL string or the record result
200
-     */
201
-    public function get($returnSQLQueryOrResultType = false){
202
-      $this->getQueryBuilder()->limit(1);
203
-      $query = $this->getAll(true);
204
-      if ($returnSQLQueryOrResultType === true){
205
-        return $query;
206
-      }
207
-      else{
208
-        return $this->query($query, false, $returnSQLQueryOrResultType == 'array');
209
-      }
210
-    }
211
-
212
-    /**
213
-     * Get the result of record rows list returned by the current query
214
-     * @param  boolean|string $returnSQLQueryOrResultType if is boolean and true will return the SQL query string.
215
-     * If is string will determine the result type "array" or "object"
216
-     * @return mixed       the query SQL string or the record result
217
-     */
218
-    public function getAll($returnSQLQueryOrResultType = false){
193
+	}
194
+
195
+	/**
196
+	 * Get the result of one record rows returned by the current query
197
+	 * @param  boolean $returnSQLQueryOrResultType if is boolean and true will return the SQL query string.
198
+	 * If is string will determine the result type "array" or "object"
199
+	 * @return mixed       the query SQL string or the record result
200
+	 */
201
+	public function get($returnSQLQueryOrResultType = false){
202
+	  $this->getQueryBuilder()->limit(1);
203
+	  $query = $this->getAll(true);
204
+	  if ($returnSQLQueryOrResultType === true){
205
+		return $query;
206
+	  }
207
+	  else{
208
+		return $this->query($query, false, $returnSQLQueryOrResultType == 'array');
209
+	  }
210
+	}
211
+
212
+	/**
213
+	 * Get the result of record rows list returned by the current query
214
+	 * @param  boolean|string $returnSQLQueryOrResultType if is boolean and true will return the SQL query string.
215
+	 * If is string will determine the result type "array" or "object"
216
+	 * @return mixed       the query SQL string or the record result
217
+	 */
218
+	public function getAll($returnSQLQueryOrResultType = false){
219 219
 	   $query = $this->getQueryBuilder()->getQuery();
220 220
 	   if ($returnSQLQueryOrResultType === true){
221
-      	return $query;
222
-      }
223
-      return $this->query($query, true, $returnSQLQueryOrResultType == 'array');
224
-    }
225
-
226
-    /**
227
-     * Insert new record in the database
228
-     * @param  array   $data   the record data if is empty will use the $this->data array.
229
-     * @param  boolean $escape  whether to escape or not the values
230
-     * @return mixed          the insert id of the new record or null
231
-     */
232
-    public function insert($data = array(), $escape = true){
233
-      if (empty($data) && $this->getData()){
234
-        //as when using $this->setData() may be the data already escaped
235
-        $escape = false;
236
-        $data = $this->getData();
237
-      }
238
-      $query = $this->getQueryBuilder()->insert($data, $escape)->getQuery();
239
-      $result = $this->query($query);
240
-      if ($result){
241
-        $this->insertId = $this->pdo->lastInsertId();
221
+	  	return $query;
222
+	  }
223
+	  return $this->query($query, true, $returnSQLQueryOrResultType == 'array');
224
+	}
225
+
226
+	/**
227
+	 * Insert new record in the database
228
+	 * @param  array   $data   the record data if is empty will use the $this->data array.
229
+	 * @param  boolean $escape  whether to escape or not the values
230
+	 * @return mixed          the insert id of the new record or null
231
+	 */
232
+	public function insert($data = array(), $escape = true){
233
+	  if (empty($data) && $this->getData()){
234
+		//as when using $this->setData() may be the data already escaped
235
+		$escape = false;
236
+		$data = $this->getData();
237
+	  }
238
+	  $query = $this->getQueryBuilder()->insert($data, $escape)->getQuery();
239
+	  $result = $this->query($query);
240
+	  if ($result){
241
+		$this->insertId = $this->pdo->lastInsertId();
242 242
 		//if the table doesn't have the auto increment field or sequence, the value of 0 will be returned 
243
-        return ! $this->insertId() ? true : $this->insertId();
244
-      }
245
-      return false;
246
-    }
247
-
248
-    /**
249
-     * Update record in the database
250
-     * @param  array   $data   the record data if is empty will use the $this->data array.
251
-     * @param  boolean $escape  whether to escape or not the values
252
-     * @return mixed          the update status
253
-     */
254
-    public function update($data = array(), $escape = true){
255
-      if (empty($data) && $this->getData()){
256
-        //as when using $this->setData() may be the data already escaped
257
-        $escape = false;
258
-        $data = $this->getData();
259
-      }
260
-      $query = $this->getQueryBuilder()->update($data, $escape)->getQuery();
261
-      return $this->query($query);
262
-    }
263
-
264
-    /**
265
-     * Delete the record in database
266
-     * @return mixed the delete status
267
-     */
268
-    public function delete(){
243
+		return ! $this->insertId() ? true : $this->insertId();
244
+	  }
245
+	  return false;
246
+	}
247
+
248
+	/**
249
+	 * Update record in the database
250
+	 * @param  array   $data   the record data if is empty will use the $this->data array.
251
+	 * @param  boolean $escape  whether to escape or not the values
252
+	 * @return mixed          the update status
253
+	 */
254
+	public function update($data = array(), $escape = true){
255
+	  if (empty($data) && $this->getData()){
256
+		//as when using $this->setData() may be the data already escaped
257
+		$escape = false;
258
+		$data = $this->getData();
259
+	  }
260
+	  $query = $this->getQueryBuilder()->update($data, $escape)->getQuery();
261
+	  return $this->query($query);
262
+	}
263
+
264
+	/**
265
+	 * Delete the record in database
266
+	 * @return mixed the delete status
267
+	 */
268
+	public function delete(){
269 269
 		$query = $this->getQueryBuilder()->delete()->getQuery();
270
-    	return $this->query($query);
271
-    }
272
-
273
-    /**
274
-     * Set database cache time to live
275
-     * @param integer $ttl the cache time to live in second
276
-     * @return object        the current Database instance
277
-     */
278
-    public function setCache($ttl = 0){
279
-      if ($ttl > 0){
280
-        $this->cacheTtl = $ttl;
281
-        $this->temporaryCacheTtl = $ttl;
282
-      }
283
-      return $this;
284
-    }
270
+		return $this->query($query);
271
+	}
272
+
273
+	/**
274
+	 * Set database cache time to live
275
+	 * @param integer $ttl the cache time to live in second
276
+	 * @return object        the current Database instance
277
+	 */
278
+	public function setCache($ttl = 0){
279
+	  if ($ttl > 0){
280
+		$this->cacheTtl = $ttl;
281
+		$this->temporaryCacheTtl = $ttl;
282
+	  }
283
+	  return $this;
284
+	}
285 285
 	
286 286
 	/**
287 287
 	 * Enabled cache temporary for the current query not globally	
@@ -289,272 +289,272 @@  discard block
 block discarded – undo
289 289
 	 * @return object        the current Database instance
290 290
 	 */
291 291
   	public function cached($ttl = 0){
292
-        if ($ttl > 0){
293
-          $this->temporaryCacheTtl = $ttl;
294
-        }
295
-        return $this;
296
-    }
297
-
298
-    /**
299
-     * Escape the data before execute query useful for security.
300
-     * @param  mixed $data the data to be escaped
301
-     * @param boolean $escaped whether we can do escape of not 
302
-     * @return mixed       the data after escaped or the same data if not
303
-     */
304
-    public function escape($data, $escaped = true){
305
-      return $escaped ? 
306
-                      $this->getPdo()->quote(trim($data)) 
307
-                      : $data; 
308
-    }
309
-
310
-    /**
311
-     * Return the number query executed count for the current request
312
-     * @return int
313
-     */
314
-    public function queryCount(){
315
-      return $this->queryCount;
316
-    }
317
-
318
-    /**
319
-     * Return the current query SQL string
320
-     * @return string
321
-     */
322
-    public function getQuery(){
323
-      return $this->query;
324
-    }
325
-
326
-    /**
327
-     * Return the application database name
328
-     * @return string
329
-     */
330
-    public function getDatabaseName(){
331
-      return $this->databaseName;
332
-    }
333
-
334
-    /**
335
-     * Return the PDO instance
336
-     * @return object
337
-     */
338
-    public function getPdo(){
339
-      return $this->pdo;
340
-    }
341
-
342
-    /**
343
-     * Set the PDO instance
344
-     * @param object $pdo the pdo object
292
+		if ($ttl > 0){
293
+		  $this->temporaryCacheTtl = $ttl;
294
+		}
295
+		return $this;
296
+	}
297
+
298
+	/**
299
+	 * Escape the data before execute query useful for security.
300
+	 * @param  mixed $data the data to be escaped
301
+	 * @param boolean $escaped whether we can do escape of not 
302
+	 * @return mixed       the data after escaped or the same data if not
303
+	 */
304
+	public function escape($data, $escaped = true){
305
+	  return $escaped ? 
306
+					  $this->getPdo()->quote(trim($data)) 
307
+					  : $data; 
308
+	}
309
+
310
+	/**
311
+	 * Return the number query executed count for the current request
312
+	 * @return int
313
+	 */
314
+	public function queryCount(){
315
+	  return $this->queryCount;
316
+	}
317
+
318
+	/**
319
+	 * Return the current query SQL string
320
+	 * @return string
321
+	 */
322
+	public function getQuery(){
323
+	  return $this->query;
324
+	}
325
+
326
+	/**
327
+	 * Return the application database name
328
+	 * @return string
329
+	 */
330
+	public function getDatabaseName(){
331
+	  return $this->databaseName;
332
+	}
333
+
334
+	/**
335
+	 * Return the PDO instance
336
+	 * @return object
337
+	 */
338
+	public function getPdo(){
339
+	  return $this->pdo;
340
+	}
341
+
342
+	/**
343
+	 * Set the PDO instance
344
+	 * @param object $pdo the pdo object
345 345
 	 * @return object Database
346
-     */
347
-    public function setPdo(PDO $pdo){
348
-      $this->pdo = $pdo;
349
-      return $this;
350
-    }
351
-
352
-
353
-    /**
354
-     * Return the Log instance
355
-     * @return Log
356
-     */
357
-    public function getLogger(){
358
-      return $this->logger;
359
-    }
360
-
361
-    /**
362
-     * Set the log instance
363
-     * @param Log $logger the log object
346
+	 */
347
+	public function setPdo(PDO $pdo){
348
+	  $this->pdo = $pdo;
349
+	  return $this;
350
+	}
351
+
352
+
353
+	/**
354
+	 * Return the Log instance
355
+	 * @return Log
356
+	 */
357
+	public function getLogger(){
358
+	  return $this->logger;
359
+	}
360
+
361
+	/**
362
+	 * Set the log instance
363
+	 * @param Log $logger the log object
364 364
 	 * @return object Database
365
-     */
366
-    public function setLogger($logger){
367
-      $this->logger = $logger;
368
-      return $this;
369
-    }
370
-
371
-     /**
372
-     * Return the cache instance
373
-     * @return CacheInterface
374
-     */
375
-    public function getCacheInstance(){
376
-      return $this->cacheInstance;
377
-    }
378
-
379
-    /**
380
-     * Set the cache instance
381
-     * @param CacheInterface $cache the cache object
365
+	 */
366
+	public function setLogger($logger){
367
+	  $this->logger = $logger;
368
+	  return $this;
369
+	}
370
+
371
+	 /**
372
+	  * Return the cache instance
373
+	  * @return CacheInterface
374
+	  */
375
+	public function getCacheInstance(){
376
+	  return $this->cacheInstance;
377
+	}
378
+
379
+	/**
380
+	 * Set the cache instance
381
+	 * @param CacheInterface $cache the cache object
382 382
 	 * @return object Database
383
-     */
384
-    public function setCacheInstance($cache){
385
-      $this->cacheInstance = $cache;
386
-      return $this;
387
-    }
388
-
389
-    /**
390
-     * Return the benchmark instance
391
-     * @return Benchmark
392
-     */
393
-    public function getBenchmark(){
394
-      return $this->benchmarkInstance;
395
-    }
396
-
397
-    /**
398
-     * Set the benchmark instance
399
-     * @param Benchmark $benchmark the benchmark object
383
+	 */
384
+	public function setCacheInstance($cache){
385
+	  $this->cacheInstance = $cache;
386
+	  return $this;
387
+	}
388
+
389
+	/**
390
+	 * Return the benchmark instance
391
+	 * @return Benchmark
392
+	 */
393
+	public function getBenchmark(){
394
+	  return $this->benchmarkInstance;
395
+	}
396
+
397
+	/**
398
+	 * Set the benchmark instance
399
+	 * @param Benchmark $benchmark the benchmark object
400 400
 	 * @return object Database
401
-     */
402
-    public function setBenchmark($benchmark){
403
-      $this->benchmarkInstance = $benchmark;
404
-      return $this;
405
-    }
401
+	 */
402
+	public function setBenchmark($benchmark){
403
+	  $this->benchmarkInstance = $benchmark;
404
+	  return $this;
405
+	}
406 406
 	
407 407
 	
408 408
 	/**
409
-     * Return the DatabaseQueryBuilder instance
410
-     * @return object DatabaseQueryBuilder
411
-     */
412
-    public function getQueryBuilder(){
413
-      return $this->queryBuilder;
414
-    }
415
-
416
-    /**
417
-     * Set the DatabaseQueryBuilder instance
418
-     * @param object DatabaseQueryBuilder $queryBuilder the DatabaseQueryBuilder object
419
-     */
420
-    public function setQueryBuilder(DatabaseQueryBuilder $queryBuilder){
421
-      $this->queryBuilder = $queryBuilder;
422
-      return $this;
423
-    }
424
-
425
-    /**
426
-     * Return the data to be used for insert, update, etc.
427
-     * @return array
428
-     */
429
-    public function getData(){
430
-      return $this->data;
431
-    }
432
-
433
-    /**
434
-     * Set the data to be used for insert, update, etc.
435
-     * @param string|array $key the data key identified
436
-     * @param mixed $value the data value
437
-     * @param boolean $escape whether to escape or not the $value
438
-     * @return object        the current Database instance
439
-     */
440
-    public function setData($key, $value = null, $escape = true){
409
+	 * Return the DatabaseQueryBuilder instance
410
+	 * @return object DatabaseQueryBuilder
411
+	 */
412
+	public function getQueryBuilder(){
413
+	  return $this->queryBuilder;
414
+	}
415
+
416
+	/**
417
+	 * Set the DatabaseQueryBuilder instance
418
+	 * @param object DatabaseQueryBuilder $queryBuilder the DatabaseQueryBuilder object
419
+	 */
420
+	public function setQueryBuilder(DatabaseQueryBuilder $queryBuilder){
421
+	  $this->queryBuilder = $queryBuilder;
422
+	  return $this;
423
+	}
424
+
425
+	/**
426
+	 * Return the data to be used for insert, update, etc.
427
+	 * @return array
428
+	 */
429
+	public function getData(){
430
+	  return $this->data;
431
+	}
432
+
433
+	/**
434
+	 * Set the data to be used for insert, update, etc.
435
+	 * @param string|array $key the data key identified
436
+	 * @param mixed $value the data value
437
+	 * @param boolean $escape whether to escape or not the $value
438
+	 * @return object        the current Database instance
439
+	 */
440
+	public function setData($key, $value = null, $escape = true){
441 441
   	  if(is_array($key)){
442
-    		foreach($key as $k => $v){
443
-    			$this->setData($k, $v, $escape);
444
-    		}	
442
+			foreach($key as $k => $v){
443
+				$this->setData($k, $v, $escape);
444
+			}	
445 445
   	  } else {
446
-        $this->data[$key] = $this->escape($value, $escape);
446
+		$this->data[$key] = $this->escape($value, $escape);
447 447
   	  }
448
-      return $this;
449
-    }
450
-
451
-     /**
452
-     * Execute an SQL query
453
-     * @param  string  $query the query SQL string
454
-     * @param  boolean|array $all  if boolean this indicate whether to return all record or not, if array 
455
-     * will 
456
-     * @param  boolean $array return the result as array
457
-     * @return mixed         the query result
458
-     */
459
-    public function query($query, $all = true, $array = false){
460
-      $this->reset();
461
-      $query = $this->getPreparedQuery($query, $all);
462
-      $this->query = preg_replace('/\s\s+|\t\t+/', ' ', trim($query));
448
+	  return $this;
449
+	}
450
+
451
+	 /**
452
+	  * Execute an SQL query
453
+	  * @param  string  $query the query SQL string
454
+	  * @param  boolean|array $all  if boolean this indicate whether to return all record or not, if array 
455
+	  * will 
456
+	  * @param  boolean $array return the result as array
457
+	  * @return mixed         the query result
458
+	  */
459
+	public function query($query, $all = true, $array = false){
460
+	  $this->reset();
461
+	  $query = $this->getPreparedQuery($query, $all);
462
+	  $this->query = preg_replace('/\s\s+|\t\t+/', ' ', trim($query));
463 463
       
464
-      $isSqlSELECTQuery = stristr($this->query, 'SELECT') !== false;
465
-
466
-      $this->logger->info(
467
-                          'Execute SQL query ['.$this->query.'], return type: ' 
468
-                          . ($array?'ARRAY':'OBJECT') .', return as list: ' 
469
-                          . (is_bool($all) && $all ? 'YES':'NO')
470
-                        );
471
-      //cache expire time
472
-      $cacheExpire = $this->temporaryCacheTtl;
464
+	  $isSqlSELECTQuery = stristr($this->query, 'SELECT') !== false;
465
+
466
+	  $this->logger->info(
467
+						  'Execute SQL query ['.$this->query.'], return type: ' 
468
+						  . ($array?'ARRAY':'OBJECT') .', return as list: ' 
469
+						  . (is_bool($all) && $all ? 'YES':'NO')
470
+						);
471
+	  //cache expire time
472
+	  $cacheExpire = $this->temporaryCacheTtl;
473 473
       
474
-      //return to the initial cache time
475
-      $this->temporaryCacheTtl = $this->cacheTtl;
474
+	  //return to the initial cache time
475
+	  $this->temporaryCacheTtl = $this->cacheTtl;
476 476
       
477
-      //config for cache
478
-      $cacheEnable = get_config('cache_enable');
477
+	  //config for cache
478
+	  $cacheEnable = get_config('cache_enable');
479 479
       
480
-      //the database cache content
481
-      $cacheContent = null;
480
+	  //the database cache content
481
+	  $cacheContent = null;
482 482
 
483
-      //if can use cache feature for this query
484
-      $dbCacheStatus = $cacheEnable && $cacheExpire > 0;
483
+	  //if can use cache feature for this query
484
+	  $dbCacheStatus = $cacheEnable && $cacheExpire > 0;
485 485
     
486
-      if ($dbCacheStatus && $isSqlSELECTQuery){
487
-          $this->logger->info('The cache is enabled for this query, try to get result from cache'); 
488
-          $cacheContent = $this->getCacheContentForQuery($query, $all, $array);  
489
-      }
486
+	  if ($dbCacheStatus && $isSqlSELECTQuery){
487
+		  $this->logger->info('The cache is enabled for this query, try to get result from cache'); 
488
+		  $cacheContent = $this->getCacheContentForQuery($query, $all, $array);  
489
+	  }
490 490
       
491
-      if ( !$cacheContent){
492
-        $sqlQuery = $this->runSqlQuery($query, $all, $array);
493
-        if (is_object($sqlQuery)){
494
-          if ($isSqlSELECTQuery){
495
-            $this->setQueryResultForSelect($sqlQuery, $all, $array);
496
-            $this->setCacheContentForQuery(
497
-                                            $this->query, 
498
-                                            $this->getCacheBenchmarkKeyForQuery($this->query, $all, $array), 
499
-                                            $this->result, 
500
-                                            $dbCacheStatus && $isSqlSELECTQuery, 
501
-                                            $cacheExpire
502
-                                          );
503
-            if (! $this->result){
504
-              $this->logger->info('No result where found for the query [' . $query . ']');
505
-            }
506
-          } else {
507
-              $this->setQueryResultForNonSelect($sqlQuery);
508
-          }
509
-        }
510
-      } else if ($isSqlSELECTQuery){
511
-          $this->logger->info('The result for query [' .$this->query. '] already cached use it');
512
-          $this->result = $cacheContent;
513
-          $this->numRows = count($this->result);
514
-      }
515
-      return $this->result;
516
-    }
491
+	  if ( !$cacheContent){
492
+		$sqlQuery = $this->runSqlQuery($query, $all, $array);
493
+		if (is_object($sqlQuery)){
494
+		  if ($isSqlSELECTQuery){
495
+			$this->setQueryResultForSelect($sqlQuery, $all, $array);
496
+			$this->setCacheContentForQuery(
497
+											$this->query, 
498
+											$this->getCacheBenchmarkKeyForQuery($this->query, $all, $array), 
499
+											$this->result, 
500
+											$dbCacheStatus && $isSqlSELECTQuery, 
501
+											$cacheExpire
502
+										  );
503
+			if (! $this->result){
504
+			  $this->logger->info('No result where found for the query [' . $query . ']');
505
+			}
506
+		  } else {
507
+			  $this->setQueryResultForNonSelect($sqlQuery);
508
+		  }
509
+		}
510
+	  } else if ($isSqlSELECTQuery){
511
+		  $this->logger->info('The result for query [' .$this->query. '] already cached use it');
512
+		  $this->result = $cacheContent;
513
+		  $this->numRows = count($this->result);
514
+	  }
515
+	  return $this->result;
516
+	}
517 517
 	
518 518
 	/**
519
-     * Run the database SQL query and return the PDOStatment object
520
-     * @see Database::query
521
-     * 
522
-     * @return object|void
523
-     */
524
-    public function runSqlQuery($query, $all, $array){
525
-       //for database query execution time
526
-        $benchmarkMarkerKey = $this->getCacheBenchmarkKeyForQuery($query, $all, $array);
527
-        $benchmarkInstance = $this->getBenchmark();
528
-        if (! is_object($benchmarkInstance)){
529
-          $obj = & get_instance();
530
-          $benchmarkInstance = $obj->benchmark; 
531
-          $this->setBenchmark($benchmarkInstance);
532
-        }
519
+	 * Run the database SQL query and return the PDOStatment object
520
+	 * @see Database::query
521
+	 * 
522
+	 * @return object|void
523
+	 */
524
+	public function runSqlQuery($query, $all, $array){
525
+	   //for database query execution time
526
+		$benchmarkMarkerKey = $this->getCacheBenchmarkKeyForQuery($query, $all, $array);
527
+		$benchmarkInstance = $this->getBenchmark();
528
+		if (! is_object($benchmarkInstance)){
529
+		  $obj = & get_instance();
530
+		  $benchmarkInstance = $obj->benchmark; 
531
+		  $this->setBenchmark($benchmarkInstance);
532
+		}
533 533
         
534
-        $benchmarkInstance->mark('DATABASE_QUERY_START(' . $benchmarkMarkerKey . ')');
535
-        //Now execute the query
536
-        $sqlQuery = $this->pdo->query($query);
534
+		$benchmarkInstance->mark('DATABASE_QUERY_START(' . $benchmarkMarkerKey . ')');
535
+		//Now execute the query
536
+		$sqlQuery = $this->pdo->query($query);
537 537
         
538
-        //get response time for this query
539
-        $responseTime = $benchmarkInstance->elapsedTime('DATABASE_QUERY_START(' . $benchmarkMarkerKey . ')', 'DATABASE_QUERY_END(' . $benchmarkMarkerKey . ')');
540
-		    //TODO use the configuration value for the high response time currently is 1 second
541
-        if ($responseTime >= 1 ){
542
-            $this->logger->warning('High response time while processing database query [' .$query. ']. The response time is [' .$responseTime. '] sec.');
543
-        }
544
-		    //count the number of query execution to server
545
-        $this->queryCount++;
538
+		//get response time for this query
539
+		$responseTime = $benchmarkInstance->elapsedTime('DATABASE_QUERY_START(' . $benchmarkMarkerKey . ')', 'DATABASE_QUERY_END(' . $benchmarkMarkerKey . ')');
540
+			//TODO use the configuration value for the high response time currently is 1 second
541
+		if ($responseTime >= 1 ){
542
+			$this->logger->warning('High response time while processing database query [' .$query. ']. The response time is [' .$responseTime. '] sec.');
543
+		}
544
+			//count the number of query execution to server
545
+		$this->queryCount++;
546 546
 		
547
-        if ($sqlQuery !== false){
548
-          return $sqlQuery;
549
-        }
550
-        $this->setQueryError();
551
-    }
547
+		if ($sqlQuery !== false){
548
+		  return $sqlQuery;
549
+		}
550
+		$this->setQueryError();
551
+	}
552 552
 	
553 553
 	
554 554
 	 /**
555
-	 * Return the database configuration
556
-	 * @return array
557
-	 */
555
+	  * Return the database configuration
556
+	  * @return array
557
+	  */
558 558
 	public  function getDatabaseConfiguration(){
559 559
 	  return $this->config;
560 560
 	}
@@ -563,39 +563,39 @@  discard block
 block discarded – undo
563 563
     * Setting the database configuration using the configuration file and additional configuration from param
564 564
     * @param array $overwriteConfig the additional configuration to overwrite with the existing one
565 565
     * @param boolean $useConfigFile whether to use database configuration file
566
-	  * @return object Database
566
+    * @return object Database
567 567
     */
568
-    public function setDatabaseConfiguration(array $overwriteConfig = array(), $useConfigFile = true){
569
-        $db = array();
570
-        if ($useConfigFile && file_exists(CONFIG_PATH . 'database.php')){
571
-            //here don't use require_once because somewhere user can create database instance directly
572
-            require CONFIG_PATH . 'database.php';
573
-        }
568
+	public function setDatabaseConfiguration(array $overwriteConfig = array(), $useConfigFile = true){
569
+		$db = array();
570
+		if ($useConfigFile && file_exists(CONFIG_PATH . 'database.php')){
571
+			//here don't use require_once because somewhere user can create database instance directly
572
+			require CONFIG_PATH . 'database.php';
573
+		}
574 574
         
575
-        //merge with the parameter  
576
-        $db = array_merge($db, $overwriteConfig);
575
+		//merge with the parameter  
576
+		$db = array_merge($db, $overwriteConfig);
577 577
         
578
-        //default configuration
579
-        $config = array(
580
-          'driver' => 'mysql',
581
-          'username' => 'root',
582
-          'password' => '',
583
-          'database' => '',
584
-          'hostname' => 'localhost',
585
-          'charset' => 'utf8',
586
-          'collation' => 'utf8_general_ci',
587
-          'prefix' => '',
588
-          'port' => ''
589
-        );
578
+		//default configuration
579
+		$config = array(
580
+		  'driver' => 'mysql',
581
+		  'username' => 'root',
582
+		  'password' => '',
583
+		  'database' => '',
584
+		  'hostname' => 'localhost',
585
+		  'charset' => 'utf8',
586
+		  'collation' => 'utf8_general_ci',
587
+		  'prefix' => '',
588
+		  'port' => ''
589
+		);
590 590
 		
591
-    		$config = array_merge($config, $db);
592
-    		//determine the port using the hostname like localhost:3307
593
-        //hostname will be "localhost", and port "3307"
594
-        $p = explode(':', $config['hostname']);
595
-    	  if (count($p) >= 2){
596
-    		  $config['hostname'] = $p[0];
597
-    		  $config['port'] = $p[1];
598
-    		}
591
+			$config = array_merge($config, $db);
592
+			//determine the port using the hostname like localhost:3307
593
+		//hostname will be "localhost", and port "3307"
594
+		$p = explode(':', $config['hostname']);
595
+		  if (count($p) >= 2){
596
+			  $config['hostname'] = $p[0];
597
+			  $config['port'] = $p[1];
598
+			}
599 599
 		
600 600
 		 $this->databaseName = $config['database'];
601 601
 		 $this->config = $config;
@@ -620,77 +620,77 @@  discard block
 block discarded – undo
620 620
   }
621 621
 	
622 622
    /**
623
-   * Set the result for SELECT query using PDOStatment
624
-   * @see Database::query
625
-   */
626
-    protected function setQueryResultForSelect($pdoStatment, $all, $array){
627
-      //if need return all result like list of record
628
-      if (is_bool($all) && $all){
629
-          $this->result = ($array === false) ? $pdoStatment->fetchAll(PDO::FETCH_OBJ) : $pdoStatment->fetchAll(PDO::FETCH_ASSOC);
630
-      }
631
-      else{
632
-          $this->result = ($array === false) ? $pdoStatment->fetch(PDO::FETCH_OBJ) : $pdoStatment->fetch(PDO::FETCH_ASSOC);
633
-      }
634
-      //Sqlite and pgsql always return 0 when using rowCount()
635
-      if (in_array($this->config['driver'], array('sqlite', 'pgsql'))){
636
-        $this->numRows = count($this->result);  
637
-      }
638
-      else{
639
-        $this->numRows = $pdoStatment->rowCount(); 
640
-      }
641
-    }
642
-
643
-    /**
644
-     * Set the result for other command than SELECT query using PDOStatment
645
-     * @see Database::query
646
-     */
647
-    protected function setQueryResultForNonSelect($pdoStatment){
648
-      //Sqlite and pgsql always return 0 when using rowCount()
649
-      if (in_array($this->config['driver'], array('sqlite', 'pgsql'))){
650
-        $this->result = true; //to test the result for the query like UPDATE, INSERT, DELETE
651
-        $this->numRows = 1; //TODO use the correct method to get the exact affected row
652
-      }
653
-      else{
654
-          $this->result = $pdoStatment->rowCount() >= 0; //to test the result for the query like UPDATE, INSERT, DELETE
655
-          $this->numRows = $pdoStatment->rowCount(); 
656
-      }
657
-    }
623
+    * Set the result for SELECT query using PDOStatment
624
+    * @see Database::query
625
+    */
626
+	protected function setQueryResultForSelect($pdoStatment, $all, $array){
627
+	  //if need return all result like list of record
628
+	  if (is_bool($all) && $all){
629
+		  $this->result = ($array === false) ? $pdoStatment->fetchAll(PDO::FETCH_OBJ) : $pdoStatment->fetchAll(PDO::FETCH_ASSOC);
630
+	  }
631
+	  else{
632
+		  $this->result = ($array === false) ? $pdoStatment->fetch(PDO::FETCH_OBJ) : $pdoStatment->fetch(PDO::FETCH_ASSOC);
633
+	  }
634
+	  //Sqlite and pgsql always return 0 when using rowCount()
635
+	  if (in_array($this->config['driver'], array('sqlite', 'pgsql'))){
636
+		$this->numRows = count($this->result);  
637
+	  }
638
+	  else{
639
+		$this->numRows = $pdoStatment->rowCount(); 
640
+	  }
641
+	}
642
+
643
+	/**
644
+	 * Set the result for other command than SELECT query using PDOStatment
645
+	 * @see Database::query
646
+	 */
647
+	protected function setQueryResultForNonSelect($pdoStatment){
648
+	  //Sqlite and pgsql always return 0 when using rowCount()
649
+	  if (in_array($this->config['driver'], array('sqlite', 'pgsql'))){
650
+		$this->result = true; //to test the result for the query like UPDATE, INSERT, DELETE
651
+		$this->numRows = 1; //TODO use the correct method to get the exact affected row
652
+	  }
653
+	  else{
654
+		  $this->result = $pdoStatment->rowCount() >= 0; //to test the result for the query like UPDATE, INSERT, DELETE
655
+		  $this->numRows = $pdoStatment->rowCount(); 
656
+	  }
657
+	}
658 658
 
659 659
 	
660 660
 
661
-    /**
662
-     * This method is used to get the PDO DSN string using the configured driver
663
-     * @return string the DSN string
664
-     */
665
-    protected function getDsnFromDriver(){
666
-      $config = $this->getDatabaseConfiguration();
667
-      if (! empty($config)){
668
-        $driver = $config['driver'];
669
-        $driverDsnMap = array(
670
-                                'mysql' => 'mysql:host=' . $config['hostname'] . ';' 
671
-                                            . (($config['port']) != '' ? 'port=' . $config['port'] . ';' : '') 
672
-                                            . 'dbname=' . $config['database'],
673
-                                'pgsql' => 'pgsql:host=' . $config['hostname'] . ';' 
674
-                                            . (($config['port']) != '' ? 'port=' . $config['port'] . ';' : '')
675
-                                            . 'dbname=' . $config['database'],
676
-                                'sqlite' => 'sqlite:' . $config['database'],
677
-                                'oracle' => 'oci:dbname=' . $config['hostname'] 
678
-                                            . (($config['port']) != '' ? ':' . $config['port'] : '')
679
-                                            . '/' . $config['database']
680
-                              );
681
-        return isset($driverDsnMap[$driver]) ? $driverDsnMap[$driver] : '';
682
-      }                   
683
-      return null;
684
-    }
685
-
686
-     /**
687
-     * Transform the prepared query like (?, ?, ?) into string format
688
-     * @see Database::query
689
-     *
690
-     * @return string
691
-     */
692
-    protected function getPreparedQuery($query, $data){
693
-      if (is_array($data)){
661
+	/**
662
+	 * This method is used to get the PDO DSN string using the configured driver
663
+	 * @return string the DSN string
664
+	 */
665
+	protected function getDsnFromDriver(){
666
+	  $config = $this->getDatabaseConfiguration();
667
+	  if (! empty($config)){
668
+		$driver = $config['driver'];
669
+		$driverDsnMap = array(
670
+								'mysql' => 'mysql:host=' . $config['hostname'] . ';' 
671
+											. (($config['port']) != '' ? 'port=' . $config['port'] . ';' : '') 
672
+											. 'dbname=' . $config['database'],
673
+								'pgsql' => 'pgsql:host=' . $config['hostname'] . ';' 
674
+											. (($config['port']) != '' ? 'port=' . $config['port'] . ';' : '')
675
+											. 'dbname=' . $config['database'],
676
+								'sqlite' => 'sqlite:' . $config['database'],
677
+								'oracle' => 'oci:dbname=' . $config['hostname'] 
678
+											. (($config['port']) != '' ? ':' . $config['port'] : '')
679
+											. '/' . $config['database']
680
+							  );
681
+		return isset($driverDsnMap[$driver]) ? $driverDsnMap[$driver] : '';
682
+	  }                   
683
+	  return null;
684
+	}
685
+
686
+	 /**
687
+	  * Transform the prepared query like (?, ?, ?) into string format
688
+	  * @see Database::query
689
+	  *
690
+	  * @return string
691
+	  */
692
+	protected function getPreparedQuery($query, $data){
693
+	  if (is_array($data)){
694 694
   			$x = explode('?', $query);
695 695
   			$q = '';
696 696
   			foreach($x as $k => $v){
@@ -699,121 +699,121 @@  discard block
 block discarded – undo
699 699
   			  }
700 700
   			}
701 701
   			return $q;
702
-      }
703
-      return $query;
704
-    }
705
-
706
-    /**
707
-     * Get the cache content for this query
708
-     * @see Database::query
709
-     *      
710
-     * @return mixed
711
-     */
712
-    protected function getCacheContentForQuery($query, $all, $array){
713
-        $cacheKey = $this->getCacheBenchmarkKeyForQuery($query, $all, $array);
714
-        if (! is_object($this->getCacheInstance())){
715
-    			//can not call method with reference in argument
716
-    			//like $this->setCacheInstance(& get_instance()->cache);
717
-    			//use temporary variable
718
-    			$instance = & get_instance()->cache;
719
-    			$this->setCacheInstance($instance);
720
-        }
721
-        return $this->getCacheInstance()->get($cacheKey);
722
-    }
723
-
724
-    /**
725
-     * Save the result of query into cache
726
-     * @param string $query  the SQL query
727
-     * @param string $key    the cache key
728
-     * @param mixed $result the query result to save
729
-     * @param boolean $status whether can save the query result into cache
730
-     * @param int $expire the cache TTL
731
-     */
732
-     protected function setCacheContentForQuery($query, $key, $result, $status, $expire){
733
-        if ($status){
734
-            $this->logger->info('Save the result for query [' .$query. '] into cache for future use');
735
-            if (! is_object($this->getCacheInstance())){
736
-      				//can not call method with reference in argument
737
-      				//like $this->setCacheInstance(& get_instance()->cache);
738
-      				//use temporary variable
739
-      				$instance = & get_instance()->cache;
740
-      				$this->setCacheInstance($instance);
741
-      			}
742
-            $this->getCacheInstance()->set($key, $result, $expire);
743
-        }
744
-     }
702
+	  }
703
+	  return $query;
704
+	}
705
+
706
+	/**
707
+	 * Get the cache content for this query
708
+	 * @see Database::query
709
+	 *      
710
+	 * @return mixed
711
+	 */
712
+	protected function getCacheContentForQuery($query, $all, $array){
713
+		$cacheKey = $this->getCacheBenchmarkKeyForQuery($query, $all, $array);
714
+		if (! is_object($this->getCacheInstance())){
715
+				//can not call method with reference in argument
716
+				//like $this->setCacheInstance(& get_instance()->cache);
717
+				//use temporary variable
718
+				$instance = & get_instance()->cache;
719
+				$this->setCacheInstance($instance);
720
+		}
721
+		return $this->getCacheInstance()->get($cacheKey);
722
+	}
723
+
724
+	/**
725
+	 * Save the result of query into cache
726
+	 * @param string $query  the SQL query
727
+	 * @param string $key    the cache key
728
+	 * @param mixed $result the query result to save
729
+	 * @param boolean $status whether can save the query result into cache
730
+	 * @param int $expire the cache TTL
731
+	 */
732
+	 protected function setCacheContentForQuery($query, $key, $result, $status, $expire){
733
+		if ($status){
734
+			$this->logger->info('Save the result for query [' .$query. '] into cache for future use');
735
+			if (! is_object($this->getCacheInstance())){
736
+	  				//can not call method with reference in argument
737
+	  				//like $this->setCacheInstance(& get_instance()->cache);
738
+	  				//use temporary variable
739
+	  				$instance = & get_instance()->cache;
740
+	  				$this->setCacheInstance($instance);
741
+	  			}
742
+			$this->getCacheInstance()->set($key, $result, $expire);
743
+		}
744
+	 }
745 745
 
746 746
     
747
-    /**
748
-     * Set error for database query execution
749
-     */
750
-    protected function setQueryError(){
751
-      $error = $this->pdo->errorInfo();
752
-      $this->error = isset($error[2]) ? $error[2] : '';
753
-      $this->logger->error('The database query execution got error: ' . stringfy_vars($error));
754
-	    //show error message
755
-      $this->error();
756
-    }
747
+	/**
748
+	 * Set error for database query execution
749
+	 */
750
+	protected function setQueryError(){
751
+	  $error = $this->pdo->errorInfo();
752
+	  $this->error = isset($error[2]) ? $error[2] : '';
753
+	  $this->logger->error('The database query execution got error: ' . stringfy_vars($error));
754
+		//show error message
755
+	  $this->error();
756
+	}
757 757
 
758 758
 	  /**
759
-     * Return the cache key for the given query
760
-     * @see Database::query
761
-     * 
762
-     *  @return string
763
-     */
764
-    protected function getCacheBenchmarkKeyForQuery($query, $all, $array){
765
-      if (is_array($all)){
766
-        $all = 'array';
767
-      }
768
-      return md5($query . $all . $array);
769
-    }
759
+	   * Return the cache key for the given query
760
+	   * @see Database::query
761
+	   * 
762
+	   *  @return string
763
+	   */
764
+	protected function getCacheBenchmarkKeyForQuery($query, $all, $array){
765
+	  if (is_array($all)){
766
+		$all = 'array';
767
+	  }
768
+	  return md5($query . $all . $array);
769
+	}
770 770
     
771 771
 	   /**
772
-     * Set the Log instance using argument or create new instance
773
-     * @param object $logger the Log instance if not null
774
-     */
775
-    protected function setLoggerFromParamOrCreateNewInstance(Log $logger = null){
776
-      if ($logger !== null){
777
-        $this->setLogger($logger);
778
-      }
779
-      else{
780
-          $this->logger =& class_loader('Log', 'classes');
781
-          $this->logger->setLogger('Library::Database');
782
-      }
783
-    }
772
+	    * Set the Log instance using argument or create new instance
773
+	    * @param object $logger the Log instance if not null
774
+	    */
775
+	protected function setLoggerFromParamOrCreateNewInstance(Log $logger = null){
776
+	  if ($logger !== null){
777
+		$this->setLogger($logger);
778
+	  }
779
+	  else{
780
+		  $this->logger =& class_loader('Log', 'classes');
781
+		  $this->logger->setLogger('Library::Database');
782
+	  }
783
+	}
784 784
 	
785 785
    /**
786
-   * Set the DatabaseQueryBuilder instance using argument or create new instance
787
-   * @param object $queryBuilder the DatabaseQueryBuilder instance if not null
788
-   */
786
+    * Set the DatabaseQueryBuilder instance using argument or create new instance
787
+    * @param object $queryBuilder the DatabaseQueryBuilder instance if not null
788
+    */
789 789
 	protected function setQueryBuilderFromParamOrCreateNewInstance(DatabaseQueryBuilder $queryBuilder = null){
790 790
 	  if ($queryBuilder !== null){
791
-      $this->setQueryBuilder($queryBuilder);
791
+	  $this->setQueryBuilder($queryBuilder);
792 792
 	  }
793 793
 	  else{
794 794
 		  $this->queryBuilder =& class_loader('DatabaseQueryBuilder', 'classes');
795 795
 	  }
796 796
 	}
797 797
 
798
-    /**
799
-     * Reset the database class attributs to the initail values before each query.
800
-     */
801
-    private function reset(){
798
+	/**
799
+	 * Reset the database class attributs to the initail values before each query.
800
+	 */
801
+	private function reset(){
802 802
 	   //query builder reset
803
-      $this->getQueryBuilder()->reset();
804
-      $this->numRows  = 0;
805
-      $this->insertId = null;
806
-      $this->query    = null;
807
-      $this->error    = null;
808
-      $this->result   = array();
809
-      $this->data     = array();
810
-    }
811
-
812
-    /**
813
-     * The class destructor
814
-     */
815
-    public function __destruct(){
816
-      $this->pdo = null;
817
-    }
803
+	  $this->getQueryBuilder()->reset();
804
+	  $this->numRows  = 0;
805
+	  $this->insertId = null;
806
+	  $this->query    = null;
807
+	  $this->error    = null;
808
+	  $this->result   = array();
809
+	  $this->data     = array();
810
+	}
811
+
812
+	/**
813
+	 * The class destructor
814
+	 */
815
+	public function __destruct(){
816
+	  $this->pdo = null;
817
+	}
818 818
 
819 819
 }
Please login to merge, or discard this patch.
core/libraries/Upload.php 1 patch
Indentation   +795 added lines, -795 removed lines patch added patch discarded remove patch
@@ -1,801 +1,801 @@
 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
-            }
260
-            $this->logger->info('The upload file information are : ' .stringfy_vars($this->file_array));
261
-        }
262
-        /**
263
-        *    Set input.
264
-        *    If you have $_FILES["file"], you must use the key "file"
265
-        *    Example:
266
-        *        $object->setInput("file");
267
-        *
268
-        *    @since     1.0
269
-        *    @version   1.0
270
-        *    @param     string      $input
271
-        *    @return    object
272
-        *    @method    boolean     setInput
273
-        */
274
-        public function setInput($input)
275
-        {
276
-            if (!empty($input) && (is_string($input) || is_numeric($input) )) {
277
-                $this->input = $input;
278
-            }
279
-            return $this;
280
-        }
281
-        /**
282
-        *    Set new filename
283
-        *    Example:
284
-        *        FileUpload::setFilename("new file.txt")
285
-        *    Remember:
286
-        *        Use %s to retrive file extension
287
-        *
288
-        *    @since     1.0
289
-        *    @version   1.0
290
-        *    @param     string      $filename
291
-        *    @return    object
292
-        *    @method    boolean     setFilename
293
-        */
294
-        public function setFilename($filename)
295
-        {
296
-            if ($this->isFilename($filename)) {
297
-                $this->filename = $filename;
298
-            }
299
-            return $this;
300
-        }
301
-        /**
302
-        *    Set automatic filename
303
-        *
304
-        *    @since     1.0
305
-        *    @version   1.5
306
-        *    @param     string      $extension
307
-        *    @return    object
308
-        *    @method    boolean     setAutoFilename
309
-        */
310
-        public function setAutoFilename()
311
-        {
312
-            $this->filename = sha1(mt_rand(1, 9999).uniqid());
313
-            $this->filename .= time();
314
-            return $this;
315
-        }
316
-        /**
317
-        *    Set file size limit
318
-        *
319
-        *    @since     1.0
320
-        *    @version   1.0
321
-        *    @param     double     $file_size
322
-        *    @return    object
323
-        *    @method    boolean     setMaxFileSize
324
-        */
325
-        public function setMaxFileSize($file_size)
326
-        {
327
-            $file_size = $this->sizeInBytes($file_size);
328
-            if (is_numeric($file_size) && $file_size > -1) {
329
-                // Get php config
330
-                $php_size = $this->sizeInBytes((int) ini_get('upload_max_filesize'));
331
-                // Calculate difference
332
-                if ($php_size < $file_size) {
333
-                    $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. ']');
334
-                }
335
-                $this->max_file_size = $file_size;
336
-            }
337
-            return $this;
338
-        }
339
-        /**
340
-        *    Set array mime types
341
-        *
342
-        *    @since     1.0
343
-        *    @version   1.0
344
-        *    @param     array       $mimes
345
-        *    @return    object
346
-        *    @method    boolean     setAllowedMimeTypes
347
-        */
348
-        public function setAllowedMimeTypes(array $mimes)
349
-        {
350
-            if (count($mimes) > 0) {
351
-                array_map(array($this , 'setAllowMimeType'), $mimes);
352
-            }
353
-            return $this;
354
-        }
355
-        /**
356
-        *    Set input callback
357
-        *
358
-        *    @since     1.0
359
-        *    @version   1.0
360
-        *    @param     mixed       $callback
361
-        *    @return    object
362
-        *    @method    boolean     setCallbackInput
363
-        */
364
-        public function setCallbackInput($callback)
365
-        {
366
-            if (is_callable($callback, false)) {
367
-                $this->callbacks['input'] = $callback;
368
-            }
369
-            return $this;
370
-        }
371
-        /**
372
-        *    Set output callback
373
-        *
374
-        *    @since     1.0
375
-        *    @version   1.0
376
-        *    @param     mixed       $callback
377
-        *    @return    object
378
-        *    @method    boolean     setCallbackOutput
379
-        */
380
-        public function setCallbackOutput($callback)
381
-        {
382
-            if (is_callable($callback, false)) {
383
-                $this->callbacks['output'] = $callback;
384
-            }
385
-            return $this;
386
-        }
387
-        /**
388
-        *    Append a mime type to allowed mime types
389
-        *
390
-        *    @since     1.0
391
-        *    @version   1.0.1
392
-        *    @param     string      $mime
393
-        *    @return    object
394
-        *    @method    boolean     setAllowMimeType
395
-        */
396
-        public function setAllowMimeType($mime)
397
-        {
398
-            if (!empty($mime) && is_string($mime)) {
399
-                $this->allowed_mime_types[] = strtolower($mime);
400
-                $this->file['allowed_mime_types'][] = strtolower($mime);
401
-            } 
402
-            return $this;
403
-        }
404
-        /**
405
-        *    Set allowed mime types from mime helping
406
-        *
407
-        *    @since     1.0.1
408
-        *    @version   1.0.1
409
-        *    @return    object
410
-        *    @method    boolean    setMimeHelping
411
-        */
412
-        public function setMimeHelping($name)
413
-        {
414
-            if (!empty($name) && is_string($name)) {
415
-                if (array_key_exists($name, $this->mime_helping)) {
416
-                    return $this->setAllowedMimeTypes($this->mime_helping[ $name ]);
417
-                }
418
-            }
419
-            return $this;
420
-        }
421
-        /**
422
-        *    Set function to upload file
423
-        *    Examples:
424
-        *        1.- FileUpload::setUploadFunction("move_uploaded_file");
425
-        *        2.- FileUpload::setUploadFunction("copy");
426
-        *
427
-        *    @since     1.0
428
-        *    @version   1.0
429
-        *    @param     string      $function
430
-        *    @return    object
431
-        *    @method    boolean     setUploadFunction
432
-        */
433
-        public function setUploadFunction($function)
434
-        {
435
-            if (!empty($function) && (is_array($function) || is_string($function) )) {
436
-                if (is_callable( $function)) {
437
-                    $this->upload_function = $function;
438
-                }
439
-            }
440
-            return $this;
441
-        }
442
-        /**
443
-        *    Clear allowed mime types cache
444
-        *
445
-        *    @since     1.0
446
-        *    @version   1.0
447
-        *    @return    object
448
-        *    @method    boolean    clearAllowedMimeTypes
449
-        */
450
-        public function clearAllowedMimeTypes()
451
-        {
452
-            $this->allowed_mime_types = array();
453
-            $this->file['allowed_mime_types'] = array();
454
-            return $this;
455
-        }
456
-        /**
457
-        *    Set destination output
458
-        *
459
-        *    @since     1.0
460
-        *    @version   1.0
461
-        *    @param     string      $destination_directory      Destination path
462
-        *    @param     boolean     $create_if_not_exist
463
-        *    @return    object
464
-        *    @method    boolean     setDestinationDirectory
465
-        */
466
-        public function setDestinationDirectory($destination_directory, $create_if_not_exist = false) {
467
-            $destination_directory = realpath($destination_directory);
468
-            if (substr($destination_directory, -1) != DIRECTORY_SEPARATOR) {
469
-                $destination_directory .= DIRECTORY_SEPARATOR;
470
-            }
471
-
472
-            if ($this->isDirpath($destination_directory)) {
473
-                if ($this->dirExists($destination_directory)) {
474
-                    $this->destination_directory = $destination_directory;
475
-                    chdir($destination_directory);
476
-                } else if ($create_if_not_exist === true) {
477
-                    if (mkdir($destination_directory, 0775, true)) {
478
-                        $this->destination_directory = $destination_directory;
479
-                        chdir($destination_directory);
480
-                    }
481
-                    else{
482
-                        $this->logger->warning('Can not create the upload directory [' .$destination_directory. ']');
483
-                    }
484
-                }
485
-            }
486
-            return $this;
487
-        }
488
-        /**
489
-        *    Check file exists
490
-        *
491
-        *    @since      1.0
492
-        *    @version    1.0.1
493
-        *    @param      string     $file_destination
494
-        *    @return     boolean
495
-        *    @method     boolean    fileExists
496
-        */
497
-        public function fileExists($file_destination)
498
-        {
499
-            if ($this->isFilename($file_destination)) {
500
-                return (file_exists($file_destination) && is_file($file_destination));
501
-            }
502
-            return false;
503
-        }
504
-        /**
505
-        *    Check dir exists
506
-        *
507
-        *    @since        1.0
508
-        *    @version    1.0.1
509
-        *    @param      string     $path
510
-        *    @return     boolean
511
-        *    @method     boolean    dirExists
512
-        */
513
-        public function dirExists($path)
514
-        {
515
-            if ($this->isDirpath($path)) {
516
-                return (file_exists($path) && is_dir($path));
517
-            }
518
-            return false;
519
-        }
520
-        /**
521
-        *    Check valid filename
522
-        *
523
-        *    @since     1.0
524
-        *    @version   1.0.1
525
-        *    @param     string      $filename
526
-        *    @return    boolean
527
-        *    @method    boolean     isFilename
528
-        */
529
-        public function isFilename($filename)
530
-        {
531
-            $filename = basename($filename);
532
-            return (!empty($filename) && (is_string( $filename) || is_numeric($filename)));
533
-        }
534
-        /**
535
-        *    Validate mime type with allowed mime types,
536
-        *    but if allowed mime types is empty, this method return true
537
-        *
538
-        *    @since     1.0
539
-        *    @version   1.0
540
-        *    @param     string      $mime
541
-        *    @return    boolean
542
-        *    @method    boolean     checkMimeType
543
-        */
544
-        public function checkMimeType($mime)
545
-        {
546
-            if (count($this->allowed_mime_types) == 0) {
547
-                return true;
548
-            }
549
-            return in_array(strtolower($mime), $this->allowed_mime_types);
550
-        }
551
-        /**
552
-        *    Retrive status of upload
553
-        *
554
-        *    @since     1.0
555
-        *    @version   1.0
556
-        *    @return    boolean
557
-        *    @method    boolean    getStatus
558
-        */
559
-        public function getStatus()
560
-        {
561
-            return $this->file['status'];
562
-        }
563
-        /**
564
-        *    Check valid path
565
-        *
566
-        *    @since        1.0
567
-        *    @version    1.0.1
568
-        *    @param        string    $filename
569
-        *    @return     boolean
570
-        *    @method     boolean    isDirpath
571
-        */
572
-        public function isDirpath($path)
573
-        {
574
-            if (!empty( $path) && (is_string( $path) || is_numeric($path) )) {
575
-                if (DIRECTORY_SEPARATOR == '/') {
576
-                    return (preg_match( '/^[^*?"<>|:]*$/' , $path) == 1 );
577
-                } else {
578
-                    return (preg_match( "/^[^*?\"<>|:]*$/" , substr($path,2) ) == 1);
579
-                }
580
-            }
581
-            return false;
582
-        }
583
-        /**
584
-        *    Allow overwriting files
585
-        *
586
-        *    @since      1.0
587
-        *    @version    1.0
588
-        *    @return     object
589
-        *    @method     boolean    allowOverwriting
590
-        */
591
-        public function allowOverwriting()
592
-        {
593
-            $this->overwrite_file = true;
594
-            return $this;
595
-        }
596
-        /**
597
-        *    File info
598
-        *
599
-        *    @since      1.0
600
-        *    @version    1.0
601
-        *    @return     object
602
-        *    @method     object    getInfo
603
-        */
604
-        public function getInfo()
605
-        {
606
-            return (object)$this->file;
607
-        }
608
-
609
-
610
-        /**
611
-         * Check if the file is uploaded
612
-         * @return boolean
613
-         */
614
-        public function isUploaded(){
615
-            return isset($this->file_array[$this->input])
616
-            && is_uploaded_file($this->file_array[$this->input]['tmp_name']);
617
-        }
618
-
619
-        /**
620
-         * Check if file upload has error
621
-         * @return boolean
622
-         */
623
-        protected function uploadHasError(){
624
-            //check if file upload is  allowed in the configuration
625
-            if(! ini_get('file_uploads')){
626
-                $this->setError($this->error_messages['file_uploads']);
627
-                return true;
628
-            }
629
-
630
-             //check for php upload error
631
-            if(is_numeric($this->file['error']) && $this->file['error'] > 0){
632
-                $this->setError($this->getPhpUploadErrorMessageByCode($this->file['error']));
633
-                return true;
634
-            }
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
+			}
260
+			$this->logger->info('The upload file information are : ' .stringfy_vars($this->file_array));
261
+		}
262
+		/**
263
+		 *    Set input.
264
+		 *    If you have $_FILES["file"], you must use the key "file"
265
+		 *    Example:
266
+		 *        $object->setInput("file");
267
+		 *
268
+		 *    @since     1.0
269
+		 *    @version   1.0
270
+		 *    @param     string      $input
271
+		 *    @return    object
272
+		 *    @method    boolean     setInput
273
+		 */
274
+		public function setInput($input)
275
+		{
276
+			if (!empty($input) && (is_string($input) || is_numeric($input) )) {
277
+				$this->input = $input;
278
+			}
279
+			return $this;
280
+		}
281
+		/**
282
+		 *    Set new filename
283
+		 *    Example:
284
+		 *        FileUpload::setFilename("new file.txt")
285
+		 *    Remember:
286
+		 *        Use %s to retrive file extension
287
+		 *
288
+		 *    @since     1.0
289
+		 *    @version   1.0
290
+		 *    @param     string      $filename
291
+		 *    @return    object
292
+		 *    @method    boolean     setFilename
293
+		 */
294
+		public function setFilename($filename)
295
+		{
296
+			if ($this->isFilename($filename)) {
297
+				$this->filename = $filename;
298
+			}
299
+			return $this;
300
+		}
301
+		/**
302
+		 *    Set automatic filename
303
+		 *
304
+		 *    @since     1.0
305
+		 *    @version   1.5
306
+		 *    @param     string      $extension
307
+		 *    @return    object
308
+		 *    @method    boolean     setAutoFilename
309
+		 */
310
+		public function setAutoFilename()
311
+		{
312
+			$this->filename = sha1(mt_rand(1, 9999).uniqid());
313
+			$this->filename .= time();
314
+			return $this;
315
+		}
316
+		/**
317
+		 *    Set file size limit
318
+		 *
319
+		 *    @since     1.0
320
+		 *    @version   1.0
321
+		 *    @param     double     $file_size
322
+		 *    @return    object
323
+		 *    @method    boolean     setMaxFileSize
324
+		 */
325
+		public function setMaxFileSize($file_size)
326
+		{
327
+			$file_size = $this->sizeInBytes($file_size);
328
+			if (is_numeric($file_size) && $file_size > -1) {
329
+				// Get php config
330
+				$php_size = $this->sizeInBytes((int) ini_get('upload_max_filesize'));
331
+				// Calculate difference
332
+				if ($php_size < $file_size) {
333
+					$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. ']');
334
+				}
335
+				$this->max_file_size = $file_size;
336
+			}
337
+			return $this;
338
+		}
339
+		/**
340
+		 *    Set array mime types
341
+		 *
342
+		 *    @since     1.0
343
+		 *    @version   1.0
344
+		 *    @param     array       $mimes
345
+		 *    @return    object
346
+		 *    @method    boolean     setAllowedMimeTypes
347
+		 */
348
+		public function setAllowedMimeTypes(array $mimes)
349
+		{
350
+			if (count($mimes) > 0) {
351
+				array_map(array($this , 'setAllowMimeType'), $mimes);
352
+			}
353
+			return $this;
354
+		}
355
+		/**
356
+		 *    Set input callback
357
+		 *
358
+		 *    @since     1.0
359
+		 *    @version   1.0
360
+		 *    @param     mixed       $callback
361
+		 *    @return    object
362
+		 *    @method    boolean     setCallbackInput
363
+		 */
364
+		public function setCallbackInput($callback)
365
+		{
366
+			if (is_callable($callback, false)) {
367
+				$this->callbacks['input'] = $callback;
368
+			}
369
+			return $this;
370
+		}
371
+		/**
372
+		 *    Set output callback
373
+		 *
374
+		 *    @since     1.0
375
+		 *    @version   1.0
376
+		 *    @param     mixed       $callback
377
+		 *    @return    object
378
+		 *    @method    boolean     setCallbackOutput
379
+		 */
380
+		public function setCallbackOutput($callback)
381
+		{
382
+			if (is_callable($callback, false)) {
383
+				$this->callbacks['output'] = $callback;
384
+			}
385
+			return $this;
386
+		}
387
+		/**
388
+		 *    Append a mime type to allowed mime types
389
+		 *
390
+		 *    @since     1.0
391
+		 *    @version   1.0.1
392
+		 *    @param     string      $mime
393
+		 *    @return    object
394
+		 *    @method    boolean     setAllowMimeType
395
+		 */
396
+		public function setAllowMimeType($mime)
397
+		{
398
+			if (!empty($mime) && is_string($mime)) {
399
+				$this->allowed_mime_types[] = strtolower($mime);
400
+				$this->file['allowed_mime_types'][] = strtolower($mime);
401
+			} 
402
+			return $this;
403
+		}
404
+		/**
405
+		 *    Set allowed mime types from mime helping
406
+		 *
407
+		 *    @since     1.0.1
408
+		 *    @version   1.0.1
409
+		 *    @return    object
410
+		 *    @method    boolean    setMimeHelping
411
+		 */
412
+		public function setMimeHelping($name)
413
+		{
414
+			if (!empty($name) && is_string($name)) {
415
+				if (array_key_exists($name, $this->mime_helping)) {
416
+					return $this->setAllowedMimeTypes($this->mime_helping[ $name ]);
417
+				}
418
+			}
419
+			return $this;
420
+		}
421
+		/**
422
+		 *    Set function to upload file
423
+		 *    Examples:
424
+		 *        1.- FileUpload::setUploadFunction("move_uploaded_file");
425
+		 *        2.- FileUpload::setUploadFunction("copy");
426
+		 *
427
+		 *    @since     1.0
428
+		 *    @version   1.0
429
+		 *    @param     string      $function
430
+		 *    @return    object
431
+		 *    @method    boolean     setUploadFunction
432
+		 */
433
+		public function setUploadFunction($function)
434
+		{
435
+			if (!empty($function) && (is_array($function) || is_string($function) )) {
436
+				if (is_callable( $function)) {
437
+					$this->upload_function = $function;
438
+				}
439
+			}
440
+			return $this;
441
+		}
442
+		/**
443
+		 *    Clear allowed mime types cache
444
+		 *
445
+		 *    @since     1.0
446
+		 *    @version   1.0
447
+		 *    @return    object
448
+		 *    @method    boolean    clearAllowedMimeTypes
449
+		 */
450
+		public function clearAllowedMimeTypes()
451
+		{
452
+			$this->allowed_mime_types = array();
453
+			$this->file['allowed_mime_types'] = array();
454
+			return $this;
455
+		}
456
+		/**
457
+		 *    Set destination output
458
+		 *
459
+		 *    @since     1.0
460
+		 *    @version   1.0
461
+		 *    @param     string      $destination_directory      Destination path
462
+		 *    @param     boolean     $create_if_not_exist
463
+		 *    @return    object
464
+		 *    @method    boolean     setDestinationDirectory
465
+		 */
466
+		public function setDestinationDirectory($destination_directory, $create_if_not_exist = false) {
467
+			$destination_directory = realpath($destination_directory);
468
+			if (substr($destination_directory, -1) != DIRECTORY_SEPARATOR) {
469
+				$destination_directory .= DIRECTORY_SEPARATOR;
470
+			}
471
+
472
+			if ($this->isDirpath($destination_directory)) {
473
+				if ($this->dirExists($destination_directory)) {
474
+					$this->destination_directory = $destination_directory;
475
+					chdir($destination_directory);
476
+				} else if ($create_if_not_exist === true) {
477
+					if (mkdir($destination_directory, 0775, true)) {
478
+						$this->destination_directory = $destination_directory;
479
+						chdir($destination_directory);
480
+					}
481
+					else{
482
+						$this->logger->warning('Can not create the upload directory [' .$destination_directory. ']');
483
+					}
484
+				}
485
+			}
486
+			return $this;
487
+		}
488
+		/**
489
+		 *    Check file exists
490
+		 *
491
+		 *    @since      1.0
492
+		 *    @version    1.0.1
493
+		 *    @param      string     $file_destination
494
+		 *    @return     boolean
495
+		 *    @method     boolean    fileExists
496
+		 */
497
+		public function fileExists($file_destination)
498
+		{
499
+			if ($this->isFilename($file_destination)) {
500
+				return (file_exists($file_destination) && is_file($file_destination));
501
+			}
502
+			return false;
503
+		}
504
+		/**
505
+		 *    Check dir exists
506
+		 *
507
+		 *    @since        1.0
508
+		 *    @version    1.0.1
509
+		 *    @param      string     $path
510
+		 *    @return     boolean
511
+		 *    @method     boolean    dirExists
512
+		 */
513
+		public function dirExists($path)
514
+		{
515
+			if ($this->isDirpath($path)) {
516
+				return (file_exists($path) && is_dir($path));
517
+			}
518
+			return false;
519
+		}
520
+		/**
521
+		 *    Check valid filename
522
+		 *
523
+		 *    @since     1.0
524
+		 *    @version   1.0.1
525
+		 *    @param     string      $filename
526
+		 *    @return    boolean
527
+		 *    @method    boolean     isFilename
528
+		 */
529
+		public function isFilename($filename)
530
+		{
531
+			$filename = basename($filename);
532
+			return (!empty($filename) && (is_string( $filename) || is_numeric($filename)));
533
+		}
534
+		/**
535
+		 *    Validate mime type with allowed mime types,
536
+		 *    but if allowed mime types is empty, this method return true
537
+		 *
538
+		 *    @since     1.0
539
+		 *    @version   1.0
540
+		 *    @param     string      $mime
541
+		 *    @return    boolean
542
+		 *    @method    boolean     checkMimeType
543
+		 */
544
+		public function checkMimeType($mime)
545
+		{
546
+			if (count($this->allowed_mime_types) == 0) {
547
+				return true;
548
+			}
549
+			return in_array(strtolower($mime), $this->allowed_mime_types);
550
+		}
551
+		/**
552
+		 *    Retrive status of upload
553
+		 *
554
+		 *    @since     1.0
555
+		 *    @version   1.0
556
+		 *    @return    boolean
557
+		 *    @method    boolean    getStatus
558
+		 */
559
+		public function getStatus()
560
+		{
561
+			return $this->file['status'];
562
+		}
563
+		/**
564
+		 *    Check valid path
565
+		 *
566
+		 *    @since        1.0
567
+		 *    @version    1.0.1
568
+		 *    @param        string    $filename
569
+		 *    @return     boolean
570
+		 *    @method     boolean    isDirpath
571
+		 */
572
+		public function isDirpath($path)
573
+		{
574
+			if (!empty( $path) && (is_string( $path) || is_numeric($path) )) {
575
+				if (DIRECTORY_SEPARATOR == '/') {
576
+					return (preg_match( '/^[^*?"<>|:]*$/' , $path) == 1 );
577
+				} else {
578
+					return (preg_match( "/^[^*?\"<>|:]*$/" , substr($path,2) ) == 1);
579
+				}
580
+			}
581
+			return false;
582
+		}
583
+		/**
584
+		 *    Allow overwriting files
585
+		 *
586
+		 *    @since      1.0
587
+		 *    @version    1.0
588
+		 *    @return     object
589
+		 *    @method     boolean    allowOverwriting
590
+		 */
591
+		public function allowOverwriting()
592
+		{
593
+			$this->overwrite_file = true;
594
+			return $this;
595
+		}
596
+		/**
597
+		 *    File info
598
+		 *
599
+		 *    @since      1.0
600
+		 *    @version    1.0
601
+		 *    @return     object
602
+		 *    @method     object    getInfo
603
+		 */
604
+		public function getInfo()
605
+		{
606
+			return (object)$this->file;
607
+		}
608
+
609
+
610
+		/**
611
+		 * Check if the file is uploaded
612
+		 * @return boolean
613
+		 */
614
+		public function isUploaded(){
615
+			return isset($this->file_array[$this->input])
616
+			&& is_uploaded_file($this->file_array[$this->input]['tmp_name']);
617
+		}
618
+
619
+		/**
620
+		 * Check if file upload has error
621
+		 * @return boolean
622
+		 */
623
+		protected function uploadHasError(){
624
+			//check if file upload is  allowed in the configuration
625
+			if(! ini_get('file_uploads')){
626
+				$this->setError($this->error_messages['file_uploads']);
627
+				return true;
628
+			}
629
+
630
+			 //check for php upload error
631
+			if(is_numeric($this->file['error']) && $this->file['error'] > 0){
632
+				$this->setError($this->getPhpUploadErrorMessageByCode($this->file['error']));
633
+				return true;
634
+			}
635 635
             
636
-            //check for mime type
637
-            if (!$this->checkMimeType($this->file['mime'])) {
638
-                $this->setError($this->error_messages['accept_file_types']);
639
-                return true;
640
-            }
641
-
642
-             // Check file size
643
-            if ($this->max_file_size > 0) {
644
-                if ($this->max_file_size < $this->file['size']) {
645
-                    $this->setError(sprintf($this->error_messages['max_file_size'], $this->sizeFormat($this->max_file_size)));
646
-                    return true;
647
-                }
648
-            }
649
-
650
-            // Check if exists file
651
-            if ($this->fileExists($this->destination_directory . $this->filename) && $this->overwrite_file === false) {
652
-                $this->setError($this->error_messages['overwritten_not_allowed']);
653
-                return true;
654
-            }
655
-
656
-            return false;
657
-        }
658
-        /**
659
-        *    Upload file
660
-        *
661
-        *    @since     1.0
662
-        *    @version   1.0.1
663
-        *    @return    boolean
664
-        *    @method    boolean    save
665
-        */
666
-        public function save(){
667
-            if (count($this->file_array) > 0) {
668
-                if (array_key_exists($this->input, $this->file_array)) {
669
-                    // set original filename if not have a new name
670
-                    if (empty($this->filename)) {
671
-                        $this->filename = $this->file_array[$this->input]['name'];
672
-                    }
673
-                    else{
674
-                        // Replace %s for extension in filename
675
-                        // Before: /[\w\d]*(.[\d\w]+)$/i
676
-                        // After: /^[\s[:alnum:]\-\_\.]*\.([\d\w]+)$/iu
677
-                        // Support unicode(utf-8) characters
678
-                        // Example: "русские.jpeg" is valid; "Zhōngguó.jpeg" is valid; "Tønsberg.jpeg" is valid
679
-                        $extension = preg_replace(
680
-                            '/^[\p{L}\d\s\-\_\.\(\)]*\.([\d\w]+)$/iu',
681
-                            '$1',
682
-                            $this->file_array[$this->input]['name']
683
-                        );
684
-                        $this->filename = $this->filename . '.' . $extension;
685
-                    }
686
-
687
-                    // set file info
688
-                    $this->file['mime']         = $this->file_array[$this->input]['type'];
689
-                    $this->file['tmp']          = $this->file_array[$this->input]['tmp_name'];
690
-                    $this->file['original']     = $this->file_array[$this->input]['name'];
691
-                    $this->file['size']         = $this->file_array[$this->input]['size'];
692
-                    $this->file['sizeFormated'] = $this->sizeFormat($this->file['size']);
693
-                    $this->file['destination']  = $this->destination_directory . $this->filename;
694
-                    $this->file['filename']     = $this->filename;
695
-                    $this->file['error']        = $this->file_array[$this->input]['error'];
696
-
697
-                    $this->logger->info('The upload file information to process is : ' .stringfy_vars($this->file));
698
-
699
-                    $error = $this->uploadHasError();
700
-                    if($error){
701
-                        return false;
702
-                    }
703
-                    // Execute input callback
704
-                    if (!empty( $this->callbacks['input'])) {
705
-                        call_user_func($this->callbacks['input'], (object)$this->file);
706
-                    }
636
+			//check for mime type
637
+			if (!$this->checkMimeType($this->file['mime'])) {
638
+				$this->setError($this->error_messages['accept_file_types']);
639
+				return true;
640
+			}
641
+
642
+			 // Check file size
643
+			if ($this->max_file_size > 0) {
644
+				if ($this->max_file_size < $this->file['size']) {
645
+					$this->setError(sprintf($this->error_messages['max_file_size'], $this->sizeFormat($this->max_file_size)));
646
+					return true;
647
+				}
648
+			}
649
+
650
+			// Check if exists file
651
+			if ($this->fileExists($this->destination_directory . $this->filename) && $this->overwrite_file === false) {
652
+				$this->setError($this->error_messages['overwritten_not_allowed']);
653
+				return true;
654
+			}
655
+
656
+			return false;
657
+		}
658
+		/**
659
+		 *    Upload file
660
+		 *
661
+		 *    @since     1.0
662
+		 *    @version   1.0.1
663
+		 *    @return    boolean
664
+		 *    @method    boolean    save
665
+		 */
666
+		public function save(){
667
+			if (count($this->file_array) > 0) {
668
+				if (array_key_exists($this->input, $this->file_array)) {
669
+					// set original filename if not have a new name
670
+					if (empty($this->filename)) {
671
+						$this->filename = $this->file_array[$this->input]['name'];
672
+					}
673
+					else{
674
+						// Replace %s for extension in filename
675
+						// Before: /[\w\d]*(.[\d\w]+)$/i
676
+						// After: /^[\s[:alnum:]\-\_\.]*\.([\d\w]+)$/iu
677
+						// Support unicode(utf-8) characters
678
+						// Example: "русские.jpeg" is valid; "Zhōngguó.jpeg" is valid; "Tønsberg.jpeg" is valid
679
+						$extension = preg_replace(
680
+							'/^[\p{L}\d\s\-\_\.\(\)]*\.([\d\w]+)$/iu',
681
+							'$1',
682
+							$this->file_array[$this->input]['name']
683
+						);
684
+						$this->filename = $this->filename . '.' . $extension;
685
+					}
686
+
687
+					// set file info
688
+					$this->file['mime']         = $this->file_array[$this->input]['type'];
689
+					$this->file['tmp']          = $this->file_array[$this->input]['tmp_name'];
690
+					$this->file['original']     = $this->file_array[$this->input]['name'];
691
+					$this->file['size']         = $this->file_array[$this->input]['size'];
692
+					$this->file['sizeFormated'] = $this->sizeFormat($this->file['size']);
693
+					$this->file['destination']  = $this->destination_directory . $this->filename;
694
+					$this->file['filename']     = $this->filename;
695
+					$this->file['error']        = $this->file_array[$this->input]['error'];
696
+
697
+					$this->logger->info('The upload file information to process is : ' .stringfy_vars($this->file));
698
+
699
+					$error = $this->uploadHasError();
700
+					if($error){
701
+						return false;
702
+					}
703
+					// Execute input callback
704
+					if (!empty( $this->callbacks['input'])) {
705
+						call_user_func($this->callbacks['input'], (object)$this->file);
706
+					}
707 707
                    
708 708
 
709
-                    $this->file['status'] = call_user_func_array(
710
-                        $this->upload_function, array(
711
-                            $this->file_array[$this->input]['tmp_name'],
712
-                            $this->destination_directory . $this->filename
713
-                        )
714
-                    );
715
-
716
-                    // Execute output callback
717
-                    if (!empty( $this->callbacks['output'])) {
718
-                        call_user_func($this->callbacks['output'], (object)$this->file);
719
-                    }
720
-                    return $this->file['status'];
721
-                }
722
-            }
723
-        }
724
-
725
-        /**
726
-        *    File size for humans.
727
-        *
728
-        *    @since      1.0
729
-        *    @version    1.0
730
-        *    @param      integer    $bytes
731
-        *    @param      integer    $precision
732
-        *    @return     string
733
-        *    @method     string     sizeFormat
734
-        */
735
-        public function sizeFormat($size, $precision = 2)
736
-        {
737
-            if($size > 0){
738
-                $base       = log($size) / log(1024);
739
-                $suffixes   = array('B', 'K', 'M', 'G', 'T');
740
-                return round(pow(1024, $base - floor($base)), $precision) . ( isset($suffixes[floor($base)]) ? $suffixes[floor($base)] : '');
741
-            }
742
-            return null;
743
-        }
709
+					$this->file['status'] = call_user_func_array(
710
+						$this->upload_function, array(
711
+							$this->file_array[$this->input]['tmp_name'],
712
+							$this->destination_directory . $this->filename
713
+						)
714
+					);
715
+
716
+					// Execute output callback
717
+					if (!empty( $this->callbacks['output'])) {
718
+						call_user_func($this->callbacks['output'], (object)$this->file);
719
+					}
720
+					return $this->file['status'];
721
+				}
722
+			}
723
+		}
724
+
725
+		/**
726
+		 *    File size for humans.
727
+		 *
728
+		 *    @since      1.0
729
+		 *    @version    1.0
730
+		 *    @param      integer    $bytes
731
+		 *    @param      integer    $precision
732
+		 *    @return     string
733
+		 *    @method     string     sizeFormat
734
+		 */
735
+		public function sizeFormat($size, $precision = 2)
736
+		{
737
+			if($size > 0){
738
+				$base       = log($size) / log(1024);
739
+				$suffixes   = array('B', 'K', 'M', 'G', 'T');
740
+				return round(pow(1024, $base - floor($base)), $precision) . ( isset($suffixes[floor($base)]) ? $suffixes[floor($base)] : '');
741
+			}
742
+			return null;
743
+		}
744 744
 
745 745
         
746
-        /**
747
-        *    Convert human file size to bytes
748
-        *
749
-        *    @since      1.0
750
-        *    @version    1.0.1
751
-        *    @param      integer|double    $size
752
-        *    @return     integer|double
753
-        *    @method     string     sizeInBytes
754
-        */
755
-        public function sizeInBytes($size)
756
-        {
757
-            $unit = 'B';
758
-            $units = array('B' => 0, 'K' => 1, 'M' => 2, 'G' => 3, 'T' => 4);
759
-            $matches = array();
760
-            preg_match('/(?<size>[\d\.]+)\s*(?<unit>b|k|m|g|t)?/i', $size, $matches);
761
-            if (array_key_exists('unit', $matches)) {
762
-                $unit = strtoupper($matches['unit']);
763
-            }
764
-            return (floatval($matches['size']) * pow(1024, $units[$unit]) ) ;
765
-        }
766
-
767
-        /**
768
-         * Get the upload error message
769
-         * @return string
770
-         */
771
-        public function getError(){
772
-            return $this->error;
773
-        }
774
-
775
-        /**
776
-         * Set the upload error message
777
-         * @param string $message the upload error message to set
778
-         */
779
-        public function setError($message){
780
-            $this->logger->info('The file upload got error : ' . $message);
781
-            $this->error = $message;
782
-        }
783
-
784
-        /**
785
-         * Get the PHP upload error message for the given code
786
-         * @param  int $code the error code
787
-         * @return string the error message
788
-         */
789
-        private function getPhpUploadErrorMessageByCode($code){
790
-            $codeMessageMaps = array(
791
-                1 => $this->error_messages['upload_err_ini_size'],
792
-                2 => $this->error_messages['upload_err_form_size'],
793
-                3 => $this->error_messages['upload_err_partial'],
794
-                4 => $this->error_messages['upload_err_no_file'],
795
-                6 => $this->error_messages['upload_err_no_tmp_dir'],
796
-                7 => $this->error_messages['upload_err_cant_write'],
797
-                8 => $this->error_messages['upload_err_extension'],
798
-            );
799
-            return isset($codeMessageMaps[$code]) ? $codeMessageMaps[$code] : null;
800
-        }
801
-    }
746
+		/**
747
+		 *    Convert human file size to bytes
748
+		 *
749
+		 *    @since      1.0
750
+		 *    @version    1.0.1
751
+		 *    @param      integer|double    $size
752
+		 *    @return     integer|double
753
+		 *    @method     string     sizeInBytes
754
+		 */
755
+		public function sizeInBytes($size)
756
+		{
757
+			$unit = 'B';
758
+			$units = array('B' => 0, 'K' => 1, 'M' => 2, 'G' => 3, 'T' => 4);
759
+			$matches = array();
760
+			preg_match('/(?<size>[\d\.]+)\s*(?<unit>b|k|m|g|t)?/i', $size, $matches);
761
+			if (array_key_exists('unit', $matches)) {
762
+				$unit = strtoupper($matches['unit']);
763
+			}
764
+			return (floatval($matches['size']) * pow(1024, $units[$unit]) ) ;
765
+		}
766
+
767
+		/**
768
+		 * Get the upload error message
769
+		 * @return string
770
+		 */
771
+		public function getError(){
772
+			return $this->error;
773
+		}
774
+
775
+		/**
776
+		 * Set the upload error message
777
+		 * @param string $message the upload error message to set
778
+		 */
779
+		public function setError($message){
780
+			$this->logger->info('The file upload got error : ' . $message);
781
+			$this->error = $message;
782
+		}
783
+
784
+		/**
785
+		 * Get the PHP upload error message for the given code
786
+		 * @param  int $code the error code
787
+		 * @return string the error message
788
+		 */
789
+		private function getPhpUploadErrorMessageByCode($code){
790
+			$codeMessageMaps = array(
791
+				1 => $this->error_messages['upload_err_ini_size'],
792
+				2 => $this->error_messages['upload_err_form_size'],
793
+				3 => $this->error_messages['upload_err_partial'],
794
+				4 => $this->error_messages['upload_err_no_file'],
795
+				6 => $this->error_messages['upload_err_no_tmp_dir'],
796
+				7 => $this->error_messages['upload_err_cant_write'],
797
+				8 => $this->error_messages['upload_err_extension'],
798
+			);
799
+			return isset($codeMessageMaps[$code]) ? $codeMessageMaps[$code] : null;
800
+		}
801
+	}
Please login to merge, or discard this patch.