<?php

/**
 * Class file for user management action.
 *
 * 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
 */

/**
 * cfBackendListusersAction Class
 *
 * Action class to list and search for users in the system.
 *
 * @package clearFusionCMS
 */
class cfBackendListusersAction extends cfBackendControllerAction {
	/**
	 * Process the action.
	 */
	function process() {
		$this->testPermission('core.users');
		$this->breadcrumbTrail->addCrumb(__('Users', 'cfBackend'), $this->assemble('', 'listusers'));

		$content = '';

		// Get the page that we're currently on
		$onPage = $this->request->getParam('*');
		if($onPage !== null && count($onPage) == 1 && preg_match('/^\d+$/', $onPage[0]))
			$onPage = $onPage[0];
		else
			$onPage = 0;

		$data = $this->session->flashGet('cfManager.user.search');
		$this->session->flashKeep('cfManager.user.search');

		// Build the search form
		$form = new flForm($this->request, 'searchform', $this->assemble('', 'listusers'), true);

		$searchfor = new flFormElementText($form, 'searchfor', $data === null ? null : $data['for']);
		$searchfor->setLabel(__('Search For', 'cfBackend'));

		$searchin = new flFormElementChecklist($form, 'searchin', $data === null ? array('username', 'email') : $data['in'], array(
			'username' => __('Username', 'cfBackend'),
			'email' => __('Email', 'cfBackend')));
		$searchin->setLabel(__('Search In', 'cfBackend'))
				->addValidator(new flFormValidatorMinChecklist(1));

		$ac = new flAcMgr($this->db);
		$roleLim = new flFormElementSelect($form, 'rolelim', $data === null ? '' : $data['rolelim'], array(0 => __('[All Roles]', 'cfBackend')) + $ac->getRoles());
		$roleLim->setLabel(__('Limit to Role', 'cfBackend'));

		$exact = new flFormElementCheckbox($form, 'exact', $data === null ? 0 : $data['exact']);
		$exact->setLabel(__('Exact Match', 'cfBackend'));

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

		$form->focusElement($searchfor);

		$userMgr = clearFusionCMS::getUserMgr();

		if($form->isSubmitted() && $form->isValid()) {
			$this->session->flashSet('cfManager.user.search', $data = array(
				'for' => $searchfor->getValue(),
				'in' => $searchin->getValue(),
				'exact' => $exact->getValue(),
				'rolelim' => $roleLim->getValue()));
			$onPage = 0;
		}

		$pagination = null;
		if($data !== null) {
			$pagination = new flWidgetPagination($onPage,
						$found = $userMgr->numFindMatches($data['for'], $data['in'], $data['exact'], $data['rolelim']));
			$pagination->setRoute($this->router->getRoute('cfManager'), array('action' => 'listusers'), '*');
			$results = $userMgr->find($data['for'], $data['in'], $data['exact'], $pagination->getStart(), $pagination->getRows(), $data['rolelim']);

			if(count($results)) {
				$table = new flWidgetTable();
				$table->setClass('tablewidget bordered striped rowhover responsive')
					->setHeadings('', __('Status', 'cfBackend'), __('Roles', 'cfBackend'), __('Operation', 'cfBackend'))
					->setColData('ue', 'state', 'roles', 'ops')
					->skipEncode('ue', 'roles', 'ops', 'state');

				foreach($results as $uid) {
					$i = $userMgr->getInfo($uid);

					$i['state'] = $userMgr->getState($uid);

					if($i['username'] == md5($uid . '__fusionLib.User__'))
						$i['username'] = '';

					$i['ue'] = '<strong>' . __('Username', 'cfBackend') . '</strong>: ' . $i['username'] . '<br />';
					$i['ue'] .= '<strong>' . __('Email', 'cfBackend') . '</strong>: ' . $i['email'];

					if($i['service'] != 'internal')
						$i['state'] .= '<br /><strong>' . $i['service'] . '</strong>';

					$roles = $userMgr->getUserRoles($uid);
					if(count($roles))
						$i['roles'] = join(', ', $roles);

					$i['ops'] = "<a href=\"" . $this->assemble('', 'edituser', array('*' => $uid)) . "\">" . __('Edit', 'cfBackend') . "</a>";

					$table->addRow($i);
				}

				$content = $table->render();
			}

			$content .= '<p>' . sprintf(__('Found: %d users', 'cfBackend'), $found) . '</p>';
		}

		// Build floating action menu
		$fam = new flWidgetFloatingActionMenu();
		$fam->setCSS('[[+css]]');

		if($this->user->hasPermission('core.usersadd'))
			$fam->addAction('person_add', __('Add User', 'cfBackend'), $this->assemble('', 'adduser'));
		$fam->addAction('lock_open', __('Clear IP Blocks', 'cfBackend'), $this->assemble('', 'clearipblocks'));

		$this->tpl->registerChunk('fam', $fam->render());

		$this->renderPage(__('Users', 'cfBackend'),
			empty($content) ? '' : $this->renderBlock(__('Users', 'cfBackend'), $content, '', '', $pagination->render()),
			$this->renderBlock('', $form->render($this->tpl->getCodeBuffer())));
	}
}
