Fixed namespaces (PHPCI -> PHPCensor)

This commit is contained in:
Dmitry Khomutov 2016-07-20 00:28:11 +06:00
commit 60a2b7282a
238 changed files with 1014 additions and 863 deletions

View file

@ -0,0 +1,55 @@
<?php
/**
* PHPCI - Continuous Integration for PHP
*
* @copyright Copyright 2014, Block 8 Limited.
* @license https://github.com/Block8/PHPCI/blob/master/LICENSE.md
* @link https://www.phptesting.org/
*/
namespace PHPCensor\Helper;
use SensioLabs\AnsiConverter\AnsiToHtmlConverter;
/**
* Converts ANSI output to HTML.
*
* @package PHPCI\Helper
*/
final class AnsiConverter
{
static private $converter = null;
/**
* Initialize the singleton.
*
* @return AnsiToHtmlConverter
*/
private static function getInstance()
{
if (self::$converter === null) {
self::$converter = new AnsiToHtmlConverter(null, false);
}
return self::$converter;
}
/**
* Convert a text containing ANSI color sequences into HTML code.
*
* @param string $text The text to convert
*
* @return string The HTML code.
*/
public static function convert($text)
{
return self::getInstance()->convert($text);
}
/**
* Do not instantiate this class.
*/
private function __construct()
{
}
}

View file

@ -0,0 +1,229 @@
<?php
/**
* PHPCI - Continuous Integration for PHP
*
* @copyright Copyright 2014, Block 8 Limited.
* @license https://github.com/Block8/PHPCI/blob/master/LICENSE.md
* @link https://www.phptesting.org/
*/
namespace PHPCensor\Helper;
use Exception;
use PHPCensor\Logging\BuildLogger;
use Psr\Log\LogLevel;
/**
* Handles running system commands with variables.
* @package PHPCI\Helper
*/
abstract class BaseCommandExecutor implements CommandExecutor
{
/**
* @var BuildLogger
*/
protected $logger;
/**
* @var bool
*/
protected $quiet;
/**
* @var bool
*/
protected $verbose;
protected $lastOutput;
protected $lastError;
public $logExecOutput = true;
/**
* The path which findBinary will look in.
* @var string
*/
protected $rootDir;
/**
* Current build path
* @var string
*/
protected $buildPath;
/**
* @param BuildLogger $logger
* @param string $rootDir
* @param bool $quiet
* @param bool $verbose
*/
public function __construct(BuildLogger $logger, $rootDir, &$quiet = false, &$verbose = false)
{
$this->logger = $logger;
$this->quiet = $quiet;
$this->verbose = $verbose;
$this->lastOutput = [];
$this->rootDir = $rootDir;
}
/**
* Executes shell commands.
*
* @param array $args
*
* @return bool Indicates success
*/
public function executeCommand($args = [])
{
$this->lastOutput = [];
$command = call_user_func_array('sprintf', $args);
$this->logger->logDebug($command);
if ($this->quiet) {
$this->logger->log('Executing: ' . $command);
}
$status = 0;
$descriptorSpec = [
0 => ["pipe", "r"], // stdin
1 => ["pipe", "w"], // stdout
2 => ["pipe", "w"], // stderr
];
$pipes = [];
$process = proc_open($command, $descriptorSpec, $pipes, $this->buildPath, null);
if (is_resource($process)) {
fclose($pipes[0]);
$this->lastOutput = stream_get_contents($pipes[1]);
$this->lastError = stream_get_contents($pipes[2]);
fclose($pipes[1]);
fclose($pipes[2]);
$status = proc_close($process);
}
$this->lastOutput = array_filter(explode(PHP_EOL, $this->lastOutput));
$shouldOutput = ($this->logExecOutput && ($this->verbose || $status != 0));
if ($shouldOutput && !empty($this->lastOutput)) {
$this->logger->log($this->lastOutput);
}
if (!empty($this->lastError)) {
$this->logger->log("\033[0;31m" . $this->lastError . "\033[0m", LogLevel::ERROR);
}
$rtn = false;
if ($status == 0) {
$rtn = true;
}
return $rtn;
}
/**
* Returns the output from the last command run.
*/
public function getLastOutput()
{
return implode(PHP_EOL, $this->lastOutput);
}
/**
* Returns the stderr output from the last command run.
*/
public function getLastError()
{
return $this->lastError;
}
/**
* Find a binary required by a plugin.
* @param string $binary
* @param bool $quiet
* @return null|string
*/
public function findBinary($binary, $quiet = false)
{
$composerBin = $this->getComposerBinDir(realpath($this->buildPath));
if (is_string($binary)) {
$binary = [$binary];
}
foreach ($binary as $bin) {
$this->logger->log(Lang::get('looking_for_binary', $bin), LogLevel::DEBUG);
if (is_dir($composerBin) && is_file($composerBin . DIRECTORY_SEPARATOR . $bin)) {
$this->logger->log(Lang::get('found_in_path', $composerBin, $bin), LogLevel::DEBUG);
return $composerBin . DIRECTORY_SEPARATOR . $bin;
}
if (is_file($this->rootDir . $bin)) {
$this->logger->log(Lang::get('found_in_path', 'root', $bin), LogLevel::DEBUG);
return $this->rootDir . $bin;
}
if (is_file($this->rootDir . 'vendor' . DIRECTORY_SEPARATOR . 'bin' . DIRECTORY_SEPARATOR . $bin)) {
$this->logger->log(Lang::get('found_in_path', 'vendor/bin', $bin), LogLevel::DEBUG);
return $this->rootDir . 'vendor' . DIRECTORY_SEPARATOR . 'bin' . DIRECTORY_SEPARATOR . $bin;
}
$findCmdResult = $this->findGlobalBinary($bin);
if (is_file($findCmdResult)) {
$this->logger->log(Lang::get('found_in_path', '', $bin), LogLevel::DEBUG);
return $findCmdResult;
}
}
if ($quiet) {
return null;
}
throw new Exception(Lang::get('could_not_find', implode('/', $binary)));
}
/**
* Find a binary which is installed globally on the system
* @param string $binary
* @return null|string
*/
abstract protected function findGlobalBinary($binary);
/**
* Try to load the composer.json file in the building project
* If the bin-dir is configured, return the full path to it
* @param string $path Current build path
* @return string|null
*/
public function getComposerBinDir($path)
{
if (is_dir($path)) {
$composer = $path . DIRECTORY_SEPARATOR . 'composer.json';
if (is_file($composer)) {
$json = json_decode(file_get_contents($composer));
if (isset($json->config->{"bin-dir"})) {
return $path . DIRECTORY_SEPARATOR . $json->config->{"bin-dir"};
} elseif (is_dir($path . DIRECTORY_SEPARATOR . 'vendor' . DIRECTORY_SEPARATOR . 'bin')) {
return $path . DIRECTORY_SEPARATOR . 'vendor' . DIRECTORY_SEPARATOR . 'bin';
}
}
}
return null;
}
/**
* Set the buildPath property.
* @param string $path
*/
public function setBuildPath($path)
{
$this->buildPath = $path;
}
}

