示例#1
0
文件: users.php 项目: hungnv0789/vhtm
	/**
	* Process
	* Works out what's going on.
	* The API does the loading, saving, updating - this page just displays the right form(s), checks password validation and so on.
	* After that, it'll print a success/failure message depending on what happened.
	* It also checks to make sure that you're an admin before letting you add or delete.
	* It also checks you're not going to delete your own account.
	* If you're not an admin user, it won't let you edit anyone elses account and it won't let you delete your own account either.
	*
	* @see PrintHeader
	* @see ParseTemplate
	* @see IEM::getDatabase()
	* @see GetUser
	* @see GetLang
	* @see User_API::Set
	* @see PrintEditForm
	* @see CheckUserSystem
	* @see PrintManageUsers
	* @see User_API::Find
	* @see User_API::Admin
	* @see PrintFooter
	*
	* @return Void Doesn't return anything, passes control over to the relevant function and prints that functions return message.
	*/
	function Process()
	{
		$action = (isset($_GET['Action'])) ? strtolower($_GET['Action']) : '';

		if (!in_array($action, $this->PopupWindows)) {
			$this->PrintHeader();
		}

		$thisuser    = IEM::getCurrentUser();
		$checkaction = $action;
		
		if ($action == 'generatetoken') {
			$checkaction = 'manage';
		}
		
		if (!$thisuser->HasAccess('users', $checkaction)) {
			$this->DenyAccess();
		}

		if ($action == 'processpaging') {
			$this->SetPerPage($_GET['PerPageDisplay']);
			
			$action = '';
		}

		switch ($action) {
			case 'generatetoken':
				$check_fields = array('username', 'fullname', 'emailaddress');
				foreach ($check_fields as $field) {
					if (!isset($_POST[$field])) {
						exit;
					}
					$$field = $_POST[$field];
				}
				$user = GetUser();
				echo htmlspecialchars(sha1($username . $fullname . $emailaddress . GetRealIp(true) . time() . microtime()), ENT_QUOTES, SENDSTUDIO_CHARSET);
				exit;
			break;

			case 'save':
				$userid = (isset($_GET['UserID']))
					? $_GET['UserID']
					: 0;
				
				if (empty($_POST)) {
					$GLOBALS['Error']   = GetLang('UserNotUpdated');
					$GLOBALS['Message'] = $this->ParseTemplate('ErrorMsg', true, false);
					
					$this->PrintEditForm($userid);
					
					break;
				}

				$user     = GetUser($userid);
				$username = false;
				
				if (isset($_POST['username'])) {
					$username = $_POST['username'];
				}
				
				$userfound = $user->Find($username);
				$error     = false;
				$template  = false;

				$duplicate_username = false;
				
				if ($userfound && $userfound != $userid) {
					$duplicate_username = true;
					$error = GetLang('UserAlreadyExists');
				}

				$warnings           = array();
				$GLOBALS['Message'] = '';

				if (!$duplicate_username) {
					$to_check = array();
					
					foreach (array('status' => 'isLastActiveUser', 'admintype' => 'isLastSystemAdmin') as $area => $desc) {
						if (!isset($_POST[$area])) {
							$to_check[] = $desc;
						}
						
						if (isset($_POST[$area]) && $_POST[$area] == '0') {
							$to_check[] = $desc;
						}
					}

					if ($user->isAdmin()) {
						$to_check[] = 'isLastSystemAdmin';
					}

					$error = $this->CheckUserSystem($userid, $to_check);
                    
					if (!$error) {
						$smtptype = (isset($_POST['smtptype']))
							? $_POST['smtptype'] 
							: 0;

						// Make sure smtptype is eiter 0 or 1
						if ($smtptype != 1) {
							$smtptype = 0;
						}

						/**
						 * This was added, because User's API uses different names than of the HTML form names.
						 * HTML form names should stay the same to keep it consistant throught the application
						 *
						 * This will actually map HTML forms => User's API fields
						 */
						$areaMapping = array(
							'trialuser'                    => 'trialuser',
							'groupid'                      => 'groupid',
							'username'                     => 'username',
							'fullname'                     => 'fullname',
							'emailaddress'                 => 'emailaddress',
							'status'                       => 'status',
							'admintype'                    => 'admintype',
							'listadmintype'                => 'listadmintype',
							'segmentadmintype'             => 'segmentadmintype',
							'templateadmintype'            => 'templateadmintype',
							'editownsettings'              => 'editownsettings',
							'usertimezone'                 => 'usertimezone',
							'textfooter'                   => 'textfooter',
							'htmlfooter'                   => 'htmlfooter',
							'infotips'                     => 'infotips',
							'smtp_server'                  => 'smtpserver',
							'smtp_u'                       => 'smtpusername',
							'smtp_p'                       => 'smtppassword',
							'smtp_port'                    => 'smtpport',
							'usewysiwyg'                   => 'usewysiwyg',
							'usexhtml'                     => 'usexhtml',
							'enableactivitylog'            => 'enableactivitylog',
							'xmlapi'                       => 'xmlapi',
							'xmltoken'                     => 'xmltoken',
							'googlecalendarusername'       => 'googlecalendarusername',
							'googlecalendarpassword'       => 'googlecalendarpassword',
							'user_language'                => 'user_language',
							'adminnotify_email'            => 'adminnotify_email',
							'adminnotify_send_flag'        => 'adminnotify_send_flag',
							'adminnotify_send_threshold'   => 'adminnotify_send_threshold',
							'adminnotify_send_emailtext'   => 'adminnotify_send_emailtext',
							'adminnotify_import_flag'      => 'adminnotify_import_flag',
							'adminnotify_import_threshold' => 'adminnotify_import_threshold',
							'adminnotify_import_emailtext' => 'adminnotify_import_emailtext'
						);
						
						$group           = API_USERGROUPS::getRecordById($_POST['groupid']);
						$totalEmails     = (int) $group['limit_totalemailslimit'];
						$unlimitedEmails = $totalEmails == 0;
						
						// set fields
						foreach ($areaMapping as $p => $area) {
							$val = (isset($_POST[$p])) ? $_POST[$p] : '';
							
							if (in_array($area, array('status', 'editownsettings'))) {
								if ($userid == $thisuser->userid) {
									$val = $thisuser->$area;
								}
							}
							
							$user->Set($area, $val);
						}

						// activity type
						$activity = IEM::requestGetPOST('eventactivitytype', '', 'trim');
						
						if (!empty($activity)) {
							$activity_array = explode("\n", $activity);
							
							for ($i = 0, $j = count($activity_array); $i < $j; ++$i) {
								$activity_array[$i] = trim($activity_array[$i]);
							}
						} else {
							$activity_array = array();
						}
						
						$user->Set('eventactivitytype', $activity_array);

						// the 'limit' things being on actually means unlimited. so check if the value is NOT set.
						foreach (array('permonth', 'perhour', 'maxlists') as $p => $area) {
							$limit_check = 'limit' . $area;
							$val         = 0;
							
							if (!isset($_POST[$limit_check])) {
								$val = (isset($_POST[$area])) 
									? $_POST[$area]
									: 0;
							}
							
							$user->Set($area, $val);
						}

						if (SENDSTUDIO_MAXHOURLYRATE > 0) {
							if ($user->Get('perhour') == 0 || ($user->Get('perhour') > SENDSTUDIO_MAXHOURLYRATE)) {
								$user_hourly = $this->FormatNumber($user->Get('perhour'));
								
								if ($user->Get('perhour') == 0) {
									$user_hourly = GetLang('UserPerHour_Unlimited');
								}
								
								$warnings[] = sprintf(GetLang('UserPerHourOverMaxHourlyRate'), $this->FormatNumber(SENDSTUDIO_MAXHOURLYRATE), $user_hourly);
							}
						}

						if ($smtptype == 0) {
							$user->Set('smtpserver', '');
							$user->Set('smtpusername', '');
							$user->Set('smtppassword', '');
							$user->Set('smtpport', 25);
						}

						if ($_POST['ss_p'] != '') {
							if ($_POST['ss_p_confirm'] != '' && $_POST['ss_p_confirm'] == $_POST['ss_p']) {
								$user->Set('password', $_POST['ss_p']);
							} else {
								$error = GetLang('PasswordsDontMatch');
							}
						}
					}

					if (!$error) {
						$user->RevokeAccess();

						$temp = array();
						
						if (!empty($_POST['permissions'])) {
							foreach ($_POST['permissions'] as $area => $p) {
								foreach ($p as $subarea => $k) {
									$temp[$subarea] = $user->GrantAccess($area, $subarea);
								}
							}
						}
					}
				}

				if (!$error) {
					$result = $user->Save();

					if ($result) {
						FlashMessage(GetLang('UserUpdated'), SS_FLASH_MSG_SUCCESS, IEM::urlFor('Users'));
					} else {
						$GLOBALS['Message'] = GetFlashMessages();
						$GLOBALS['Error'] = GetLang('UserNotUpdated');
						$GLOBALS['Message'] .= $this->ParseTemplate('ErrorMsg', true, false);
					}
				} else {
					$GLOBALS['Error'] = $error;
					$GLOBALS['Message'] = $this->ParseTemplate('ErrorMsg', true, false);
				}

				if (!empty($warnings)) {
					$GLOBALS['Warning'] = implode('<br/>', $warnings);
					$GLOBALS['Message'] .= $this->ParseTemplate('WarningMsg', true, false);
				}

				$this->PrintEditForm($userid);
			break;

			case 'add':
				$temp = get_available_user_count();
				if ($temp['normal'] == 0 && $temp['trial'] == 0) {
					$this->PrintManageUsers();
					break;
				}

				$this->PrintEditForm(0);
			break;

			case 'delete':
				$users = IEM::requestGetPOST('users', array(), 'intval');
				$deleteData = (IEM::requestGetPOST('deleteData', 0, 'intval') == 1);

				$this->DeleteUsers($users, $deleteData);
			break;

			case 'create':
				$user     = New User_API();
				$warnings = array();
				$fields   = array(
					'trialuser', 'username', 'fullname', 'emailaddress',
					'status', 'admintype', 'editownsettings',
					'listadmintype', 'segmentadmintype', 'usertimezone',
					'textfooter', 'htmlfooter', 'templateadmintype',
					'infotips', 'smtpserver',
					'smtpusername', 'smtpport', 'usewysiwyg',
					'enableactivitylog', 'xmlapi', 'xmltoken',
					'googlecalendarusername','googlecalendarpassword',
					'adminnotify_email','adminnotify_send_flag','adminnotify_send_threshold',
					'adminnotify_send_emailtext','adminnotify_import_flag','adminnotify_import_threshold',
					'adminnotify_import_emailtext'
				);

				if (!$user->Find($_POST['username'])) {
					foreach ($fields as $p => $area) {
						$val = (isset($_POST[$area]))
							? $_POST[$area]
							: '';

						$user->Set($area, $val);
					}

					// activity type
					$activity = IEM::requestGetPOST('eventactivitytype', '', 'trim');
					
					if (!empty($activity)) {
						$activity_array = explode("\n", $activity);
						
						for ($i = 0, $j = count($activity_array); $i < $j; ++$i) {
							$activity_array[$i] = trim($activity_array[$i]);
						}
					} else {
						$activity_array = array();
					}
					
					$user->Set('eventactivitytype', $activity_array);

					// the 'limit' things being on actually means unlimited. so check if the value is NOT set.
					foreach (array('permonth', 'perhour', 'maxlists') as $p => $area) {
						$limit_check = 'limit' . $area;
						$val         = 0;
						
						if (!isset($_POST[$limit_check])) {
							$val = (isset($_POST[$area])) 
								? $_POST[$area]
								: 0;
						}
						
						$user->Set($area, $val);
					}

					if (SENDSTUDIO_MAXHOURLYRATE > 0) {
						if ($user->Get('perhour') == 0 || ($user->Get('perhour') > SENDSTUDIO_MAXHOURLYRATE)) {
							$user_hourly = $this->FormatNumber($user->Get('perhour'));
							
							if ($user->Get('perhour') == 0) {
								$user_hourly = GetLang('UserPerHour_Unlimited');
							}
							
							$warnings[] = sprintf(GetLang('UserPerHourOverMaxHourlyRate'), $this->FormatNumber(SENDSTUDIO_MAXHOURLYRATE), $user_hourly);
						}
					}

					// this has a different post value otherwise firefox tries to pre-fill it.
					$smtp_password = '';
					
					if (isset($_POST['smtp_p'])) {
						$smtp_password = $_POST['smtp_p'];
					}
					
					$user->Set('smtppassword', $smtp_password);

					$error = false;

					if ($_POST['ss_p'] != '') {
						if ($_POST['ss_p_confirm'] != '' && $_POST['ss_p_confirm'] == $_POST['ss_p']) {
							$user->Set('password', $_POST['ss_p']);
						} else {
							$error = GetLang('PasswordsDontMatch');
						}
					}

					if (!$error) {
						if (!empty($_POST['permissions'])) {
							foreach ($_POST['permissions'] as $area => $p) {
								foreach ($p as $subarea => $k) {
									$user->GrantAccess($area, $subarea);
								}
							}
						}

						if (!empty($_POST['lists'])) {
							$user->GrantListAccess($_POST['lists']);
						}

						if (!empty($_POST['templates'])) {
							$user->GrantTemplateAccess($_POST['templates']);
						}

						if (!empty($_POST['segments'])) {
							$user->GrantSegmentAccess($_POST['segments']);
						}

						$GLOBALS['Message'] = '';

						if (!empty($warnings)) {
							$GLOBALS['Warning']  = implode('<br/>', $warnings);
							$GLOBALS['Message'] .= $this->ParseTemplate('WarningMsg', true, false);
						}

						$user->Set('gettingstarted', 0);
						$user->Set('groupid', (int) IEM_Request::getParam('groupid'));
						
						$result = $user->Create();
						
						if ($result == '-1') {
							FlashMessage(GetLang('UserNotCreated_License'), SS_FLASH_MSG_ERROR, IEM::urlFor('Users'));
							
							break;
						} else {
							if ($result) {
								FlashMessage(GetLang('UserCreated'), SS_FLASH_MSG_SUCCESS, IEM::urlFor('Users'));
								
								break;
							} else {
								FlashMessage(GetLang('UserNotCreated'), SS_FLASH_MSG_ERROR, IEM::urlFor('Users'));
							}
						}
					} else {
						$GLOBALS['Error'] = $error;
					}
				} else {
					$GLOBALS['Error'] = GetLang('UserAlreadyExists');
				}
				
				$GLOBALS['Message'] = $this->ParseTemplate('ErrorMsg', true, false);

				$details = array();
				
				foreach (array('FullName', 'EmailAddress', 'Status', 'AdminType', 'ListAdminType', 'SegmentAdminType', 'TemplateAdminType', 'InfoTips', 'forcedoubleoptin', 'forcespamcheck', 'smtpserver', 'smtpusername', 'smtpport') as $p => $area) {
					$lower          = strtolower($area);
					$val            = (isset($_POST[$lower])) ? $_POST[$lower] : '';
					$details[$area] = $val;
				}
				
				$this->PrintEditForm(0, $details);
			break;

			case 'edit':
				$userid = IEM::requestGetGET('UserID', 0, 'intval');
				
				if ($userid == 0) {
					$this->DenyAccess();
				}

				$this->PrintEditForm($userid);
			break;

			case 'sendpreviewdisplay':
				$this->PrintHeader(true);
				$this->SendTestPreviewDisplay('index.php?Page=Users&Action=SendPreview', 'self.parent.getSMTPPreviewParameters()');
				$this->PrintFooter(true);
			break;

			case 'testgooglecalendar':
				$status = array(
					'status' => false,
					'message' => ''
				);
				try {
					$details = array(
						'username' => $_REQUEST['gcusername'],
						'password' => $_REQUEST['gcpassword']
					);

					$this->GoogleCalendarAdd($details, true);

					$status['status'] = true;
					$status['message'] = GetLang('GooglecalendarTestSuccess');
				} catch (Exception $e) {
					$status['message'] = GetLang('GooglecalendarTestFailure');
				}

				print GetJSON($status);
			break;

			case 'sendpreview':
				$this->SendTestPreview();
			break;

			default:
				$this->PrintManageUsers();
			break;
		}

		if (!in_array($action, $this->PopupWindows)) {
			$this->PrintFooter();
		}
	}
	/**
	 *
	 * @return unknown_type
	 * @todo phpdocs
	 */
	public function page_deleteGroups()
	{
		$groupIds = IEM_Request::getParam('groups', array());

		// No IDs specified
		if (empty($groupIds)) {
			$this->page_manageGroups();

			return;
		}

		if (!is_array($groupIds)) {
			$groupIds = array($groupIds);
		}

		$failed  = array();
		$success = array();

		foreach ($groupIds as $id) {
			$status = API_USERGROUPS::deleteRecordByID($id);

			if ($status) {
				$success[] = $id;
			} else {
				$failed[] = $id;
			}
		}

		if (count($failed) != 0) {
			FlashMessage(GetLang('UsersGroups_ManageGroups_Message_DeleteFail'), SS_FLASH_MSG_ERROR, IEM::urlFor('UsersGroups', array('Action' => 'manageGroups')));
		} else {
			FlashMessage(sprintf(GetLang('UsersGroups_ManageGroups_Message_DeleteSuccess'), count($success)), SS_FLASH_MSG_SUCCESS, IEM::urlFor('UsersGroups', array('Action' => 'manageGroups')));
		}
	}