PSR2 compliance for PHPCI/Controller - Issue #18

This commit is contained in:
Dan Cryer 2013-05-16 15:25:39 +01:00
parent 65f93555be
commit e4a6e224c4
7 changed files with 558 additions and 580 deletions

View file

@ -8,9 +8,10 @@
*/
namespace PHPCI\Controller;
use b8,
b8\Store,
PHPCI\Model\Build;
use b8;
use b8\Store;
use PHPCI\Model\Build;
/**
* BitBucket Controller - Processes webhook pings from BitBucket.
@ -20,45 +21,39 @@ use b8,
*/
class BitbucketController extends b8\Controller
{
public function init()
{
$this->_buildStore = Store\Factory::getStore('Build');
}
public function init()
{
$this->_buildStore = Store\Factory::getStore('Build');
}
public function webhook($project)
{
$payload = json_decode($this->getParam('payload'), true);
$branches = array();
$commits = array();
public function webhook($project)
{
$payload = json_decode($this->getParam('payload'), true);
$branches = array();
$commits = array();
foreach($payload['commits'] as $commit)
{
if(!in_array($commit['branch'], $branches))
{
$branches[] = $commit['branch'];
$commits[$commit['branch']] = $commit['raw_node'];
}
}
foreach ($payload['commits'] as $commit) {
if (!in_array($commit['branch'], $branches)) {
$branches[] = $commit['branch'];
$commits[$commit['branch']] = $commit['raw_node'];
}
}
foreach($branches as $branch)
{
try
{
foreach ($branches as $branch) {
try {
$build = new Build();
$build->setProjectId($project);
$build->setCommitId($commits[$branch]);
$build->setStatus(0);
$build->setLog('');
$build->setCreated(new \DateTime());
$build->setBranch($branch);
$this->_buildStore->save($build);
}
catch(\Exception $ex)
{
}
}
die('OK');
}
}
$build = new Build();
$build->setProjectId($project);
$build->setCommitId($commits[$branch]);
$build->setStatus(0);
$build->setLog('');
$build->setCreated(new \DateTime());
$build->setBranch($branch);
$this->_buildStore->save($build);
} catch (\Exception $ex) {
}
}
die('OK');
}
}

View file

@ -8,9 +8,10 @@
*/
namespace PHPCI\Controller;
use b8,
b8\Registry,
PHPCI\Model\Build;
use b8;
use b8\Registry;
use PHPCI\Model\Build;
/**
* Build Controller - Allows users to run and view builds.
@ -20,77 +21,76 @@ use b8,
*/
class BuildController extends b8\Controller
{
public function init()
{
$this->_buildStore = b8\Store\Factory::getStore('Build');
}
public function init()
{
$this->_buildStore = b8\Store\Factory::getStore('Build');
}
public function view($buildId)
{
$build = $this->_buildStore->getById($buildId);
public function view($buildId)
{
$build = $this->_buildStore->getById($buildId);
$view = new b8\View('Build');
$view->build = $build;
$view->data = $this->getBuildData($buildId);
$view = new b8\View('Build');
$view->build = $build;
$view->data = $this->getBuildData($buildId);
return $view->render();
}
return $view->render();
}
public function data($buildId)
{
die($this->getBuildData($buildId));
}
public function data($buildId)
{
die($this->getBuildData($buildId));
}
protected function getBuildData($buildId)
{
$build = $this->_buildStore->getById($buildId);
protected function getBuildData($buildId)
{
$build = $this->_buildStore->getById($buildId);
$data = array();
$data['status'] = (int)$build->getStatus();
$data['log'] = $this->cleanLog($build->getLog());
$data['plugins'] = json_decode($build->getPlugins(), true);
$data['created'] = !is_null($build->getCreated()) ? $build->getCreated()->format('Y-m-d H:i:s') : null;
$data['started'] = !is_null($build->getStarted()) ? $build->getStarted()->format('Y-m-d H:i:s') : null;
$data['finished'] = !is_null($build->getFinished()) ? $build->getFinished()->format('Y-m-d H:i:s') : null;
$data = array();
$data['status'] = (int)$build->getStatus();
$data['log'] = $this->cleanLog($build->getLog());
$data['plugins'] = json_decode($build->getPlugins(), true);
$data['created'] = !is_null($build->getCreated()) ? $build->getCreated()->format('Y-m-d H:i:s') : null;
$data['started'] = !is_null($build->getStarted()) ? $build->getStarted()->format('Y-m-d H:i:s') : null;
$data['finished'] = !is_null($build->getFinished()) ? $build->getFinished()->format('Y-m-d H:i:s') : null;
return json_encode($data);
}
return json_encode($data);
}
public function rebuild($buildId)
{
$copy = $this->_buildStore->getById($buildId);
public function rebuild($buildId)
{
$copy = $this->_buildStore->getById($buildId);
$build = new Build();
$build->setProjectId($copy->getProjectId());
$build->setCommitId($copy->getCommitId());
$build->setStatus(0);
$build->setBranch($copy->getBranch());
$build->setCreated(new \DateTime());
$build = new Build();
$build->setProjectId($copy->getProjectId());
$build->setCommitId($copy->getCommitId());
$build->setStatus(0);
$build->setBranch($copy->getBranch());
$build->setCreated(new \DateTime());
$build = $this->_buildStore->save($build);
$build = $this->_buildStore->save($build);
header('Location: /build/view/' . $build->getId());
}
header('Location: /build/view/' . $build->getId());
}
public function delete($buildId)
{
if(!Registry::getInstance()->get('user')->getIsAdmin())
{
throw new \Exception('You do not have permission to do that.');
}
$build = $this->_buildStore->getById($buildId);
$this->_buildStore->delete($build);
public function delete($buildId)
{
if (!Registry::getInstance()->get('user')->getIsAdmin()) {
throw new \Exception('You do not have permission to do that.');
}
$build = $this->_buildStore->getById($buildId);
$this->_buildStore->delete($build);
header('Location: /project/view/' . $build->getProjectId());
}
header('Location: /project/view/' . $build->getProjectId());
}
protected function cleanLog($log)
{
$log = str_replace('[0;32m', '<span style="color: green">', $log);
$log = str_replace('[0;31m', '<span style="color: red">', $log);
$log = str_replace('[0m', '</span>', $log);
protected function cleanLog($log)
{
$log = str_replace('[0;32m', '<span style="color: green">', $log);
$log = str_replace('[0;31m', '<span style="color: red">', $log);
$log = str_replace('[0m', '</span>', $log);
return $log;
}
}
return $log;
}
}