View file

@ -0,0 +1,29 @@
<?php
/**
* PHPCI - Continuous Integration for PHP
*
* @copyright Copyright 2014, Block 8 Limited.
* @license https://github.com/Block8/PHPCI/blob/master/LICENSE.md
* @link https://www.phptesting.org/
*/
namespace PHPCensor\Helper;
/**
* User Helper - Provides access to logged in user information in views.
* @author Dan Cryer <dan@block8.co.uk>
* @package PHPCI
* @subpackage Web
*/
class Build
{
/**
* Returns a more human-friendly version of a plugin name.
* @param $name
* @return mixed
*/
public function formatPluginName($name)
{
return str_replace('Php', 'PHP', ucwords(str_replace('_', ' ', $name)));
}
}

View file

@ -0,0 +1,88 @@
<?php
/**
* PHPCI - Continuous Integration for PHP
*
* @copyright Copyright 2014, Block 8 Limited.
* @license https://github.com/Block8/PHPCI/blob/master/LICENSE.md
* @link https://www.phptesting.org/
*/
namespace PHPCensor\Helper;
use PHPCensor\Model\Build;
/**
* The BuildInterpolator class replaces variables in a string with build-specific information.
* @package PHPCI\Helper
*/
class BuildInterpolator
{
/**
* An array of key => value pairs that will be used for
* interpolation and environment variables
* @var mixed[]
* @see setupInterpolationVars()
*/
protected $interpolation_vars = [];
/**
* Sets the variables that will be used for interpolation.
* @param Build $build
* @param string $buildPath
* @param string $phpCiUrl
*/
public function setupInterpolationVars(Build $build, $buildPath, $phpCiUrl)
{
$this->interpolation_vars = [];
$this->interpolation_vars['%PHPCI%'] = 1;
$this->interpolation_vars['%COMMIT%'] = $build->getCommitId();
$this->interpolation_vars['%SHORT_COMMIT%'] = substr($build->getCommitId(), 0, 7);
$this->interpolation_vars['%COMMIT_EMAIL%'] = $build->getCommitterEmail();
$this->interpolation_vars['%COMMIT_MESSAGE%'] = $build->getCommitMessage();
$this->interpolation_vars['%COMMIT_URI%'] = $build->getCommitLink();
$this->interpolation_vars['%BRANCH%'] = $build->getBranch();
$this->interpolation_vars['%BRANCH_URI%'] = $build->getBranchLink();
$this->interpolation_vars['%PROJECT%'] = $build->getProjectId();
$this->interpolation_vars['%BUILD%'] = $build->getId();
$this->interpolation_vars['%PROJECT_TITLE%'] = $build->getProjectTitle();
$this->interpolation_vars['%PROJECT_URI%'] = $phpCiUrl . "project/view/" . $build->getProjectId();
$this->interpolation_vars['%BUILD_PATH%'] = $buildPath;
$this->interpolation_vars['%BUILD_URI%'] = $phpCiUrl . "build/view/" . $build->getId();
$this->interpolation_vars['%PHPCI_COMMIT%'] = $this->interpolation_vars['%COMMIT%'];
$this->interpolation_vars['%PHPCI_SHORT_COMMIT%'] = $this->interpolation_vars['%SHORT_COMMIT%'];
$this->interpolation_vars['%PHPCI_COMMIT_MESSAGE%'] = $this->interpolation_vars['%COMMIT_MESSAGE%'];
$this->interpolation_vars['%PHPCI_COMMIT_EMAIL%'] = $this->interpolation_vars['%COMMIT_EMAIL%'];
$this->interpolation_vars['%PHPCI_COMMIT_URI%'] = $this->interpolation_vars['%COMMIT_URI%'];
$this->interpolation_vars['%PHPCI_PROJECT%'] = $this->interpolation_vars['%PROJECT%'];
$this->interpolation_vars['%PHPCI_BUILD%'] = $this->interpolation_vars['%BUILD%'];
$this->interpolation_vars['%PHPCI_PROJECT_TITLE%'] = $this->interpolation_vars['%PROJECT_TITLE%'];
$this->interpolation_vars['%PHPCI_PROJECT_URI%'] = $this->interpolation_vars['%PROJECT_URI%'];
$this->interpolation_vars['%PHPCI_BUILD_PATH%'] = $this->interpolation_vars['%BUILD_PATH%'];
$this->interpolation_vars['%PHPCI_BUILD_URI%'] = $this->interpolation_vars['%BUILD_URI%'];
putenv('PHPCI=1');
putenv('PHPCI_COMMIT=' . $this->interpolation_vars['%COMMIT%']);
putenv('PHPCI_SHORT_COMMIT=' . $this->interpolation_vars['%SHORT_COMMIT%']);
putenv('PHPCI_COMMIT_MESSAGE=' . $this->interpolation_vars['%COMMIT_MESSAGE%']);
putenv('PHPCI_COMMIT_EMAIL=' . $this->interpolation_vars['%COMMIT_EMAIL%']);
putenv('PHPCI_COMMIT_URI=' . $this->interpolation_vars['%COMMIT_URI%']);
putenv('PHPCI_PROJECT=' . $this->interpolation_vars['%PROJECT%']);
putenv('PHPCI_BUILD=' . $this->interpolation_vars['%BUILD%']);
putenv('PHPCI_PROJECT_TITLE=' . $this->interpolation_vars['%PROJECT_TITLE%']);
putenv('PHPCI_BUILD_PATH=' . $this->interpolation_vars['%BUILD_PATH%']);
putenv('PHPCI_BUILD_URI=' . $this->interpolation_vars['%BUILD_URI%']);
}
/**
* Replace every occurrence of the interpolation vars in the given string
* Example: "This is build %PHPCI_BUILD%" => "This is build 182"
* @param string $input
* @return string
*/
public function interpolate($input)
{
$keys = array_keys($this->interpolation_vars);
$values = array_values($this->interpolation_vars);
return str_replace($keys, $values, $input);
}
}

