ConfirmedPasswordField.php 10.5 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435
<?php

/**
 * Two masked input fields, checks for matching passwords.
 *
 * Optionally hides the fields by default and shows a link to toggle their 
 * visibility.
 * 
 * @package forms
 * @subpackage fields-formattedinput
 */
class ConfirmedPasswordField extends FormField {
	
	/**
	 * Minimum character length of the password.
	 *
	 * @var int
	 */
	public $minLength = null;
	
	/**
	 * Maximum character length of the password.
	 *
	 * @var int
	 */
	public $maxLength = null;
	
	/**
	 * Enforces at least one digit and one alphanumeric
	 * character (in addition to {$minLength} and {$maxLength}
	 *
	 * @var boolean
	 */
	public $requireStrongPassword = false;
	
	/**
	 * Allow empty fields in serverside validation
	 *
	 * @var boolean
	 */
	public $canBeEmpty = false;
	
	/**
	 * If set to TRUE, the "password" and "confirm password" form fields will 
	 * be hidden via CSS and JavaScript by default, and triggered by a link. 
	 *
	 * An additional hidden field determines if showing the fields has been 
	 * triggered and just validates/saves the input in this case.
	 *
	 * This behaviour works unobtrusively, without JavaScript enabled
	 * the fields show, validate and save by default.
	 * 
	 * @param boolean $showOnClick
	 */
	protected $showOnClick = false;


	/**
	 * A place to temporarly store the confirm password value
	 * @var string
	 */
	protected $confirmValue;
	
	/**
	 * Title for the link that triggers the visibility of password fields.
	 *
	 * @var string
	 */
	public $showOnClickTitle;
	
	/**
	 * Child fields (_Password, _ConfirmPassword)
	 * 
	 * @var FieldList
	 */
	public $children;
	
	/**
	 * @param string $name
	 * @param string $title
	 * @param mixed $value
	 * @param Form $form
	 * @param boolean $showOnClick
	 * @param string $titleConfirmField Alternate title (not localizeable)
	 */
	public function __construct($name, $title = null, $value = "", $form = null, $showOnClick = false,
			$titleConfirmField = null) {

		// naming with underscores to prevent values from actually being saved somewhere
		$this->children = new FieldList(
			new PasswordField(
				"{$name}[_Password]", 
				(isset($title)) ? $title : _t('Member.PASSWORD', 'Password')
			),
			new PasswordField(
				"{$name}[_ConfirmPassword]",
				(isset($titleConfirmField)) ? $titleConfirmField : _t('Member.CONFIRMPASSWORD', 'Confirm Password')
			)
		);
		
		// has to be called in constructor because Field() isn't triggered upon saving the instance
		if($showOnClick) {
			$this->children->push(new HiddenField("{$name}[_PasswordFieldVisible]"));
		}

		// disable auto complete
		foreach($this->children as $child) {
			$child->setAttribute('autocomplete', 'off');
		}

		$this->showOnClick = $showOnClick;
		
		// we have labels for the subfields
		$title = false;
		
		parent::__construct($name, $title, null, $form);
		$this->setValue($value);
	}
	
	/**
	 * @param array $properties
	 *
	 * @return string
	 */
	public function Field($properties = array()) {
		Requirements::javascript(FRAMEWORK_DIR . '/thirdparty/jquery/jquery.js');
		Requirements::javascript(FRAMEWORK_DIR . '/javascript/ConfirmedPasswordField.js');
		Requirements::css(FRAMEWORK_DIR . '/css/ConfirmedPasswordField.css');
		
		$content = '';
		
		if($this->showOnClick) {
			if($this->showOnClickTitle) {
				$title = $this->showOnClickTitle;
			} else {
				$title = _t(
					'ConfirmedPasswordField.SHOWONCLICKTITLE', 
					'Change Password', 
					
					'Label of the link which triggers display of the "change password" formfields'
				);
			}
			
			$content .= "<div class=\"showOnClick\">\n";
			$content .= "<a href=\"#\">{$title}</a>\n";
			$content .= "<div class=\"showOnClickContainer\">";
		}

		foreach($this->children as $field) {
			$field->setDisabled($this->isDisabled()); 
			$field->setReadonly($this->isReadonly());

			if(count($this->attributes)) {
				foreach($this->attributes as $name => $value) {
					$field->setAttribute($name, $value);
				}
			}

			$content .= $field->FieldHolder();
		}

		if($this->showOnClick) {
			$content .= "</div>\n";
			$content .= "</div>\n";
		}
		
		return $content;
	}
	