View file

@ -8,9 +8,10 @@
*/
namespace PHPCI\Controller;
use b8,
b8\Store,
PHPCI\Model\Build;
use b8;
use b8\Store;
use PHPCI\Model\Build;
/**
* Github Controller - Processes webhook pings from Github.
@ -20,44 +21,38 @@ use b8,
*/
class GithubController extends b8\Controller
{
public function init()
{
$this->_buildStore = Store\Factory::getStore('Build');
}
public function init()
{
$this->_buildStore = Store\Factory::getStore('Build');
}
public function webhook($project)
{
$payload = json_decode($this->getParam('payload'), true);
public function webhook($project)
{
$payload = json_decode($this->getParam('payload'), true);
try
{
$build = new Build();
$build->setProjectId($project);
$build->setCommitId($payload['after']);
$build->setStatus(0);
$build->setLog('');
$build->setCreated(new \DateTime());
$build->setBranch(str_replace('refs/heads/', '', $payload['ref']));
}
catch(\Exception $ex)
{
header('HTTP/1.1 400 Bad Request');
header('Ex: ' . $ex->getMessage());
die('FAIL');
}
try {
$build = new Build();
$build->setProjectId($project);
$build->setCommitId($payload['after']);
$build->setStatus(0);
$build->setLog('');
$build->setCreated(new \DateTime());
$build->setBranch(str_replace('refs/heads/', '', $payload['ref']));
} catch (\Exception $ex) {
header('HTTP/1.1 400 Bad Request');
header('Ex: ' . $ex->getMessage());
die('FAIL');
}
try
{
$build = $this->_buildStore->save($build);
$build->sendStatusPostback();
}
catch(\Exception $ex)
{
header('HTTP/1.1 500 Internal Server Error');
header('Ex: ' . $ex->getMessage());
die('FAIL');
}
die('OK');
}
}
try {
$build = $this->_buildStore->save($build);
$build->sendStatusPostback();
} catch (\Exception $ex) {
header('HTTP/1.1 500 Internal Server Error');
header('Ex: ' . $ex->getMessage());
die('FAIL');
}
die('OK');
}
}

View file