View file

@ -0,0 +1,46 @@
<?php
/**
* PHPCI - Continuous Integration for PHP
*
* @copyright Copyright 2014, Block 8 Limited.
* @license https://github.com/Block8/PHPCI/blob/master/LICENSE.md
* @link https://www.phptesting.org/
*/
namespace PHPCensor\Helper;
interface CommandExecutor
{
/**
* Executes shell commands. Accepts multiple arguments the first
* is the template and everything else is inserted in. c.f. sprintf
*
* @param array $args
*
* @return bool Indicates success
*/
public function executeCommand($args = []);
/**
* Returns the output from the last command run.
*/
public function getLastOutput();
/**
* Find a binary required by a plugin.
*
* @param string $binary
* @param bool $quiet Returns null instead of throwing an execption.
*
* @return null|string
*
* @throws \Exception when no binary has been found and $quiet is false.
*/
public function findBinary($binary, $quiet = false);
/**
* Set the buildPath property.
* @param string $path
*/
public function setBuildPath($path);
}

View file

@ -0,0 +1,58 @@
<?php
/**
* PHPCI - Continuous Integration for PHP
*
* @copyright Copyright 2015, Block 8 Limited.
* @license https://github.com/Block8/PHPCI/blob/master/LICENSE.md
* @link https://www.phptesting.org/
*/
namespace PHPCensor\Helper;
/**
* Provides some basic diff processing functionality.
* @package PHPCI\Helper
*/
class Diff
{
/**
* Take a diff
* @param string $diff
* @return array
*/
public function getLinePositions($diff)
{
if (empty($diff)) {
return null;
}
$rtn = [];
$diffLines = explode(PHP_EOL, $diff);
while (count($diffLines)) {
$line = array_shift($diffLines);
if (substr($line, 0, 2) == '@@') {
array_unshift($diffLines, $line);
break;
}
}
$lineNumber = 0;
$position = 0;
foreach ($diffLines as $diffLine) {
if (preg_match('/@@\s+\-[0-9]+\,[0-9]+\s+\+([0-9]+)\,([0-9]+)/', $diffLine, $matches)) {
$lineNumber = (int)$matches[1] - 1;
}
$rtn[$lineNumber] = $position;
$lineNumber++;
$position++;
}
return $rtn;
}
}