	/**
	 * Can be empty is a flag that turns on / off empty field checking.
	 *
	 * For example, set this to false (the default) when creating a user account,
	 * and true when displaying on an edit form.
	 *
	 * @param boolean $value
	 * 
	 * @return ConfirmedPasswordField
	 */
	public function setCanBeEmpty($value) {
		$this->canBeEmpty = (bool)$value;

		return $this;
	}
	
	/**
	 * The title on the link which triggers display of the "password" and 
	 * "confirm password" formfields. Only used if {@link setShowOnClick()} 
	 * is set to TRUE.
	 * 
	 * @param string $title
	 *
	 * @return ConfirmedPasswordField
	 */
	public function setShowOnClickTitle($title) {
		$this->showOnClickTitle = $title;

		return $this;
	}
	
	/**
	 * @return string $title
	 */
	public function getShowOnClickTitle() {
		return $this->showOnClickTitle;
	}
	
	/**
	 * @param string $title
	 *
	 * @return ConfirmedPasswordField
	 */
	public function setRightTitle($title) {
		foreach($this->children as $field) {
			$field->setRightTitle($title);
		}

		return $this;
	}
	
	/**
	 * @param array $titles 2 entry array with the customized title for each 
	 *						of the 2 children.
	 *
	 * @return ConfirmedPasswordField
	 */
	public function setChildrenTitles($titles) {
		if(is_array($titles) && count($titles) == 2) {
			foreach($this->children as $field) {
				if(isset($titles[0])) {
					$field->setTitle($titles[0]);

					array_shift($titles);		
				}
			}
		}

		return $this;
	}
	
	/**
	 * Value is sometimes an array, and sometimes a single value, so we need 
	 * to handle both cases.
	 *
	 * @param mixed $value
	 *
	 * @return ConfirmedPasswordField
	 */
	public function setValue($value, $data = null) {
		// If $data is a DataObject, don't use the value, since it's a hashed value
		if ($data && $data instanceof DataObject) $value = '';

		//store this for later
		$oldValue = $this->value;

		if(is_array($value)) {
			$this->value = $value['_Password'];
			$this->confirmValue = $value['_ConfirmPassword'];

			if($this->showOnClick && isset($value['_PasswordFieldVisible'])) {
				$this->children->fieldByName($this->getName() . '[_PasswordFieldVisible]')
					->setValue($value['_PasswordFieldVisible']);
			}
		} else {
			if($value || (!$value && $this->canBeEmpty)) {
				$this->value = $value;
			}
		}

		//looking up field by name is expensive, so lets check it needs to change
		if ($oldValue != $this->value) {
			$this->children->fieldByName($this->getName() . '[_Password]')
				->setValue($this->value);

			$this->children->fieldByName($this->getName() . '[_ConfirmPassword]')
				->setValue($this->value);
		}

		return $this;
	}

	/**
	 * Update the names of the child fields when updating name of field.
	 * 
	 * @param string $name new name to give to the field.
	 */
	public function setName($name) {
		$this->children->fieldByName($this->getName() . '[_Password]')
				->setName($name . '[_Password]');
		$this->children->fieldByName($this->getName() . '[_ConfirmPassword]')
				->setName($name . '[_ConfirmPassword]');

		return parent::setName($name);
	}

