Completed
Push — master ( 3dc19b...4dfbc7 )
by Agel_Nash
03:42
created
assets/snippets/DLUsers/src/Actions.php 2 patches
Indentation   +403 added lines, -403 removed lines patch added patch discarded remove patch
@@ -12,9 +12,9 @@  discard block
 block discarded – undo
12 12
 class Actions{
13 13
     protected $modx = null;
14 14
     public $userObj = null;
15
-	/**
16
-	 * @var DLCollection
17
-	 */
15
+    /**
16
+     * @var DLCollection
17
+     */
18 18
     public $url;
19 19
     protected static $lang = null;
20 20
     protected static $langDic = array();
@@ -23,7 +23,7 @@  discard block
 block discarded – undo
23 23
      */
24 24
     protected static $instance;
25 25
 
26
-	protected $config = array();
26
+    protected $config = array();
27 27
 
28 28
     /**
29 29
      * gets the instance via lazy initialization (created on first usage)
@@ -50,15 +50,15 @@  discard block
 block discarded – undo
50 50
     private function __construct(DocumentParser $modx, $userClass, $debug)
51 51
     {
52 52
         $this->modx = $modx;
53
-		$this->userObj = new $userClass($this->modx, $debug);
54
-		$this->url = new DLCollection($this->modx);
53
+        $this->userObj = new $userClass($this->modx, $debug);
54
+        $this->url = new DLCollection($this->modx);
55 55
 
56
-		$site_url = $this->modx->getConfig('site_url');
57
-		$site_start = $this->modx->getConfig('site_start', 1);
58
-		$error_page = $this->modx->getConfig('error_page', $site_start);
59
-		$unauthorized_page = $this->modx->getConfig('unauthorized_page', $error_page);
56
+        $site_url = $this->modx->getConfig('site_url');
57
+        $site_start = $this->modx->getConfig('site_start', 1);
58
+        $error_page = $this->modx->getConfig('error_page', $site_start);
59
+        $unauthorized_page = $this->modx->getConfig('unauthorized_page', $error_page);
60 60
 
61
-		$this->config = compact('site_url', 'site_start', 'error_page', 'unauthorized_page');
61
+        $this->config = compact('site_url', 'site_start', 'error_page', 'unauthorized_page');
62 62
     }
63 63
 
64 64
     /**
@@ -85,48 +85,48 @@  discard block
 block discarded – undo
85 85
      * Сброс авторизации и обновление страницы
86 86
      */
87 87
     public function logout($params){
88
-    	$LogoutName = APIHelpers::getkey($params, 'LogoutName', 'logout');
89
-    	if(is_scalar($LogoutName) && !empty($LogoutName) && isset($_GET[$LogoutName])){
90
-    		$type = 'web';
91
-    		$userID = $this->UserID(compact('type'));
92
-    		if($userID){
93
-    			$this->userObj->edit($userID);
94
-    			if($this->userObj->getID()){
95
-	    			$this->modx->invokeEvent("OnBeforeWebLogout", array(
96
-		    			"userid"   => $this->userObj->getID(),
97
-		    			"username" => $this->userObj->get('username')
98
-		    		));
99
-	    		}
100
-		    	$this->userObj->logOut();
101
-		    	if($this->userObj->getID()){
102
-		    		$this->modx->invokeEvent("OnWebLogout", array(
103
-		    			"userid"        => $this->userObj->getID(),
104
-		    			"username"      => $this->userObj->get('username')
105
-		    		));
106
-		    	}
107
-
108
-			    $go = APIHelpers::getkey($params, 'url', '');
109
-			    if(empty($go)){
110
-			    	$go = str_replace(
111
-			    		array("?".$LogoutName, "&".$LogoutName),
112
-			    		array("", ""),
113
-			    		$_SERVER['REQUEST_URI']
114
-			    	);
115
-			    }
116
-
117
-			    $start = $this->makeUrl($this->config['site_start']);
118
-			    if($start == $go){
119
-			        $go = $this->config['site_url'];
120
-			    }else{
121
-			        $go = $this->config['site_url'].ltrim($go, '/');
122
-			    }
123
-			    $this->moveTo(array('url' => $go));
124
-    		}else{
125
-    			//Если юзер не авторизован, то показываем ему 404 ошибку
126
-    			$this->modx->sendErrorPage();
127
-    		}
128
-		}
129
-	    return true;
88
+        $LogoutName = APIHelpers::getkey($params, 'LogoutName', 'logout');
89
+        if(is_scalar($LogoutName) && !empty($LogoutName) && isset($_GET[$LogoutName])){
90
+            $type = 'web';
91
+            $userID = $this->UserID(compact('type'));
92
+            if($userID){
93
+                $this->userObj->edit($userID);
94
+                if($this->userObj->getID()){
95
+                    $this->modx->invokeEvent("OnBeforeWebLogout", array(
96
+                        "userid"   => $this->userObj->getID(),
97
+                        "username" => $this->userObj->get('username')
98
+                    ));
99
+                }
100
+                $this->userObj->logOut();
101
+                if($this->userObj->getID()){
102
+                    $this->modx->invokeEvent("OnWebLogout", array(
103
+                        "userid"        => $this->userObj->getID(),
104
+                        "username"      => $this->userObj->get('username')
105
+                    ));
106
+                }
107
+
108
+                $go = APIHelpers::getkey($params, 'url', '');
109
+                if(empty($go)){
110
+                    $go = str_replace(
111
+                        array("?".$LogoutName, "&".$LogoutName),
112
+                        array("", ""),
113
+                        $_SERVER['REQUEST_URI']
114
+                    );
115
+                }
116
+
117
+                $start = $this->makeUrl($this->config['site_start']);
118
+                if($start == $go){
119
+                    $go = $this->config['site_url'];
120
+                }else{
121
+                    $go = $this->config['site_url'].ltrim($go, '/');
122
+                }
123
+                $this->moveTo(array('url' => $go));
124
+            }else{
125
+                //Если юзер не авторизован, то показываем ему 404 ошибку
126
+                $this->modx->sendErrorPage();
127
+            }
128
+        }
129
+        return true;
130 130
     }
131 131
 
132 132
     /**
@@ -134,14 +134,14 @@  discard block
 block discarded – undo
134 134
      * @return string
135 135
      */
136 136
     public function logoutUrl($params){
137
-    	$LogoutName = APIHelpers::getkey($params, 'LogoutName', 'logout');
138
-    	$request = parse_url($_SERVER['REQUEST_URI']);
137
+        $LogoutName = APIHelpers::getkey($params, 'LogoutName', 'logout');
138
+        $request = parse_url($_SERVER['REQUEST_URI']);
139 139
 
140
-    	//Во избежании XSS мы не сохраняем весь REQUEST_URI, а берем только path
141
-    	/*$query = (!empty($request['query'])) ? $request['query'].'&' : '';*/
142
-    	$query = '?'.$LogoutName;
140
+        //Во избежании XSS мы не сохраняем весь REQUEST_URI, а берем только path
141
+        /*$query = (!empty($request['query'])) ? $request['query'].'&' : '';*/
142
+        $query = '?'.$LogoutName;
143 143
 
144
-    	return $request['path'].$query;
144
+        return $request['path'].$query;
145 145
     }
146 146
 
147 147
     /**
@@ -150,350 +150,350 @@  discard block
 block discarded – undo
150 150
      *   	В противном случае вся работа происходит внутри самого блока
151 151
      */
152 152
     public function AuthBlock($params){
153
-    	$POST = array('backUrl' => $_SERVER['REQUEST_URI']);
154
-
155
-    	$error = $errorCode = '';
156
-
157
-    	$pwdField = APIHelpers::getkey($params, 'pwdField', 'password');
158
-		$emailField = APIHelpers::getkey($params, 'emailField', 'email');
159
-		$rememberField = APIHelpers::getkey($params, 'rememberField', 'remember');
160
-
161
-    	$type = 'web';
162
-		if($this->UserID(compact('type'))){
163
-			$tpl = APIHelpers::getkey($params, 'tplProfile', '');
164
-			if(empty($tpl)){
165
-				$tpl = $this->getTemplate('tplProfile');
166
-			}
167
-			$dataTPL = $this->userObj->toArray();
168
-			$dataTPL['url.logout'] = $this->logoutUrl($params);
169
-    		$homeID = APIHelpers::getkey($params, 'homeID');
170
-			if(!empty($homeID)){
171
-				$dataTPL['url.profile'] = $this->makeUrl($homeID);
172
-			}
173
-		}else{
174
-			$tpl = APIHelpers::getkey($params, 'tplForm', '');
175
-			if(empty($tpl)){
176
-				$tpl = $this->getTemplate('authForm');
177
-			}
178
-			$POST = $this->Auth($pwdField, $emailField, $rememberField, $POST['backUrl'], __METHOD__, $error, $errorCode, $params);
179
-	    	$dataTPL = array(
180
-				'backUrl' => APIHelpers::getkey($POST, 'backUrl', ''),
181
-				'emailValue' => APIHelpers::getkey($POST, 'email', ''),
182
-				'emailField' => $emailField,
183
-				'pwdField' => $pwdField,
184
-		    	'method' => strtolower(__METHOD__),
185
-				'error' => $error,
186
-				'errorCode' => $errorCode
187
-			);
188
-			$authId = APIHelpers::getkey($params, 'authId');
189
-			if(!empty($authId)){
190
-				$dataTPL['authPage'] = $this->makeUrl($authId);
191
-				$dataTPL['method'] = strtolower(__CLASS__ . '::'. 'authpage');
192
-			}
193
-		}
194
-		return DLTemplate::getInstance($this->modx)->parseChunk($tpl, $dataTPL);
153
+        $POST = array('backUrl' => $_SERVER['REQUEST_URI']);
154
+
155
+        $error = $errorCode = '';
156
+
157
+        $pwdField = APIHelpers::getkey($params, 'pwdField', 'password');
158
+        $emailField = APIHelpers::getkey($params, 'emailField', 'email');
159
+        $rememberField = APIHelpers::getkey($params, 'rememberField', 'remember');
160
+
161
+        $type = 'web';
162
+        if($this->UserID(compact('type'))){
163
+            $tpl = APIHelpers::getkey($params, 'tplProfile', '');
164
+            if(empty($tpl)){
165
+                $tpl = $this->getTemplate('tplProfile');
166
+            }
167
+            $dataTPL = $this->userObj->toArray();
168
+            $dataTPL['url.logout'] = $this->logoutUrl($params);
169
+            $homeID = APIHelpers::getkey($params, 'homeID');
170
+            if(!empty($homeID)){
171
+                $dataTPL['url.profile'] = $this->makeUrl($homeID);
172
+            }
173
+        }else{
174
+            $tpl = APIHelpers::getkey($params, 'tplForm', '');
175
+            if(empty($tpl)){
176
+                $tpl = $this->getTemplate('authForm');
177
+            }
178
+            $POST = $this->Auth($pwdField, $emailField, $rememberField, $POST['backUrl'], __METHOD__, $error, $errorCode, $params);
179
+            $dataTPL = array(
180
+                'backUrl' => APIHelpers::getkey($POST, 'backUrl', ''),
181
+                'emailValue' => APIHelpers::getkey($POST, 'email', ''),
182
+                'emailField' => $emailField,
183
+                'pwdField' => $pwdField,
184
+                'method' => strtolower(__METHOD__),
185
+                'error' => $error,
186
+                'errorCode' => $errorCode
187
+            );
188
+            $authId = APIHelpers::getkey($params, 'authId');
189
+            if(!empty($authId)){
190
+                $dataTPL['authPage'] = $this->makeUrl($authId);
191
+                $dataTPL['method'] = strtolower(__CLASS__ . '::'. 'authpage');
192
+            }
193
+        }
194
+        return DLTemplate::getInstance($this->modx)->parseChunk($tpl, $dataTPL);
195 195
     }
196 196
 
197
-	/**
198
-	 * Авторизация на сайте со страницы авторизации
199
-	 * [!Auth? &login=`password` &pwdField=`password` &homeID=`72`!]
200
-	 */
201
-	public function AuthPage($params){
202
-		$homeID = APIHelpers::getkey($params, 'homeID');
203
-		$this->isAuthGoHome(array('id' => $homeID));
204
-
205
-		$error = $errorCode = '';
206
-		$POST = array('backUrl' => '');
207
-
208
-		$pwdField = APIHelpers::getkey($params, 'pwdField', 'password');
209
-		$emailField = APIHelpers::getkey($params, 'emailField', 'email');
210
-		$rememberField = APIHelpers::getkey($params, 'rememberField', 'remember');
211
-
212
-		$tpl = APIHelpers::getkey($params, 'tpl', '');
213
-		if(empty($tpl)){
214
-			$tpl = $this->getTemplate('authForm');
215
-		}
216
-
217
-		$request = parse_url($_SERVER['REQUEST_URI']);
218
-		if(!empty($_SERVER['HTTP_REFERER'])){
219
-			/**
220
-			 * Thank you for super protection against hacking in protect.inc.php:-)
221
-			 */
222
-			$refer = htmlspecialchars_decode($_SERVER['HTTP_REFERER'], ENT_QUOTES);
223
-		}else{
224
-			$selfHost = rtrim(str_replace("http://", "", $this->config['site_url']), '/');
225
-			if(empty( $request['host']) ||  $request['host']==$selfHost){
226
-				$query = !empty($request['query']) ? '?'.$request['query'] : '';
227
-			    $refer = !empty($request['path']) ? $request['path'].$query : '';
228
-			}else{
229
-				$refer = '';
230
-			}
231
-		}
232
-
233
-		if($_SERVER['REQUEST_METHOD'] == 'POST'){
234
-			$backUrl = APIHelpers::getkey($_POST, 'backUrl', $POST['backUrl']);
235
-			if(!is_scalar($backUrl)){
236
-				$backUrl = $refer;
237
-			}else{
238
-				$backUrl = urldecode($backUrl);
239
-			}
240
-		}else{
241
-			$backUrl = $refer;
242
-		}
243
-		$backUrl = parse_url($backUrl);
244
-		if(!empty($backUrl['path']) && $request['path'] != $backUrl['path']){
245
-		    $POST['backUrl'] = $backUrl['path'];
246
-		}else{
247
-			$selfHost = rtrim(str_replace("http://", "", $this->config['site_url']), '/');
248
-			if(empty($uri['host']) || $uri['host']==$selfHost){
249
-				$query = !empty($uri['query']) ? '?'.$uri['query'] : '';
250
-			    $POST['backUrl'] = !empty($uri['path']) ? $uri['path'].$query : '';
251
-			}else{
252
-				$POST['backUrl'] = '';
253
-			}
254
-		}
255
-		if(!empty($POST['backUrl'])){
256
-			$idURL = $this->moveTo(array(
257
-				'url' => '/'.ltrim($POST['backUrl'], '/'),
258
-			    'validate' => true
259
-			));
260
-		}else{
261
-			$idURL = 0;
262
-		}
263
-		if(empty($idURL)){
264
-			if(empty($homeID)){
265
-				$homeID = $this->config['site_start'];
266
-			}
267
-			$POST['backUrl'] = $this->makeUrl($homeID);
268
-		}
269
-		$POST = $this->Auth($pwdField, $emailField, $rememberField, $POST['backUrl'], __METHOD__, $error, $errorCode, $params);
270
-		return DLTemplate::getInstance($this->modx)->parseChunk($tpl, array(
271
-		    'backUrl' => APIHelpers::getkey($POST, 'backUrl', ''),
272
-			'emailValue' => APIHelpers::getkey($POST, 'email', ''),
273
-			'emailField' => $emailField,
274
-		    'pwdField' => $pwdField,
275
-		    'method' => strtolower(__METHOD__),
276
-			'error' => $error,
277
-			'errorCode' => $errorCode
278
-		));
279
-	}
280
-	protected function Auth($pwdField, $emailField, $rememberField, $backUrl, $method, &$error, &$errorCode, $params = array()){
281
-		$POST = array(
282
-			'backUrl' => urlencode($backUrl)
283
-		);
284
-		$userObj = &$this->userObj;
285
-		if($_SERVER['REQUEST_METHOD']=='POST' && APIHelpers::getkey($_POST, 'method', '') == strtolower($method)){
286
-			$POST = array_merge($POST, array(
287
-				'password' => APIHelpers::getkey($_POST, $pwdField, ''),
288
-				'email' => APIHelpers::getkey($_POST, $emailField, ''),
289
-				'remember' => (bool)((int)APIHelpers::getkey($_POST, $rememberField, 0))
290
-			));
291
-			if(!empty($POST['email']) && is_scalar($POST['email']) && !$userObj->emailValidate($POST['email'], false)){
292
-				$openUser = $userObj->edit($POST['email']);
293
-
294
-				$this->modx->invokeEvent("OnBeforeWebLogin", array(
295
-		            "username"		=> $POST['email'],
296
-		            "userpassword"	=> $POST['password'],
297
-		            "rememberme"	=> $POST['remember'],
298
-		            'userObj'		=> $userObj
299
-		        ));
300
-				if($userObj->getID() && !$userObj->checkBlock($userObj->getID())){
301
-					$pluginFlag = $this->modx->invokeEvent("OnWebAuthentication", array(
302
-	                    "userid"        => $userObj->getID(),
303
-	                    "username"      => $userObj->get('username'),
304
-	                    "userpassword"  => $POST['password'],
305
-	                    "savedpassword" => $userObj->get('password'),
306
-	                    "rememberme"    => $POST['remember'],
307
-	                ));
308
-					if(
309
-						($pluginFlag === true || $userObj->testAuth($userObj->getID(), $POST['password'], 0))
310
-							&&
311
-						$userObj->authUser($userObj->getID(), $POST['remember'])
312
-					){
313
-						$userObj->set('logincount', (int)$userObj->get('logincount') + 1);
314
-						$userObj->set('lastlogin', time());
315
-						$userObj->set('failedlogincount', 0);
316
-						$userObj->save(false, false);
317
-
318
-						$this->modx->invokeEvent("OnWebLogin", array(
319
-			                "userid"		=> $userObj->getID(),
320
-			                "username"		=> $userObj->get('username'),
321
-			                "userpassword"	=> $POST['password'],
322
-			                "rememberme"	=> $POST['remember'],
323
-			            ));
324
-						$this->moveTo(array('url' => urldecode($POST['backUrl'])));
325
-					}else{
326
-						$userObj->set('failedlogincount', (int)$userObj->get('failedlogincount') + 1);
327
-						$userObj->save(false, false);
328
-
329
-						$error = 'error.incorrect_password';
330
-					}
331
-				}else{
332
-					$error = 'error.no_user';
333
-				}
334
-			}else{
335
-				$error = 'error.incorrect_mail';
336
-				$POST['email'] = '';
337
-			}
338
-		}
339
-		if(!empty($error)){
340
-			$errorCode = $error;
341
-			$error = APIHelpers::getkey($params, $error, '');
342
-			$error = static::getLangMsg($error, $error);
343
-		}
344
-		return $POST;
345
-	}
346
-	/**
347
-	 * Информация о пользователе
348
-	 * [!DLUsers? &action=`UserInfo` &field=`fullname` &id=`2`!]
349
-	 */
350
-	public function UserInfo($params){
351
-		$out = '';
352
-		$type = 'web';
353
-		$userID = APIHelpers::getkey($params, 'id', 0);
354
-		if(empty($userID)){
355
-			$userID = $this->UserID(compact('type'));
356
-		}
357
-		$field = APIHelpers::getkey($params, 'field', 'username');
358
-		if($userID > 0){
359
-			$this->userObj->edit($userID);
360
-			switch(true){
361
-				case ($field == $this->userObj->fieldPKName()):{
362
-					$out = $this->userObj->getID();
363
-					break;
364
-				}
365
-				case ($this->userObj->issetField($field)):{
366
-					$out = $this->userObj->get($field);
367
-					break;
368
-				}
369
-			}
370
-		}
371
-		return $out;
372
-	}
373
-	/**
374
-	 * ID пользователя
375
-	 */
376
-	public function UserID($params){
377
-		$type = 'web';
378
-		return $this->modx->getLoginUserID($type);
379
-	}
380
-	/**
381
-	 * Если не авторизован - то отправить на страницу
382
-	 */
383
-	public function isGuestGoHome($params){
384
-		$type = 'web';
385
-		if(!$this->UserID(compact('type'))){
386
-			/**
387
-			 * @see : http://modx.im/blog/triks/105.html
388
-			 */
389
-			$this->modx->invokeEvent('OnPageUnauthorized');
390
-			$id = APIHelpers::getkey($params, 'id', $this->config['unauthorized_page']);
391
-		    $this->moveTo(compact('id'));
392
-		}
393
-		return;
394
-	}
395
-
396
-	/**
397
-	 * Если авторизован - то открыть личный кабинет
398
-	 */
399
-	public function isAuthGoHome($params){
400
-		$type = 'web';
401
-		$userID = $this->UserID(compact('type'));
402
-		if($userID>0){
403
-			$id = APIHelpers::getkey($params, 'homeID');
404
-		    if(empty($id)){
405
-				$id = $this->modx->getConfig('login_home', $this->config['site_start']);
406
-		    }
407
-		    $this->moveTo(compact('id'));
408
-		}
409
-		return;
410
-	}
411
-
412
-	/**
413
-	 * Редирект
414
-	 */
415
-	public function moveTo($params){
416
-		$id = (int)APIHelpers::getkey($params, 'id', 0);
417
-		$uri = APIHelpers::getkey($params, 'url', '');
418
-		if((empty($uri) && !empty($id)) || !is_string($uri)){
419
-			$uri = $this->makeUrl($id);
420
-		}
421
-		$code = (int)APIHelpers::getkey($params, 'code', 0);
422
-		$addUrl = APIHelpers::getkey($params, 'addUrl', '');
423
-		if(is_scalar($addUrl) && $addUrl!=''){
424
-		    $uri .= "?".$addUrl;
425
-		}
426
-		if(APIHelpers::getkey($params, 'validate', false)){
427
-			if(isset($this->modx->snippetCache['getPageID'])){
428
-				$out = $this->modx->runSnippet('getPageID', compact('uri'));
429
-				if(empty($out)){
430
-					$uri = '';
431
-				}
432
-			}else{
433
-				$uri = APIhelpers::sanitarTag($uri);
434
-			}
435
-		}else{
436
-			//$modx->sendRedirect($url, 0, 'REDIRECT_HEADER', 'HTTP/1.1 307 Temporary Redirect');
437
-			header("Location: ".$uri, true, ($code>0 ? $code : 307));
438
-		}
439
-		return $uri;
440
-	}
441
-
442
-	/**
443
-	 * Создание ссылки на страницу
444
-	 *
445
-	 * @param  int $id ID документа
446
-	 * @return string
447
-	 */
448
-	protected function makeUrl($id = null){
449
-		$id = (int)$id;
450
-		if($id <= 0){
451
-			$id = $this->modx->documentObject['id'];
452
-		}
453
-		if($this->url->containsKey($id)){
454
-			$url = $this->url->get($id);
455
-		}else{
456
-			$url = $this->modx->makeUrl($id);
457
-			$this->url->set($id, $url);
458
-		}
459
-		return $url;
460
-	}
461
-	protected function getTemplate($name){
462
-		$out = '';
463
-		$file = dirname(dirname(__FILE__)).'/tpl/'.$name.'.html';
464
-		if( FS::getInstance()->checkFile($file)){
465
-			$out = '@CODE: '.file_get_contents($file);
466
-		}
467
-		return $out;
468
-	}
469
-	protected static function loadLang($lang){
470
-		$file = dirname(dirname(__FILE__)).'/lang/'.$lang.'.php';
471
-		if( ! FS::getInstance()->checkFile($file)){
472
-			$file = false;
473
-		}
474
-		if(!empty($lang) && !isset(static::$langDic[$lang]) && !empty($file)){
475
-			static::$langDic[$lang] = include_once($file);
476
-			if(is_array(static::$langDic[$lang])){
477
-				static::$langDic[$lang] = APIHelpers::renameKeyArr(static::$langDic[$lang], $lang);
478
-			}else{
479
-				static::$langDic[$lang] = array();
480
-			}
481
-		}
482
-		return !(empty($lang) || empty(static::$langDic[$lang]));
483
-	}
484
-	protected static function getLangMsg($key, $default){
485
-		$out = $default;
486
-		$lng = static::$lang;
487
-		$dic = static::$langDic;
488
-		if(isset($dic[$lng], $dic[$lng][$lng.'.'.$key])){
489
-			$out = $dic[$lng][$lng.'.'.$key];
490
-		}
491
-		if(class_exists('evoBabel', false) && isset(self::$instance->modx->snippetCache['lang'])){
492
-			$msg = self::$instance->modx->runSnippet('lang', array('a' => 'DLUsers.'.$key));
493
-			if(!empty($msg)){
494
-				$out = $msg;
495
-			}
496
-		}
497
-		return $out;
498
-	}
197
+    /**
198
+     * Авторизация на сайте со страницы авторизации
199
+     * [!Auth? &login=`password` &pwdField=`password` &homeID=`72`!]
200
+     */
201
+    public function AuthPage($params){
202
+        $homeID = APIHelpers::getkey($params, 'homeID');
203
+        $this->isAuthGoHome(array('id' => $homeID));
204
+
205
+        $error = $errorCode = '';
206
+        $POST = array('backUrl' => '');
207
+
208
+        $pwdField = APIHelpers::getkey($params, 'pwdField', 'password');
209
+        $emailField = APIHelpers::getkey($params, 'emailField', 'email');
210
+        $rememberField = APIHelpers::getkey($params, 'rememberField', 'remember');
211
+
212
+        $tpl = APIHelpers::getkey($params, 'tpl', '');
213
+        if(empty($tpl)){
214
+            $tpl = $this->getTemplate('authForm');
215
+        }
216
+
217
+        $request = parse_url($_SERVER['REQUEST_URI']);
218
+        if(!empty($_SERVER['HTTP_REFERER'])){
219
+            /**
220
+             * Thank you for super protection against hacking in protect.inc.php:-)
221
+             */
222
+            $refer = htmlspecialchars_decode($_SERVER['HTTP_REFERER'], ENT_QUOTES);
223
+        }else{
224
+            $selfHost = rtrim(str_replace("http://", "", $this->config['site_url']), '/');
225
+            if(empty( $request['host']) ||  $request['host']==$selfHost){
226
+                $query = !empty($request['query']) ? '?'.$request['query'] : '';
227
+                $refer = !empty($request['path']) ? $request['path'].$query : '';
228
+            }else{
229
+                $refer = '';
230
+            }
231
+        }
232
+
233
+        if($_SERVER['REQUEST_METHOD'] == 'POST'){
234
+            $backUrl = APIHelpers::getkey($_POST, 'backUrl', $POST['backUrl']);
235
+            if(!is_scalar($backUrl)){
236
+                $backUrl = $refer;
237
+            }else{
238
+                $backUrl = urldecode($backUrl);
239
+            }
240
+        }else{
241
+            $backUrl = $refer;
242
+        }
243
+        $backUrl = parse_url($backUrl);
244
+        if(!empty($backUrl['path']) && $request['path'] != $backUrl['path']){
245
+            $POST['backUrl'] = $backUrl['path'];
246
+        }else{
247
+            $selfHost = rtrim(str_replace("http://", "", $this->config['site_url']), '/');
248
+            if(empty($uri['host']) || $uri['host']==$selfHost){
249
+                $query = !empty($uri['query']) ? '?'.$uri['query'] : '';
250
+                $POST['backUrl'] = !empty($uri['path']) ? $uri['path'].$query : '';
251
+            }else{
252
+                $POST['backUrl'] = '';
253
+            }
254
+        }
255
+        if(!empty($POST['backUrl'])){
256
+            $idURL = $this->moveTo(array(
257
+                'url' => '/'.ltrim($POST['backUrl'], '/'),
258
+                'validate' => true
259
+            ));
260
+        }else{
261
+            $idURL = 0;
262
+        }
263
+        if(empty($idURL)){
264
+            if(empty($homeID)){
265
+                $homeID = $this->config['site_start'];
266
+            }
267
+            $POST['backUrl'] = $this->makeUrl($homeID);
268
+        }
269
+        $POST = $this->Auth($pwdField, $emailField, $rememberField, $POST['backUrl'], __METHOD__, $error, $errorCode, $params);
270
+        return DLTemplate::getInstance($this->modx)->parseChunk($tpl, array(
271
+            'backUrl' => APIHelpers::getkey($POST, 'backUrl', ''),
272
+            'emailValue' => APIHelpers::getkey($POST, 'email', ''),
273
+            'emailField' => $emailField,
274
+            'pwdField' => $pwdField,
275
+            'method' => strtolower(__METHOD__),
276
+            'error' => $error,
277
+            'errorCode' => $errorCode
278
+        ));
279
+    }
280
+    protected function Auth($pwdField, $emailField, $rememberField, $backUrl, $method, &$error, &$errorCode, $params = array()){
281
+        $POST = array(
282
+            'backUrl' => urlencode($backUrl)
283
+        );
284
+        $userObj = &$this->userObj;
285
+        if($_SERVER['REQUEST_METHOD']=='POST' && APIHelpers::getkey($_POST, 'method', '') == strtolower($method)){
286
+            $POST = array_merge($POST, array(
287
+                'password' => APIHelpers::getkey($_POST, $pwdField, ''),
288
+                'email' => APIHelpers::getkey($_POST, $emailField, ''),
289
+                'remember' => (bool)((int)APIHelpers::getkey($_POST, $rememberField, 0))
290
+            ));
291
+            if(!empty($POST['email']) && is_scalar($POST['email']) && !$userObj->emailValidate($POST['email'], false)){
292
+                $openUser = $userObj->edit($POST['email']);
293
+
294
+                $this->modx->invokeEvent("OnBeforeWebLogin", array(
295
+                    "username"		=> $POST['email'],
296
+                    "userpassword"	=> $POST['password'],
297
+                    "rememberme"	=> $POST['remember'],
298
+                    'userObj'		=> $userObj
299
+                ));
300
+                if($userObj->getID() && !$userObj->checkBlock($userObj->getID())){
301
+                    $pluginFlag = $this->modx->invokeEvent("OnWebAuthentication", array(
302
+                        "userid"        => $userObj->getID(),
303
+                        "username"      => $userObj->get('username'),
304
+                        "userpassword"  => $POST['password'],
305
+                        "savedpassword" => $userObj->get('password'),
306
+                        "rememberme"    => $POST['remember'],
307
+                    ));
308
+                    if(
309
+                        ($pluginFlag === true || $userObj->testAuth($userObj->getID(), $POST['password'], 0))
310
+                            &&
311
+                        $userObj->authUser($userObj->getID(), $POST['remember'])
312
+                    ){
313
+                        $userObj->set('logincount', (int)$userObj->get('logincount') + 1);
314
+                        $userObj->set('lastlogin', time());
315
+                        $userObj->set('failedlogincount', 0);
316
+                        $userObj->save(false, false);
317
+
318
+                        $this->modx->invokeEvent("OnWebLogin", array(
319
+                            "userid"		=> $userObj->getID(),
320
+                            "username"		=> $userObj->get('username'),
321
+                            "userpassword"	=> $POST['password'],
322
+                            "rememberme"	=> $POST['remember'],
323
+                        ));
324
+                        $this->moveTo(array('url' => urldecode($POST['backUrl'])));
325
+                    }else{
326
+                        $userObj->set('failedlogincount', (int)$userObj->get('failedlogincount') + 1);
327
+                        $userObj->save(false, false);
328
+
329
+                        $error = 'error.incorrect_password';
330
+                    }
331
+                }else{
332
+                    $error = 'error.no_user';
333
+                }
334
+            }else{
335
+                $error = 'error.incorrect_mail';
336
+                $POST['email'] = '';
337
+            }
338
+        }
339
+        if(!empty($error)){
340
+            $errorCode = $error;
341
+            $error = APIHelpers::getkey($params, $error, '');
342
+            $error = static::getLangMsg($error, $error);
343
+        }
344
+        return $POST;
345
+    }
346
+    /**
347
+     * Информация о пользователе
348
+     * [!DLUsers? &action=`UserInfo` &field=`fullname` &id=`2`!]
349
+     */
350
+    public function UserInfo($params){
351
+        $out = '';
352
+        $type = 'web';
353
+        $userID = APIHelpers::getkey($params, 'id', 0);
354
+        if(empty($userID)){
355
+            $userID = $this->UserID(compact('type'));
356
+        }
357
+        $field = APIHelpers::getkey($params, 'field', 'username');
358
+        if($userID > 0){
359
+            $this->userObj->edit($userID);
360
+            switch(true){
361
+                case ($field == $this->userObj->fieldPKName()):{
362
+                    $out = $this->userObj->getID();
363
+                    break;
364
+                }
365
+                case ($this->userObj->issetField($field)):{
366
+                    $out = $this->userObj->get($field);
367
+                    break;
368
+                }
369
+            }
370
+        }
371
+        return $out;
372
+    }
373
+    /**
374
+     * ID пользователя
375
+     */
376
+    public function UserID($params){
377
+        $type = 'web';
378
+        return $this->modx->getLoginUserID($type);
379
+    }
380
+    /**
381
+     * Если не авторизован - то отправить на страницу
382
+     */
383
+    public function isGuestGoHome($params){
384
+        $type = 'web';
385
+        if(!$this->UserID(compact('type'))){
386
+            /**
387
+             * @see : http://modx.im/blog/triks/105.html
388
+             */
389
+            $this->modx->invokeEvent('OnPageUnauthorized');
390
+            $id = APIHelpers::getkey($params, 'id', $this->config['unauthorized_page']);
391
+            $this->moveTo(compact('id'));
392
+        }
393
+        return;
394
+    }
395
+
396
+    /**
397
+     * Если авторизован - то открыть личный кабинет
398
+     */
399
+    public function isAuthGoHome($params){
400
+        $type = 'web';
401
+        $userID = $this->UserID(compact('type'));
402
+        if($userID>0){
403
+            $id = APIHelpers::getkey($params, 'homeID');
404
+            if(empty($id)){
405
+                $id = $this->modx->getConfig('login_home', $this->config['site_start']);
406
+            }
407
+            $this->moveTo(compact('id'));
408
+        }
409
+        return;
410
+    }
411
+
412
+    /**
413
+     * Редирект
414
+     */
415
+    public function moveTo($params){
416
+        $id = (int)APIHelpers::getkey($params, 'id', 0);
417
+        $uri = APIHelpers::getkey($params, 'url', '');
418
+        if((empty($uri) && !empty($id)) || !is_string($uri)){
419
+            $uri = $this->makeUrl($id);
420
+        }
421
+        $code = (int)APIHelpers::getkey($params, 'code', 0);
422
+        $addUrl = APIHelpers::getkey($params, 'addUrl', '');
423
+        if(is_scalar($addUrl) && $addUrl!=''){
424
+            $uri .= "?".$addUrl;
425
+        }
426
+        if(APIHelpers::getkey($params, 'validate', false)){
427
+            if(isset($this->modx->snippetCache['getPageID'])){
428
+                $out = $this->modx->runSnippet('getPageID', compact('uri'));
429
+                if(empty($out)){
430
+                    $uri = '';
431
+                }
432
+            }else{
433
+                $uri = APIhelpers::sanitarTag($uri);
434
+            }
435
+        }else{
436
+            //$modx->sendRedirect($url, 0, 'REDIRECT_HEADER', 'HTTP/1.1 307 Temporary Redirect');
437
+            header("Location: ".$uri, true, ($code>0 ? $code : 307));
438
+        }
439
+        return $uri;
440
+    }
441
+
442
+    /**
443
+     * Создание ссылки на страницу
444
+     *
445
+     * @param  int $id ID документа
446
+     * @return string
447
+     */
448
+    protected function makeUrl($id = null){
449
+        $id = (int)$id;
450
+        if($id <= 0){
451
+            $id = $this->modx->documentObject['id'];
452
+        }
453
+        if($this->url->containsKey($id)){
454
+            $url = $this->url->get($id);
455
+        }else{
456
+            $url = $this->modx->makeUrl($id);
457
+            $this->url->set($id, $url);
458
+        }
459
+        return $url;
460
+    }
461
+    protected function getTemplate($name){
462
+        $out = '';
463
+        $file = dirname(dirname(__FILE__)).'/tpl/'.$name.'.html';
464
+        if( FS::getInstance()->checkFile($file)){
465
+            $out = '@CODE: '.file_get_contents($file);
466
+        }
467
+        return $out;
468
+    }
469
+    protected static function loadLang($lang){
470
+        $file = dirname(dirname(__FILE__)).'/lang/'.$lang.'.php';
471
+        if( ! FS::getInstance()->checkFile($file)){
472
+            $file = false;
473
+        }
474
+        if(!empty($lang) && !isset(static::$langDic[$lang]) && !empty($file)){
475
+            static::$langDic[$lang] = include_once($file);
476
+            if(is_array(static::$langDic[$lang])){
477
+                static::$langDic[$lang] = APIHelpers::renameKeyArr(static::$langDic[$lang], $lang);
478
+            }else{
479
+                static::$langDic[$lang] = array();
480
+            }
481
+        }
482
+        return !(empty($lang) || empty(static::$langDic[$lang]));
483
+    }
484
+    protected static function getLangMsg($key, $default){
485
+        $out = $default;
486
+        $lng = static::$lang;
487
+        $dic = static::$langDic;
488
+        if(isset($dic[$lng], $dic[$lng][$lng.'.'.$key])){
489
+            $out = $dic[$lng][$lng.'.'.$key];
490
+        }
491
+        if(class_exists('evoBabel', false) && isset(self::$instance->modx->snippetCache['lang'])){
492
+            $msg = self::$instance->modx->runSnippet('lang', array('a' => 'DLUsers.'.$key));
493
+            if(!empty($msg)){
494
+                $out = $msg;
495
+            }
496
+        }
497
+        return $out;
498
+    }
499 499
 }