View file

@ -0,0 +1,188 @@
<?php
/**
* PHPCI - Continuous Integration for PHP
*
* @copyright Copyright 2014, Block 8 Limited.
* @license https://github.com/Block8/PHPCI/blob/master/LICENSE.md
* @link https://www.phptesting.org/
*/
namespace PHPCensor\Helper;
use b8\Config;
use PHPCensor\Builder;
/**
* Helper class for sending emails using PHPCI's email configuration.
* @package PHPCI\Helper
*/
class Email
{
const DEFAULT_FROM = 'PHP Censor <no-reply@php-censor.local>';
protected $emailTo = [];
protected $emailCc = [];
protected $subject = 'Email from PHP Censor';
protected $body = '';
protected $isHtml = false;
protected $config;
/**
* Create a new email object.
*/
public function __construct()
{
$this->config = Config::getInstance();
}
/**
* Set the email's To: header.
* @param string $email
* @param string|null $name
* @return $this
*/
public function setEmailTo($email, $name = null)
{
$this->emailTo[$email] = $name;
return $this;
}
/**
* Add an address to the email's CC header.
* @param string $email
* @param string|null $name
* @return $this
*/
public function addCc($email, $name = null)
{
$this->emailCc[$email] = $name;
return $this;
}
/**
* Set the email subject.
* @param string $subject
* @return $this
*/
public function setSubject($subject)
{
$this->subject = $subject;
return $this;
}
/**
* Set the email body.
* @param string $body
* @return $this
*/
public function setBody($body)
{
$this->body = $body;
return $this;
}
/**
* Set whether or not the email body is HTML.
* @param bool $isHtml
* @return $this
*/
public function setHtml($isHtml = false)
{
$this->isHtml = $isHtml;
return $this;
}
/**
* Send the email.
*
* @param Builder $phpci
*
* @return bool|int
*/
public function send(Builder $phpci)
{
$smtpServer = $this->config->get('phpci.email_settings.smtp_address');
$phpci->logDebug(sprintf("SMTP: '%s'", !empty($smtpServer) ? 'true' : 'false'));
if (empty($smtpServer)) {
return $this->sendViaMail();
} else {
return $this->sendViaSwiftMailer();
}
}
/**
* Sends the email via the built in PHP mail() function.
* @return bool
*/
protected function sendViaMail()
{
$headers = '';
if ($this->isHtml) {
$headers = 'Content-Type: text/html' . PHP_EOL;
}
$headers .= 'From: ' . $this->getFrom() . PHP_EOL;
$emailTo = [];
foreach ($this->emailTo as $email => $name) {
$thisTo = $email;
if (!is_null($name)) {
$thisTo = '"' . $name . '" <' . $thisTo . '>';
}
$emailTo[] = $thisTo;
}
$emailTo = implode(', ', $emailTo);
return mail($emailTo, $this->subject, $this->body, $headers);
}
/**
* Sends the email using SwiftMailer.
* @return int
*/
protected function sendViaSwiftMailer()
{
$factory = new MailerFactory($this->config->get('phpci'));
$mailer = $factory->getSwiftMailerFromConfig();
$message = \Swift_Message::newInstance($this->subject)
->setFrom($this->getFrom())
->setTo($this->emailTo)
->setBody($this->body);
if ($this->isHtml) {
$message->setContentType('text/html');
}
if (is_array($this->emailCc) && count($this->emailCc)) {
$message->setCc($this->emailCc);
}
return $mailer->send($message);
}
/**
* Get the from address to use for the email.
* @return mixed|string
*/
protected function getFrom()
{
$email = $this->config->get('phpci.email_settings.from_address', self::DEFAULT_FROM);
if (empty($email)) {
$email = self::DEFAULT_FROM;
}
return $email;
}
}