@ -8,6 +8,7 @@
*/
namespace PHPCI\Controller;
use b8;
/**
@ -18,33 +19,33 @@ use b8;
*/
class IndexController extends b8\Controller
{
public function init()
{
$this->_buildStore = b8\Store\Factory::getStore('Build');
$this->_projectStore = b8\Store\Factory::getStore('Project');
}
public function init()
{
$this->_buildStore = b8\Store\Factory::getStore('Build');
$this->_projectStore = b8\Store\Factory::getStore('Project');
}
public function index()
{
$projects = $this->_projectStore->getWhere(array(), 50, 0, array(), array('title' => 'ASC'));
$view = new b8\View('Index');
$view->builds = $this->getLatestBuildsHtml();
$view->projects = $projects['items'];
public function index()
{
$projects = $this->_projectStore->getWhere(array(), 50, 0, array(), array('title' => 'ASC'));
$view = new b8\View('Index');
$view->builds = $this->getLatestBuildsHtml();
$view->projects = $projects['items'];
return $view->render();
}
return $view->render();
}
public function latest()
{
die($this->getLatestBuildsHtml());
}
public function latest()
{
die($this->getLatestBuildsHtml());
}
protected function getLatestBuildsHtml()
{
$builds = $this->_buildStore->getWhere(array(), 10, 0, array(), array('id' => 'DESC'));
$view = new b8\View('BuildsTable');
$view->builds = $builds['items'];
protected function getLatestBuildsHtml()
{
$builds = $this->_buildStore->getWhere(array(), 10, 0, array(), array('id' => 'DESC'));
$view = new b8\View('BuildsTable');
$view->builds = $builds['items'];
return $view->render();
}
}
return $view->render();
}
}

View file