500 500
\ No newline at end of file
Please login to merge, or discard this patch.
Spacing   +96 added lines, -96 removed lines patch added patch discarded remove patch
@@ -9,7 +9,7 @@  discard block
 block discarded – undo
9 9
 use APIHelpers, DocumentParser, DLCollection, DLTemplate;
10 10
 use Helpers\FS;
11 11
 
12
-class Actions{
12
+class Actions {
13 13
     protected $modx = null;
14 14
     public $userObj = null;
15 15
 	/**
@@ -84,21 +84,21 @@  discard block
 block discarded – undo
84 84
     /**
85 85
      * Сброс авторизации и обновление страницы
86 86
      */
87
-    public function logout($params){
87
+    public function logout($params) {
88 88
     	$LogoutName = APIHelpers::getkey($params, 'LogoutName', 'logout');
89
-    	if(is_scalar($LogoutName) && !empty($LogoutName) && isset($_GET[$LogoutName])){
89
+    	if (is_scalar($LogoutName) && !empty($LogoutName) && isset($_GET[$LogoutName])) {
90 90
     		$type = 'web';
91 91
     		$userID = $this->UserID(compact('type'));
92
-    		if($userID){
92
+    		if ($userID) {
93 93
     			$this->userObj->edit($userID);
94
-    			if($this->userObj->getID()){
94
+    			if ($this->userObj->getID()) {
95 95
 	    			$this->modx->invokeEvent("OnBeforeWebLogout", array(
96 96
 		    			"userid"   => $this->userObj->getID(),
97 97
 		    			"username" => $this->userObj->get('username')
98 98
 		    		));
99 99
 	    		}
100 100
 		    	$this->userObj->logOut();
101
-		    	if($this->userObj->getID()){
101
+		    	if ($this->userObj->getID()) {
102 102
 		    		$this->modx->invokeEvent("OnWebLogout", array(
103 103
 		    			"userid"        => $this->userObj->getID(),
104 104
 		    			"username"      => $this->userObj->get('username')
@@ -106,22 +106,22 @@  discard block
 block discarded – undo
106 106
 		    	}
107 107
 
108 108
 			    $go = APIHelpers::getkey($params, 'url', '');
109
-			    if(empty($go)){
109
+			    if (empty($go)) {
110 110
 			    	$go = str_replace(
111
-			    		array("?".$LogoutName, "&".$LogoutName),
111
+			    		array("?" . $LogoutName, "&" . $LogoutName),
112 112
 			    		array("", ""),
113 113
 			    		$_SERVER['REQUEST_URI']
114 114
 			    	);
115 115
 			    }
116 116
 
117 117
 			    $start = $this->makeUrl($this->config['site_start']);
118
-			    if($start == $go){
118
+			    if ($start == $go) {
119 119
 			        $go = $this->config['site_url'];
120
-			    }else{
121
-			        $go = $this->config['site_url'].ltrim($go, '/');
120
+			    } else {
121
+			        $go = $this->config['site_url'] . ltrim($go, '/');
122 122
 			    }
123 123
 			    $this->moveTo(array('url' => $go));
124
-    		}else{
124
+    		} else {
125 125
     			//Если юзер не авторизован, то показываем ему 404 ошибку
126 126
     			$this->modx->sendErrorPage();
127 127
     		}
@@ -133,15 +133,15 @@  discard block
 block discarded – undo
133 133
      * Генерация ссылки под кнопку выход
134 134
      * @return string
135 135
      */
136
-    public function logoutUrl($params){
136
+    public function logoutUrl($params) {
137 137
     	$LogoutName = APIHelpers::getkey($params, 'LogoutName', 'logout');
138 138
     	$request = parse_url($_SERVER['REQUEST_URI']);
139 139
 
140 140
     	//Во избежании XSS мы не сохраняем весь REQUEST_URI, а берем только path
141 141
     	/*$query = (!empty($request['query'])) ? $request['query'].'&' : '';*/
142
-    	$query = '?'.$LogoutName;
142
+    	$query = '?' . $LogoutName;
143 143
 
144
-    	return $request['path'].$query;
144
+    	return $request['path'] . $query;
145 145
     }
146 146
 
147 147
     /**
@@ -149,7 +149,7 @@  discard block
 block discarded – undo
149 149
      * 		если указан параметр authId, то данные из формы перекидываются в метод AuthPage
150 150
      *   	В противном случае вся работа происходит внутри самого блока
151 151
      */
152
-    public function AuthBlock($params){
152
+    public function AuthBlock($params) {
153 153
     	$POST = array('backUrl' => $_SERVER['REQUEST_URI']);
154 154
 
155 155
     	$error = $errorCode = '';
@@ -159,20 +159,20 @@  discard block
 block discarded – undo
159 159
 		$rememberField = APIHelpers::getkey($params, 'rememberField', 'remember');
160 160
 
161 161
     	$type = 'web';
162
-		if($this->UserID(compact('type'))){
162
+		if ($this->UserID(compact('type'))) {
163 163
 			$tpl = APIHelpers::getkey($params, 'tplProfile', '');
164
-			if(empty($tpl)){
164
+			if (empty($tpl)) {
165 165
 				$tpl = $this->getTemplate('tplProfile');
166 166
 			}
167 167
 			$dataTPL = $this->userObj->toArray();
168 168
 			$dataTPL['url.logout'] = $this->logoutUrl($params);
169 169
     		$homeID = APIHelpers::getkey($params, 'homeID');
170
-			if(!empty($homeID)){
170
+			if (!empty($homeID)) {
171 171
 				$dataTPL['url.profile'] = $this->makeUrl($homeID);
172 172
 			}
173
-		}else{
173
+		} else {
174 174
 			$tpl = APIHelpers::getkey($params, 'tplForm', '');
175
-			if(empty($tpl)){
175
+			if (empty($tpl)) {
176 176
 				$tpl = $this->getTemplate('authForm');
177 177
 			}
178 178
 			$POST = $this->Auth($pwdField, $emailField, $rememberField, $POST['backUrl'], __METHOD__, $error, $errorCode, $params);
@@ -186,9 +186,9 @@  discard block
 block discarded – undo
186 186
 				'errorCode' => $errorCode
187 187
 			);
188 188
 			$authId = APIHelpers::getkey($params, 'authId');
189
-			if(!empty($authId)){
189
+			if (!empty($authId)) {
190 190
 				$dataTPL['authPage'] = $this->makeUrl($authId);
191
-				$dataTPL['method'] = strtolower(__CLASS__ . '::'. 'authpage');
191
+				$dataTPL['method'] = strtolower(__CLASS__ . '::' . 'authpage');
192 192
 			}
193 193
 		}
194 194
 		return DLTemplate::getInstance($this->modx)->parseChunk($tpl, $dataTPL);
@@ -198,7 +198,7 @@  discard block
 block discarded – undo
198 198
 	 * Авторизация на сайте со страницы авторизации
199 199
 	 * [!Auth? &login=`password` &pwdField=`password` &homeID=`72`!]
200 200
 	 */
201
-	public function AuthPage($params){
201
+	public function AuthPage($params) {
202 202
 		$homeID = APIHelpers::getkey($params, 'homeID');
203 203
 		$this->isAuthGoHome(array('id' => $homeID));
204 204
 
@@ -210,58 +210,58 @@  discard block
 block discarded – undo
210 210
 		$rememberField = APIHelpers::getkey($params, 'rememberField', 'remember');
211 211
 
212 212
 		$tpl = APIHelpers::getkey($params, 'tpl', '');
213
-		if(empty($tpl)){
213
+		if (empty($tpl)) {
214 214
 			$tpl = $this->getTemplate('authForm');
215 215
 		}
216 216
 
217 217
 		$request = parse_url($_SERVER['REQUEST_URI']);
218
-		if(!empty($_SERVER['HTTP_REFERER'])){
218
+		if (!empty($_SERVER['HTTP_REFERER'])) {
219 219
 			/**
220 220
 			 * Thank you for super protection against hacking in protect.inc.php:-)
221 221
 			 */
222 222
 			$refer = htmlspecialchars_decode($_SERVER['HTTP_REFERER'], ENT_QUOTES);
223
-		}else{
223
+		} else {
224 224
 			$selfHost = rtrim(str_replace("http://", "", $this->config['site_url']), '/');
225
-			if(empty( $request['host']) ||  $request['host']==$selfHost){
226
-				$query = !empty($request['query']) ? '?'.$request['query'] : '';
227
-			    $refer = !empty($request['path']) ? $request['path'].$query : '';
228
-			}else{
225
+			if (empty($request['host']) || $request['host'] == $selfHost) {
226
+				$query = !empty($request['query']) ? '?' . $request['query'] : '';
227
+			    $refer = !empty($request['path']) ? $request['path'] . $query : '';
228
+			} else {
229 229
 				$refer = '';
230 230
 			}
231 231
 		}
232 232
 
233
-		if($_SERVER['REQUEST_METHOD'] == 'POST'){
233
+		if ($_SERVER['REQUEST_METHOD'] == 'POST') {
234 234
 			$backUrl = APIHelpers::getkey($_POST, 'backUrl', $POST['backUrl']);
235
-			if(!is_scalar($backUrl)){
235
+			if (!is_scalar($backUrl)) {
236 236
 				$backUrl = $refer;
237
-			}else{
237
+			} else {
238 238
 				$backUrl = urldecode($backUrl);
239 239
 			}
240
-		}else{
240
+		} else {
241 241
 			$backUrl = $refer;
242 242
 		}
243 243
 		$backUrl = parse_url($backUrl);
244
-		if(!empty($backUrl['path']) && $request['path'] != $backUrl['path']){
244
+		if (!empty($backUrl['path']) && $request['path'] != $backUrl['path']) {
245 245
 		    $POST['backUrl'] = $backUrl['path'];
246
-		}else{
246
+		} else {
247 247
 			$selfHost = rtrim(str_replace("http://", "", $this->config['site_url']), '/');
248
-			if(empty($uri['host']) || $uri['host']==$selfHost){
249
-				$query = !empty($uri['query']) ? '?'.$uri['query'] : '';
250
-			    $POST['backUrl'] = !empty($uri['path']) ? $uri['path'].$query : '';
251
-			}else{
248
+			if (empty($uri['host']) || $uri['host'] == $selfHost) {
249
+				$query = !empty($uri['query']) ? '?' . $uri['query'] : '';
250
+			    $POST['backUrl'] = !empty($uri['path']) ? $uri['path'] . $query : '';
251
+			} else {
252 252
 				$POST['backUrl'] = '';
253 253
 			}
254 254
 		}
255
-		if(!empty($POST['backUrl'])){
255
+		if (!empty($POST['backUrl'])) {
256 256
 			$idURL = $this->moveTo(array(
257
-				'url' => '/'.ltrim($POST['backUrl'], '/'),
257
+				'url' => '/' . ltrim($POST['backUrl'], '/'),
258 258
 			    'validate' => true
259 259
 			));
260
-		}else{
260
+		} else {
261 261
 			$idURL = 0;
262 262
 		}
263
-		if(empty($idURL)){
264
-			if(empty($homeID)){
263
+		if (empty($idURL)) {
264
+			if (empty($homeID)) {
265 265
 				$homeID = $this->config['site_start'];
266 266
 			}
267 267
 			$POST['backUrl'] = $this->makeUrl($homeID);
@@ -277,18 +277,18 @@  discard block
 block discarded – undo
277 277
 			'errorCode' => $errorCode
278 278
 		));
279 279
 	}
280
-	protected function Auth($pwdField, $emailField, $rememberField, $backUrl, $method, &$error, &$errorCode, $params = array()){
280
+	protected function Auth($pwdField, $emailField, $rememberField, $backUrl, $method, &$error, &$errorCode, $params = array()) {
281 281
 		$POST = array(
282 282
 			'backUrl' => urlencode($backUrl)
283 283
 		);
284 284
 		$userObj = &$this->userObj;
285
-		if($_SERVER['REQUEST_METHOD']=='POST' && APIHelpers::getkey($_POST, 'method', '') == strtolower($method)){
285
+		if ($_SERVER['REQUEST_METHOD'] == 'POST' && APIHelpers::getkey($_POST, 'method', '') == strtolower($method)) {
286 286
 			$POST = array_merge($POST, array(
287 287
 				'password' => APIHelpers::getkey($_POST, $pwdField, ''),
288 288
 				'email' => APIHelpers::getkey($_POST, $emailField, ''),
289 289
 				'remember' => (bool)((int)APIHelpers::getkey($_POST, $rememberField, 0))
290 290
 			));
291
-			if(!empty($POST['email']) && is_scalar($POST['email']) && !$userObj->emailValidate($POST['email'], false)){
291
+			if (!empty($POST['email']) && is_scalar($POST['email']) && !$userObj->emailValidate($POST['email'], false)) {
292 292
 				$openUser = $userObj->edit($POST['email']);
293 293
 
294 294
 				$this->modx->invokeEvent("OnBeforeWebLogin", array(
@@ -297,7 +297,7 @@  discard block
 block discarded – undo
297 297
 		            "rememberme"	=> $POST['remember'],
298 298
 		            'userObj'		=> $userObj
299 299
 		        ));
300
-				if($userObj->getID() && !$userObj->checkBlock($userObj->getID())){
300
+				if ($userObj->getID() && !$userObj->checkBlock($userObj->getID())) {
301 301
 					$pluginFlag = $this->modx->invokeEvent("OnWebAuthentication", array(
302 302
 	                    "userid"        => $userObj->getID(),
303 303
 	                    "username"      => $userObj->get('username'),
@@ -305,11 +305,11 @@  discard block
 block discarded – undo
305 305
 	                    "savedpassword" => $userObj->get('password'),
306 306
 	                    "rememberme"    => $POST['remember'],
307 307
 	                ));
308
-					if(
308
+					if (
309 309
 						($pluginFlag === true || $userObj->testAuth($userObj->getID(), $POST['password'], 0))
310 310
 							&&
311 311
 						$userObj->authUser($userObj->getID(), $POST['remember'])
312
-					){
312
+					) {
313 313
 						$userObj->set('logincount', (int)$userObj->get('logincount') + 1);
314 314
 						$userObj->set('lastlogin', time());
315 315
 						$userObj->set('failedlogincount', 0);
@@ -322,21 +322,21 @@  discard block
 block discarded – undo
322 322
 			                "rememberme"	=> $POST['remember'],
323 323
 			            ));
324 324
 						$this->moveTo(array('url' => urldecode($POST['backUrl'])));
325
-					}else{
325
+					} else {
326 326
 						$userObj->set('failedlogincount', (int)$userObj->get('failedlogincount') + 1);
327 327
 						$userObj->save(false, false);
328 328
 
329 329
 						$error = 'error.incorrect_password';
330 330
 					}
331
-				}else{
331
+				} else {
332 332
 					$error = 'error.no_user';
333 333
 				}
334
-			}else{
334
+			} else {
335 335
 				$error = 'error.incorrect_mail';
336 336
 				$POST['email'] = '';
337 337
 			}
338 338
 		}
339
-		if(!empty($error)){
339
+		if (!empty($error)) {
340 340
 			$errorCode = $error;
341 341
 			$error = APIHelpers::getkey($params, $error, '');
342 342
 			$error = static::getLangMsg($error, $error);
@@ -347,17 +347,17 @@  discard block
 block discarded – undo
347 347
 	 * Информация о пользователе
348 348
 	 * [!DLUsers? &action=`UserInfo` &field=`fullname` &id=`2`!]
349 349
 	 */
350
-	public function UserInfo($params){
350
+	public function UserInfo($params) {
351 351
 		$out = '';
352 352
 		$type = 'web';
353 353
 		$userID = APIHelpers::getkey($params, 'id', 0);
354
-		if(empty($userID)){
354
+		if (empty($userID)) {
355 355
 			$userID = $this->UserID(compact('type'));
356 356
 		}
357 357
 		$field = APIHelpers::getkey($params, 'field', 'username');
358
-		if($userID > 0){
358
+		if ($userID > 0) {
359 359
 			$this->userObj->edit($userID);
360
-			switch(true){
360
+			switch (true) {
361 361
 				case ($field == $this->userObj->fieldPKName()):{
362 362
 					$out = $this->userObj->getID();
363 363
 					break;
@@ -373,16 +373,16 @@  discard block
 block discarded – undo
373 373
 	/**
374 374
 	 * ID пользователя
375 375
 	 */
376
-	public function UserID($params){
376
+	public function UserID($params) {
377 377
 		$type = 'web';
378 378
 		return $this->modx->getLoginUserID($type);
379 379
 	}
380 380
 	/**
381 381
 	 * Если не авторизован - то отправить на страницу
382 382
 	 */
383
-	public function isGuestGoHome($params){
383
+	public function isGuestGoHome($params) {
384 384
 		$type = 'web';
385
-		if(!$this->UserID(compact('type'))){
385
+		if (!$this->UserID(compact('type'))) {
386 386
 			/**
387 387
 			 * @see : http://modx.im/blog/triks/105.html
388 388
 			 */
@@ -396,12 +396,12 @@  discard block
 block discarded – undo
396 396
 	/**
397 397
 	 * Если авторизован - то открыть личный кабинет
398 398
 	 */
399
-	public function isAuthGoHome($params){
399
+	public function isAuthGoHome($params) {
400 400
 		$type = 'web';
401 401
 		$userID = $this->UserID(compact('type'));
402
-		if($userID>0){
402
+		if ($userID > 0) {
403 403
 			$id = APIHelpers::getkey($params, 'homeID');
404
-		    if(empty($id)){
404
+		    if (empty($id)) {
405 405
 				$id = $this->modx->getConfig('login_home', $this->config['site_start']);
406 406
 		    }
407 407
 		    $this->moveTo(compact('id'));
@@ -412,29 +412,29 @@  discard block
 block discarded – undo
412 412
 	/**
413 413
 	 * Редирект
414 414
 	 */
415
-	public function moveTo($params){
415
+	public function moveTo($params) {
416 416
 		$id = (int)APIHelpers::getkey($params, 'id', 0);
417 417
 		$uri = APIHelpers::getkey($params, 'url', '');
418
-		if((empty($uri) && !empty($id)) || !is_string($uri)){
418
+		if ((empty($uri) && !empty($id)) || !is_string($uri)) {
419 419
 			$uri = $this->makeUrl($id);
420 420
 		}
421 421
 		$code = (int)APIHelpers::getkey($params, 'code', 0);
422 422
 		$addUrl = APIHelpers::getkey($params, 'addUrl', '');
423
-		if(is_scalar($addUrl) && $addUrl!=''){
424
-		    $uri .= "?".$addUrl;
423
+		if (is_scalar($addUrl) && $addUrl != '') {
424
+		    $uri .= "?" . $addUrl;
425 425
 		}
426
-		if(APIHelpers::getkey($params, 'validate', false)){
427
-			if(isset($this->modx->snippetCache['getPageID'])){
426
+		if (APIHelpers::getkey($params, 'validate', false)) {
427
+			if (isset($this->modx->snippetCache['getPageID'])) {
428 428
 				$out = $this->modx->runSnippet('getPageID', compact('uri'));
429
-				if(empty($out)){
429
+				if (empty($out)) {
430 430
 					$uri = '';
431 431
 				}
432
-			}else{
432
+			} else {
433 433
 				$uri = APIhelpers::sanitarTag($uri);
434 434
 			}
435
-		}else{
435
+		} else {
436 436
 			//$modx->sendRedirect($url, 0, 'REDIRECT_HEADER', 'HTTP/1.1 307 Temporary Redirect');
437
-			header("Location: ".$uri, true, ($code>0 ? $code : 307));
437
+			header("Location: " . $uri, true, ($code > 0 ? $code : 307));
438 438
 		}
439 439
 		return $uri;
440 440
 	}
@@ -445,52 +445,52 @@  discard block
 block discarded – undo
445 445
 	 * @param  int $id ID документа
446 446
 	 * @return string
447 447
 	 */
448
-	protected function makeUrl($id = null){
448
+	protected function makeUrl($id = null) {
449 449
 		$id = (int)$id;
450
-		if($id <= 0){
450
+		if ($id <= 0) {
451 451
 			$id = $this->modx->documentObject['id'];
452 452
 		}
453
-		if($this->url->containsKey($id)){
453
+		if ($this->url->containsKey($id)) {
454 454
 			$url = $this->url->get($id);
455
-		}else{
455
+		} else {
456 456
 			$url = $this->modx->makeUrl($id);
457 457
 			$this->url->set($id, $url);
458 458
 		}
459 459
 		return $url;
460 460
 	}
461
-	protected function getTemplate($name){
461
+	protected function getTemplate($name) {
462 462
 		$out = '';
463
-		$file = dirname(dirname(__FILE__)).'/tpl/'.$name.'.html';
464
-		if( FS::getInstance()->checkFile($file)){
465
-			$out = '@CODE: '.file_get_contents($file);
463
+		$file = dirname(dirname(__FILE__)) . '/tpl/' . $name . '.html';
464
+		if (FS::getInstance()->checkFile($file)) {
465
+			$out = '@CODE: ' . file_get_contents($file);
466 466
 		}
467 467
 		return $out;
468 468
 	}
469
-	protected static function loadLang($lang){
470
-		$file = dirname(dirname(__FILE__)).'/lang/'.$lang.'.php';
471
-		if( ! FS::getInstance()->checkFile($file)){
469
+	protected static function loadLang($lang) {
470
+		$file = dirname(dirname(__FILE__)) . '/lang/' . $lang . '.php';
471
+		if (!FS::getInstance()->checkFile($file)) {
472 472
 			$file = false;
473 473
 		}
474
-		if(!empty($lang) && !isset(static::$langDic[$lang]) && !empty($file)){
474
+		if (!empty($lang) && !isset(static::$langDic[$lang]) && !empty($file)) {
475 475
 			static::$langDic[$lang] = include_once($file);
476
-			if(is_array(static::$langDic[$lang])){
476
+			if (is_array(static::$langDic[$lang])) {
477 477
 				static::$langDic[$lang] = APIHelpers::renameKeyArr(static::$langDic[$lang], $lang);
478
-			}else{
478
+			} else {
479 479
 				static::$langDic[$lang] = array();
480 480
 			}
481 481
 		}
482 482
 		return !(empty($lang) || empty(static::$langDic[$lang]));
483 483
 	}
484
-	protected static function getLangMsg($key, $default){
484
+	protected static function getLangMsg($key, $default) {
485 485
 		$out = $default;
486 486
 		$lng = static::$lang;
487 487
 		$dic = static::$langDic;
488
-		if(isset($dic[$lng], $dic[$lng][$lng.'.'.$key])){
489
-			$out = $dic[$lng][$lng.'.'.$key];
488
+		if (isset($dic[$lng], $dic[$lng][$lng . '.' . $key])) {
489
+			$out = $dic[$lng][$lng . '.' . $key];
490 490
 		}
491
-		if(class_exists('evoBabel', false) && isset(self::$instance->modx->snippetCache['lang'])){
492
-			$msg = self::$instance->modx->runSnippet('lang', array('a' => 'DLUsers.'.$key));
493
-			if(!empty($msg)){
491
+		if (class_exists('evoBabel', false) && isset(self::$instance->modx->snippetCache['lang'])) {
492
+			$msg = self::$instance->modx->runSnippet('lang', array('a' => 'DLUsers.' . $key));
493
+			if (!empty($msg)) {
494 494
 				$out = $msg;
495 495
 			}
496 496
 		}
Please login to merge, or discard this patch.
assets/snippets/DocLister/core/DocLister.abstract.php 3 patches
Indentation   +121 added lines, -121 removed lines patch added patch discarded remove patch
@@ -3,20 +3,20 @@  discard block
 block discarded – undo
3 3
     die('HACK???');
4 4
 }
5 5
 /**
6
- * DocLister class
7
- *
8
- * @license GNU General Public License (GPL), http://www.gnu.org/copyleft/gpl.html
9
- * @author Agel_Nash <[email protected]>
10
- *
11
- * @TODO add controller for work with plugin http://modx.com/extras/package/quid and get TV value via LEFT JOIN
12
- * @TODO add controller for filter by TV values
13
- * @TODO add method load default template
14
- * @TODO add example custom controller for build google sitemap.xml
15
- * @TODO add method build tree for replace Wayfinder if need TV value in menu OR sitemap
16
- * @TODO add controller for show list web-user with filter by group and other user information
17
- * @TODO depending on the parameters
18
- * @TODO prepare value before return final data (maybe callback function OR extender)
19
- */
6
+     * DocLister class
7
+     *
8
+     * @license GNU General Public License (GPL), http://www.gnu.org/copyleft/gpl.html
9
+     * @author Agel_Nash <[email protected]>
10
+     *
11
+     * @TODO add controller for work with plugin http://modx.com/extras/package/quid and get TV value via LEFT JOIN
12
+     * @TODO add controller for filter by TV values
13
+     * @TODO add method load default template
14
+     * @TODO add example custom controller for build google sitemap.xml
15
+     * @TODO add method build tree for replace Wayfinder if need TV value in menu OR sitemap
16
+     * @TODO add controller for show list web-user with filter by group and other user information
17
+     * @TODO depending on the parameters
18
+     * @TODO prepare value before return final data (maybe callback function OR extender)
19
+     */
20 20
 include_once(MODX_BASE_PATH . 'assets/lib/APIHelpers.class.php');
21 21
 include_once(MODX_BASE_PATH . 'assets/lib/Helpers/FS.php');
22 22
 require_once(dirname(dirname(__FILE__)) . "/lib/jsonHelper.class.php");
@@ -107,10 +107,10 @@  discard block
 block discarded – undo
107 107
     protected $idField = 'id';
108 108
 
109 109
     /**
110
-    * Parent Key основной таблицы
111
-    * @var string
112
-    * @access protected
113
-    */
110
+     * Parent Key основной таблицы
111
+     * @var string
112
+     * @access protected
113
+     */
114 114
     protected $parentField = 'parent';
115 115
     /**
116 116
      * Дополнительные условия для SQL запросов
@@ -168,18 +168,18 @@  discard block
 block discarded – undo
168 168
 
169 169
     public $FS = null;
170 170
     /** @var string результатирующая строка которая была последний раз сгенирирована
171
-    *               вызовами методов DocLister::render и DocLister::getJSON
172
-    */
171
+     *               вызовами методов DocLister::render и DocLister::getJSON
172
+     */
173 173
     protected $outData = '';
174 174
 	
175
-	/** @var int Число документов, которые были отфильтрованы через prepare при выводе */
176
-	public $skippedDocs = 0;
175
+    /** @var int Число документов, которые были отфильтрованы через prepare при выводе */
176
+    public $skippedDocs = 0;
177 177
 
178
-	/** @var string Имя таблицы */
179
-	protected $table = '';
178
+    /** @var string Имя таблицы */
179
+    protected $table = '';
180 180
 
181
-	/** @var null|paginate_DL_Extender  */
182
-	protected $extPaginate = null;
181
+    /** @var null|paginate_DL_Extender  */
182
+    protected $extPaginate = null;
183 183
     /**
184 184
      * Конструктор контроллеров DocLister
185 185
      *
@@ -191,30 +191,30 @@  discard block
 block discarded – undo
191 191
     {
192 192
         $this->setTimeStart($startTime);
193 193
 
194
-		if (extension_loaded('mbstring')) {
195
-        	mb_internal_encoding("UTF-8");
196
-		} else {
197
-        	throw new Exception('Not found php extension mbstring');
198
-		}
194
+        if (extension_loaded('mbstring')) {
195
+            mb_internal_encoding("UTF-8");
196
+        } else {
197
+            throw new Exception('Not found php extension mbstring');
198
+        }
199 199
 
200 200
         if ($modx instanceof DocumentParser) {
201
-        	$this->modx = $modx;
201
+            $this->modx = $modx;
202 202
             $this->setDebug(1);
203 203
             $this->loadLang(array('core', 'json'));
204 204
 
205 205
             if (!is_array($cfg) || empty($cfg)) $cfg = $this->modx->Event->params;
206
-		} else {
207
-        	throw new Exception('MODX var is not instaceof DocumentParser');
208
-		}
206
+        } else {
207
+            throw new Exception('MODX var is not instaceof DocumentParser');
208
+        }
209 209
 
210 210
         $this->FS = \Helpers\FS::getInstance();
211 211
         if (isset($cfg['config'])) {
212
-        	$cfg = array_merge($this->loadConfig($cfg['config']), $cfg);
213
-		}
212
+            $cfg = array_merge($this->loadConfig($cfg['config']), $cfg);
213
+        }
214 214
 
215
-		if (!$this->setConfig($cfg)) {
216
-        	throw new Exception('no parameters to run DocLister');
217
-		}
215
+        if (!$this->setConfig($cfg)) {
216
+            throw new Exception('no parameters to run DocLister');
217
+        }
218 218
 
219 219
         $this->setDebug($this->getCFGDef('debug', 0));
220 220
 
@@ -266,52 +266,52 @@  discard block
 block discarded – undo
266 266
 
267 267
     /**
268 268
      * Разбиение фильтра на субфильтры с учётом вложенности
269
-	 * @param string $str строка с фильтром
269
+     * @param string $str строка с фильтром
270 270
      * @return array массив субфильтров
271 271
      */
272
-	public function smartSplit($str){
273
-		$res = array();
274
-		$cur = '';
275
-		$open = 0;
276
-		$strlen = mb_strlen($str, 'UTF-8');
277
-		for($i=0;$i<=$strlen;$i++){
278
-			$e = mb_substr($str, $i, 1, 'UTF-8');
279
-			switch($e){
280
-				case ')': {
281
-					$open--;
282
-					if($open == 0){
283
-						$res[] = $cur.')';
284
-						$cur = '';
285
-					} else {
286
-						$cur .= $e;
287
-					}
288
-					break;
289
-				}
290
-				case '(':{
291
-					$open++;
292
-					$cur .= $e;
293
-					break;
294
-				}
295
-				case ';':{
296
-					if($open == 0){
297
-						$res[] = $cur;
298
-						$cur = '';
299
-					} else {
300
-						$cur .= $e;
301
-					}
302
-					break;
303
-				}
304
-				default:{
305
-					$cur .= $e;
306
-				}
307
-			}
308
-		}
309
-		$cur = preg_replace("/(\))$/u", '', $cur);
310
-		if ($cur != ''){
311
-			$res[] = $cur;
312
-		}
313
-		return $res;
314
-	}
272
+    public function smartSplit($str){
273
+        $res = array();
274
+        $cur = '';
275
+        $open = 0;
276
+        $strlen = mb_strlen($str, 'UTF-8');
277
+        for($i=0;$i<=$strlen;$i++){
278
+            $e = mb_substr($str, $i, 1, 'UTF-8');
279
+            switch($e){
280
+                case ')': {
281
+                    $open--;
282
+                    if($open == 0){
283
+                        $res[] = $cur.')';
284
+                        $cur = '';
285
+                    } else {
286
+                        $cur .= $e;
287
+                    }
288
+                    break;
289
+                }
290
+                case '(':{
291
+                    $open++;
292
+                    $cur .= $e;
293
+                    break;
294
+                }
295
+                case ';':{
296
+                    if($open == 0){
297
+                        $res[] = $cur;
298
+                        $cur = '';
299
+                    } else {
300
+                        $cur .= $e;
301
+                    }
302
+                    break;
303
+                }
304
+                default:{
305
+                    $cur .= $e;
306
+                }
307
+            }
308
+        }
309
+        $cur = preg_replace("/(\))$/u", '', $cur);
310
+        if ($cur != ''){
311
+            $res[] = $cur;
312
+        }
313
+        return $res;
314
+    }
315 315
 
316 316
     /**
317 317
      * Трансформация объекта в строку
@@ -502,7 +502,7 @@  discard block
 block discarded – undo
502 502
         $flag = true;
503 503
         $extenders = $this->getCFGDef('extender', '');
504 504
         $extenders = explode(",", $extenders);
505
-        	if (($this->getCFGDef('requestActive', '') != '' || in_array('request', $extenders)) && !$this->_loadExtender('request')) { //OR request in extender's parameter
505
+            if (($this->getCFGDef('requestActive', '') != '' || in_array('request', $extenders)) && !$this->_loadExtender('request')) { //OR request in extender's parameter
506 506
                 throw new Exception('Error load request extender');
507 507
             }
508 508
 
@@ -606,17 +606,17 @@  discard block
 block discarded – undo
606 606
      ****************** CORE Block *********************
607 607
      ***************************************************/
608 608
 
609
-	 /**
610
-	 * Определение ID страницы открытой во фронте
611
-	 *
612
-	 * @return int
613
-	 */
614
-	 public function getCurrentMODXPageID(){
615
-		$id = isset($this->modx->documentIdentifier) ? (int)$this->modx->documentIdentifier : 0;
616
-		$docData = isset($this->modx->documentObject) ? $this->modx->documentObject : array();
609
+        /**
610
+         * Определение ID страницы открытой во фронте
611
+         *
612
+         * @return int
613
+         */
614
+        public function getCurrentMODXPageID(){
615
+        $id = isset($this->modx->documentIdentifier) ? (int)$this->modx->documentIdentifier : 0;
616
+        $docData = isset($this->modx->documentObject) ? $this->modx->documentObject : array();
617 617
 
618
-		return empty($id) ? \APIHelpers::getkey($docData, 'id', 0) : $id;
619
-	}
618
+        return empty($id) ? \APIHelpers::getkey($docData, 'id', 0) : $id;
619
+    }
620 620
 
621 621
     /**
622 622
      * Display and save error information
@@ -677,7 +677,7 @@  discard block
 block discarded – undo
677 677
         return $out;
678 678
     }
679 679
 
680
-	/**
680
+    /**
681 681
      * Получение всего списка настроек
682 682
      * @return array
683 683
      */
@@ -693,7 +693,7 @@  discard block
 block discarded – undo
693 693
      */
694 694
     public function setConfig($cfg)
695 695
     {
696
-		if(is_scalar($cfg)) $cfg = array($cfg);
696
+        if(is_scalar($cfg)) $cfg = array($cfg);
697 697
         if (is_array($cfg)) {
698 698
             $this->_cfg = array_merge($this->_cfg, $cfg);
699 699
             $ret = count($this->_cfg);
@@ -703,7 +703,7 @@  discard block
 block discarded – undo
703 703
         return $ret;
704 704
     }
705 705
 
706
-	/**
706
+    /**
707 707
      * Полная перезапись настроек вызова сниппета
708 708
      * @param array $cfg массив настроек
709 709
      * @return int Общее число новых настроек
@@ -711,9 +711,9 @@  discard block
 block discarded – undo
711 711
     public function replaceConfig($cfg)
712 712
     {
713 713
         if (!is_array($cfg)) {
714
-			$cfg = array();
714
+            $cfg = array();
715 715
         }
716
-		$this->_cfg = $cfg;
716
+        $this->_cfg = $cfg;
717 717
         return count($this->_cfg);
718 718
     }
719 719
 
@@ -997,21 +997,21 @@  discard block
 block discarded – undo
997 997
      */
998 998
     public function renderWrap($data){
999 999
         $out = $data;
1000
-		$docs = count($this->_docs) - $this->skippedDocs;
1001
-		if ((($this->getCFGDef("noneWrapOuter", "1") && $docs == 0) || $docs > 0) && !empty($this->ownerTPL)) {
1000
+        $docs = count($this->_docs) - $this->skippedDocs;
1001
+        if ((($this->getCFGDef("noneWrapOuter", "1") && $docs == 0) || $docs > 0) && !empty($this->ownerTPL)) {
1002 1002
             $this->debug->debug("","renderWrapTPL",2);
1003 1003
             $parse = true;
1004 1004
             $plh = array($this->getCFGDef("sysKey", "dl") . ".wrap" => $data);
1005 1005
             /**
1006
-            * @var $extPrepare prepare_DL_Extender
1007
-            */
1006
+             * @var $extPrepare prepare_DL_Extender
1007
+             */
1008 1008
             $extPrepare = $this->getExtender('prepare');
1009 1009
             if ($extPrepare) {
1010 1010
                 $params = $extPrepare->init($this, array(
1011 1011
                     'data' => array(
1012
-						'docs' => $this->_docs,
1013
-						'placeholders' => $plh
1014
-					),
1012
+                        'docs' => $this->_docs,
1013
+                        'placeholders' => $plh
1014
+                    ),
1015 1015
                     'nameParam' => 'prepareWrap',
1016 1016
                     'return' => 'placeholders'
1017 1017
                 ));
@@ -1037,12 +1037,12 @@  discard block
 block discarded – undo
1037 1037
         return $out;
1038 1038
     }
1039 1039
     /**
1040
-    * Единые обработки массива с данными о документе для всех контроллеров
1041
-    *
1042
-    * @param array $data массив с данными о текущем документе
1043
-    * @param int $i номер итерации в цикле
1044
-    * @return array массив с данными которые можно использовать в цикле render метода
1045
-    */
1040
+     * Единые обработки массива с данными о документе для всех контроллеров
1041
+     *
1042
+     * @param array $data массив с данными о текущем документе
1043
+     * @param int $i номер итерации в цикле
1044
+     * @return array массив с данными которые можно использовать в цикле render метода
1045
+     */
1046 1046
     protected function uniformPrepare(&$data, $i=0){
1047 1047
         $class = array();
1048 1048
 
@@ -1075,8 +1075,8 @@  discard block
 block discarded – undo
1075 1075
         $data[$this->getCFGDef("sysKey", "dl") . '.class'] = $class;
1076 1076
 
1077 1077
         /**
1078
-        * @var $extE e_DL_Extender
1079
-        */
1078
+         * @var $extE e_DL_Extender
1079
+         */
1080 1080
         $extE = $this->getExtender('e', true, true);
1081 1081
         if($out = $extE->init($this, compact('data'))){
1082 1082
             if(is_array($out)){
@@ -1314,7 +1314,7 @@  discard block
 block discarded – undo
1314 1314
         return $out;
1315 1315
     }
1316 1316
 
1317
-	public function docsCollection(){
1317
+    public function docsCollection(){
1318 1318
         return new DLCollection($this->modx, $this->_docs);
1319 1319
     }
1320 1320
 
@@ -1511,10 +1511,10 @@  discard block
 block discarded – undo
1511 1511
     }
1512 1512
 
1513 1513
     /**
1514
-    * Получение Parent key
1515
-    * По умолчанию это parent. Переопределить можно в контроллере присвоив другое значение переменной parentField
1516
-    * @return string Parent Key основной таблицы
1517
-    */
1514
+     * Получение Parent key
1515
+     * По умолчанию это parent. Переопределить можно в контроллере присвоив другое значение переменной parentField
1516
+     * @return string Parent Key основной таблицы
1517
+     */
1518 1518
     public function getParentField(){
1519 1519
         return isset($this->parentField) ? $this->parentField : '';
1520 1520
     }
@@ -1533,7 +1533,7 @@  discard block
 block discarded – undo
1533 1533
         if (!$filter_string) return;
1534 1534
         $output = array('join' => '', 'where' => '');
1535 1535
         $logic_op_found = false;
1536
-		$joins = $wheres = array();
1536
+        $joins = $wheres = array();
1537 1537
         foreach ($this->_logic_ops as $op => $sql) {
1538 1538
             if (strpos($filter_string, $op) === 0) {
1539 1539
                 $logic_op_found = true;
Please login to merge, or discard this patch.
Spacing   +29 added lines, -29 removed lines patch added patch discarded remove patch
@@ -269,18 +269,18 @@  discard block
 block discarded – undo
269 269
 	 * @param string $str строка с фильтром
270 270
      * @return array массив субфильтров
271 271
      */
272
-	public function smartSplit($str){
272
+	public function smartSplit($str) {
273 273
 		$res = array();
274 274
 		$cur = '';
275 275
 		$open = 0;
276 276
 		$strlen = mb_strlen($str, 'UTF-8');
277
-		for($i=0;$i<=$strlen;$i++){
277
+		for ($i = 0; $i <= $strlen; $i++) {
278 278
 			$e = mb_substr($str, $i, 1, 'UTF-8');
279
-			switch($e){
279
+			switch ($e) {
280 280
 				case ')': {
281 281
 					$open--;
282
-					if($open == 0){
283
-						$res[] = $cur.')';
282
+					if ($open == 0) {
283
+						$res[] = $cur . ')';
284 284
 						$cur = '';
285 285
 					} else {
286 286
 						$cur .= $e;
@@ -293,7 +293,7 @@  discard block
 block discarded – undo
293 293
 					break;
294 294
 				}
295 295
 				case ';':{
296
-					if($open == 0){
296
+					if ($open == 0) {
297 297
 						$res[] = $cur;
298 298
 						$cur = '';
299 299
 					} else {
@@ -307,7 +307,7 @@  discard block
 block discarded – undo
307 307
 			}
308 308
 		}
309 309
 		$cur = preg_replace("/(\))$/u", '', $cur);
310
-		if ($cur != ''){
310
+		if ($cur != '') {
311 311
 			$res[] = $cur;
312 312
 		}
313 313
 		return $res;
@@ -435,14 +435,14 @@  discard block
 block discarded – undo
435 435
                 $cfgName[1] = 'custom';
436 436
             }
437 437
             $cfgName[1] = rtrim($cfgName[1], '/');
438
-            switch($cfgName[1]){
438
+            switch ($cfgName[1]) {
439 439
                 case 'custom':
440 440
                 case 'core':{
441 441
                     $configFile = dirname(dirname(__FILE__)) . "/config/{$cfgName[1]}/{$cfgName[0]}.json";
442 442
                     break;
443 443
                 }
444 444
                 default:{
445
-                    $configFile = $this->FS->relativePath( $cfgName[1] . '/' . $cfgName[0] . ".json");
445
+                    $configFile = $this->FS->relativePath($cfgName[1] . '/' . $cfgName[0] . ".json");
446 446
                     break;
447 447
                 }
448 448
             }
@@ -611,7 +611,7 @@  discard block
 block discarded – undo
611 611
 	 *
612 612
 	 * @return int
613 613
 	 */
614
-	 public function getCurrentMODXPageID(){
614
+	 public function getCurrentMODXPageID() {
615 615
 		$id = isset($this->modx->documentIdentifier) ? (int)$this->modx->documentIdentifier : 0;
616 616
 		$docData = isset($this->modx->documentObject) ? $this->modx->documentObject : array();
617 617
 
@@ -693,7 +693,7 @@  discard block
 block discarded – undo
693 693
      */
694 694
     public function setConfig($cfg)
695 695
     {
696
-		if(is_scalar($cfg)) $cfg = array($cfg);
696
+		if (is_scalar($cfg)) $cfg = array($cfg);
697 697
         if (is_array($cfg)) {
698 698
             $this->_cfg = array_merge($this->_cfg, $cfg);
699 699
             $ret = count($this->_cfg);
@@ -749,7 +749,7 @@  discard block
 block discarded – undo
749 749
         $out = DLTemplate::getInstance($this->getMODX())->toPlaceholders($data, $set, $key, $id);
750 750
 
751 751
         $this->debug->debugEnd(
752
-            "toPlaceholders", array($key ." placeholder" => $data), array('html')
752
+            "toPlaceholders", array($key . " placeholder" => $data), array('html')
753 753
         );
754 754
         return $out;
755 755
     }
@@ -771,7 +771,7 @@  discard block
 block discarded – undo
771 771
         }
772 772
         $out = array();
773 773
         foreach ($data as $item) {
774
-            if($item !== ''){
774
+            if ($item !== '') {
775 775
                 $out[] = $this->modx->db->escape($item);
776 776
             }
777 777
         }
@@ -995,11 +995,11 @@  discard block
 block discarded – undo
995 995
      * @param string $data html код который нужно обернуть в ownerTPL
996 996
      * @return string результатирующий html код
997 997
      */
998
-    public function renderWrap($data){
998
+    public function renderWrap($data) {
999 999
         $out = $data;
1000 1000
 		$docs = count($this->_docs) - $this->skippedDocs;
1001 1001
 		if ((($this->getCFGDef("noneWrapOuter", "1") && $docs == 0) || $docs > 0) && !empty($this->ownerTPL)) {
1002
-            $this->debug->debug("","renderWrapTPL",2);
1002
+            $this->debug->debug("", "renderWrapTPL", 2);
1003 1003
             $parse = true;
1004 1004
             $plh = array($this->getCFGDef("sysKey", "dl") . ".wrap" => $data);
1005 1005
             /**
@@ -1015,13 +1015,13 @@  discard block
 block discarded – undo
1015 1015
                     'nameParam' => 'prepareWrap',
1016 1016
                     'return' => 'placeholders'
1017 1017
                 ));
1018
-                if (is_bool($params) && $params === false){
1018
+                if (is_bool($params) && $params === false) {
1019 1019
                     $out = $data;
1020 1020
                     $parse = false;
1021 1021
                 }
1022 1022
                 $plh = $params;
1023 1023
             }
1024
-            if($parse && !empty($this->ownerTPL)){
1024
+            if ($parse && !empty($this->ownerTPL)) {
1025 1025
                 $this->debug->updateMessage(
1026 1026
                     array("render ownerTPL" => $this->ownerTPL, "With data" => print_r($plh, 1)),
1027 1027
                     "renderWrapTPL",
@@ -1029,7 +1029,7 @@  discard block
 block discarded – undo
1029 1029
                 );
1030 1030
                 $out = $this->parseChunk($this->ownerTPL, $plh);
1031 1031
             }
1032
-            if(empty($this->ownerTPL)){
1032
+            if (empty($this->ownerTPL)) {
1033 1033
                 $this->debug->updateMessage("empty ownerTPL", "renderWrapTPL");
1034 1034
             }
1035 1035
             $this->debug->debugEnd("renderWrapTPL");
@@ -1043,12 +1043,12 @@  discard block
 block discarded – undo
1043 1043
     * @param int $i номер итерации в цикле
1044 1044
     * @return array массив с данными которые можно использовать в цикле render метода
1045 1045
     */
1046
-    protected function uniformPrepare(&$data, $i=0){
1046
+    protected function uniformPrepare(&$data, $i = 0) {
1047 1047
         $class = array();
1048 1048
 
1049 1049
         $iterationName = ($i % 2 == 0) ? 'Odd' : 'Even';
1050 1050
         $tmp = strtolower($iterationName);
1051
-        $class[] = $this->getCFGDef($tmp.'Class', $tmp);
1051
+        $class[] = $this->getCFGDef($tmp . 'Class', $tmp);
1052 1052
 
1053 1053
         $this->renderTPL = $this->getCFGDef('tplId' . $i, $this->renderTPL);
1054 1054
         $this->renderTPL = $this->getCFGDef('tpl' . $iterationName, $this->renderTPL);
@@ -1078,9 +1078,9 @@  discard block
 block discarded – undo
1078 1078
         * @var $extE e_DL_Extender
1079 1079
         */
1080 1080
         $extE = $this->getExtender('e', true, true);
1081
-        if($out = $extE->init($this, compact('data'))){
1082
-            if(is_array($out)){
1083
-                $data =  $out;
1081
+        if ($out = $extE->init($this, compact('data'))) {
1082
+            if (is_array($out)) {
1083
+                $data = $out;
1084 1084
             }
1085 1085
         }
1086 1086
         return compact('class', 'iterationName');
@@ -1314,7 +1314,7 @@  discard block
 block discarded – undo
1314 1314
         return $out;
1315 1315
     }
1316 1316
 
1317
-	public function docsCollection(){
1317
+	public function docsCollection() {
1318 1318
         return new DLCollection($this->modx, $this->_docs);
1319 1319
     }
1320 1320
 
@@ -1479,18 +1479,18 @@  discard block
 block discarded – undo
1479 1479
         $children = array(); // children of each ID
1480 1480
         $ids = array();
1481 1481
         foreach ($data as $i => $r) {
1482
-            $row =& $data[$i];
1482
+            $row = & $data[$i];
1483 1483
             $id = $row[$idName];
1484 1484
             $pid = $row[$pidName];
1485
-            $children[$pid][$id] =& $row;
1485
+            $children[$pid][$id] = & $row;
1486 1486
             if (!isset($children[$id])) $children[$id] = array();
1487
-            $row['#childNodes'] =& $children[$id];
1487
+            $row['#childNodes'] = & $children[$id];
1488 1488
             $ids[$row[$idName]] = true;
1489 1489
         }
1490 1490
         // Root elements are elements with non-found PIDs.
1491 1491
         $this->_tree = array();
1492 1492
         foreach ($data as $i => $r) {
1493
-            $row =& $data[$i];
1493
+            $row = & $data[$i];
1494 1494
             if (!isset($ids[$row[$pidName]])) {
1495 1495
                 $this->_tree[$row[$idName]] = $row;
1496 1496
             }
@@ -1515,7 +1515,7 @@  discard block
 block discarded – undo
1515 1515
     * По умолчанию это parent. Переопределить можно в контроллере присвоив другое значение переменной parentField
1516 1516
     * @return string Parent Key основной таблицы
1517 1517
     */
1518
-    public function getParentField(){
1518
+    public function getParentField() {
1519 1519
         return isset($this->parentField) ? $this->parentField : '';
1520 1520
     }
1521 1521
     /**
Please login to merge, or discard this patch.
Braces   +24 added lines, -8 removed lines patch added patch discarded remove patch
@@ -202,7 +202,9 @@  discard block
 block discarded – undo
202 202
             $this->setDebug(1);
203 203
             $this->loadLang(array('core', 'json'));
204 204
 
205
-            if (!is_array($cfg) || empty($cfg)) $cfg = $this->modx->Event->params;
205
+            if (!is_array($cfg) || empty($cfg)) {
206
+                $cfg = $this->modx->Event->params;
207
+            }
206 208
 		} else {
207 209
         	throw new Exception('MODX var is not instaceof DocumentParser');
208 210
 		}
@@ -693,7 +695,9 @@  discard block
 block discarded – undo
693 695
      */
694 696
     public function setConfig($cfg)
695 697
     {
696
-		if(is_scalar($cfg)) $cfg = array($cfg);
698
+		if(is_scalar($cfg)) {
699
+		    $cfg = array($cfg);
700
+		}
697 701
         if (is_array($cfg)) {
698 702
             $this->_cfg = array_merge($this->_cfg, $cfg);
699 703
             $ret = count($this->_cfg);
@@ -745,7 +749,9 @@  discard block
 block discarded – undo
745 749
         }
746 750
         $this->_plh[$key] = $data;
747 751
         $id = $this->getCFGDef('id', '');
748
-        if ($id != '') $id .= ".";
752
+        if ($id != '') {
753
+            $id .= ".";
754
+        }
749 755
         $out = DLTemplate::getInstance($this->getMODX())->toPlaceholders($data, $set, $key, $id);
750 756
 
751 757
         $this->debug->debugEnd(
@@ -1483,7 +1489,9 @@  discard block
 block discarded – undo
1483 1489
             $id = $row[$idName];
1484 1490
             $pid = $row[$pidName];
1485 1491
             $children[$pid][$id] =& $row;
1486
-            if (!isset($children[$id])) $children[$id] = array();
1492
+            if (!isset($children[$id])) {
1493
+                $children[$id] = array();
1494
+            }
1487 1495
             $row['#childNodes'] =& $children[$id];
1488 1496
             $ids[$row[$idName]] = true;
1489 1497
         }
@@ -1530,7 +1538,9 @@  discard block
 block discarded – undo
1530 1538
         $this->debug->debug("getFilters: " . $this->debug->dumpData($filter_string), 'getFilter', 1);
1531 1539
         // the filter parameter tells us, which filters can be used in this query
1532 1540
         $filter_string = trim($filter_string, ' ;');
1533
-        if (!$filter_string) return;
1541
+        if (!$filter_string) {
1542
+            return;
1543
+        }
1534 1544
         $output = array('join' => '', 'where' => '');
1535 1545
         $logic_op_found = false;
1536 1546
 		$joins = $wheres = array();
@@ -1541,9 +1551,15 @@  discard block
 block discarded – undo
1541 1551
                 $subfilters = $this->smartSplit($subfilters);
1542 1552
                 foreach ($subfilters as $subfilter) {
1543 1553
                     $subfilter = $this->getFilters(trim($subfilter));
1544
-                    if (!$subfilter) continue;
1545
-                    if ($subfilter['join']) $joins[] = $subfilter['join'];
1546
-                    if ($subfilter['where']) $wheres[] = $subfilter['where'];
1554
+                    if (!$subfilter) {
1555
+                        continue;
1556
+                    }
1557
+                    if ($subfilter['join']) {
1558
+                        $joins[] = $subfilter['join'];
1559
+                    }
1560
+                    if ($subfilter['where']) {
1561
+                        $wheres[] = $subfilter['where'];
1562
+                    }
1547 1563
                 }
1548 1564
                 $output['join'] = !empty($joins) ? implode(' ', $joins) : '';
1549 1565
                 $output['where'] = !empty($wheres) ? '(' . implode($sql, $wheres) . ')' : '';
Please login to merge, or discard this patch.
assets/snippets/DocLister/snippet.DLglossary.php 1 patch
Indentation   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -79,7 +79,7 @@
 block discarded – undo
79 79
     $p = array();
80 80
 }
81 81
 if (!empty($loadfilter)) {
82
-	$field = explode(".", $field);
82
+    $field = explode(".", $field);
83 83
     $field = end($field);
84 84
     if (!empty($p['filters'])) {
85 85
         $p['filters'] = rtrim(trim($p['filters']), ";") . ";";
Please login to merge, or discard this patch.
assets/snippets/DocLister/lib/DLTemplate.class.php 2 patches
Indentation   +19 added lines, -19 removed lines patch added patch discarded remove patch
@@ -195,20 +195,20 @@  discard block
 block discarded – undo
195 195
         return $tpl;
196 196
     }
197 197
     /**
198
-    * Рендер документа с подстановкой плейсхолдеров и выполнением сниппетов
199
-    *
200
-    * @param int $id ID документа
201
-    * @param bool $events Во время рендера документа стоит ли вызывать события OnLoadWebDocument и OnLoadDocumentObject (внутри метода getDocumentObject).
202
-    * @param mixed $tpl Шаблон с которым необходимо отрендерить документ. Возможные значения:
203
-    *                       null - Использовать шаблон который назначен документу
204
-    *                       int(0-n) - Получить шаблон из базы данных с указанным ID и применить его к документу
205
-    *                       string - Применить шаблон указанный в строке к документу
206
-    * @return string
207
-    *
208
-    * Событие OnLoadWebDocument дополнительно передает параметры:
209
-    *       - с источиком от куда произошел вызов события
210
-    *       - оригинальный экземпляр класса DocumentParser
211
-    */
198
+     * Рендер документа с подстановкой плейсхолдеров и выполнением сниппетов
199
+     *
200
+     * @param int $id ID документа
201
+     * @param bool $events Во время рендера документа стоит ли вызывать события OnLoadWebDocument и OnLoadDocumentObject (внутри метода getDocumentObject).
202
+     * @param mixed $tpl Шаблон с которым необходимо отрендерить документ. Возможные значения:
203
+     *                       null - Использовать шаблон который назначен документу
204
+     *                       int(0-n) - Получить шаблон из базы данных с указанным ID и применить его к документу
205
+     *                       string - Применить шаблон указанный в строке к документу
206
+     * @return string
207
+     *
208
+     * Событие OnLoadWebDocument дополнительно передает параметры:
209
+     *       - с источиком от куда произошел вызов события
210
+     *       - оригинальный экземпляр класса DocumentParser
211
+     */
212 212
     public function renderDoc($id, $events = false, $tpl = null){
213 213
         if((int)$id <= 0) return '';
214 214
 
@@ -243,13 +243,13 @@  discard block
 block discarded – undo
243 243
     }
244 244
 
245 245
     /**
246
-    * Получить содержимое шаблона с определенным номером
247
-    * @param int $id Номер шаблона
248
-    * @return string HTML код шаблона
249
-    */
246
+     * Получить содержимое шаблона с определенным номером
247
+     * @param int $id Номер шаблона
248
+     * @return string HTML код шаблона
249
+     */
250 250
     public function getTemplate($id){
251 251
         $tpl = null;
252
-		if ($id > 0){
252
+        if ($id > 0){
253 253
             $tpl = $this->modx->db->getValue("SELECT `content` FROM {$this->modx->getFullTableName("site_templates")} WHERE `id` = '{$id}'");
254 254
         }
255 255
         if(is_null($tpl)){
Please login to merge, or discard this patch.
Spacing   +13 added lines, -13 removed lines patch added patch discarded remove patch
@@ -209,17 +209,17 @@  discard block
 block discarded – undo
209 209
     *       - с источиком от куда произошел вызов события
210 210
     *       - оригинальный экземпляр класса DocumentParser
211 211
     */
212
-    public function renderDoc($id, $events = false, $tpl = null){
213
-        if((int)$id <= 0) return '';
212
+    public function renderDoc($id, $events = false, $tpl = null) {
213
+        if ((int)$id <= 0) return '';
214 214
 
215 215
         $m = clone $this->modx; //Чтобы была возможность вызывать события
216
-        $m->documentObject = $m->getDocumentObject('id', (int)$id , $events ? 'prepareResponse' : null);
216
+        $m->documentObject = $m->getDocumentObject('id', (int)$id, $events ? 'prepareResponse' : null);
217 217
         if ($m->documentObject['type'] == "reference") {
218 218
             if (is_numeric($m->documentObject['content']) && $m->documentObject['content'] > 0) {
219 219
                 $m->documentObject['content'] = $this->renderDoc($m->documentObject['content'], $events);
220 220
             }
221 221
         }
222
-        switch(true){
222
+        switch (true) {
223 223
             case is_integer($tpl):{
224 224
                 $tpl = $this->getTemplate($tpl);
225 225
                 break;
@@ -233,7 +233,7 @@  discard block
 block discarded – undo
233 233
             }
234 234
         }
235 235
         $m->documentContent = $tpl;
236
-        if($events){
236
+        if ($events) {
237 237
             $m->invokeEvent("OnLoadWebDocument", array(
238 238
                 'source' => 'DLTemplate',
239 239
                 'mainModx' => $this->modx,
@@ -247,12 +247,12 @@  discard block
 block discarded – undo
247 247
     * @param int $id Номер шаблона
248 248
     * @return string HTML код шаблона
249 249
     */
250
-    public function getTemplate($id){
250
+    public function getTemplate($id) {
251 251
         $tpl = null;
252
-		if ($id > 0){
252
+		if ($id > 0) {
253 253
             $tpl = $this->modx->db->getValue("SELECT `content` FROM {$this->modx->getFullTableName("site_templates")} WHERE `id` = '{$id}'");
254 254
         }
255
-        if(is_null($tpl)){
255
+        if (is_null($tpl)) {
256 256
             $tpl = '[*content*]';
257 257
         }
258 258
         return $tpl;
@@ -346,21 +346,21 @@  discard block
 block discarded – undo
346 346
 
347 347
     public function parseDocumentSource($out, $modx = null)
348 348
     {
349
-        if(!is_object($modx)){
349
+        if (!is_object($modx)) {
350 350
             $modx = $this->modx;
351 351
         }
352 352
         $minPasses = empty ($modx->minParserPasses) ? 2 : $modx->minParserPasses;
353 353
         $maxPasses = empty ($modx->maxParserPasses) ? 10 : $modx->maxParserPasses;
354 354
         $site_status = $modx->getConfig('site_status');
355 355
         $modx->config['site_status'] = 0;
356
-        for($i=1; $i<=$maxPasses; $i++){
356
+        for ($i = 1; $i <= $maxPasses; $i++) {
357 357
             $html = $out;
358
-            if(preg_match('/\[\!(.*)\!\]/us', $out)){
358
+            if (preg_match('/\[\!(.*)\!\]/us', $out)) {
359 359
                 $out = str_replace(array('[!', '!]'), array('[[', ']]'), $out);
360 360
             }
361
-            if($i <= $minPasses || $out != $html){
361
+            if ($i <= $minPasses || $out != $html) {
362 362
                 $out = $modx->parseDocumentSource($out);
363
-            }else{
363
+            } else {
364 364
                 break;
365 365
             }
366 366
         }
Please login to merge, or discard this patch.
assets/snippets/DocLister/lib/DLpaginate.class.php 1 patch
Spacing   +13 added lines, -13 removed lines patch added patch discarded remove patch
@@ -135,13 +135,13 @@  discard block
 block discarded – undo
135 135
 
136 136
     public function getOutput() {
137 137
         $out = '';
138
-        if (!$this->calculate && $this->calculate() && !empty($this->pagination)){
138
+        if (!$this->calculate && $this->calculate() && !empty($this->pagination)) {
139 139
             $out = str_replace(array("[+class+]", "[+wrap+]"), array($this->className, $this->pagination), $this->mainTpl) . "\n";
140 140
         }
141 141
         return $out;
142 142
     }
143
-    protected function getPageQuery($page){
144
-        switch($this->mode){
143
+    protected function getPageQuery($page) {
144
+        switch ($this->mode) {
145 145
             case 'offset':
146 146
                 $display = isset($this->modeConfig['display']) ? $this->modeConfig['display'] : 0;
147 147
                 $out = $display * ($page - 1);
@@ -157,12 +157,12 @@  discard block
 block discarded – undo
157 157
     public function get_pagenum_link($id) {
158 158
         $flag = (strpos($this->target, '?') === false);
159 159
         $value = $this->getPageQuery($id);
160
-        if ($flag && $this->urlF){
160
+        if ($flag && $this->urlF) {
161 161
             $out = str_replace($this->urlF, $value, $this->target);
162 162
         } else {
163 163
             $out = $this->target;
164 164
             if ($id > 1) {
165
-                $out .= ($flag ? "?" : "&") . $this->parameterName."=".$value;
165
+                $out .= ($flag ? "?" : "&") . $this->parameterName . "=" . $value;
166 166
             }
167 167
         }
168 168
         return $out;
@@ -211,9 +211,9 @@  discard block
 block discarded – undo
211 211
         if ($lastpage > 1) {
212 212
             if ($this->page) {
213 213
                 if ($this->page > 1) {
214
-                    $this->pagination .=  $this->prevT ? $this->renderItemTPL( $this->prevT, $prev) : '';
214
+                    $this->pagination .= $this->prevT ? $this->renderItemTPL($this->prevT, $prev) : '';
215 215
                 } else {
216
-                    $this->pagination .=  $this->prevI ? $this->renderItemTPL( $this->prevI, $prev) : '';
216
+                    $this->pagination .= $this->prevI ? $this->renderItemTPL($this->prevI, $prev) : '';
217 217
                 }
218 218
             }
219 219
             //pages
@@ -238,7 +238,7 @@  discard block
 block discarded – undo
238 238
                     $this->pagination .= $this->renderItemTPL($this->numberT, 2);
239 239
                     $this->pagination .= $this->renderItemTPL($this->dotsT, 3);
240 240
 
241
-                    for ($counter = $this->page - $this->adjacents; $counter <= $this->page + $this->adjacents; $counter++){
241
+                    for ($counter = $this->page - $this->adjacents; $counter <= $this->page + $this->adjacents; $counter++) {
242 242
                         $tpl = ($counter == $this->page) ? $this->currentT : $this->numberT;
243 243
                         $this->pagination .= $this->renderItemTPL($tpl, $counter);
244 244
                     }
@@ -251,17 +251,17 @@  discard block
 block discarded – undo
251 251
                     $this->pagination .= $this->renderItemTPL($this->numberT, 2);
252 252
                     $this->pagination .= $this->renderItemTPL($this->dotsT, 3);
253 253
 
254
-                    for ($counter = $lastpage - (2 + ($this->adjacents * 2)); $counter <= $lastpage; $counter++){
254
+                    for ($counter = $lastpage - (2 + ($this->adjacents * 2)); $counter <= $lastpage; $counter++) {
255 255
                         $tpl = ($counter == $this->page) ? $this->currentT : $this->numberT;
256 256
                         $this->pagination .= $this->renderItemTPL($tpl, $counter);
257 257
                     }
258 258
                 }
259 259
             }
260 260
             if ($this->page) {
261
-                if (isset($counter) && $this->page < $counter - 1){
262
-                    $this->pagination .=  $this->nextT ? $this->renderItemTPL( $this->nextT, $next) : '';
261
+                if (isset($counter) && $this->page < $counter - 1) {
262
+                    $this->pagination .= $this->nextT ? $this->renderItemTPL($this->nextT, $next) : '';
263 263
                 } else {
264
-                    $this->pagination .=  $this->nextI ? $this->renderItemTPL( $this->nextI, $next) : '';
264
+                    $this->pagination .= $this->nextI ? $this->renderItemTPL($this->nextI, $next) : '';
265 265
                 }
266 266
 
267 267
                 if ($this->showCounter) {
@@ -273,7 +273,7 @@  discard block
 block discarded – undo
273 273
         return true;
274 274
     }
275 275
 
276
-    protected function renderItemTPL($tpl, $num){
276
+    protected function renderItemTPL($tpl, $num) {
277 277
         return str_replace(array('[+num+]', '[+link+]'), array($num, $this->get_pagenum_link($num)), $tpl);
278 278
     }
279 279
 }
280 280
\ No newline at end of file
Please login to merge, or discard this patch.
assets/snippets/DocLister/lib/DLphx.class.php 3 patches
Indentation   +57 added lines, -57 removed lines patch added patch discarded remove patch
@@ -15,25 +15,25 @@  discard block
 block discarded – undo
15 15
 class DLphx
16 16
 {
17 17
     public $placeholders = array();
18
-	public $name = 'PHx';
19
-	public $version = '2.2.0';
20
-	public $user = array();
21
-	public $cache = array(
22
-		'cm' => array(),
23
-		'ui' => array(),
24
-		'mo' => array()
25
-	);
26
-	public $safetags = array(
27
-		array('~(?<![\[]|^\^)\[(?=[^\+\*\(\[]|$)~s', '~(?<=[^\+\*\)\]]|^)\](?=[^\]]|$)~s'),
28
-		array('&_PHX_INTERNAL_091_&', '&_PHX_INTERNAL_093_&'),
29
-		array('[', ']')
30
-	);
31
-	public $console = array();
32
-	public $debug = false;
33
-	public $debugLog = false;
34
-	public $curPass = 0;
35
-	public $maxPasses = 50;
36
-	public $swapSnippetCache = array();
18
+    public $name = 'PHx';
19
+    public $version = '2.2.0';
20
+    public $user = array();
21
+    public $cache = array(
22
+        'cm' => array(),
23
+        'ui' => array(),
24
+        'mo' => array()
25
+    );
26
+    public $safetags = array(
27
+        array('~(?<![\[]|^\^)\[(?=[^\+\*\(\[]|$)~s', '~(?<=[^\+\*\)\]]|^)\](?=[^\]]|$)~s'),
28
+        array('&_PHX_INTERNAL_091_&', '&_PHX_INTERNAL_093_&'),
29
+        array('[', ']')
30
+    );
31
+    public $console = array();
32
+    public $debug = false;
33
+    public $debugLog = false;
34
+    public $curPass = 0;
35
+    public $maxPasses = 50;
36
+    public $swapSnippetCache = array();
37 37
 
38 38
     public function __construct($debug = 0, $maxpass = 50)
39 39
     {
@@ -42,7 +42,7 @@  discard block
 block discarded – undo
42 42
         $this->user["usrid"] = isset($_SESSION['webInternalKey']) ? intval($_SESSION['webInternalKey']) : 0;
43 43
         $this->user["id"] = ($this->user["usrid"] > 0) ? (-$this->user["usrid"]) : $this->user["mgrid"];
44 44
 
45
-		$this->debug = ($debug != '') ? $debug : 0;
45
+        $this->debug = ($debug != '') ? $debug : 0;
46 46
 
47 47
         $this->maxPasses = ($maxpass != '') ? $maxpass : 50;
48 48
 
@@ -236,9 +236,9 @@  discard block
 block discarded – undo
236 236
                     case "eq":
237 237
                         $condition[] = intval(($output == $modifier_value[$i]));
238 238
                         break;
239
-					case "empty":
240
-						 $condition[] = intval(empty($output));
241
-						break;
239
+                    case "empty":
240
+                         $condition[] = intval(empty($output));
241
+                        break;
242 242
                     case "notequals":
243 243
                     case "isnot":
244 244
                     case "isnt":
@@ -283,7 +283,7 @@  discard block
 block discarded – undo
283 283
                         if (!$isvalid) {
284 284
                             $output = NULL;
285 285
                         }
286
-						break;
286
+                        break;
287 287
                     case "then":
288 288
                         $conditional = implode(' ', $condition);
289 289
                         $isvalid = intval(eval("return (" . $conditional . ");"));
@@ -295,7 +295,7 @@  discard block
 block discarded – undo
295 295
                         break;
296 296
                     case "else":
297 297
                         $conditional = implode(' ', $condition);
298
-						$isvalid = intval(eval("return (" . $conditional . ");"));
298
+                        $isvalid = intval(eval("return (" . $conditional . ");"));
299 299
                         if (!$isvalid) {
300 300
                             $output = $modifier_value[$i];
301 301
                         }
@@ -303,7 +303,7 @@  discard block
 block discarded – undo
303 303
                     case "select":
304 304
                         $raw = explode("&", $modifier_value[$i]);
305 305
                         $map = array();
306
-						$count = count($raw);
306
+                        $count = count($raw);
307 307
                         for ($m = 0; $m < $count; $m++) {
308 308
                             $mi = explode("=", $raw[$m]);
309 309
                             $map[$mi[0]] = $mi[1];
@@ -313,7 +313,7 @@  discard block
 block discarded – undo
313 313
                     ##### End of Conditional Modifiers
314 314
 
315 315
                     #####  String Modifiers
316
-					case "default":{
316
+                    case "default":{
317 317
                         $output = ($output === '') ? $modifier_value[0] : $output;
318 318
                         break;
319 319
                     }
@@ -423,7 +423,7 @@  discard block
 block discarded – undo
423 423
 
424 424
                     // If we haven't yet found the modifier, let's look elsewhere
425 425
                     default:
426
-						$snippet = '';
426
+                        $snippet = '';
427 427
                         // modified by Anton Kuzmin (23.06.2010) //
428 428
                         $snippetName = 'phx:' . $modifier_cmd[$i];
429 429
                         if (isset($modx->snippetCache[$snippetName])) {
@@ -453,16 +453,16 @@  discard block
 block discarded – undo
453 453
                         $cm = $snippet;
454 454
                         // end //
455 455
 
456
-						if(!empty($cm)){
457
-							ob_start();
458
-							$options = $modifier_value[$i];
459
-							$custom = eval($cm);
460
-							$msg = ob_get_contents();
461
-							$output = $msg . $custom;
462
-							ob_end_clean();
463
-						}else{
464
-							$output = '';
465
-						}
456
+                        if(!empty($cm)){
457
+                            ob_start();
458
+                            $options = $modifier_value[$i];
459
+                            $custom = eval($cm);
460
+                            $msg = ob_get_contents();
461
+                            $output = $msg . $custom;
462
+                            ob_end_clean();
463
+                        }else{
464
+                            $output = '';
465
+                        }
466 466
                         break;
467 467
                 }
468 468
                 if (count($condition)) $this->Log("  |--- Condition = '" . $condition[count($condition) - 1] . "'");
@@ -483,7 +483,7 @@  discard block
 block discarded – undo
483 483
     }
484 484
 
485 485
     // Returns a cleaned string escaping the HTML and special MODx characters
486
-	public function LogClean($string)
486
+    public function LogClean($string)
487 487
     {
488 488
         $string = preg_replace("/&amp;(#[0-9]+|[a-z]+);/i", "&$1;", $string);
489 489
         $string = APIHelpers::sanitarTag($string);
@@ -491,7 +491,7 @@  discard block
 block discarded – undo
491 491
     }
492 492
 
493 493
     // Simple log entry
494
-	public function Log($string)
494
+    public function Log($string)
495 495
     {
496 496
         if ($this->debug) {
497 497
             $this->debugLog = true;
@@ -500,7 +500,7 @@  discard block
 block discarded – undo
500 500
     }
501 501
 
502 502
     // Log snippet output
503
-	public function LogSnippet($string)
503
+    public function LogSnippet($string)
504 504
     {
505 505
         if ($this->debug) {
506 506
             $this->debugLog = true;
@@ -509,13 +509,13 @@  discard block
 block discarded – undo
509 509
     }
510 510
 
511 511
     // Log pass
512
-	public function LogPass()
512
+    public function LogPass()
513 513
     {
514 514
         $this->console[] = "<div style='margin: 2px;margin-top: 5px;border-bottom: 1px solid black;'>Pass " . $this->curPass . "</div>";
515 515
     }
516 516
 
517 517
     // Log pass
518
-	public function LogSource($string)
518
+    public function LogSource($string)
519 519
     {
520 520
         $this->console[] = "<div style='margin: 2px;margin-top: 5px;border-bottom: 1px solid black;'>Source:</div>" . $this->LogClean($string);
521 521
     }
@@ -523,7 +523,7 @@  discard block
 block discarded – undo
523 523
 
524 524
     // Returns the specified field from the user record
525 525
     // positive userid = manager, negative integer = webuser
526
-	public function ModUser($userid, $field)
526
+    public function ModUser($userid, $field)
527 527
     {
528 528
         global $modx;
529 529
         if (!array_key_exists($userid, $this->cache["ui"])) {
@@ -540,7 +540,7 @@  discard block
 block discarded – undo
540 540
     }
541 541
 
542 542
     // Returns true if the user id is in one the specified webgroups
543
-	public function isMemberOfWebGroupByUserId($userid = 0, $groupNames = array())
543
+    public function isMemberOfWebGroupByUserId($userid = 0, $groupNames = array())
544 544
     {
545 545
         global $modx;
546 546
 
@@ -570,7 +570,7 @@  discard block
 block discarded – undo
570 570
     }
571 571
 
572 572
     // Returns the value of a PHx/MODx placeholder.
573
-	public function getPHxVariable($name)
573
+    public function getPHxVariable($name)
574 574
     {
575 575
         global $modx;
576 576
         // Check if this variable is created by PHx
@@ -584,71 +584,71 @@  discard block
 block discarded – undo
584 584
     }
585 585
 
586 586
     // Sets a placeholder variable which can only be access by PHx
587
-	public function setPHxVariable($name, $value)
587
+    public function setPHxVariable($name, $value)
588 588
     {
589 589
         if ($name != "phx") $this->placeholders[$name] = $value;
590 590
     }
591 591
 
592 592
     //mbstring
593
-	public function substr($str, $s, $l = null)
593
+    public function substr($str, $s, $l = null)
594 594
     {
595 595
         if (function_exists('mb_substr')) return mb_substr($str, $s, $l);
596 596
         return substr($str, $s, $l);
597 597
     }
598 598
 
599
-	public function strlen($str)
599
+    public function strlen($str)
600 600
     {
601 601
         if (function_exists('mb_strlen')) return mb_strlen($str);
602 602
         return strlen($str);
603 603
     }
604 604
 
605
-	public function strtolower($str)
605
+    public function strtolower($str)
606 606
     {
607 607
         if (function_exists('mb_strtolower')) return mb_strtolower($str);
608 608
         return strtolower($str);
609 609
     }
610 610
 
611
-	public function strtoupper($str)
611
+    public function strtoupper($str)
612 612
     {
613 613
         if (function_exists('mb_strtoupper')) return mb_strtoupper($str);
614 614
         return strtoupper($str);
615 615
     }
616 616
 
617
-	public function ucfirst($str)
617
+    public function ucfirst($str)
618 618
     {
619 619
         if (function_exists('mb_strtoupper') && function_exists('mb_substr') && function_exists('mb_strlen'))
620 620
             return mb_strtoupper(mb_substr($str, 0, 1)) . mb_substr($str, 1, mb_strlen($str));
621 621
         return ucfirst($str);
622 622
     }
623 623
 
624
-	public function lcfirst($str)
624
+    public function lcfirst($str)
625 625
     {
626 626
         if (function_exists('mb_strtolower') && function_exists('mb_substr') && function_exists('mb_strlen'))
627 627
             return mb_strtolower(mb_substr($str, 0, 1)) . mb_substr($str, 1, mb_strlen($str));
628 628
         return lcfirst($str);
629 629
     }
630 630
 
631
-	public function ucwords($str)
631
+    public function ucwords($str)
632 632
     {
633 633
         if (function_exists('mb_convert_case'))
634 634
             return mb_convert_case($str, MB_CASE_TITLE);
635 635
         return ucwords($str);
636 636
     }
637 637
 
638
-	public function strrev($str)
638
+    public function strrev($str)
639 639
     {
640 640
         preg_match_all('/./us', $str, $ar);
641 641
         return implode(array_reverse($ar[0]));
642 642
     }
643 643
 
644
-	public function str_shuffle($str)
644
+    public function str_shuffle($str)
645 645
     {
646 646
         preg_match_all('/./us', $str, $ar);
647 647
         shuffle($ar[0]);
648 648
         return implode($ar[0]);
649 649
     }
650 650
 
651
-	public function str_word_count($str)
651
+    public function str_word_count($str)
652 652
     {
653 653
         return count(preg_split('~[^\p{L}\p{N}\']+~u', $str));
654 654
     }
Please login to merge, or discard this patch.
Spacing   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -453,14 +453,14 @@
 block discarded – undo
453 453
                         $cm = $snippet;
454 454
                         // end //
455 455
 
456
-						if(!empty($cm)){
456
+						if (!empty($cm)) {
457 457
 							ob_start();
458 458
 							$options = $modifier_value[$i];
459 459
 							$custom = eval($cm);
460 460
 							$msg = ob_get_contents();
461 461
 							$output = $msg . $custom;
462 462
 							ob_end_clean();
463
-						}else{
463
+						} else {
464 464
 							$output = '';
465 465
 						}
466 466
                         break;
Please login to merge, or discard this patch.
Braces   +70 added lines, -28 removed lines patch added patch discarded remove patch
@@ -47,7 +47,9 @@  discard block
 block discarded – undo
47 47
         $this->maxPasses = ($maxpass != '') ? $maxpass : 50;
48 48
 
49 49
         $modx->setPlaceholder("phx", "&_PHX_INTERNAL_&");
50
-        if (function_exists('mb_internal_encoding')) mb_internal_encoding($modx->config['modx_charset']);
50
+        if (function_exists('mb_internal_encoding')) {
51
+            mb_internal_encoding($modx->config['modx_charset']);
52
+        }
51 53
     }
52 54
 
53 55
     // Plugin event hook for MODx
@@ -67,7 +69,9 @@  discard block
 block discarded – undo
67 69
     {
68 70
         global $modx;
69 71
         // If we already reached max passes don't get at it again.
70
-        if ($this->curPass == $this->maxPasses) return $template;
72
+        if ($this->curPass == $this->maxPasses) {
73
+            return $template;
74
+        }
71 75
         // Set template pre-process hash
72 76
         $st = md5($template);
73 77
         // Replace non-call characters in the template: [, ]
@@ -85,7 +89,9 @@  discard block
 block discarded – undo
85 89
         // Set template post-process hash
86 90
         $et = md5($template);
87 91
         // If template has changed, parse it once more...
88
-        if ($st != $et) $template = $this->Parse($template);
92
+        if ($st != $et) {
93
+            $template = $this->Parse($template);
94
+        }
89 95
         // Write an event log if debugging is enabled and there is something to log
90 96
         if ($this->debug && $this->debugLog) {
91 97
             $modx->logEvent($this->curPass, 1, $this->createEventLog(), $this->name . ' ' . $this->version);
@@ -203,9 +209,13 @@  discard block
 block discarded – undo
203 209
         $et = md5($template); // Post-process template hash
204 210
 
205 211
         // Log an event if this was the maximum pass
206
-        if ($this->curPass == $this->maxPasses) $this->Log("Max passes reached. infinite loop protection so exiting.\n If you need the extra passes set the max passes to the highest count of nested tags in your template.");
212
+        if ($this->curPass == $this->maxPasses) {
213
+            $this->Log("Max passes reached. infinite loop protection so exiting.\n If you need the extra passes set the max passes to the highest count of nested tags in your template.");
214
+        }
207 215
         // If this pass is not at maximum passes and the template hash is not the same, get at it again.
208
-        if (($this->curPass < $this->maxPasses) && ($st != $et)) $template = $this->ParseValues($template);
216
+        if (($this->curPass < $this->maxPasses) && ($st != $et)) {
217
+            $template = $this->ParseValues($template);
218
+        }
209 219
 
210 220
         return $template;
211 221
     }
@@ -224,7 +234,9 @@  discard block
 block discarded – undo
224 234
             for ($i = 0; $i < $count; $i++) {
225 235
                 $output = trim($output);
226 236
                 $this->Log("  |--- Modifier = '" . $modifier_cmd[$i] . "'");
227
-                if ($modifier_value[$i] != '') $this->Log("  |--- Options = '" . $modifier_value[$i] . "'");
237
+                if ($modifier_value[$i] != '') {
238
+                    $this->Log("  |--- Options = '" . $modifier_value[$i] . "'");
239
+                }
228 240
                 switch ($modifier_cmd[$i]) {
229 241
                     #####  Conditional Modifiers
230 242
                     case "input":
@@ -267,7 +279,9 @@  discard block
 block discarded – undo
267 279
                     case "ir":
268 280
                     case "memberof":
269 281
                     case "mo": // Is Member Of  (same as inrole but this one can be stringed as a conditional)
270
-                        if ($output == "&_PHX_INTERNAL_&") $output = $this->user["id"];
282
+                        if ($output == "&_PHX_INTERNAL_&") {
283
+                            $output = $this->user["id"];
284
+                        }
271 285
                         $grps = ($this->strlen($modifier_value[$i]) > 0) ? explode(",", $modifier_value[$i]) : array();
272 286
                         $condition[] = intval($this->isMemberOfWebGroupByUserId($output, $grps));
273 287
                         break;
@@ -386,11 +400,15 @@  discard block
 block discarded – undo
386 400
                         $output = eval("return " . $filter . ";");
387 401
                         break;
388 402
                     case "isnotempty":
389
-                        if (!empty($output)) $output = $modifier_value[$i];
403
+                        if (!empty($output)) {
404
+                            $output = $modifier_value[$i];
405
+                        }
390 406
                         break;
391 407
                     case "isempty":
392 408
                     case "ifempty":
393
-                        if (empty($output)) $output = $modifier_value[$i];
409
+                        if (empty($output)) {
410
+                            $output = $modifier_value[$i];
411
+                        }
394 412
                         break;
395 413
                     case "nl2br":
396 414
                         $output = nl2br($output);
@@ -400,7 +418,9 @@  discard block
 block discarded – undo
400 418
                         break;
401 419
                     case "set":
402 420
                         $c = $i + 1;
403
-                        if ($count > $c && $modifier_cmd[$c] == "value") $output = preg_replace("~([^a-zA-Z0-9])~", "", $modifier_value[$i]);
421
+                        if ($count > $c && $modifier_cmd[$c] == "value") {
422
+                            $output = preg_replace("~([^a-zA-Z0-9])~", "", $modifier_value[$i]);
423
+                        }
404 424
                         break;
405 425
                     case "value":
406 426
                         if ($i > 0 && $modifier_cmd[$i - 1] == "set") {
@@ -412,11 +432,15 @@  discard block
 block discarded – undo
412 432
                         $output = md5($output);
413 433
                         break;
414 434
                     case "userinfo":
415
-                        if ($output == "&_PHX_INTERNAL_&") $output = $this->user["id"];
435
+                        if ($output == "&_PHX_INTERNAL_&") {
436
+                            $output = $this->user["id"];
437
+                        }
416 438
                         $output = $this->ModUser($output, $modifier_value[$i]);
417 439
                         break;
418 440
                     case "inrole": // deprecated
419
-                        if ($output == "&_PHX_INTERNAL_&") $output = $this->user["id"];
441
+                        if ($output == "&_PHX_INTERNAL_&") {
442
+                            $output = $this->user["id"];
443
+                        }
420 444
                         $grps = ($this->strlen($modifier_value[$i]) > 0) ? explode(",", $modifier_value[$i]) : array();
421 445
                         $output = intval($this->isMemberOfWebGroupByUserId($output, $grps));
422 446
                         break;
@@ -460,12 +484,14 @@  discard block
 block discarded – undo
460 484
 							$msg = ob_get_contents();
461 485
 							$output = $msg . $custom;
462 486
 							ob_end_clean();
463
-						}else{
487
+						} else{
464 488
 							$output = '';
465 489
 						}
466 490
                         break;
467 491
                 }
468
-                if (count($condition)) $this->Log("  |--- Condition = '" . $condition[count($condition) - 1] . "'");
492
+                if (count($condition)) {
493
+                    $this->Log("  |--- Condition = '" . $condition[count($condition) - 1] . "'");
494
+                }
469 495
                 $this->Log("  |--- Output = '" . $output . "'");
470 496
             }
471 497
         }
@@ -545,7 +571,9 @@  discard block
 block discarded – undo
545 571
         global $modx;
546 572
 
547 573
         // if $groupNames is not an array return false
548
-        if (!is_array($groupNames)) return false;
574
+        if (!is_array($groupNames)) {
575
+            return false;
576
+        }
549 577
 
550 578
         // if the user id is a negative number make it positive
551 579
         if (intval($userid) < 0) {
@@ -562,8 +590,9 @@  discard block
 block discarded – undo
562 590
             $grpNames = $this->cache["mo"][$userid];
563 591
         }
564 592
         // Check if a supplied group matches a webgroup from the array we just created
565
-        foreach ($groupNames as $k => $v)
566
-            if (in_array(trim($v), $grpNames)) return true;
593
+        foreach ($groupNames as $k => $v) {
594
+                    if (in_array(trim($v), $grpNames)) return true;
595
+        }
567 596
 
568 597
         // If we get here the above logic did not find a match, so return false
569 598
         return false;
@@ -586,52 +615,65 @@  discard block
 block discarded – undo
586 615
     // Sets a placeholder variable which can only be access by PHx
587 616
 	public function setPHxVariable($name, $value)
588 617
     {
589
-        if ($name != "phx") $this->placeholders[$name] = $value;
618
+        if ($name != "phx") {
619
+            $this->placeholders[$name] = $value;
620
+        }
590 621
     }
591 622
 
592 623
     //mbstring
593 624
 	public function substr($str, $s, $l = null)
594 625
     {
595
-        if (function_exists('mb_substr')) return mb_substr($str, $s, $l);
626
+        if (function_exists('mb_substr')) {
627
+            return mb_substr($str, $s, $l);
628
+        }
596 629
         return substr($str, $s, $l);
597 630
     }
598 631
 
599 632
 	public function strlen($str)
600 633
     {
601
-        if (function_exists('mb_strlen')) return mb_strlen($str);
634
+        if (function_exists('mb_strlen')) {
635
+            return mb_strlen($str);
636
+        }
602 637
         return strlen($str);
603 638
     }
604 639
 
605 640
 	public function strtolower($str)
606 641
     {
607
-        if (function_exists('mb_strtolower')) return mb_strtolower($str);
642
+        if (function_exists('mb_strtolower')) {
643
+            return mb_strtolower($str);
644
+        }
608 645
         return strtolower($str);
609 646
     }
610 647
 
611 648
 	public function strtoupper($str)
612 649
     {
613
-        if (function_exists('mb_strtoupper')) return mb_strtoupper($str);
650
+        if (function_exists('mb_strtoupper')) {
651
+            return mb_strtoupper($str);
652
+        }
614 653
         return strtoupper($str);
615 654
     }
616 655
 
617 656
 	public function ucfirst($str)
618 657
     {
619
-        if (function_exists('mb_strtoupper') && function_exists('mb_substr') && function_exists('mb_strlen'))
620
-            return mb_strtoupper(mb_substr($str, 0, 1)) . mb_substr($str, 1, mb_strlen($str));
658
+        if (function_exists('mb_strtoupper') && function_exists('mb_substr') && function_exists('mb_strlen')) {
659
+                    return mb_strtoupper(mb_substr($str, 0, 1)) . mb_substr($str, 1, mb_strlen($str));
660
+        }
621 661
         return ucfirst($str);
622 662
     }
623 663
 
624 664
 	public function lcfirst($str)
625 665
     {
626
-        if (function_exists('mb_strtolower') && function_exists('mb_substr') && function_exists('mb_strlen'))
627
-            return mb_strtolower(mb_substr($str, 0, 1)) . mb_substr($str, 1, mb_strlen($str));
666
+        if (function_exists('mb_strtolower') && function_exists('mb_substr') && function_exists('mb_strlen')) {
667
+                    return mb_strtolower(mb_substr($str, 0, 1)) . mb_substr($str, 1, mb_strlen($str));
668
+        }
628 669
         return lcfirst($str);
629 670
     }
630 671
 
631 672
 	public function ucwords($str)
632 673
     {
633
-        if (function_exists('mb_convert_case'))
634
-            return mb_convert_case($str, MB_CASE_TITLE);
674
+        if (function_exists('mb_convert_case')) {
675
+                    return mb_convert_case($str, MB_CASE_TITLE);
676
+        }
635 677
         return ucwords($str);
636 678
     }
637 679
 
Please login to merge, or discard this patch.