View file

@ -0,0 +1,175 @@
<?php
/**
* PHPCI - Continuous Integration for PHP
*
* @copyright Copyright 2014, Block 8 Limited.
* @license https://github.com/Block8/PHPCI/blob/master/LICENSE.md
* @link https://www.phptesting.org/
*/
namespace PHPCensor\Helper;
use b8\Cache;
use b8\Config;
use b8\HttpClient;
/**
* The Github Helper class provides some Github API call functionality.
* @package PHPCI\Helper
*/
class Github
{
/**
* Make a request to the Github API.
* @param $url
* @param $params
* @return mixed
*/
public function makeRequest($url, $params)
{
$http = new HttpClient('https://api.github.com');
$res = $http->get($url, $params);
return $res['body'];
}
/**
* Make all GitHub requests following the Link HTTP headers.
*
* @param string $url
* @param mixed $params
* @param array $results
*
* @return array
*/
public function makeRecursiveRequest($url, $params, $results = [])
{
$http = new HttpClient('https://api.github.com');
$res = $http->get($url, $params);
foreach ($res['body'] as $item) {
$results[] = $item;
}
foreach ($res['headers'] as $header) {
if (preg_match('/^Link: <([^>]+)>; rel="next"/', $header, $r)) {
$host = parse_url($r[1]);
parse_str($host['query'], $params);
$results = $this->makeRecursiveRequest($host['path'], $params, $results);
break;
}
}
return $results;
}
/**
* Get an array of repositories from Github's API.
*/
public function getRepositories()
{
$token = Config::getInstance()->get('phpci.github.token');
if (!$token) {
return null;
}
$cache = Cache::getCache(Cache::TYPE_APC);
$rtn = $cache->get('phpci_github_repos');
if (!$rtn) {
$orgs = $this->makeRequest('/user/orgs', ['access_token' => $token]);
$params = ['type' => 'all', 'access_token' => $token];
$repos = ['user' => []];
$repos['user'] = $this->makeRecursiveRequest('/user/repos', $params);
foreach ($orgs as $org) {
$repos[$org['login']] = $this->makeRecursiveRequest('/orgs/'.$org['login'].'/repos', $params);
}
$rtn = [];
foreach ($repos as $repoGroup) {
foreach ($repoGroup as $repo) {
$rtn['repos'][] = $repo['full_name'];
}
}
$cache->set('phpci_github_repos', $rtn);
}
return $rtn;
}
/**
* Create a comment on a specific file (and commit) in a Github Pull Request.
* @param $repo
* @param $pullId
* @param $commitId
* @param $file
* @param $line
* @param $comment
* @return null
*/
public function createPullRequestComment($repo, $pullId, $commitId, $file, $line, $comment)
{
$token = Config::getInstance()->get('phpci.github.token');
if (!$token) {
return null;
}
$url = '/repos/' . strtolower($repo) . '/pulls/' . $pullId . '/comments';
$params = [
'body' => $comment,
'commit_id' => $commitId,
'path' => $file,
'position' => $line,
];
$http = new HttpClient('https://api.github.com');
$http->setHeaders([
'Content-Type: application/x-www-form-urlencoded',
'Authorization: Basic ' . base64_encode($token . ':x-oauth-basic'),
]);
$http->post($url, json_encode($params));
}
/**
* Create a comment on a Github commit.
* @param $repo
* @param $commitId
* @param $file
* @param $line
* @param $comment
* @return null
*/
public function createCommitComment($repo, $commitId, $file, $line, $comment)
{
$token = Config::getInstance()->get('phpci.github.token');
if (!$token) {
return null;
}
$url = '/repos/' . strtolower($repo) . '/commits/' . $commitId . '/comments';
$params = [
'body' => $comment,
'path' => $file,
'position' => $line,
];
$http = new HttpClient('https://api.github.com');
$http->setHeaders([
'Content-Type: application/x-www-form-urlencoded',
'Authorization: Basic ' . base64_encode($token . ':x-oauth-basic'),
]);
$http->post($url, json_encode($params));
}
}

