PageRenderTime 73ms CodeModel.GetById 44ms app.highlight 22ms RepoModel.GetById 1ms app.codeStats 0ms

/web/concrete/core/controllers/single_pages/dashboard/users/search.php

https://github.com/glockops/concrete5
PHP | 413 lines | 328 code | 70 blank | 15 comment | 95 complexity | 3294dca0091132b5d38fb0ef9a91dac9 MD5 | raw file
  1<?
  2defined('C5_EXECUTE') or die("Access Denied.");
  3class Concrete5_Controller_Dashboard_Users_Search extends Controller {
  4
  5	public function on_start(){
  6		$this->error = Loader::helper('validation/error');
  7	}
  8
  9	public function view() {
 10		// this is hacky as hell, we need to make this page MVC
 11		if ($_REQUEST['task'] != 'edit' && !$_REQUEST['uID']) {
 12			$this->addHeaderItem('<script type="text/javascript">$(function() { ccm_setupAdvancedSearch(\'user\'); });</script>');
 13			$userList = $this->getRequestedSearchResults();
 14			$users = $userList->getPage();
 15					
 16			$this->set('userList', $userList);		
 17			$this->set('users', $users);		
 18			$this->set('pagination', $userList->getPagination());	
 19		}
 20
 21		$form = Loader::helper('form');
 22		$this->set('form', $form);
 23
 24		if($_POST['edit'])	{
 25			$this->validate_user();
 26		}
 27		
 28		if ($_REQUEST['deactivated']) {
 29			$this->set('message', t('User deactivated.'));
 30		}
 31		if ($_REQUEST['activated']) {
 32			$this->set('message', t('User activated.'));
 33		}
 34		if ($_REQUEST['validated']) {
 35			$this->set('message', t('Email marked as valid.'));
 36		}
 37		if ($_REQUEST['user_created']) {
 38			$this->set('message', t('User created.'));
 39		}
 40
 41	}
 42	
 43	
 44	
 45	public function validate_user() {
 46		$pke = PermissionKey::getByHandle('edit_user_properties');
 47		if (!$pke->validate()) {
 48			return false;
 49		}
 50		
 51		$assignment = $pke->getMyAssignment();
 52		
 53		
 54		$vals = Loader::helper('validation/strings');
 55		$valt = Loader::helper('validation/token');
 56		$valc = Loader::helper('concrete/validation');
 57
 58		$uo = UserInfo::getByID(intval($_GET['uID']));			
 59		
 60		$username = trim($_POST['uName']);
 61		$username = preg_replace("/\s+/", " ", $username);
 62		
 63		if ($assignment->allowEditPassword()) { 
 64
 65			$password = $_POST['uPassword'];
 66			$passwordConfirm = $_POST['uPasswordConfirm'];
 67
 68			if ($password) {
 69				if ((strlen($password) < USER_PASSWORD_MINIMUM) || (strlen($password) > USER_PASSWORD_MAXIMUM)) {
 70					$this->error->add( t('A password must be between %s and %s characters',USER_PASSWORD_MINIMUM,USER_PASSWORD_MAXIMUM));
 71				}
 72			}
 73		}		
 74		
 75		if ($assignment->allowEditEmail()) { 
 76			if (!$vals->email($_POST['uEmail'])) {
 77				$this->error->add(t('Invalid email address provided.'));
 78			} else if (!$valc->isUniqueEmail($_POST['uEmail']) && $uo->getUserEmail() != $_POST['uEmail']) {
 79				$this->error->add(t("The email address '%s' is already in use. Please choose another.",$_POST['uEmail']));
 80			}
 81		}
 82
 83		if ($assignment->allowEditUserName()) { 
 84			$_POST['uName'] = $username;		
 85			if (USER_REGISTRATION_WITH_EMAIL_ADDRESS == false) {
 86				if (strlen($username) < USER_USERNAME_MINIMUM) {
 87					$this->error->add(t('A username must be at least %s characters long.',USER_USERNAME_MINIMUM));
 88				}
 89	
 90				if (strlen($username) > USER_USERNAME_MAXIMUM) {
 91					$this->error->add(t('A username cannot be more than %s characters long.',USER_USERNAME_MAXIMUM));
 92				}
 93	
 94				/*
 95				if (strlen($username) >= USER_USERNAME_MINIMUM && !$vals->alphanum($username,USER_USERNAME_ALLOW_SPACES)) {
 96					if(USER_USERNAME_ALLOW_SPACES) {
 97						$e->add(t('A username may only contain letters, numbers and spaces.'));
 98					} else {
 99						$e->add(t('A username may only contain letters or numbers.'));
100					}
101					
102				}
103				*/
104				
105				if (strlen($username) >= USER_USERNAME_MINIMUM && !$valc->username($username)) {
106					if(USER_USERNAME_ALLOW_SPACES) {
107						$this->error->add(t('A username may only contain letters, numbers, spaces, dots (not at the beginning/end), underscores (not at the beginning/end).'));
108					} else {
109						$this->error->add(t('A username may only contain letters numbers, dots (not at the beginning/end), underscores (not at the beginning/end).'));
110					}
111				}
112				if (strcasecmp($uo->getUserName(), $username) && !$valc->isUniqueUsername($username)) {
113					$this->error->add(t("The username '%s' already exists. Please choose another",$username));
114				}		
115			}
116		}
117
118		if ($assignment->allowEditPassword()) { 
119			if (strlen($password) >= USER_PASSWORD_MINIMUM && !$valc->password($password)) {
120				$this->error->add(t('A password may not contain ", \', >, <, or any spaces.'));
121			}
122			
123			if ($password) {
124				if ($password != $passwordConfirm) {
125					$this->error->add(t('The two passwords provided do not match.'));
126				}
127			}
128		}
129		
130		if (!$valt->validate('update_account_' . intval($_GET['uID']) )) {
131			$this->error->add($valt->getErrorMessage());
132		}
133	
134		if (!$this->error->has()) {
135			// do the registration
136			$data = array();
137			if ($assignment->allowEditUserName()) { 
138				$data['uName'] = $_POST['uName'];
139			}
140			if ($assignment->allowEditEmail()) { 
141				$data['uEmail'] = $_POST['uEmail'];
142			}
143			if ($assignment->allowEditPassword()) { 
144				$data['uPassword'] = $_POST['uPassword'];
145				$data['uPasswordConfirm'] = $_POST['uPasswordConfirm'];
146			}
147			if ($assignment->allowEditTimezone()) { 
148				$data['uTimezone'] = $_POST['uTimezone'];
149			}
150			if ($assignment->allowEditDefaultLanguage()) { 
151				$data['uDefaultLanguage'] = $_POST['uDefaultLanguage'];
152			}
153			$process = $uo->update($data);
154			
155			//$db = Loader::db();
156			if ($process) {
157				if ($assignment->allowEditAvatar()) {
158					$av = Loader::helper('concrete/avatar'); 
159					if ( is_uploaded_file($_FILES['uAvatar']['tmp_name']) ) {
160						$uHasAvatar = $av->updateUserAvatar($_FILES['uAvatar']['tmp_name'], $uo->getUserID());
161					}
162				}
163				
164				$gak = PermissionKey::getByHandle('assign_user_groups');
165				$gIDs = array();
166				if (is_array($_POST['gID'])) {
167					foreach($_POST['gID'] as $gID) {
168						if ($gak->validate($gID)) {
169							$gIDs[] = intval($gID);
170						}
171					}
172				}
173				
174				$gIDs = array_unique($gIDs);
175
176				$uo->updateGroups($gIDs);
177
178				$message = t("User updated successfully. ");
179				if ($password) {
180					$message .= t("Password changed.");
181				}
182				$editComplete = true;
183				// reload user object
184				$uo = UserInfo::getByID(intval($_GET['uID']));
185				$this->set('message', $message);
186			} else {
187				$db = Loader::db();
188				$this->error->add($db->ErrorMsg());
189				$this->set('error',$this->error);
190			}
191		}else{
192			$this->set('error',$this->error);
193		}		
194
195	}
196	
197	public function getRequestedSearchResults() {
198		$userList = new UserList();
199		$userList->sortBy('uDateAdded', 'desc');
200		$userList->showInactiveUsers = true;
201		$userList->showInvalidatedUsers = true;
202		
203		$columns = UserSearchColumnSet::getCurrent();
204		$this->set('columns', $columns);
205
206		if ($_GET['keywords'] != '') {
207			$userList->filterByKeywords($_GET['keywords']);
208		}	
209		
210		if ($_REQUEST['numResults'] && Loader::helper('validation/numbers')->integer($_REQUEST['numResults'])) {
211			$userList->setItemsPerPage($_REQUEST['numResults']);
212		}
213		
214		$pk = PermissionKey::getByHandle('access_user_search');
215		$asl = $pk->getMyAssignment();
216
217		$p = new Permissions();
218
219		$filterGIDs = array();
220		if ($asl->getGroupsAllowedPermission() == 'C') { 
221			$userList->filter('u.uID', USER_SUPER_ID, '<>');
222			$userList->addToQuery("left join UserGroups ugRequired on ugRequired.uID = u.uID ");	
223			if (in_array(REGISTERED_GROUP_ID, $asl->getGroupsAllowedArray())) {
224				$userList->filter(false, '(ugRequired.gID in (' . implode(',', $asl->getGroupsAllowedArray()) . ') or ugRequired.gID is null)');
225			} else {
226				$userList->filter('ugRequired.gID', $asl->getGroupsAllowedArray(), 'in');		
227			}
228		}
229		
230		if (isset($_REQUEST['gID']) && is_array($_REQUEST['gID'])) {
231			foreach($_REQUEST['gID'] as $gID) {
232				$g = Group::getByID($gID);
233				if (is_object($g)) {
234					if ($pk->validate($g) && (!in_array($g->getGroupID(), $filterGIDs))) {
235						$filterGIDs[] = $g->getGroupID();
236					}
237				}
238			}
239		}
240		
241		foreach($filterGIDs as $gID) {
242			$userList->filterByGroupID($gID);
243		}
244		if (is_array($_REQUEST['selectedSearchField'])) {
245			foreach($_REQUEST['selectedSearchField'] as $i => $item) {
246				// due to the way the form is setup, index will always be one more than the arrays
247				if ($item != '') {
248					switch($item) {
249						case 'is_active':
250							if ($_GET['active'] === '0') {
251								$userList->filterByIsActive(0);
252							} else if ($_GET['active'] === '1') {
253								$userList->filterByIsActive(1);
254							}
255							break;
256						case "date_added":
257							$dateFrom = $_REQUEST['date_from'];
258							$dateTo = $_REQUEST['date_to'];
259							if ($dateFrom != '') {
260								$dateFrom = date('Y-m-d', strtotime($dateFrom));
261								$userList->filterByDateAdded($dateFrom, '>=');
262								$dateFrom .= ' 00:00:00';
263							}
264							if ($dateTo != '') {
265								$dateTo = date('Y-m-d', strtotime($dateTo));
266								$dateTo .= ' 23:59:59';
267								
268								$userList->filterByDateAdded($dateTo, '<=');
269							}
270							break;
271						case "group_set":
272							$gsID = $_REQUEST['gsID'];
273							$gs = GroupSet::getByID($gsID);
274							$groupsetids = array(-1);
275							if (is_object($gs)) {
276								$groups = $gs->getGroups();
277							}
278							$userList->addToQuery('left join UserGroups ugs on u.uID = ugs.uID');
279							foreach($groups as $g) {
280								if ($pk->validate($g) && (!in_array($g->getGroupID(), $groupsetids))) {
281									$groupsetids[] = $g->getGroupID();
282								}								
283							}							
284							$instr = 'ugs.gID in (' . implode(',', $groupsetids) . ')';
285							$userList->filter(false, $instr);
286							break;
287
288						default:
289							$akID = $item;
290							$fak = UserAttributeKey::get($akID);
291							$type = $fak->getAttributeType();
292							$cnt = $type->getController();
293							$cnt->setAttributeKey($fak);
294							$cnt->searchForm($userList);
295							break;
296					}
297				}
298			}
299		}
300		return $userList;
301	}
302	
303		public function sign_in_as_user($uID, $token = null) {
304		try {
305			$u = new User();
306			
307			$tp = new TaskPermission();
308			if (!$tp->canSudo()) { 
309				throw new Exception(t('You do not have permission to perform this action.'));
310			}
311			
312			$ui = UserInfo::getByID($uID); 
313			if(!($ui instanceof UserInfo)) {
314				throw new Exception(t('Invalid user ID.'));
315			}
316
317			$pk = PermissionKey::getByHandle('access_user_search');
318			if ($pk->validate($ui)) { 
319		
320				$valt = Loader::helper('validation/token');
321				if (!$valt->validate('sudo', $token)) {
322					throw new Exception($valt->getErrorMessage());
323				}
324				
325				User::loginByUserID($uID);
326				$this->redirect('/');
327			
328			}
329			
330		} catch(Exception $e) {
331			$this->set('error', $e);
332			$this->view();
333		}
334	}
335	
336	public function edit_attribute() {
337		$uo = UserInfo::getByID($_POST['uID']);
338		$u = new User();
339		if ($uo->getUserID() == USER_SUPER_ID && (!$u->isSuperUser())) {
340			throw new Exception(t('Only the super user may edit this account.'));
341		}
342		
343		$assignment = PermissionKey::getByHandle('edit_user_properties')->getMyAssignment();
344		$akID = $_REQUEST['uakID'];
345		if (!in_array($akID, $assignment->getAttributesAllowedArray())) {
346			throw new Exception(t('You do not have permission to modify this attribute.'));
347		}
348		
349		$ak = UserAttributeKey::get($akID);
350
351		if ($_POST['task'] == 'update_extended_attribute') { 
352			$ak->saveAttributeForm($uo);
353			$val = $uo->getAttributeValueObject($ak);
354			print $val->getValue('displaySanitized','display');
355			exit;
356		}
357		
358		if ($_POST['task'] == 'clear_extended_attribute') {
359			$uo->clearAttribute($ak);			
360			$val = $uo->getAttributeValueObject($ak);
361			print '<div class="ccm-attribute-field-none">' . t('None') . '</div>';
362			exit;
363		}
364	}
365	
366	public function delete($delUserId, $token = null){
367		$u=new User();
368		try {
369
370			$delUI=UserInfo::getByID($delUserId); 
371			
372			if(!($delUI instanceof UserInfo)) {
373				throw new Exception(t('Invalid user ID.'));
374			}
375
376			if (!PermissionKey::getByHandle('access_user_search')->validate($delUI)) { 
377				throw new Exception(t('Access Denied.'));
378			}
379		
380			$tp = new TaskPermission();
381			if (!$tp->canDeleteUser()) { 
382				throw new Exception(t('You do not have permission to perform this action.'));
383			}
384
385			if ($delUserId == USER_SUPER_ID) {
386				throw new Exception(t('You may not remove the super user account.'));
387			}			
388
389			if($delUserId==$u->getUserID()) {
390				throw new Exception(t('You cannot delete your own user account.'));
391			}
392
393
394			$valt = Loader::helper('validation/token');
395			if (!$valt->validate('delete_account', $token)) {
396				throw new Exception($valt->getErrorMessage());
397			}
398			
399			$delUI->delete(); 
400			$resultMsg=t('User deleted successfully.');
401			
402			$_REQUEST=array();
403			$_GET=array();
404			$_POST=array();		
405			$this->set('message', $resultMsg);
406		} catch (Exception $e) {
407			$this->set('error', $e);
408		}
409		$this->view();
410
411	}
412
413}