@ -8,11 +8,12 @@
*/
namespace PHPCI\Controller;
use b8,
PHPCI\Model\Build,
PHPCI\Model\Project,
b8\Form,
b8\Registry;
use b8;
use PHPCI\Model\Build;
use PHPCI\Model\Project;
use b8\Form;
use b8\Registry;
/**
* Project Controller - Allows users to create, edit and view projects.
@ -22,283 +23,280 @@ use b8,
*/
class ProjectController extends b8\Controller
{
public function init()
{
$this->_buildStore = b8\Store\Factory::getStore('Build');
$this->_projectStore = b8\Store\Factory::getStore('Project');
}
public function init()
{
$this->_buildStore = b8\Store\Factory::getStore('Build');
$this->_projectStore = b8\Store\Factory::getStore('Project');
}
public function view($projectId)
{
$project = $this->_projectStore->getById($projectId);
$page = $this->getParam('p', 1);
$builds = $this->getLatestBuildsHtml($projectId, (($page - 1) * 10));
public function view($projectId)
{
$project = $this->_projectStore->getById($projectId);
$page = $this->getParam('p', 1);
$builds = $this->getLatestBuildsHtml($projectId, (($page - 1) * 10));
$view = new b8\View('Project');
$view->builds = $builds[0];
$view->total = $builds[1];
$view->project = $project;
$view->page = $page;
$view = new b8\View('Project');
$view->builds = $builds[0];
$view->total = $builds[1];
$view->project = $project;
$view->page = $page;
return $view->render();
}
return $view->render();
}
public function build($projectId)
{
$build = new Build();
$build->setProjectId($projectId);
$build->setCommitId('Manual');
$build->setStatus(0);
$build->setBranch('master');
$build->setCreated(new \DateTime());
public function build($projectId)
{
$build = new Build();
$build->setProjectId($projectId);
$build->setCommitId('Manual');
$build->setStatus(0);
$build->setBranch('master');
$build->setCreated(new \DateTime());
$build = $this->_buildStore->save($build);
$build = $this->_buildStore->save($build);
header('Location: /build/view/' . $build->getId());
}
header('Location: /build/view/' . $build->getId());
}
public function delete($id)
{
if(!Registry::getInstance()->get('user')->getIsAdmin())
{
throw new \Exception('You do not have permission to do that.');
}
public function delete($id)
{
if (!Registry::getInstance()->get('user')->getIsAdmin()) {
throw new \Exception('You do not have permission to do that.');
}
$project = $this->_projectStore->getById($id);
$this->_projectStore->delete($project);
$project = $this->_projectStore->getById($id);
$this->_projectStore->delete($project);
header('Location: /');
}
header('Location: /');
}
public function builds($projectId)
{
$builds = $this->getLatestBuildsHtml($projectId);
die($builds[0]);
}
public function builds($projectId)
{
$builds = $this->getLatestBuildsHtml($projectId);
die($builds[0]);
}
protected function getLatestBuildsHtml($projectId, $start = 0)
{
$builds = $this->_buildStore->getWhere(array('project_id' => $projectId), 10, $start, array(), array('id' => 'DESC'));
$view = new b8\View('BuildsTable');
$view->builds = $builds['items'];
protected function getLatestBuildsHtml($projectId, $start = 0)
{
$criteria = array('project_id' => $projectId), 10, $start, array(), array('id' => 'DESC');
$builds = $this->_buildStore->getWhere($criteria);
$view = new b8\View('BuildsTable');
$view->builds = $builds['items'];
return array($view->render(), $builds['count']);
}
return array($view->render(), $builds['count']);
}
public function add()
{
if(!Registry::getInstance()->get('user')->getIsAdmin())
{
throw new \Exception('You do not have permission to do that.');
}
public function add()
{
if (!Registry::getInstance()->get('user')->getIsAdmin()) {
throw new \Exception('You do not have permission to do that.');
}
$method = Registry::getInstance()->get('requestMethod');
$method = Registry::getInstance()->get('requestMethod');
if($method == 'POST')
{
$values = $this->getParams();
$pub = null;
}
else
{
$tempPath = sys_get_temp_dir() . '/';
if ($method == 'POST') {
$values = $this->getParams();
$pub = null;
} else {
$tempPath = sys_get_temp_dir() . '/';
// FastCGI fix for Windows machines, where temp path is not available to
// PHP, and defaults to the unwritable system directory. If the temp
// path is pointing to the system directory, shift to the 'TEMP'
// sub-folder, which should also exist, but actually be writable.
if ($tempPath == getenv("SystemRoot") . '/') {
$tempPath = getenv("SystemRoot") . '/TEMP/';
}
// FastCGI fix for Windows machines, where temp path is not available to
// PHP, and defaults to the unwritable system directory. If the temp
// path is pointing to the system directory, shift to the 'TEMP'
// sub-folder, which should also exist, but actually be writable.
if ($tempPath == getenv("SystemRoot") . '/') {
$tempPath = getenv("SystemRoot") . '/TEMP/';
}
$id = $tempPath . md5(microtime(true));
if (!is_dir($tempPath)) {
mkdir($tempPath);
}
shell_exec('ssh-keygen -q -t rsa -b 2048 -f '.$id.' -N "" -C "deploy@phpci"');
$id = $tempPath . md5(microtime(true));
$pub = file_get_contents($id . '.pub');
$prv = file_get_contents($id);
if (!is_dir($tempPath)) {
mkdir($tempPath);
}
$values = array('key' => $prv, 'pubkey' => $pub, 'token' => $_SESSION['github_token']);
}
shell_exec('ssh-keygen -q -t rsa -b 2048 -f '.$id.' -N "" -C "deploy@phpci"');
$form = $this->projectForm($values);
$pub = file_get_contents($id . '.pub');
$prv = file_get_contents($id);
if($method != 'POST' || ($method == 'POST' && !$form->validate()))
{
$gh = \b8\Registry::getInstance()->get('github_app');
$code = $this->getParam('code', null);
$values = array('key' => $prv, 'pubkey' => $pub, 'token' => $_SESSION['github_token']);
}
if(!is_null($code))
{
$http = new \b8\HttpClient();
$resp = $http->post('https://github.com/login/oauth/access_token', array('client_id' => $gh['id'], 'client_secret' => $gh['secret'], 'code' => $code));
if($resp['success'])
{
parse_str($resp['body'], $resp);
$_SESSION['github_token'] = $resp['access_token'];
header('Location: /project/add');
die;
}
}
$form = $this->projectForm($values);
$view = new b8\View('ProjectForm');
$view->type = 'add';
$view->project = null;
$view->form = $form;
$view->key = $pub;
$view->token = $_SESSION['github_token'] ? $_SESSION['github_token'] : null;
if ($method != 'POST' || ($method == 'POST' && !$form->validate())) {
$gh = \b8\Registry::getInstance()->get('github_app');
$code = $this->getParam('code', null);
return $view->render();
}
if (!is_null($code)) {
$http = new \b8\HttpClient();
$url = 'https://github.com/login/oauth/access_token';
$params = array('client_id' => $gh['id'], 'client_secret' => $gh['secret'], 'code' => $code)
$resp = $http->post($url, $params);
if ($resp['success']) {
parse_str($resp['body'], $resp);
$_SESSION['github_token'] = $resp['access_token'];
header('Location: /project/add');
die;
}
}
$values = $form->getValues();
$values['git_key'] = $values['key'];
$view = new b8\View('ProjectForm');
$view->type = 'add';
$view->project = null;
$view->form = $form;
$view->key = $pub;
$view->token = $_SESSION['github_token'] ? $_SESSION['github_token'] : null;
$project = new Project();
$project->setValues($values);
return $view->render();
}
$project = $this->_projectStore->save($project);
$values = $form->getValues();
$values['git_key'] = $values['key'];
header('Location: /project/view/' . $project->getId());
die;
}
$project = new Project();
$project->setValues($values);
public function edit($id)
{
if(!Registry::getInstance()->get('user')->getIsAdmin())
{
throw new \Exception('You do not have permission to do that.');
}
$method = Registry::getInstance()->get('requestMethod');
$project = $this->_projectStore->getById($id);
$project = $this->_projectStore->save($project);
if($method == 'POST')
{
$values = $this->getParams();
}
else
{
$values = $project->getDataArray();
$values['key'] = $values['git_key'];
}
header('Location: /project/view/' . $project->getId());
die;
}
$form = $this->projectForm($values, 'edit/' . $id);
public function edit($id)
{
if (!Registry::getInstance()->get('user')->getIsAdmin()) {
throw new \Exception('You do not have permission to do that.');
}
$method = Registry::getInstance()->get('requestMethod');
$project = $this->_projectStore->getById($id);
if($method != 'POST' || ($method == 'POST' && !$form->validate()))
{
$view = new b8\View('ProjectForm');
$view->type = 'edit';
$view->project = $project;
$view->form = $form;
$view->key = null;
if ($method == 'POST') {
$values = $this->getParams();
} else {
$values = $project->getDataArray();
$values['key'] = $values['git_key'];
}
return $view->render();
}
$form = $this->projectForm($values, 'edit/' . $id);
$values = $form->getValues();
$values['git_key'] = $values['key'];
if ($method != 'POST' || ($method == 'POST' && !$form->validate())) {
$view = new b8\View('ProjectForm');
$view->type = 'edit';
$view->project = $project;
$view->form = $form;
$view->key = null;
$project->setValues($values);
$project = $this->_projectStore->save($project);
return $view->render();
}
header('Location: /project/view/' . $project->getId());
die;
}
$values = $form->getValues();
$values['git_key'] = $values['key'];
protected function projectForm($values, $type = 'add')
{
$form = new Form();
$form->setMethod('POST');
$form->setAction('/project/' . $type);
$form->addField(new Form\Element\Csrf('csrf'));
$form->addField(new Form\Element\Hidden('token'));
$form->addField(new Form\Element\Hidden('pubkey'));
$project->setValues($values);
$project = $this->_projectStore->save($project);
$field = new Form\Element\Select('type');
$field->setRequired(true);
$field->setPattern('^(github|bitbucket|local)');
$field->setOptions(array('choose' => 'Select repository type...', 'github' => 'Github', 'bitbucket' => 'Bitbucket', 'local' => 'Local Path'));
$field->setLabel('Where is your project hosted?');
$field->setClass('span4');
$form->addField($field);
header('Location: /project/view/' . $project->getId());
die;
}
if(isset($_SESSION['github_token']))
{
$field = new Form\Element\Select('github');
$field->setLabel('Choose a Github repository:');
$field->setClass('span4');
$field->setOptions($this->getGithubRepositories());
$form->addField($field);
}
protected function projectForm($values, $type = 'add')
{
$form = new Form();
$form->setMethod('POST');
$form->setAction('/project/' . $type);
$form->addField(new Form\Element\Csrf('csrf'));
$form->addField(new Form\Element\Hidden('token'));
$form->addField(new Form\Element\Hidden('pubkey'));
$field = new Form\Element\Text('reference');
$field->setRequired(true);
$field->setValidator(function($val) use ($values)
{
$type = $values['type'];
$options = array(
'choose' => 'Select repository type...',
'github' => 'Github',
'bitbucket' => 'Bitbucket',
'local' => 'Local Path'
);
switch($type) {
case 'local':
if(!is_dir($val)) {
throw new \Exception('The path you specified does not exist.');
}
break;
$field = new Form\Element\Select('type');
$field->setRequired(true);
$field->setPattern('^(github|bitbucket|local)');
$field->setOptions($options);
$field->setLabel('Where is your project hosted?');
$field->setClass('span4');
$form->addField($field);
case 'github':
case 'bitbucket':
if(!preg_match('/^[a-zA-Z0-9_\-]+\/[a-zA-Z0-9_\-]+$/', $val)) {
throw new \Exception('Repository name must be in the format "owner/repo".');
}
break;
}
if (isset($_SESSION['github_token'])) {
$field = new Form\Element\Select('github');
$field->setLabel('Choose a Github repository:');
$field->setClass('span4');
$field->setOptions($this->getGithubRepositories());
$form->addField($field);
}
return true;
});
$field->setLabel('Repository Name / URL (Remote) or Path (Local)');
$field->setClass('span4');
$form->addField($field);
$referenceValidator = function ($val) use ($values) {
$type = $values['type'];
$field = new Form\Element\Text('title');
$field->setRequired(true);
$field->setLabel('Project Title');
$field->setClass('span4');
$form->addField($field);
$field = new Form\Element\TextArea('key');
$field->setRequired(false);
$field->setLabel('Private key to use to access repository (leave blank for local and/or anonymous remotes)');
$field->setClass('span7');
$field->setRows(6);
$form->addField($field);
switch($type) {
case 'local':
if (!is_dir($val)) {
throw new \Exception('The path you specified does not exist.');
}
break;
case 'github':
case 'bitbucket':
if (!preg_match('/^[a-zA-Z0-9_\-]+\/[a-zA-Z0-9_\-]+$/', $val)) {
throw new \Exception('Repository name must be in the format "owner/repo".');
}
break;
}
$field = new Form\Element\Submit();
$field->setValue('Save Project');
$field->setClass('btn-success');
$form->addField($field);
return true;
};
$form->setValues($values);
return $form;
}
$field = new Form\Element\Text('reference');
$field->setRequired(true);
$field->setValidator($referenceValidator);
$field->setLabel('Repository Name / URL (Remote) or Path (Local)');
$field->setClass('span4');
$form->addField($field);
protected function getGithubRepositories()
{
$http = new \b8\HttpClient();
$res = $http->get('https://api.github.com/user/repos', array('type' => 'all', 'access_token' => $_SESSION['github_token']));
$field = new Form\Element\Text('title');
$field->setRequired(true);
$field->setLabel('Project Title');
$field->setClass('span4');
$form->addField($field);
$field = new Form\Element\TextArea('key');
$field->setRequired(false);
$field->setLabel('Private key to use to access repository (leave blank for local and/or anonymous remotes)');
$field->setClass('span7');
$field->setRows(6);
$form->addField($field);
$rtn = array();
$rtn['choose'] = 'Select a repository...';
if($res['success'])
{
foreach($res['body'] as $repo)
{
$rtn[$repo['full_name']] = $repo['full_name'];
}
}
$field = new Form\Element\Submit();
$field->setValue('Save Project');
$field->setClass('btn-success');
$form->addField($field);
return $rtn;
}
}
$form->setValues($values);
return $form;
}
protected function getGithubRepositories()
{
$http = new \b8\HttpClient();
$url = 'https://api.github.com/user/repos';
$res = $http->get($url, array('type' => 'all', 'access_token' => $_SESSION['github_token']));
$rtn = array();
$rtn['choose'] = 'Select a repository...';
if ($res['success']) {
foreach ($res['body'] as $repo) {
$rtn[$repo['full_name']] = $repo['full_name'];
}
}
return $rtn;
}
}