View file

@ -0,0 +1,220 @@
<?php
/**
* PHPCI - Continuous Integration for PHP
*
* @copyright Copyright 2014, Block 8 Limited.
* @license https://github.com/Block8/PHPCI/blob/master/LICENSE.md
* @link https://www.phptesting.org/
*/
namespace PHPCensor\Helper;
use b8\Config;
/**
* Languages Helper Class - Handles loading strings files and the strings within them.
*
* @package PHPCI\Helper
*/
class Lang
{
/**
* @var string
*/
protected static $language = null;
/**
* @var array
*/
protected static $languages = [];
/**
* @var array
*/
protected static $strings = [];
/**
* @var array
*/
protected static $en_strings = [];
/**
* Get a specific string from the language file.
*
* @param $string
* @return mixed|string
*/
public static function get($string)
{
$vars = func_get_args();
if (array_key_exists($string, self::$strings)) {
$vars[0] = self::$strings[$string];
return call_user_func_array('sprintf', $vars);
} elseif ('en' !== self::$language && array_key_exists($string, self::$en_strings)) {
$vars[0] = self::$en_strings[$string];
return call_user_func_array('sprintf', $vars);
}
return '%%MISSING STRING: ' . $string . '%%';
}
/**
* Output a specific string from the language file.
*/
public static function out()
{
print call_user_func_array(['PHPCensor\Helper\Lang', 'get'], func_get_args());
}
/**
* Get the currently active language.
*
* @return string|null
*/
public static function getLanguage()
{
return self::$language;
}
/**
* Try and load a language, and if successful, set it for use throughout the system.
*
* @param $language
*
* @return bool
*/
public static function setLanguage($language)
{
if (in_array($language, self::$languages)) {
self::$language = $language;
self::$strings = self::loadLanguage();
return true;
}
return false;
}
/**
* Return a list of available languages and their names.
*
* @return array
*/
public static function getLanguageOptions()
{
$languages = [];
foreach (self::$languages as $language) {
$strings = include_once(PHPCI_DIR . 'Languages' . DIRECTORY_SEPARATOR . 'lang.' . $language . '.php');
$languages[$language] = !empty($strings['language_name']) ? $strings['language_name'] : $language;
}
return $languages;
}
/**
* Get the strings for the currently active language.
*
* @return string[]
*/
public static function getStrings()
{
return self::$strings;
}
/**
* Initialise the Language helper, try load the language file for the user's browser or the configured default.
*
* @param Config $config
*/
public static function init(Config $config)
{
self::$en_strings = self::loadLanguage('en');
self::loadAvailableLanguages();
// Try cookies first:
if (isset($_COOKIE) && array_key_exists('phpcilang', $_COOKIE) && self::setLanguage($_COOKIE['phpcilang'])) {
return;
}
// Try user language:
if (isset($_SERVER) && array_key_exists('HTTP_ACCEPT_LANGUAGE', $_SERVER)) {
$langs = explode(',', $_SERVER['HTTP_ACCEPT_LANGUAGE']);
foreach ($langs as $lang) {
$parts = explode(';', $lang);
$language = strtolower($parts[0]);
if (self::setLanguage($language)) {
return;
}
}
}
// Try the installation default language:
$language = $config->get('phpci.basic.language', null);
if (self::setLanguage($language)) {
return;
}
// Fall back to English:
self::$language = 'en';
self::$strings = self::loadLanguage();
}
/**
* Load a specific language file.
*
* @param string $language
*
* @return string[]|null
*/
protected static function loadLanguage($language = null)
{
$language = $language ? $language : self::$language;
$langFile = PHPCI_DIR . 'Languages' . DIRECTORY_SEPARATOR . 'lang.' . $language . '.php';
if (!file_exists($langFile)) {
return null;
}
$strings = include($langFile);
if (is_null($strings) || !is_array($strings) || !count($strings)) {
return null;
}
return $strings;
}
/**
* Load the names of all available languages.
*/
protected static function loadAvailableLanguages()
{
$matches = [];
foreach (glob(PHPCI_DIR . 'Languages' . DIRECTORY_SEPARATOR . 'lang.*.php') as $file) {
if (preg_match('/lang\.([a-z]{2}\-?[a-z]*)\.php/', $file, $matches)) {
self::$languages[] = $matches[1];
}
}
}
/**
* Create a time tag for localization.
*
* See http://momentjs.com/docs/#/displaying/format/ for a list of supported formats.
*
* @param \DateTime $dateTime The dateTime to represent.
* @param string $format The moment.js format to use.
*
* @return string The formatted tag.
*/
public static function formatDateTime(\DateTime $dateTime, $format = 'lll')
{
return sprintf(
'<time datetime="%s" data-format="%s">%s</time>',
$dateTime->format(\DateTime::ISO8601),
$format,
$dateTime->format(\DateTime::RFC2822)
);
}
}

