Passed
Branch 1.0.0-dev (958860)
by nguereza
06:24
created
core/classes/Loader.php 1 patch
Spacing   +107 added lines, -107 removed lines patch added patch discarded remove patch
@@ -23,7 +23,7 @@  discard block
 block discarded – undo
23 23
 	 * along with this program; if not, write to the Free Software
24 24
 	 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
25 25
 	*/
26
-	class Loader{
26
+	class Loader {
27 27
 		
28 28
 		/**
29 29
 		 * List of loaded resources
@@ -38,7 +38,7 @@  discard block
 block discarded – undo
38 38
 		private static $logger;
39 39
 
40 40
 
41
-		public function __construct(){
41
+		public function __construct() {
42 42
 			//add the resources already loaded during application bootstrap
43 43
 			//in the list to prevent duplicate or loading the resources again.
44 44
 			static::$loaded = class_loaded();
@@ -51,9 +51,9 @@  discard block
 block discarded – undo
51 51
 		 * Get the logger singleton instance
52 52
 		 * @return Log the logger instance
53 53
 		 */
54
-		private static function getLogger(){
55
-			if(self::$logger == null){
56
-				self::$logger[0] =& class_loader('Log', 'classes');
54
+		private static function getLogger() {
55
+			if (self::$logger == null) {
56
+				self::$logger[0] = & class_loader('Log', 'classes');
57 57
 				self::$logger[0]->setLogger('Library::Loader');
58 58
 			}
59 59
 			return self::$logger[0];
@@ -67,25 +67,25 @@  discard block
 block discarded – undo
67 67
 		 *
68 68
 		 * @return void
69 69
 		 */
70
-		public static function model($class, $instance = null){
70
+		public static function model($class, $instance = null) {
71 71
 			$logger = static::getLogger();
72 72
 			$class = str_ireplace('.php', '', $class);
73 73
 			$class = trim($class, '/\\');
74
-			$file = ucfirst($class).'.php';
74
+			$file = ucfirst($class) . '.php';
75 75
 			$logger->debug('Loading model [' . $class . '] ...');
76
-			if(! $instance){
76
+			if (!$instance) {
77 77
 				//for module
78
-				if(strpos($class, '/') !== false){
78
+				if (strpos($class, '/') !== false) {
79 79
 					$path = explode('/', $class);
80
-					if(isset($path[1])){
80
+					if (isset($path[1])) {
81 81
 						$instance = strtolower($path[1]);
82 82
 					}
83 83
 				}
84
-				else{
84
+				else {
85 85
 					$instance = strtolower($class);
86 86
 				}
87 87
 			}
88
-			if(isset(static::$loaded[$instance])){
88
+			if (isset(static::$loaded[$instance])) {
89 89
 				$logger->info('Model [' . $class . '] already loaded no need to load it again, cost in performance');
90 90
 				return;
91 91
 			}
@@ -95,43 +95,43 @@  discard block
 block discarded – undo
95 95
 			$searchModuleName = null;
96 96
 			$obj = & get_instance();
97 97
 			//check if the request class contains module name
98
-			if(strpos($class, '/') !== false){
98
+			if (strpos($class, '/') !== false) {
99 99
 				$path = explode('/', $class);
100
-				if(isset($path[0]) && in_array($path[0], Module::getModuleList())){
100
+				if (isset($path[0]) && in_array($path[0], Module::getModuleList())) {
101 101
 					$searchModuleName = $path[0];
102 102
 					$class = ucfirst($path[1]);
103 103
 				}
104 104
 			}
105
-			else{
105
+			else {
106 106
 				$class = ucfirst($class);
107 107
 			}
108 108
 
109
-			if(! $searchModuleName && !empty($obj->moduleName)){
109
+			if (!$searchModuleName && !empty($obj->moduleName)) {
110 110
 				$searchModuleName = $obj->moduleName;
111 111
 			}
112 112
 			$moduleModelFilePath = Module::findModelFullPath($class, $searchModuleName);
113
-			if($moduleModelFilePath){
114
-				$logger->info('Found model [' . $class . '] from module [' .$searchModuleName. '], the file path is [' .$moduleModelFilePath. '] we will used it');
113
+			if ($moduleModelFilePath) {
114
+				$logger->info('Found model [' . $class . '] from module [' . $searchModuleName . '], the file path is [' . $moduleModelFilePath . '] we will used it');
115 115
 				$classFilePath = $moduleModelFilePath;
116 116
 			}
117
-			else{
117
+			else {
118 118
 				$logger->info('Cannot find model [' . $class . '] from modules using the default location');
119 119
 			}
120 120
 			$logger->info('The model file path to be loaded is [' . $classFilePath . ']');
121
-			if(file_exists($classFilePath)){
121
+			if (file_exists($classFilePath)) {
122 122
 				require_once $classFilePath;
123
-				if(class_exists($class)){
123
+				if (class_exists($class)) {
124 124
 					$c = new $class();
125 125
 					$obj = & get_instance();
126 126
 					$obj->{$instance} = $c;
127 127
 					static::$loaded[$instance] = $class;
128 128
 					$logger->info('Model [' . $class . '] --> ' . $classFilePath . ' loaded successfully.');
129 129
 				}
130
-				else{
131
-					show_error('The file '.$classFilePath.' exists but does not contain the class ['. $class . ']');
130
+				else {
131
+					show_error('The file ' . $classFilePath . ' exists but does not contain the class [' . $class . ']');
132 132
 				}
133 133
 			}
134
-			else{
134
+			else {
135 135
 				show_error('Unable to find the model [' . $class . ']');
136 136
 			}
137 137
 		}
@@ -146,31 +146,31 @@  discard block
 block discarded – undo
146 146
 		 *
147 147
 		 * @return void
148 148
 		 */
149
-		public static function library($class, $instance = null, array $params = array()){
149
+		public static function library($class, $instance = null, array $params = array()) {
150 150
 			$logger = static::getLogger();
151 151
 			$class = str_ireplace('.php', '', $class);
152 152
 			$class = trim($class, '/\\');
153
-			$file = ucfirst($class) .'.php';
153
+			$file = ucfirst($class) . '.php';
154 154
 			$logger->debug('Loading library [' . $class . '] ...');
155
-			if(! $instance){
155
+			if (!$instance) {
156 156
 				//for module
157
-				if(strpos($class, '/') !== false){
157
+				if (strpos($class, '/') !== false) {
158 158
 					$path = explode('/', $class);
159
-					if(isset($path[1])){
159
+					if (isset($path[1])) {
160 160
 						$instance = strtolower($path[1]);
161 161
 					}
162 162
 				}
163
-				else{
163
+				else {
164 164
 					$instance = strtolower($class);
165 165
 				}
166 166
 			}
167
-			if(isset(static::$loaded[$instance])){
167
+			if (isset(static::$loaded[$instance])) {
168 168
 				$logger->info('Library [' . $class . '] already loaded no need to load it again, cost in performance');
169 169
 				return;
170 170
 			}
171 171
 			$obj = & get_instance();
172 172
 			//TODO for Database library
173
-			if(strtolower($class) == 'database'){
173
+			if (strtolower($class) == 'database') {
174 174
 				$logger->info('This is the Database library ...');
175 175
 				$dbInstance = & class_loader('Database', 'classes', $params);
176 176
 				$obj->{$instance} = $dbInstance;
@@ -180,44 +180,44 @@  discard block
 block discarded – undo
180 180
 			}
181 181
 			$libraryFilePath = null;
182 182
 			$logger->debug('Check if this is a system library ...');
183
-			if(file_exists(CORE_LIBRARY_PATH . $file)){
183
+			if (file_exists(CORE_LIBRARY_PATH . $file)) {
184 184
 				$libraryFilePath = CORE_LIBRARY_PATH . $file;
185 185
 				$class = ucfirst($class);
186 186
 				$logger->info('This library is a system library');
187 187
 			}
188
-			else{
188
+			else {
189 189
 				$logger->info('This library is not a system library');	
190 190
 				//first check if this library is in the module
191 191
 				$logger->debug('Checking library [' . $class . '] from module list ...');
192 192
 				$searchModuleName = null;
193 193
 				//check if the request class contains module name
194
-				if(strpos($class, '/') !== false){
194
+				if (strpos($class, '/') !== false) {
195 195
 					$path = explode('/', $class);
196
-					if(isset($path[0]) && in_array($path[0], Module::getModuleList())){
196
+					if (isset($path[0]) && in_array($path[0], Module::getModuleList())) {
197 197
 						$searchModuleName = $path[0];
198 198
 						$class = ucfirst($path[1]);
199 199
 					}
200 200
 				}
201
-				else{
201
+				else {
202 202
 					$class = ucfirst($class);
203 203
 				}
204
-				if(! $searchModuleName && !empty($obj->moduleName)){
204
+				if (!$searchModuleName && !empty($obj->moduleName)) {
205 205
 					$searchModuleName = $obj->moduleName;
206 206
 				}
207 207
 				$moduleLibraryPath = Module::findLibraryFullPath($class, $searchModuleName);
208
-				if($moduleLibraryPath){
209
-					$logger->info('Found library [' . $class . '] from module [' .$searchModuleName. '], the file path is [' .$moduleLibraryPath. '] we will used it');
208
+				if ($moduleLibraryPath) {
209
+					$logger->info('Found library [' . $class . '] from module [' . $searchModuleName . '], the file path is [' . $moduleLibraryPath . '] we will used it');
210 210
 					$libraryFilePath = $moduleLibraryPath;
211 211
 				}
212
-				else{
212
+				else {
213 213
 					$logger->info('Cannot find library [' . $class . '] from modules using the default location');
214 214
 				}
215 215
 			}
216
-			if(! $libraryFilePath){
216
+			if (!$libraryFilePath) {
217 217
 				$searchDir = array(LIBRARY_PATH);
218
-				foreach($searchDir as $dir){
218
+				foreach ($searchDir as $dir) {
219 219
 					$filePath = $dir . $file;
220
-					if(file_exists($filePath)){
220
+					if (file_exists($filePath)) {
221 221
 						$libraryFilePath = $filePath;
222 222
 						//is already found not to continue
223 223
 						break;
@@ -225,20 +225,20 @@  discard block
 block discarded – undo
225 225
 				}
226 226
 			}
227 227
 			$logger->info('The library file path to be loaded is [' . $libraryFilePath . ']');
228
-			if($libraryFilePath){
228
+			if ($libraryFilePath) {
229 229
 				require_once $libraryFilePath;
230
-				if(class_exists($class)){
230
+				if (class_exists($class)) {
231 231
 					$c = $params ? new $class($params) : new $class();
232 232
 					$obj = & get_instance();
233 233
 					$obj->{$instance} = $c;
234 234
 					static::$loaded[$instance] = $class;
235 235
 					$logger->info('Library [' . $class . '] --> ' . $libraryFilePath . ' loaded successfully.');
236 236
 				}
237
-				else{
238
-					show_error('The file '.$libraryFilePath.' exists but does not contain the class '.$class);
237
+				else {
238
+					show_error('The file ' . $libraryFilePath . ' exists but does not contain the class ' . $class);
239 239
 				}
240 240
 			}
241
-			else{
241
+			else {
242 242
 				show_error('Unable to find library class [' . $class . ']');
243 243
 			}
244 244
 		}
@@ -250,14 +250,14 @@  discard block
 block discarded – undo
250 250
 		 *
251 251
 		 * @return void
252 252
 		 */
253
-		public static function functions($function){
253
+		public static function functions($function) {
254 254
 			$logger = static::getLogger();
255 255
 			$function = str_ireplace('.php', '', $function);
256 256
 			$function = trim($function, '/\\');
257 257
 			$function = str_ireplace('function_', '', $function);
258
-			$file = 'function_'.$function.'.php';
258
+			$file = 'function_' . $function . '.php';
259 259
 			$logger->debug('Loading helper [' . $function . '] ...');
260
-			if(isset(static::$loaded['function_' . $function])){
260
+			if (isset(static::$loaded['function_' . $function])) {
261 261
 				$logger->info('Helper [' . $function . '] already loaded no need to load it again, cost in performance');
262 262
 				return;
263 263
 			}
@@ -267,30 +267,30 @@  discard block
 block discarded – undo
267 267
 			$searchModuleName = null;
268 268
 			$obj = & get_instance();
269 269
 			//check if the request class contains module name
270
-			if(strpos($function, '/') !== false){
270
+			if (strpos($function, '/') !== false) {
271 271
 				$path = explode('/', $function);
272
-				if(isset($path[0]) && in_array($path[0], Module::getModuleList())){
272
+				if (isset($path[0]) && in_array($path[0], Module::getModuleList())) {
273 273
 					$searchModuleName = $path[0];
274 274
 					$function = 'function_' . $path[1] . '.php';
275
-					$file = $path[0] . DS . 'function_'.$function.'.php';
275
+					$file = $path[0] . DS . 'function_' . $function . '.php';
276 276
 				}
277 277
 			}
278
-			if(! $searchModuleName && !empty($obj->moduleName)){
278
+			if (!$searchModuleName && !empty($obj->moduleName)) {
279 279
 				$searchModuleName = $obj->moduleName;
280 280
 			}
281 281
 			$moduleFunctionPath = Module::findFunctionFullPath($function, $searchModuleName);
282
-			if($moduleFunctionPath){
283
-				$logger->info('Found helper [' . $function . '] from module [' .$searchModuleName. '], the file path is [' .$moduleFunctionPath. '] we will used it');
282
+			if ($moduleFunctionPath) {
283
+				$logger->info('Found helper [' . $function . '] from module [' . $searchModuleName . '], the file path is [' . $moduleFunctionPath . '] we will used it');
284 284
 				$functionFilePath = $moduleFunctionPath;
285 285
 			}
286
-			else{
286
+			else {
287 287
 				$logger->info('Cannot find helper [' . $function . '] from modules using the default location');
288 288
 			}
289
-			if(! $functionFilePath){
289
+			if (!$functionFilePath) {
290 290
 				$searchDir = array(FUNCTIONS_PATH, CORE_FUNCTIONS_PATH);
291
-				foreach($searchDir as $dir){
291
+				foreach ($searchDir as $dir) {
292 292
 					$filePath = $dir . $file;
293
-					if(file_exists($filePath)){
293
+					if (file_exists($filePath)) {
294 294
 						$functionFilePath = $filePath;
295 295
 						//is already found not to continue
296 296
 						break;
@@ -298,12 +298,12 @@  discard block
 block discarded – undo
298 298
 				}
299 299
 			}
300 300
 			$logger->info('The helper file path to be loaded is [' . $functionFilePath . ']');
301
-			if($functionFilePath){
301
+			if ($functionFilePath) {
302 302
 				require_once $functionFilePath;
303 303
 				static::$loaded['function_' . $function] = $functionFilePath;
304 304
 				$logger->info('Helper [' . $function . '] --> ' . $functionFilePath . ' loaded successfully.');
305 305
 			}
306
-			else{
306
+			else {
307 307
 				show_error('Unable to find helper file [' . $file . ']');
308 308
 			}
309 309
 		}
@@ -315,14 +315,14 @@  discard block
 block discarded – undo
315 315
 		 *
316 316
 		 * @return void
317 317
 		 */
318
-		public static function config($filename){
318
+		public static function config($filename) {
319 319
 			$logger = static::getLogger();
320 320
 			$filename = str_ireplace('.php', '', $filename);
321 321
 			$filename = trim($filename, '/\\');
322 322
 			$filename = str_ireplace('config_', '', $filename);
323
-			$file = 'config_'.$filename.'.php';
323
+			$file = 'config_' . $filename . '.php';
324 324
 			$logger->debug('Loading configuration [' . $filename . '] ...');
325
-			if(isset(static::$loaded['config_' . $filename])){
325
+			if (isset(static::$loaded['config_' . $filename])) {
326 326
 				$logger->info('Configuration [' . $file . '] already loaded no need to load it again, cost in performance');
327 327
 				return;
328 328
 			}
@@ -332,34 +332,34 @@  discard block
 block discarded – undo
332 332
 			$searchModuleName = null;
333 333
 			$obj = & get_instance();
334 334
 			//check if the request class contains module name
335
-			if(strpos($filename, '/') !== false){
335
+			if (strpos($filename, '/') !== false) {
336 336
 				$path = explode('/', $filename);
337
-				if(isset($path[0]) && in_array($path[0], Module::getModuleList())){
337
+				if (isset($path[0]) && in_array($path[0], Module::getModuleList())) {
338 338
 					$searchModuleName = $path[0];
339 339
 					$filename = $path[1] . '.php';
340 340
 				}
341 341
 			}
342
-			if(! $searchModuleName && !empty($obj->moduleName)){
342
+			if (!$searchModuleName && !empty($obj->moduleName)) {
343 343
 				$searchModuleName = $obj->moduleName;
344 344
 			}
345 345
 			$moduleConfigPath = Module::findConfigFullPath($filename, $searchModuleName);
346
-			if($moduleConfigPath){
347
-				$logger->info('Found config [' . $filename . '] from module [' .$searchModuleName. '], the file path is [' .$moduleConfigPath. '] we will used it');
346
+			if ($moduleConfigPath) {
347
+				$logger->info('Found config [' . $filename . '] from module [' . $searchModuleName . '], the file path is [' . $moduleConfigPath . '] we will used it');
348 348
 				$configFilePath = $moduleConfigPath;
349 349
 			}
350
-			else{
350
+			else {
351 351
 				$logger->info('Cannot find config [' . $filename . '] from modules using the default location');
352 352
 			}
353 353
 			$logger->info('The config file path to be loaded is [' . $configFilePath . ']');
354
-			if(file_exists($configFilePath)){
354
+			if (file_exists($configFilePath)) {
355 355
 				$config = array();
356 356
 				require_once $configFilePath;
357
-				if(! empty($config) && is_array($config)){
357
+				if (!empty($config) && is_array($config)) {
358 358
 					Config::setAll($config);
359 359
 				}
360 360
 			}
361
-			else{
362
-				show_error('Unable to find config file ['. $configFilePath . ']');
361
+			else {
362
+				show_error('Unable to find config file [' . $configFilePath . ']');
363 363
 			}
364 364
 			static::$loaded['config_' . $filename] = $configFilePath;
365 365
 			$logger->info('Configuration [' . $configFilePath . '] loaded successfully.');
@@ -375,14 +375,14 @@  discard block
 block discarded – undo
375 375
 		 *
376 376
 		 * @return void
377 377
 		 */
378
-		public static function lang($language){
378
+		public static function lang($language) {
379 379
 			$logger = static::getLogger();
380 380
 			$language = str_ireplace('.php', '', $language);
381 381
 			$language = trim($language, '/\\');
382 382
 			$language = str_ireplace('lang_', '', $language);
383
-			$file = 'lang_'.$language.'.php';
383
+			$file = 'lang_' . $language . '.php';
384 384
 			$logger->debug('Loading language [' . $language . '] ...');
385
-			if(isset(static::$loaded['lang_' . $language])){
385
+			if (isset(static::$loaded['lang_' . $language])) {
386 386
 				$logger->info('Language [' . $language . '] already loaded no need to load it again, cost in performance');
387 387
 				return;
388 388
 			}
@@ -392,7 +392,7 @@  discard block
 block discarded – undo
392 392
 			$cfgKey = get_config('language_cookie_name');
393 393
 			$objCookie = & class_loader('Cookie');
394 394
 			$cookieLang = $objCookie->get($cfgKey);
395
-			if($cookieLang){
395
+			if ($cookieLang) {
396 396
 				$appLang = $cookieLang;
397 397
 			}
398 398
 			$languageFilePath = null;
@@ -401,30 +401,30 @@  discard block
 block discarded – undo
401 401
 			$searchModuleName = null;
402 402
 			$obj = & get_instance();
403 403
 			//check if the request class contains module name
404
-			if(strpos($language, '/') !== false){
404
+			if (strpos($language, '/') !== false) {
405 405
 				$path = explode('/', $language);
406
-				if(isset($path[0]) && in_array($path[0], Module::getModuleList())){
406
+				if (isset($path[0]) && in_array($path[0], Module::getModuleList())) {
407 407
 					$searchModuleName = $path[0];
408 408
 					$language = 'lang_' . $path[1] . '.php';
409
-					$file = $path[0] . DS .$language;
409
+					$file = $path[0] . DS . $language;
410 410
 				}
411 411
 			}
412
-			if(! $searchModuleName && !empty($obj->moduleName)){
412
+			if (!$searchModuleName && !empty($obj->moduleName)) {
413 413
 				$searchModuleName = $obj->moduleName;
414 414
 			}
415 415
 			$moduleLanguagePath = Module::findLanguageFullPath($language, $searchModuleName, $appLang);
416
-			if($moduleLanguagePath){
417
-				$logger->info('Found language [' . $language . '] from module [' .$searchModuleName. '], the file path is [' .$moduleLanguagePath. '] we will used it');
416
+			if ($moduleLanguagePath) {
417
+				$logger->info('Found language [' . $language . '] from module [' . $searchModuleName . '], the file path is [' . $moduleLanguagePath . '] we will used it');
418 418
 				$languageFilePath = $moduleLanguagePath;
419 419
 			}
420
-			else{
420
+			else {
421 421
 				$logger->info('Cannot find language [' . $language . '] from modules using the default location');
422 422
 			}
423
-			if(! $languageFilePath){
423
+			if (!$languageFilePath) {
424 424
 				$searchDir = array(APP_LANG_PATH, CORE_LANG_PATH);
425
-				foreach($searchDir as $dir){
425
+				foreach ($searchDir as $dir) {
426 426
 					$filePath = $dir . $appLang . DS . $file;
427
-					if(file_exists($filePath)){
427
+					if (file_exists($filePath)) {
428 428
 						$languageFilePath = $filePath;
429 429
 						//is already found not to continue
430 430
 						break;
@@ -432,13 +432,13 @@  discard block
 block discarded – undo
432 432
 				}
433 433
 			}
434 434
 			$logger->info('The language file path to be loaded is [' . $languageFilePath . ']');
435
-			if($languageFilePath){
435
+			if ($languageFilePath) {
436 436
 				$lang = array();
437 437
 				require_once $languageFilePath;
438
-				if(! empty($lang) && is_array($lang)){
439
-					$logger->info('Language file  [' .$languageFilePath. '] contains the valid languages keys add them to language list');
438
+				if (!empty($lang) && is_array($lang)) {
439
+					$logger->info('Language file  [' . $languageFilePath . '] contains the valid languages keys add them to language list');
440 440
 					//Note: may be here the class 'Lang' not yet loaded
441
-					$langObj =& class_loader('Lang', 'classes');
441
+					$langObj = & class_loader('Lang', 'classes');
442 442
 					$langObj->addLangMessages($lang);
443 443
 					//free the memory
444 444
 					unset($lang);
@@ -446,13 +446,13 @@  discard block
 block discarded – undo
446 446
 				static::$loaded['lang_' . $language] = $languageFilePath;
447 447
 				$logger->info('Language [' . $language . '] --> ' . $languageFilePath . ' loaded successfully.');
448 448
 			}
449
-			else{
449
+			else {
450 450
 				show_error('Unable to find language file [' . $file . ']');
451 451
 			}
452 452
 		}
453 453
 
454 454
 
455
-		private function getResourcesFromAutoloadConfig(){
455
+		private function getResourcesFromAutoloadConfig() {
456 456
 			$autoloads = array();
457 457
 			$autoloads['config']    = array();
458 458
 			$autoloads['languages'] = array();
@@ -460,23 +460,23 @@  discard block
 block discarded – undo
460 460
 			$autoloads['models']    = array();
461 461
 			$autoloads['functions'] = array();
462 462
 			//loading of the resources in autoload.php configuration file
463
-			if(file_exists(CONFIG_PATH . 'autoload.php')){
463
+			if (file_exists(CONFIG_PATH . 'autoload.php')) {
464 464
 				$autoload = array();
465 465
 				require_once CONFIG_PATH . 'autoload.php';
466
-				if(! empty($autoload) && is_array($autoload)){
466
+				if (!empty($autoload) && is_array($autoload)) {
467 467
 					$autoloads = array_merge($autoloads, $autoload);
468 468
 					unset($autoload);
469 469
 				}
470 470
 			}
471 471
 			//loading autoload configuration for modules
472 472
 			$modulesAutoloads = Module::getModulesAutoloadConfig();
473
-			if(! empty($modulesAutoloads) && is_array($modulesAutoloads)){
473
+			if (!empty($modulesAutoloads) && is_array($modulesAutoloads)) {
474 474
 				$autoloads = array_merge_recursive($autoloads, $modulesAutoloads);
475 475
 			}
476 476
 			return $autoloads;
477 477
 		}
478 478
 
479
-		private function loadResourcesFromAutoloadConfig(){
479
+		private function loadResourcesFromAutoloadConfig() {
480 480
 			$autoloads = array();
481 481
 			$autoloads['config']    = array();
482 482
 			$autoloads['languages'] = array();
@@ -488,28 +488,28 @@  discard block
 block discarded – undo
488 488
 
489 489
 			$autoloads = array_merge($autoloads, $list);
490 490
 			//config autoload
491
-			foreach($autoloads['config'] as $c){
491
+			foreach ($autoloads['config'] as $c) {
492 492
 				$this->config($c);
493 493
 			}
494 494
 			
495 495
 			//languages autoload
496
-			foreach($autoloads['languages'] as $language){
496
+			foreach ($autoloads['languages'] as $language) {
497 497
 				$this->lang($language);
498 498
 			}
499 499
 			
500 500
 			//libraries autoload
501
-			foreach($autoloads['libraries'] as $library){
501
+			foreach ($autoloads['libraries'] as $library) {
502 502
 				$this->library($library);
503 503
 			}
504 504
 
505 505
 			//models autoload
506
-			if(! empty($autoloads['models']) && is_array($autoloads['models'])){
507
-				foreach($autoloads['models'] as $model){
506
+			if (!empty($autoloads['models']) && is_array($autoloads['models'])) {
507
+				foreach ($autoloads['models'] as $model) {
508 508
 					$this->model($model);
509 509
 				}
510 510
 			}
511 511
 			
512
-			foreach($autoloads['functions'] as $function){
512
+			foreach ($autoloads['functions'] as $function) {
513 513
 				$this->functions($function);
514 514
 			}
515 515
 		}
Please login to merge, or discard this patch.
core/classes/Module.php 2 patches
Spacing   +79 added lines, -79 removed lines patch added patch discarded remove patch
@@ -24,7 +24,7 @@  discard block
 block discarded – undo
24 24
      * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
25 25
     */
26 26
    
27
-	class Module{
27
+	class Module {
28 28
 		
29 29
 		/**
30 30
 		 * list of loaded module
@@ -42,9 +42,9 @@  discard block
 block discarded – undo
42 42
 		 * The signleton of the logger
43 43
 		 * @return Object the Log instance
44 44
 		 */
45
-		private static function getLogger(){
46
-			if(self::$logger == null){
47
-				self::$logger[0] =& class_loader('Log', 'classes');
45
+		private static function getLogger() {
46
+			if (self::$logger == null) {
47
+				self::$logger[0] = & class_loader('Log', 'classes');
48 48
 				self::$logger[0]->setLogger('Library::Module');
49 49
 			}
50 50
 			return self::$logger[0];
@@ -53,27 +53,27 @@  discard block
 block discarded – undo
53 53
 		/**
54 54
 		 * Initialise the module list by scanning the directory MODULE_PATH
55 55
 		 */
56
-		public function init(){
56
+		public function init() {
57 57
 			$logger = self::getLogger();
58 58
 			$logger->debug('Check if the application contains the modules ...');
59 59
 			$moduleDir = opendir(MODULE_PATH);
60
-			if(is_resource($moduleDir)){
61
-				while(($module = readdir($moduleDir)) !== false){
62
-					if(preg_match('/^([a-z0-9-_]+)$/i', $module) && is_dir(MODULE_PATH . $module)){
60
+			if (is_resource($moduleDir)) {
61
+				while (($module = readdir($moduleDir)) !== false) {
62
+					if (preg_match('/^([a-z0-9-_]+)$/i', $module) && is_dir(MODULE_PATH . $module)) {
63 63
 						self::$list[] = $module;
64 64
 					}
65
-					else{
66
-						$logger->info('Skipping [' .$module. '], may be this is not a directory or does not exists or is invalid name');
65
+					else {
66
+						$logger->info('Skipping [' . $module . '], may be this is not a directory or does not exists or is invalid name');
67 67
 					}
68 68
 				}
69 69
 				closedir($moduleDir);
70 70
 			}
71 71
 			ksort(self::$list);
72 72
 			
73
-			if(self::hasModule()){
73
+			if (self::hasModule()) {
74 74
 				$logger->info('The application contains the module below [' . implode(', ', self::getModuleList()) . ']');
75 75
 			}
76
-			else{
76
+			else {
77 77
 				$logger->info('The application contains no module skipping');
78 78
 			}
79 79
 		}
@@ -82,9 +82,9 @@  discard block
 block discarded – undo
82 82
 		 * Get the list of the custom autoload configuration from module if exists
83 83
 		 * @return array|boolean the autoload configurations list or false if no module contains the autoload configuration values
84 84
 		 */
85
-		public static function getModulesAutoloadConfig(){
85
+		public static function getModulesAutoloadConfig() {
86 86
 			$logger = self::getLogger();
87
-			if(! self::hasModule()){
87
+			if (!self::hasModule()) {
88 88
 				$logger->info('No module was loaded skipping.');
89 89
 				return false;
90 90
 			}
@@ -97,10 +97,10 @@  discard block
 block discarded – undo
97 97
 			
98 98
 			foreach (self::$list as $module) {
99 99
 				$file = MODULE_PATH . $module . DS . 'config' . DS . 'autoload.php';
100
-				if(file_exists($file)){
100
+				if (file_exists($file)) {
101 101
 					$autoload = array();
102 102
 					require_once $file;
103
-					if(! empty($autoload) && is_array($autoload)){
103
+					if (!empty($autoload) && is_array($autoload)) {
104 104
 						$autoloads = array_merge_recursive($autoloads, $autoload);
105 105
 						unset($autoload);
106 106
 					}
@@ -113,23 +113,23 @@  discard block
 block discarded – undo
113 113
 		 * Get the list of the custom routes configuration from module if exists
114 114
 		 * @return array|boolean the routes list or false if no module contains the routes configuration
115 115
 		 */
116
-		public static function getModulesRoutes(){
116
+		public static function getModulesRoutes() {
117 117
 			$logger = self::getLogger();
118
-			if(! self::hasModule()){
118
+			if (!self::hasModule()) {
119 119
 				$logger->info('No module was loaded skipping.');
120 120
 				return false;
121 121
 			}
122 122
 			$routes = array();
123 123
 			foreach (self::$list as $module) {
124 124
 				$file = MODULE_PATH . $module . DS . 'config' . DS . 'routes.php';
125
-				if(file_exists($file)){
125
+				if (file_exists($file)) {
126 126
 					require_once $file;
127
-					if(! empty($route) && is_array($route)){
127
+					if (!empty($route) && is_array($route)) {
128 128
 						$routes = array_merge($routes, $route);
129 129
 						unset($route);
130 130
 					}
131
-					else{
132
-						show_error('No routing configuration found in [' .$file. '] for module [' . $module . ']');
131
+					else {
132
+						show_error('No routing configuration found in [' . $file . '] for module [' . $module . ']');
133 133
 					}
134 134
 				}
135 135
 			}
@@ -143,23 +143,23 @@  discard block
 block discarded – undo
143 143
 		 * @param  string $module  the module name
144 144
 		 * @return boolean|string  false or null if no module have this controller, path the full path of the controller
145 145
 		 */
146
-		public static function findControllerFullPath($class, $module = null){
146
+		public static function findControllerFullPath($class, $module = null) {
147 147
 			$logger = self::getLogger();
148
-			if(! self::hasModule()){
148
+			if (!self::hasModule()) {
149 149
 				$logger->info('No module was loaded skiping.');
150 150
 				return false;
151 151
 			}
152 152
 			$class = str_ireplace('.php', '', $class);
153 153
 			$class = ucfirst($class);
154
-			$classFile = $class.'.php';
155
-			$logger->debug('Checking the controller [' . $class . '] in module [' .$module. '] ...');
154
+			$classFile = $class . '.php';
155
+			$logger->debug('Checking the controller [' . $class . '] in module [' . $module . '] ...');
156 156
 			$filePath = MODULE_PATH . $module . DS . 'controllers' . DS . $classFile;
157
-			if(file_exists($filePath)){
158
-				$logger->info('Found controller [' . $class . '] in module [' .$module. '], the file path is [' .$filePath. ']');
157
+			if (file_exists($filePath)) {
158
+				$logger->info('Found controller [' . $class . '] in module [' . $module . '], the file path is [' . $filePath . ']');
159 159
 				return $filePath;
160 160
 			}
161
-			else{
162
-				$logger->info('Controller [' . $class . '] does not exist in the module [' .$module. ']');
161
+			else {
162
+				$logger->info('Controller [' . $class . '] does not exist in the module [' . $module . ']');
163 163
 				return false;
164 164
 			}
165 165
 		}
@@ -170,23 +170,23 @@  discard block
 block discarded – undo
170 170
 		 * @param string $module the module name
171 171
 		 * @return boolean|string  false or null if no module have this model, return the full path of this model
172 172
 		 */
173
-		public static function findModelFullPath($class, $module = null){
173
+		public static function findModelFullPath($class, $module = null) {
174 174
 			$logger = self::getLogger();
175
-			if(! self::hasModule()){
175
+			if (!self::hasModule()) {
176 176
 				$logger->info('No module was loaded skiping.');
177 177
 				return false;
178 178
 			}
179 179
 			$class = str_ireplace('.php', '', $class);
180 180
 			$class = ucfirst($class);
181
-			$classFile = $class.'.php';
182
-			$logger->debug('Checking model [' . $class . '] in module [' .$module. '] ...');
181
+			$classFile = $class . '.php';
182
+			$logger->debug('Checking model [' . $class . '] in module [' . $module . '] ...');
183 183
 			$filePath = MODULE_PATH . $module . DS . 'models' . DS . $classFile;
184
-			if(file_exists($filePath)){
185
-				$logger->info('Found model [' . $class . '] in module [' .$module. '], the file path is [' .$filePath. ']');
184
+			if (file_exists($filePath)) {
185
+				$logger->info('Found model [' . $class . '] in module [' . $module . '], the file path is [' . $filePath . ']');
186 186
 				return $filePath;
187 187
 			}
188
-			else{
189
-				$logger->info('Model [' . $class . '] does not exist in the module [' .$module. ']');
188
+			else {
189
+				$logger->info('Model [' . $class . '] does not exist in the module [' . $module . ']');
190 190
 				return false;
191 191
 			}
192 192
 		}
@@ -197,22 +197,22 @@  discard block
 block discarded – undo
197 197
 		 * @param string $module the module name
198 198
 		 * @return boolean|string  false or null if no module have this configuration,  return the full path of this configuration
199 199
 		 */
200
-		public static function findConfigFullPath($configuration, $module = null){
200
+		public static function findConfigFullPath($configuration, $module = null) {
201 201
 			$logger = self::getLogger();
202
-			if(! self::hasModule()){
202
+			if (!self::hasModule()) {
203 203
 				$logger->info('No module was loaded skiping.');
204 204
 				return false;
205 205
 			}
206 206
 			$configuration = str_ireplace('.php', '', $configuration);
207
-			$file = $configuration.'.php';
208
-			$logger->debug('Checking configuration [' . $configuration . '] in module [' .$module. '] ...');
207
+			$file = $configuration . '.php';
208
+			$logger->debug('Checking configuration [' . $configuration . '] in module [' . $module . '] ...');
209 209
 			$filePath = MODULE_PATH . $module . DS . 'config' . DS . $file;
210
-			if(file_exists($filePath)){
211
-				$logger->info('Found configuration [' . $configuration . '] in module [' .$module. '], the file path is [' .$filePath. ']');
210
+			if (file_exists($filePath)) {
211
+				$logger->info('Found configuration [' . $configuration . '] in module [' . $module . '], the file path is [' . $filePath . ']');
212 212
 				return $filePath;
213 213
 			}
214
-			else{
215
-				$logger->info('Configuration [' . $configuration . '] does not exist in the module [' .$module. ']');
214
+			else {
215
+				$logger->info('Configuration [' . $configuration . '] does not exist in the module [' . $module . ']');
216 216
 				return false;
217 217
 			}
218 218
 		}
@@ -223,23 +223,23 @@  discard block
 block discarded – undo
223 223
 		 * @param string $module the module name
224 224
 		 * @return boolean|string  false or null if no module have this helper,  return the full path of this helper
225 225
 		 */
226
-		public static function findFunctionFullPath($helper, $module = null){
226
+		public static function findFunctionFullPath($helper, $module = null) {
227 227
 			$logger = self::getLogger();
228
-			if(! self::hasModule()){
228
+			if (!self::hasModule()) {
229 229
 				$logger->info('No module was loaded skiping.');
230 230
 				return false;
231 231
 			}
232 232
 			$helper = str_ireplace('.php', '', $helper);
233 233
 			$helper = str_ireplace('function_', '', $helper);
234
-			$file = 'function_'.$helper.'.php';
235
-			$logger->debug('Checking helper [' . $helper . '] in module [' .$module. '] ...');
234
+			$file = 'function_' . $helper . '.php';
235
+			$logger->debug('Checking helper [' . $helper . '] in module [' . $module . '] ...');
236 236
 			$filePath = MODULE_PATH . $module . DS . 'functions' . DS . $file;
237
-			if(file_exists($filePath)){
238
-				$logger->info('Found helper [' . $helper . '] in module [' .$module. '], the file path is [' .$filePath. ']');
237
+			if (file_exists($filePath)) {
238
+				$logger->info('Found helper [' . $helper . '] in module [' . $module . '], the file path is [' . $filePath . ']');
239 239
 				return $filePath;
240 240
 			}
241
-			else{
242
-				$logger->info('Helper [' . $helper . '] does not exist in the module [' .$module. ']');
241
+			else {
242
+				$logger->info('Helper [' . $helper . '] does not exist in the module [' . $module . ']');
243 243
 				return false;
244 244
 			}
245 245
 		}
@@ -251,22 +251,22 @@  discard block
 block discarded – undo
251 251
 		 * @param string $module the module name
252 252
 		 * @return boolean|string  false or null if no module have this library,  return the full path of this library
253 253
 		 */
254
-		public static function findLibraryFullPath($class, $module = null){
254
+		public static function findLibraryFullPath($class, $module = null) {
255 255
 			$logger = self::getLogger();
256
-			if(! self::hasModule()){
256
+			if (!self::hasModule()) {
257 257
 				$logger->info('No module was loaded skiping.');
258 258
 				return false;
259 259
 			}
260 260
 			$class = str_ireplace('.php', '', $class);
261
-			$file = $class.'.php';
262
-			$logger->debug('Checking library [' . $class . '] in module [' .$module. '] ...');
261
+			$file = $class . '.php';
262
+			$logger->debug('Checking library [' . $class . '] in module [' . $module . '] ...');
263 263
 			$filePath = MODULE_PATH . $module . DS . 'libraries' . DS . $file;
264
-			if(file_exists($filePath)){
265
-				$logger->info('Found library [' . $class . '] in module [' .$module. '], the file path is [' .$filePath. ']');
264
+			if (file_exists($filePath)) {
265
+				$logger->info('Found library [' . $class . '] in module [' . $module . '], the file path is [' . $filePath . ']');
266 266
 				return $filePath;
267 267
 			}
268
-			else{
269
-				$logger->info('Library [' . $class . '] does not exist in the module [' .$module. ']');
268
+			else {
269
+				$logger->info('Library [' . $class . '] does not exist in the module [' . $module . ']');
270 270
 				return false;
271 271
 			}
272 272
 		}
@@ -278,9 +278,9 @@  discard block
 block discarded – undo
278 278
 		 * @param string $module the module name to check
279 279
 		 * @return boolean|string  false or null if no module have this view, path the full path of the view
280 280
 		 */
281
-		public static function findViewFullPath($view, $module = null){
281
+		public static function findViewFullPath($view, $module = null) {
282 282
 			$logger = self::getLogger();
283
-			if(! self::hasModule()){
283
+			if (!self::hasModule()) {
284 284
 				$logger->info('No module was loaded skiping.');
285 285
 				return false;
286 286
 			}
@@ -288,14 +288,14 @@  discard block
 block discarded – undo
288 288
 			$view = trim($view, '/\\');
289 289
 			$view = str_ireplace('/', DS, $view);
290 290
 			$viewFile = $view . '.php';
291
-			$logger->debug('Checking view [' . $view . '] in module [' .$module. '] ...');
291
+			$logger->debug('Checking view [' . $view . '] in module [' . $module . '] ...');
292 292
 			$filePath = MODULE_PATH . $module . DS . 'views' . DS . $viewFile;
293
-			if(file_exists($filePath)){
294
-				$logger->info('Found view [' . $view . '] in module [' .$module. '], the file path is [' .$filePath. ']');
293
+			if (file_exists($filePath)) {
294
+				$logger->info('Found view [' . $view . '] in module [' . $module . '], the file path is [' . $filePath . ']');
295 295
 				return $filePath;
296 296
 			}
297
-			else{
298
-				$logger->info('View [' . $view . '] does not exist in the module [' .$module. ']');
297
+			else {
298
+				$logger->info('View [' . $view . '] does not exist in the module [' . $module . ']');
299 299
 				return false;
300 300
 			}
301 301
 		}
@@ -307,23 +307,23 @@  discard block
 block discarded – undo
307 307
 		 * @param string $appLang the application language like 'en', 'fr'
308 308
 		 * @return boolean|string  false or null if no module have this language,  return the full path of this language
309 309
 		 */
310
-		public static function findLanguageFullPath($language, $module = null, $appLang){
310
+		public static function findLanguageFullPath($language, $module = null, $appLang) {
311 311
 			$logger = self::getLogger();
312
-			if(! self::hasModule()){
312
+			if (!self::hasModule()) {
313 313
 				$logger->info('No module was loaded skiping.');
314 314
 				return false;
315 315
 			}
316 316
 			$language = str_ireplace('.php', '', $language);
317 317
 			$language = str_ireplace('lang_', '', $language);
318
-			$file = 'lang_'.$language.'.php';
319
-			$logger->debug('Checking language [' . $language . '] in module [' .$module. '] ...');
318
+			$file = 'lang_' . $language . '.php';
319
+			$logger->debug('Checking language [' . $language . '] in module [' . $module . '] ...');
320 320
 			$filePath = MODULE_PATH . $module . DS . 'lang' . DS . $appLang . DS . $file;
321
-			if(file_exists($filePath)){
322
-				$logger->info('Found language [' . $language . '] in module [' .$module. '], the file path is [' .$filePath. ']');
321
+			if (file_exists($filePath)) {
322
+				$logger->info('Found language [' . $language . '] in module [' . $module . '], the file path is [' . $filePath . ']');
323 323
 				return $filePath;
324 324
 			}
325
-			else{
326
-				$logger->info('Language [' . $language . '] does not exist in the module [' .$module. ']');
325
+			else {
326
+				$logger->info('Language [' . $language . '] does not exist in the module [' . $module . ']');
327 327
 				return false;
328 328
 			}
329 329
 		}
@@ -332,7 +332,7 @@  discard block
 block discarded – undo
332 332
 		 * Get the list of module loaded
333 333
 		 * @return array the module list
334 334
 		 */
335
-		public static function getModuleList(){
335
+		public static function getModuleList() {
336 336
 			return self::$list;
337 337
 		}
338 338
 
@@ -340,7 +340,7 @@  discard block
 block discarded – undo
340 340
 		 * Check if the application has an module
341 341
 		 * @return boolean
342 342
 		 */
343
-		public static function hasModule(){
343
+		public static function hasModule() {
344 344
 			return !empty(self::$list);
345 345
 		}
346 346
 
Please login to merge, or discard this patch.
Braces   +10 added lines, -20 removed lines patch added patch discarded remove patch
@@ -61,8 +61,7 @@  discard block
 block discarded – undo
61 61
 				while(($module = readdir($moduleDir)) !== false){
62 62
 					if(preg_match('/^([a-z0-9-_]+)$/i', $module) && is_dir(MODULE_PATH . $module)){
63 63
 						self::$list[] = $module;
64
-					}
65
-					else{
64
+					} else{
66 65
 						$logger->info('Skipping [' .$module. '], may be this is not a directory or does not exists or is invalid name');
67 66
 					}
68 67
 				}
@@ -72,8 +71,7 @@  discard block
 block discarded – undo
72 71
 			
73 72
 			if(self::hasModule()){
74 73
 				$logger->info('The application contains the module below [' . implode(', ', self::getModuleList()) . ']');
75
-			}
76
-			else{
74
+			} else{
77 75
 				$logger->info('The application contains no module skipping');
78 76
 			}
79 77
 		}
@@ -127,8 +125,7 @@  discard block
 block discarded – undo
127 125
 					if(! empty($route) && is_array($route)){
128 126
 						$routes = array_merge($routes, $route);
129 127
 						unset($route);
130
-					}
131
-					else{
128
+					} else{
132 129
 						show_error('No routing configuration found in [' .$file. '] for module [' . $module . ']');
133 130
 					}
134 131
 				}
@@ -157,8 +154,7 @@  discard block
 block discarded – undo
157 154
 			if(file_exists($filePath)){
158 155
 				$logger->info('Found controller [' . $class . '] in module [' .$module. '], the file path is [' .$filePath. ']');
159 156
 				return $filePath;
160
-			}
161
-			else{
157
+			} else{
162 158
 				$logger->info('Controller [' . $class . '] does not exist in the module [' .$module. ']');
163 159
 				return false;
164 160
 			}
@@ -184,8 +180,7 @@  discard block
 block discarded – undo
184 180
 			if(file_exists($filePath)){
185 181
 				$logger->info('Found model [' . $class . '] in module [' .$module. '], the file path is [' .$filePath. ']');
186 182
 				return $filePath;
187
-			}
188
-			else{
183
+			} else{
189 184
 				$logger->info('Model [' . $class . '] does not exist in the module [' .$module. ']');
190 185
 				return false;
191 186
 			}
@@ -210,8 +205,7 @@  discard block
 block discarded – undo
210 205
 			if(file_exists($filePath)){
211 206
 				$logger->info('Found configuration [' . $configuration . '] in module [' .$module. '], the file path is [' .$filePath. ']');
212 207
 				return $filePath;
213
-			}
214
-			else{
208
+			} else{
215 209
 				$logger->info('Configuration [' . $configuration . '] does not exist in the module [' .$module. ']');
216 210
 				return false;
217 211
 			}
@@ -237,8 +231,7 @@  discard block
 block discarded – undo
237 231
 			if(file_exists($filePath)){
238 232
 				$logger->info('Found helper [' . $helper . '] in module [' .$module. '], the file path is [' .$filePath. ']');
239 233
 				return $filePath;
240
-			}
241
-			else{
234
+			} else{
242 235
 				$logger->info('Helper [' . $helper . '] does not exist in the module [' .$module. ']');
243 236
 				return false;
244 237
 			}
@@ -264,8 +257,7 @@  discard block
 block discarded – undo
264 257
 			if(file_exists($filePath)){
265 258
 				$logger->info('Found library [' . $class . '] in module [' .$module. '], the file path is [' .$filePath. ']');
266 259
 				return $filePath;
267
-			}
268
-			else{
260
+			} else{
269 261
 				$logger->info('Library [' . $class . '] does not exist in the module [' .$module. ']');
270 262
 				return false;
271 263
 			}
@@ -293,8 +285,7 @@  discard block
 block discarded – undo
293 285
 			if(file_exists($filePath)){
294 286
 				$logger->info('Found view [' . $view . '] in module [' .$module. '], the file path is [' .$filePath. ']');
295 287
 				return $filePath;
296
-			}
297
-			else{
288
+			} else{
298 289
 				$logger->info('View [' . $view . '] does not exist in the module [' .$module. ']');
299 290
 				return false;
300 291
 			}
@@ -321,8 +312,7 @@  discard block
 block discarded – undo
321 312
 			if(file_exists($filePath)){
322 313
 				$logger->info('Found language [' . $language . '] in module [' .$module. '], the file path is [' .$filePath. ']');
323 314
 				return $filePath;
324
-			}
325
-			else{
315
+			} else{
326 316
 				$logger->info('Language [' . $language . '] does not exist in the module [' .$module. ']');
327 317
 				return false;
328 318
 			}
Please login to merge, or discard this patch.
core/classes/cache/FileCache.php 2 patches
Indentation   +86 added lines, -86 removed lines patch added patch discarded remove patch
@@ -22,7 +22,7 @@  discard block
 block discarded – undo
22 22
 	 * You should have received a copy of the GNU General Public License
23 23
 	 * along with this program; if not, write to the Free Software
24 24
 	 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
25
-	*/
25
+	 */
26 26
 
27 27
 	class FileCache implements CacheInterface{
28 28
 		
@@ -44,15 +44,15 @@  discard block
 block discarded – undo
44 44
 				show_error('The cache for file system is not available. Check the cache directory if is exists or is writable.');
45 45
 			}
46 46
 			/**
47
-	         * instance of the Log class
48
-	         */
49
-	        if(is_object($logger)){
50
-	          $this->logger = $logger;
51
-	        }
52
-	        else{
53
-	            $this->logger =& class_loader('Log', 'classes');
54
-	            $this->logger->setLogger('Library::FileCache');
55
-	        }
47
+			 * instance of the Log class
48
+			 */
49
+			if(is_object($logger)){
50
+			  $this->logger = $logger;
51
+			}
52
+			else{
53
+				$this->logger =& class_loader('Log', 'classes');
54
+				$this->logger->setLogger('Library::FileCache');
55
+			}
56 56
 			
57 57
 			//if Zlib extension is not loaded set compressCacheData to false
58 58
 			if(! extension_loaded('zlib')){
@@ -80,26 +80,26 @@  discard block
 block discarded – undo
80 80
 				return false;
81 81
 			}
82 82
 			// Getting a shared lock 
83
-		    flock($handle, LOCK_SH);
84
-		    $data = file_get_contents($filePath);
85
-      		fclose($handle);
86
-      		$data = @unserialize($this->compressCacheData ? gzinflate($data) : $data);
87
-      		if (! $data) {
88
-      			$this->logger->error('Can not unserialize the cache data for the key ['. $key .'], return false');
89
-		         // If unserializing somehow didn't work out, we'll delete the file
90
-		         unlink($filePath);
91
-		         return false;
92
-	      	}
93
-	      	if (time() > $data['expire']) {
94
-	      		$this->logger->info('The cache data for the key ['. $key .'] already expired delete the cache file [' .$filePath. ']');
95
-		        // Unlinking when the file was expired
96
-		        unlink($filePath);
97
-		        return false;
98
-		     }
99
-		     else{
100
-		     	$this->logger->info('The cache not yet expire, now return the cache data for key ['. $key .'], the cache will expire at [' . date('Y-m-d H:i:s', $data['expire']) . ']');
101
-		     	return $data['data'];
102
-		     }
83
+			flock($handle, LOCK_SH);
84
+			$data = file_get_contents($filePath);
85
+	  		fclose($handle);
86
+	  		$data = @unserialize($this->compressCacheData ? gzinflate($data) : $data);
87
+	  		if (! $data) {
88
+	  			$this->logger->error('Can not unserialize the cache data for the key ['. $key .'], return false');
89
+				 // If unserializing somehow didn't work out, we'll delete the file
90
+				 unlink($filePath);
91
+				 return false;
92
+		  	}
93
+		  	if (time() > $data['expire']) {
94
+		  		$this->logger->info('The cache data for the key ['. $key .'] already expired delete the cache file [' .$filePath. ']');
95
+				// Unlinking when the file was expired
96
+				unlink($filePath);
97
+				return false;
98
+			 }
99
+			 else{
100
+			 	$this->logger->info('The cache not yet expire, now return the cache data for key ['. $key .'], the cache will expire at [' . date('Y-m-d H:i:s', $data['expire']) . ']');
101
+			 	return $data['data'];
102
+			 }
103 103
 		}
104 104
 
105 105
 
@@ -121,25 +121,25 @@  discard block
 block discarded – undo
121 121
 			}
122 122
 			flock($handle, LOCK_EX); // exclusive lock, will get released when the file is closed
123 123
 			//Serializing along with the TTL
124
-		    $cacheData = serialize(array(
124
+			$cacheData = serialize(array(
125 125
 									'mtime' => time(),
126 126
 									'expire' => $expire,
127 127
 									'data' => $data,
128 128
 									'ttl' => $ttl
129 129
 									)
130 130
 								);		   
131
-		    $result = fwrite($handle, $this->compressCacheData ? gzdeflate($cacheData, 9) : $cacheData);
132
-		    if(! $result){
133
-		    	$this->logger->error('Can not write cache data into file [' .$filePath. '] for the key ['. $key .'], return false');
134
-		    	fclose($handle);
135
-		    	return false;
136
-		    }
137
-		    else{
138
-		    	$this->logger->info('Cache data saved into file [' .$filePath. '] for the key ['. $key .']');
139
-		    	fclose($handle);
131
+			$result = fwrite($handle, $this->compressCacheData ? gzdeflate($cacheData, 9) : $cacheData);
132
+			if(! $result){
133
+				$this->logger->error('Can not write cache data into file [' .$filePath. '] for the key ['. $key .'], return false');
134
+				fclose($handle);
135
+				return false;
136
+			}
137
+			else{
138
+				$this->logger->info('Cache data saved into file [' .$filePath. '] for the key ['. $key .']');
139
+				fclose($handle);
140 140
 				chmod($filePath, 0640);
141 141
 				return true;
142
-		    }
142
+			}
143 143
 		}	
144 144
 
145 145
 
@@ -159,7 +159,7 @@  discard block
 block discarded – undo
159 159
 			}
160 160
 			else{
161 161
 				$this->logger->info('Found cache file [' .$filePath. '] remove it');
162
-	      		unlink($filePath);
162
+		  		unlink($filePath);
163 163
 				return true;
164 164
 			}
165 165
 		}
@@ -182,7 +182,7 @@  discard block
 block discarded – undo
182 182
 			}
183 183
 			else{
184 184
 				$this->logger->info('Found cache file [' .$filePath. '] check the validity');
185
-	      		$data = file_get_contents($filePath);
185
+		  		$data = file_get_contents($filePath);
186 186
 				$data = @unserialize($this->compressCacheData ? gzinflate($data) : $data);
187 187
 				if(! $data){
188 188
 					$this->logger->warning('Can not unserialize the cache data for file [' . $filePath . ']');
@@ -222,17 +222,17 @@  discard block
 block discarded – undo
222 222
 				foreach ($list as $file) {
223 223
 					$this->logger->debug('Processing the cache file [' . $file . ']');
224 224
 					$data = file_get_contents($file);
225
-		      		$data = @unserialize($this->compressCacheData ? gzinflate($data) : $data);
226
-		      		if(! $data){
227
-		      			$this->logger->warning('Can not unserialize the cache data for file [' . $file . ']');
228
-		      		}
229
-		      		else if(time() > $data['expire']){
230
-		      			$this->logger->info('The cache data for file [' . $file . '] already expired remove it');
231
-		      			unlink($file);
232
-		      		}
233
-		      		else{
234
-		      			$this->logger->info('The cache data for file [' . $file . '] not yet expired skip it');
235
-		      		}
225
+			  		$data = @unserialize($this->compressCacheData ? gzinflate($data) : $data);
226
+			  		if(! $data){
227
+			  			$this->logger->warning('Can not unserialize the cache data for file [' . $file . ']');
228
+			  		}
229
+			  		else if(time() > $data['expire']){
230
+			  			$this->logger->info('The cache data for file [' . $file . '] already expired remove it');
231
+			  			unlink($file);
232
+			  		}
233
+			  		else{
234
+			  			$this->logger->info('The cache data for file [' . $file . '] not yet expired skip it');
235
+			  		}
236 236
 				}
237 237
 			}
238 238
 		}	
@@ -255,19 +255,19 @@  discard block
 block discarded – undo
255 255
 			}
256 256
 		}
257 257
 	
258
-	    /**
259
-	     * @return boolean
260
-	     */
261
-	    public function isCompressCacheData(){
262
-	        return $this->compressCacheData;
263
-	    }
258
+		/**
259
+		 * @return boolean
260
+		 */
261
+		public function isCompressCacheData(){
262
+			return $this->compressCacheData;
263
+		}
264 264
 
265
-	    /**
266
-	     * @param boolean $compressCacheData
267
-	     *
268
-	     * @return self
269
-	     */
270
-	    public function setCompressCacheData($status = true){
265
+		/**
266
+		 * @param boolean $compressCacheData
267
+		 *
268
+		 * @return self
269
+		 */
270
+		public function setCompressCacheData($status = true){
271 271
 			//if Zlib extension is not loaded set compressCacheData to false
272 272
 			if($status === true && ! extension_loaded('zlib')){
273 273
 				
@@ -278,7 +278,7 @@  discard block
 block discarded – undo
278 278
 				$this->compressCacheData = $status;
279 279
 			}
280 280
 			return $this;
281
-	    }
281
+		}
282 282
 		
283 283
 		/**
284 284
 		 * Check whether the cache feature for the handle is supported
@@ -290,28 +290,28 @@  discard block
 block discarded – undo
290 290
 		}
291 291
 
292 292
 		/**
293
-	     * Return the Log instance
294
-	     * @return Log
295
-	     */
296
-	    public function getLogger(){
297
-	      return $this->logger;
298
-	    }
293
+		 * Return the Log instance
294
+		 * @return Log
295
+		 */
296
+		public function getLogger(){
297
+		  return $this->logger;
298
+		}
299 299
 
300
-	    /**
301
-	     * Set the log instance
302
-	     * @param Log $logger the log object
303
-	     */
304
-	    public function setLogger(Log $logger){
305
-	      $this->logger = $logger;
306
-	      return $this;
307
-	    }
300
+		/**
301
+		 * Set the log instance
302
+		 * @param Log $logger the log object
303
+		 */
304
+		public function setLogger(Log $logger){
305
+		  $this->logger = $logger;
306
+		  return $this;
307
+		}
308 308
 		
309 309
 		/**
310
-		* Get the cache file full path for the given key
311
-		*
312
-		* @param $key the cache item key
313
-		* @return string  		the full cache file path for this key
314
-		*/
310
+		 * Get the cache file full path for the given key
311
+		 *
312
+		 * @param $key the cache item key
313
+		 * @return string  		the full cache file path for this key
314
+		 */
315 315
 		private function getFilePath($key){
316 316
 			return CACHE_PATH . md5($key) . '.cache';
317 317
 		}
Please login to merge, or discard this patch.
Spacing   +62 added lines, -62 removed lines patch added patch discarded remove patch
@@ -24,7 +24,7 @@  discard block
 block discarded – undo
24 24
 	 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
25 25
 	*/
26 26
 
27
-	class FileCache implements CacheInterface{
27
+	class FileCache implements CacheInterface {
28 28
 		
29 29
 		/**
30 30
 		 * Whether to enable compression of the cache data file.
@@ -39,23 +39,23 @@  discard block
 block discarded – undo
39 39
 		private $logger;
40 40
 		
41 41
 		
42
-		public function __construct(Log $logger = null){
43
-			if(! $this->isSupported()){
42
+		public function __construct(Log $logger = null) {
43
+			if (!$this->isSupported()) {
44 44
 				show_error('The cache for file system is not available. Check the cache directory if is exists or is writable.');
45 45
 			}
46 46
 			/**
47 47
 	         * instance of the Log class
48 48
 	         */
49
-	        if(is_object($logger)){
49
+	        if (is_object($logger)) {
50 50
 	          $this->logger = $logger;
51 51
 	        }
52
-	        else{
53
-	            $this->logger =& class_loader('Log', 'classes');
52
+	        else {
53
+	            $this->logger = & class_loader('Log', 'classes');
54 54
 	            $this->logger->setLogger('Library::FileCache');
55 55
 	        }
56 56
 			
57 57
 			//if Zlib extension is not loaded set compressCacheData to false
58
-			if(! extension_loaded('zlib')){
58
+			if (!extension_loaded('zlib')) {
59 59
 				$this->logger->warning('The zlib extension is not loaded set cache compress data to FALSE');
60 60
 				$this->compressCacheData = false;
61 61
 			}
@@ -66,17 +66,17 @@  discard block
 block discarded – undo
66 66
 		 * @param  string $key the key to identify the cache data
67 67
 		 * @return mixed      the cache data if exists else return false
68 68
 		 */
69
-		public function get($key){
70
-			$this->logger->debug('Getting cache data for key ['. $key .']');
69
+		public function get($key) {
70
+			$this->logger->debug('Getting cache data for key [' . $key . ']');
71 71
 			$filePath = $this->getFilePath($key);
72
-			if(! file_exists($filePath)){
73
-				$this->logger->info('No cache file found for the key ['. $key .'], return false');
72
+			if (!file_exists($filePath)) {
73
+				$this->logger->info('No cache file found for the key [' . $key . '], return false');
74 74
 				return false;
75 75
 			}
76
-			$this->logger->info('The cache file [' .$filePath. '] for the key ['. $key .'] exists, check if the cache data is valid');
77
-			$handle = fopen($filePath,'r');
78
-			if(! is_resource($handle)){
79
-				$this->logger->error('Can not open the file cache [' .$filePath. '] for the key ['. $key .'], return false');
76
+			$this->logger->info('The cache file [' . $filePath . '] for the key [' . $key . '] exists, check if the cache data is valid');
77
+			$handle = fopen($filePath, 'r');
78
+			if (!is_resource($handle)) {
79
+				$this->logger->error('Can not open the file cache [' . $filePath . '] for the key [' . $key . '], return false');
80 80
 				return false;
81 81
 			}
82 82
 			// Getting a shared lock 
@@ -84,20 +84,20 @@  discard block
 block discarded – undo
84 84
 		    $data = file_get_contents($filePath);
85 85
       		fclose($handle);
86 86
       		$data = @unserialize($this->compressCacheData ? gzinflate($data) : $data);
87
-      		if (! $data) {
88
-      			$this->logger->error('Can not unserialize the cache data for the key ['. $key .'], return false');
87
+      		if (!$data) {
88
+      			$this->logger->error('Can not unserialize the cache data for the key [' . $key . '], return false');
89 89
 		         // If unserializing somehow didn't work out, we'll delete the file
90 90
 		         unlink($filePath);
91 91
 		         return false;
92 92
 	      	}
93 93
 	      	if (time() > $data['expire']) {
94
-	      		$this->logger->info('The cache data for the key ['. $key .'] already expired delete the cache file [' .$filePath. ']');
94
+	      		$this->logger->info('The cache data for the key [' . $key . '] already expired delete the cache file [' . $filePath . ']');
95 95
 		        // Unlinking when the file was expired
96 96
 		        unlink($filePath);
97 97
 		        return false;
98 98
 		     }
99
-		     else{
100
-		     	$this->logger->info('The cache not yet expire, now return the cache data for key ['. $key .'], the cache will expire at [' . date('Y-m-d H:i:s', $data['expire']) . ']');
99
+		     else {
100
+		     	$this->logger->info('The cache not yet expire, now return the cache data for key [' . $key . '], the cache will expire at [' . date('Y-m-d H:i:s', $data['expire']) . ']');
101 101
 		     	return $data['data'];
102 102
 		     }
103 103
 		}
@@ -110,13 +110,13 @@  discard block
 block discarded – undo
110 110
 		 * @param integer $ttl  the cache life time
111 111
 		 * @return boolean true if success otherwise will return false
112 112
 		 */
113
-		public function set($key, $data, $ttl = 0){
113
+		public function set($key, $data, $ttl = 0) {
114 114
 			$expire = time() + $ttl;
115
-			$this->logger->debug('Setting cache data for key ['. $key .'], time to live [' .$ttl. '], expire at [' . date('Y-m-d H:i:s', $expire) . ']');
115
+			$this->logger->debug('Setting cache data for key [' . $key . '], time to live [' . $ttl . '], expire at [' . date('Y-m-d H:i:s', $expire) . ']');
116 116
 			$filePath = $this->getFilePath($key);
117
-			$handle = fopen($filePath,'w');
118
-			if(! is_resource($handle)){
119
-				$this->logger->error('Can not open the file cache [' .$filePath. '] for the key ['. $key .'], return false');
117
+			$handle = fopen($filePath, 'w');
118
+			if (!is_resource($handle)) {
119
+				$this->logger->error('Can not open the file cache [' . $filePath . '] for the key [' . $key . '], return false');
120 120
 				return false;
121 121
 			}
122 122
 			flock($handle, LOCK_EX); // exclusive lock, will get released when the file is closed
@@ -129,13 +129,13 @@  discard block
 block discarded – undo
129 129
 									)
130 130
 								);		   
131 131
 		    $result = fwrite($handle, $this->compressCacheData ? gzdeflate($cacheData, 9) : $cacheData);
132
-		    if(! $result){
133
-		    	$this->logger->error('Can not write cache data into file [' .$filePath. '] for the key ['. $key .'], return false');
132
+		    if (!$result) {
133
+		    	$this->logger->error('Can not write cache data into file [' . $filePath . '] for the key [' . $key . '], return false');
134 134
 		    	fclose($handle);
135 135
 		    	return false;
136 136
 		    }
137
-		    else{
138
-		    	$this->logger->info('Cache data saved into file [' .$filePath. '] for the key ['. $key .']');
137
+		    else {
138
+		    	$this->logger->info('Cache data saved into file [' . $filePath . '] for the key [' . $key . ']');
139 139
 		    	fclose($handle);
140 140
 				chmod($filePath, 0640);
141 141
 				return true;
@@ -149,16 +149,16 @@  discard block
 block discarded – undo
149 149
 		 * @return boolean      true if the cache is delete, false if can't delete 
150 150
 		 * the cache or the cache with the given key not exist
151 151
 		 */
152
-		public function delete($key){
153
-			$this->logger->debug('Deleting of cache data for key [' .$key. ']');
152
+		public function delete($key) {
153
+			$this->logger->debug('Deleting of cache data for key [' . $key . ']');
154 154
 			$filePath = $this->getFilePath($key);
155
-			$this->logger->info('The file path for the key [' .$key. '] is [' .$filePath. ']');
156
-			if(! file_exists($filePath)){
155
+			$this->logger->info('The file path for the key [' . $key . '] is [' . $filePath . ']');
156
+			if (!file_exists($filePath)) {
157 157
 				$this->logger->info('This cache file does not exists skipping');
158 158
 				return false;
159 159
 			}
160
-			else{
161
-				$this->logger->info('Found cache file [' .$filePath. '] remove it');
160
+			else {
161
+				$this->logger->info('Found cache file [' . $filePath . '] remove it');
162 162
 	      		unlink($filePath);
163 163
 				return true;
164 164
 			}
@@ -172,25 +172,25 @@  discard block
 block discarded – undo
172 172
 		 * 'expire' => expiration time of the cache (Unix timestamp),
173 173
 		 * 'ttl' => the time to live of the cache in second
174 174
 		 */
175
-		public function getInfo($key){
176
-			$this->logger->debug('Getting of cache info for key [' .$key. ']');
175
+		public function getInfo($key) {
176
+			$this->logger->debug('Getting of cache info for key [' . $key . ']');
177 177
 			$filePath = $this->getFilePath($key);
178
-			$this->logger->info('The file path for the key [' .$key. '] is [' .$filePath. ']');
179
-			if(! file_exists($filePath)){
178
+			$this->logger->info('The file path for the key [' . $key . '] is [' . $filePath . ']');
179
+			if (!file_exists($filePath)) {
180 180
 				$this->logger->info('This cache file does not exists skipping');
181 181
 				return false;
182 182
 			}
183
-			else{
184
-				$this->logger->info('Found cache file [' .$filePath. '] check the validity');
183
+			else {
184
+				$this->logger->info('Found cache file [' . $filePath . '] check the validity');
185 185
 	      		$data = file_get_contents($filePath);
186 186
 				$data = @unserialize($this->compressCacheData ? gzinflate($data) : $data);
187
-				if(! $data){
187
+				if (!$data) {
188 188
 					$this->logger->warning('Can not unserialize the cache data for file [' . $filePath . ']');
189 189
 					return false;
190 190
 				}
191
-				else{
191
+				else {
192 192
 					$this->logger->info('This cache data is OK check for expire');
193
-					if(isset($data['expire']) && $data['expire'] > time()){
193
+					if (isset($data['expire']) && $data['expire'] > time()) {
194 194
 						$this->logger->info('This cache not yet expired return cache informations');
195 195
 						$info = array(
196 196
 							'mtime' => $data['mtime'],
@@ -199,7 +199,7 @@  discard block
 block discarded – undo
199 199
 							);
200 200
 						return $info;
201 201
 					}
202
-					else{
202
+					else {
203 203
 						$this->logger->info('This cache already expired return false');
204 204
 						return false;
205 205
 					}
@@ -211,26 +211,26 @@  discard block
 block discarded – undo
211 211
 		/**
212 212
 		 * Used to delete expired cache data
213 213
 		 */
214
-		public function deleteExpiredCache(){
214
+		public function deleteExpiredCache() {
215 215
 			$this->logger->debug('Deleting of expired cache files');
216 216
 			$list = glob(CACHE_PATH . '*.cache');
217
-			if(! $list){
217
+			if (!$list) {
218 218
 				$this->logger->info('No cache files were found skipping');
219 219
 			}
220
-			else{
220
+			else {
221 221
 				$this->logger->info('Found [' . count($list) . '] cache files to remove if expired');
222 222
 				foreach ($list as $file) {
223 223
 					$this->logger->debug('Processing the cache file [' . $file . ']');
224 224
 					$data = file_get_contents($file);
225 225
 		      		$data = @unserialize($this->compressCacheData ? gzinflate($data) : $data);
226
-		      		if(! $data){
226
+		      		if (!$data) {
227 227
 		      			$this->logger->warning('Can not unserialize the cache data for file [' . $file . ']');
228 228
 		      		}
229
-		      		else if(time() > $data['expire']){
229
+		      		else if (time() > $data['expire']) {
230 230
 		      			$this->logger->info('The cache data for file [' . $file . '] already expired remove it');
231 231
 		      			unlink($file);
232 232
 		      		}
233
-		      		else{
233
+		      		else {
234 234
 		      			$this->logger->info('The cache data for file [' . $file . '] not yet expired skip it');
235 235
 		      		}
236 236
 				}
@@ -240,13 +240,13 @@  discard block
 block discarded – undo
240 240
 		/**
241 241
 		 * Remove all file from cache folder
242 242
 		 */
243
-		public function clean(){
243
+		public function clean() {
244 244
 			$this->logger->debug('Deleting of all cache files');
245 245
 			$list = glob(CACHE_PATH . '*.cache');
246
-			if(! $list){
246
+			if (!$list) {
247 247
 				$this->logger->info('No cache files were found skipping');
248 248
 			}
249
-			else{
249
+			else {
250 250
 				$this->logger->info('Found [' . count($list) . '] cache files to remove');
251 251
 				foreach ($list as $file) {
252 252
 					$this->logger->debug('Processing the cache file [' . $file . ']');
@@ -258,7 +258,7 @@  discard block
 block discarded – undo
258 258
 	    /**
259 259
 	     * @return boolean
260 260
 	     */
261
-	    public function isCompressCacheData(){
261
+	    public function isCompressCacheData() {
262 262
 	        return $this->compressCacheData;
263 263
 	    }
264 264
 
@@ -267,14 +267,14 @@  discard block
 block discarded – undo
267 267
 	     *
268 268
 	     * @return self
269 269
 	     */
270
-	    public function setCompressCacheData($status = true){
270
+	    public function setCompressCacheData($status = true) {
271 271
 			//if Zlib extension is not loaded set compressCacheData to false
272
-			if($status === true && ! extension_loaded('zlib')){
272
+			if ($status === true && !extension_loaded('zlib')) {
273 273
 				
274 274
 				$this->logger->warning('The zlib extension is not loaded set cache compress data to FALSE');
275 275
 				$this->compressCacheData = false;
276 276
 			}
277
-			else{
277
+			else {
278 278
 				$this->compressCacheData = $status;
279 279
 			}
280 280
 			return $this;
@@ -285,7 +285,7 @@  discard block
 block discarded – undo
285 285
 		 *
286 286
 		 * @return bool
287 287
 		 */
288
-		public function isSupported(){
288
+		public function isSupported() {
289 289
 			return CACHE_PATH && is_dir(CACHE_PATH) && is_writable(CACHE_PATH);
290 290
 		}
291 291
 
@@ -293,7 +293,7 @@  discard block
 block discarded – undo
293 293
 	     * Return the Log instance
294 294
 	     * @return Log
295 295
 	     */
296
-	    public function getLogger(){
296
+	    public function getLogger() {
297 297
 	      return $this->logger;
298 298
 	    }
299 299
 
@@ -301,7 +301,7 @@  discard block
 block discarded – undo
301 301
 	     * Set the log instance
302 302
 	     * @param Log $logger the log object
303 303
 	     */
304
-	    public function setLogger(Log $logger){
304
+	    public function setLogger(Log $logger) {
305 305
 	      $this->logger = $logger;
306 306
 	      return $this;
307 307
 	    }
@@ -312,7 +312,7 @@  discard block
 block discarded – undo
312 312
 		* @param $key the cache item key
313 313
 		* @return string  		the full cache file path for this key
314 314
 		*/
315
-		private function getFilePath($key){
315
+		private function getFilePath($key) {
316 316
 			return CACHE_PATH . md5($key) . '.cache';
317 317
 		}
318 318
 	}
Please login to merge, or discard this patch.
core/classes/Response.php 2 patches
Spacing   +74 added lines, -74 removed lines patch added patch discarded remove patch
@@ -24,7 +24,7 @@  discard block
 block discarded – undo
24 24
 	 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
25 25
 	*/
26 26
 
27
-	class Response{
27
+	class Response {
28 28
 
29 29
 		/**
30 30
 		 * The list of request header to send with response
@@ -65,9 +65,9 @@  discard block
 block discarded – undo
65 65
 		/**
66 66
 		 * Construct new response instance
67 67
 		 */
68
-		public function __construct(){
69
-			$this->_currentUrl =  (! empty($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : '' )
70
-					. (! empty($_SERVER['QUERY_STRING']) ? ('?' . $_SERVER['QUERY_STRING']) : '' );
68
+		public function __construct() {
69
+			$this->_currentUrl = (!empty($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : '')
70
+					. (!empty($_SERVER['QUERY_STRING']) ? ('?' . $_SERVER['QUERY_STRING']) : '');
71 71
 					
72 72
 			$this->_currentUrlCacheKey = md5($this->_currentUrl);
73 73
 			
@@ -82,9 +82,9 @@  discard block
 block discarded – undo
82 82
 		 * Get the logger singleton instance
83 83
 		 * @return Log the logger instance
84 84
 		 */
85
-		private static function getLogger(){
86
-			if(self::$logger == null){
87
-				self::$logger[0] =& class_loader('Log', 'classes');
85
+		private static function getLogger() {
86
+			if (self::$logger == null) {
87
+				self::$logger[0] = & class_loader('Log', 'classes');
88 88
 				self::$logger[0]->setLogger('Library::Response');
89 89
 			}
90 90
 			return self::$logger[0];
@@ -95,12 +95,12 @@  discard block
 block discarded – undo
95 95
 		 * @param  integer $httpCode the HTTP status code
96 96
 		 * @param  array   $headers   the additional headers to add to the existing headers list
97 97
 		 */
98
-		public static function sendHeaders($httpCode = 200, array $headers = array()){
98
+		public static function sendHeaders($httpCode = 200, array $headers = array()) {
99 99
 			set_http_status_header($httpCode);
100 100
 			self::setHeaders($headers);
101
-			if(! headers_sent()){
102
-				foreach(self::getHeaders() as $key => $value){
103
-					header($key .': '.$value);
101
+			if (!headers_sent()) {
102
+				foreach (self::getHeaders() as $key => $value) {
103
+					header($key . ': ' . $value);
104 104
 				}
105 105
 			}
106 106
 		}
@@ -109,7 +109,7 @@  discard block
 block discarded – undo
109 109
 		 * Get the list of the headers
110 110
 		 * @return array the headers list
111 111
 		 */
112
-		public static function getHeaders(){
112
+		public static function getHeaders() {
113 113
 			return self::$headers;
114 114
 		}
115 115
 
@@ -118,7 +118,7 @@  discard block
 block discarded – undo
118 118
 		 * @param  string $name the header name
119 119
 		 * @return string       the header value
120 120
 		 */
121
-		public static function getHeader($name){
121
+		public static function getHeader($name) {
122 122
 			return array_key_exists($name, self::$headers) ? self::$headers[$name] : null;
123 123
 		}
124 124
 
@@ -128,7 +128,7 @@  discard block
 block discarded – undo
128 128
 		 * @param string $name  the header name
129 129
 		 * @param string $value the header value to be set
130 130
 		 */
131
-		public static function setHeader($name, $value){
131
+		public static function setHeader($name, $value) {
132 132
 			self::$headers[$name] = $value;
133 133
 		}
134 134
 
@@ -137,7 +137,7 @@  discard block
 block discarded – undo
137 137
 		 * @param array $headers the list of the headers to set. 
138 138
 		 * Note: this will merge with the existing headers
139 139
 		 */
140
-		public static function setHeaders(array $headers){
140
+		public static function setHeaders(array $headers) {
141 141
 			self::$headers = array_merge(self::getHeaders(), $headers);
142 142
 		}
143 143
 		
@@ -145,17 +145,17 @@  discard block
 block discarded – undo
145 145
 		 * Redirect user in the specified page
146 146
 		 * @param  string $path the URL or URI to be redirect to
147 147
 		 */
148
-		public static function redirect($path = ''){
148
+		public static function redirect($path = '') {
149 149
 			$logger = self::getLogger();
150 150
 			$url = Url::site_url($path);
151
-			$logger->info('Redirect to URL [' .$url. ']');
152
-			if(! headers_sent()){
153
-				header('Location: '.$url);
151
+			$logger->info('Redirect to URL [' . $url . ']');
152
+			if (!headers_sent()) {
153
+				header('Location: ' . $url);
154 154
 				exit;
155 155
 			}
156
-			else{
156
+			else {
157 157
 				echo '<script>
158
-						location.href = "'.$url.'";
158
+						location.href = "'.$url . '";
159 159
 					</script>';
160 160
 			}
161 161
 		}
@@ -168,10 +168,10 @@  discard block
 block discarded – undo
168 168
 		 * @return void|string          if $return is true will return the view content otherwise
169 169
 		 * will display the view content.
170 170
 		 */
171
-		public function render($view, $data = null, $return = false){
171
+		public function render($view, $data = null, $return = false) {
172 172
 			$logger = self::getLogger();
173 173
 			//convert data to an array
174
-			$data = ! is_array($data) ? (array) $data : $data;
174
+			$data = !is_array($data) ? (array) $data : $data;
175 175
 			$view = str_ireplace('.php', '', $view);
176 176
 			$view = trim($view, '/\\');
177 177
 			$viewFile = $view . '.php';
@@ -180,42 +180,42 @@  discard block
 block discarded – undo
180 180
 			//super instance
181 181
 			$obj = & get_instance();
182 182
 			
183
-			if(Module::hasModule()){
183
+			if (Module::hasModule()) {
184 184
 				//check in module first
185 185
 				$logger->debug('Checking the view [' . $view . '] from module list ...');
186 186
 				$mod = null;
187 187
 				//check if the request class contains module name
188
-				if(strpos($view, '/') !== false){
188
+				if (strpos($view, '/') !== false) {
189 189
 					$viewPath = explode('/', $view);
190
-					if(isset($viewPath[0]) && in_array($viewPath[0], Module::getModuleList())){
190
+					if (isset($viewPath[0]) && in_array($viewPath[0], Module::getModuleList())) {
191 191
 						$mod = $viewPath[0];
192 192
 						array_shift($viewPath);
193 193
 						$view = implode('/', $viewPath);
194 194
 						$viewFile = $view . '.php';
195 195
 					}
196 196
 				}
197
-				if(! $mod && !empty($obj->moduleName)){
197
+				if (!$mod && !empty($obj->moduleName)) {
198 198
 					$mod = $obj->moduleName;
199 199
 				}
200
-				if($mod){
200
+				if ($mod) {
201 201
 					$moduleViewPath = Module::findViewFullPath($view, $mod);
202
-					if($moduleViewPath){
202
+					if ($moduleViewPath) {
203 203
 						$path = $moduleViewPath;
204
-						$logger->info('Found view [' . $view . '] in module [' .$mod. '], the file path is [' .$moduleViewPath. '] we will used it');
204
+						$logger->info('Found view [' . $view . '] in module [' . $mod . '], the file path is [' . $moduleViewPath . '] we will used it');
205 205
 					}
206
-					else{
207
-						$logger->info('Cannot find view [' . $view . '] in module [' .$mod. '] using the default location');
206
+					else {
207
+						$logger->info('Cannot find view [' . $view . '] in module [' . $mod . '] using the default location');
208 208
 					}
209 209
 				}
210
-				else{
210
+				else {
211 211
 					$logger->info('The current request does not use module using the default location.');
212 212
 				}
213 213
 			}
214 214
 			$logger->info('The view file path to be loaded is [' . $path . ']');
215 215
 			$found = false;
216
-			if(file_exists($path)){
217
-				foreach(get_object_vars($obj) as $key => $value){
218
-					if(! isset($this->{$key})){
216
+			if (file_exists($path)) {
217
+				foreach (get_object_vars($obj) as $key => $value) {
218
+					if (!isset($this->{$key})) {
219 219
 						$this->{$key} = & $obj->{$key};
220 220
 					}
221 221
 				}
@@ -224,44 +224,44 @@  discard block
 block discarded – undo
224 224
 				//need use require() instead of require_once because can load this view many time
225 225
 				require $path;
226 226
 				$content = ob_get_clean();
227
-				if($return){
227
+				if ($return) {
228 228
 					return $content;
229 229
 				}
230 230
 				$this->_pageRender .= $content;
231 231
 				$found = true;
232 232
 			}
233
-			if(! $found){
234
-				show_error('Unable to find view [' .$view . ']');
233
+			if (!$found) {
234
+				show_error('Unable to find view [' . $view . ']');
235 235
 			}
236 236
 		}
237 237
 		
238 238
 		/**
239 239
 		* Send the final page output to user
240 240
 		*/
241
-		public function renderFinalPage(){
241
+		public function renderFinalPage() {
242 242
 			$logger = self::getLogger();
243 243
 			$obj = & get_instance();
244 244
 			$cachePageStatus = get_config('cache_enable', false) && !empty($obj->view_cache_enable);
245 245
 			$dispatcher = $obj->eventdispatcher;
246 246
 			$content = $this->_pageRender;
247
-			if(! $content){
247
+			if (!$content) {
248 248
 				$logger->warning('The final view content is empty.');
249 249
 				return;
250 250
 			}
251 251
 			//dispatch
252 252
 			$event = $dispatcher->dispatch(new EventInfo('FINAL_VIEW_READY', $content, true));
253
-			$content = ! empty($event->payload) ? $event->payload : null;
254
-			if(empty($content)){
253
+			$content = !empty($event->payload) ? $event->payload : null;
254
+			if (empty($content)) {
255 255
 				$logger->warning('The view content is empty after dispatch to event listeners.');
256 256
 			}
257 257
 			
258 258
 			//check whether need save the page into cache.
259
-			if($cachePageStatus){
259
+			if ($cachePageStatus) {
260 260
 				//current page URL
261 261
 				$url = $this->_currentUrl;
262 262
 				//Cache view Time to live in second
263 263
 				$viewCacheTtl = get_config('cache_ttl');
264
-				if (!empty($obj->view_cache_ttl)){
264
+				if (!empty($obj->view_cache_ttl)) {
265 265
 					$viewCacheTtl = $obj->view_cache_ttl;
266 266
 				}
267 267
 				//the cache handler instance
@@ -274,14 +274,14 @@  discard block
 block discarded – undo
274 274
 				
275 275
 				//get the cache information to prepare header to send to browser
276 276
 				$cacheInfo = $cacheInstance->getInfo($cacheKey);
277
-				if($cacheInfo){
277
+				if ($cacheInfo) {
278 278
 					$lastModified = $cacheInfo['mtime'];
279 279
 					$expire = $cacheInfo['expire'];
280 280
 					$maxAge = $expire - time();
281 281
 					self::setHeader('Pragma', 'public');
282 282
 					self::setHeader('Cache-Control', 'max-age=' . $maxAge . ', public');
283
-					self::setHeader('Expires', gmdate('D, d M Y H:i:s', $expire).' GMT');
284
-					self::setHeader('Last-modified', gmdate('D, d M Y H:i:s', $lastModified).' GMT');	
283
+					self::setHeader('Expires', gmdate('D, d M Y H:i:s', $expire) . ' GMT');
284
+					self::setHeader('Last-modified', gmdate('D, d M Y H:i:s', $lastModified) . ' GMT');	
285 285
 				}
286 286
 			}
287 287
 			
@@ -293,7 +293,7 @@  discard block
 block discarded – undo
293 293
 			
294 294
 			//compress the output if is available
295 295
 			$type = null;
296
-			if (self::$_canCompressOutput){
296
+			if (self::$_canCompressOutput) {
297 297
 				$type = 'ob_gzhandler';
298 298
 			}
299 299
 			ob_start($type);
@@ -305,7 +305,7 @@  discard block
 block discarded – undo
305 305
 		/**
306 306
 		* Send the final page output to user if is cached
307 307
 		*/
308
-		public function renderFinalPageFromCache(&$cache){
308
+		public function renderFinalPageFromCache(&$cache) {
309 309
 			$logger = self::getLogger();
310 310
 			$url = $this->_currentUrl;					
311 311
 			//the current page cache key for identification
@@ -314,25 +314,25 @@  discard block
 block discarded – undo
314 314
 			$logger->debug('Checking if the page content for the URL [' . $url . '] is cached ...');
315 315
 			//get the cache information to prepare header to send to browser
316 316
 			$cacheInfo = $cache->getInfo($pageCacheKey);
317
-			if($cacheInfo){
317
+			if ($cacheInfo) {
318 318
 				$lastModified = $cacheInfo['mtime'];
319 319
 				$expire = $cacheInfo['expire'];
320 320
 				$maxAge = $expire - $_SERVER['REQUEST_TIME'];
321 321
 				self::setHeader('Pragma', 'public');
322 322
 				self::setHeader('Cache-Control', 'max-age=' . $maxAge . ', public');
323
-				self::setHeader('Expires', gmdate('D, d M Y H:i:s', $expire).' GMT');
324
-				self::setHeader('Last-modified', gmdate('D, d M Y H:i:s', $lastModified).' GMT');
325
-				if (isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) && $lastModified <= strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE'])){
323
+				self::setHeader('Expires', gmdate('D, d M Y H:i:s', $expire) . ' GMT');
324
+				self::setHeader('Last-modified', gmdate('D, d M Y H:i:s', $lastModified) . ' GMT');
325
+				if (isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) && $lastModified <= strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE'])) {
326 326
 					$logger->info('The cache page content is not yet expire for the URL [' . $url . '] send 304 header to browser');
327 327
 					self::sendHeaders(304);
328 328
 					return;
329 329
 				}
330
-				else{
330
+				else {
331 331
 					$logger->info('The cache page content is expired or the browser don\'t send the HTTP_IF_MODIFIED_SINCE header for the URL [' . $url . '] send cache headers to tell the browser');
332 332
 					self::sendHeaders(200);
333 333
 					//get the cache content
334 334
 					$content = $cache->get($pageCacheKey);
335
-					if($content){
335
+					if ($content) {
336 336
 						$logger->info('The page content for the URL [' . $url . '] already cached just display it');
337 337
 						//load benchmark class
338 338
 						$benchmark = & class_loader('Benchmark');
@@ -345,17 +345,17 @@  discard block
 block discarded – undo
345 345
 						
346 346
 						///display the final output
347 347
 						//compress the output if is available
348
-						if (self::$_canCompressOutput){
348
+						if (self::$_canCompressOutput) {
349 349
 							ob_start('ob_gzhandler');
350 350
 						}
351
-						else{
351
+						else {
352 352
 							ob_start();
353 353
 						}
354 354
 						echo $content;
355 355
 						ob_end_flush();
356 356
 						return;
357 357
 					}
358
-					else{
358
+					else {
359 359
 						$logger->info('The page cache content for the URL [' . $url . '] is not valid may be already expired');
360 360
 						$cache->delete($pageCacheKey);
361 361
 					}
@@ -367,7 +367,7 @@  discard block
 block discarded – undo
367 367
 		* Get the final page to be rendered
368 368
 		* @return string
369 369
 		*/
370
-		public function getFinalPageRendered(){
370
+		public function getFinalPageRendered() {
371 371
 			return $this->_pageRender;
372 372
 		}
373 373
 
@@ -375,14 +375,14 @@  discard block
 block discarded – undo
375 375
 		 * Send the HTTP 404 error if can not found the 
376 376
 		 * routing information for the current request
377 377
 		 */
378
-		public static function send404(){
378
+		public static function send404() {
379 379
 			/********* for logs **************/
380 380
 			//can't use $obj = & get_instance()  here because the global super object will be available until
381 381
 			//the main controller is loaded even for Loader::library('xxxx');
382 382
 			$logger = self::getLogger();
383
-			$request =& class_loader('Request', 'classes');
384
-			$userAgent =& class_loader('Browser');
385
-			$browser = $userAgent->getPlatform().', '.$userAgent->getBrowser().' '.$userAgent->getVersion();
383
+			$request = & class_loader('Request', 'classes');
384
+			$userAgent = & class_loader('Browser');
385
+			$browser = $userAgent->getPlatform() . ', ' . $userAgent->getBrowser() . ' ' . $userAgent->getVersion();
386 386
 			
387 387
 			//here can't use Loader::functions just include the helper manually
388 388
 			require_once CORE_FUNCTIONS_PATH . 'function_user_agent.php';
@@ -392,12 +392,12 @@  discard block
 block discarded – undo
392 392
 			$logger->error($str);
393 393
 			/***********************************/
394 394
 			$path = CORE_VIEWS_PATH . '404.php';
395
-			if(file_exists($path)){
395
+			if (file_exists($path)) {
396 396
 				//compress the output if is available
397
-				if (self::$_canCompressOutput){
397
+				if (self::$_canCompressOutput) {
398 398
 					ob_start('ob_gzhandler');
399 399
 				}
400
-				else{
400
+				else {
401 401
 					ob_start();
402 402
 				}
403 403
 				require_once $path;
@@ -405,8 +405,8 @@  discard block
 block discarded – undo
405 405
 				self::sendHeaders(404);
406 406
 				echo $output;
407 407
 			}
408
-			else{
409
-				show_error('The 404 view [' .$path. '] does not exist');
408
+			else {
409
+				show_error('The 404 view [' . $path . '] does not exist');
410 410
 			}
411 411
 		}
412 412
 
@@ -414,14 +414,14 @@  discard block
 block discarded – undo
414 414
 		 * Display the error to user
415 415
 		 * @param  array  $data the error information
416 416
 		 */
417
-		public static function sendError(array $data = array()){
417
+		public static function sendError(array $data = array()) {
418 418
 			$path = CORE_VIEWS_PATH . 'errors.php';
419
-			if(file_exists($path)){
419
+			if (file_exists($path)) {
420 420
 				//compress the output if exists
421
-				if (self::$_canCompressOutput){
421
+				if (self::$_canCompressOutput) {
422 422
 					ob_start('ob_gzhandler');
423 423
 				}
424
-				else{
424
+				else {
425 425
 					ob_start();
426 426
 				}
427 427
 				extract($data);
@@ -430,7 +430,7 @@  discard block
 block discarded – undo
430 430
 				self::sendHeaders(503);
431 431
 				echo $output;
432 432
 			}
433
-			else{
433
+			else {
434 434
 				//can't use show_error() at this time because some dependencies not yet loaded and to prevent loop
435 435
 				set_http_status_header(503);
436 436
 				echo 'The error view [' . $path . '] does not exist';
Please login to merge, or discard this patch.
Braces   +10 added lines, -20 removed lines patch added patch discarded remove patch
@@ -152,8 +152,7 @@  discard block
 block discarded – undo
152 152
 			if(! headers_sent()){
153 153
 				header('Location: '.$url);
154 154
 				exit;
155
-			}
156
-			else{
155
+			} else{
157 156
 				echo '<script>
158 157
 						location.href = "'.$url.'";
159 158
 					</script>';
@@ -202,12 +201,10 @@  discard block
 block discarded – undo
202 201
 					if($moduleViewPath){
203 202
 						$path = $moduleViewPath;
204 203
 						$logger->info('Found view [' . $view . '] in module [' .$mod. '], the file path is [' .$moduleViewPath. '] we will used it');
205
-					}
206
-					else{
204
+					} else{
207 205
 						$logger->info('Cannot find view [' . $view . '] in module [' .$mod. '] using the default location');
208 206
 					}
209
-				}
210
-				else{
207
+				} else{
211 208
 					$logger->info('The current request does not use module using the default location.');
212 209
 				}
213 210
 			}
@@ -326,8 +323,7 @@  discard block
 block discarded – undo
326 323
 					$logger->info('The cache page content is not yet expire for the URL [' . $url . '] send 304 header to browser');
327 324
 					self::sendHeaders(304);
328 325
 					return;
329
-				}
330
-				else{
326
+				} else{
331 327
 					$logger->info('The cache page content is expired or the browser don\'t send the HTTP_IF_MODIFIED_SINCE header for the URL [' . $url . '] send cache headers to tell the browser');
332 328
 					self::sendHeaders(200);
333 329
 					//get the cache content
@@ -347,15 +343,13 @@  discard block
 block discarded – undo
347 343
 						//compress the output if is available
348 344
 						if (self::$_canCompressOutput){
349 345
 							ob_start('ob_gzhandler');
350
-						}
351
-						else{
346
+						} else{
352 347
 							ob_start();
353 348
 						}
354 349
 						echo $content;
355 350
 						ob_end_flush();
356 351
 						return;
357
-					}
358
-					else{
352
+					} else{
359 353
 						$logger->info('The page cache content for the URL [' . $url . '] is not valid may be already expired');
360 354
 						$cache->delete($pageCacheKey);
361 355
 					}
@@ -396,16 +390,14 @@  discard block
 block discarded – undo
396 390
 				//compress the output if is available
397 391
 				if (self::$_canCompressOutput){
398 392
 					ob_start('ob_gzhandler');
399
-				}
400
-				else{
393
+				} else{
401 394
 					ob_start();
402 395
 				}
403 396
 				require_once $path;
404 397
 				$output = ob_get_clean();
405 398
 				self::sendHeaders(404);
406 399
 				echo $output;
407
-			}
408
-			else{
400
+			} else{
409 401
 				show_error('The 404 view [' .$path. '] does not exist');
410 402
 			}
411 403
 		}
@@ -420,8 +412,7 @@  discard block
 block discarded – undo
420 412
 				//compress the output if exists
421 413
 				if (self::$_canCompressOutput){
422 414
 					ob_start('ob_gzhandler');
423
-				}
424
-				else{
415
+				} else{
425 416
 					ob_start();
426 417
 				}
427 418
 				extract($data);
@@ -429,8 +420,7 @@  discard block
 block discarded – undo
429 420
 				$output = ob_get_clean();
430 421
 				self::sendHeaders(503);
431 422
 				echo $output;
432
-			}
433
-			else{
423
+			} else{
434 424
 				//can't use show_error() at this time because some dependencies not yet loaded and to prevent loop
435 425
 				set_http_status_header(503);
436 426
 				echo 'The error view [' . $path . '] does not exist';
Please login to merge, or discard this patch.
core/classes/model/Model.php 1 patch
Indentation   +920 added lines, -920 removed lines patch added patch discarded remove patch
@@ -1,561 +1,561 @@  discard block
 block discarded – undo
1 1
 <?php
2
-    defined('ROOT_PATH') || exit('Access denied');
3
-    /**
4
-     * TNH Framework
5
-     *
6
-     * A simple PHP framework using HMVC architecture
7
-     *
8
-     * This content is released under the GNU GPL License (GPL)
9
-     *
10
-     * Copyright (C) 2017 Tony NGUEREZA
11
-     *
12
-     * This program is free software; you can redistribute it and/or
13
-     * modify it under the terms of the GNU General Public License
14
-     * as published by the Free Software Foundation; either version 3
15
-     * of the License, or (at your option) any later version.
16
-     *
17
-     * This program is distributed in the hope that it will be useful,
18
-     * but WITHOUT ANY WARRANTY; without even the implied warranty of
19
-     * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20
-     * GNU General Public License for more details.
21
-     *
22
-     * You should have received a copy of the GNU General Public License
23
-     * along with this program; if not, write to the Free Software
24
-     * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
25
-    */
26
-
27
-
28
-    /**
29
-     * A base model with a series of CRUD functions (powered by CI's query builder),
30
-     * validation-in-model support, event callbacks and more.
31
-     *
32
-     * @link http://github.com/jamierumbelow/codeigniter-base-model
33
-     * @copyright Copyright (c) 2012, Jamie Rumbelow <http://jamierumbelow.net>
34
-     */
35
-
36
-    class Model{
37
-
38
-        /* --------------------------------------------------------------
2
+	defined('ROOT_PATH') || exit('Access denied');
3
+	/**
4
+	 * TNH Framework
5
+	 *
6
+	 * A simple PHP framework using HMVC architecture
7
+	 *
8
+	 * This content is released under the GNU GPL License (GPL)
9
+	 *
10
+	 * Copyright (C) 2017 Tony NGUEREZA
11
+	 *
12
+	 * This program is free software; you can redistribute it and/or
13
+	 * modify it under the terms of the GNU General Public License
14
+	 * as published by the Free Software Foundation; either version 3
15
+	 * of the License, or (at your option) any later version.
16
+	 *
17
+	 * This program is distributed in the hope that it will be useful,
18
+	 * but WITHOUT ANY WARRANTY; without even the implied warranty of
19
+	 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20
+	 * GNU General Public License for more details.
21
+	 *
22
+	 * You should have received a copy of the GNU General Public License
23
+	 * along with this program; if not, write to the Free Software
24
+	 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
25
+	 */
26
+
27
+
28
+	/**
29
+	 * A base model with a series of CRUD functions (powered by CI's query builder),
30
+	 * validation-in-model support, event callbacks and more.
31
+	 *
32
+	 * @link http://github.com/jamierumbelow/codeigniter-base-model
33
+	 * @copyright Copyright (c) 2012, Jamie Rumbelow <http://jamierumbelow.net>
34
+	 */
35
+
36
+	class Model{
37
+
38
+		/* --------------------------------------------------------------
39 39
          * VARIABLES
40 40
          * ------------------------------------------------------------ */
41 41
 
42
-        /**
43
-         * This model's default database table. Automatically
44
-         * guessed by pluralising the model name.
45
-         */
46
-        protected $_table;
47
-
48
-        /**
49
-         * The database connection object. Will be set to the default
50
-         * connection. This allows individual models to use different DBs
51
-         * without overwriting the global database connection.
52
-         */
53
-        protected $_database;
54
-
55
-        /**
56
-         * This model's default primary key or unique identifier.
57
-         * Used by the get(), update() and delete() functions.
58
-         */
59
-        protected $primary_key = 'id';
60
-
61
-        /**
62
-         * Support for soft deletes and this model's 'deleted' key
63
-         */
64
-        protected $soft_delete = false;
65
-        protected $soft_delete_key = 'is_deleted';
66
-        protected $_temporary_with_deleted = FALSE;
67
-        protected $_temporary_only_deleted = FALSE;
68
-
69
-        /**
70
-         * The various callbacks available to the model. Each are
71
-         * simple lists of method names (methods will be run on $this).
72
-         */
73
-        protected $before_create = array();
74
-        protected $after_create = array();
75
-        protected $before_update = array();
76
-        protected $after_update = array();
77
-        protected $before_get = array();
78
-        protected $after_get = array();
79
-        protected $before_delete = array();
80
-        protected $after_delete = array();
81
-
82
-        protected $callback_parameters = array();
83
-
84
-        /**
85
-         * Protected, non-modifiable attributes
86
-         */
87
-        protected $protected_attributes = array();
88
-
89
-        /**
90
-         * Relationship arrays. Use flat strings for defaults or string
91
-         * => array to customise the class name and primary key
92
-         */
93
-        protected $belongs_to = array();
94
-        protected $has_many = array();
95
-
96
-        protected $_with = array();
97
-
98
-        /**
99
-         * An array of validation rules. This needs to be the same format
100
-         * as validation rules passed to the FormValidation library.
101
-         */
102
-        protected $validate = array();
103
-
104
-        /**
105
-         * Optionally skip the validation. Used in conjunction with
106
-         * skip_validation() to skip data validation for any future calls.
107
-         */
108
-        protected $skip_validation = FALSE;
109
-
110
-        /**
111
-         * By default we return our results as objects. If we need to override
112
-         * this, we can, or, we could use the `as_array()` and `as_object()` scopes.
113
-         */
114
-        protected $return_type = 'object';
115
-
116
-        /**
117
-         * Set return type array or object
118
-         * @var string
119
-         */
120
-        protected $_temporary_return_type = NULL;
42
+		/**
43
+		 * This model's default database table. Automatically
44
+		 * guessed by pluralising the model name.
45
+		 */
46
+		protected $_table;
47
+
48
+		/**
49
+		 * The database connection object. Will be set to the default
50
+		 * connection. This allows individual models to use different DBs
51
+		 * without overwriting the global database connection.
52
+		 */
53
+		protected $_database;
54
+
55
+		/**
56
+		 * This model's default primary key or unique identifier.
57
+		 * Used by the get(), update() and delete() functions.
58
+		 */
59
+		protected $primary_key = 'id';
60
+
61
+		/**
62
+		 * Support for soft deletes and this model's 'deleted' key
63
+		 */
64
+		protected $soft_delete = false;
65
+		protected $soft_delete_key = 'is_deleted';
66
+		protected $_temporary_with_deleted = FALSE;
67
+		protected $_temporary_only_deleted = FALSE;
68
+
69
+		/**
70
+		 * The various callbacks available to the model. Each are
71
+		 * simple lists of method names (methods will be run on $this).
72
+		 */
73
+		protected $before_create = array();
74
+		protected $after_create = array();
75
+		protected $before_update = array();
76
+		protected $after_update = array();
77
+		protected $before_get = array();
78
+		protected $after_get = array();
79
+		protected $before_delete = array();
80
+		protected $after_delete = array();
81
+
82
+		protected $callback_parameters = array();
83
+
84
+		/**
85
+		 * Protected, non-modifiable attributes
86
+		 */
87
+		protected $protected_attributes = array();
88
+
89
+		/**
90
+		 * Relationship arrays. Use flat strings for defaults or string
91
+		 * => array to customise the class name and primary key
92
+		 */
93
+		protected $belongs_to = array();
94
+		protected $has_many = array();
95
+
96
+		protected $_with = array();
97
+
98
+		/**
99
+		 * An array of validation rules. This needs to be the same format
100
+		 * as validation rules passed to the FormValidation library.
101
+		 */
102
+		protected $validate = array();
103
+
104
+		/**
105
+		 * Optionally skip the validation. Used in conjunction with
106
+		 * skip_validation() to skip data validation for any future calls.
107
+		 */
108
+		protected $skip_validation = FALSE;
109
+
110
+		/**
111
+		 * By default we return our results as objects. If we need to override
112
+		 * this, we can, or, we could use the `as_array()` and `as_object()` scopes.
113
+		 */
114
+		protected $return_type = 'object';
115
+
116
+		/**
117
+		 * Set return type array or object
118
+		 * @var string
119
+		 */
120
+		protected $_temporary_return_type = NULL;
121 121
     	
122 122
     	
123
-    	/**
123
+		/**
124 124
     		The database cache time 
125
-    	*/
126
-    	protected $dbCacheTime = 0;
127
-
128
-        /**
129
-         * Instance of the Loader class
130
-         * @var Loader
131
-         */
132
-        protected $loaderInstance = null;
133
-
134
-        /**
135
-         * Instance of the FormValidation library
136
-         * @var FormValidation
137
-         */
138
-        protected $formValidationInstance = null;
125
+		 */
126
+		protected $dbCacheTime = 0;
127
+
128
+		/**
129
+		 * Instance of the Loader class
130
+		 * @var Loader
131
+		 */
132
+		protected $loaderInstance = null;
133
+
134
+		/**
135
+		 * Instance of the FormValidation library
136
+		 * @var FormValidation
137
+		 */
138
+		protected $formValidationInstance = null;
139 139
 		
140
-        /* --------------------------------------------------------------
140
+		/* --------------------------------------------------------------
141 141
          * GENERIC METHODS
142 142
          * ------------------------------------------------------------ */
143 143
 
144
-        /**
145
-         * Initialise the model, tie into the CodeIgniter superobject and
146
-         * try our best to guess the table name.
147
-         */
148
-        public function __construct(Database $db = null){
149
-            if (is_object($db)){
150
-                $this->setDatabaseInstance($db);
151
-            }
152
-            else{
153
-                $obj = & get_instance();
154
-        		if (isset($obj->database) && is_object($obj->database)){
155
-                    /**
156
-                    * NOTE: Need use "clone" because some Model need have the personal instance of the database library
157
-                    * to prevent duplication
158
-                    */
159
-        			$this->setDatabaseInstance(clone $obj->database);
160
-                }
161
-            }
162
-
163
-            array_unshift($this->before_create, 'protect_attributes');
164
-            array_unshift($this->before_update, 'protect_attributes');
165
-            $this->_temporary_return_type = $this->return_type;
166
-        }
167
-
168
-        /* --------------------------------------------------------------
144
+		/**
145
+		 * Initialise the model, tie into the CodeIgniter superobject and
146
+		 * try our best to guess the table name.
147
+		 */
148
+		public function __construct(Database $db = null){
149
+			if (is_object($db)){
150
+				$this->setDatabaseInstance($db);
151
+			}
152
+			else{
153
+				$obj = & get_instance();
154
+				if (isset($obj->database) && is_object($obj->database)){
155
+					/**
156
+					 * NOTE: Need use "clone" because some Model need have the personal instance of the database library
157
+					 * to prevent duplication
158
+					 */
159
+					$this->setDatabaseInstance(clone $obj->database);
160
+				}
161
+			}
162
+
163
+			array_unshift($this->before_create, 'protect_attributes');
164
+			array_unshift($this->before_update, 'protect_attributes');
165
+			$this->_temporary_return_type = $this->return_type;
166
+		}
167
+
168
+		/* --------------------------------------------------------------
169 169
          * CRUD INTERFACE
170 170
          * ------------------------------------------------------------ */
171 171
 
172
-        /**
173
-         * Fetch a single record based on the primary key. Returns an object.
174
-         */
175
-        public function get($primary_value)
176
-        {
177
-    		return $this->get_by($this->primary_key, $primary_value);
178
-        }
179
-
180
-        /**
181
-         * Fetch a single record based on an arbitrary WHERE call. Can be
182
-         * any valid value to DatabaseQueryBuilder->where().
183
-         */
184
-        public function get_by()
185
-        {
186
-            $where = func_get_args();
187
-
188
-            if ($this->soft_delete && $this->_temporary_with_deleted !== TRUE)
189
-            {
190
-                $this->getQueryBuilder()->where($this->soft_delete_key, (bool)$this->_temporary_only_deleted);
191
-            }
192
-    		$this->_set_where($where);
193
-
194
-            $this->trigger('before_get');
172
+		/**
173
+		 * Fetch a single record based on the primary key. Returns an object.
174
+		 */
175
+		public function get($primary_value)
176
+		{
177
+			return $this->get_by($this->primary_key, $primary_value);
178
+		}
179
+
180
+		/**
181
+		 * Fetch a single record based on an arbitrary WHERE call. Can be
182
+		 * any valid value to DatabaseQueryBuilder->where().
183
+		 */
184
+		public function get_by()
185
+		{
186
+			$where = func_get_args();
187
+
188
+			if ($this->soft_delete && $this->_temporary_with_deleted !== TRUE)
189
+			{
190
+				$this->getQueryBuilder()->where($this->soft_delete_key, (bool)$this->_temporary_only_deleted);
191
+			}
192
+			$this->_set_where($where);
193
+
194
+			$this->trigger('before_get');
195 195
 			$type = $this->_temporary_return_type == 'array' ? 'array' : false;
196
-            $this->getQueryBuilder()->from($this->_table);
196
+			$this->getQueryBuilder()->from($this->_table);
197 197
 			$row = $this->_database->get($type);
198
-            $this->_temporary_return_type = $this->return_type;
199
-            $row = $this->trigger('after_get', $row);
200
-            $this->_with = array();
201
-            return $row;
202
-        }
203
-
204
-        /**
205
-         * Fetch an array of records based on an array of primary values.
206
-         */
207
-        public function get_many($values)
208
-        {
209
-            $this->getQueryBuilder()->in($this->primary_key, $values);
210
-            return $this->get_all();
211
-        }
212
-
213
-        /**
214
-         * Fetch an array of records based on an arbitrary WHERE call.
215
-         */
216
-        public function get_many_by()
217
-        {
218
-            $where = func_get_args();
219
-            $this->_set_where($where);
220
-            return $this->get_all();
221
-        }
222
-
223
-        /**
224
-         * Fetch all the records in the table. Can be used as a generic call
225
-         * to $this->_database->get() with scoped methods.
226
-         */
227
-        public function get_all()
228
-        {
229
-            $this->trigger('before_get');
230
-            if ($this->soft_delete && $this->_temporary_with_deleted !== TRUE)
231
-            {
232
-                $this->getQueryBuilder()->where($this->soft_delete_key, (bool)$this->_temporary_only_deleted);
233
-            }
198
+			$this->_temporary_return_type = $this->return_type;
199
+			$row = $this->trigger('after_get', $row);
200
+			$this->_with = array();
201
+			return $row;
202
+		}
203
+
204
+		/**
205
+		 * Fetch an array of records based on an array of primary values.
206
+		 */
207
+		public function get_many($values)
208
+		{
209
+			$this->getQueryBuilder()->in($this->primary_key, $values);
210
+			return $this->get_all();
211
+		}
212
+
213
+		/**
214
+		 * Fetch an array of records based on an arbitrary WHERE call.
215
+		 */
216
+		public function get_many_by()
217
+		{
218
+			$where = func_get_args();
219
+			$this->_set_where($where);
220
+			return $this->get_all();
221
+		}
222
+
223
+		/**
224
+		 * Fetch all the records in the table. Can be used as a generic call
225
+		 * to $this->_database->get() with scoped methods.
226
+		 */
227
+		public function get_all()
228
+		{
229
+			$this->trigger('before_get');
230
+			if ($this->soft_delete && $this->_temporary_with_deleted !== TRUE)
231
+			{
232
+				$this->getQueryBuilder()->where($this->soft_delete_key, (bool)$this->_temporary_only_deleted);
233
+			}
234 234
 			$type = $this->_temporary_return_type == 'array' ? 'array':false;
235
-            $this->getQueryBuilder()->from($this->_table);
235
+			$this->getQueryBuilder()->from($this->_table);
236 236
 			$result = $this->_database->getAll($type);
237
-            $this->_temporary_return_type = $this->return_type;
238
-
239
-            foreach ($result as $key => &$row)
240
-            {
241
-                $row = $this->trigger('after_get', $row, ($key == count($result) - 1));
242
-            }
243
-            $this->_with = array();
244
-            return $result;
245
-        }
246
-
247
-        /**
248
-         * Insert a new row into the table. $data should be an associative array
249
-         * of data to be inserted. Returns newly created ID.
237
+			$this->_temporary_return_type = $this->return_type;
238
+
239
+			foreach ($result as $key => &$row)
240
+			{
241
+				$row = $this->trigger('after_get', $row, ($key == count($result) - 1));
242
+			}
243
+			$this->_with = array();
244
+			return $result;
245
+		}
246
+
247
+		/**
248
+		 * Insert a new row into the table. $data should be an associative array
249
+		 * of data to be inserted. Returns newly created ID.
250 250
 		 * @see Database::insert
251
-         */
252
-        public function insert($data = array(), $skip_validation = FALSE, $escape = true)
253
-        {
254
-            if ($skip_validation === FALSE)
255
-            {
256
-                $data = $this->validate($data);
257
-            }
258
-
259
-            if ($data !== FALSE)
260
-            {
261
-                $data = $this->trigger('before_create', $data);
262
-                $this->getQueryBuilder()->from($this->_table);
251
+		 */
252
+		public function insert($data = array(), $skip_validation = FALSE, $escape = true)
253
+		{
254
+			if ($skip_validation === FALSE)
255
+			{
256
+				$data = $this->validate($data);
257
+			}
258
+
259
+			if ($data !== FALSE)
260
+			{
261
+				$data = $this->trigger('before_create', $data);
262
+				$this->getQueryBuilder()->from($this->_table);
263 263
 				$this->_database->insert($data, $escape);
264
-                $insert_id = $this->_database->insertId();
265
-                $this->trigger('after_create', $insert_id);
264
+				$insert_id = $this->_database->insertId();
265
+				$this->trigger('after_create', $insert_id);
266 266
 				//if the table doesn't have the auto increment field or sequence, the value of 0 will be returned 
267 267
 				return ! $insert_id ? true : $insert_id;
268
-            }
269
-            else
270
-            {
271
-                return FALSE;
272
-            }
273
-        }
274
-
275
-        /**
276
-         * Insert multiple rows into the table. Returns an array of multiple IDs.
277
-         */
278
-        public function insert_many($data = array(), $skip_validation = FALSE, $escape = true)
279
-        {
280
-            $ids = array();
281
-            foreach ($data as $key => $row)
282
-            {
283
-                $ids[] = $this->insert($row, $skip_validation, $escape);
284
-            }
285
-            return $ids;
286
-        }
287
-
288
-        /**
289
-         * Updated a record based on the primary value.
290
-         */
291
-        public function update($primary_value, $data = array(), $skip_validation = FALSE, $escape = true)
292
-        {
293
-            $data = $this->trigger('before_update', $data);
294
-            if ($skip_validation === FALSE)
295
-            {
296
-                $data = $this->validate($data);
297
-            }
298
-
299
-            if ($data !== FALSE)
300
-            {
301
-                $this->getQueryBuilder()->where($this->primary_key, $primary_value)
302
-                                        ->from($this->_table);
303
-                $result = $this->_database->update($data, $escape);
304
-                $this->trigger('after_update', array($data, $result));
305
-                return $result;
306
-            }
307
-            else
308
-            {
309
-                return FALSE;
310
-            }
311
-        }
312
-
313
-        /**
314
-         * Update many records, based on an array of primary values.
315
-         */
316
-        public function update_many($primary_values, $data = array(), $skip_validation = FALSE, $escape = true)
317
-        {
318
-            $data = $this->trigger('before_update', $data);
319
-            if ($skip_validation === FALSE)
320
-            {
321
-                $data = $this->validate($data);
322
-            }
323
-            if ($data !== FALSE)
324
-            {
325
-                $this->getQueryBuilder()->in($this->primary_key, $primary_values)
326
-                                        ->from($this->_table);
268
+			}
269
+			else
270
+			{
271
+				return FALSE;
272
+			}
273
+		}
274
+
275
+		/**
276
+		 * Insert multiple rows into the table. Returns an array of multiple IDs.
277
+		 */
278
+		public function insert_many($data = array(), $skip_validation = FALSE, $escape = true)
279
+		{
280
+			$ids = array();
281
+			foreach ($data as $key => $row)
282
+			{
283
+				$ids[] = $this->insert($row, $skip_validation, $escape);
284
+			}
285
+			return $ids;
286
+		}
287
+
288
+		/**
289
+		 * Updated a record based on the primary value.
290
+		 */
291
+		public function update($primary_value, $data = array(), $skip_validation = FALSE, $escape = true)
292
+		{
293
+			$data = $this->trigger('before_update', $data);
294
+			if ($skip_validation === FALSE)
295
+			{
296
+				$data = $this->validate($data);
297
+			}
298
+
299
+			if ($data !== FALSE)
300
+			{
301
+				$this->getQueryBuilder()->where($this->primary_key, $primary_value)
302
+										->from($this->_table);
303
+				$result = $this->_database->update($data, $escape);
304
+				$this->trigger('after_update', array($data, $result));
305
+				return $result;
306
+			}
307
+			else
308
+			{
309
+				return FALSE;
310
+			}
311
+		}
312
+
313
+		/**
314
+		 * Update many records, based on an array of primary values.
315
+		 */
316
+		public function update_many($primary_values, $data = array(), $skip_validation = FALSE, $escape = true)
317
+		{
318
+			$data = $this->trigger('before_update', $data);
319
+			if ($skip_validation === FALSE)
320
+			{
321
+				$data = $this->validate($data);
322
+			}
323
+			if ($data !== FALSE)
324
+			{
325
+				$this->getQueryBuilder()->in($this->primary_key, $primary_values)
326
+										->from($this->_table);
327 327
 				$result = $this->_database->update($data, $escape);
328
-                $this->trigger('after_update', array($data, $result));
329
-                return $result;
330
-            }
331
-            else
332
-            {
333
-                return FALSE;
334
-            }
335
-        }
336
-
337
-        /**
338
-         * Updated a record based on an arbitrary WHERE clause.
339
-         */
340
-        public function update_by()
341
-        {
342
-            $args = func_get_args();
343
-            $data = array();
344
-            if (count($args) == 2){
345
-                if (is_array($args[1])){
346
-                    $data = array_pop($args);
347
-                }
348
-            }
349
-            else if (count($args) == 3){
350
-                if (is_array($args[2])){
351
-                    $data = array_pop($args);
352
-                }
353
-            }
354
-            $data = $this->trigger('before_update', $data);
355
-            if ($this->validate($data) !== FALSE)
356
-            {
357
-                $this->_set_where($args);
358
-                $this->getQueryBuilder()->from($this->_table);
328
+				$this->trigger('after_update', array($data, $result));
329
+				return $result;
330
+			}
331
+			else
332
+			{
333
+				return FALSE;
334
+			}
335
+		}
336
+
337
+		/**
338
+		 * Updated a record based on an arbitrary WHERE clause.
339
+		 */
340
+		public function update_by()
341
+		{
342
+			$args = func_get_args();
343
+			$data = array();
344
+			if (count($args) == 2){
345
+				if (is_array($args[1])){
346
+					$data = array_pop($args);
347
+				}
348
+			}
349
+			else if (count($args) == 3){
350
+				if (is_array($args[2])){
351
+					$data = array_pop($args);
352
+				}
353
+			}
354
+			$data = $this->trigger('before_update', $data);
355
+			if ($this->validate($data) !== FALSE)
356
+			{
357
+				$this->_set_where($args);
358
+				$this->getQueryBuilder()->from($this->_table);
359 359
 				$result = $this->_database->update($data);
360
-                $this->trigger('after_update', array($data, $result));
361
-                return $result;
362
-            }
363
-            else
364
-            {
365
-                return FALSE;
366
-            }
367
-        }
368
-
369
-        /**
370
-         * Update all records
371
-         */
372
-        public function update_all($data = array(), $escape = true)
373
-        {
374
-            $data = $this->trigger('before_update', $data);
375
-            $this->getQueryBuilder()->from($this->_table);
360
+				$this->trigger('after_update', array($data, $result));
361
+				return $result;
362
+			}
363
+			else
364
+			{
365
+				return FALSE;
366
+			}
367
+		}
368
+
369
+		/**
370
+		 * Update all records
371
+		 */
372
+		public function update_all($data = array(), $escape = true)
373
+		{
374
+			$data = $this->trigger('before_update', $data);
375
+			$this->getQueryBuilder()->from($this->_table);
376 376
 			$result = $this->_database->update($data, $escape);
377
-            $this->trigger('after_update', array($data, $result));
378
-            return $result;
379
-        }
380
-
381
-        /**
382
-         * Delete a row from the table by the primary value
383
-         */
384
-        public function delete($id)
385
-        {
386
-            $this->trigger('before_delete', $id);
387
-            $this->getQueryBuilder()->where($this->primary_key, $id);
377
+			$this->trigger('after_update', array($data, $result));
378
+			return $result;
379
+		}
380
+
381
+		/**
382
+		 * Delete a row from the table by the primary value
383
+		 */
384
+		public function delete($id)
385
+		{
386
+			$this->trigger('before_delete', $id);
387
+			$this->getQueryBuilder()->where($this->primary_key, $id);
388 388
 			$result = false;
389
-            if ($this->soft_delete)
390
-            {
391
-                $this->getQueryBuilder()->from($this->_table);	
389
+			if ($this->soft_delete)
390
+			{
391
+				$this->getQueryBuilder()->from($this->_table);	
392 392
 				$result = $this->_database->update(array( $this->soft_delete_key => TRUE ));
393
-            }
394
-            else
395
-            {
396
-                $this->getQueryBuilder()->from($this->_table); 
393
+			}
394
+			else
395
+			{
396
+				$this->getQueryBuilder()->from($this->_table); 
397 397
 				$result = $this->_database->delete();
398
-            }
399
-
400
-            $this->trigger('after_delete', $result);
401
-            return $result;
402
-        }
403
-
404
-        /**
405
-         * Delete a row from the database table by an arbitrary WHERE clause
406
-         */
407
-        public function delete_by()
408
-        {
409
-            $where = func_get_args();
410
-    	    $where = $this->trigger('before_delete', $where);
411
-            $this->_set_where($where);
398
+			}
399
+
400
+			$this->trigger('after_delete', $result);
401
+			return $result;
402
+		}
403
+
404
+		/**
405
+		 * Delete a row from the database table by an arbitrary WHERE clause
406
+		 */
407
+		public function delete_by()
408
+		{
409
+			$where = func_get_args();
410
+			$where = $this->trigger('before_delete', $where);
411
+			$this->_set_where($where);
412 412
 			$result = false;
413
-            if ($this->soft_delete)
414
-            {
415
-                $this->getQueryBuilder()->from($this->_table);	
413
+			if ($this->soft_delete)
414
+			{
415
+				$this->getQueryBuilder()->from($this->_table);	
416 416
 				$result = $this->_database->update(array( $this->soft_delete_key => TRUE ));
417
-            }
418
-            else
419
-            {
420
-                $this->getQueryBuilder()->from($this->_table); 
417
+			}
418
+			else
419
+			{
420
+				$this->getQueryBuilder()->from($this->_table); 
421 421
 				$result = $this->_database->delete();
422
-            }
423
-            $this->trigger('after_delete', $result);
424
-            return $result;
425
-        }
426
-
427
-        /**
428
-         * Delete many rows from the database table by multiple primary values
429
-         */
430
-        public function delete_many($primary_values)
431
-        {
432
-            $primary_values = $this->trigger('before_delete', $primary_values);
433
-            $this->getQueryBuilder()->in($this->primary_key, $primary_values);
422
+			}
423
+			$this->trigger('after_delete', $result);
424
+			return $result;
425
+		}
426
+
427
+		/**
428
+		 * Delete many rows from the database table by multiple primary values
429
+		 */
430
+		public function delete_many($primary_values)
431
+		{
432
+			$primary_values = $this->trigger('before_delete', $primary_values);
433
+			$this->getQueryBuilder()->in($this->primary_key, $primary_values);
434 434
 			$result = false;
435
-            if ($this->soft_delete)
436
-            {
437
-                $this->getQueryBuilder()->from($this->_table);	
435
+			if ($this->soft_delete)
436
+			{
437
+				$this->getQueryBuilder()->from($this->_table);	
438 438
 				$result = $this->_database->update(array( $this->soft_delete_key => TRUE ));
439
-            }
440
-            else
441
-            {
442
-                $this->getQueryBuilder()->from($this->_table); 
439
+			}
440
+			else
441
+			{
442
+				$this->getQueryBuilder()->from($this->_table); 
443 443
 				$result = $this->_database->delete();
444
-            }
445
-            $this->trigger('after_delete', $result);
446
-            return $result;
447
-        }
444
+			}
445
+			$this->trigger('after_delete', $result);
446
+			return $result;
447
+		}
448 448
 
449 449
 
450
-        /**
451
-         * Truncates the table
452
-         */
453
-        public function truncate()
454
-        {
450
+		/**
451
+		 * Truncates the table
452
+		 */
453
+		public function truncate()
454
+		{
455 455
 			$this->getQueryBuilder()->from($this->_table); 
456 456
 			$result = $this->_database->delete();
457
-            return $result;
458
-        }
457
+			return $result;
458
+		}
459 459
 
460
-        /* --------------------------------------------------------------
460
+		/* --------------------------------------------------------------
461 461
          * RELATIONSHIPS
462 462
          * ------------------------------------------------------------ */
463 463
 
464
-        public function with($relationship)
465
-        {
466
-            $this->_with[] = $relationship;
467
-            if (!in_array('relate', $this->after_get))
468
-            {
469
-                $this->after_get[] = 'relate';
470
-            }
471
-            return $this;
472
-        }
464
+		public function with($relationship)
465
+		{
466
+			$this->_with[] = $relationship;
467
+			if (!in_array('relate', $this->after_get))
468
+			{
469
+				$this->after_get[] = 'relate';
470
+			}
471
+			return $this;
472
+		}
473 473
 		
474 474
 		/**
475
-		* Relationship
476
-		*/
477
-        public function relate($row)
478
-        {
479
-    		if (empty($row))
480
-            {
481
-    		    return $row;
482
-            }
483
-
484
-            $row = $this->relateBelongsTo($row);
485
-            $row = $this->relateHasMany($row);
486
-            return $row;
487
-        }
488
-
489
-        /* --------------------------------------------------------------
475
+		 * Relationship
476
+		 */
477
+		public function relate($row)
478
+		{
479
+			if (empty($row))
480
+			{
481
+				return $row;
482
+			}
483
+
484
+			$row = $this->relateBelongsTo($row);
485
+			$row = $this->relateHasMany($row);
486
+			return $row;
487
+		}
488
+
489
+		/* --------------------------------------------------------------
490 490
          * UTILITY METHODS
491 491
          * ------------------------------------------------------------ */
492 492
 
493
-        /**
494
-         * Retrieve and generate a form_dropdown friendly array
495
-         */
496
-        public function dropdown()
497
-        {
498
-            $args = func_get_args();
499
-            if (count($args) == 2)
500
-            {
501
-                list($key, $value) = $args;
502
-            }
503
-            else
504
-            {
505
-                $key = $this->primary_key;
506
-                $value = $args[0];
507
-            }
508
-            $this->trigger('before_dropdown', array( $key, $value ));
509
-            if ($this->soft_delete && $this->_temporary_with_deleted !== TRUE)
510
-            {
511
-                $this->getQueryBuilder()->where($this->soft_delete_key, FALSE);
512
-            }
513
-            $this->getQueryBuilder()
493
+		/**
494
+		 * Retrieve and generate a form_dropdown friendly array
495
+		 */
496
+		public function dropdown()
497
+		{
498
+			$args = func_get_args();
499
+			if (count($args) == 2)
500
+			{
501
+				list($key, $value) = $args;
502
+			}
503
+			else
504
+			{
505
+				$key = $this->primary_key;
506
+				$value = $args[0];
507
+			}
508
+			$this->trigger('before_dropdown', array( $key, $value ));
509
+			if ($this->soft_delete && $this->_temporary_with_deleted !== TRUE)
510
+			{
511
+				$this->getQueryBuilder()->where($this->soft_delete_key, FALSE);
512
+			}
513
+			$this->getQueryBuilder()
514 514
 									 ->select(array($key, $value))
515 515
 									 ->from($this->_table);
516 516
 			$result = $this->_database->getAll();
517
-            $options = array();
518
-            foreach ($result as $row)
519
-            {
520
-                $options[$row->{$key}] = $row->{$value};
521
-            }
522
-            $options = $this->trigger('after_dropdown', $options);
523
-            return $options;
524
-        }
525
-
526
-        /**
527
-         * Fetch a count of rows based on an arbitrary WHERE call.
528
-         */
529
-        public function count_by()
530
-        {
531
-            if ($this->soft_delete && $this->_temporary_with_deleted !== TRUE)
532
-            {
533
-                $this->getQueryBuilder()->where($this->soft_delete_key, (bool)$this->_temporary_only_deleted);
534
-            }
535
-            $where = func_get_args();
536
-            $this->_set_where($where);
537
-            $this->getQueryBuilder()->from($this->_table);
517
+			$options = array();
518
+			foreach ($result as $row)
519
+			{
520
+				$options[$row->{$key}] = $row->{$value};
521
+			}
522
+			$options = $this->trigger('after_dropdown', $options);
523
+			return $options;
524
+		}
525
+
526
+		/**
527
+		 * Fetch a count of rows based on an arbitrary WHERE call.
528
+		 */
529
+		public function count_by()
530
+		{
531
+			if ($this->soft_delete && $this->_temporary_with_deleted !== TRUE)
532
+			{
533
+				$this->getQueryBuilder()->where($this->soft_delete_key, (bool)$this->_temporary_only_deleted);
534
+			}
535
+			$where = func_get_args();
536
+			$this->_set_where($where);
537
+			$this->getQueryBuilder()->from($this->_table);
538 538
 			$this->_database->getAll();
539
-            return $this->_database->numRows();
540
-        }
541
-
542
-        /**
543
-         * Fetch a total count of rows, disregarding any previous conditions
544
-         */
545
-        public function count_all()
546
-        {
547
-            if ($this->soft_delete && $this->_temporary_with_deleted !== TRUE)
548
-            {
549
-                $this->getQueryBuilder()->where($this->soft_delete_key, (bool)$this->_temporary_only_deleted);
550
-            }
539
+			return $this->_database->numRows();
540
+		}
541
+
542
+		/**
543
+		 * Fetch a total count of rows, disregarding any previous conditions
544
+		 */
545
+		public function count_all()
546
+		{
547
+			if ($this->soft_delete && $this->_temporary_with_deleted !== TRUE)
548
+			{
549
+				$this->getQueryBuilder()->where($this->soft_delete_key, (bool)$this->_temporary_only_deleted);
550
+			}
551 551
 			$this->getQueryBuilder()->from($this->_table);
552 552
 			$this->_database->getAll();
553
-            return $this->_database->numRows();
554
-        }
553
+			return $this->_database->numRows();
554
+		}
555 555
 		
556 556
 		/**
557
-		* Enabled cache temporary
558
-		*/
557
+		 * Enabled cache temporary
558
+		 */
559 559
 		public function cached($ttl = 0){
560 560
 		  if ($ttl > 0){
561 561
 			$this->_database = $this->_database->cached($ttl);
@@ -563,424 +563,424 @@  discard block
 block discarded – undo
563 563
 		  return $this;
564 564
 		}
565 565
 
566
-        /**
567
-         * Tell the class to skip the insert validation
568
-         */
569
-        public function skip_validation()
570
-        {
571
-            $this->skip_validation = TRUE;
572
-            return $this;
573
-        }
574
-
575
-        /**
576
-         * Get the skip validation status
577
-         */
578
-        public function get_skip_validation()
579
-        {
580
-            return $this->skip_validation;
581
-        }
582
-
583
-        /**
584
-         * Return the next auto increment of the table. Only tested on MySQL.
585
-         */
586
-        public function get_next_id()
587
-        {
566
+		/**
567
+		 * Tell the class to skip the insert validation
568
+		 */
569
+		public function skip_validation()
570
+		{
571
+			$this->skip_validation = TRUE;
572
+			return $this;
573
+		}
574
+
575
+		/**
576
+		 * Get the skip validation status
577
+		 */
578
+		public function get_skip_validation()
579
+		{
580
+			return $this->skip_validation;
581
+		}
582
+
583
+		/**
584
+		 * Return the next auto increment of the table. Only tested on MySQL.
585
+		 */
586
+		public function get_next_id()
587
+		{
588 588
 			$this->getQueryBuilder()->select('AUTO_INCREMENT')
589 589
 									->from('information_schema.TABLES')
590 590
 									->where('TABLE_NAME', $this->_table)
591 591
 									->where('TABLE_SCHEMA', $this->_database->getDatabaseName());
592
-            return (int) $this->_database->get()->AUTO_INCREMENT;
593
-        }
594
-
595
-        /**
596
-         * Getter for the table name
597
-         */
598
-        public function table()
599
-        {
600
-            return $this->_table;
601
-        }
602
-
603
-        /* --------------------------------------------------------------
592
+			return (int) $this->_database->get()->AUTO_INCREMENT;
593
+		}
594
+
595
+		/**
596
+		 * Getter for the table name
597
+		 */
598
+		public function table()
599
+		{
600
+			return $this->_table;
601
+		}
602
+
603
+		/* --------------------------------------------------------------
604 604
          * GLOBAL SCOPES
605 605
          * ------------------------------------------------------------ */
606 606
 
607
-        /**
608
-         * Return the next call as an array rather than an object
609
-         */
610
-        public function as_array()
611
-        {
612
-            $this->_temporary_return_type = 'array';
613
-            return $this;
614
-        }
615
-
616
-        /**
617
-         * Return the next call as an object rather than an array
618
-         */
619
-        public function as_object()
620
-        {
621
-            $this->_temporary_return_type = 'object';
622
-            return $this;
623
-        }
624
-
625
-        /**
626
-         * Don't care about soft deleted rows on the next call
627
-         */
628
-        public function with_deleted()
629
-        {
630
-            $this->_temporary_with_deleted = TRUE;
631
-            return $this;
632
-        }
633
-
634
-        /**
635
-         * Only get deleted rows on the next call
636
-         */
637
-        public function only_deleted()
638
-        {
639
-            $this->_temporary_only_deleted = TRUE;
640
-            return $this;
641
-        }
642
-
643
-        /* --------------------------------------------------------------
607
+		/**
608
+		 * Return the next call as an array rather than an object
609
+		 */
610
+		public function as_array()
611
+		{
612
+			$this->_temporary_return_type = 'array';
613
+			return $this;
614
+		}
615
+
616
+		/**
617
+		 * Return the next call as an object rather than an array
618
+		 */
619
+		public function as_object()
620
+		{
621
+			$this->_temporary_return_type = 'object';
622
+			return $this;
623
+		}
624
+
625
+		/**
626
+		 * Don't care about soft deleted rows on the next call
627
+		 */
628
+		public function with_deleted()
629
+		{
630
+			$this->_temporary_with_deleted = TRUE;
631
+			return $this;
632
+		}
633
+
634
+		/**
635
+		 * Only get deleted rows on the next call
636
+		 */
637
+		public function only_deleted()
638
+		{
639
+			$this->_temporary_only_deleted = TRUE;
640
+			return $this;
641
+		}
642
+
643
+		/* --------------------------------------------------------------
644 644
          * OBSERVERS
645 645
          * ------------------------------------------------------------ */
646 646
 
647
-        /**
648
-         * MySQL DATETIME created_at and updated_at
649
-         */
650
-        public function created_at($row)
651
-        {
652
-            if (is_object($row))
653
-            {
654
-                $row->created_at = date('Y-m-d H:i:s');
655
-            }
656
-            else
657
-            {
658
-                $row['created_at'] = date('Y-m-d H:i:s');
659
-            }
660
-            return $row;
661
-        }
662
-
663
-        public function updated_at($row)
664
-        {
665
-            if (is_object($row))
666
-            {
667
-                $row->updated_at = date('Y-m-d H:i:s');
668
-            }
669
-            else
670
-            {
671
-                $row['updated_at'] = date('Y-m-d H:i:s');
672
-            }
673
-            return $row;
674
-        }
675
-
676
-        /**
677
-         * Serialises data for you automatically, allowing you to pass
678
-         * through objects and let it handle the serialisation in the background
679
-         */
680
-        public function serialize($row)
681
-        {
682
-            foreach ($this->callback_parameters as $column)
683
-            {
684
-                $row[$column] = serialize($row[$column]);
685
-            }
686
-            return $row;
687
-        }
688
-
689
-        public function unserialize($row)
690
-        {
691
-            foreach ($this->callback_parameters as $column)
692
-            {
693
-                if (is_array($row))
694
-                {
695
-                    $row[$column] = unserialize($row[$column]);
696
-                }
697
-                else
698
-                {
699
-                    $row->$column = unserialize($row->$column);
700
-                }
701
-            }
702
-            return $row;
703
-        }
704
-
705
-        /**
706
-         * Protect attributes by removing them from $row array
707
-         */
708
-        public function protect_attributes($row)
709
-        {
710
-            foreach ($this->protected_attributes as $attr)
711
-            {
712
-                if (is_object($row))
713
-                {
647
+		/**
648
+		 * MySQL DATETIME created_at and updated_at
649
+		 */
650
+		public function created_at($row)
651
+		{
652
+			if (is_object($row))
653
+			{
654
+				$row->created_at = date('Y-m-d H:i:s');
655
+			}
656
+			else
657
+			{
658
+				$row['created_at'] = date('Y-m-d H:i:s');
659
+			}
660
+			return $row;
661
+		}
662
+
663
+		public function updated_at($row)
664
+		{
665
+			if (is_object($row))
666
+			{
667
+				$row->updated_at = date('Y-m-d H:i:s');
668
+			}
669
+			else
670
+			{
671
+				$row['updated_at'] = date('Y-m-d H:i:s');
672
+			}
673
+			return $row;
674
+		}
675
+
676
+		/**
677
+		 * Serialises data for you automatically, allowing you to pass
678
+		 * through objects and let it handle the serialisation in the background
679
+		 */
680
+		public function serialize($row)
681
+		{
682
+			foreach ($this->callback_parameters as $column)
683
+			{
684
+				$row[$column] = serialize($row[$column]);
685
+			}
686
+			return $row;
687
+		}
688
+
689
+		public function unserialize($row)
690
+		{
691
+			foreach ($this->callback_parameters as $column)
692
+			{
693
+				if (is_array($row))
694
+				{
695
+					$row[$column] = unserialize($row[$column]);
696
+				}
697
+				else
698
+				{
699
+					$row->$column = unserialize($row->$column);
700
+				}
701
+			}
702
+			return $row;
703
+		}
704
+
705
+		/**
706
+		 * Protect attributes by removing them from $row array
707
+		 */
708
+		public function protect_attributes($row)
709
+		{
710
+			foreach ($this->protected_attributes as $attr)
711
+			{
712
+				if (is_object($row))
713
+				{
714 714
 					if (isset($row->$attr)){
715 715
 						unset($row->$attr);
716 716
 					}
717
-                }
718
-                else
719
-                {
717
+				}
718
+				else
719
+				{
720 720
 					if (isset($row[$attr])){
721 721
 						unset($row[$attr]);
722 722
 					}
723
-                }
724
-            }
725
-            return $row;
726
-        }
723
+				}
724
+			}
725
+			return $row;
726
+		}
727 727
 		
728 728
 		 /**
729
-         * Return the database instance
730
-         * @return Database the database instance
731
-         */
732
-        public function getDatabaseInstance(){
733
-            return $this->_database;
734
-        }
735
-
736
-        /**
737
-         * set the Database instance for future use
738
-         * @param Database $db the database object
739
-         */
740
-         public function setDatabaseInstance($db){
741
-            $this->_database = $db;
742
-            if ($this->dbCacheTime > 0){
743
-                $this->_database->setCache($this->dbCacheTime);
744
-            }
745
-            return $this;
746
-        }
747
-
748
-        /**
749
-         * Return the loader instance
750
-         * @return Loader the loader instance
751
-         */
752
-        public function getLoader(){
753
-            return $this->loaderInstance;
754
-        }
755
-
756
-        /**
757
-         * Set the loader instance for future use
758
-         * @param Loader $loader the loader object
729
+		  * Return the database instance
730
+		  * @return Database the database instance
731
+		  */
732
+		public function getDatabaseInstance(){
733
+			return $this->_database;
734
+		}
735
+
736
+		/**
737
+		 * set the Database instance for future use
738
+		 * @param Database $db the database object
739
+		 */
740
+		 public function setDatabaseInstance($db){
741
+			$this->_database = $db;
742
+			if ($this->dbCacheTime > 0){
743
+				$this->_database->setCache($this->dbCacheTime);
744
+			}
745
+			return $this;
746
+		}
747
+
748
+		/**
749
+		 * Return the loader instance
750
+		 * @return Loader the loader instance
751
+		 */
752
+		public function getLoader(){
753
+			return $this->loaderInstance;
754
+		}
755
+
756
+		/**
757
+		 * Set the loader instance for future use
758
+		 * @param Loader $loader the loader object
759 759
 		 * @return object
760
-         */
761
-         public function setLoader($loader){
762
-            $this->loaderInstance = $loader;
763
-            return $this;
764
-        }
760
+		 */
761
+		 public function setLoader($loader){
762
+			$this->loaderInstance = $loader;
763
+			return $this;
764
+		}
765
+
766
+		/**
767
+		 * Return the queryBuilder instance this is the shortcut to database queryBuilder
768
+		 * @return object the DatabaseQueryBuilder instance
769
+		 */
770
+		public function getQueryBuilder(){
771
+			return $this->_database->getQueryBuilder();
772
+		}
765 773
 
766 774
 		/**
767
-         * Return the queryBuilder instance this is the shortcut to database queryBuilder
768
-         * @return object the DatabaseQueryBuilder instance
769
-         */
770
-        public function getQueryBuilder(){
771
-            return $this->_database->getQueryBuilder();
772
-        }
773
-
774
-        /**
775
-         * Set the DatabaseQueryBuilder instance for future use
776
-         * @param object $queryBuilder the DatabaseQueryBuilder object
775
+		 * Set the DatabaseQueryBuilder instance for future use
776
+		 * @param object $queryBuilder the DatabaseQueryBuilder object
777 777
 		 * @return object
778
-         */
779
-         public function setQueryBuilder($queryBuilder){
780
-            $this->_database->setQueryBuilder($queryBuilder);
781
-            return $this;
782
-        }
778
+		 */
779
+		 public function setQueryBuilder($queryBuilder){
780
+			$this->_database->setQueryBuilder($queryBuilder);
781
+			return $this;
782
+		}
783 783
 
784 784
 		
785
-        /**
786
-         * Return the FormValidation instance
787
-         * @return FormValidation the form validation instance
788
-         */
789
-        public function getFormValidation(){
790
-            return $this->formValidationInstance;
791
-        }
792
-
793
-        /**
794
-         * Set the form validation instance for future use
795
-         * @param FormValidation $fv the form validation object
785
+		/**
786
+		 * Return the FormValidation instance
787
+		 * @return FormValidation the form validation instance
788
+		 */
789
+		public function getFormValidation(){
790
+			return $this->formValidationInstance;
791
+		}
792
+
793
+		/**
794
+		 * Set the form validation instance for future use
795
+		 * @param FormValidation $fv the form validation object
796 796
 		 * @return object
797
-         */
798
-         public function setFormValidation($fv){
799
-            $this->formValidationInstance = $fv;
800
-            return $this;
801
-        }
797
+		 */
798
+		 public function setFormValidation($fv){
799
+			$this->formValidationInstance = $fv;
800
+			return $this;
801
+		}
802 802
 
803
-        /* --------------------------------------------------------------
803
+		/* --------------------------------------------------------------
804 804
          * QUERY BUILDER DIRECT ACCESS METHODS
805 805
          * ------------------------------------------------------------ */
806 806
 
807
-        /**
808
-         * A wrapper to $this->getQueryBuilder()->orderBy()
809
-         */
810
-        public function order_by($criteria, $order = 'ASC')
811
-        {
812
-            if ( is_array($criteria) )
813
-            {
814
-                foreach ($criteria as $key => $value)
815
-                {
816
-                    $this->getQueryBuilder()->orderBy($key, $value);
817
-                }
818
-            }
819
-            else
820
-            {
821
-                $this->getQueryBuilder()->orderBy($criteria, $order);
822
-            }
823
-            return $this;
824
-        }
825
-
826
-        /**
827
-         * A wrapper to $this->getQueryBuilder()->limit()
828
-         */
829
-        public function limit($offset = 0, $limit = 10)
830
-        {
831
-            $this->getQueryBuilder()->limit($offset, $limit);
832
-            return $this;
833
-        }
834
-
835
-        /* --------------------------------------------------------------
807
+		/**
808
+		 * A wrapper to $this->getQueryBuilder()->orderBy()
809
+		 */
810
+		public function order_by($criteria, $order = 'ASC')
811
+		{
812
+			if ( is_array($criteria) )
813
+			{
814
+				foreach ($criteria as $key => $value)
815
+				{
816
+					$this->getQueryBuilder()->orderBy($key, $value);
817
+				}
818
+			}
819
+			else
820
+			{
821
+				$this->getQueryBuilder()->orderBy($criteria, $order);
822
+			}
823
+			return $this;
824
+		}
825
+
826
+		/**
827
+		 * A wrapper to $this->getQueryBuilder()->limit()
828
+		 */
829
+		public function limit($offset = 0, $limit = 10)
830
+		{
831
+			$this->getQueryBuilder()->limit($offset, $limit);
832
+			return $this;
833
+		}
834
+
835
+		/* --------------------------------------------------------------
836 836
          * INTERNAL METHODS
837 837
          * ------------------------------------------------------------ */
838 838
 
839 839
 		/**
840
-		* relate for the relation "belongs_to"
841
-		* @return mixed
842
-		*/
840
+		 * relate for the relation "belongs_to"
841
+		 * @return mixed
842
+		 */
843 843
 		protected function relateBelongsTo($row){
844 844
 			foreach ($this->belongs_to as $key => $value)
845
-            {
846
-                if (is_string($value))
847
-                {
848
-                    $relationship = $value;
849
-                    $options = array( 'primary_key' => $value . '_id', 'model' => $value . '_model' );
850
-                }
851
-                else
852
-                {
853
-                    $relationship = $key;
854
-                    $options = $value;
855
-                }
856
-
857
-                if (in_array($relationship, $this->_with))
858
-                {
859
-                    if (is_object($this->loaderInstance)){
860
-                        $this->loaderInstance->model($options['model'], $relationship . '_model');
861
-                    }
862
-                    else{
863
-                        Loader::model($options['model'], $relationship . '_model');    
864
-                    }
865
-                    if (is_object($row))
866
-                    {
867
-                        $row->{$relationship} = $this->{$relationship . '_model'}->get($row->{$options['primary_key']});
868
-                    }
869
-                    else
870
-                    {
871
-                        $row[$relationship] = $this->{$relationship . '_model'}->get($row[$options['primary_key']]);
872
-                    }
873
-                }
874
-            }
845
+			{
846
+				if (is_string($value))
847
+				{
848
+					$relationship = $value;
849
+					$options = array( 'primary_key' => $value . '_id', 'model' => $value . '_model' );
850
+				}
851
+				else
852
+				{
853
+					$relationship = $key;
854
+					$options = $value;
855
+				}
856
+
857
+				if (in_array($relationship, $this->_with))
858
+				{
859
+					if (is_object($this->loaderInstance)){
860
+						$this->loaderInstance->model($options['model'], $relationship . '_model');
861
+					}
862
+					else{
863
+						Loader::model($options['model'], $relationship . '_model');    
864
+					}
865
+					if (is_object($row))
866
+					{
867
+						$row->{$relationship} = $this->{$relationship . '_model'}->get($row->{$options['primary_key']});
868
+					}
869
+					else
870
+					{
871
+						$row[$relationship] = $this->{$relationship . '_model'}->get($row[$options['primary_key']]);
872
+					}
873
+				}
874
+			}
875 875
 			return $row;
876 876
 		}
877 877
 
878 878
 		/**
879
-		* relate for the relation "has_many"
880
-		* @return mixed
881
-		*/
879
+		 * relate for the relation "has_many"
880
+		 * @return mixed
881
+		 */
882 882
 		protected function relateHasMany($row){
883 883
 			foreach ($this->has_many as $key => $value)
884
-            {
885
-                if (is_string($value))
886
-                {
887
-                    $relationship = $value;
888
-                    $options = array( 'primary_key' => $this->_table . '_id', 'model' => $value . '_model' );
889
-                }
890
-                else
891
-                {
892
-                    $relationship = $key;
893
-                    $options = $value;
894
-                }
895
-
896
-                if (in_array($relationship, $this->_with))
897
-                {
898
-                    if (is_object($this->loaderInstance)){
899
-                        $this->loaderInstance->model($options['model'], $relationship . '_model');
900
-                    }
901
-                    else{
902
-                        Loader::model($options['model'], $relationship . '_model');    
903
-                    }
904
-                    if (is_object($row))
905
-                    {
906
-                        $row->{$relationship} = $this->{$relationship . '_model'}->get_many_by($options['primary_key'], $row->{$this->primary_key});
907
-                    }
908
-                    else
909
-                    {
910
-                        $row[$relationship] = $this->{$relationship . '_model'}->get_many_by($options['primary_key'], $row[$this->primary_key]);
911
-                    }
912
-                }
913
-            }
884
+			{
885
+				if (is_string($value))
886
+				{
887
+					$relationship = $value;
888
+					$options = array( 'primary_key' => $this->_table . '_id', 'model' => $value . '_model' );
889
+				}
890
+				else
891
+				{
892
+					$relationship = $key;
893
+					$options = $value;
894
+				}
895
+
896
+				if (in_array($relationship, $this->_with))
897
+				{
898
+					if (is_object($this->loaderInstance)){
899
+						$this->loaderInstance->model($options['model'], $relationship . '_model');
900
+					}
901
+					else{
902
+						Loader::model($options['model'], $relationship . '_model');    
903
+					}
904
+					if (is_object($row))
905
+					{
906
+						$row->{$relationship} = $this->{$relationship . '_model'}->get_many_by($options['primary_key'], $row->{$this->primary_key});
907
+					}
908
+					else
909
+					{
910
+						$row[$relationship] = $this->{$relationship . '_model'}->get_many_by($options['primary_key'], $row[$this->primary_key]);
911
+					}
912
+				}
913
+			}
914 914
 			return $row;
915 915
 		}
916 916
 		
917
-        /**
918
-         * Trigger an event and call its observers. Pass through the event name
919
-         * (which looks for an instance variable $this->event_name), an array of
920
-         * parameters to pass through and an optional 'last in interation' boolean
921
-         */
922
-        protected function trigger($event, $data = FALSE, $last = TRUE)
923
-        {
924
-            if (isset($this->$event) && is_array($this->$event))
925
-            {
926
-                foreach ($this->$event as $method)
927
-                {
928
-                    if (strpos($method, '('))
929
-                    {
930
-                        preg_match('/([a-zA-Z0-9\_\-]+)(\(([a-zA-Z0-9\_\-\., ]+)\))?/', $method, $matches);
931
-                        $method = $matches[1];
932
-                        $this->callback_parameters = explode(',', $matches[3]);
933
-                    }
934
-                    $data = call_user_func_array(array($this, $method), array($data, $last));
935
-                }
936
-            }
937
-            return $data;
938
-        }
939
-
940
-        /**
941
-         * Run validation on the passed data
942
-         */
943
-        protected function validate(array $data)
944
-        {
945
-            if ($this->skip_validation)
946
-            {
947
-                return $data;
948
-            }
949
-            if (!empty($this->validate))
950
-            {
951
-                $fv = null;
952
-                if (is_object($this->formValidationInstance)){
953
-                    $fv = $this->formValidationInstance;
954
-                }
955
-                else{
956
-                    Loader::library('FormValidation');
957
-                    $fv = $this->formvalidation;
958
-                    $this->setFormValidation($fv);
959
-                }
917
+		/**
918
+		 * Trigger an event and call its observers. Pass through the event name
919
+		 * (which looks for an instance variable $this->event_name), an array of
920
+		 * parameters to pass through and an optional 'last in interation' boolean
921
+		 */
922
+		protected function trigger($event, $data = FALSE, $last = TRUE)
923
+		{
924
+			if (isset($this->$event) && is_array($this->$event))
925
+			{
926
+				foreach ($this->$event as $method)
927
+				{
928
+					if (strpos($method, '('))
929
+					{
930
+						preg_match('/([a-zA-Z0-9\_\-]+)(\(([a-zA-Z0-9\_\-\., ]+)\))?/', $method, $matches);
931
+						$method = $matches[1];
932
+						$this->callback_parameters = explode(',', $matches[3]);
933
+					}
934
+					$data = call_user_func_array(array($this, $method), array($data, $last));
935
+				}
936
+			}
937
+			return $data;
938
+		}
939
+
940
+		/**
941
+		 * Run validation on the passed data
942
+		 */
943
+		protected function validate(array $data)
944
+		{
945
+			if ($this->skip_validation)
946
+			{
947
+				return $data;
948
+			}
949
+			if (!empty($this->validate))
950
+			{
951
+				$fv = null;
952
+				if (is_object($this->formValidationInstance)){
953
+					$fv = $this->formValidationInstance;
954
+				}
955
+				else{
956
+					Loader::library('FormValidation');
957
+					$fv = $this->formvalidation;
958
+					$this->setFormValidation($fv);
959
+				}
960 960
                
961
-                $fv->setData($data);
962
-                $fv->setRules($this->validate);
963
-
964
-                if ($fv->run())
965
-                {
966
-                    return $data;
967
-                }
968
-                else
969
-                {
970
-                    return FALSE;
971
-                }
972
-            }
973
-            else
974
-            {
975
-                return $data;
976
-            }
977
-        }
961
+				$fv->setData($data);
962
+				$fv->setRules($this->validate);
963
+
964
+				if ($fv->run())
965
+				{
966
+					return $data;
967
+				}
968
+				else
969
+				{
970
+					return FALSE;
971
+				}
972
+			}
973
+			else
974
+			{
975
+				return $data;
976
+			}
977
+		}
978 978
 		
979 979
 		
980 980
 		/**
981
-		* Set WHERE parameters, when is array
982
-		* @param array $params
983
-		*/
981
+		 * Set WHERE parameters, when is array
982
+		 * @param array $params
983
+		 */
984 984
 		protected function _set_where_array(array $params){
985 985
 			foreach ($params as $field => $filter)
986 986
 			{
@@ -1003,52 +1003,52 @@  discard block
 block discarded – undo
1003 1003
 		}
1004 1004
 
1005 1005
 
1006
-        /**
1007
-         * Set WHERE parameters, cleverly
1008
-         */
1009
-        protected function _set_where($params)
1010
-        {
1011
-            if (count($params) == 1 && is_array($params[0]))
1012
-            {
1013
-                $this->_set_where_array($params[0]);
1014
-            }
1015
-            else if (count($params) == 1)
1016
-            {
1017
-                $this->getQueryBuilder()->where($params[0]);
1018
-            }
1019
-        	else if (count($params) == 2)
1020
-    		{
1021
-                if (is_array($params[1]))
1022
-                {
1023
-                    $this->getQueryBuilder()->in($params[0], $params[1]);
1024
-                }
1025
-                else
1026
-                {
1027
-                    $this->getQueryBuilder()->where($params[0], $params[1]);
1028
-                }
1029
-    		}
1030
-    		else if (count($params) == 3)
1031
-    		{
1032
-    			$this->getQueryBuilder()->where($params[0], $params[1], $params[2]);
1033
-    		}
1034
-            else
1035
-            {
1036
-                if (is_array($params[1]))
1037
-                {
1038
-                    $this->getQueryBuilder()->in($params[0], $params[1]);
1039
-                }
1040
-                else
1041
-                {
1042
-                    $this->getQueryBuilder()->where($params[0], $params[1]);
1043
-                }
1044
-            }
1045
-        }
1046
-
1047
-        /**
1006
+		/**
1007
+		 * Set WHERE parameters, cleverly
1008
+		 */
1009
+		protected function _set_where($params)
1010
+		{
1011
+			if (count($params) == 1 && is_array($params[0]))
1012
+			{
1013
+				$this->_set_where_array($params[0]);
1014
+			}
1015
+			else if (count($params) == 1)
1016
+			{
1017
+				$this->getQueryBuilder()->where($params[0]);
1018
+			}
1019
+			else if (count($params) == 2)
1020
+			{
1021
+				if (is_array($params[1]))
1022
+				{
1023
+					$this->getQueryBuilder()->in($params[0], $params[1]);
1024
+				}
1025
+				else
1026
+				{
1027
+					$this->getQueryBuilder()->where($params[0], $params[1]);
1028
+				}
1029
+			}
1030
+			else if (count($params) == 3)
1031
+			{
1032
+				$this->getQueryBuilder()->where($params[0], $params[1], $params[2]);
1033
+			}
1034
+			else
1035
+			{
1036
+				if (is_array($params[1]))
1037
+				{
1038
+					$this->getQueryBuilder()->in($params[0], $params[1]);
1039
+				}
1040
+				else
1041
+				{
1042
+					$this->getQueryBuilder()->where($params[0], $params[1]);
1043
+				}
1044
+			}
1045
+		}
1046
+
1047
+		/**
1048 1048
             Shortcut to controller
1049
-        */
1050
-        public function __get($key){
1051
-            return get_instance()->{$key};
1052
-        }
1049
+		 */
1050
+		public function __get($key){
1051
+			return get_instance()->{$key};
1052
+		}
1053 1053
 
1054
-    }
1054
+	}
Please login to merge, or discard this patch.
core/classes/Router.php 2 patches
Indentation   +15 added lines, -15 removed lines patch added patch discarded remove patch
@@ -22,23 +22,23 @@  discard block
 block discarded – undo
22 22
 	 * You should have received a copy of the GNU General Public License
23 23
 	 * along with this program; if not, write to the Free Software
24 24
 	 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
25
-	*/
25
+	 */
26 26
 
27 27
 	class Router {
28 28
 		
29 29
 		/**
30
-		* @var array $pattern: The list of URIs to validate against
31
-		*/
30
+		 * @var array $pattern: The list of URIs to validate against
31
+		 */
32 32
 		private $pattern = array();
33 33
 
34 34
 		/**
35
-		* @var array $callback: The list of callback to call
36
-		*/
35
+		 * @var array $callback: The list of callback to call
36
+		 */
37 37
 		private $callback = array();
38 38
 
39 39
 		/**
40
-		* @var string $uriTrim: The char to remove from the URIs
41
-		*/
40
+		 * @var string $uriTrim: The char to remove from the URIs
41
+		 */
42 42
 		protected $uriTrim = '/\^$';
43 43
 
44 44
 		/**
@@ -94,9 +94,9 @@  discard block
 block discarded – undo
94 94
 		 */
95 95
 		public function __construct(){
96 96
 			$this->logger =& class_loader('Log', 'classes');
97
-	        $this->logger->setLogger('Library::Router');
98
-	        $routesPath = CONFIG_PATH . 'routes.php';
99
-	        $this->logger->debug('Loading of routes configuration file --> ' . $routesPath . ' ...');
97
+			$this->logger->setLogger('Library::Router');
98
+			$routesPath = CONFIG_PATH . 'routes.php';
99
+			$this->logger->debug('Loading of routes configuration file --> ' . $routesPath . ' ...');
100 100
 			if(file_exists($routesPath)){
101 101
 				$this->logger->info('Found routes configuration file --> ' . $routesPath. ' now load it');
102 102
 				$route = array();
@@ -145,11 +145,11 @@  discard block
 block discarded – undo
145 145
 		}
146 146
 
147 147
 		/**
148
-		* Add the URI and callback to the list of URIs to validate
149
-		*
150
-		* @param string $uri the request URI
151
-		* @param object $callback the callback function
152
-		*/
148
+		 * Add the URI and callback to the list of URIs to validate
149
+		 *
150
+		 * @param string $uri the request URI
151
+		 * @param object $callback the callback function
152
+		 */
153 153
 		public function add($uri, $callback) {
154 154
 			$uri = trim($uri, $this->uriTrim);
155 155
 			if(in_array($uri, $this->pattern)){
Please login to merge, or discard this patch.
Spacing   +59 added lines, -59 removed lines patch added patch discarded remove patch
@@ -92,37 +92,37 @@  discard block
 block discarded – undo
92 92
 		/**
93 93
 		 * Construct the new Router instance
94 94
 		 */
95
-		public function __construct(){
96
-			$this->logger =& class_loader('Log', 'classes');
95
+		public function __construct() {
96
+			$this->logger = & class_loader('Log', 'classes');
97 97
 	        $this->logger->setLogger('Library::Router');
98 98
 	        $routesPath = CONFIG_PATH . 'routes.php';
99 99
 	        $this->logger->debug('Loading of routes configuration file --> ' . $routesPath . ' ...');
100
-			if(file_exists($routesPath)){
101
-				$this->logger->info('Found routes configuration file --> ' . $routesPath. ' now load it');
100
+			if (file_exists($routesPath)) {
101
+				$this->logger->info('Found routes configuration file --> ' . $routesPath . ' now load it');
102 102
 				$route = array();
103 103
 				require_once $routesPath;
104
-				if(! empty($route) && is_array($route)){
104
+				if (!empty($route) && is_array($route)) {
105 105
 					$this->routes = $route;
106 106
 					unset($route);
107 107
 				}
108 108
 			}
109
-			else{
109
+			else {
110 110
 				show_error('Unable to find the routes configuration file [' . $routesPath . ']');
111 111
 			}
112 112
 			
113 113
 			//loading routes for module
114 114
 			$this->logger->debug('Loading of modules routes ... ');
115 115
 			$modulesRoutes = Module::getModulesRoutes();
116
-			if($modulesRoutes && is_array($modulesRoutes)){
116
+			if ($modulesRoutes && is_array($modulesRoutes)) {
117 117
 				$this->routes = array_merge($this->routes, $modulesRoutes);
118 118
 				$this->logger->info('Routes for all modules loaded successfully');
119 119
 			}
120
-			else{
120
+			else {
121 121
 				$this->logger->info('No routes found for all modules skipping.');
122 122
 			}
123 123
 			$this->logger->info('The routes configuration are listed below: ' . stringfy_vars($this->routes));
124 124
 
125
-			foreach($this->routes as $pattern => $callback){
125
+			foreach ($this->routes as $pattern => $callback) {
126 126
 				$this->add($pattern, $callback);
127 127
 			}
128 128
 			
@@ -130,14 +130,14 @@  discard block
 block discarded – undo
130 130
 			$uri = isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : '';
131 131
 			$this->logger->debug('Check if URL suffix is enabled in the configuration');
132 132
 			//remove url suffix from the request URI
133
-			if($suffix = get_config('url_suffix')){
134
-				$this->logger->info('URL suffix is enabled in the configuration, the value is [' . $suffix . ']' );
133
+			if ($suffix = get_config('url_suffix')) {
134
+				$this->logger->info('URL suffix is enabled in the configuration, the value is [' . $suffix . ']');
135 135
 				$uri = str_ireplace($suffix, '', $uri);
136 136
 			}
137
-			else{
137
+			else {
138 138
 				$this->logger->info('URL suffix is not enabled in the configuration');
139 139
 			}
140
-			if(strpos($uri, '?') !== false){
140
+			if (strpos($uri, '?') !== false) {
141 141
 				$uri = substr($uri, 0, strpos($uri, '?'));
142 142
 			}
143 143
 			$uri = trim($uri, $this->uriTrim);
@@ -152,7 +152,7 @@  discard block
 block discarded – undo
152 152
 		*/
153 153
 		public function add($uri, $callback) {
154 154
 			$uri = trim($uri, $this->uriTrim);
155
-			if(in_array($uri, $this->pattern)){
155
+			if (in_array($uri, $this->pattern)) {
156 156
 				$this->logger->warning('The route [' . $uri . '] already added, may be adding again can have route conflict');
157 157
 			}
158 158
 			$this->pattern[] = $uri;
@@ -163,7 +163,7 @@  discard block
 block discarded – undo
163 163
 		 * Get the module name
164 164
 		 * @return string
165 165
 		 */
166
-		public function getModule(){
166
+		public function getModule() {
167 167
 			return $this->module;
168 168
 		}
169 169
 		
@@ -171,7 +171,7 @@  discard block
 block discarded – undo
171 171
 		 * Get the controller name
172 172
 		 * @return string
173 173
 		 */
174
-		public function getController(){
174
+		public function getController() {
175 175
 			return $this->controller;
176 176
 		}
177 177
 
@@ -179,7 +179,7 @@  discard block
 block discarded – undo
179 179
 		 * Get the controller file path
180 180
 		 * @return string
181 181
 		 */
182
-		public function getControllerPath(){
182
+		public function getControllerPath() {
183 183
 			return $this->controllerPath;
184 184
 		}
185 185
 
@@ -187,7 +187,7 @@  discard block
 block discarded – undo
187 187
 		 * Get the controller method
188 188
 		 * @return string
189 189
 		 */
190
-		public function getMethod(){
190
+		public function getMethod() {
191 191
 			return $this->method;
192 192
 		}
193 193
 
@@ -195,7 +195,7 @@  discard block
 block discarded – undo
195 195
 		 * Get the request arguments
196 196
 		 * @return array
197 197
 		 */
198
-		public function getArgs(){
198
+		public function getArgs() {
199 199
 			return $this->args;
200 200
 		}
201 201
 
@@ -203,7 +203,7 @@  discard block
 block discarded – undo
203 203
 		 * Get the URL segments array
204 204
 		 * @return array
205 205
 		 */
206
-		public function getSegments(){
206
+		public function getSegments() {
207 207
 			return $this->segments;
208 208
 		}
209 209
 
@@ -212,27 +212,27 @@  discard block
 block discarded – undo
212 212
 		 * otherwise send 404 error.
213 213
 		 */
214 214
 		public function run() {
215
-			$benchmark =& class_loader('Benchmark');
215
+			$benchmark = & class_loader('Benchmark');
216 216
 			$benchmark->mark('ROUTING_PROCESS_START');
217 217
 			$this->logger->debug('Routing process start ...');
218 218
 			$segment = $this->segments;
219 219
 			$baseUrl = get_config('base_url');
220 220
 			//check if the app is not in DOCUMENT_ROOT
221
-			if(isset($segment[0]) && stripos($baseUrl, $segment[0]) != false){
221
+			if (isset($segment[0]) && stripos($baseUrl, $segment[0]) != false) {
222 222
 				array_shift($segment);
223 223
 				$this->segments = $segment;
224 224
 			}
225 225
 			$this->logger->debug('Check if the request URI contains the front controller');
226
-			if(isset($segment[0]) && $segment[0] == SELF){
226
+			if (isset($segment[0]) && $segment[0] == SELF) {
227 227
 				$this->logger->info('The request URI contains the front controller');
228 228
 				array_shift($segment);
229 229
 				$this->segments = $segment;
230 230
 			}
231
-			else{
231
+			else {
232 232
 				$this->logger->info('The request URI does not contain the front controller');
233 233
 			}
234 234
 			$uri = implode('/', $segment);
235
-			$this->logger->info('The final Request URI is [' . $uri . ']' );
235
+			$this->logger->info('The final Request URI is [' . $uri . ']');
236 236
 			//generic routes
237 237
 			$pattern = array(':num', ':alpha', ':alnum', ':any');
238 238
 			$replace = array('[0-9]+', '[a-zA-Z]+', '[a-zA-Z0-9]+', '.*');
@@ -246,20 +246,20 @@  discard block
 block discarded – undo
246 246
 					array_shift($args);
247 247
 					//check if this contains an module
248 248
 					$moduleControllerMethod = explode('#', $this->callback[$index]);
249
-					if(is_array($moduleControllerMethod) && count($moduleControllerMethod) >= 2){
250
-						$this->logger->info('The current request use the module [' .$moduleControllerMethod[0]. ']');
249
+					if (is_array($moduleControllerMethod) && count($moduleControllerMethod) >= 2) {
250
+						$this->logger->info('The current request use the module [' . $moduleControllerMethod[0] . ']');
251 251
 						$this->module = $moduleControllerMethod[0];
252 252
 						$moduleControllerMethod = explode('@', $moduleControllerMethod[1]);
253 253
 					}
254
-					else{
254
+					else {
255 255
 						$this->logger->info('The current request does not use the module');
256 256
 						$moduleControllerMethod = explode('@', $this->callback[$index]);
257 257
 					}
258
-					if(is_array($moduleControllerMethod)){
259
-						if(isset($moduleControllerMethod[0])){
258
+					if (is_array($moduleControllerMethod)) {
259
+						if (isset($moduleControllerMethod[0])) {
260 260
 							$this->controller = $moduleControllerMethod[0];	
261 261
 						}
262
-						if(isset($moduleControllerMethod[1])){
262
+						if (isset($moduleControllerMethod[1])) {
263 263
 							$this->method = $moduleControllerMethod[1];
264 264
 						}
265 265
 						$this->args = $args;
@@ -269,73 +269,73 @@  discard block
 block discarded – undo
269 269
 				}
270 270
 			}
271 271
 			//first if the controller is not set and the module is set use the module name as the controller
272
-			if(! $this->getController() && $this->getModule()){
272
+			if (!$this->getController() && $this->getModule()) {
273 273
 				$this->logger->info('After loop in predefined routes configuration, the module name is set but the controller is not set, so we will use module as the controller');
274 274
 				$this->controller = $this->getModule();
275 275
 			}
276 276
 			//if can not determine the module/controller/method via the defined routes configuration we will use
277 277
 			//the URL like http://domain.com/module/controller/method/arg1/arg2
278
-			if(! $this->getController()){
278
+			if (!$this->getController()) {
279 279
 				$this->logger->info('Cannot determine the routing information using the predefined routes configuration, will use the request URI parameters');
280 280
 				$nbSegment = count($segment);
281 281
 				//if segment is null so means no need to perform
282
-				if($nbSegment > 0){
282
+				if ($nbSegment > 0) {
283 283
 					//get the module list
284 284
 					$modules = Module::getModuleList();
285 285
 					//first check if no module
286
-					if(! $modules){
286
+					if (!$modules) {
287 287
 						$this->logger->info('No module was loaded will skip the module checking');
288 288
 						//the application don't use module
289 289
 						//controller
290
-						if(isset($segment[0])){
290
+						if (isset($segment[0])) {
291 291
 							$this->controller = $segment[0];
292 292
 							array_shift($segment);
293 293
 						}
294 294
 						//method
295
-						if(isset($segment[0])){
295
+						if (isset($segment[0])) {
296 296
 							$this->method = $segment[0];
297 297
 							array_shift($segment);
298 298
 						}
299 299
 						//args
300 300
 						$this->args = $segment;
301 301
 					}
302
-					else{
302
+					else {
303 303
 						$this->logger->info('The application contains a loaded module will check if the current request is found in the module list');
304
-						if(in_array($segment[0], $modules)){
304
+						if (in_array($segment[0], $modules)) {
305 305
 							$this->logger->info('Found, the current request use the module [' . $segment[0] . ']');
306 306
 							$this->module = $segment[0];
307 307
 							array_shift($segment);
308 308
 							//check if the second arg is the controller from module
309
-							if(isset($segment[0])){
309
+							if (isset($segment[0])) {
310 310
 								$this->controller = $segment[0];
311 311
 								//check if the request use the same module name and controller
312 312
 								$path = Module::findControllerFullPath(ucfirst($this->getController()), $this->getModule());
313
-								if(! $path){
313
+								if (!$path) {
314 314
 									$this->logger->info('The controller [' . $this->getController() . '] not found in the module, may be will use the module [' . $this->getModule() . '] as controller');
315 315
 									$this->controller = $this->getModule();
316 316
 								}
317
-								else{
317
+								else {
318 318
 									$this->controllerPath = $path;
319 319
 									array_shift($segment);
320 320
 								}
321 321
 							}
322 322
 							//check for method
323
-							if(isset($segment[0])){
323
+							if (isset($segment[0])) {
324 324
 								$this->method = $segment[0];
325 325
 								array_shift($segment);
326 326
 							}
327 327
 							//the remaining is for args
328 328
 							$this->args = $segment;
329 329
 						}
330
-						else{
330
+						else {
331 331
 							$this->logger->info('The current request information is not found in the module list');
332 332
 							//controller
333
-							if(isset($segment[0])){
333
+							if (isset($segment[0])) {
334 334
 								$this->controller = $segment[0];
335 335
 								array_shift($segment);
336 336
 							}
337 337
 							//method
338
-							if(isset($segment[0])){
338
+							if (isset($segment[0])) {
339 339
 								$this->method = $segment[0];
340 340
 								array_shift($segment);
341 341
 							}
@@ -345,18 +345,18 @@  discard block
 block discarded – undo
345 345
 					}
346 346
 				}
347 347
 			}
348
-			if(! $this->getController() && $this->getModule()){
348
+			if (!$this->getController() && $this->getModule()) {
349 349
 				$this->logger->info('After using the request URI the module name is set but the controller is not set so we will use module as the controller');
350 350
 				$this->controller = $this->getModule();
351 351
 			}
352 352
 			//did we set the controller, so set the controller path
353
-			if($this->getController() && ! $this->getControllerPath()){
353
+			if ($this->getController() && !$this->getControllerPath()) {
354 354
 				$this->logger->debug('Setting the file path for the controller [' . $this->getController() . ']');
355 355
 				//if it is the module controller
356
-				if($this->getModule()){
356
+				if ($this->getModule()) {
357 357
 					$this->controllerPath = Module::findControllerFullPath(ucfirst($this->getController()), $this->getModule());
358 358
 				}
359
-				else{
359
+				else {
360 360
 					$this->controllerPath = APPS_CONTROLLER_PATH . ucfirst($this->getController()) . '.php';
361 361
 				}
362 362
 			}
@@ -366,20 +366,20 @@  discard block
 block discarded – undo
366 366
 			$this->logger->debug('Loading controller [' . $controller . '], the file path is [' . $classFilePath . ']...');
367 367
 			$benchmark->mark('ROUTING_PROCESS_END');
368 368
 			$e404 = false;
369
-			if(file_exists($classFilePath)){
369
+			if (file_exists($classFilePath)) {
370 370
 				require_once $classFilePath;
371
-				if(! class_exists($controller, false)){
371
+				if (!class_exists($controller, false)) {
372 372
 					$e404 = true;
373
-					$this->logger->info('The controller file [' .$classFilePath. '] exists but does not contain the class [' . $controller . ']');
373
+					$this->logger->info('The controller file [' . $classFilePath . '] exists but does not contain the class [' . $controller . ']');
374 374
 				}
375
-				else{
375
+				else {
376 376
 					$controllerInstance = new $controller();
377 377
 					$controllerMethod = $this->getMethod();
378
-					if(! method_exists($controllerInstance, $controllerMethod)){
378
+					if (!method_exists($controllerInstance, $controllerMethod)) {
379 379
 						$e404 = true;
380 380
 						$this->logger->info('The controller [' . $controller . '] exist but does not contain the method [' . $controllerMethod . ']');
381 381
 					}
382
-					else{
382
+					else {
383 383
 						$this->logger->info('Routing data is set correctly now GO!');
384 384
 						call_user_func_array(array($controllerInstance, $controllerMethod), $this->getArgs());
385 385
 						$obj = & get_instance();
@@ -389,12 +389,12 @@  discard block
 block discarded – undo
389 389
 					}
390 390
 				}
391 391
 			}
392
-			else{
392
+			else {
393 393
 				$this->logger->info('The controller file path [' . $classFilePath . '] does not exist');
394 394
 				$e404 = true;
395 395
 			}
396
-			if($e404){
397
-				$response =& class_loader('Response', 'classes');
396
+			if ($e404) {
397
+				$response = & class_loader('Response', 'classes');
398 398
 				$response->send404();
399 399
 			}
400 400
 		}
Please login to merge, or discard this patch.
core/classes/Database.php 2 patches
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.
Spacing   +115 added lines, -115 removed lines patch added patch discarded remove patch
@@ -23,110 +23,110 @@  discard block
 block discarded – undo
23 23
    * along with this program; if not, write to the Free Software
24 24
    * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
25 25
   */
26
-  class Database{
26
+  class Database {
27 27
 	
28 28
 	/**
29 29
 	 * The PDO instance
30 30
 	 * @var object
31 31
 	*/
32
-    private $pdo                 = null;
32
+    private $pdo = null;
33 33
     
34 34
 	/**
35 35
 	 * The database name used for the application
36 36
 	 * @var string
37 37
 	*/
38
-	private $databaseName        = null;
38
+	private $databaseName = null;
39 39
 	
40 40
 	/**
41 41
 	 * The number of rows returned by the last query
42 42
 	 * @var int
43 43
 	*/
44
-    private $numRows             = 0;
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 49
 	*/
50
-    private $insertId            = null;
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 55
 	*/
56
-    private $query               = null;
56
+    private $query = null;
57 57
 	
58 58
 	/**
59 59
 	 * The error returned for the last query
60 60
 	 * @var string
61 61
 	*/
62
-    private $error               = null;
62
+    private $error = null;
63 63
 	
64 64
 	/**
65 65
 	 * The result returned for the last query
66 66
 	 * @var mixed
67 67
 	*/
68
-    private $result              = array();
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
-	private $cacheTtl              = 0;
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 79
 	*/
80
-    private $temporaryCacheTtl   = 0;
80
+    private $temporaryCacheTtl = 0;
81 81
 	
82 82
 	/**
83 83
 	 * The number of executed query for the current request
84 84
 	 * @var int
85 85
 	*/
86
-    private $queryCount          = 0;
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 91
 	*/
92
-    private $data                = array();
92
+    private $data = array();
93 93
 	
94 94
 	/**
95 95
 	 * The database configuration
96 96
 	 * @var array
97 97
 	*/
98
-    private $config              = array();
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 106
     /**
107 107
     * The cache instance
108 108
     * @var object
109 109
     */
110
-    private $cacheInstance       = null;
110
+    private $cacheInstance = null;
111 111
 
112 112
     /**
113 113
     * The benchmark instance
114 114
     * @var object
115 115
     */
116
-    private $benchmarkInstance   = null;
116
+    private $benchmarkInstance = null;
117 117
 	
118 118
 	/**
119 119
     * The DatabaseQueryBuilder instance
120 120
     * @var object
121 121
     */
122
-    private $queryBuilder        = null;
122
+    private $queryBuilder = null;
123 123
 
124 124
 
125 125
     /**
126 126
      * Construct new database
127 127
      * @param array $overwriteConfig the config to overwrite with the config set in database.php
128 128
      */
129
-    public function __construct($overwriteConfig = array()){
129
+    public function __construct($overwriteConfig = array()) {
130 130
         //Set Log instance to use
131 131
         $this->setLoggerFromParamOrCreateNewInstance(null);
132 132
 		
@@ -144,23 +144,23 @@  discard block
 block discarded – undo
144 144
      * This is used to connect to database
145 145
      * @return bool 
146 146
      */
147
-    public function connect(){
147
+    public function connect() {
148 148
       $config = $this->getDatabaseConfiguration();
149
-      if (! empty($config)){
150
-        try{
149
+      if (!empty($config)) {
150
+        try {
151 151
             $this->pdo = new PDO($this->getDsnFromDriver(), $config['username'], $config['password']);
152 152
             $this->pdo->exec("SET NAMES '" . $config['charset'] . "' COLLATE '" . $config['collation'] . "'");
153 153
             $this->pdo->exec("SET CHARACTER SET '" . $config['charset'] . "'");
154 154
             $this->pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_OBJ);
155 155
             return true;
156 156
           }
157
-          catch (PDOException $e){
157
+          catch (PDOException $e) {
158 158
             $this->logger->fatal($e->getMessage());
159 159
             show_error('Cannot connect to Database.');
160 160
             return false;
161 161
           }
162 162
       }
163
-      else{
163
+      else {
164 164
         show_error('Database configuration is not set.');
165 165
         return false;
166 166
       }
@@ -171,7 +171,7 @@  discard block
 block discarded – undo
171 171
      * Return the number of rows returned by the current query
172 172
      * @return int
173 173
      */
174
-    public function numRows(){
174
+    public function numRows() {
175 175
       return $this->numRows;
176 176
     }
177 177
 
@@ -179,15 +179,15 @@  discard block
 block discarded – undo
179 179
      * Return the last insert id value
180 180
      * @return mixed
181 181
      */
182
-    public function insertId(){
182
+    public function insertId() {
183 183
       return $this->insertId;
184 184
     }
185 185
 
186 186
     /**
187 187
      * Show an error got from the current query (SQL command synthax error, database driver returned error, etc.)
188 188
      */
189
-    public function error(){
190
-  		if ($this->error){
189
+    public function error() {
190
+  		if ($this->error) {
191 191
   			show_error('Query: "' . $this->query . '" Error: ' . $this->error, 'Database Error');
192 192
   		}
193 193
     }
@@ -198,13 +198,13 @@  discard block
 block discarded – undo
198 198
      * If is string will determine the result type "array" or "object"
199 199
      * @return mixed       the query SQL string or the record result
200 200
      */
201
-    public function get($returnSQLQueryOrResultType = false){
201
+    public function get($returnSQLQueryOrResultType = false) {
202 202
       $this->getQueryBuilder()->limit(1);
203 203
       $query = $this->getAll(true);
204
-      if ($returnSQLQueryOrResultType === true){
204
+      if ($returnSQLQueryOrResultType === true) {
205 205
         return $query;
206 206
       }
207
-      else{
207
+      else {
208 208
         return $this->query($query, false, $returnSQLQueryOrResultType == 'array');
209 209
       }
210 210
     }
@@ -215,9 +215,9 @@  discard block
 block discarded – undo
215 215
      * If is string will determine the result type "array" or "object"
216 216
      * @return mixed       the query SQL string or the record result
217 217
      */
218
-    public function getAll($returnSQLQueryOrResultType = false){
218
+    public function getAll($returnSQLQueryOrResultType = false) {
219 219
 	   $query = $this->getQueryBuilder()->getQuery();
220
-	   if ($returnSQLQueryOrResultType === true){
220
+	   if ($returnSQLQueryOrResultType === true) {
221 221
       	return $query;
222 222
       }
223 223
       return $this->query($query, true, $returnSQLQueryOrResultType == 'array');
@@ -229,18 +229,18 @@  discard block
 block discarded – undo
229 229
      * @param  boolean $escape  whether to escape or not the values
230 230
      * @return mixed          the insert id of the new record or null
231 231
      */
232
-    public function insert($data = array(), $escape = true){
233
-      if (empty($data) && $this->getData()){
232
+    public function insert($data = array(), $escape = true) {
233
+      if (empty($data) && $this->getData()) {
234 234
         //as when using $this->setData() may be the data already escaped
235 235
         $escape = false;
236 236
         $data = $this->getData();
237 237
       }
238 238
       $query = $this->getQueryBuilder()->insert($data, $escape)->getQuery();
239 239
       $result = $this->query($query);
240
-      if ($result){
240
+      if ($result) {
241 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();
243
+        return !$this->insertId() ? true : $this->insertId();
244 244
       }
245 245
       return false;
246 246
     }
@@ -251,8 +251,8 @@  discard block
 block discarded – undo
251 251
      * @param  boolean $escape  whether to escape or not the values
252 252
      * @return mixed          the update status
253 253
      */
254
-    public function update($data = array(), $escape = true){
255
-      if (empty($data) && $this->getData()){
254
+    public function update($data = array(), $escape = true) {
255
+      if (empty($data) && $this->getData()) {
256 256
         //as when using $this->setData() may be the data already escaped
257 257
         $escape = false;
258 258
         $data = $this->getData();
@@ -265,7 +265,7 @@  discard block
 block discarded – undo
265 265
      * Delete the record in database
266 266
      * @return mixed the delete status
267 267
      */
268
-    public function delete(){
268
+    public function delete() {
269 269
 		$query = $this->getQueryBuilder()->delete()->getQuery();
270 270
     	return $this->query($query);
271 271
     }
@@ -275,8 +275,8 @@  discard block
 block discarded – undo
275 275
      * @param integer $ttl the cache time to live in second
276 276
      * @return object        the current Database instance
277 277
      */
278
-    public function setCache($ttl = 0){
279
-      if ($ttl > 0){
278
+    public function setCache($ttl = 0) {
279
+      if ($ttl > 0) {
280 280
         $this->cacheTtl = $ttl;
281 281
         $this->temporaryCacheTtl = $ttl;
282 282
       }
@@ -288,8 +288,8 @@  discard block
 block discarded – undo
288 288
 	 * @param  integer $ttl the cache time to live in second
289 289
 	 * @return object        the current Database instance
290 290
 	 */
291
-  	public function cached($ttl = 0){
292
-        if ($ttl > 0){
291
+  	public function cached($ttl = 0) {
292
+        if ($ttl > 0) {
293 293
           $this->temporaryCacheTtl = $ttl;
294 294
         }
295 295
         return $this;
@@ -301,7 +301,7 @@  discard block
 block discarded – undo
301 301
      * @param boolean $escaped whether we can do escape of not 
302 302
      * @return mixed       the data after escaped or the same data if not
303 303
      */
304
-    public function escape($data, $escaped = true){
304
+    public function escape($data, $escaped = true) {
305 305
       return $escaped ? 
306 306
                       $this->getPdo()->quote(trim($data)) 
307 307
                       : $data; 
@@ -311,7 +311,7 @@  discard block
 block discarded – undo
311 311
      * Return the number query executed count for the current request
312 312
      * @return int
313 313
      */
314
-    public function queryCount(){
314
+    public function queryCount() {
315 315
       return $this->queryCount;
316 316
     }
317 317
 
@@ -319,7 +319,7 @@  discard block
 block discarded – undo
319 319
      * Return the current query SQL string
320 320
      * @return string
321 321
      */
322
-    public function getQuery(){
322
+    public function getQuery() {
323 323
       return $this->query;
324 324
     }
325 325
 
@@ -327,7 +327,7 @@  discard block
 block discarded – undo
327 327
      * Return the application database name
328 328
      * @return string
329 329
      */
330
-    public function getDatabaseName(){
330
+    public function getDatabaseName() {
331 331
       return $this->databaseName;
332 332
     }
333 333
 
@@ -335,7 +335,7 @@  discard block
 block discarded – undo
335 335
      * Return the PDO instance
336 336
      * @return object
337 337
      */
338
-    public function getPdo(){
338
+    public function getPdo() {
339 339
       return $this->pdo;
340 340
     }
341 341
 
@@ -344,7 +344,7 @@  discard block
 block discarded – undo
344 344
      * @param object $pdo the pdo object
345 345
 	 * @return object Database
346 346
      */
347
-    public function setPdo(PDO $pdo){
347
+    public function setPdo(PDO $pdo) {
348 348
       $this->pdo = $pdo;
349 349
       return $this;
350 350
     }
@@ -354,7 +354,7 @@  discard block
 block discarded – undo
354 354
      * Return the Log instance
355 355
      * @return Log
356 356
      */
357
-    public function getLogger(){
357
+    public function getLogger() {
358 358
       return $this->logger;
359 359
     }
360 360
 
@@ -363,7 +363,7 @@  discard block
 block discarded – undo
363 363
      * @param Log $logger the log object
364 364
 	 * @return object Database
365 365
      */
366
-    public function setLogger($logger){
366
+    public function setLogger($logger) {
367 367
       $this->logger = $logger;
368 368
       return $this;
369 369
     }
@@ -372,7 +372,7 @@  discard block
 block discarded – undo
372 372
      * Return the cache instance
373 373
      * @return CacheInterface
374 374
      */
375
-    public function getCacheInstance(){
375
+    public function getCacheInstance() {
376 376
       return $this->cacheInstance;
377 377
     }
378 378
 
@@ -381,7 +381,7 @@  discard block
 block discarded – undo
381 381
      * @param CacheInterface $cache the cache object
382 382
 	 * @return object Database
383 383
      */
384
-    public function setCacheInstance($cache){
384
+    public function setCacheInstance($cache) {
385 385
       $this->cacheInstance = $cache;
386 386
       return $this;
387 387
     }
@@ -390,7 +390,7 @@  discard block
 block discarded – undo
390 390
      * Return the benchmark instance
391 391
      * @return Benchmark
392 392
      */
393
-    public function getBenchmark(){
393
+    public function getBenchmark() {
394 394
       return $this->benchmarkInstance;
395 395
     }
396 396
 
@@ -399,7 +399,7 @@  discard block
 block discarded – undo
399 399
      * @param Benchmark $benchmark the benchmark object
400 400
 	 * @return object Database
401 401
      */
402
-    public function setBenchmark($benchmark){
402
+    public function setBenchmark($benchmark) {
403 403
       $this->benchmarkInstance = $benchmark;
404 404
       return $this;
405 405
     }
@@ -409,7 +409,7 @@  discard block
 block discarded – undo
409 409
      * Return the DatabaseQueryBuilder instance
410 410
      * @return object DatabaseQueryBuilder
411 411
      */
412
-    public function getQueryBuilder(){
412
+    public function getQueryBuilder() {
413 413
       return $this->queryBuilder;
414 414
     }
415 415
 
@@ -417,7 +417,7 @@  discard block
 block discarded – undo
417 417
      * Set the DatabaseQueryBuilder instance
418 418
      * @param object DatabaseQueryBuilder $queryBuilder the DatabaseQueryBuilder object
419 419
      */
420
-    public function setQueryBuilder(DatabaseQueryBuilder $queryBuilder){
420
+    public function setQueryBuilder(DatabaseQueryBuilder $queryBuilder) {
421 421
       $this->queryBuilder = $queryBuilder;
422 422
       return $this;
423 423
     }
@@ -426,7 +426,7 @@  discard block
 block discarded – undo
426 426
      * Return the data to be used for insert, update, etc.
427 427
      * @return array
428 428
      */
429
-    public function getData(){
429
+    public function getData() {
430 430
       return $this->data;
431 431
     }
432 432
 
@@ -437,9 +437,9 @@  discard block
 block discarded – undo
437 437
      * @param boolean $escape whether to escape or not the $value
438 438
      * @return object        the current Database instance
439 439
      */
440
-    public function setData($key, $value = null, $escape = true){
441
-  	  if(is_array($key)){
442
-    		foreach($key as $k => $v){
440
+    public function setData($key, $value = null, $escape = true) {
441
+  	  if (is_array($key)) {
442
+    		foreach ($key as $k => $v) {
443 443
     			$this->setData($k, $v, $escape);
444 444
     		}	
445 445
   	  } else {
@@ -456,7 +456,7 @@  discard block
 block discarded – undo
456 456
      * @param  boolean $array return the result as array
457 457
      * @return mixed         the query result
458 458
      */
459
-    public function query($query, $all = true, $array = false){
459
+    public function query($query, $all = true, $array = false) {
460 460
       $this->reset();
461 461
       $query = $this->getPreparedQuery($query, $all);
462 462
       $this->query = preg_replace('/\s\s+|\t\t+/', ' ', trim($query));
@@ -464,9 +464,9 @@  discard block
 block discarded – undo
464 464
       $isSqlSELECTQuery = stristr($this->query, 'SELECT') !== false;
465 465
 
466 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')
467
+                          'Execute SQL query [' . $this->query . '], return type: ' 
468
+                          . ($array ? 'ARRAY' : 'OBJECT') . ', return as list: ' 
469
+                          . (is_bool($all) && $all ? 'YES' : 'NO')
470 470
                         );
471 471
       //cache expire time
472 472
       $cacheExpire = $this->temporaryCacheTtl;
@@ -483,15 +483,15 @@  discard block
 block discarded – undo
483 483
       //if can use cache feature for this query
484 484
       $dbCacheStatus = $cacheEnable && $cacheExpire > 0;
485 485
     
486
-      if ($dbCacheStatus && $isSqlSELECTQuery){
486
+      if ($dbCacheStatus && $isSqlSELECTQuery) {
487 487
           $this->logger->info('The cache is enabled for this query, try to get result from cache'); 
488 488
           $cacheContent = $this->getCacheContentForQuery($query, $all, $array);  
489 489
       }
490 490
       
491
-      if ( !$cacheContent){
491
+      if (!$cacheContent) {
492 492
         $sqlQuery = $this->runSqlQuery($query, $all, $array);
493
-        if (is_object($sqlQuery)){
494
-          if ($isSqlSELECTQuery){
493
+        if (is_object($sqlQuery)) {
494
+          if ($isSqlSELECTQuery) {
495 495
             $this->setQueryResultForSelect($sqlQuery, $all, $array);
496 496
             $this->setCacheContentForQuery(
497 497
                                             $this->query, 
@@ -500,15 +500,15 @@  discard block
 block discarded – undo
500 500
                                             $dbCacheStatus && $isSqlSELECTQuery, 
501 501
                                             $cacheExpire
502 502
                                           );
503
-            if (! $this->result){
503
+            if (!$this->result) {
504 504
               $this->logger->info('No result where found for the query [' . $query . ']');
505 505
             }
506 506
           } else {
507 507
               $this->setQueryResultForNonSelect($sqlQuery);
508 508
           }
509 509
         }
510
-      } else if ($isSqlSELECTQuery){
511
-          $this->logger->info('The result for query [' .$this->query. '] already cached use it');
510
+      } else if ($isSqlSELECTQuery) {
511
+          $this->logger->info('The result for query [' . $this->query . '] already cached use it');
512 512
           $this->result = $cacheContent;
513 513
           $this->numRows = count($this->result);
514 514
       }
@@ -521,11 +521,11 @@  discard block
 block discarded – undo
521 521
      * 
522 522
      * @return object|void
523 523
      */
524
-    public function runSqlQuery($query, $all, $array){
524
+    public function runSqlQuery($query, $all, $array) {
525 525
        //for database query execution time
526 526
         $benchmarkMarkerKey = $this->getCacheBenchmarkKeyForQuery($query, $all, $array);
527 527
         $benchmarkInstance = $this->getBenchmark();
528
-        if (! is_object($benchmarkInstance)){
528
+        if (!is_object($benchmarkInstance)) {
529 529
           $obj = & get_instance();
530 530
           $benchmarkInstance = $obj->benchmark; 
531 531
           $this->setBenchmark($benchmarkInstance);
@@ -538,13 +538,13 @@  discard block
 block discarded – undo
538 538
         //get response time for this query
539 539
         $responseTime = $benchmarkInstance->elapsedTime('DATABASE_QUERY_START(' . $benchmarkMarkerKey . ')', 'DATABASE_QUERY_END(' . $benchmarkMarkerKey . ')');
540 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.');
541
+        if ($responseTime >= 1) {
542
+            $this->logger->warning('High response time while processing database query [' . $query . ']. The response time is [' . $responseTime . '] sec.');
543 543
         }
544 544
 		    //count the number of query execution to server
545 545
         $this->queryCount++;
546 546
 		
547
-        if ($sqlQuery !== false){
547
+        if ($sqlQuery !== false) {
548 548
           return $sqlQuery;
549 549
         }
550 550
         $this->setQueryError();
@@ -555,7 +555,7 @@  discard block
 block discarded – undo
555 555
 	 * Return the database configuration
556 556
 	 * @return array
557 557
 	 */
558
-	public  function getDatabaseConfiguration(){
558
+	public  function getDatabaseConfiguration() {
559 559
 	  return $this->config;
560 560
 	}
561 561
 
@@ -565,9 +565,9 @@  discard block
 block discarded – undo
565 565
     * @param boolean $useConfigFile whether to use database configuration file
566 566
 	  * @return object Database
567 567
     */
568
-    public function setDatabaseConfiguration(array $overwriteConfig = array(), $useConfigFile = true){
568
+    public function setDatabaseConfiguration(array $overwriteConfig = array(), $useConfigFile = true) {
569 569
         $db = array();
570
-        if ($useConfigFile && file_exists(CONFIG_PATH . 'database.php')){
570
+        if ($useConfigFile && file_exists(CONFIG_PATH . 'database.php')) {
571 571
             //here don't use require_once because somewhere user can create database instance directly
572 572
             require CONFIG_PATH . 'database.php';
573 573
         }
@@ -592,7 +592,7 @@  discard block
 block discarded – undo
592 592
     		//determine the port using the hostname like localhost:3307
593 593
         //hostname will be "localhost", and port "3307"
594 594
         $p = explode(':', $config['hostname']);
595
-    	  if (count($p) >= 2){
595
+    	  if (count($p) >= 2) {
596 596
     		  $config['hostname'] = $p[0];
597 597
     		  $config['port'] = $p[1];
598 598
     		}
@@ -611,7 +611,7 @@  discard block
 block discarded – undo
611 611
 		 $this->connect();
612 612
 		 
613 613
 		 //update queryBuilder with some properties needed
614
-		 if(is_object($this->getQueryBuilder())){
614
+		 if (is_object($this->getQueryBuilder())) {
615 615
 			  $this->getQueryBuilder()->setDriver($config['driver']);
616 616
 			  $this->getQueryBuilder()->setPrefix($config['prefix']);
617 617
 			  $this->getQueryBuilder()->setPdo($this->getPdo());
@@ -623,19 +623,19 @@  discard block
 block discarded – undo
623 623
    * Set the result for SELECT query using PDOStatment
624 624
    * @see Database::query
625 625
    */
626
-    protected function setQueryResultForSelect($pdoStatment, $all, $array){
626
+    protected function setQueryResultForSelect($pdoStatment, $all, $array) {
627 627
       //if need return all result like list of record
628
-      if (is_bool($all) && $all){
628
+      if (is_bool($all) && $all) {
629 629
           $this->result = ($array === false) ? $pdoStatment->fetchAll(PDO::FETCH_OBJ) : $pdoStatment->fetchAll(PDO::FETCH_ASSOC);
630 630
       }
631
-      else{
631
+      else {
632 632
           $this->result = ($array === false) ? $pdoStatment->fetch(PDO::FETCH_OBJ) : $pdoStatment->fetch(PDO::FETCH_ASSOC);
633 633
       }
634 634
       //Sqlite and pgsql always return 0 when using rowCount()
635
-      if (in_array($this->config['driver'], array('sqlite', 'pgsql'))){
635
+      if (in_array($this->config['driver'], array('sqlite', 'pgsql'))) {
636 636
         $this->numRows = count($this->result);  
637 637
       }
638
-      else{
638
+      else {
639 639
         $this->numRows = $pdoStatment->rowCount(); 
640 640
       }
641 641
     }
@@ -644,13 +644,13 @@  discard block
 block discarded – undo
644 644
      * Set the result for other command than SELECT query using PDOStatment
645 645
      * @see Database::query
646 646
      */
647
-    protected function setQueryResultForNonSelect($pdoStatment){
647
+    protected function setQueryResultForNonSelect($pdoStatment) {
648 648
       //Sqlite and pgsql always return 0 when using rowCount()
649
-      if (in_array($this->config['driver'], array('sqlite', 'pgsql'))){
649
+      if (in_array($this->config['driver'], array('sqlite', 'pgsql'))) {
650 650
         $this->result = true; //to test the result for the query like UPDATE, INSERT, DELETE
651 651
         $this->numRows = 1; //TODO use the correct method to get the exact affected row
652 652
       }
653
-      else{
653
+      else {
654 654
           $this->result = $pdoStatment->rowCount() >= 0; //to test the result for the query like UPDATE, INSERT, DELETE
655 655
           $this->numRows = $pdoStatment->rowCount(); 
656 656
       }
@@ -662,9 +662,9 @@  discard block
 block discarded – undo
662 662
      * This method is used to get the PDO DSN string using the configured driver
663 663
      * @return string the DSN string
664 664
      */
665
-    protected function getDsnFromDriver(){
665
+    protected function getDsnFromDriver() {
666 666
       $config = $this->getDatabaseConfiguration();
667
-      if (! empty($config)){
667
+      if (!empty($config)) {
668 668
         $driver = $config['driver'];
669 669
         $driverDsnMap = array(
670 670
                                 'mysql' => 'mysql:host=' . $config['hostname'] . ';' 
@@ -689,12 +689,12 @@  discard block
 block discarded – undo
689 689
      *
690 690
      * @return string
691 691
      */
692
-    protected function getPreparedQuery($query, $data){
693
-      if (is_array($data)){
692
+    protected function getPreparedQuery($query, $data) {
693
+      if (is_array($data)) {
694 694
   			$x = explode('?', $query);
695 695
   			$q = '';
696
-  			foreach($x as $k => $v){
697
-  			  if (! empty($v)){
696
+  			foreach ($x as $k => $v) {
697
+  			  if (!empty($v)) {
698 698
   				  $q .= $v . (isset($data[$k]) ? $this->escape($data[$k]) : '');
699 699
   			  }
700 700
   			}
@@ -709,9 +709,9 @@  discard block
 block discarded – undo
709 709
      *      
710 710
      * @return mixed
711 711
      */
712
-    protected function getCacheContentForQuery($query, $all, $array){
712
+    protected function getCacheContentForQuery($query, $all, $array) {
713 713
         $cacheKey = $this->getCacheBenchmarkKeyForQuery($query, $all, $array);
714
-        if (! is_object($this->getCacheInstance())){
714
+        if (!is_object($this->getCacheInstance())) {
715 715
     			//can not call method with reference in argument
716 716
     			//like $this->setCacheInstance(& get_instance()->cache);
717 717
     			//use temporary variable
@@ -729,10 +729,10 @@  discard block
 block discarded – undo
729 729
      * @param boolean $status whether can save the query result into cache
730 730
      * @param int $expire the cache TTL
731 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())){
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 736
       				//can not call method with reference in argument
737 737
       				//like $this->setCacheInstance(& get_instance()->cache);
738 738
       				//use temporary variable
@@ -747,7 +747,7 @@  discard block
 block discarded – undo
747 747
     /**
748 748
      * Set error for database query execution
749 749
      */
750
-    protected function setQueryError(){
750
+    protected function setQueryError() {
751 751
       $error = $this->pdo->errorInfo();
752 752
       $this->error = isset($error[2]) ? $error[2] : '';
753 753
       $this->logger->error('The database query execution got error: ' . stringfy_vars($error));
@@ -761,8 +761,8 @@  discard block
 block discarded – undo
761 761
      * 
762 762
      *  @return string
763 763
      */
764
-    protected function getCacheBenchmarkKeyForQuery($query, $all, $array){
765
-      if (is_array($all)){
764
+    protected function getCacheBenchmarkKeyForQuery($query, $all, $array) {
765
+      if (is_array($all)) {
766 766
         $all = 'array';
767 767
       }
768 768
       return md5($query . $all . $array);
@@ -772,12 +772,12 @@  discard block
 block discarded – undo
772 772
      * Set the Log instance using argument or create new instance
773 773
      * @param object $logger the Log instance if not null
774 774
      */
775
-    protected function setLoggerFromParamOrCreateNewInstance(Log $logger = null){
776
-      if ($logger !== null){
775
+    protected function setLoggerFromParamOrCreateNewInstance(Log $logger = null) {
776
+      if ($logger !== null) {
777 777
         $this->setLogger($logger);
778 778
       }
779
-      else{
780
-          $this->logger =& class_loader('Log', 'classes');
779
+      else {
780
+          $this->logger = & class_loader('Log', 'classes');
781 781
           $this->logger->setLogger('Library::Database');
782 782
       }
783 783
     }
@@ -786,19 +786,19 @@  discard block
 block discarded – undo
786 786
    * Set the DatabaseQueryBuilder instance using argument or create new instance
787 787
    * @param object $queryBuilder the DatabaseQueryBuilder instance if not null
788 788
    */
789
-	protected function setQueryBuilderFromParamOrCreateNewInstance(DatabaseQueryBuilder $queryBuilder = null){
790
-	  if ($queryBuilder !== null){
789
+	protected function setQueryBuilderFromParamOrCreateNewInstance(DatabaseQueryBuilder $queryBuilder = null) {
790
+	  if ($queryBuilder !== null) {
791 791
       $this->setQueryBuilder($queryBuilder);
792 792
 	  }
793
-	  else{
794
-		  $this->queryBuilder =& class_loader('DatabaseQueryBuilder', 'classes');
793
+	  else {
794
+		  $this->queryBuilder = & class_loader('DatabaseQueryBuilder', 'classes');
795 795
 	  }
796 796
 	}
797 797
 
798 798
     /**
799 799
      * Reset the database class attributs to the initail values before each query.
800 800
      */
801
-    private function reset(){
801
+    private function reset() {
802 802
 	   //query builder reset
803 803
       $this->getQueryBuilder()->reset();
804 804
       $this->numRows  = 0;
@@ -812,7 +812,7 @@  discard block
 block discarded – undo
812 812
     /**
813 813
      * The class destructor
814 814
      */
815
-    public function __destruct(){
815
+    public function __destruct() {
816 816
       $this->pdo = null;
817 817
     }
818 818
 
Please login to merge, or discard this patch.
core/libraries/Html.php 1 patch
Spacing   +43 added lines, -43 removed lines patch added patch discarded remove patch
@@ -24,7 +24,7 @@  discard block
 block discarded – undo
24 24
 	 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
25 25
 	*/
26 26
 
27
-	class Html{
27
+	class Html {
28 28
 
29 29
 		/**
30 30
 		 * Generate the html anchor link
@@ -35,21 +35,21 @@  discard block
 block discarded – undo
35 35
 		 *
36 36
 		 * @return string|void             the anchor link generated html if $return is true or display it if not
37 37
 		 */
38
-		public static function a($link = '', $anchor = null, array $attributes = array(), $return = true){
39
-			if(! is_url($link)){
38
+		public static function a($link = '', $anchor = null, array $attributes = array(), $return = true) {
39
+			if (!is_url($link)) {
40 40
 				$link = Url::site_url($link);
41 41
 			}
42
-			if(! $anchor){
42
+			if (!$anchor) {
43 43
 				$anchor = $link;
44 44
 			}
45 45
 			$str = null;
46
-			$str .= '<a href = "'.$link.'"';
46
+			$str .= '<a href = "' . $link . '"';
47 47
 			$str .= attributes_to_string($attributes);
48 48
 			$str .= '>';
49 49
 			$str .= $anchor;
50 50
 			$str .= '</a>';
51 51
 
52
-			if($return){
52
+			if ($return) {
53 53
 				return $str;
54 54
 			}
55 55
 			echo $str;
@@ -64,18 +64,18 @@  discard block
 block discarded – undo
64 64
 		 *
65 65
 		 * @return string|void             the generated html for mailto link if $return is true or display it if not
66 66
 		 */
67
-		public static function mailto($link, $anchor = null, array $attributes = array(), $return = true){
68
-			if(! $anchor){
67
+		public static function mailto($link, $anchor = null, array $attributes = array(), $return = true) {
68
+			if (!$anchor) {
69 69
 				$anchor = $link;
70 70
 			}
71 71
 			$str = null;
72
-			$str .= '<a href = "mailto:'.$link.'"';
72
+			$str .= '<a href = "mailto:' . $link . '"';
73 73
 			$str .= attributes_to_string($attributes);
74 74
 			$str .= '>';
75 75
 			$str .= $anchor;
76 76
 			$str .= '</a>';
77 77
 
78
-			if($return){
78
+			if ($return) {
79 79
 				return $str;
80 80
 			}
81 81
 			echo $str;
@@ -88,14 +88,14 @@  discard block
 block discarded – undo
88 88
 		 *
89 89
 		 * @return string|void      the generated "br" html if $return is true or display it if not
90 90
 		 */
91
-		public static function br($nb = 1, $return = true){
91
+		public static function br($nb = 1, $return = true) {
92 92
 			$nb = (int) $nb;
93 93
 			$str = null;
94 94
 			for ($i = 1; $i <= $nb; $i++) {
95 95
 				$str .= '<br />';
96 96
 			}
97 97
 
98
-			if($return){
98
+			if ($return) {
99 99
 				return $str;
100 100
 			}
101 101
 			echo $str;
@@ -109,13 +109,13 @@  discard block
 block discarded – undo
109 109
 		 *
110 110
 		 * @return string|void the generated "hr" html if $return is true or display it if not.
111 111
 		 */
112
-		public static function hr($nb = 1, array $attributes = array(), $return = true){
112
+		public static function hr($nb = 1, array $attributes = array(), $return = true) {
113 113
 			$nb = (int) $nb;
114 114
 			$str = null;
115 115
 			for ($i = 1; $i <= $nb; $i++) {
116
-				$str .= '<hr' .attributes_to_string($attributes). ' />';
116
+				$str .= '<hr' . attributes_to_string($attributes) . ' />';
117 117
 			}
118
-			if($return){
118
+			if ($return) {
119 119
 				return $str;
120 120
 			}
121 121
 			echo $str;
@@ -131,17 +131,17 @@  discard block
 block discarded – undo
131 131
 		 *
132 132
 		 * @return string|void the generated header html if $return is true or display it if not.
133 133
 		 */
134
-		public static function head($type = 1, $text = null, $nb = 1, array $attributes = array(), $return = true){
134
+		public static function head($type = 1, $text = null, $nb = 1, array $attributes = array(), $return = true) {
135 135
 			$nb = (int) $nb;
136 136
 			$type = (int) $type;
137
-			if($type <= 0 || $type > 6){
137
+			if ($type <= 0 || $type > 6) {
138 138
 				$type = 1;
139 139
 			}
140 140
 			$str = null;
141 141
 			for ($i = 1; $i <= $nb; $i++) {
142
-				$str .= '<h' . $type . attributes_to_string($attributes). '>' .$text. '</h' . $type . '>';
142
+				$str .= '<h' . $type . attributes_to_string($attributes) . '>' . $text . '</h' . $type . '>';
143 143
 			}
144
-			if($return){
144
+			if ($return) {
145 145
 				return $str;
146 146
 			}
147 147
 			echo $str;
@@ -156,15 +156,15 @@  discard block
 block discarded – undo
156 156
 		 *
157 157
 		 * @return string|void the generated "ul" html  if $return is true or display it if not.
158 158
 		 */
159
-		public static function ul($data = array(), $attributes = array(), $return = true){
159
+		public static function ul($data = array(), $attributes = array(), $return = true) {
160 160
 			$data = (array) $data;
161 161
 			$str = null;
162
-			$str .= '<ul' . (! empty($attributes['ul']) ? attributes_to_string($attributes['ul']):'') . '>';
162
+			$str .= '<ul' . (!empty($attributes['ul']) ? attributes_to_string($attributes['ul']) : '') . '>';
163 163
 			foreach ($data as $row) {
164
-				$str .= '<li' . (! empty($attributes['li']) ? attributes_to_string($attributes['li']):'') .'>' .$row. '</li>';
164
+				$str .= '<li' . (!empty($attributes['li']) ? attributes_to_string($attributes['li']) : '') . '>' . $row . '</li>';
165 165
 			}
166 166
 			$str .= '</ul>';
167
-			if($return){
167
+			if ($return) {
168 168
 				return $str;
169 169
 			}
170 170
 			echo $str;
@@ -178,15 +178,15 @@  discard block
 block discarded – undo
178 178
 		 * @param  boolean $return whether need return the generated html or just display it directly
179 179
 		 * @return string|void the generated "ol" html  if $return is true or display it if not.
180 180
 		 */
181
-		public static function ol($data = array(), $attributes = array(), $return = true){
181
+		public static function ol($data = array(), $attributes = array(), $return = true) {
182 182
 			$data = (array) $data;
183 183
 			$str = null;
184
-			$str .= '<ol' . (!empty($attributes['ol']) ? attributes_to_string($attributes['ol']):'') . '>';
184
+			$str .= '<ol' . (!empty($attributes['ol']) ? attributes_to_string($attributes['ol']) : '') . '>';
185 185
 			foreach ($data as $row) {
186
-				$str .= '<li' . (!empty($attributes['li']) ? attributes_to_string($attributes['li']):'') .'>' .$row. '</li>';
186
+				$str .= '<li' . (!empty($attributes['li']) ? attributes_to_string($attributes['li']) : '') . '>' . $row . '</li>';
187 187
 			}
188 188
 			$str .= '</ol>';
189
-			if($return){
189
+			if ($return) {
190 190
 				return $str;
191 191
 			}
192 192
 			echo $str;
@@ -204,46 +204,46 @@  discard block
 block discarded – undo
204 204
 		 * @param  boolean $return whether need return the generated html or just display it directly
205 205
 		 * @return string|void the generated "table" html  if $return is true or display it if not.
206 206
 		 */
207
-		public static function table($headers = array(), $body = array(), $attributes = array(), $use_footer = false, $return = true){
207
+		public static function table($headers = array(), $body = array(), $attributes = array(), $use_footer = false, $return = true) {
208 208
 			$headers = (array) $headers;
209 209
 			$body = (array) $body;
210 210
 			$str = null;
211
-			$str .= '<table' . (! empty($attributes['table']) ? attributes_to_string($attributes['table']):'') . '>';
212
-			if(! empty($headers)){
213
-				$str .= '<thead' . (! empty($attributes['thead']) ? attributes_to_string($attributes['thead']):'') .'>';
214
-				$str .= '<tr' . (! empty($attributes['thead_tr']) ? attributes_to_string($attributes['thead_tr']):'') .'>';
211
+			$str .= '<table' . (!empty($attributes['table']) ? attributes_to_string($attributes['table']) : '') . '>';
212
+			if (!empty($headers)) {
213
+				$str .= '<thead' . (!empty($attributes['thead']) ? attributes_to_string($attributes['thead']) : '') . '>';
214
+				$str .= '<tr' . (!empty($attributes['thead_tr']) ? attributes_to_string($attributes['thead_tr']) : '') . '>';
215 215
 				foreach ($headers as $value) {
216
-					$str .= '<th' . (! empty($attributes['thead_th']) ? attributes_to_string($attributes['thead_th']):'') .'>' .$value. '</th>';
216
+					$str .= '<th' . (!empty($attributes['thead_th']) ? attributes_to_string($attributes['thead_th']) : '') . '>' . $value . '</th>';
217 217
 				}
218 218
 				$str .= '</tr>';
219 219
 				$str .= '</thead>';
220 220
 			}
221
-			else{
221
+			else {
222 222
 				//no need check for footer
223 223
 				$use_footer = false;
224 224
 			}
225
-			$str .= '<tbody' . (! empty($attributes['tbody']) ? attributes_to_string($attributes['tbody']):'') .'>';
225
+			$str .= '<tbody' . (!empty($attributes['tbody']) ? attributes_to_string($attributes['tbody']) : '') . '>';
226 226
 			foreach ($body as $row) {
227
-				if(is_array($row)){
228
-					$str .= '<tr' . (! empty($attributes['tbody_tr']) ? attributes_to_string($attributes['tbody_tr']):'') .'>';
227
+				if (is_array($row)) {
228
+					$str .= '<tr' . (!empty($attributes['tbody_tr']) ? attributes_to_string($attributes['tbody_tr']) : '') . '>';
229 229
 					foreach ($row as $value) {
230
-						$str .= '<td' . (! empty($attributes['tbody_td']) ? attributes_to_string($attributes['tbody_td']):'') .'>' .$value. '</td>';	
230
+						$str .= '<td' . (!empty($attributes['tbody_td']) ? attributes_to_string($attributes['tbody_td']) : '') . '>' . $value . '</td>';	
231 231
 					}
232 232
 					$str .= '</tr>';
233 233
 				}
234 234
 			}
235 235
 			$str .= '</tbody>';
236
-			if($use_footer){
237
-				$str .= '<tfoot' . (! empty($attributes['tfoot']) ? attributes_to_string($attributes['tfoot']):'') .'>';
238
-				$str .= '<tr' . (! empty($attributes['tfoot_tr']) ? attributes_to_string($attributes['tfoot_tr']):'') .'>';
236
+			if ($use_footer) {
237
+				$str .= '<tfoot' . (!empty($attributes['tfoot']) ? attributes_to_string($attributes['tfoot']) : '') . '>';
238
+				$str .= '<tr' . (!empty($attributes['tfoot_tr']) ? attributes_to_string($attributes['tfoot_tr']) : '') . '>';
239 239
 				foreach ($headers as $value) {
240
-					$str .= '<th' . (! empty($attributes['tfoot_th']) ? attributes_to_string($attributes['tfoot_th']):'') .'>' .$value. '</th>';
240
+					$str .= '<th' . (!empty($attributes['tfoot_th']) ? attributes_to_string($attributes['tfoot_th']) : '') . '>' . $value . '</th>';
241 241
 				}
242 242
 				$str .= '</tr>';
243 243
 				$str .= '</tfoot>';
244 244
 			}
245 245
 			$str .= '</table>';
246
-			if($return){
246
+			if ($return) {
247 247
 				return $str;
248 248
 			}
249 249
 			echo $str;
Please login to merge, or discard this patch.
core/libraries/Upload.php 2 patches
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.
Spacing   +48 added lines, -48 removed lines patch added patch discarded remove patch
@@ -37,7 +37,7 @@  discard block
 block discarded – undo
37 37
     *    @package FileUpload
38 38
     *    @version 1.5
39 39
     */
40
-    class Upload{
40
+    class Upload {
41 41
 
42 42
         /**
43 43
         *   Version
@@ -69,7 +69,7 @@  discard block
 block discarded – undo
69 69
         *    @version    1.0
70 70
         *    @var        array
71 71
         */
72
-        private $file_array    = array();
72
+        private $file_array = array();
73 73
 
74 74
         /**
75 75
         *    If the file you are trying to upload already exists it will
@@ -119,7 +119,7 @@  discard block
 block discarded – undo
119 119
         *    @version    1.0
120 120
         *    @var        float
121 121
         */
122
-        private $max_file_size= 0.0;
122
+        private $max_file_size = 0.0;
123 123
 
124 124
         /**
125 125
         *    List of allowed mime types
@@ -217,12 +217,12 @@  discard block
 block discarded – undo
217 217
         *    @return    object
218 218
         *    @method    object    __construct
219 219
         */
220
-        public function __construct(){
221
-            $this->logger =& class_loader('Log', 'classes');
220
+        public function __construct() {
221
+            $this->logger = & class_loader('Log', 'classes');
222 222
             $this->logger->setLogger('Library::Upload');
223 223
 
224 224
             Loader::lang('file_upload');
225
-            $obj =& get_instance();
225
+            $obj = & get_instance();
226 226
 
227 227
             $this->error_messages = array(
228 228
                 'upload_err_ini_size' => $obj->lang->get('fu_upload_err_ini_size'),
@@ -239,15 +239,15 @@  discard block
 block discarded – undo
239 239
             );
240 240
 
241 241
             $this->file = array(
242
-                'status'                =>    false,    // True: success upload
243
-                'mime'                  =>    '',       // Empty string
244
-                'filename'              =>    '',       // Empty string
245
-                'original'              =>    '',       // Empty string
246
-                'size'                  =>    0,        // 0 Bytes
247
-                'sizeFormated'          =>    '0B',     // 0 Bytes
248
-                'destination'           =>    './',     // Default: ./
249
-                'allowed_mime_types'    =>    array(),  // Allowed mime types
250
-                'error'                 =>    null,        // File error
242
+                'status'                =>    false, // True: success upload
243
+                'mime'                  =>    '', // Empty string
244
+                'filename'              =>    '', // Empty string
245
+                'original'              =>    '', // Empty string
246
+                'size'                  =>    0, // 0 Bytes
247
+                'sizeFormated'          =>    '0B', // 0 Bytes
248
+                'destination'           =>    './', // Default: ./
249
+                'allowed_mime_types'    =>    array(), // Allowed mime types
250
+                'error'                 =>    null, // File error
251 251
             );
252 252
 
253 253
             // Change dir to current dir
@@ -257,7 +257,7 @@  discard block
 block discarded – undo
257 257
             if (isset($_FILES) && is_array($_FILES)) {
258 258
                 $this->file_array = $_FILES;
259 259
             }
260
-            $this->logger->info('The upload file information are : ' .stringfy_vars($this->file_array));
260
+            $this->logger->info('The upload file information are : ' . stringfy_vars($this->file_array));
261 261
         }
262 262
         /**
263 263
         *    Set input.
@@ -273,7 +273,7 @@  discard block
 block discarded – undo
273 273
         */
274 274
         public function setInput($input)
275 275
         {
276
-            if (!empty($input) && (is_string($input) || is_numeric($input) )) {
276
+            if (!empty($input) && (is_string($input) || is_numeric($input))) {
277 277
                 $this->input = $input;
278 278
             }
279 279
             return $this;
@@ -309,7 +309,7 @@  discard block
 block discarded – undo
309 309
         */
310 310
         public function setAutoFilename()
311 311
         {
312
-            $this->filename = sha1(mt_rand(1, 9999).uniqid());
312
+            $this->filename = sha1(mt_rand(1, 9999) . uniqid());
313 313
             $this->filename .= time();
314 314
             return $this;
315 315
         }
@@ -330,7 +330,7 @@  discard block
 block discarded – undo
330 330
                 $php_size = $this->sizeInBytes((int) ini_get('upload_max_filesize'));
331 331
                 // Calculate difference
332 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. ']');
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 334
                 }
335 335
                 $this->max_file_size = $file_size;
336 336
             }
@@ -348,7 +348,7 @@  discard block
 block discarded – undo
348 348
         public function setAllowedMimeTypes(array $mimes)
349 349
         {
350 350
             if (count($mimes) > 0) {
351
-                array_map(array($this , 'setAllowMimeType'), $mimes);
351
+                array_map(array($this, 'setAllowMimeType'), $mimes);
352 352
             }
353 353
             return $this;
354 354
         }
@@ -413,7 +413,7 @@  discard block
 block discarded – undo
413 413
         {
414 414
             if (!empty($name) && is_string($name)) {
415 415
                 if (array_key_exists($name, $this->mime_helping)) {
416
-                    return $this->setAllowedMimeTypes($this->mime_helping[ $name ]);
416
+                    return $this->setAllowedMimeTypes($this->mime_helping[$name]);
417 417
                 }
418 418
             }
419 419
             return $this;
@@ -432,8 +432,8 @@  discard block
 block discarded – undo
432 432
         */
433 433
         public function setUploadFunction($function)
434 434
         {
435
-            if (!empty($function) && (is_array($function) || is_string($function) )) {
436
-                if (is_callable( $function)) {
435
+            if (!empty($function) && (is_array($function) || is_string($function))) {
436
+                if (is_callable($function)) {
437 437
                     $this->upload_function = $function;
438 438
                 }
439 439
             }
@@ -478,8 +478,8 @@  discard block
 block discarded – undo
478 478
                         $this->destination_directory = $destination_directory;
479 479
                         chdir($destination_directory);
480 480
                     }
481
-                    else{
482
-                        $this->logger->warning('Can not create the upload directory [' .$destination_directory. ']');
481
+                    else {
482
+                        $this->logger->warning('Can not create the upload directory [' . $destination_directory . ']');
483 483
                     }
484 484
                 }
485 485
             }
@@ -529,7 +529,7 @@  discard block
 block discarded – undo
529 529
         public function isFilename($filename)
530 530
         {
531 531
             $filename = basename($filename);
532
-            return (!empty($filename) && (is_string( $filename) || is_numeric($filename)));
532
+            return (!empty($filename) && (is_string($filename) || is_numeric($filename)));
533 533
         }
534 534
         /**
535 535
         *    Validate mime type with allowed mime types,
@@ -571,11 +571,11 @@  discard block
 block discarded – undo
571 571
         */
572 572
         public function isDirpath($path)
573 573
         {
574
-            if (!empty( $path) && (is_string( $path) || is_numeric($path) )) {
574
+            if (!empty($path) && (is_string($path) || is_numeric($path))) {
575 575
                 if (DIRECTORY_SEPARATOR == '/') {
576
-                    return (preg_match( '/^[^*?"<>|:]*$/' , $path) == 1 );
576
+                    return (preg_match('/^[^*?"<>|:]*$/', $path) == 1);
577 577
                 } else {
578
-                    return (preg_match( "/^[^*?\"<>|:]*$/" , substr($path,2) ) == 1);
578
+                    return (preg_match("/^[^*?\"<>|:]*$/", substr($path, 2)) == 1);
579 579
                 }
580 580
             }
581 581
             return false;
@@ -603,7 +603,7 @@  discard block
 block discarded – undo
603 603
         */
604 604
         public function getInfo()
605 605
         {
606
-            return (object)$this->file;
606
+            return (object) $this->file;
607 607
         }
608 608
 
609 609
 
@@ -611,7 +611,7 @@  discard block
 block discarded – undo
611 611
          * Check if the file is uploaded
612 612
          * @return boolean
613 613
          */
614
-        public function isUploaded(){
614
+        public function isUploaded() {
615 615
             return isset($this->file_array[$this->input])
616 616
             && is_uploaded_file($this->file_array[$this->input]['tmp_name']);
617 617
         }
@@ -620,15 +620,15 @@  discard block
 block discarded – undo
620 620
          * Check if file upload has error
621 621
          * @return boolean
622 622
          */
623
-        protected function uploadHasError(){
623
+        protected function uploadHasError() {
624 624
             //check if file upload is  allowed in the configuration
625
-            if(! ini_get('file_uploads')){
625
+            if (!ini_get('file_uploads')) {
626 626
                 $this->setError($this->error_messages['file_uploads']);
627 627
                 return true;
628 628
             }
629 629
 
630 630
              //check for php upload error
631
-            if(is_numeric($this->file['error']) && $this->file['error'] > 0){
631
+            if (is_numeric($this->file['error']) && $this->file['error'] > 0) {
632 632
                 $this->setError($this->getPhpUploadErrorMessageByCode($this->file['error']));
633 633
                 return true;
634 634
             }
@@ -663,14 +663,14 @@  discard block
 block discarded – undo
663 663
         *    @return    boolean
664 664
         *    @method    boolean    save
665 665
         */
666
-        public function save(){
666
+        public function save() {
667 667
             if (count($this->file_array) > 0) {
668 668
                 if (array_key_exists($this->input, $this->file_array)) {
669 669
                     // set original filename if not have a new name
670 670
                     if (empty($this->filename)) {
671 671
                         $this->filename = $this->file_array[$this->input]['name'];
672 672
                     }
673
-                    else{
673
+                    else {
674 674
                         // Replace %s for extension in filename
675 675
                         // Before: /[\w\d]*(.[\d\w]+)$/i
676 676
                         // After: /^[\s[:alnum:]\-\_\.]*\.([\d\w]+)$/iu
@@ -694,15 +694,15 @@  discard block
 block discarded – undo
694 694
                     $this->file['filename']     = $this->filename;
695 695
                     $this->file['error']        = $this->file_array[$this->input]['error'];
696 696
 
697
-                    $this->logger->info('The upload file information to process is : ' .stringfy_vars($this->file));
697
+                    $this->logger->info('The upload file information to process is : ' . stringfy_vars($this->file));
698 698
 
699 699
                     $error = $this->uploadHasError();
700
-                    if($error){
700
+                    if ($error) {
701 701
                         return false;
702 702
                     }
703 703
                     // Execute input callback
704
-                    if (!empty( $this->callbacks['input'])) {
705
-                        call_user_func($this->callbacks['input'], (object)$this->file);
704
+                    if (!empty($this->callbacks['input'])) {
705
+                        call_user_func($this->callbacks['input'], (object) $this->file);
706 706
                     }
707 707
                    
708 708
 
@@ -714,8 +714,8 @@  discard block
 block discarded – undo
714 714
                     );
715 715
 
716 716
                     // Execute output callback
717
-                    if (!empty( $this->callbacks['output'])) {
718
-                        call_user_func($this->callbacks['output'], (object)$this->file);
717
+                    if (!empty($this->callbacks['output'])) {
718
+                        call_user_func($this->callbacks['output'], (object) $this->file);
719 719
                     }
720 720
                     return $this->file['status'];
721 721
                 }
@@ -734,10 +734,10 @@  discard block
 block discarded – undo
734 734
         */
735 735
         public function sizeFormat($size, $precision = 2)
736 736
         {
737
-            if($size > 0){
737
+            if ($size > 0) {
738 738
                 $base       = log($size) / log(1024);
739 739
                 $suffixes   = array('B', 'K', 'M', 'G', 'T');
740
-                return round(pow(1024, $base - floor($base)), $precision) . ( isset($suffixes[floor($base)]) ? $suffixes[floor($base)] : '');
740
+                return round(pow(1024, $base - floor($base)), $precision) . (isset($suffixes[floor($base)]) ? $suffixes[floor($base)] : '');
741 741
             }
742 742
             return null;
743 743
         }
@@ -761,14 +761,14 @@  discard block
 block discarded – undo
761 761
             if (array_key_exists('unit', $matches)) {
762 762
                 $unit = strtoupper($matches['unit']);
763 763
             }
764
-            return (floatval($matches['size']) * pow(1024, $units[$unit]) ) ;
764
+            return (floatval($matches['size']) * pow(1024, $units[$unit]));
765 765
         }
766 766
 
767 767
         /**
768 768
          * Get the upload error message
769 769
          * @return string
770 770
          */
771
-        public function getError(){
771
+        public function getError() {
772 772
             return $this->error;
773 773
         }
774 774
 
@@ -776,7 +776,7 @@  discard block
 block discarded – undo
776 776
          * Set the upload error message
777 777
          * @param string $message the upload error message to set
778 778
          */
779
-        public function setError($message){
779
+        public function setError($message) {
780 780
             $this->logger->info('The file upload got error : ' . $message);
781 781
             $this->error = $message;
782 782
         }
@@ -786,7 +786,7 @@  discard block
 block discarded – undo
786 786
          * @param  int $code the error code
787 787
          * @return string the error message
788 788
          */
789
-        private function getPhpUploadErrorMessageByCode($code){
789
+        private function getPhpUploadErrorMessageByCode($code) {
790 790
             $codeMessageMaps = array(
791 791
                 1 => $this->error_messages['upload_err_ini_size'],
792 792
                 2 => $this->error_messages['upload_err_form_size'],
Please login to merge, or discard this patch.