View file

@ -8,6 +8,7 @@
*/
namespace PHPCI\Controller;
use b8;
/**
@ -18,56 +19,54 @@ use b8;
*/
class SessionController extends b8\Controller
{
public function init()
{
$this->_userStore = b8\Store\Factory::getStore('User');
}
public function init()
{
$this->_userStore = b8\Store\Factory::getStore('User');
}
public function login()
{
if(b8\Registry::getInstance()->get('requestMethod') == 'POST')
{
$user = $this->_userStore->getByEmail($this->getParam('email'));
public function login()
{
if (b8\Registry::getInstance()->get('requestMethod') == 'POST') {
$user = $this->_userStore->getByEmail($this->getParam('email'));
if($user && password_verify($this->getParam('password', ''), $user->getHash()))
{
$_SESSION['user_id'] = $user->getId();
header('Location: /');
die;
}
}
if ($user && password_verify($this->getParam('password', ''), $user->getHash())) {
$_SESSION['user_id'] = $user->getId();
header('Location: /');
die;
}
}
$form = new b8\Form();
$form->setMethod('POST');
$form->setAction('/session/login');
$form = new b8\Form();
$form->setMethod('POST');
$form->setAction('/session/login');
$email = new b8\Form\Element\Email('email');
$email->setLabel('Email Address');
$email->setRequired(true);
$email->setClass('span3');
$form->addField($email);
$email = new b8\Form\Element\Email('email');
$email->setLabel('Email Address');
$email->setRequired(true);
$email->setClass('span3');
$form->addField($email);
$pwd = new b8\Form\Element\Password('password');
$pwd->setLabel('Password');
$pwd->setRequired(true);
$pwd->setClass('span3');
$form->addField($pwd);
$pwd = new b8\Form\Element\Password('password');
$pwd->setLabel('Password');
$pwd->setRequired(true);
$pwd->setClass('span3');
$form->addField($pwd);
$pwd = new b8\Form\Element\Submit();
$pwd->setValue('Login &raquo;');
$pwd->setClass('btn-success');
$form->addField($pwd);
$pwd = new b8\Form\Element\Submit();
$pwd->setValue('Login &raquo;');
$pwd->setClass('btn-success');
$form->addField($pwd);
$view = new b8\View('Login');
$view->form = $form->render();
die($view->render());
}
$view = new b8\View('Login');
$view->form = $form->render();
die($view->render());
}
public function logout()
{
unset($_SESSION['user_id']);
unset($_SESSION['github_token']);
header('Location: /');
die;
}
}
public function logout()
{
unset($_SESSION['user_id']);
unset($_SESSION['github_token']);
header('Location: /');
die;
}
}

