<?php

/**
 * THIS SOFTWARE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED
 * WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
 *
 * @package clearFusionCMS
 * @copyright Copyright (c) 2012 - 2016 clearFusionCMS. All rights reserved.
 * @link http://clearfusioncms.com
 */

/**
 * cfBackendMyprofileAction Class
 *
 * Manager user profile update action class.
 *
 * @package clearFusionCMS
 */
class cfBackendMyprofileAction extends cfBackendControllerAction {

	/**
	 * User profile management page.
	 */
	function process() {
		$this->breadcrumbTrail->addCrumb(__('My Profile', 'cfBackend'), $this->assemble('', 'myprofile'));

		$msg = $this->session->flashGet('cfManagerOpSuccess', '');
		$form = new flForm($this->request, 'profileform', $this->assemble('', 'myprofile'), true);

		$profile = new cfUserProfile($this->db, $this->user, cfUserProfile::USEREDITINMGR, 0, true, false, true);

		// WYSIWYG Editor
		$cfg = clearFusionCMS::getSiteConfig('cfSystemCtntEdit');

		$mm = new flModuleMgr($this->db);
		$modules = $mm->getInstalled('WYSIWYG');
		$el = array('' => __('[no editor]', 'cfBackend'));
		$ced = array('' => __('[no editor]', 'cfBackend'));
		foreach($modules as $name => $ver) {
			if($info = $mm->getInfo($name)) {
				$el[$name] = $info->name . ($cfg->editor == $name ? __(' [Default]', 'cfBackend') : '');
				$ced[$name] = $info->name . ($cfg->get('codeEditor', '') == $name ? __(' [Default]', 'cfBackend') : '');
			}
		}

		$editor = new flFormElementSelect($form, 'editor', $this->managerSession->get('editor', $cfg->editor), $el);
		$editor->setLabel(__('WYSIWYG Editor', 'cfBackend'));

		$codeEditor = new flFormElementSelect($form, 'codeEditor', $this->managerSession->get('codeEditor', $cfg->get('codeEditor', '')), $ced);
		$codeEditor->setLabel(__('Code Editor', 'cfBackend'));

		$panel = new flFormElementPane($form, 'editorinfo', $this->alertMessage('Info', __('Selecting a different editor here will override the system setting for the life of this session.', 'cfBackend')));

		$form->groupElements('editorgrp', array($editor, $codeEditor, $panel))
			->setGroupLabel('editorgrp', __('Editor for This Session', 'cfBackend'));

		$secCfg = new flConfigDb('cfSystemSecurity', $this->db);
		if($secCfg->get('twoFactor', false)) {
			$secret = $this->user->getAuthKey();
			if(empty($secret)) {
				$enable2fa = new flFormElementSubmit($form, 'enable2fa');
				$enable2fa->setCaption(__('Enable', 'cfBackend'))->setCSS('primary');

				$form->groupElements('twofa', array($enable2fa))
					->setGroupLabel('twofa', __('Two Factor Authentication', 'cfBackend'));
			} else {
				$tfaName = new flFormElementText($form, 'twofaname', $secCfg->get('twoFactorName', clearFusionCMS::getSiteName()));
				$tfaName->setLabel(__('Key Name', 'cfBackend'))
					->setDisabled(true)
					->setReadonly(true);

				$tfaSecret = new flFormElementText($form, 'twofasecret', $secret);
				$tfaSecret->setLabel(__('Secret Key', 'cfBackend'))
					->setDisabled(true)
					->setReadonly(true);

				$qr = new flFormElementPane($form, 'twofaqr', '<img src="' . flAuthTOTP::getQRCode($secCfg->get('twoFactorName', clearFusionCMS::getSiteName()), $secret, 200) . '" alt="QR" class="qrcode2fa" />');

				$disable2fa = new flFormElementSubmit($form, 'disable2fa');
				$disable2fa->setCaption(__('Disable', 'cfBackend'))->setCSS('primary');

				$regen2fa = new flFormElementSubmit($form, 'regen2fa');
				$regen2fa->setCaption(__('Regenerate Secret Key', 'cfBackend'))->setCSS('primary');

				$form->groupElements('twofa', array($tfaName, $tfaSecret, $qr, $disable2fa, $regen2fa))
					->setGroupLabel('twofa', __('Two Factor Authentication', 'cfBackend'));
			}
		}

		$profile->process($form);

		if($form->isSubmitted() && $form->isValid() && !$form->isInvalidated()) {

			$uMgr = clearFusionCMS::getUserMgr();

			// If enabling 2fa
			if((isset($enable2fa) && $enable2fa->getValue()) || (isset($regen2fa) && $regen2fa->getValue()))
				$uMgr->setAuthKey($this->user->getId(), flAuthTOTP::generateSecret());
			else if(isset($disable2fa) && $disable2fa->getValue())
				$uMgr->setAuthKey($this->user->getId(), '');

			if($editor->getValue() == $cfg->editor)
				unset($this->managerSession->editor);
			else
				$this->managerSession->editor = $editor->getValue();

			if($codeEditor->getValue() == $cfg->get('codeEditor', ''))
				unset($this->managerSession->codeEditor);
			else
				$this->managerSession->codeEditor = $codeEditor->getValue();

			$msg = $this->alertMessage('Success', __('Your profile has been updated.', 'cfBackend'));

			if((isset($enable2fa) && $enable2fa->getValue()) ||
				(isset($disable2fa) && $disable2fa->getValue()) ||
				(isset($regen2fa) && $regen2fa->getValue())
			) {
				$this->session->flashSet('cfManagerOpSuccess', $msg);
				$this->response->redirectTo($this->request->getSelf(true));
			}
		}

		// Force other computers to logout
		$formForce = new flForm($this->request, 'forceform', $this->assemble('', 'myprofile'), true);
		$formForce->setGroupLabel(null, __('Logout', 'cfBackend'));

		$logoutOthers = new flFormElementSubmit($formForce, 'logoutothers');
		$logoutOthers->setCaption(__('Logout Other Computers', 'cfBackend'))->setCSS('danger')
			->setDescription(__('Force other computers that you may be logged in on to be logged out.', 'cfBackend'));

		if($formForce->isSubmitted() && $formForce->isValid()) {
			$this->user->regenerateAuth();
			$msg = $this->alertMessage('Success', __('All other computers have been logged out of your account.', 'cfBackend'));
		}

		$this->renderPage(__('My Profile', 'cfBackend'),
			$this->renderBlock(__('Update Your User Profile', 'cfBackend'),
				$form->render($this->tpl->getCodeBuffer()) . $formForce->render($this->tpl->getCodeBuffer()),
				__('Complete the form below to update your user profile. Leave the password fields blank to leave your password unchanged.', 'cfBackend'), $msg));
	}
}