View file

@ -0,0 +1,37 @@
<?php
/**
* PHPCI - Continuous Integration for PHP
*
* @copyright Copyright 2014, Block 8 Limited.
* @license https://github.com/Block8/PHPCI/blob/master/LICENSE.md
* @link https://www.phptesting.org/
*/
namespace PHPCensor\Helper;
use b8\Config;
/**
* Login Is Disabled Helper - Checks if login is disabled in the view
* @author Stephen Ball <phpci@stephen.rebelinblue.com>
* @package PHPCI
* @subpackage Web
*/
class LoginIsDisabled
{
/**
* Checks if
* @param $method
* @param array $params
* @return mixed|null
*/
public function __call($method, $params = [])
{
unset($method, $params);
$config = Config::getInstance();
$state = (bool) $config->get('phpci.authentication_settings.state', false);
return (false !== $state);
}
}

View file

@ -0,0 +1,88 @@
<?php
/**
* PHPCI - Continuous Integration for PHP
*
* @copyright Copyright 2014, Block 8 Limited.
* @license https://github.com/Block8/PHPCI/blob/master/LICENSE.md
* @link https://www.phptesting.org/
*/
namespace PHPCensor\Helper;
/**
* Class MailerFactory helps to set up and configure a SwiftMailer object.
* @package PHPCI\Helper
*/
class MailerFactory
{
/**
* @var array
*/
protected $emailConfig;
/**
* Set the mailer factory configuration.
* @param array $config
*/
public function __construct($config = [])
{
if (!is_array($config)) {
$config = [];
}
$this->emailConfig = isset($config['email_settings']) ? $config['email_settings'] : [];
}
/**
* Returns an instance of Swift_Mailer based on the config.s
* @return \Swift_Mailer
*/
public function getSwiftMailerFromConfig()
{
$encryptionType = $this->getMailConfig('smtp_encryption');
// Workaround issue where smtp_encryption could == 1 in the past by
// checking it is a valid transport
if ($encryptionType && !in_array($encryptionType, stream_get_transports())) {
$encryptionType = null;
}
/** @var \Swift_SmtpTransport $transport */
$transport = \Swift_SmtpTransport::newInstance(
$this->getMailConfig('smtp_address'),
$this->getMailConfig('smtp_port'),
$encryptionType
);
$transport->setUsername($this->getMailConfig('smtp_username'));
$transport->setPassword($this->getMailConfig('smtp_password'));
return \Swift_Mailer::newInstance($transport);
}
/**
* Return a specific configuration value by key.
* @param $configName
* @return null|string
*/
public function getMailConfig($configName)
{
if (isset($this->emailConfig[$configName]) && $this->emailConfig[$configName] != "") {
return $this->emailConfig[$configName];
} else {
// Check defaults
switch ($configName) {
case 'smtp_address':
return "localhost";
case 'default_mailto_address':
return null;
case 'smtp_port':
return '25';
case 'smtp_encryption':
return null;
default:
return "";
}
}
}
}