View file

@ -8,10 +8,11 @@
*/
namespace PHPCI\Controller;
use b8,
b8\Registry,
PHPCI\Model\User,
b8\Form;
use b8;
use b8\Registry;
use PHPCI\Model\User;
use b8\Form;
/**
* User Controller - Allows an administrator to view, add, edit and delete users.
@ -21,160 +22,149 @@ use b8,
*/
class UserController extends b8\Controller
{
public function init()
{
$this->_userStore = b8\Store\Factory::getStore('User');
}
public function init()
{
$this->_userStore = b8\Store\Factory::getStore('User');
}
public function index()
{
$users = $this->_userStore->getWhere(array(), 1000, 0, array(), array('email' => 'ASC'));
$view = new b8\View('User');
$view->users = $users;
public function index()
{
$users = $this->_userStore->getWhere(array(), 1000, 0, array(), array('email' => 'ASC'));
$view = new b8\View('User');
$view->users = $users;
return $view->render();
}
return $view->render();
}
public function add()
{
if(!Registry::getInstance()->get('user')->getIsAdmin())
{
throw new \Exception('You do not have permission to do that.');
}
public function add()
{
if (!Registry::getInstance()->get('user')->getIsAdmin()) {
throw new \Exception('You do not have permission to do that.');
}
$method = Registry::getInstance()->get('requestMethod');
$method = Registry::getInstance()->get('requestMethod');
if($method == 'POST')
{
$values = $this->getParams();
}
else
{
$values = array();
}
if ($method == 'POST') {
$values = $this->getParams();
} else {
$values = array();
}
$form = $this->userForm($values);
$form = $this->userForm($values);
if($method != 'POST' || ($method == 'POST' && !$form->validate()))
{
$view = new b8\View('UserForm');
$view->type = 'add';
$view->user = null;
$view->form = $form;
if ($method != 'POST' || ($method == 'POST' && !$form->validate())) {
$view = new b8\View('UserForm');
$view->type = 'add';
$view->user = null;
$view->form = $form;
return $view->render();
}
return $view->render();
}
$values = $form->getValues();
$values['is_admin'] = $values['admin'] ? 1 : 0;
$values['hash'] = password_hash($values['password'], PASSWORD_DEFAULT);
$values = $form->getValues();
$values['is_admin'] = $values['admin'] ? 1 : 0;
$values['hash'] = password_hash($values['password'], PASSWORD_DEFAULT);
$user = new User();
$user->setValues($values);
$user = new User();
$user->setValues($values);
$user = $this->_userStore->save($user);
$user = $this->_userStore->save($user);
header('Location: /user');
die;
}
header('Location: /user');
die;
}
public function edit($id)
{
if(!Registry::getInstance()->get('user')->getIsAdmin())
{
throw new \Exception('You do not have permission to do that.');
}
public function edit($id)
{
if (!Registry::getInstance()->get('user')->getIsAdmin()) {
throw new \Exception('You do not have permission to do that.');
}
$method = Registry::getInstance()->get('requestMethod');
$user = $this->_userStore->getById($id);
$method = Registry::getInstance()->get('requestMethod');
$user = $this->_userStore->getById($id);
if($method == 'POST')
{
$values = $this->getParams();
}
else
{
$values = $user->getDataArray();
$values['admin'] = $values['is_admin'];
}
if ($method == 'POST') {
$values = $this->getParams();
} else {
$values = $user->getDataArray();
$values['admin'] = $values['is_admin'];
}
$form = $this->userForm($values, 'edit/' . $id);
$form = $this->userForm($values, 'edit/' . $id);
if($method != 'POST' || ($method == 'POST' && !$form->validate()))
{
$view = new b8\View('UserForm');
$view->type = 'edit';
$view->user = $user;
$view->form = $form;
if ($method != 'POST' || ($method == 'POST' && !$form->validate())) {
$view = new b8\View('UserForm');
$view->type = 'edit';
$view->user = $user;
$view->form = $form;
return $view->render();
}
return $view->render();
}
$values = $form->getValues();
$values['is_admin'] = $values['admin'] ? 1 : 0;
$values = $form->getValues();
$values['is_admin'] = $values['admin'] ? 1 : 0;
if(!empty($values['password']))
{
$values['hash'] = password_hash($values['password'], PASSWORD_DEFAULT);
}
if (!empty($values['password'])) {
$values['hash'] = password_hash($values['password'], PASSWORD_DEFAULT);
}
$user->setValues($values);
$user = $this->_userStore->save($user);
$user->setValues($values);
$user = $this->_userStore->save($user);
header('Location: /user');
die;
}
header('Location: /user');
die;
}
protected function userForm($values, $type = 'add')
{
$form = new Form();
$form->setMethod('POST');
$form->setAction('/user/' . $type);
$form->addField(new Form\Element\Csrf('csrf'));
protected function userForm($values, $type = 'add')
{
$form = new Form();
$form->setMethod('POST');
$form->setAction('/user/' . $type);
$form->addField(new Form\Element\Csrf('csrf'));
$field = new Form\Element\Email('email');
$field->setRequired(true);
$field->setLabel('Email Address');
$field->setClass('span4');
$form->addField($field);
$field = new Form\Element\Email('email');
$field->setRequired(true);
$field->setLabel('Email Address');
$field->setClass('span4');
$form->addField($field);
$field = new Form\Element\Text('name');
$field->setRequired(true);
$field->setLabel('Name');
$field->setClass('span4');
$form->addField($field);
$field = new Form\Element\Text('name');
$field->setRequired(true);
$field->setLabel('Name');
$field->setClass('span4');
$form->addField($field);
$field = new Form\Element\Password('password');
$field->setRequired(true);
$field->setLabel('Password' . ($type == 'edit' ? ' (leave blank to keep current password)' : ''));
$field->setClass('span4');
$form->addField($field);
$field = new Form\Element\Password('password');
$field->setRequired(true);
$field->setLabel('Password' . ($type == 'edit' ? ' (leave blank to keep current password)' : ''));
$field->setClass('span4');
$form->addField($field);
$field = new Form\Element\Checkbox('admin');
$field->setRequired(false);
$field->setCheckedValue(1);
$field->setLabel('Is this user an administrator?');
$form->addField($field);
$field = new Form\Element\Checkbox('admin');
$field->setRequired(false);
$field->setCheckedValue(1);
$field->setLabel('Is this user an administrator?');
$form->addField($field);
$field = new Form\Element\Submit();
$field->setValue('Save User');
$field->setClass('btn-success');
$form->addField($field);
$field = new Form\Element\Submit();
$field->setValue('Save User');
$field->setClass('btn-success');
$form->addField($field);
$form->setValues($values);
return $form;
}
$form->setValues($values);
return $form;
}
public function delete($id)
{
if(!Registry::getInstance()->get('user')->getIsAdmin())
{
throw new \Exception('You do not have permission to do that.');
}
$user = $this->_userStore->getById($id);
$this->_userStore->delete($user);
public function delete($id)
{
if (!Registry::getInstance()->get('user')->getIsAdmin()) {
throw new \Exception('You do not have permission to do that.');
}
$user = $this->_userStore->getById($id);
$this->_userStore->delete($user);
header('Location: /user');
}
}
header('Location: /user');
die;
}
}