	/**
	 * Determines if the field was actually shown on the client side - if not, 
	 * we don't validate or save it.
	 * 
	 * @return boolean
	 */
	public function isSaveable() {
		$isVisible = $this->children->fieldByName($this->getName() . '[_PasswordFieldVisible]');

		return (!$this->showOnClick || ($this->showOnClick && $isVisible && $isVisible->Value()));
	}
	
	/**
	 * @param Validator $validator
	 *
	 * @return boolean
	 */
	public function validate($validator) {
		$name = $this->name;
		
		// if field isn't visible, don't validate
		if(!$this->isSaveable()) {
			return true;
		}
		
		$passwordField = $this->children->fieldByName($name.'[_Password]');
		$passwordConfirmField = $this->children->fieldByName($name.'[_ConfirmPassword]');
		$passwordField->setValue($this->value);
		$passwordConfirmField->setValue($this->confirmValue);

		$value = $passwordField->Value();
		
		// both password-fields should be the same
		if($value != $passwordConfirmField->Value()) {
			$validator->validationError(
				$name, 
				_t('Form.VALIDATIONPASSWORDSDONTMATCH',"Passwords don't match"),
				"validation", 
				false
			);

			return false;
		}

		if(!$this->canBeEmpty) {
			// both password-fields shouldn't be empty
			if(!$value || !$passwordConfirmField->Value()) {
				$validator->validationError(
					$name, 
					_t('Form.VALIDATIONPASSWORDSNOTEMPTY', "Passwords can't be empty"),
					"validation", 
					false
				);

				return false;
			}
		}
			
		// lengths
		if(($this->minLength || $this->maxLength)) {
			if($this->minLength && $this->maxLength) {
				$limit = "{{$this->minLength},{$this->maxLength}}";
				$errorMsg = _t(
					'ConfirmedPasswordField.BETWEEN', 
					'Passwords must be {min} to {max} characters long.', 
					array('min' => $this->minLength, 'max' => $this->maxLength)
				);
			} elseif($this->minLength) {
				$limit = "{{$this->minLength}}.*";
				$errorMsg = _t(
					'ConfirmedPasswordField.ATLEAST', 
					'Passwords must be at least {min} characters long.', 
					array('min' => $this->minLength)
				);
			} elseif($this->maxLength) {
				$limit = "{0,{$this->maxLength}}";
				$errorMsg = _t(
					'ConfirmedPasswordField.MAXIMUM', 
					'Passwords must be at most {max} characters long.', 
					array('max' => $this->maxLength)
				);
			}
			$limitRegex = '/^.' . $limit . '$/';
			if(!empty($value) && !preg_match($limitRegex,$value)) {
				$validator->validationError(
					$name,
					$errorMsg,
					"validation", 
					false
				);
			}
		}
		
		if($this->requireStrongPassword) {
			if(!preg_match('/^(([a-zA-Z]+\d+)|(\d+[a-zA-Z]+))[a-zA-Z0-9]*$/',$value)) {
				$validator->validationError(
					$name,
					_t('Form.VALIDATIONSTRONGPASSWORD',
						"Passwords must have at least one digit and one alphanumeric character"), 
					"validation", 
					false
				);

				return false;
			}
		}

		return true;
	}
	
	/**
	 * Only save if field was shown on the client, and is not empty.
	 *
	 * @param DataObjectInterface $record
	 *
	 * @return boolean
	 */
	public function saveInto(DataObjectInterface $record) {
		if(!$this->isSaveable()) {
			return false;
		}
		
		if(!($this->canBeEmpty && !$this->value)) {
			parent::saveInto($record);
		}
	}
	
	/**
	 * Makes a read only field with some stars in it to replace the password
	 *
	 * @return ReadonlyField
	 */
	public function performReadonlyTransformation() {
		$field = $this->castedCopy('ReadonlyField')
			->setTitle($this->title ? $this->title : _t('Member.PASSWORD'))
			->setValue('*****');

		return $field;
	}
}