View file

@ -0,0 +1,59 @@
<?php
/**
* PHPCI - Continuous Integration for PHP
*
* @copyright Copyright 2014, Block 8 Limited.
* @license https://github.com/Block8/PHPCI/blob/master/LICENSE.md
* @link https://www.phptesting.org/
*/
namespace PHPCensor\Helper;
/**
* Helper class for dealing with SSH keys.
* @package PHPCI\Helper
*/
class SshKey
{
/**
* Uses ssh-keygen to generate a public/private key pair.
* @return array
*/
public function generate()
{
$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 (IS_WIN && $tempPath == getenv("SystemRoot") . '/') {
$tempPath = getenv("SystemRoot") . '/TEMP/';
}
$keyFile = $tempPath . md5(microtime(true));
if (!is_dir($tempPath)) {
mkdir($tempPath);
}
$return = ['private_key' => '', 'public_key' => ''];
$output = @shell_exec('ssh-keygen -t rsa -b 2048 -f '.$keyFile.' -N "" -C "deploy@phpci"');
if (!empty($output)) {
$pub = file_get_contents($keyFile . '.pub');
$prv = file_get_contents($keyFile);
if (!empty($pub)) {
$return['public_key'] = $pub;
}
if (!empty($prv)) {
$return['private_key'] = $prv;
}
}
return $return;
}
}

View file

@ -0,0 +1,27 @@
<?php
/**
* PHPCI - Continuous Integration for PHP
*
* @copyright Copyright 2014, Block 8 Limited.
* @license https://github.com/Block8/PHPCI/blob/master/LICENSE.md
* @link https://www.phptesting.org/
*/
namespace PHPCensor\Helper;
/**
* Unix/Linux specific extension of the CommandExecutor class.
* @package PHPCI\Helper
*/
class UnixCommandExecutor extends BaseCommandExecutor
{
/**
* Uses 'which' to find a system binary by name.
* @param string $binary
* @return null|string
*/
protected function findGlobalBinary($binary)
{
return trim(shell_exec('which ' . $binary));
}
}

View file

@ -0,0 +1,36 @@
<?php
/**
* PHPCI - Continuous Integration for PHP
*
* @copyright Copyright 2014, Block 8 Limited.
* @license https://github.com/Block8/PHPCI/blob/master/LICENSE.md
* @link https://www.phptesting.org/
*/
namespace PHPCensor\Helper;
/**
* User Helper - Provides access to logged in user information in views.
* @author Dan Cryer <dan@block8.co.uk>
* @package PHPCI
* @subpackage Web
*/
class User
{
/**
* Proxies method calls through to the current active user model.
* @param $method
* @param array $params
* @return mixed|null
*/
public function __call($method, $params = [])
{
$user = $_SESSION['phpci_user'];
if (!is_object($user)) {
return null;
}
return call_user_func_array([$user, $method], $params);
}
}

View file

@ -0,0 +1,30 @@
<?php
/**
* PHPCI - Continuous Integration for PHP
*
* @copyright Copyright 2014, Block 8 Limited.
* @license https://github.com/Block8/PHPCI/blob/master/LICENSE.md
* @link https://www.phptesting.org/
*/
namespace PHPCensor\Helper;
/**
* Windows-specific extension of the CommandExecutor class.
* @package PHPCI\Helper
*/
class WindowsCommandExecutor extends BaseCommandExecutor
{
/**
* Use 'where' on Windows to find a binary, rather than 'which'
* @param string $binary
* @return null|string
*/
protected function findGlobalBinary($binary)
{
$command = sprintf('where %s', $binary);
$result = shell_exec($command);
return trim($result);
}
}