diff options
author | sualko <klaus@jsxc.org> | 2017-07-26 16:55:48 +0300 |
---|---|---|
committer | sualko <klaus@jsxc.org> | 2017-07-26 16:55:48 +0300 |
commit | 4e1922e1060f5d54c7ecc661aed121b9f94b15dd (patch) | |
tree | 84161e7df22d864b191e980a83aee2943788fab6 | |
parent | 71dc0a788d641b2751a5dabd7bbf25eb1e70a870 (diff) |
run php-cs-fixer
56 files changed, 1870 insertions, 1706 deletions
diff --git a/lib/ContactsMenu/Providers/ChatProvider.php b/lib/ContactsMenu/Providers/ChatProvider.php index 5e892bb..e466bcd 100644 --- a/lib/ContactsMenu/Providers/ChatProvider.php +++ b/lib/ContactsMenu/Providers/ChatProvider.php @@ -11,75 +11,75 @@ use OCP\IURLGenerator; class ChatProvider implements IProvider { - /** @var IActionFactory */ - private $actionFactory; - - /** @var IURLGenerator */ - private $urlGenerator; - - /** @var IL10N */ - private $l10n; - - /** - * @param IActionFactory $actionFactory - * @param IURLGenerator $urlGenerator - * @param IL10N $l10n - */ - public function __construct(IActionFactory $actionFactory, IURLGenerator $urlGenerator, IL10N $l10n) - { - $this->actionFactory = $actionFactory; - $this->urlGenerator = $urlGenerator; - $this->l10n = $l10n; - } - - /** - * @param IEntry $entry - */ - public function process(IEntry $entry) - { - $uid = $entry->getProperty('UID'); - $iconUrl = $this->urlGenerator->getAbsoluteURL($this->urlGenerator->imagePath('ojsxc', 'actions/chat.svg')); - $localIm = null; - - if (is_null($uid)) { - // Nothing to do - return; - } - - if ($entry->getProperty('isLocalSystemBook') === true) { - // internal user - - $config = \OC::$server->getConfig(); - $serverType = $config->getAppValue('ojsxc', 'serverType', 'external'); - - if ($serverType === 'internal') { - $domain = \OC::$server->getRequest()->getServerHost(); - } else { - $domain = trim($config->getAppValue('ojsxc', 'xmppDomain')); - } - - if ($domain !== "") { - $localIm = $uid.'@'.$domain; - $chatUrl = 'xmpp:'.$localIm; - - $action = $this->actionFactory->newLinkAction($iconUrl, $localIm, $chatUrl); - $entry->addAction($action); - } - } - - $imProperties = $entry->getProperty('IMPP'); - - if (!is_null($imProperties)) { - foreach ($imProperties as $externalIm) { - if (!preg_match("/^[a-z0-9\.\-_]+@[a-z0-9\.\-_]+$/i", $externalIm) || $externalIm === $localIm) { - continue; - } - - $chatUrl = 'xmpp:'.$externalIm; - - $action = $this->actionFactory->newLinkAction($iconUrl, $externalIm, $chatUrl); - $entry->addAction($action); - } - } - } + /** @var IActionFactory */ + private $actionFactory; + + /** @var IURLGenerator */ + private $urlGenerator; + + /** @var IL10N */ + private $l10n; + + /** + * @param IActionFactory $actionFactory + * @param IURLGenerator $urlGenerator + * @param IL10N $l10n + */ + public function __construct(IActionFactory $actionFactory, IURLGenerator $urlGenerator, IL10N $l10n) + { + $this->actionFactory = $actionFactory; + $this->urlGenerator = $urlGenerator; + $this->l10n = $l10n; + } + + /** + * @param IEntry $entry + */ + public function process(IEntry $entry) + { + $uid = $entry->getProperty('UID'); + $iconUrl = $this->urlGenerator->getAbsoluteURL($this->urlGenerator->imagePath('ojsxc', 'actions/chat.svg')); + $localIm = null; + + if (is_null($uid)) { + // Nothing to do + return; + } + + if ($entry->getProperty('isLocalSystemBook') === true) { + // internal user + + $config = \OC::$server->getConfig(); + $serverType = $config->getAppValue('ojsxc', 'serverType', 'external'); + + if ($serverType === 'internal') { + $domain = \OC::$server->getRequest()->getServerHost(); + } else { + $domain = trim($config->getAppValue('ojsxc', 'xmppDomain')); + } + + if ($domain !== "") { + $localIm = $uid.'@'.$domain; + $chatUrl = 'xmpp:'.$localIm; + + $action = $this->actionFactory->newLinkAction($iconUrl, $localIm, $chatUrl); + $entry->addAction($action); + } + } + + $imProperties = $entry->getProperty('IMPP'); + + if (!is_null($imProperties)) { + foreach ($imProperties as $externalIm) { + if (!preg_match("/^[a-z0-9\.\-_]+@[a-z0-9\.\-_]+$/i", $externalIm) || $externalIm === $localIm) { + continue; + } + + $chatUrl = 'xmpp:'.$externalIm; + + $action = $this->actionFactory->newLinkAction($iconUrl, $externalIm, $chatUrl); + $entry->addAction($action); + } + } + } } diff --git a/lib/Controller/ExternalApiController.php b/lib/Controller/ExternalApiController.php index 36e0f60..0cec8a5 100644 --- a/lib/Controller/ExternalApiController.php +++ b/lib/Controller/ExternalApiController.php @@ -14,146 +14,149 @@ use OCA\OJSXC\Exceptions\UnprocessableException; class ExternalApiController extends SignatureProtectedApiController { - private $userManager; + private $userManager; - private $userSession; + private $userSession; - private $groupManager; + private $groupManager; - private $logger; + private $logger; - public function __construct($appName, + public function __construct($appName, IRequest $request, IUserManager $userManager, IUserSession $userSession, IGroupManager $groupManager, ILogger $logger) - { - parent::__construct($appName, $request); - - $this->userManager = $userManager; - $this->userSession = $userSession; - $this->groupManager = $groupManager; - $this->logger = $logger; - } - - public function index($operation) - { - switch($operation) { - case 'auth': - return checkPassword( - $this->request->getParam('username'), - $this->request->getParam('password'), - $this->request->getParam('domain') - ); - break; - case 'isuser': - return isUser( - $this->request->getParam('username'), - $this->request->getParam('domain') - ); - break; - case 'sharedroster': - return sharedRoster( - $this->request->getParam('username'), - $this->request->getParam('domain') - ); - break; - default: - throw new UnprocessableException( 'Unsupported operation.'); - } - } - - public function checkPassword($username = '', $password = '', $domain = '') { - $currentUser = null; - - $this->logger->info('ExAPI: Check password for user: '.$username.'@'.$domain); - - if(!empty($password) && !empty($username)) { - $loggedIn = false; - if(!empty($domain)) { - $loggedIn = $this->userSession->login($username . '@' . $domain, $password); - } - if(!$loggedIn) { - $loggedIn = $this->userSession->login($username, $password); - } - - if($loggedIn === true) { - $currentUser = $this->userSession->getUser(); - } - } - - if (!$currentUser) { - return array( - 'result' => 'noauth', - ); - } - - $data = array(); - $data ['uid'] = $currentUser->getUID(); - - return array( - 'result' => 'success', - 'data' => $data, - ); - } - - public function isUser($username = '', $domain = '') { - $this->logger->info('ExAPI: Check if "'.$username.'@'.$domain.'" exists'); - - $isUser = false; - - if(!empty($username)) { - if(!empty($domain)) { - $isUser = $this->userManager->userExists($username . '@' . $domain); - } - if(!$isUser) { - $isUser = $this->userManager->userExists($username); - } - } - - return array( - 'result' => 'success', - 'data' => array( - 'isUser' => $isUser - ) - ); - } - - public function sharedRoster($username = '', $domain = '') { - if(!empty($username)) { - if(!empty($domain)) { - $username .= '@' . $domain; - } - } else { - throw new UnprocessableException('No username provided'); - } - - $roster = []; - $user = $this->userManager->get($username); - - $userGroups = $this->groupManager->getUserGroups($user); - - foreach($userGroups as $userGroup) { - foreach($userGroup->getUsers() as $user) { - $uid = $user->getUID(); - - if(!array_key_exists($uid, $roster)) { - $roster[$uid] = [ - 'name' => $user->getDisplayName(), - 'groups' => [] - ]; - } - - $roster[$uid]['groups'][] = $userGroup->getDisplayName(); - } - } - - return array( - 'result' => 'success', - 'data' => array( - 'sharedRoster' => $roster - ) - ); - } + { + parent::__construct($appName, $request); + + $this->userManager = $userManager; + $this->userSession = $userSession; + $this->groupManager = $groupManager; + $this->logger = $logger; + } + + public function index($operation) + { + switch ($operation) { + case 'auth': + return checkPassword( + $this->request->getParam('username'), + $this->request->getParam('password'), + $this->request->getParam('domain') + ); + break; + case 'isuser': + return isUser( + $this->request->getParam('username'), + $this->request->getParam('domain') + ); + break; + case 'sharedroster': + return sharedRoster( + $this->request->getParam('username'), + $this->request->getParam('domain') + ); + break; + default: + throw new UnprocessableException('Unsupported operation.'); + } + } + + public function checkPassword($username = '', $password = '', $domain = '') + { + $currentUser = null; + + $this->logger->info('ExAPI: Check password for user: '.$username.'@'.$domain); + + if (!empty($password) && !empty($username)) { + $loggedIn = false; + if (!empty($domain)) { + $loggedIn = $this->userSession->login($username . '@' . $domain, $password); + } + if (!$loggedIn) { + $loggedIn = $this->userSession->login($username, $password); + } + + if ($loggedIn === true) { + $currentUser = $this->userSession->getUser(); + } + } + + if (!$currentUser) { + return [ + 'result' => 'noauth', + ]; + } + + $data = []; + $data ['uid'] = $currentUser->getUID(); + + return [ + 'result' => 'success', + 'data' => $data, + ]; + } + + public function isUser($username = '', $domain = '') + { + $this->logger->info('ExAPI: Check if "'.$username.'@'.$domain.'" exists'); + + $isUser = false; + + if (!empty($username)) { + if (!empty($domain)) { + $isUser = $this->userManager->userExists($username . '@' . $domain); + } + if (!$isUser) { + $isUser = $this->userManager->userExists($username); + } + } + + return [ + 'result' => 'success', + 'data' => [ + 'isUser' => $isUser + ] + ]; + } + + public function sharedRoster($username = '', $domain = '') + { + if (!empty($username)) { + if (!empty($domain)) { + $username .= '@' . $domain; + } + } else { + throw new UnprocessableException('No username provided'); + } + + $roster = []; + $user = $this->userManager->get($username); + + $userGroups = $this->groupManager->getUserGroups($user); + + foreach ($userGroups as $userGroup) { + foreach ($userGroup->getUsers() as $user) { + $uid = $user->getUID(); + + if (!array_key_exists($uid, $roster)) { + $roster[$uid] = [ + 'name' => $user->getDisplayName(), + 'groups' => [] + ]; + } + + $roster[$uid]['groups'][] = $userGroup->getDisplayName(); + } + } + + return [ + 'result' => 'success', + 'data' => [ + 'sharedRoster' => $roster + ] + ]; + } } diff --git a/lib/Controller/HttpBindController.php b/lib/Controller/HttpBindController.php index 4d4b0dd..da159a8 100644 --- a/lib/Controller/HttpBindController.php +++ b/lib/Controller/HttpBindController.php @@ -19,18 +19,17 @@ use OCP\IRequest; use Sabre\Xml\Reader; use Sabre\Xml\LibXMLException; - /** * Class HttpBindController * * @package OCA\OJSXC\Controller */ -class HttpBindController extends Controller { - - const MESSAGE=0; - const IQ=1; - const PRESENCE=2; - const BODY=2; +class HttpBindController extends Controller +{ + const MESSAGE = 0; + const IQ = 1; + const PRESENCE = 2; + const BODY = 2; /** @@ -142,7 +141,7 @@ class HttpBindController extends Controller { $this->body = $body; $this->sleepTime = $sleepTime; $this->maxCicles = $maxCicles; - $this->response = new XMPPResponse($stanzaLogger); + $this->response = new XMPPResponse($stanzaLogger); $this->lock = $lock; $this->presenceHandler = $presenceHandler; $this->presenceMapper = $presenceMapper; @@ -155,7 +154,8 @@ class HttpBindController extends Controller { * @NoCSRFRequired * @return XMPPResponse */ - public function index() { + public function index() + { $this->lock->setLock(); $this->presenceMapper->updatePresence(); $input = $this->body; @@ -168,8 +168,8 @@ class HttpBindController extends Controller { $reader->xml($input); $reader->elementMap = [ '{jabber:client}message' => 'Sabre\Xml\Element\KeyValue', - '{jabber:client}presence' => function(Reader $reader) { - return Presence::createFromXml($reader,$this->userId); + '{jabber:client}presence' => function (Reader $reader) { + return Presence::createFromXml($reader, $this->userId); } ]; $stanzas = null; @@ -187,13 +187,13 @@ class HttpBindController extends Controller { $stanzaType = $this->getStanzaType($stanza); if ($stanzaType === self::MESSAGE) { $this->messageHandler->handle($stanza); - } else if ($stanzaType === self::IQ) { + } elseif ($stanzaType === self::IQ) { $result = $this->iqHandler->handle($stanza); if (!is_null($result)) { $longpoll = false; $this->response->write($result); } - } else if ($stanza['value'] instanceof Presence) { + } elseif ($stanza['value'] instanceof Presence) { $results = $this->presenceHandler->handle($stanza['value']); if (!is_null($results) && is_array($results)) { $longpoll = false; @@ -210,7 +210,7 @@ class HttpBindController extends Controller { // Start long polling $this->presenceMapper->setActive($this->userId); - if ($this->newContentContainer->getCount() > 0 ){ + if ($this->newContentContainer->getCount() > 0) { foreach ($this->newContentContainer->getStanzas() as $stanz) { $this->response->write($stanz); } @@ -227,7 +227,7 @@ class HttpBindController extends Controller { $this->response->write($stanz); } $recordFound = true; - } Catch (DoesNotExistException $e) { + } catch (DoesNotExistException $e) { sleep($this->sleepTime); $recordFound = false; } @@ -242,8 +242,9 @@ class HttpBindController extends Controller { * @return int * @codeCoverageIgnore */ - private function getStanzaType($stanza){ - switch($stanza['name']){ + private function getStanzaType($stanza) + { + switch ($stanza['name']) { case '{jabber:client}message': return self::MESSAGE; case '{jabber:client}iq': diff --git a/lib/Controller/SettingsController.php b/lib/Controller/SettingsController.php index 68be1ef..4bb9da3 100644 --- a/lib/Controller/SettingsController.php +++ b/lib/Controller/SettingsController.php @@ -11,24 +11,24 @@ use OCA\OJSXC\TimeLimitedToken; class SettingsController extends Controller { - private $config; + private $config; - private $userManager; + private $userManager; - private $userSession; + private $userSession; - public function __construct($appName, + public function __construct($appName, IRequest $request, IConfig $config, IUserManager $userManager, IUserSession $userSession) - { - parent::__construct($appName, $request); + { + parent::__construct($appName, $request); - $this->config = $config; - $this->userManager = $userManager; - $this->userSession = $userSession; - } + $this->config = $config; + $this->userManager = $userManager; + $this->userSession = $userSession; + } /** * @NoAdminRequired @@ -36,302 +36,312 @@ class SettingsController extends Controller */ public function index() { - $currentUser = $this->getCurrentUser(); - - if (!$currentUser) { - return array( - 'result' => 'noauth', - ); - } - - $currentUID = $currentUser->getUID(); - - $serverType = $this->getAppValue('serverType'); - - $data = array( - 'serverType' => (!empty($serverType))? $serverType : 'internal', - 'loginForm' => array( - 'startMinimized' => $this->getBooleanAppValue('xmppStartMinimized') - ) - ); - - if ($data ['serverType'] === 'internal') { - $data['adminSettings']['xmppDomain'] = $this->request->getServerHost(); - - return array( - 'result' => 'success', - 'data' => $data, - ); - } - - $data ['screenMediaExtension'] = array( - 'firefox' => trim($this->getAppValue('firefoxExtension')), - 'chrome' => trim($this->getAppValue('chromeExtension')) - ); - - $data ['xmpp'] = array( - 'url' => trim($this->getAppValue('boshUrl')), - 'domain' => trim($this->getAppValue('xmppDomain')), - 'resource' => trim($this->getAppValue('xmppResource')), - 'overwrite' => $this->getBooleanAppValue('xmppOverwrite'), - 'onlogin' => null - ); - - $data ['adminSettings'] = array( - 'xmppDomain' => trim($this->getAppValue('xmppDomain')) - ); - - if ($this->getBooleanAppValue('xmppPreferMail')) { - $mail = $this->config->getUserValue($currentUID, 'settings', 'email'); - - if ($mail !== null) { - list($u, $d) = explode("@", $mail, 2); - if ($d !== null && $d !== "") { - $data ['xmpp'] ['username'] = $u; - $data ['xmpp'] ['domain'] = $d; - } - } - } - - if ($this->getBooleanAppValue('timeLimitedToken')) { - if (!array_key_exists('username', $data['xmpp']) || empty($data['xmpp']['username'])) { - $data['xmpp']['username'] = $currentUID; - } - - $token = $this->generateTimeLimitedToken($data['xmpp']['username'], $data['xmpp']['domain']); - - $data['xmpp']['password'] = $token; - } - - $data = $this->overwriteByUserDefined($currentUID, $data); - - return array( - 'result' => 'success', - 'data' => $data, - ); + $currentUser = $this->getCurrentUser(); + + if (!$currentUser) { + return [ + 'result' => 'noauth', + ]; + } + + $currentUID = $currentUser->getUID(); + + $serverType = $this->getAppValue('serverType'); + + $data = [ + 'serverType' => (!empty($serverType))? $serverType : 'internal', + 'loginForm' => [ + 'startMinimized' => $this->getBooleanAppValue('xmppStartMinimized') + ] + ]; + + if ($data ['serverType'] === 'internal') { + $data['adminSettings']['xmppDomain'] = $this->request->getServerHost(); + + return [ + 'result' => 'success', + 'data' => $data, + ]; + } + + $data ['screenMediaExtension'] = [ + 'firefox' => trim($this->getAppValue('firefoxExtension')), + 'chrome' => trim($this->getAppValue('chromeExtension')) + ]; + + $data ['xmpp'] = [ + 'url' => trim($this->getAppValue('boshUrl')), + 'domain' => trim($this->getAppValue('xmppDomain')), + 'resource' => trim($this->getAppValue('xmppResource')), + 'overwrite' => $this->getBooleanAppValue('xmppOverwrite'), + 'onlogin' => null + ]; + + $data ['adminSettings'] = [ + 'xmppDomain' => trim($this->getAppValue('xmppDomain')) + ]; + + if ($this->getBooleanAppValue('xmppPreferMail')) { + $mail = $this->config->getUserValue($currentUID, 'settings', 'email'); + + if ($mail !== null) { + list($u, $d) = explode("@", $mail, 2); + if ($d !== null && $d !== "") { + $data ['xmpp'] ['username'] = $u; + $data ['xmpp'] ['domain'] = $d; + } + } + } + + if ($this->getBooleanAppValue('timeLimitedToken')) { + if (!array_key_exists('username', $data['xmpp']) || empty($data['xmpp']['username'])) { + $data['xmpp']['username'] = $currentUID; + } + + $token = $this->generateTimeLimitedToken($data['xmpp']['username'], $data['xmpp']['domain']); + + $data['xmpp']['password'] = $token; + } + + $data = $this->overwriteByUserDefined($currentUID, $data); + + return [ + 'result' => 'success', + 'data' => $data, + ]; } - public function setAdmin() { - if ($this->isPasswordConfirmationRequired()) { - $l = \OC::$server->getL10N('core'); - - return array( - 'status' => 'error', - 'data' => array( - 'message' => $l->t('Password confirmation is required') - ) - ); - } - - $this->setAppValue('serverType', $this->getParam('serverType')); - $this->setAppValue('boshUrl', $this->getTrimParam('boshUrl')); - $this->setAppValue('xmppDomain', $this->getTrimParam('xmppDomain')); - $this->setAppValue('xmppResource', $this->getTrimParam('xmppResource')); - $this->setAppValue('xmppOverwrite', $this->getCheckboxParam('xmppOverwrite')); - $this->setAppValue('xmppStartMinimized', $this->getCheckboxParam('xmppStartMinimized')); - $this->setAppValue('xmppPreferMail', $this->getCheckboxParam('xmppPreferMail')); - - $this->setAppValue('iceUrl', $this->getTrimParam('iceUrl')); - $this->setAppValue('iceUsername', $this->getTrimParam('iceUsername')); - $this->setAppValue('iceCredential', $this->getParam('iceCredential')); - $this->setAppValue('iceSecret', $this->getParam('iceSecret')); - $this->setAppValue('iceTtl', $this->getParam('iceTtl')); - - $this->setAppValue('timeLimitedToken', $this->getCheckboxParam('timeLimitedToken')); - - $this->setAppValue('firefoxExtension', $this->getParam('firefoxExtension')); - $this->setAppValue('chromeExtension', $this->getParam('chromeExtension')); - - $externalServices = array(); - foreach($this->getParam('externalServices') as $es) { - if (preg_match('/^(https:\/\/)?([\w\d*][\w\d-]*)(\.[\w\d-]+)+(:[\d]+)?$/', $es)) { - $externalServices[] = $es; - } - } - $this->setAppValue('externalServices', implode('|', $externalServices)); - - return array( - 'status' => 'success' - ); - } + public function setAdmin() + { + if ($this->isPasswordConfirmationRequired()) { + $l = \OC::$server->getL10N('core'); + + return [ + 'status' => 'error', + 'data' => [ + 'message' => $l->t('Password confirmation is required') + ] + ]; + } + + $this->setAppValue('serverType', $this->getParam('serverType')); + $this->setAppValue('boshUrl', $this->getTrimParam('boshUrl')); + $this->setAppValue('xmppDomain', $this->getTrimParam('xmppDomain')); + $this->setAppValue('xmppResource', $this->getTrimParam('xmppResource')); + $this->setAppValue('xmppOverwrite', $this->getCheckboxParam('xmppOverwrite')); + $this->setAppValue('xmppStartMinimized', $this->getCheckboxParam('xmppStartMinimized')); + $this->setAppValue('xmppPreferMail', $this->getCheckboxParam('xmppPreferMail')); + + $this->setAppValue('iceUrl', $this->getTrimParam('iceUrl')); + $this->setAppValue('iceUsername', $this->getTrimParam('iceUsername')); + $this->setAppValue('iceCredential', $this->getParam('iceCredential')); + $this->setAppValue('iceSecret', $this->getParam('iceSecret')); + $this->setAppValue('iceTtl', $this->getParam('iceTtl')); + + $this->setAppValue('timeLimitedToken', $this->getCheckboxParam('timeLimitedToken')); + + $this->setAppValue('firefoxExtension', $this->getParam('firefoxExtension')); + $this->setAppValue('chromeExtension', $this->getParam('chromeExtension')); + + $externalServices = []; + foreach ($this->getParam('externalServices') as $es) { + if (preg_match('/^(https:\/\/)?([\w\d*][\w\d-]*)(\.[\w\d-]+)+(:[\d]+)?$/', $es)) { + $externalServices[] = $es; + } + } + $this->setAppValue('externalServices', implode('|', $externalServices)); + + return [ + 'status' => 'success' + ]; + } /** * @NoAdminRequired */ - public function setUser() { - $uid = $this->userSession->getUser()->getUID(); + public function setUser() + { + $uid = $this->userSession->getUser()->getUID(); - $options = $this->config->getUserValue($uid, 'ojsxc', 'options'); - $options = json_decode($options, true); + $options = $this->config->getUserValue($uid, 'ojsxc', 'options'); + $options = json_decode($options, true); - foreach($_POST as $key => $val) { - $options[$key] = $val; - } + foreach ($_POST as $key => $val) { + $options[$key] = $val; + } - $this->config->setUserValue($uid, 'ojsxc', 'options', json_encode($options)); + $this->config->setUserValue($uid, 'ojsxc', 'options', json_encode($options)); - return array( - 'status' => 'success' - ); + return [ + 'status' => 'success' + ]; } /** * @NoAdminRequired */ - public function getIceServers() { - $secret = $this->getAppValue('iceSecret'); - $ttl = $this->getAppValue('iceTtl', 3600 * 24); // one day (according to TURN-REST-API) - $url = $this->getAppValue('iceUrl'); - $username = $this->getAppValue('iceUsername', ''); - $credential = $this->getAppValue('iceCredential', ''); - - $url = preg_match('/^(turn|stun):/', $url) || empty($url) ? $url : "turn:$url"; - - if (!empty($secret) && (empty($username) || empty($credential))) { - $uid = $this->userSession->getUser()->getUID(); - - $accessData = TimeLimitedToken::generateTURN($uid, $secret, $ttl); - - $username = $accessData[0]; - $credential = $accessData[1]; - } - - if (!empty($url)) { - $data = array( - 'ttl' => $ttl, - 'iceServers' => array( - array( - 'urls' => array($url), - 'credential' => $credential, - 'username' => $username, - ), - ), - ); - } else { - $data = array(); - } - - return $data; + public function getIceServers() + { + $secret = $this->getAppValue('iceSecret'); + $ttl = $this->getAppValue('iceTtl', 3600 * 24); // one day (according to TURN-REST-API) + $url = $this->getAppValue('iceUrl'); + $username = $this->getAppValue('iceUsername', ''); + $credential = $this->getAppValue('iceCredential', ''); + + $url = preg_match('/^(turn|stun):/', $url) || empty($url) ? $url : "turn:$url"; + + if (!empty($secret) && (empty($username) || empty($credential))) { + $uid = $this->userSession->getUser()->getUID(); + + $accessData = TimeLimitedToken::generateTURN($uid, $secret, $ttl); + + $username = $accessData[0]; + $credential = $accessData[1]; + } + + if (!empty($url)) { + $data = [ + 'ttl' => $ttl, + 'iceServers' => [ + [ + 'urls' => [$url], + 'credential' => $credential, + 'username' => $username, + ], + ], + ]; + } else { + $data = []; + } + + return $data; } /** * @NoAdminRequired */ - public function getUsers($search = '') { - $limit = 10; - $offset = 0; - - $preferMail = $this->getBooleanAppValue('xmppPreferMail'); - - $users = $this->userManager->searchDisplayName($search, $limit, $offset); - $response = array(); - - foreach($users as $user) { - $uid = $user->getUID(); - $index = $uid; - - if ($preferMail) { - $mail = $this->config->getUserValue($uid, 'settings', 'email'); + public function getUsers($search = '') + { + $limit = 10; + $offset = 0; - if (!empty($mail)) { - $index = $mail; - } - } + $preferMail = $this->getBooleanAppValue('xmppPreferMail'); - $response[$index] = $user->getDisplayName(); - } + $users = $this->userManager->searchDisplayName($search, $limit, $offset); + $response = []; - return $response; - } + foreach ($users as $user) { + $uid = $user->getUID(); + $index = $uid; - private function getCurrentUser() - { - $currentUser = false; - - if (\OCP\User::isLoggedIn()) { - $currentUser = $this->userSession->getUser(); - } elseif (!empty($this->getParam('username')) && !empty($this->getParam('password'))) { - $currentUser = $this->userManager->checkPassword($this->getParam('username'), $this->getParam('password')); - } - - return $currentUser; - } - - private function generateTimeLimitedToken($node, $domain) - { - $secret = $this->getAppValue('apiSecret'); - - return TimeLimitedToken::generateUser($node, $domain, $secret); - } - - private function overwriteByUserDefined($currentUID, $data) - { - $options = $this->config->getUserValue($currentUID, 'ojsxc', 'options'); - - if ($options !== null) { - $options = (array) json_decode($options, true); - - if (is_array($options)) { - foreach ($options as $prop => $value) { - if ($prop !== 'xmpp' || $data ['xmpp'] ['overwrite']) { - foreach ($value as $key => $v) { - if ($v !== '') { - $data [$prop] [$key] = ($v === 'false' || $v === 'true') ? $this->validateBoolean($v) : $v; - } - } - } - } - } - } - - return $data; - } - - private function getBooleanAppValue($key) - { - return $this->validateBoolean($this->getAppValue($key)); - } - - private function getAppValue($key, $default = null) - { - $value = $this->config->getAppValue($this->appName, $key, $default); - - return (empty($value)) ? $default : $value; - } - - private function setAppValue($key, $value) { - return $this->config->setAppValue($this->appName, $key, $value); - } - - private function validateBoolean($val) - { - return $val === true || $val === 'true'; - } - - private function isPasswordConfirmationRequired() { - $version = \OCP\Util::getVersion(); - preg_match('/^([0-9]+)\.', $version, $versionMatches); - $majorVersion = intval($versionMatches[1]); - - // copied from owncloud/settings/ajax/installapp.php - $lastConfirm = (int) \OC::$server->getSession()->get('last-password-confirm'); - - return $majorVersion >= 11 && $lastConfirm < (time() - 30 * 60 + 15); - } + if ($preferMail) { + $mail = $this->config->getUserValue($uid, 'settings', 'email'); - private function getCheckboxValue($var) { - return (isset($var)) ? $var : 'false'; - } + if (!empty($mail)) { + $index = $mail; + } + } - private function getParam($key) { - return $this->request->getParam($key); - } + $response[$index] = $user->getDisplayName(); + } - private function getCheckboxParam($key) { - return $this->getCheckboxValue($this->request->getParam($key)); + return $response; } - private function getTrimParam($key) { - return trim($this->request->getParam($key)); - } + private function getCurrentUser() + { + $currentUser = false; + + if (\OCP\User::isLoggedIn()) { + $currentUser = $this->userSession->getUser(); + } elseif (!empty($this->getParam('username')) && !empty($this->getParam('password'))) { + $currentUser = $this->userManager->checkPassword($this->getParam('username'), $this->getParam('password')); + } + + return $currentUser; + } + + private function generateTimeLimitedToken($node, $domain) + { + $secret = $this->getAppValue('apiSecret'); + + return TimeLimitedToken::generateUser($node, $domain, $secret); + } + + private function overwriteByUserDefined($currentUID, $data) + { + $options = $this->config->getUserValue($currentUID, 'ojsxc', 'options'); + + if ($options !== null) { + $options = (array) json_decode($options, true); + + if (is_array($options)) { + foreach ($options as $prop => $value) { + if ($prop !== 'xmpp' || $data ['xmpp'] ['overwrite']) { + foreach ($value as $key => $v) { + if ($v !== '') { + $data [$prop] [$key] = ($v === 'false' || $v === 'true') ? $this->validateBoolean($v) : $v; + } + } + } + } + } + } + + return $data; + } + + private function getBooleanAppValue($key) + { + return $this->validateBoolean($this->getAppValue($key)); + } + + private function getAppValue($key, $default = null) + { + $value = $this->config->getAppValue($this->appName, $key, $default); + + return (empty($value)) ? $default : $value; + } + + private function setAppValue($key, $value) + { + return $this->config->setAppValue($this->appName, $key, $value); + } + + private function validateBoolean($val) + { + return $val === true || $val === 'true'; + } + + private function isPasswordConfirmationRequired() + { + $version = \OCP\Util::getVersion(); + preg_match('/^([0-9]+)\.', $version, $versionMatches); + $majorVersion = intval($versionMatches[1]); + + // copied from owncloud/settings/ajax/installapp.php + $lastConfirm = (int) \OC::$server->getSession()->get('last-password-confirm'); + + return $majorVersion >= 11 && $lastConfirm < (time() - 30 * 60 + 15); + } + + private function getCheckboxValue($var) + { + return (isset($var)) ? $var : 'false'; + } + + private function getParam($key) + { + return $this->request->getParam($key); + } + + private function getCheckboxParam($key) + { + return $this->getCheckboxValue($this->request->getParam($key)); + } + + private function getTrimParam($key) + { + return trim($this->request->getParam($key)); + } } diff --git a/lib/Controller/SignatureProtectedApiController.php b/lib/Controller/SignatureProtectedApiController.php index 0d2edac..c9f8b31 100644 --- a/lib/Controller/SignatureProtectedApiController.php +++ b/lib/Controller/SignatureProtectedApiController.php @@ -4,6 +4,6 @@ namespace OCA\OJSXC\Controller; use OCP\AppFramework\ApiController; -abstract class SignatureProtectedApiController extends ApiController { - +abstract class SignatureProtectedApiController extends ApiController +{ } diff --git a/lib/Exceptions/Exception.php b/lib/Exceptions/Exception.php index 950f4c7..50346c3 100644 --- a/lib/Exceptions/Exception.php +++ b/lib/Exceptions/Exception.php @@ -2,4 +2,6 @@ namespace OCA\OJSXC\Exceptions; -class Exception extends \Exception {} +class Exception extends \Exception +{ +} diff --git a/lib/Exceptions/SecurityException.php b/lib/Exceptions/SecurityException.php index 90cddea..31b99d6 100644 --- a/lib/Exceptions/SecurityException.php +++ b/lib/Exceptions/SecurityException.php @@ -2,4 +2,6 @@ namespace OCA\OJSXC\Exceptions; -class SecurityException extends Exception {} +class SecurityException extends Exception +{ +} diff --git a/lib/Exceptions/UnprocessableException.php b/lib/Exceptions/UnprocessableException.php index 1b6ca01..670942f 100644 --- a/lib/Exceptions/UnprocessableException.php +++ b/lib/Exceptions/UnprocessableException.php @@ -2,4 +2,6 @@ namespace OCA\OJSXC\Exceptions; -class UnprocessableException extends Exception {} +class UnprocessableException extends Exception +{ +} diff --git a/lib/Middleware/ExternalApiMiddleware.php b/lib/Middleware/ExternalApiMiddleware.php index 8429e0c..4b7f293 100644 --- a/lib/Middleware/ExternalApiMiddleware.php +++ b/lib/Middleware/ExternalApiMiddleware.php @@ -14,60 +14,60 @@ use OCA\OJSXC\RawRequest; class ExternalApiMiddleware extends Middleware { - private $request; + private $request; - private $config; + private $config; - private $rawRequest; + private $rawRequest; - public function __construct(IRequest $request, IConfig $config, RawRequest $rawRequest) - { - $this->request = $request; - $this->config = $config; - $this->rawRequest = $rawRequest; - } + public function __construct(IRequest $request, IConfig $config, RawRequest $rawRequest) + { + $this->request = $request; + $this->config = $config; + $this->rawRequest = $rawRequest; + } - public function beforeController($controller, $methodName) - { - if (!$controller instanceof SignatureProtectedApiController) { - return; - } + public function beforeController($controller, $methodName) + { + if (!$controller instanceof SignatureProtectedApiController) { + return; + } - $apiSecret = $this->config->getAppValue('ojsxc', 'apiSecret'); - $jsxcSignatureHeader = $this->request->getHeader('X-JSXC-SIGNATURE'); + $apiSecret = $this->config->getAppValue('ojsxc', 'apiSecret'); + $jsxcSignatureHeader = $this->request->getHeader('X-JSXC-SIGNATURE'); - // check if we have a signature - if (! isset($jsxcSignatureHeader)) { - throw new SecurityException('HTTP header "X-JSXC-Signature" is missing.'); - } elseif (! extension_loaded('hash')) { - throw new SecurityException('Missing "hash" extension to check the secret code validity.'); - } elseif (! $apiSecret) { - throw new SecurityException('Missing secret.'); - } + // check if we have a signature + if (! isset($jsxcSignatureHeader)) { + throw new SecurityException('HTTP header "X-JSXC-Signature" is missing.'); + } elseif (! extension_loaded('hash')) { + throw new SecurityException('Missing "hash" extension to check the secret code validity.'); + } elseif (! $apiSecret) { + throw new SecurityException('Missing secret.'); + } - // check if the algo is supported - list($algo, $hash) = explode('=', $jsxcSignatureHeader, 2) + array( '', '' ); - if (! in_array($algo, hash_algos(), true)) { - throw new SecurityException("Hash algorithm '$algo' is not supported."); - } + // check if the algo is supported + list($algo, $hash) = explode('=', $jsxcSignatureHeader, 2) + [ '', '' ]; + if (! in_array($algo, hash_algos(), true)) { + throw new SecurityException("Hash algorithm '$algo' is not supported."); + } - // check if the key is valid - if ($hash !== hash_hmac($algo, $this->rawRequest->get(), $apiSecret)) { - throw new SecurityException('Signature does not match.'); - } - } + // check if the key is valid + if ($hash !== hash_hmac($algo, $this->rawRequest->get(), $apiSecret)) { + throw new SecurityException('Signature does not match.'); + } + } - public function afterException($controller, $methodName, \Exception $exception) - { - if($exception instanceof Exception) { - return new JSONResponse(array( - 'result' => 'error', - 'data' => array( - 'msg' => $exception->getMessage() - ) - ), Http::STATUS_INTERNAL_SERVER_ERROR); - } + public function afterException($controller, $methodName, \Exception $exception) + { + if ($exception instanceof Exception) { + return new JSONResponse([ + 'result' => 'error', + 'data' => [ + 'msg' => $exception->getMessage() + ] + ], Http::STATUS_INTERNAL_SERVER_ERROR); + } - throw $exception; - } + throw $exception; + } } diff --git a/lib/RawRequest.php b/lib/RawRequest.php index 0ebe9c0..61be367 100644 --- a/lib/RawRequest.php +++ b/lib/RawRequest.php @@ -2,8 +2,10 @@ namespace OCA\OJSXC; -class RawRequest { - public function get() { - return file_get_contents('php://input'); - } +class RawRequest +{ + public function get() + { + return file_get_contents('php://input'); + } } diff --git a/lib/Settings/Admin.php b/lib/Settings/Admin.php index 4b1cacb..87d7d0a 100644 --- a/lib/Settings/Admin.php +++ b/lib/Settings/Admin.php @@ -8,63 +8,64 @@ use OCP\IConfig; class Admin implements ISettings { - /** @var IConfig */ + /** @var IConfig */ private $config; - public function __construct(IConfig $config) { - $this->config = $config; - } + public function __construct(IConfig $config) + { + $this->config = $config; + } - /** - * @return TemplateResponse - */ - public function getForm() - { - $externalServices = $this->config->getAppValue('ojsxc', 'externalServices'); - $externalServices = explode("|", $externalServices); + /** + * @return TemplateResponse + */ + public function getForm() + { + $externalServices = $this->config->getAppValue('ojsxc', 'externalServices'); + $externalServices = explode("|", $externalServices); - $serverType = $this->config->getAppValue('ojsxc', 'serverType'); + $serverType = $this->config->getAppValue('ojsxc', 'serverType'); - $parameters = [ - 'serverType' => (!empty($serverType))? $serverType : 'internal', - 'boshUrl' => $this->config->getAppValue('ojsxc', 'boshUrl'), - 'xmppDomain' => $this->config->getAppValue('ojsxc', 'xmppDomain'), - 'xmppPreferMail' => $this->config->getAppValue('ojsxc', 'xmppPreferMail'), - 'xmppResource' => $this->config->getAppValue('ojsxc', 'xmppResource'), - 'xmppOverwrite' => $this->config->getAppValue('ojsxc', 'xmppOverwrite'), - 'xmppStartMinimized' => $this->config->getAppValue('ojsxc', 'xmppStartMinimized'), - 'iceUrl' => $this->config->getAppValue('ojsxc', 'iceUrl'), - 'iceUsername' => $this->config->getAppValue('ojsxc', 'iceUsername'), - 'iceCredential' => $this->config->getAppValue('ojsxc', 'iceCredential'), - 'iceSecret' => $this->config->getAppValue('ojsxc', 'iceSecret'), - 'iceTtl' => $this->config->getAppValue('ojsxc', 'iceTtl'), - 'firefoxExtension' => $this->config->getAppValue('ojsxc', 'firefoxExtension'), - 'chromeExtension' => $this->config->getAppValue('ojsxc', 'chromeExtension'), - 'timeLimitedToken' => $this->config->getAppValue('ojsxc', 'timeLimitedToken'), - 'externalServices' => $externalServices, - 'apiSecret' => $this->config->getAppValue('ojsxc', 'apiSecret') - ]; + $parameters = [ + 'serverType' => (!empty($serverType))? $serverType : 'internal', + 'boshUrl' => $this->config->getAppValue('ojsxc', 'boshUrl'), + 'xmppDomain' => $this->config->getAppValue('ojsxc', 'xmppDomain'), + 'xmppPreferMail' => $this->config->getAppValue('ojsxc', 'xmppPreferMail'), + 'xmppResource' => $this->config->getAppValue('ojsxc', 'xmppResource'), + 'xmppOverwrite' => $this->config->getAppValue('ojsxc', 'xmppOverwrite'), + 'xmppStartMinimized' => $this->config->getAppValue('ojsxc', 'xmppStartMinimized'), + 'iceUrl' => $this->config->getAppValue('ojsxc', 'iceUrl'), + 'iceUsername' => $this->config->getAppValue('ojsxc', 'iceUsername'), + 'iceCredential' => $this->config->getAppValue('ojsxc', 'iceCredential'), + 'iceSecret' => $this->config->getAppValue('ojsxc', 'iceSecret'), + 'iceTtl' => $this->config->getAppValue('ojsxc', 'iceTtl'), + 'firefoxExtension' => $this->config->getAppValue('ojsxc', 'firefoxExtension'), + 'chromeExtension' => $this->config->getAppValue('ojsxc', 'chromeExtension'), + 'timeLimitedToken' => $this->config->getAppValue('ojsxc', 'timeLimitedToken'), + 'externalServices' => $externalServices, + 'apiSecret' => $this->config->getAppValue('ojsxc', 'apiSecret') + ]; - return new TemplateResponse('ojsxc', 'settings/admin', $parameters); - } + return new TemplateResponse('ojsxc', 'settings/admin', $parameters); + } - /** - * @return string the section ID, e.g. 'sharing' - */ - public function getSection() - { - return 'ojsxc'; - } + /** + * @return string the section ID, e.g. 'sharing' + */ + public function getSection() + { + return 'ojsxc'; + } - /** - * @return int whether the form should be rather on the top or bottom of - * the admin section. The forms are arranged in ascending order of the - * priority values. It is required to return a value between 0 and 100. - * - * E.g.: 70 - */ - public function getPriority() - { - return 50; - } + /** + * @return int whether the form should be rather on the top or bottom of + * the admin section. The forms are arranged in ascending order of the + * priority values. It is required to return a value between 0 and 100. + * + * E.g.: 70 + */ + public function getPriority() + { + return 50; + } } diff --git a/lib/Settings/Section.php b/lib/Settings/Section.php index a103c4e..50fec5e 100644 --- a/lib/Settings/Section.php +++ b/lib/Settings/Section.php @@ -8,68 +8,68 @@ use OCP\Settings\ISection; class SectionBase implements ISection { - /** @var IL10N */ - private $l; + /** @var IL10N */ + private $l; - /** @var IURLGenerator */ - private $url; + /** @var IURLGenerator */ + private $url; - public function __construct(IL10N $l, IURLGenerator $url) - { - $this->l = $l; - $this->url = $url; - } + public function __construct(IL10N $l, IURLGenerator $url) + { + $this->l = $l; + $this->url = $url; + } - /** - * returns the ID of the section. It is supposed to be a lower case string, - * e.g. 'ldap' - * - * @returns string - */ - public function getID() - { - return 'ojsxc'; - } + /** + * returns the ID of the section. It is supposed to be a lower case string, + * e.g. 'ldap' + * + * @returns string + */ + public function getID() + { + return 'ojsxc'; + } - /** - * returns the translated name as it should be displayed, e.g. 'LDAP / AD - * integration'. Use the L10N service to translate it. - * - * @return string - */ - public function getName() - { - return 'JavaScript XMPP Client'; - } + /** + * returns the translated name as it should be displayed, e.g. 'LDAP / AD + * integration'. Use the L10N service to translate it. + * + * @return string + */ + public function getName() + { + return 'JavaScript XMPP Client'; + } - /** - * @return int whether the form should be rather on the top or bottom of - * the settings navigation. The sections are arranged in ascending order of - * the priority values. It is required to return a value between 0 and 99. - * - * E.g.: 70 - */ - public function getPriority() - { - return 50; - } + /** + * @return int whether the form should be rather on the top or bottom of + * the settings navigation. The sections are arranged in ascending order of + * the priority values. It is required to return a value between 0 and 99. + * + * E.g.: 70 + */ + public function getPriority() + { + return 50; + } - /** - * {@inheritdoc} - */ - public function getIcon() - { - return $this->url->imagePath('ojsxc', 'app-black.svg'); - } + /** + * {@inheritdoc} + */ + public function getIcon() + { + return $this->url->imagePath('ojsxc', 'app-black.svg'); + } } $version = \OCP\Util::getVersion(); if ($version[0] >= 12) { - class Section extends SectionBase implements \OCP\Settings\IIconSection - { - } + class Section extends SectionBase implements \OCP\Settings\IIconSection + { + } } else { - class Section extends SectionBase - { - } + class Section extends SectionBase + { + } } diff --git a/lib/TimeLimitedToken.php b/lib/TimeLimitedToken.php index 17bcefc..0a8cf08 100644 --- a/lib/TimeLimitedToken.php +++ b/lib/TimeLimitedToken.php @@ -2,37 +2,40 @@ namespace OCA\OJSXC; -class TimeLimitedToken { - public static function generateUser($node, $domain, $secret, $ttl = 60*60, $time = null) { - if (!isset($time) || $time === null) { - $time = time(); - } - - $jid = $node. '@' . $domain; - $expiry = $time + $ttl; - - $version = hex2bin('00'); - $secretID = substr(hash('sha256', $secret, true), 0, 2); - $header = $secretID.pack('N', $expiry); - $challenge = $version.$header.$jid; - $hmac = hash_hmac('sha256', $challenge, $secret, true); - $token = $version.substr($hmac, 0, 16).$header; - - // format as "user-friendly" base64 - $token = str_replace('=', '', strtr(base64_encode($token), - 'OIl', '-$%')); - - return $token; - } - - public static function generateTURN($uid, $secret, $ttl = 3600 * 24, $time = null) { - if (!isset($time) || $time === null) { - $time = time(); - } - - $username = ($time + $ttl).':'.$uid; - $credential = base64_encode(hash_hmac('sha1', $username, $secret, true)); - - return [$username, $credential]; - } +class TimeLimitedToken +{ + public static function generateUser($node, $domain, $secret, $ttl = 60 * 60, $time = null) + { + if (!isset($time) || $time === null) { + $time = time(); + } + + $jid = $node. '@' . $domain; + $expiry = $time + $ttl; + + $version = hex2bin('00'); + $secretID = substr(hash('sha256', $secret, true), 0, 2); + $header = $secretID.pack('N', $expiry); + $challenge = $version.$header.$jid; + $hmac = hash_hmac('sha256', $challenge, $secret, true); + $token = $version.substr($hmac, 0, 16).$header; + + // format as "user-friendly" base64 + $token = str_replace('=', '', strtr(base64_encode($token), + 'OIl', '-$%')); + + return $token; + } + + public static function generateTURN($uid, $secret, $ttl = 3600 * 24, $time = null) + { + if (!isset($time) || $time === null) { + $time = time(); + } + + $username = ($time + $ttl).':'.$uid; + $credential = base64_encode(hash_hmac('sha1', $username, $secret, true)); + + return [$username, $credential]; + } } diff --git a/lib/command/refreshroster.php b/lib/command/refreshroster.php index 46e20ee..f48d47d 100644 --- a/lib/command/refreshroster.php +++ b/lib/command/refreshroster.php @@ -9,7 +9,8 @@ use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; -class RefreshRoster extends Command { +class RefreshRoster extends Command +{ /** * @var IUserManager @@ -22,20 +23,21 @@ class RefreshRoster extends Command { private $rosterPush; public function __construct(IUserManager $userManager, - RosterPush $rosterPush) { + RosterPush $rosterPush) + { parent::__construct(); $this->userManager = $userManager; $this->rosterPush = $rosterPush; - } - protected function configure() { + protected function configure() + { $this->setName('ojsxc:refresh-roster'); $this->setDescription('Refresh the roster of all users'); } - protected function execute(InputInterface $input, OutputInterface $output) { - + protected function execute(InputInterface $input, OutputInterface $output) + { $users = $this->userManager->search(''); foreach ($users as $user) { @@ -44,5 +46,4 @@ class RefreshRoster extends Command { $output->writeln("<info>Refreshed " . count($users) . " rosters. </info>"); } - } diff --git a/lib/db/iqroster.php b/lib/db/iqroster.php index 6eb3f66..44b98c7 100644 --- a/lib/db/iqroster.php +++ b/lib/db/iqroster.php @@ -7,7 +7,6 @@ use Sabre\Xml\Writer; use Sabre\Xml\XmlDeserializable; use Sabre\Xml\XmlSerializable; - /** * This is an entity used by the IqHandler, but not stored/mapped in the database. * Class IQRoster @@ -20,7 +19,8 @@ use Sabre\Xml\XmlSerializable; * @method string getQid() * @method array getItems() */ -class IQRoster extends Stanza implements XmlSerializable{ +class IQRoster extends Stanza implements XmlSerializable +{ /** * @var string $type @@ -37,7 +37,8 @@ class IQRoster extends Stanza implements XmlSerializable{ */ public $items; - public function xmlSerialize(Writer $writer) { + public function xmlSerialize(Writer $writer) + { $writer->write([ [ 'name' => 'iq', @@ -61,7 +62,8 @@ class IQRoster extends Stanza implements XmlSerializable{ * @param string $jid * @param string $name */ - public function addItem($jid, $name){ + public function addItem($jid, $name) + { $this->items[] = [ "name" => "item", "attributes" => [ @@ -72,5 +74,4 @@ class IQRoster extends Stanza implements XmlSerializable{ "value" => '' ]; } - -}
\ No newline at end of file +} diff --git a/lib/db/iqrosterpush.php b/lib/db/iqrosterpush.php index 2138082..1d8b596 100644 --- a/lib/db/iqrosterpush.php +++ b/lib/db/iqrosterpush.php @@ -7,7 +7,6 @@ use Sabre\Xml\Writer; use Sabre\Xml\XmlDeserializable; use Sabre\Xml\XmlSerializable; - /** * This entity represents a roster push. * @see https://tools.ietf.org/html/rfc6121#section-2.1.6 @@ -21,7 +20,8 @@ use Sabre\Xml\XmlSerializable; * @method string getName() * @method string getSubscription() */ -class IQRosterPush extends Stanza implements XmlSerializable{ +class IQRosterPush extends Stanza implements XmlSerializable +{ /** * @var string jid of the user, when inserting this into the DB, only userid @@ -39,7 +39,8 @@ class IQRosterPush extends Stanza implements XmlSerializable{ */ public $subscription; - public function xmlSerialize(Writer $writer) { + public function xmlSerialize(Writer $writer) + { $writer->write([ [ 'name' => 'iq', @@ -66,5 +67,4 @@ class IQRosterPush extends Stanza implements XmlSerializable{ ] ]); } - -}
\ No newline at end of file +} diff --git a/lib/db/iqrosterpushmapper.php b/lib/db/iqrosterpushmapper.php index 6fe7491..1b72ef4 100644 --- a/lib/db/iqrosterpushmapper.php +++ b/lib/db/iqrosterpushmapper.php @@ -7,6 +7,6 @@ namespace OCA\OJSXC\Db; * * @package OCA\OJSXC\Db */ -class IQRosterPushMapper extends StanzaMapper { - -}
\ No newline at end of file +class IQRosterPushMapper extends StanzaMapper +{ +} diff --git a/lib/db/message.php b/lib/db/message.php index bf289dd..08f5656 100644 --- a/lib/db/message.php +++ b/lib/db/message.php @@ -15,7 +15,8 @@ use Sabre\Xml\XmlSerializable; * @method string getType() * @method array getValue() */ -class Message extends Stanza implements XmlSerializable{ +class Message extends Stanza implements XmlSerializable +{ /** * @var string $type @@ -27,7 +28,8 @@ class Message extends Stanza implements XmlSerializable{ */ public $value; - public function xmlSerialize(Writer $writer) { + public function xmlSerialize(Writer $writer) + { $writer->write([ [ 'name' => 'message', @@ -42,5 +44,4 @@ class Message extends Stanza implements XmlSerializable{ ] ]); } - -}
\ No newline at end of file +} diff --git a/lib/db/messagemapper.php b/lib/db/messagemapper.php index 9de2392..c3f2804 100644 --- a/lib/db/messagemapper.php +++ b/lib/db/messagemapper.php @@ -7,6 +7,6 @@ namespace OCA\OJSXC\Db; * * @package OCA\OJSXC\Db */ -class MessageMapper extends StanzaMapper { - -}
\ No newline at end of file +class MessageMapper extends StanzaMapper +{ +} diff --git a/lib/db/presence.php b/lib/db/presence.php index bf2cba7..08886b6 100644 --- a/lib/db/presence.php +++ b/lib/db/presence.php @@ -23,7 +23,8 @@ use Sabre\Xml\Element\keyValue; * @method string getPresence() * @method int getLastActive() */ -class Presence extends Stanza implements XmlSerializable, XmlDeserializable{ +class Presence extends Stanza implements XmlSerializable, XmlDeserializable +{ /** * @var string $userid @@ -40,14 +41,16 @@ class Presence extends Stanza implements XmlSerializable, XmlDeserializable{ */ public $lastActive; - public function __construct() { + public function __construct() + { $this->addType('lastActive', 'integer'); } /** * @param Writer $writer */ - public function xmlSerialize(Writer $writer) { + public function xmlSerialize(Writer $writer) + { if ($this->presence === 'online' || $this->presence === '') { $writer->write([ [ @@ -60,7 +63,7 @@ class Presence extends Stanza implements XmlSerializable, XmlDeserializable{ 'value' => null ] ]); - } else if ($this->presence === 'unavailable') { + } elseif ($this->presence === 'unavailable') { $writer->write([ [ 'name' => 'presence', @@ -99,7 +102,8 @@ class Presence extends Stanza implements XmlSerializable, XmlDeserializable{ * @param string $userId * @return Presence */ - public static function createFromXml(Reader $reader, $userId){ + public static function createFromXml(Reader $reader, $userId) + { $newElement = self::xmlDeserialize($reader); $newElement->setUserid($userId); return $newElement; @@ -109,13 +113,14 @@ class Presence extends Stanza implements XmlSerializable, XmlDeserializable{ * @param Reader $reader * @return Presence */ - public static function xmlDeserialize(Reader $reader) { + public static function xmlDeserialize(Reader $reader) + { $newElement = new self(); $attributes = $reader->parseAttributes(); $children = $reader->parseInnerTree(); if (key_exists('type', $attributes) && $attributes['type'] === 'unavailable') { $newElement->presence = 'unavailable'; - } else if (is_null($children)) { + } elseif (is_null($children)) { // this match elements which don't have children -> online $newElement->presence = 'online'; } else { @@ -134,6 +139,4 @@ class Presence extends Stanza implements XmlSerializable, XmlDeserializable{ $newElement->lastActive = time(); return $newElement; } - - -}
\ No newline at end of file +} diff --git a/lib/db/presencemapper.php b/lib/db/presencemapper.php index f0b5f31..3f7d819 100644 --- a/lib/db/presencemapper.php +++ b/lib/db/presencemapper.php @@ -14,7 +14,8 @@ use OCP\IDb; * * @package OCA\OJSXC\Db */ -class PresenceMapper extends Mapper { +class PresenceMapper extends Mapper +{ /** * @var bool this value indicates if we already have updated the presence @@ -69,7 +70,8 @@ class PresenceMapper extends Mapper { * @param NewContentContainer $newContentContainer * @param int $timeout */ - public function __construct(IDBConnection $db, $host, $userId, MessageMapper $messageMapper, NewContentContainer $newContentContainer, $timeout) { + public function __construct(IDBConnection $db, $host, $userId, MessageMapper $messageMapper, NewContentContainer $newContentContainer, $timeout) + { parent::__construct($db, 'ojsxc_presence'); $this->host = $host; $this->userId = $userId; @@ -82,7 +84,8 @@ class PresenceMapper extends Mapper { * @brief This function sets or update the presence of a user. * @param PresenceEntity $stanza */ - public function setPresence(PresenceEntity $stanza) { + public function setPresence(PresenceEntity $stanza) + { $sql = "UPDATE `*PREFIX*ojsxc_presence` SET `presence`=?, `last_active`=? WHERE `userid` = ?"; $q = $this->db->prepare($sql); @@ -101,10 +104,11 @@ class PresenceMapper extends Mapper { * the current user. * @return array */ - public function getPresences() { + public function getPresences() + { $stmt = $this->execute("SELECT * FROM `*PREFIX*ojsxc_presence` WHERE `userid` != ?", [$this->userId]); $results = []; - while($row = $stmt->fetch()){ + while ($row = $stmt->fetch()) { $row['from'] = $row['userid'] . '@' . $this->host . '/internal'; $row['to'] = $this->userId . '@' . $this->host . '/internal'; $results[] = $this->mapRowToEntity($row); @@ -124,7 +128,8 @@ class PresenceMapper extends Mapper { * and return it as an array of the userids. * @return array */ - public function getConnectedUsers() { + public function getConnectedUsers() + { if (!self::$fetchedConnectedUsers) { self::$fetchedConnectedUsers = true; @@ -146,7 +151,8 @@ class PresenceMapper extends Mapper { * @brief updates the last_active label in the DB. * @param the user to update the last_active field */ - public function setActive($user) { + public function setActive($user) + { // just do an update since we can assume the user is already online // otherwise this wouldn't make sense $sql = "UPDATE `*PREFIX*ojsxc_presence` SET `last_active`=? WHERE `userid` = ?"; @@ -159,7 +165,8 @@ class PresenceMapper extends Mapper { * @brief this function will update the presence of users who doesn't * contacted the server for $this->timeout seconds. */ - public function updatePresence() { + public function updatePresence() + { if (!self::$updatedPresence) { self::$updatedPresence = true; @@ -194,7 +201,6 @@ class PresenceMapper extends Mapper { $presenceToSend->setFrom($inactiveUser . '@' . $this->host . '/internal'); $this->newContentContainer->addStanza($presenceToSend); } - } } @@ -202,11 +208,11 @@ class PresenceMapper extends Mapper { * @brief Deletes the presence records of a user. * @param string $user */ - public function deletePresence($user) { + public function deletePresence($user) + { $sql = "DELETE FROM `*PREFIX*ojsxc_presence` WHERE `userid` = ?"; $q = $this->db->prepare($sql); $q->execute([$user]); - } -}
\ No newline at end of file +} diff --git a/lib/db/stanza.php b/lib/db/stanza.php index eae2929..673fd02 100644 --- a/lib/db/stanza.php +++ b/lib/db/stanza.php @@ -16,44 +16,50 @@ use Sabre\Xml\XmlSerializable; * @method string getStanza() * @method void setStanza($stanza) */ -class Stanza extends Entity implements XmlSerializable{ - - public function __construct($stanza='') { - $this->setStanza($stanza); - } +class Stanza extends Entity implements XmlSerializable +{ + public function __construct($stanza = '') + { + $this->setStanza($stanza); + } - /** - * @var string $to - */ - public $to; + /** + * @var string $to + */ + public $to; - /** - * @var string $to - */ - public $from; + /** + * @var string $to + */ + public $from; - /** - * @var string $stanza - */ - public $stanza; + /** + * @var string $stanza + */ + public $stanza; - public function getTo() { + public function getTo() + { return $this->to; } - public function setTo($userId) { + public function setTo($userId) + { $this->to = strtolower($userId); } - public function setFrom($userId) { + public function setFrom($userId) + { $this->from = strtolower($userId); } - public function getFrom() { + public function getFrom() + { return $this->from; } - public function xmlSerialize(Writer $writer) { - $writer->writeRaw($this->getStanza()); - } -}
\ No newline at end of file + public function xmlSerialize(Writer $writer) + { + $writer->writeRaw($this->getStanza()); + } +} diff --git a/lib/db/stanzamapper.php b/lib/db/stanzamapper.php index 820c9e9..6f7ae73 100644 --- a/lib/db/stanzamapper.php +++ b/lib/db/stanzamapper.php @@ -15,8 +15,8 @@ use Sabre\Xml\Writer; * * @package OCA\OJSXC\Db */ -class StanzaMapper extends Mapper { - +class StanzaMapper extends Mapper +{ private $host; /** @@ -30,7 +30,8 @@ class StanzaMapper extends Mapper { * @param IDBConnection $db * @param string $host */ - public function __construct(IDBConnection $db, $host, StanzaLogger $stanzaLogger) { + public function __construct(IDBConnection $db, $host, StanzaLogger $stanzaLogger) + { parent::__construct($db, 'ojsxc_stanzas'); $this->host = $host; $this->stanzaLogger = $stanzaLogger; @@ -40,7 +41,8 @@ class StanzaMapper extends Mapper { * @param Entity $entity * @return void */ - public function insert(Entity $entity) { + public function insert(Entity $entity) + { $writer = new Writer(); $writer->openMemory(); $writer->write($entity); @@ -59,10 +61,11 @@ class StanzaMapper extends Mapper { * @return Stanza[] * @throws DoesNotExistException */ - public function findByTo($to){ + public function findByTo($to) + { $stmt = $this->execute("SELECT stanza, id FROM *PREFIX*ojsxc_stanzas WHERE `to`=?", [$to]); $results = []; - while($row = $stmt->fetch()){ + while ($row = $stmt->fetch()) { $row['stanza'] = preg_replace('/to="([^"@]*)"/', "to=\"$1@" .$this->host ."/internal\"", $row['stanza']); $row['stanza'] = preg_replace('/from="([^"@]*)"/', "from=\"$1@" .$this->host ."/internal\"", $row['stanza']); $row['stanza'] = preg_replace('/jid="([^"@]*)"/', "jid=\"$1@" .$this->host ."/internal\"", $row['stanza']); @@ -70,11 +73,11 @@ class StanzaMapper extends Mapper { } $stmt->closeCursor(); - if (count($results) === 0){ + if (count($results) === 0) { throw new DoesNotExistException('Not Found'); } - foreach($results as $result){ + foreach ($results as $result) { $this->delete($result); } @@ -85,8 +88,8 @@ class StanzaMapper extends Mapper { * @brief Deletes all stanzas addressed to a user. * @param $uid */ - public function deleteByTo($uid) { + public function deleteByTo($uid) + { $this->execute("DELETE FROM *PREFIX*ojsxc_stanzas WHERE `to`=?", [$uid]); } - -}
\ No newline at end of file +} diff --git a/lib/dblock.php b/lib/dblock.php index d075577..e5e917d 100644 --- a/lib/dblock.php +++ b/lib/dblock.php @@ -11,7 +11,8 @@ use OCP\IDBConnection; * * @package OCA\OJSXC */ -class DbLock implements ILock { +class DbLock implements ILock +{ /** * @var IConfig $config */ @@ -33,26 +34,28 @@ class DbLock implements ILock { * @param string $userId * @param IConfig $config */ - public function __construct($userId, IConfig $config, IDBConnection $con) { + public function __construct($userId, IConfig $config, IDBConnection $con) + { $this->userId = $userId; $this->config = $config; $this->pollingId = time(); $this->con = $con; } - public function setLock() { + public function setLock() + { $this->config->setUserValue($this->userId, 'ojsxc', 'longpolling', $this->pollingId); } /** * @return bool */ - public function stillLocked() { + public function stillLocked() + { $sql = "SELECT `configvalue` FROM `*PREFIX*preferences` WHERE `userid` = ? AND `appid`='ojsxc' AND `configkey`='longpolling'"; $q = $this->con->prepare($sql); $q->execute([$this->userId]); $r = $q->fetch(); return (int)$r['configvalue'] === (int)$this->pollingId; } - } diff --git a/lib/hooks.php b/lib/hooks.php index e04ed7e..e59a0e6 100644 --- a/lib/hooks.php +++ b/lib/hooks.php @@ -11,7 +11,8 @@ use OCP\IUserManager; use OCP\IUser; use OCP\IUserSession; -class Hooks { +class Hooks +{ /** * @var IUserManager @@ -37,7 +38,8 @@ class Hooks { IUserSession $userSession, RosterPush $rosterPush, PresenceMapper $presenceMapper, - StanzaMapper $stanzaMapper) { + StanzaMapper $stanzaMapper) + { $this->userManager = $userManager; $this->userSession = $userSession; $this->rosterPush = $rosterPush; @@ -45,7 +47,8 @@ class Hooks { $this->stanzaMapper = $stanzaMapper; } - public function register() { + public function register() + { $this->userManager->listen('\OC\User', 'postCreateUser', [$this, 'onCreateUser']); $this->userManager->listen('\OC\User', 'postDelete', [$this, 'onDeleteUser']); $this->userSession->listen('\OC\User', 'changeUser', [$this, 'onChangeUser']); @@ -60,7 +63,8 @@ class Hooks { * @param IUser $user * @param string $password */ - public function onCreateUser(IUser $user, $password) { + public function onCreateUser(IUser $user, $password) + { $this->rosterPush->createOrUpdateRosterItem($user); } @@ -73,7 +77,8 @@ class Hooks { * @see https://tools.ietf.org/html/rfc6121#section-2.1.6 * @param IUser $user */ - public function onDeleteUser(IUser $user) { + public function onDeleteUser(IUser $user) + { $this->rosterPush->removeRosterItem($user); // delete the presence record of this user @@ -93,20 +98,19 @@ class Hooks { * @param string $feature feature which was changed. Enabled and displayName are supported. * @param string $value */ - public function onChangeUser(IUser $user, $feature, $value) { + public function onChangeUser(IUser $user, $feature, $value) + { if ($feature === "enabled") { if ($value === "true") { // if user is enabled, add to roster $this->onCreateUser($user, ''); - - } else if ($value === "false") { + } elseif ($value === "false") { // if user is enabled, remove from roster $this->onDeleteUser($user); } - } else if ($feature === "displayName") { + } elseif ($feature === "displayName") { // if the user was changed, resend the whole roster item $this->onCreateUser($user, ''); } } - -}
\ No newline at end of file +} diff --git a/lib/http/xmppresponse.php b/lib/http/xmppresponse.php index d89c524..349016f 100644 --- a/lib/http/xmppresponse.php +++ b/lib/http/xmppresponse.php @@ -11,7 +11,8 @@ use OCA\OJSXC\Db\Stanza; * * @package OCA\OJSXC\Http */ -class XMPPResponse extends Response { +class XMPPResponse extends Response +{ /** * @var Writer $writer @@ -29,9 +30,10 @@ class XMPPResponse extends Response { * @param Stanza|null $stanza * @param StanzaLogger $stanzaLogger */ - public function __construct(StanzaLogger $stanzaLogger, Stanza $stanza=null) { + public function __construct(StanzaLogger $stanzaLogger, Stanza $stanza = null) + { $this->addHeader('Content-Type', 'text/xml'); - $this->writer = new Writer(); + $this->writer = new Writer(); $this->writer->openMemory(); $this->writer->startElement('body'); $this->writer->writeAttribute('xmlns', 'http://jabber.org/protocol/httpbind'); @@ -44,7 +46,8 @@ class XMPPResponse extends Response { /** * @param Stanza $input */ - public function write(Stanza $input) { + public function write(Stanza $input) + { $this->stanzaLogger->log($input, StanzaLogger::SENDING); $this->writer->write($input); } @@ -52,9 +55,9 @@ class XMPPResponse extends Response { /** * @return string */ - public function render() { + public function render() + { $this->writer->endElement(); return $this->writer->outputMemory(); } - } diff --git a/lib/ilock.php b/lib/ilock.php index c0017e0..160e2f2 100644 --- a/lib/ilock.php +++ b/lib/ilock.php @@ -7,7 +7,8 @@ namespace OCA\OJSXC; * * @package OCA\OJSXC */ -interface ILock { +interface ILock +{ /** * @return void @@ -18,5 +19,4 @@ interface ILock { * @return bool */ public function stillLocked(); - -}
\ No newline at end of file +} diff --git a/lib/memlock.php b/lib/memlock.php index 9334141..111227d 100644 --- a/lib/memlock.php +++ b/lib/memlock.php @@ -9,7 +9,8 @@ use OCP\ICache; * * @package OCA\OJSXC */ -class MemLock implements ILock { +class MemLock implements ILock +{ /** * @var \OCP\ICache $memcache @@ -32,13 +33,15 @@ class MemLock implements ILock { * @param $userId * @param ICache $cache */ - public function __construct($userId, ICache $cache) { + public function __construct($userId, ICache $cache) + { $this->userId = $userId; $this->memcache = $cache; $this->pollingId = time(); } - public function setLock() { + public function setLock() + { $this->memcache->remove('-' . $this->userId . '-ojxsc-lock'); $this->memcache->add('-' . $this->userId . '-ojxsc-lock', $this->pollingId); } @@ -46,9 +49,9 @@ class MemLock implements ILock { /** * @return bool */ - public function stillLocked() { + public function stillLocked() + { $r = $this->memcache->get('-' . $this->userId . '-ojxsc-lock'); return $r === $this->pollingId; } - -}
\ No newline at end of file +} diff --git a/lib/newcontentcontainer.php b/lib/newcontentcontainer.php index 12b95ab..908bd07 100644 --- a/lib/newcontentcontainer.php +++ b/lib/newcontentcontainer.php @@ -11,25 +11,28 @@ use OCA\OJSXC\Db\Stanza; * without adding extra features/code to the `HTTPBindController` class. * @package OCA\OJSXC */ -class NewContentContainer { +class NewContentContainer +{ /** * @var Stanza[] */ private static $stanzas; - public function addStanza(Stanza $stanza) { + public function addStanza(Stanza $stanza) + { self::$stanzas[] = $stanza; } - public function getStanzas() { + public function getStanzas() + { $tmp = self::$stanzas; self::$stanzas = []; return $tmp; } - public function getCount() { + public function getCount() + { return count(self::$stanzas); } - -}
\ No newline at end of file +} diff --git a/lib/rosterpush.php b/lib/rosterpush.php index 6634540..c548be1 100644 --- a/lib/rosterpush.php +++ b/lib/rosterpush.php @@ -9,7 +9,8 @@ use OCP\IUserManager; use OCP\IUser; use OCP\IUserSession; -class RosterPush { +class RosterPush +{ /** * @var IUserManager @@ -30,7 +31,8 @@ class RosterPush { public function __construct(IUserManager $userManager, IUserSession $userSession, $host, - IQRosterPushMapper $iqRosterPushMapper) { + IQRosterPushMapper $iqRosterPushMapper) + { $this->userManager = $userManager; $this->userSession = $userSession; $this->host = $host; @@ -41,7 +43,8 @@ class RosterPush { * @see https://tools.ietf.org/html/rfc6121#section-2.1.6 * @param IUser $user */ - public function createOrUpdateRosterItem(IUser $user) { + public function createOrUpdateRosterItem(IUser $user) + { $iq = new IQRosterPush(); $iq->setJid($user->getUID()); $iq->setName($user->getDisplayName()); @@ -50,7 +53,7 @@ class RosterPush { foreach ($this->userManager->search('') as $recipient) { - if($recipient->getUID() !== $user->getUID()) { + if ($recipient->getUID() !== $user->getUID()) { $iq->setTo($recipient->getUID()); $this->iqRosterPushMapper->insert($iq); } @@ -61,7 +64,8 @@ class RosterPush { * @see https://tools.ietf.org/html/rfc6121#section-2.1.6 * @param IUser $user */ - public function removeRosterItem(IUser $user) { + public function removeRosterItem(IUser $user) + { $iq = new IQRosterPush(); $iq->setJid($user->getUID()); $iq->setName($user->getDisplayName()); @@ -70,10 +74,10 @@ class RosterPush { foreach ($this->userManager->search('') as $recipient) { - if($recipient->getUID() !== $user->getUID()) { + if ($recipient->getUID() !== $user->getUID()) { $iq->setTo($recipient->getUID()); $this->iqRosterPushMapper->insert($iq); } } } -}
\ No newline at end of file +} diff --git a/lib/stanzahandlers/iq.php b/lib/stanzahandlers/iq.php index 45fc13a..1d0aaba 100644 --- a/lib/stanzahandlers/iq.php +++ b/lib/stanzahandlers/iq.php @@ -12,7 +12,8 @@ use Sabre\Xml\Writer; * * @package OCA\OJSXC\StanzaHandlers */ -class IQ extends StanzaHandler { +class IQ extends StanzaHandler +{ /** * @var IUserManager @@ -26,7 +27,8 @@ class IQ extends StanzaHandler { * @param string $host * @param IUserManager $userManager */ - public function __construct($userId, $host, IUserManager $userManager) { + public function __construct($userId, $host, IUserManager $userManager) + { parent::__construct($userId, $host); $this->userManager = $userManager; } @@ -36,7 +38,8 @@ class IQ extends StanzaHandler { * @param array $stanza * @return IQRoster */ - public function handle(array $stanza) { + public function handle(array $stanza) + { $this->to = $this->getAttribute($stanza, 'to'); if ($stanza['value'][0]['name'] === '{jabber:iq:roster}query') { @@ -46,13 +49,11 @@ class IQ extends StanzaHandler { $iqRoster->setTo($this->from); $iqRoster->setQid($id); foreach ($this->userManager->search('') as $user) { - if($user->getUID() !== $this->userId) { + if ($user->getUID() !== $this->userId) { $iqRoster->addItem($user->getUID() . '@' . $this->host, $user->getDisplayName()); } } return $iqRoster; } - } - -}
\ No newline at end of file +} diff --git a/lib/stanzahandlers/message.php b/lib/stanzahandlers/message.php index 32585be..d5f203e 100644 --- a/lib/stanzahandlers/message.php +++ b/lib/stanzahandlers/message.php @@ -12,7 +12,8 @@ use OCA\OJSXC\Db\Message as MessageEntity; * * @package OCA\OJSXC\StanzaHandlers */ -class Message extends StanzaHandler { +class Message extends StanzaHandler +{ /** * @var MessageMapper $messageMapper @@ -41,7 +42,8 @@ class Message extends StanzaHandler { * @param string $host * @param MessageMapper $messageMapper */ - public function __construct($userId, $host, MessageMapper $messageMapper) { + public function __construct($userId, $host, MessageMapper $messageMapper) + { parent::__construct($userId, $host); $this->messageMapper = $messageMapper; } @@ -49,15 +51,16 @@ class Message extends StanzaHandler { /** * @param array $stanza */ - public function handle(array $stanza) { + public function handle(array $stanza) + { $to = $this->getAttribute($stanza, 'to'); $pos = strpos($to, '@'); $this->to = substr($to, 0, $pos); - foreach($stanza['value'] as $keyRaw=>$value) { + foreach ($stanza['value'] as $keyRaw => $value) { // remove namespace from key as it is unneeded and cause problems $key = substr($keyRaw, strpos($keyRaw, '}') + 1, strlen($keyRaw)); // fetch namespace from key to readd it - $ns = substr($keyRaw, 1, strpos($keyRaw, '}')-1); + $ns = substr($keyRaw, 1, strpos($keyRaw, '}') - 1); $this->values[] = [ "name" => $key, @@ -76,5 +79,4 @@ class Message extends StanzaHandler { $this->messageMapper->insert($message); $this->values = []; } - -}
\ No newline at end of file +} diff --git a/lib/stanzahandlers/presence.php b/lib/stanzahandlers/presence.php index 7da43c5..97a49c2 100644 --- a/lib/stanzahandlers/presence.php +++ b/lib/stanzahandlers/presence.php @@ -13,7 +13,8 @@ use OCA\OJSXC\Db\Presence as PresenceEntity; * * @package OCA\OJSXC\StanzaHandlers */ -class Presence extends StanzaHandler { +class Presence extends StanzaHandler +{ /** * @var PresenceMapper $presenceMapper @@ -33,7 +34,8 @@ class Presence extends StanzaHandler { * @param PresenceMapper $presenceMapper * @param MessageMapper $messageMapper */ - public function __construct($userId, $host, PresenceMapper $presenceMapper, MessageMapper $messageMapper) { + public function __construct($userId, $host, PresenceMapper $presenceMapper, MessageMapper $messageMapper) + { parent::__construct($userId, $host); $this->presenceMapper = $presenceMapper; $this->messageMapper = $messageMapper; @@ -48,7 +50,8 @@ class Presence extends StanzaHandler { * @param PresenceEntity $presence * @return PresenceEntity[] */ - public function handle(PresenceEntity $presence) { + public function handle(PresenceEntity $presence) + { // update the presence $this->presenceMapper->setPresence($presence); @@ -71,5 +74,4 @@ class Presence extends StanzaHandler { return []; } } - -}
\ No newline at end of file +} diff --git a/lib/stanzahandlers/stanzahandler.php b/lib/stanzahandlers/stanzahandler.php index ee6c79d..6b0d78f 100644 --- a/lib/stanzahandlers/stanzahandler.php +++ b/lib/stanzahandlers/stanzahandler.php @@ -9,7 +9,8 @@ use Sabre\Xml\Writer; * * @package OCA\OJSXC\StanzaHandlers */ -class StanzaHandler { +class StanzaHandler +{ /** * @var string $userId @@ -32,7 +33,8 @@ class StanzaHandler { * @param string 1$userId * @param string $host */ - public function __construct($userId, $host) { + public function __construct($userId, $host) + { $this->userId = $userId; $this->host = $host; $this->from = $this->userId; @@ -45,9 +47,8 @@ class StanzaHandler { * @param $attr * @return null|string */ - protected function getAttribute($stanza, $attr){ + protected function getAttribute($stanza, $attr) + { return isset($stanza['attributes'][$attr]) ? (string) $stanza['attributes'][$attr] : null; } - - } diff --git a/lib/stanzalogger.php b/lib/stanzalogger.php index 8711c69..fa1c41e 100644 --- a/lib/stanzalogger.php +++ b/lib/stanzalogger.php @@ -6,7 +6,8 @@ use OCA\OJSXC\Db\Stanza; use OCP\ILogger; use Sabre\Xml\Writer; -class StanzaLogger { +class StanzaLogger +{ /** * @var ILogger @@ -30,13 +31,14 @@ class StanzaLogger { private $userId; - public function __construct(ILogger $logger, $userId) { + public function __construct(ILogger $logger, $userId) + { $this->logger = $logger; $this->userId = $userId; - } - public function log(Stanza $stanza, $action) { + public function log(Stanza $stanza, $action) + { if (\OC::$server->getConfig()->getSystemValue('loglevel') === \OCP\Util::DEBUG) { // only serialize when needed $writer = new Writer(); @@ -46,7 +48,8 @@ class StanzaLogger { } } - public function logRaw($stanza, $action) { + public function logRaw($stanza, $action) + { $this->logger->debug($action . " {" . $this->userId . "} : " . $stanza, ["app" => "ojsxc"]); } -}
\ No newline at end of file +} diff --git a/settings/personal.php b/settings/personal.php index 63da6d8..4a366dd 100644 --- a/settings/personal.php +++ b/settings/personal.php @@ -11,15 +11,15 @@ $currentUID = \OC::$server->getUserSession()->getUser()->getUID(); $options = $config->getUserValue($currentUID, 'ojsxc', 'options'); if ($options !== null) { - $options = (array) json_decode($options, true); + $options = (array) json_decode($options, true); - if (is_array($options)) { - $loginFormEnable = true; - if (is_array($options['loginForm']) && isset($options['loginForm']['enable'])) { - $loginFormEnable = $options['loginForm']['enable']; - } - $tmpl->assign('loginFormEnable', $loginFormEnable); - } + if (is_array($options)) { + $loginFormEnable = true; + if (is_array($options['loginForm']) && isset($options['loginForm']['enable'])) { + $loginFormEnable = $options['loginForm']['enable']; + } + $tmpl->assign('loginFormEnable', $loginFormEnable); + } } return $tmpl->fetchPage(); diff --git a/tests/bootstrap-integration.php b/tests/bootstrap-integration.php index 852ed9f..fc7bc15 100644 --- a/tests/bootstrap-integration.php +++ b/tests/bootstrap-integration.php @@ -3,6 +3,5 @@ try { require_once __DIR__ . '/../../../tests/bootstrap.php'; } catch (Exception $ex) { require_once __DIR__ . '/../../../lib/base.php'; - } require_once __DIR__ . '/../vendor/autoload.php'; diff --git a/tests/bootstrap-unit.php b/tests/bootstrap-unit.php index 3ccb8db..d704aee 100644 --- a/tests/bootstrap-unit.php +++ b/tests/bootstrap-unit.php @@ -1,3 +1,3 @@ <?php require_once __DIR__ . '/../../../lib/base.php'; -require_once __DIR__ . '/../vendor/autoload.php';
\ No newline at end of file +require_once __DIR__ . '/../vendor/autoload.php'; diff --git a/tests/integration/DbLockTest.php b/tests/integration/DbLockTest.php index d157b48..d344c9f 100644 --- a/tests/integration/DbLockTest.php +++ b/tests/integration/DbLockTest.php @@ -8,7 +8,8 @@ use OCA\OJSXC\DbLock; $time = 0; -function time() { +function time() +{ global $time; return $time; } @@ -16,7 +17,8 @@ function time() { /** * @group DB */ -class DbLockTest extends TestCase { +class DbLockTest extends TestCase +{ /** * @var \OCA\OJSXC\DbLock @@ -39,7 +41,8 @@ class DbLockTest extends TestCase { */ private $container; - public function setUp() { + public function setUp() + { parent::setUp(); $app = new Application(); $this->container = $app->getContainer(); @@ -51,7 +54,8 @@ class DbLockTest extends TestCase { * Tests the setLock and stillLocked function by setting up and lock * and then setting a new lock. */ - public function testLock() { + public function testLock() + { global $time; $time = 4; $this->dbLock = new DbLock( @@ -86,20 +90,19 @@ class DbLockTest extends TestCase { $this->assertEquals($result[0]['configkey'], 'longpolling'); $this->assertEquals($result[0]['configvalue'], '5'); $this->assertTrue($this->dbLock2->stillLocked()); - } - private function fetchLocks() { + private function fetchLocks() + { $stmt = $this->con->executeQuery("SELECT * FROM `*PREFIX*preferences` WHERE `appid`='ojsxc' AND `configkey`='longpolling'"); $reuslt = []; - while($row = $stmt->fetch()){ + while ($row = $stmt->fetch()) { $result[] = $row; } return $result; } - -}
\ No newline at end of file +} diff --git a/tests/integration/MemLockTest.php b/tests/integration/MemLockTest.php index 3ab1c16..f29df59 100644 --- a/tests/integration/MemLockTest.php +++ b/tests/integration/MemLockTest.php @@ -13,7 +13,8 @@ use OCA\OJSXC\MemLock; /** * @group DB */ -class MemLockTest extends TestCase { +class MemLockTest extends TestCase +{ /** * @var \OCA\OJSXC\MemLock @@ -37,7 +38,8 @@ class MemLockTest extends TestCase { public static $time; - public function setUp() { + public function setUp() + { parent::setUp(); $app = new Application(); $this->container = $app->getContainer(); @@ -46,14 +48,14 @@ class MemLockTest extends TestCase { if ($version[0] === 8 && $version[1] == 0) { $this->markTestSkipped(); } - } /** * Tests the setLock and stillLocked function by setting up and lock * and then setting a new lock. */ - public function testLock() { + public function testLock() + { global $time; $time = 4; $cache = $this->container->getServer()->getMemCacheFactory(); @@ -87,11 +89,10 @@ class MemLockTest extends TestCase { $this->assertTrue($this->memLock2->stillLocked()); $result = $this->fetchLock(); $this->assertEquals('5', $result); - } - private function fetchLock() { + private function fetchLock() + { return $this->memCache->get('-john-ojxsc-lock'); } - -}
\ No newline at end of file +} diff --git a/tests/integration/db/IqRosterTest.php b/tests/integration/db/IqRosterTest.php index f2613c7..beb60bb 100644 --- a/tests/integration/db/IqRosterTest.php +++ b/tests/integration/db/IqRosterTest.php @@ -4,12 +4,13 @@ namespace OCA\OJSXC\Db; use Sabre\Xml\Writer; use OCA\OJSXC\Utility\TestCase; -class IqRosterTest extends TestCase { - - public function testIqRoster() { +class IqRosterTest extends TestCase +{ + public function testIqRoster() + { $expected = '<body xmlns="http://jabber.org/protocol/httpbind"><iq to="john@localhost" type="result" id="4434"><query xmlns="jabber:iq:roster"><item jid="test@test.be" name="Test Test" subscription="both"></item><item jid="test2@test.be" name="Test2 Test" subscription="both"></item></query></iq></body>'; - $writer = new Writer(); + $writer = new Writer(); $writer->openMemory(); $writer->startElement('body'); $writer->writeAttribute('xmlns', 'http://jabber.org/protocol/httpbind'); @@ -24,7 +25,7 @@ class IqRosterTest extends TestCase { $this->assertEquals($iqRoster->getType(), 'result'); $this->assertEquals($iqRoster->getTo(), 'john@localhost'); $this->assertEquals($iqRoster->getQid(), 4434); - $this->assertEquals($iqRoster->getItems(), [ + $this->assertEquals($iqRoster->getItems(), [ [ "name" => "item", "attributes" => [ @@ -52,5 +53,4 @@ class IqRosterTest extends TestCase { $this->assertEquals($expected, $result); } - } diff --git a/tests/integration/db/MessageMapperTest.php b/tests/integration/db/MessageMapperTest.php index e4d3a9a..3aa1ce6 100644 --- a/tests/integration/db/MessageMapperTest.php +++ b/tests/integration/db/MessageMapperTest.php @@ -5,7 +5,8 @@ namespace OCA\OJSXC\Db; use OCA\OJSXC\Utility\MapperTestUtility; use OCP\AppFramework\Db\DoesNotExistException; -function uniqid() { +function uniqid() +{ return 4; // chosen by fair dice roll. // guaranteed to be unique. } @@ -13,20 +14,23 @@ function uniqid() { /** * @group DB */ -class MessageMapperTest extends MapperTestUtility { +class MessageMapperTest extends MapperTestUtility +{ /** * @var StanzaMapper */ protected $mapper; - protected function setUp() { + protected function setUp() + { $this->entityName = 'OCA\OJSXC\Db\Message'; $this->mapperName = 'MessageMapper'; parent::setUp(); } - public function insertProvider() { + public function insertProvider() + { return [ [ 'john@localhost', @@ -42,7 +46,8 @@ class MessageMapperTest extends MapperTestUtility { /** * @dataProvider insertProvider */ - public function testInsert($from, $to, $data, $type, $msg, $expectedStanza) { + public function testInsert($from, $to, $data, $type, $msg, $expectedStanza) + { $stanza = new Message(); $stanza->setFrom($from); $stanza->setTo($to); @@ -61,22 +66,24 @@ class MessageMapperTest extends MapperTestUtility { $this->assertCount(1, $result); $this->assertEquals($stanza->getFrom(), $result[0]->getFrom()); - $this->assertEquals($stanza->getTo(), $result[0]->getTo()); - $this->assertEquals($expectedStanza, $result[0]->getStanza()); - $this->assertEquals(null, $result[0]->getType()); // type is saved into the XML string, not the DB. + $this->assertEquals($stanza->getTo(), $result[0]->getTo()); + $this->assertEquals($expectedStanza, $result[0]->getStanza()); + $this->assertEquals(null, $result[0]->getType()); // type is saved into the XML string, not the DB. } /** * @expectedException \OCP\AppFramework\Db\DoesNotExistException */ - public function testFindByToNotFound() { + public function testFindByToNotFound() + { $this->mapper->findByTo('test'); } /** * @expectedException \OCP\AppFramework\Db\DoesNotExistException */ - public function testFindByToNotFound2() { + public function testFindByToNotFound2() + { $stanza = new Message(); $stanza->setFrom('john@localhost'); $stanza->setTo('john@localhost'); @@ -88,7 +95,8 @@ class MessageMapperTest extends MapperTestUtility { $this->mapper->findByTo('test'); } - public function testFindByToFound() { + public function testFindByToFound() + { $stanza1 = new Message(); $stanza1->setFrom('jan@localhost'); $stanza1->setTo('john@localhost'); @@ -113,15 +121,13 @@ class MessageMapperTest extends MapperTestUtility { // check findByTo $result = $this->mapper->findByTo('john@localhost'); $this->assertCount(1, $result); - $this->assertEquals('<message to="john@localhost" from="jan@localhost" type="test" xmlns="jabber:client" id="4-msg">Messageabc</message>', $result[0]->getStanza()); + $this->assertEquals('<message to="john@localhost" from="jan@localhost" type="test" xmlns="jabber:client" id="4-msg">Messageabc</message>', $result[0]->getStanza()); // check if element is deleted $result = $this->fetchAll(); $this->assertCount(1, $result); $this->assertEquals($stanza2->getFrom(), $result[0]->getFrom()); - $this->assertEquals($stanza2->getTo(), $result[0]->getTo()); - $this->assertEquals('<message to="jan@localhost" from="thomas@localhost" type="test2" xmlns="jabber:client" id="4-msg">Message</message>', $result[0]->getStanza()); - + $this->assertEquals($stanza2->getTo(), $result[0]->getTo()); + $this->assertEquals('<message to="jan@localhost" from="thomas@localhost" type="test2" xmlns="jabber:client" id="4-msg">Message</message>', $result[0]->getStanza()); } - -}
\ No newline at end of file +} diff --git a/tests/integration/db/PresenceMapperTest.php b/tests/integration/db/PresenceMapperTest.php index 4be8a0e..11968c1 100644 --- a/tests/integration/db/PresenceMapperTest.php +++ b/tests/integration/db/PresenceMapperTest.php @@ -8,7 +8,8 @@ use OCA\OJSXC\Utility\MapperTestUtility; $time = 0; -function time() { +function time() +{ global $time; return $time; } @@ -17,7 +18,8 @@ function time() { /** * @group DB */ -class PresenceMapperTest extends MapperTestUtility { +class PresenceMapperTest extends MapperTestUtility +{ /** * @var PresenceMapper @@ -29,7 +31,8 @@ class PresenceMapperTest extends MapperTestUtility { */ protected $newContentContainer; - protected function setUp() { + protected function setUp() + { $this->entityName = 'OCA\OJSXC\Db\Presence'; $this->mapperName = 'PresenceMapper'; parent::setUp(); @@ -43,7 +46,8 @@ class PresenceMapperTest extends MapperTestUtility { /** * @return array */ - public function presenceIfNotExitsProvider() { + public function presenceIfNotExitsProvider() + { $input1 = new PresenceEntity(); $input1->setPresence('online'); $input1->setUserid('admin'); @@ -90,7 +94,8 @@ class PresenceMapperTest extends MapperTestUtility { * @param PresenceEntity[] $inputs * @param array $expected */ - public function testSetPresenceIfNotExists($inputs, $expected) { + public function testSetPresenceIfNotExists($inputs, $expected) + { foreach ($inputs as $input) { $this->mapper->setPresence($input); } @@ -102,7 +107,8 @@ class PresenceMapperTest extends MapperTestUtility { /** * @return array */ - public function presenceIfExitsProvider() { + public function presenceIfExitsProvider() + { $input1 = new PresenceEntity(); $input1->setPresence('online'); $input1->setUserid('admin'); @@ -158,7 +164,8 @@ class PresenceMapperTest extends MapperTestUtility { * @param PresenceEntity[] $inputs * @param array $expected */ - public function testSetPresenceIfExists($inputs, $expected) { + public function testSetPresenceIfExists($inputs, $expected) + { foreach ($inputs as $input) { $this->mapper->setPresence($input); } @@ -168,7 +175,8 @@ class PresenceMapperTest extends MapperTestUtility { $this->assertArrayDbResultsEqual($expected, $result, ['userid', 'presence', 'last_active']); } - public function getPresenceProvider() { + public function getPresenceProvider() + { $input1 = new PresenceEntity(); $input1->setPresence('online'); $input1->setUserid('admin'); @@ -221,7 +229,8 @@ class PresenceMapperTest extends MapperTestUtility { * @param $inputs * @param $expected */ - public function testGetPresence($inputs, $expected) { + public function testGetPresence($inputs, $expected) + { foreach ($inputs as $input) { $this->mapper->setPresence($input); } @@ -231,7 +240,8 @@ class PresenceMapperTest extends MapperTestUtility { $this->assertObjectDbResultsEqual($expected, $result, ['userid', 'presence', 'lastActive', 'to', 'from']); } - public function getConnectedUsersProvider() { + public function getConnectedUsersProvider() + { $input1 = new PresenceEntity(); $input1->setPresence('online'); $input1->setUserid('admin'); @@ -273,7 +283,8 @@ class PresenceMapperTest extends MapperTestUtility { /** * @dataProvider getConnectedUsersProvider */ - public function testGetConnectedUsers($inputs, $expected) { + public function testGetConnectedUsers($inputs, $expected) + { foreach ($inputs as $input) { $this->mapper->setPresence($input); } @@ -286,7 +297,8 @@ class PresenceMapperTest extends MapperTestUtility { $this->assertEquals($expected, $result); } - public function updatePresenceProvider() { + public function updatePresenceProvider() + { $input1 = new PresenceEntity(); $input1->setPresence('online'); $input1->setUserid('admin'); @@ -370,8 +382,8 @@ class PresenceMapperTest extends MapperTestUtility { * @param int $expNewContentCount * @param array $expStanzasToSend */ - public function testUpdatePresence($inputs, $expInput, $expConnectedUsers, $expNewContent, $expNewContentCount, $expStanzasToSend) { - + public function testUpdatePresence($inputs, $expInput, $expConnectedUsers, $expNewContent, $expNewContentCount, $expStanzasToSend) + { global $time; $time = 1000; foreach ($inputs as $input) { @@ -396,10 +408,10 @@ class PresenceMapperTest extends MapperTestUtility { $stanzasToSend = $this->fetchAllAsArray('*PREFIX*ojsxc_stanzas'); $this->assertArrayDbResultsEqual($expStanzasToSend, $stanzasToSend, ['to', 'from', 'stanza']); - } - public function setActiveProvider() { + public function setActiveProvider() + { $input1 = new PresenceEntity(); $input1->setPresence('online'); $input1->setUserid('admin'); @@ -452,7 +464,8 @@ class PresenceMapperTest extends MapperTestUtility { /** * @dataProvider setActiveProvider */ - public function testSetActive($inputs, $expected) { + public function testSetActive($inputs, $expected) + { global $time; foreach ($inputs as $input) { @@ -466,7 +479,5 @@ class PresenceMapperTest extends MapperTestUtility { $result = $this->fetchAllAsArray(); $this->assertArrayDbResultsEqual($expected, $result, ['userid', 'last_active', 'presence']); - } - -}
\ No newline at end of file +} diff --git a/tests/integration/db/PresenceTest.php b/tests/integration/db/PresenceTest.php index b92af60..7c7bfa0 100644 --- a/tests/integration/db/PresenceTest.php +++ b/tests/integration/db/PresenceTest.php @@ -8,13 +8,14 @@ use Sabre\Xml\LibXMLException; use Sabre\Xml\ParseException; use OCA\OJSXC\Utility\TestCase; -class PresenceTest extends TestCase{ - - private function generateFactoryData($xml, $from, $to, $presence, $userId) { +class PresenceTest extends TestCase +{ + private function generateFactoryData($xml, $from, $to, $presence, $userId) + { $reader = new Reader(); $reader->xml($xml); $reader->elementMap = [ - '{jabber:client}presence' => function(Reader $reader) use ($userId) { + '{jabber:client}presence' => function (Reader $reader) use ($userId) { return Presence::createFromXml($reader, $userId); } ]; @@ -30,10 +31,10 @@ class PresenceTest extends TestCase{ $userId, $expected ]; - } - public function factoryProvider() { + public function factoryProvider() + { return [ $this->generateFactoryData("<presence xmlns='jabber:client' type='unavailable'/>", null, null, 'unavailable', 'admin'), $this->generateFactoryData("<presence xmlns='jabber:client' type='unavailable'></presence>", null, null, 'unavailable', 'admin'), @@ -52,7 +53,8 @@ class PresenceTest extends TestCase{ /** * @dataProvider factoryProvider */ - public function testFactory($reader, $userid, Presence $expectedElement) { + public function testFactory($reader, $userid, Presence $expectedElement) + { $result = $reader->parse(); $result = $result['value']; $this->assertEquals($expectedElement->getTo(), $result->getTo()); @@ -62,8 +64,9 @@ class PresenceTest extends TestCase{ } - private function generateSerializeData($to, $from, $presence, $expected) { - $writer = new Writer(); + private function generateSerializeData($to, $from, $presence, $expected) + { + $writer = new Writer(); $writer->openMemory(); $writer->startElement('body'); $writer->writeAttribute('xmlns', 'http://jabber.org/protocol/httpbind'); @@ -82,7 +85,8 @@ class PresenceTest extends TestCase{ $presence ]; } - public function serializeProvider() { + public function serializeProvider() + { return [ $this->generateSerializeData('admin@own.dev', 'derp@own.dev', 'chat', '<body xmlns="http://jabber.org/protocol/httpbind"><presence from="derp@own.dev" to="admin@own.dev" xmlns="jabber:client"><show>chat</show></presence></body>'), $this->generateSerializeData('admin@own.dev', 'derp@own.dev', 'online', '<body xmlns="http://jabber.org/protocol/httpbind"><presence from="derp@own.dev" to="admin@own.dev" xmlns="jabber:client" /></body>'), @@ -97,7 +101,8 @@ class PresenceTest extends TestCase{ /** * @dataProvider serializeProvider */ - public function testSerialize(Writer $writer, Presence $presenceEntity, $expected, $to, $from, $presence) { + public function testSerialize(Writer $writer, Presence $presenceEntity, $expected, $to, $from, $presence) + { $writer->write($presenceEntity); $writer->endElement(); $result = $writer->outputMemory(); @@ -107,4 +112,4 @@ class PresenceTest extends TestCase{ $this->assertEquals($presence, $presenceEntity->getPresence()); $this->assertSabreXmlEqualsXml($expected, $result); } -}
\ No newline at end of file +} diff --git a/tests/integration/db/StanzaMapperTest.php b/tests/integration/db/StanzaMapperTest.php index b4385b5..a2c09b0 100644 --- a/tests/integration/db/StanzaMapperTest.php +++ b/tests/integration/db/StanzaMapperTest.php @@ -8,20 +8,23 @@ use OCP\AppFramework\Db\DoesNotExistException; /** * @group DB */ -class StanzaMapperTest extends MapperTestUtility { +class StanzaMapperTest extends MapperTestUtility +{ /** * @var StanzaMapper */ protected $mapper; - protected function setUp() { + protected function setUp() + { $this->entityName = 'OCA\OJSXC\Db\Stanza'; $this->mapperName = 'StanzaMapper'; parent::setUp(); } - public function insertProvider() { + public function insertProvider() + { return [ [ 'john@localhost', @@ -34,7 +37,8 @@ class StanzaMapperTest extends MapperTestUtility { /** * @dataProvider insertProvider */ - public function testInsert($from, $to, $data) { + public function testInsert($from, $to, $data) + { $stanza = new Stanza(); $stanza->setFrom($from); $stanza->setTo($to); @@ -50,21 +54,23 @@ class StanzaMapperTest extends MapperTestUtility { $this->assertCount(1, $result); $this->assertEquals($stanza->getFrom(), $result[0]->getFrom()); - $this->assertEquals($stanza->getTo(), $result[0]->getTo()); - $this->assertEquals($stanza->getStanza(), $result[0]->getStanza()); + $this->assertEquals($stanza->getTo(), $result[0]->getTo()); + $this->assertEquals($stanza->getStanza(), $result[0]->getStanza()); } /** * @expectedException \OCP\AppFramework\Db\DoesNotExistException */ - public function testFindByToNotFound() { + public function testFindByToNotFound() + { $this->mapper->findByTo('test'); } /** * @expectedException \OCP\AppFramework\Db\DoesNotExistException */ - public function testFindByToNotFound2() { + public function testFindByToNotFound2() + { $stanza = new Stanza(); $stanza->setFrom('john@localhost'); $stanza->setTo('john@localhost'); @@ -74,7 +80,8 @@ class StanzaMapperTest extends MapperTestUtility { $this->mapper->findByTo('test'); } - public function testFindByToFound() { + public function testFindByToFound() + { $stanza1 = new Stanza(); $stanza1->setFrom('jan@localhost'); $stanza1->setTo('john@localhost'); @@ -95,15 +102,13 @@ class StanzaMapperTest extends MapperTestUtility { // check findByTo $result = $this->mapper->findByTo('john@localhost'); $this->assertCount(1, $result); - $this->assertEquals($stanza1->getStanza(), $result[0]->getStanza()); + $this->assertEquals($stanza1->getStanza(), $result[0]->getStanza()); // check if element is deleted $result = $this->fetchAll(); $this->assertCount(1, $result); $this->assertEquals($stanza2->getFrom(), $result[0]->getFrom()); - $this->assertEquals($stanza2->getTo(), $result[0]->getTo()); - $this->assertEquals($stanza2->getStanza(), $result[0]->getStanza()); - + $this->assertEquals($stanza2->getTo(), $result[0]->getTo()); + $this->assertEquals($stanza2->getStanza(), $result[0]->getStanza()); } - -}
\ No newline at end of file +} diff --git a/tests/travis/autoconfig-stable8-mysql.php b/tests/travis/autoconfig-stable8-mysql.php index 517d0e5..a4aab54 100644 --- a/tests/travis/autoconfig-stable8-mysql.php +++ b/tests/travis/autoconfig-stable8-mysql.php @@ -1,5 +1,5 @@ <?php -$AUTOCONFIG = array ( +$AUTOCONFIG = [ 'installed' => false, 'dbtype' => 'mysql', 'dbtableprefix' => 'oc_', @@ -10,5 +10,4 @@ $AUTOCONFIG = array ( 'dbhost' => 'localhost', 'dbpass' => '', 'directory' => getcwd() . '/data', -); - +]; diff --git a/tests/unit/Middleware/ExternalApiMiddlewareTest.php b/tests/unit/Middleware/ExternalApiMiddlewareTest.php index 5af16ae..2fa90c4 100644 --- a/tests/unit/Middleware/ExternalApiMiddlewareTest.php +++ b/tests/unit/Middleware/ExternalApiMiddlewareTest.php @@ -10,142 +10,150 @@ use OCP\IRequest; use OCP\IConfig; use PHPUnit\Framework\TestCase; -class ExternalApiMiddlewareTest extends TestCase { - private $request; - private $config; - private $rawRequest; - private $externalApiMiddleware; - - public function setUp() { - parent::setUp(); - - $this->request = $this->createMock(IRequest::class); - $this->config = $this->createMock(IConfig::class); - $this->rawRequest = $this->createMock(RawRequest::class); - - $this->externalApiMiddleware = new ExternalApiMiddleware( - $this->request, - $this->config, - $this->rawRequest - ); - } - - public function testBeforeControllerWithoutHeader() { - $this->request - ->expects($this->once()) - ->method('getHeader') - ->with('X-JSXC-SIGNATURE') - ->willReturn(null); - - $this->expectException(SecurityException::class); - $this->expectExceptionMessage('HTTP header "X-JSXC-Signature" is missing.'); - - $controller = $this->createMock(SignatureProtectedApiController::class); - $this->externalApiMiddleware->beforeController($controller, 'someMethod'); - } - - public function testBeforeControllerWithoutSecret() { - $this->request - ->expects($this->once()) - ->method('getHeader') - ->with('X-JSXC-SIGNATURE') - ->willReturn('foo=bar'); - $this->config - ->expects($this->once()) - ->method('getAppValue') - ->with('ojsxc', 'apiSecret') - ->willReturn(null); - - $this->expectException(SecurityException::class); - $this->expectExceptionMessage('Missing secret.'); - - $controller = $this->createMock(SignatureProtectedApiController::class); - $this->externalApiMiddleware->beforeController($controller, 'someMethod'); - } - - public function testBeforeControllerWithUnsupportedAlgo() { - $this->request - ->expects($this->once()) - ->method('getHeader') - ->with('X-JSXC-SIGNATURE') - ->willReturn('foo=bar'); - $this->config - ->expects($this->once()) - ->method('getAppValue') - ->with('ojsxc', 'apiSecret') - ->willReturn('secret'); - - $this->expectException(SecurityException::class); - $this->expectExceptionMessage('Hash algorithm \'foo\' is not supported.'); - - $controller = $this->createMock(SignatureProtectedApiController::class); - $this->externalApiMiddleware->beforeController($controller, 'someMethod'); - } - - public function testBeforeControllerWithInvalidHeaderFormat() { - $this->request - ->expects($this->once()) - ->method('getHeader') - ->with('X-JSXC-SIGNATURE') - ->willReturn('foobar'); - $this->config - ->expects($this->once()) - ->method('getAppValue') - ->with('ojsxc', 'apiSecret') - ->willReturn('secret'); - - $this->expectException(SecurityException::class); - $this->expectExceptionMessage('Hash algorithm \'foobar\' is not supported.'); - - $controller = $this->createMock(SignatureProtectedApiController::class); - $this->externalApiMiddleware->beforeController($controller, 'someMethod'); - } - - public function testBeforeControllerWithInvalidHeader() { - $this->request - ->expects($this->once()) - ->method('getHeader') - ->with('X-JSXC-SIGNATURE') - ->willReturn('sha1=foobar'); - $this->config - ->expects($this->once()) - ->method('getAppValue') - ->with('ojsxc', 'apiSecret') - ->willReturn('secret'); - $this->rawRequest - ->expects($this->once()) - ->method('get') - ->willReturn('asdf'); - - $this->expectException(SecurityException::class); - $this->expectExceptionMessage('Signature does not match.'); - - $controller = $this->createMock(SignatureProtectedApiController::class); - $this->externalApiMiddleware->beforeController($controller, 'someMethod'); - } - - public function testBeforeControllerWithValidHeader() { - $algo = 'sha1'; - $apiSecret = 'secret'; - $rawRequestBody = 'rawRequestBody'; - $hash = hash_hmac($algo, $rawRequestBody, $apiSecret); - - $this->request - ->expects($this->once()) - ->method('getHeader') - ->with('X-JSXC-SIGNATURE') - ->willReturn($algo.'='.$hash); - $this->config - ->expects($this->once()) - ->method('getAppValue') - ->with('ojsxc', 'apiSecret') - ->willReturn($apiSecret); - $this->rawRequest - ->expects($this->once()) - ->method('get') - ->willReturn($rawRequestBody); - - $controller = $this->createMock(SignatureProtectedApiController::class); - $this->externalApiMiddleware->beforeController($controller, 'someMethod'); - } +class ExternalApiMiddlewareTest extends TestCase +{ + private $request; + private $config; + private $rawRequest; + private $externalApiMiddleware; + + public function setUp() + { + parent::setUp(); + + $this->request = $this->createMock(IRequest::class); + $this->config = $this->createMock(IConfig::class); + $this->rawRequest = $this->createMock(RawRequest::class); + + $this->externalApiMiddleware = new ExternalApiMiddleware( + $this->request, + $this->config, + $this->rawRequest + ); + } + + public function testBeforeControllerWithoutHeader() + { + $this->request + ->expects($this->once()) + ->method('getHeader') + ->with('X-JSXC-SIGNATURE') + ->willReturn(null); + + $this->expectException(SecurityException::class); + $this->expectExceptionMessage('HTTP header "X-JSXC-Signature" is missing.'); + + $controller = $this->createMock(SignatureProtectedApiController::class); + $this->externalApiMiddleware->beforeController($controller, 'someMethod'); + } + + public function testBeforeControllerWithoutSecret() + { + $this->request + ->expects($this->once()) + ->method('getHeader') + ->with('X-JSXC-SIGNATURE') + ->willReturn('foo=bar'); + $this->config + ->expects($this->once()) + ->method('getAppValue') + ->with('ojsxc', 'apiSecret') + ->willReturn(null); + + $this->expectException(SecurityException::class); + $this->expectExceptionMessage('Missing secret.'); + + $controller = $this->createMock(SignatureProtectedApiController::class); + $this->externalApiMiddleware->beforeController($controller, 'someMethod'); + } + + public function testBeforeControllerWithUnsupportedAlgo() + { + $this->request + ->expects($this->once()) + ->method('getHeader') + ->with('X-JSXC-SIGNATURE') + ->willReturn('foo=bar'); + $this->config + ->expects($this->once()) + ->method('getAppValue') + ->with('ojsxc', 'apiSecret') + ->willReturn('secret'); + + $this->expectException(SecurityException::class); + $this->expectExceptionMessage('Hash algorithm \'foo\' is not supported.'); + + $controller = $this->createMock(SignatureProtectedApiController::class); + $this->externalApiMiddleware->beforeController($controller, 'someMethod'); + } + + public function testBeforeControllerWithInvalidHeaderFormat() + { + $this->request + ->expects($this->once()) + ->method('getHeader') + ->with('X-JSXC-SIGNATURE') + ->willReturn('foobar'); + $this->config + ->expects($this->once()) + ->method('getAppValue') + ->with('ojsxc', 'apiSecret') + ->willReturn('secret'); + + $this->expectException(SecurityException::class); + $this->expectExceptionMessage('Hash algorithm \'foobar\' is not supported.'); + + $controller = $this->createMock(SignatureProtectedApiController::class); + $this->externalApiMiddleware->beforeController($controller, 'someMethod'); + } + + public function testBeforeControllerWithInvalidHeader() + { + $this->request + ->expects($this->once()) + ->method('getHeader') + ->with('X-JSXC-SIGNATURE') + ->willReturn('sha1=foobar'); + $this->config + ->expects($this->once()) + ->method('getAppValue') + ->with('ojsxc', 'apiSecret') + ->willReturn('secret'); + $this->rawRequest + ->expects($this->once()) + ->method('get') + ->willReturn('asdf'); + + $this->expectException(SecurityException::class); + $this->expectExceptionMessage('Signature does not match.'); + + $controller = $this->createMock(SignatureProtectedApiController::class); + $this->externalApiMiddleware->beforeController($controller, 'someMethod'); + } + + public function testBeforeControllerWithValidHeader() + { + $algo = 'sha1'; + $apiSecret = 'secret'; + $rawRequestBody = 'rawRequestBody'; + $hash = hash_hmac($algo, $rawRequestBody, $apiSecret); + + $this->request + ->expects($this->once()) + ->method('getHeader') + ->with('X-JSXC-SIGNATURE') + ->willReturn($algo.'='.$hash); + $this->config + ->expects($this->once()) + ->method('getAppValue') + ->with('ojsxc', 'apiSecret') + ->willReturn($apiSecret); + $this->rawRequest + ->expects($this->once()) + ->method('get') + ->willReturn($rawRequestBody); + + $controller = $this->createMock(SignatureProtectedApiController::class); + $this->externalApiMiddleware->beforeController($controller, 'someMethod'); + } } diff --git a/tests/unit/NewContentContainerTest.php b/tests/unit/NewContentContainerTest.php index e2caf39..ded45c3 100644 --- a/tests/unit/NewContentContainerTest.php +++ b/tests/unit/NewContentContainerTest.php @@ -6,18 +6,21 @@ use OCA\OJSXC\Db\Message; use OCA\OJSXC\Db\Stanza; use PHPUnit_Framework_TestCase; -class NewContentContainerTest extends PHPUnit_Framework_TestCase { +class NewContentContainerTest extends PHPUnit_Framework_TestCase +{ /** * @var NewContentContainer $newContentContainer */ private $newContentContainer; - public function setUp() { + public function setUp() + { $this->newContentContainer = new NewContentContainer(); } - public function testProvider() { + public function testProvider() + { $stanza1 = new Stanza(); $stanza1->setFrom('test@own.dev'); $stanza1->setTo('adsffdsst@own.dev'); @@ -38,7 +41,8 @@ class NewContentContainerTest extends PHPUnit_Framework_TestCase { /** * @dataProvider testProvider */ - public function test($stanzas, $count) { + public function test($stanzas, $count) + { foreach ($stanzas as $stanza) { $this->newContentContainer->addStanza($stanza); } @@ -46,8 +50,5 @@ class NewContentContainerTest extends PHPUnit_Framework_TestCase { $result = $this->newContentContainer->getStanzas(); $this->assertEquals(sort($stanzas), sort($result)); - } - - -}
\ No newline at end of file +} diff --git a/tests/unit/TimeLimitedTokenTest.php b/tests/unit/TimeLimitedTokenTest.php index f7ab789..7142728 100644 --- a/tests/unit/TimeLimitedTokenTest.php +++ b/tests/unit/TimeLimitedTokenTest.php @@ -4,43 +4,46 @@ namespace OCA\OJSXC; use PHPUnit\Framework\TestCase; -class TimeLimitedTokenTest extends TestCase { - public function testGenerateUser() { - $this->assertEquals( - 'AJP4Mvv5P8qZZJcENQhzfH$ruF%1458', - TimeLimitedToken::generateUser('foo', 'bar', 'secret', 60*60, 1500894607) - ); - - $this->assertEquals( - 'AELcjDTQjxEJptXaWb29gkt+LF%2Yi8', - TimeLimitedToken::generateUser('foo-bar', 'localhost.xyz', 'AJP4Mvv5P8', 60*60*10, 1500894607) - ); - - $this->assertEquals( - 'AEU+Upmh-jRtoHQ2Um1cYMcMV1%2Yi8', - TimeLimitedToken::generateUser('foo.bar', 'local.host.xyz', 'iiGTp+LF%2', 60*60*10, 1500894607) - ); - } - - public function testGenerateTURN() { - $this->assertEquals( - [(60*60 + 1500894607).':foobar', 'u66TdvZP9USnoCeOBFtVQa4DCkw='], - TimeLimitedToken::generateTURN('foobar', 'secret', 60*60, 1500894607) - ); - - $this->assertEquals( - [(3600 * 24 + 1500894607).':foo.bar', 'zfLkyJlJPx+KnLo5eLEUwJXDbGo='], - TimeLimitedToken::generateTURN('foo.bar', 'CeOBFtVQa', 3600 * 24, 1500894607) - ); - - $this->assertEquals( - [(3600 * 24 + 1500894607).':foo:bar', 'e+dKdn0JtGWccYCJ3NKaDUD6JZk='], - TimeLimitedToken::generateTURN('foo:bar', 'nLo5eLEUwJXD', 3600 * 24, 1500894607) - ); - - $this->assertEquals( - [(3600 * 24 + 1500894607).':foobar', 'q01XUfO0p37h5dGDd5R2PO2RhpM='], - TimeLimitedToken::generateTURN('foobar', 'nLo5eLEUwJXD', 3600 * 24, 1500894607) - ); - } +class TimeLimitedTokenTest extends TestCase +{ + public function testGenerateUser() + { + $this->assertEquals( + 'AJP4Mvv5P8qZZJcENQhzfH$ruF%1458', + TimeLimitedToken::generateUser('foo', 'bar', 'secret', 60 * 60, 1500894607) + ); + + $this->assertEquals( + 'AELcjDTQjxEJptXaWb29gkt+LF%2Yi8', + TimeLimitedToken::generateUser('foo-bar', 'localhost.xyz', 'AJP4Mvv5P8', 60 * 60 * 10, 1500894607) + ); + + $this->assertEquals( + 'AEU+Upmh-jRtoHQ2Um1cYMcMV1%2Yi8', + TimeLimitedToken::generateUser('foo.bar', 'local.host.xyz', 'iiGTp+LF%2', 60 * 60 * 10, 1500894607) + ); + } + + public function testGenerateTURN() + { + $this->assertEquals( + [(60 * 60 + 1500894607).':foobar', 'u66TdvZP9USnoCeOBFtVQa4DCkw='], + TimeLimitedToken::generateTURN('foobar', 'secret', 60 * 60, 1500894607) + ); + + $this->assertEquals( + [(3600 * 24 + 1500894607).':foo.bar', 'zfLkyJlJPx+KnLo5eLEUwJXDbGo='], + TimeLimitedToken::generateTURN('foo.bar', 'CeOBFtVQa', 3600 * 24, 1500894607) + ); + + $this->assertEquals( + [(3600 * 24 + 1500894607).':foo:bar', 'e+dKdn0JtGWccYCJ3NKaDUD6JZk='], + TimeLimitedToken::generateTURN('foo:bar', 'nLo5eLEUwJXD', 3600 * 24, 1500894607) + ); + + $this->assertEquals( + [(3600 * 24 + 1500894607).':foobar', 'q01XUfO0p37h5dGDd5R2PO2RhpM='], + TimeLimitedToken::generateTURN('foobar', 'nLo5eLEUwJXD', 3600 * 24, 1500894607) + ); + } } diff --git a/tests/unit/controller/ExternalApiControllerTest.php b/tests/unit/controller/ExternalApiControllerTest.php index 7f5c44d..aac2183 100644 --- a/tests/unit/controller/ExternalApiControllerTest.php +++ b/tests/unit/controller/ExternalApiControllerTest.php @@ -13,322 +13,339 @@ use OCP\IUser; use OCP\IGroup; use PHPUnit\Framework\TestCase; -class ExternalApiControllerTest extends TestCase { - private $request; - private $userManager; - private $userSession; - private $groupManager; - private $logger; - private $user; - private $externalApiController; - - public function setUp() { - parent::setUp(); - - $this->request = $this->createMock(IRequest::class); - $this->userManager = $this->createMock(IUserManager::class); - $this->userSession = $this->createMock(IUserSession::class); - $this->groupManager = $this->createMock(IGroupManager::class); - $this->logger = $this->createMock(ILogger::class); - $this->user = $this->createMock(IUser::class); - - $this->externalApiController = new ExternalApiController( - 'ojsxc', - $this->request, - $this->userManager, - $this->userSession, - $this->groupManager, - $this->logger - ); - } - - public function testSignatureProtected() { - $this->assertInstanceOf(SignatureProtectedApiController::class, $this->externalApiController); - } - - public function testCheckPasswordWithInvalidParams() { - $this->userSession - ->expects($this->once()) - ->method('login') - ->with('foo', 'bar') - ->willReturn(false); - - $return = $this->externalApiController->checkPassword('foo', 'bar'); - - $this->assertEquals('noauth', $return['result']); - } - - public function testCheckPasswordWithInvalidParamsAndDomain() { - $this->userSession - ->expects($this->exactly(2)) - ->method('login') - ->will($this->returnValueMap([ - ['foo@localhost', 'bar', false], - ['foo', 'bar', false] - ])); - - $return = $this->externalApiController->checkPassword('foo', 'bar', 'localhost'); - - $this->assertEquals('noauth', $return['result']); - } - - public function testCheckPasswordWithValidParams() { - $uid = 'foo'; - $this->user - ->expects($this->once()) - ->method('getUID') - ->willReturn($uid); - $this->userSession - ->expects($this->once()) - ->method('login') - ->with('foo', 'bar') - ->willReturn(true); - $this->userSession - ->expects($this->once()) - ->method('getUser') - ->willReturn($this->user); - - $return = $this->externalApiController->checkPassword('foo', 'bar'); - - $this->assertEquals('success', $return['result']); - $this->assertEquals($uid, $return['data']['uid']); - } - - public function testCheckPasswordWithValidParamsAndDomain() { - $uid = 'foo'; - $this->user - ->expects($this->once()) - ->method('getUID') - ->willReturn($uid); - $this->userSession - ->expects($this->once()) - ->method('login') - ->with('foo@localhost', 'bar') - ->willReturn(true); - $this->userSession - ->expects($this->once()) - ->method('getUser') - ->willReturn($this->user); - - $return = $this->externalApiController->checkPassword('foo', 'bar', 'localhost'); - - $this->assertEquals('success', $return['result']); - $this->assertEquals($uid, $return['data']['uid']); - } - - public function testIsUserFail() { - $this->userManager - ->expects($this->once()) - ->method('userExists') - ->with('foo') - ->willReturn(false); - - $return = $this->externalApiController->isUser('foo'); - - $this->assertEquals('success', $return['result']); - $this->assertEquals(false, $return['data']['isUser']); - } - - public function testIsUserFailWithDomain() { - $this->userManager - ->expects($this->exactly(2)) - ->method('userExists') - ->will($this->returnValueMap([ - ['foo@localhost', false], - ['foo', false] - ])); - - $return = $this->externalApiController->isUser('foo', 'localhost'); - - $this->assertEquals('success', $return['result']); - $this->assertEquals(false, $return['data']['isUser']); - } - - public function testIsUserSuccess() { - $this->userManager - ->expects($this->once()) - ->method('userExists') - ->with('foo') - ->willReturn(true); - - $return = $this->externalApiController->isUser('foo'); - - $this->assertEquals('success', $return['result']); - $this->assertEquals(true, $return['data']['isUser']); - } - - public function testIsUserSuccessWithDomain() { - $this->userManager - ->expects($this->once()) - ->method('userExists') - ->with('foo@localhost') - ->willReturn(true); - - $return = $this->externalApiController->isUser('foo', 'localhost'); - - $this->assertEquals('success', $return['result']); - $this->assertEquals(true, $return['data']['isUser']); - } - - public function testSharedRosterWithoutUsername() { - $this->expectException(\Exception::class); - $this->expectExceptionMessage('No username provided'); - - $this->externalApiController->sharedRoster(); - } - - public function testSharedRosterNoGroups() { - $user = $this->createUserMock('foobar'); - - $this->userManager - ->expects($this->once()) - ->method('get') - ->with($user->getUID()) - ->willReturn($user); - - $this->groupManager - ->expects($this->once()) - ->method('getUserGroups') - ->with($user) - ->willReturn([]); - - $return = $this->externalApiController->sharedRoster($user->getUID()); - - $this->assertEquals('success', $return['result']); - $this->assertEquals([], $return['data']['sharedRoster']); - } - - public function testSharedRosterMultipleDistinctGroups() { - $user = $this->createUserMock('foobar'); - - $this->userManager - ->expects($this->once()) - ->method('get') - ->with($user->getUID()) - ->willReturn($user); - - $this->groupManager - ->expects($this->once()) - ->method('getUserGroups') - ->with($user) - ->willReturn([ - $this->createGroupMock('Group1', ['Foo Bar', 'John Doo', 'user42']), - $this->createGroupMock('Group2', ['Fritz', 'John', 'Eve']) - ]); - - $expectedResult = [ - 'Foo-Bar' => [ - 'name' => 'Foo Bar', - 'groups' => ['Group1'] - ], - 'John-Doo' => [ - 'name' => 'John Doo', - 'groups' => ['Group1'] - ], - 'user42' => [ - 'name' => 'user42', - 'groups' => ['Group1'] - ], - 'Fritz' => [ - 'name' => 'Fritz', - 'groups' => ['Group2'] - ], - 'John' => [ - 'name' => 'John', - 'groups' => ['Group2'] - ], - 'Eve' => [ - 'name' => 'Eve', - 'groups' => ['Group2'] - ] - ]; - - $return = $this->externalApiController->sharedRoster($user->getUID()); - - $this->assertEquals('success', $return['result']); - - foreach($return['data']['sharedRoster'] as $key=>$value) { - $this->assertEquals($expectedResult[$key], $value); - } - } - - public function testSharedRosterMultipleOverlapGroups() { - $user = $this->createUserMock('foobar'); - - $this->userManager - ->expects($this->once()) - ->method('get') - ->with($user->getUID()) - ->willReturn($user); - - $this->groupManager - ->expects($this->once()) - ->method('getUserGroups') - ->with($user) - ->willReturn([ - $this->createGroupMock('Group1', ['Foo Bar', 'John Doo', 'user42']), - $this->createGroupMock('Group2', ['user42', 'John', 'Foo Bar']) - ]); - - $expectedResult = [ - 'Foo-Bar' => [ - 'name' => 'Foo Bar', - 'groups' => ['Group1', 'Group2'] - ], - 'John-Doo' => [ - 'name' => 'John Doo', - 'groups' => ['Group1'] - ], - 'user42' => [ - 'name' => 'user42', - 'groups' => ['Group1', 'Group2'] - ], - 'John' => [ - 'name' => 'John', - 'groups' => ['Group2'] - ] - ]; - - $return = $this->externalApiController->sharedRoster($user->getUID()); - - $this->assertEquals('success', $return['result']); - - foreach($return['data']['sharedRoster'] as $key=>$value) { - $this->assertEquals($expectedResult[$key], $value); - } - } - - private function createGroupMock($groupName, $displayNames = []) { - $users = []; - - foreach($displayNames as $displayName) { - $users[] = $this->createUserMock($displayName); - } - - $group = $this->createMock(IGroup::class); - - $group - ->method('getDisplayName') - ->willReturn($groupName); - - $group - ->method('getUsers') - ->willReturn($users); - - return $group; - } - - private function createUserMock($displayName) { - $user = $this->createMock(IUser::class); - - $user - ->method('getUID') - ->willReturn(preg_replace('/ /', '-', $displayName)); - - $user - ->method('getDisplayName') - ->willReturn($displayName); - - return $user; - } +class ExternalApiControllerTest extends TestCase +{ + private $request; + private $userManager; + private $userSession; + private $groupManager; + private $logger; + private $user; + private $externalApiController; + + public function setUp() + { + parent::setUp(); + + $this->request = $this->createMock(IRequest::class); + $this->userManager = $this->createMock(IUserManager::class); + $this->userSession = $this->createMock(IUserSession::class); + $this->groupManager = $this->createMock(IGroupManager::class); + $this->logger = $this->createMock(ILogger::class); + $this->user = $this->createMock(IUser::class); + + $this->externalApiController = new ExternalApiController( + 'ojsxc', + $this->request, + $this->userManager, + $this->userSession, + $this->groupManager, + $this->logger + ); + } + + public function testSignatureProtected() + { + $this->assertInstanceOf(SignatureProtectedApiController::class, $this->externalApiController); + } + + public function testCheckPasswordWithInvalidParams() + { + $this->userSession + ->expects($this->once()) + ->method('login') + ->with('foo', 'bar') + ->willReturn(false); + + $return = $this->externalApiController->checkPassword('foo', 'bar'); + + $this->assertEquals('noauth', $return['result']); + } + + public function testCheckPasswordWithInvalidParamsAndDomain() + { + $this->userSession + ->expects($this->exactly(2)) + ->method('login') + ->will($this->returnValueMap([ + ['foo@localhost', 'bar', false], + ['foo', 'bar', false] + ])); + + $return = $this->externalApiController->checkPassword('foo', 'bar', 'localhost'); + + $this->assertEquals('noauth', $return['result']); + } + + public function testCheckPasswordWithValidParams() + { + $uid = 'foo'; + $this->user + ->expects($this->once()) + ->method('getUID') + ->willReturn($uid); + $this->userSession + ->expects($this->once()) + ->method('login') + ->with('foo', 'bar') + ->willReturn(true); + $this->userSession + ->expects($this->once()) + ->method('getUser') + ->willReturn($this->user); + + $return = $this->externalApiController->checkPassword('foo', 'bar'); + + $this->assertEquals('success', $return['result']); + $this->assertEquals($uid, $return['data']['uid']); + } + + public function testCheckPasswordWithValidParamsAndDomain() + { + $uid = 'foo'; + $this->user + ->expects($this->once()) + ->method('getUID') + ->willReturn($uid); + $this->userSession + ->expects($this->once()) + ->method('login') + ->with('foo@localhost', 'bar') + ->willReturn(true); + $this->userSession + ->expects($this->once()) + ->method('getUser') + ->willReturn($this->user); + + $return = $this->externalApiController->checkPassword('foo', 'bar', 'localhost'); + + $this->assertEquals('success', $return['result']); + $this->assertEquals($uid, $return['data']['uid']); + } + + public function testIsUserFail() + { + $this->userManager + ->expects($this->once()) + ->method('userExists') + ->with('foo') + ->willReturn(false); + + $return = $this->externalApiController->isUser('foo'); + + $this->assertEquals('success', $return['result']); + $this->assertEquals(false, $return['data']['isUser']); + } + + public function testIsUserFailWithDomain() + { + $this->userManager + ->expects($this->exactly(2)) + ->method('userExists') + ->will($this->returnValueMap([ + ['foo@localhost', false], + ['foo', false] + ])); + + $return = $this->externalApiController->isUser('foo', 'localhost'); + + $this->assertEquals('success', $return['result']); + $this->assertEquals(false, $return['data']['isUser']); + } + + public function testIsUserSuccess() + { + $this->userManager + ->expects($this->once()) + ->method('userExists') + ->with('foo') + ->willReturn(true); + + $return = $this->externalApiController->isUser('foo'); + + $this->assertEquals('success', $return['result']); + $this->assertEquals(true, $return['data']['isUser']); + } + + public function testIsUserSuccessWithDomain() + { + $this->userManager + ->expects($this->once()) + ->method('userExists') + ->with('foo@localhost') + ->willReturn(true); + + $return = $this->externalApiController->isUser('foo', 'localhost'); + + $this->assertEquals('success', $return['result']); + $this->assertEquals(true, $return['data']['isUser']); + } + + public function testSharedRosterWithoutUsername() + { + $this->expectException(\Exception::class); + $this->expectExceptionMessage('No username provided'); + + $this->externalApiController->sharedRoster(); + } + + public function testSharedRosterNoGroups() + { + $user = $this->createUserMock('foobar'); + + $this->userManager + ->expects($this->once()) + ->method('get') + ->with($user->getUID()) + ->willReturn($user); + + $this->groupManager + ->expects($this->once()) + ->method('getUserGroups') + ->with($user) + ->willReturn([]); + + $return = $this->externalApiController->sharedRoster($user->getUID()); + + $this->assertEquals('success', $return['result']); + $this->assertEquals([], $return['data']['sharedRoster']); + } + + public function testSharedRosterMultipleDistinctGroups() + { + $user = $this->createUserMock('foobar'); + + $this->userManager + ->expects($this->once()) + ->method('get') + ->with($user->getUID()) + ->willReturn($user); + + $this->groupManager + ->expects($this->once()) + ->method('getUserGroups') + ->with($user) + ->willReturn([ + $this->createGroupMock('Group1', ['Foo Bar', 'John Doo', 'user42']), + $this->createGroupMock('Group2', ['Fritz', 'John', 'Eve']) + ]); + + $expectedResult = [ + 'Foo-Bar' => [ + 'name' => 'Foo Bar', + 'groups' => ['Group1'] + ], + 'John-Doo' => [ + 'name' => 'John Doo', + 'groups' => ['Group1'] + ], + 'user42' => [ + 'name' => 'user42', + 'groups' => ['Group1'] + ], + 'Fritz' => [ + 'name' => 'Fritz', + 'groups' => ['Group2'] + ], + 'John' => [ + 'name' => 'John', + 'groups' => ['Group2'] + ], + 'Eve' => [ + 'name' => 'Eve', + 'groups' => ['Group2'] + ] + ]; + + $return = $this->externalApiController->sharedRoster($user->getUID()); + + $this->assertEquals('success', $return['result']); + + foreach ($return['data']['sharedRoster'] as $key => $value) { + $this->assertEquals($expectedResult[$key], $value); + } + } + + public function testSharedRosterMultipleOverlapGroups() + { + $user = $this->createUserMock('foobar'); + + $this->userManager + ->expects($this->once()) + ->method('get') + ->with($user->getUID()) + ->willReturn($user); + + $this->groupManager + ->expects($this->once()) + ->method('getUserGroups') + ->with($user) + ->willReturn([ + $this->createGroupMock('Group1', ['Foo Bar', 'John Doo', 'user42']), + $this->createGroupMock('Group2', ['user42', 'John', 'Foo Bar']) + ]); + + $expectedResult = [ + 'Foo-Bar' => [ + 'name' => 'Foo Bar', + 'groups' => ['Group1', 'Group2'] + ], + 'John-Doo' => [ + 'name' => 'John Doo', + 'groups' => ['Group1'] + ], + 'user42' => [ + 'name' => 'user42', + 'groups' => ['Group1', 'Group2'] + ], + 'John' => [ + 'name' => 'John', + 'groups' => ['Group2'] + ] + ]; + + $return = $this->externalApiController->sharedRoster($user->getUID()); + + $this->assertEquals('success', $return['result']); + + foreach ($return['data']['sharedRoster'] as $key => $value) { + $this->assertEquals($expectedResult[$key], $value); + } + } + + private function createGroupMock($groupName, $displayNames = []) + { + $users = []; + + foreach ($displayNames as $displayName) { + $users[] = $this->createUserMock($displayName); + } + + $group = $this->createMock(IGroup::class); + + $group + ->method('getDisplayName') + ->willReturn($groupName); + + $group + ->method('getUsers') + ->willReturn($users); + + return $group; + } + + private function createUserMock($displayName) + { + $user = $this->createMock(IUser::class); + + $user + ->method('getUID') + ->willReturn(preg_replace('/ /', '-', $displayName)); + + $user + ->method('getDisplayName') + ->willReturn($displayName); + + return $user; + } } diff --git a/tests/unit/controller/HttpBindControllerTest.php b/tests/unit/controller/HttpBindControllerTest.php index 97bd035..e530222 100644 --- a/tests/unit/controller/HttpBindControllerTest.php +++ b/tests/unit/controller/HttpBindControllerTest.php @@ -13,8 +13,8 @@ use PHPUnit_Framework_TestCase; use Sabre\Xml\Writer; use PHPUnit_Framework_MockObject_MockObject; - -class HttpBindControllerTest extends PHPUnit_Framework_TestCase { +class HttpBindControllerTest extends PHPUnit_Framework_TestCase +{ /** * @var HttpBindController @@ -63,11 +63,13 @@ class HttpBindControllerTest extends PHPUnit_Framework_TestCase { */ private $stanzaLogger; - public function setUp() { + public function setUp() + { $this->stanzaLogger = $this->getMockBuilder('OCA\OJSXC\StanzaLogger')->disableOriginalConstructor()->getMock(); } - private function mockLock() { + private function mockLock() + { $this->lock->expects($this->any()) ->method('setLock') ->will($this->returnValue(null)); @@ -75,14 +77,15 @@ class HttpBindControllerTest extends PHPUnit_Framework_TestCase { $this->lock->expects($this->any()) ->method('stillLocked') ->will($this->returnValue(true)); - } + } /** * Helper function to set up the controller. This can't be done in the setUp, * since the requestBody is different for every test. * @param $requestBody */ - private function setUpController($requestBody) { + private function setUpController($requestBody) + { $request = $this->getMockBuilder('OCP\IRequest')->disableOriginalConstructor()->getMock(); $this->stanzaMapper = $this->getMockBuilder('OCA\OJSXC\Db\StanzaMapper')->disableOriginalConstructor()->getMock(); $this->presenceMapper = $this->getMockBuilder('OCA\OJSXC\Db\PresenceMapper')->disableOriginalConstructor()->getMock(); @@ -115,7 +118,8 @@ class HttpBindControllerTest extends PHPUnit_Framework_TestCase { ); } - public function testNewContentContainerNoNew() { + public function testNewContentContainerNoNew() + { $this->setUpController('<body xmlns=\'http://jabber.org/protocol/httpbind\'/>'); $this->mockLock(); $ex = new DoesNotExistException(''); @@ -139,10 +143,10 @@ class HttpBindControllerTest extends PHPUnit_Framework_TestCase { $response = $this->controller->index(); $this->assertEquals($expResponse, $response); - } - public function testNewContentContainerNoNewWithDbResults() { + public function testNewContentContainerNoNewWithDbResults() + { $result = new Stanza('test'); $this->setUpController('<body rid=\'897878797\' xmlns=\'http://jabber.org/protocol/httpbind\' sid=\'7862\'/>'); $this->mockLock(); @@ -156,7 +160,7 @@ class HttpBindControllerTest extends PHPUnit_Framework_TestCase { $r1 = $this->getMockBuilder('OCA\OJSXC\Db\Stanza')->disableOriginalConstructor()->getMock(); $r1->expects($this->once()) ->method('xmlSerialize') - ->will($this->returnCallback(function(Writer $writer){ + ->will($this->returnCallback(function (Writer $writer) { $writer->write('test'); })); @@ -182,7 +186,8 @@ class HttpBindControllerTest extends PHPUnit_Framework_TestCase { } - public function testNewContentContainerWithNewWithDbResults() { + public function testNewContentContainerWithNewWithDbResults() + { $result = new Stanza('test'); $this->setUpController('<body rid=\'897878797\' xmlns=\'http://jabber.org/protocol/httpbind\' sid=\'7862\'/>'); $this->mockLock(); @@ -196,7 +201,7 @@ class HttpBindControllerTest extends PHPUnit_Framework_TestCase { $r1 = $this->getMockBuilder('OCA\OJSXC\Db\Stanza')->disableOriginalConstructor()->getMock(); $r1->expects($this->once()) ->method('xmlSerialize') - ->will($this->returnCallback(function(Writer $writer){ + ->will($this->returnCallback(function (Writer $writer) { $writer->write('test'); })); @@ -213,7 +218,7 @@ class HttpBindControllerTest extends PHPUnit_Framework_TestCase { ->method('getCount') ->will($this->returnValue(5)); - $testStanza = new Stanza(); + $testStanza = new Stanza(); $testStanza->setFrom('derp@own.dev'); $testStanza->setTo('admin@own.dev'); @@ -239,12 +244,13 @@ class HttpBindControllerTest extends PHPUnit_Framework_TestCase { * {"reqId":"HmbEV6qTWF68ii1G\/kz1","remoteAddr":"","app":"PHP","message":"XMLReader::read(): An Error Occured while reading at \/var\/www\/owncloud\/apps\/ojsxc\/vendor\/sabre\/xml\/lib\/Reader.php#66","level":0,"time":"2016-01-30T14:52:44+00:00","method":"--","url":"--"} * {"reqId":"HmbEV6qTWF68ii1G\/kz1","remoteAddr":"","app":"PHP","message":"XMLReader::read(): An Error Occured while reading at \/var\/www\/owncloud\/apps\/ojsxc\/vendor\/sabre\/xml\/lib\/Reader.php#145","level":0,"time":"2016-01-30T14:52:44+00:00","method":"--","url":"--"} */ - public function testInvalidXML() { + public function testInvalidXML() + { $ex = new DoesNotExistException(''); $expResponse = new XMPPResponse($this->stanzaLogger); $this->setUpController('<x>'); - $this->mockLock(); + $this->mockLock(); $this->stanzaMapper->expects($this->exactly(10)) ->method('findByTo') ->with('john') @@ -258,7 +264,8 @@ class HttpBindControllerTest extends PHPUnit_Framework_TestCase { $this->assertEquals($expResponse, $response); } - public function IQProvider() { + public function IQProvider() + { $expStanza1 = new Stanza(); $expStanza1->setStanza('<iq to="admin@localhost" type="result" id="2:sendIQ"><query xmlns="jabber:iq:roster"><item jid="derp@localhost" name="derp"></item></query></iq><iq to="admin@localhost" type="result" id="2:sendIQ"><query xmlns="jabber:iq:roster"><item jid="derp@localhost" name="derp"></item></query></iq><iq to="admin@localhost" type="result" id="2:sendIQ"><query xmlns="jabber:iq:roster"><item jid="derp@localhost" name="derp"></item></query></iq>'); @@ -290,10 +297,11 @@ class HttpBindControllerTest extends PHPUnit_Framework_TestCase { /** * @dataProvider IQProvider */ - public function testIQHandlerWhenNoDbResults($body, $result, $expected, $pollCount, $handlerCount) { + public function testIQHandlerWhenNoDbResults($body, $result, $expected, $pollCount, $handlerCount) + { $ex = new DoesNotExistException(''); $this->setUpController($body); - $this->mockLock(); + $this->mockLock(); $expResponse = new XMPPResponse($this->stanzaLogger); $expResponse->write($expected); @@ -313,13 +321,13 @@ class HttpBindControllerTest extends PHPUnit_Framework_TestCase { $response = $this->controller->index(); $this->assertEquals($expResponse, $response); $this->assertEquals($expResponse->render(), $response->render()); - } - public function testDbResults() { + public function testDbResults() + { $result = new Stanza('test'); $this->setUpController('<body rid=\'897878797\' xmlns=\'http://jabber.org/protocol/httpbind\' sid=\'7862\'/>'); - $this->mockLock(); + $this->mockLock(); $expResponse = new XMPPResponse($this->stanzaLogger, $result); @@ -330,7 +338,7 @@ class HttpBindControllerTest extends PHPUnit_Framework_TestCase { $r1 = $this->getMockBuilder('OCA\OJSXC\Db\Stanza')->disableOriginalConstructor()->getMock(); $r1->expects($this->once()) ->method('xmlSerialize') - ->will($this->returnCallback(function(Writer $writer){ + ->will($this->returnCallback(function (Writer $writer) { $writer->write('test'); })); @@ -348,11 +356,12 @@ class HttpBindControllerTest extends PHPUnit_Framework_TestCase { $this->assertEquals($expResponse->render(), $response->render()); } - public function testMessageNoDbHandler() { + public function testMessageNoDbHandler() + { $body = '<body rid=\'897878959\' xmlns=\'http://jabber.org/protocol/httpbind\' sid=\'7862\'><message to=\'derp@own.dev\' type=\'chat\' id=\'1452960296859-msg\' xmlns=\'jabber:client\'><body>abc</body><request xmlns=\'urn:xmpp:receipts\'/></message></body>'; $ex = new DoesNotExistException(''); $this->setUpController($body); - $this->mockLock(); + $this->mockLock(); $expResponse = new XMPPResponse($this->stanzaLogger); @@ -374,7 +383,8 @@ class HttpBindControllerTest extends PHPUnit_Framework_TestCase { } - public function testMultipleMessageNoDbHandler() { + public function testMultipleMessageNoDbHandler() + { $body = <<<XML <body rid='897878959' xmlns='http://jabber.org/protocol/httpbind' sid='7862'> <message to='derp@own.dev' type='chat' id='1452960296859-msg' xmlns='jabber:client'><body>abc</body></message> @@ -436,10 +446,11 @@ XML; $this->assertEquals($expResponse->render(), $response->render()); } - public function testMessageDbHandler() { + public function testMessageDbHandler() + { $body = '<body rid=\'897878959\' xmlns=\'http://jabber.org/protocol/httpbind\' sid=\'7862\'><message to=\'derp@own.dev\' type=\'chat\' id=\'1452960296859-msg\' xmlns=\'jabber:client\'><body>abc</body><request xmlns=\'urn:xmpp:receipts\'/></message></body>'; $this->setUpController($body); - $this->mockLock(); + $this->mockLock(); $expResponse = new XMPPResponse($this->stanzaLogger, new Stanza('test')); @@ -449,7 +460,7 @@ XML; $r1 = $this->getMockBuilder('OCA\OJSXC\Db\Stanza')->disableOriginalConstructor()->getMock(); $r1->expects($this->once()) ->method('xmlSerialize') - ->will($this->returnCallback(function(Writer $writer){ + ->will($this->returnCallback(function (Writer $writer) { $writer->write('test'); })); @@ -467,13 +478,14 @@ XML; $this->assertEquals($expResponse->render(), $response->render()); } - public function testPresenceReturnNothingHandler() { + public function testPresenceReturnNothingHandler() + { $body = "<body xmlns='http://jabber.org/protocol/httpbind'><presence xmlns='jabber:client'><show>chat</show></presence></body>"; $ex = new DoesNotExistException(''); $expResponse = new XMPPResponse($this->stanzaLogger); $this->setUpController($body); - $this->mockLock(); + $this->mockLock(); $this->presenceHandler->expects($this->once()) ->method('handle') @@ -491,10 +503,10 @@ XML; $response = $this->controller->index(); $this->assertEquals($expResponse, $response); $this->assertEquals($expResponse->render(), $response->render()); - } - public function testPresenceHandler() { + public function testPresenceHandler() + { $body = "<body xmlns='http://jabber.org/protocol/httpbind'><presence xmlns='jabber:client'><show>chat</show></presence></body>"; $ex = new DoesNotExistException(''); $expResponse = new XMPPResponse($this->stanzaLogger); @@ -533,14 +545,14 @@ XML; $response = $this->controller->index(); $this->assertEquals($expResponse, $response); $this->assertEquals($expResponse->render(), $response->render()); - } - public function testBodyHandler() { + public function testBodyHandler() + { $ex = new DoesNotExistException(''); $body = '<body rid=\'897878985\' xmlns=\'http://jabber.org/protocol/httpbind\' sid=\'7862\'/>'; $this->setUpController($body); - $this->mockLock(); + $this->mockLock(); $expResponse = new XMPPResponse($this->stanzaLogger); $this->stanzaMapper->expects($this->exactly(10)) @@ -556,5 +568,4 @@ XML; $this->assertEquals($expResponse, $response); $this->assertEquals($expResponse->render(), $response->render()); } - } diff --git a/tests/unit/controller/SettingsControllerTest.php b/tests/unit/controller/SettingsControllerTest.php index 29b1c72..3eda211 100644 --- a/tests/unit/controller/SettingsControllerTest.php +++ b/tests/unit/controller/SettingsControllerTest.php @@ -9,183 +9,197 @@ use OCP\IUser; use OCP\IUserSession; use PHPUnit\Framework\TestCase; -class SettingsControllerTest extends TestCase { - private $request; - private $config; - private $userManager; - private $userSession; - private $settingsController; - - public function setUp() { - parent::setUp(); - - $this->request = $this->createMock(IRequest::class); - $this->config = $this->createMock(IConfig::class); - $this->userManager = $this->createMock(IUserManager::class); - $this->userSession = $this->createMock(IUserSession::class); - - $this->settingsController = new SettingsController( - 'ojsxc', - $this->request, - $this->config, - $this->userManager, - $this->userSession - ); - } - - public function testIndexWithoutUser() { - $return = $this->settingsController->index(); - - $this->assertEquals('noauth', $return['result']); - } - - public function testIndexDefaultServerType() { - $this->expectsInternalServerSettings(null); - } - - public function testIndexServerTypeInternal() { - $this->expectsInternalServerSettings('internal'); - } - - public function testIndexPreferPersonalEmail() { - $mapGetAppValue = [ - ['ojsxc', 'serverType', null, 'external'], - ['ojsxc', 'xmppPreferMail', null, 'true'] - ]; - - $node = 'foobar'; - $domain = 'host'; - - $mapGetUserValue = [ - ['Foo', 'settings', 'email', '', $node.'@'.$domain] - ]; - - $this->setUpAuthenticatedIndex($mapGetAppValue, $mapGetUserValue); - - $return = $this->settingsController->index(); - - $this->assertEquals('success', $return['result']); - $this->assertEquals($node, $return['data']['xmpp']['username']); - $this->assertEquals($domain, $return['data']['xmpp']['domain']); - } - - public function testIndexTimeLimitedToken() { - $mapGetAppValue = [ - ['ojsxc', 'serverType', null, 'external'], - ['ojsxc', 'timeLimitedToken', null, 'true'], - ['ojsxc', 'xmppDomain', null, 'localhost'] - ]; - - $this->setUpAuthenticatedIndex($mapGetAppValue); - - $return = $this->settingsController->index(); - - $this->assertEquals('success', $return['result']); - $this->assertNotEquals(null, $return['data']['xmpp']['password']); - } - - public function testGetIceServersNoData() { - $this->setUpGetIceServers(); - - $return = $this->settingsController->getIceServers(); - - $this->assertEquals([], $return); - } - - public function testGetIceServersStoredDataWithPrefix() { - $this->setUpGetIceServers('turn:localhost', '12345', 'foobar', 'password', 'secret'); - - $return = $this->settingsController->getIceServers(); - - $this->assertEquals('12345', $return['ttl']); - $this->assertEquals('turn:localhost', $return['iceServers'][0]['urls'][0]); - $this->assertEquals('foobar', $return['iceServers'][0]['username']); - $this->assertEquals('password', $return['iceServers'][0]['credential']); - } - - public function testGetIceServersGeneratedToken() { - $ttl = 12345; - $this->setUpGetIceServers('turn:localhost', ''.$ttl, '', 'password', 'secret'); - - $this->userSession - ->expects($this->once()) - ->method('getUser') - ->willReturn($this->createUserMock('Foo')); - - $return = $this->settingsController->getIceServers(); - - $this->assertEquals('12345', $return['ttl']); - $this->assertEquals('turn:localhost', $return['iceServers'][0]['urls'][0]); - - $username = $return['iceServers'][0]['username']; - list($validUntil, $uid) = explode(':', $username); - - $this->assertGreaterThan(time(), intval($validUntil)); - $this->assertLessThanOrEqual(time() + $ttl, intval($validUntil)); - $this->assertEquals('Foo', $uid); - $this->assertNotEquals('password', $return['iceServers'][0]['credential']); - $this->assertFalse(empty($return['iceServers'][0]['credential'])); - } - - private function expectsInternalServerSettings($serverType) { - $mapGetAppValue = [ - ['ojsxc', 'serverType', null, $serverType] - ]; - - $this->setUpAuthenticatedIndex($mapGetAppValue); - - $this->request - ->expects($this->once()) - ->method('getServerHost') - ->willReturn('localhost'); - - $return = $this->settingsController->index(); - - $this->assertEquals('success', $return['result']); - $this->assertEquals('internal', $return['data']['serverType']); - $this->assertEquals('localhost', $return['data']['adminSettings']['xmppDomain']); - } - - private function setUpAuthenticatedIndex($mapGetAppValue = [], $mapGetUserValue = []) { - $mapGetParam = [ - ['username', null, 'foo'], - ['password', null, 'bar'] - ]; - - $this->request->method('getParam')->will($this->returnValueMap($mapGetParam)); - $this->config->method('getAppValue')->will($this->returnValueMap($mapGetAppValue)); - $this->config->method('getUserValue')->will($this->returnValueMap($mapGetUserValue)); - - $this->userManager - ->expects($this->once()) - ->method('checkPassword') - ->with('foo', 'bar') - ->willReturn($this->createUserMock('Foo')); - } - - private function setUpGetIceServers($iceUrl = '', $iceTtl = '', $iceUsername = '', $iceCredential = '', $iceSecret = '') { - $mapGetAppValue = [ - ['ojsxc', 'iceSecret', null, $iceSecret], - ['ojsxc', 'iceTtl', 3600*24, $iceTtl], - ['ojsxc', 'iceUrl', null, $iceUrl], - ['ojsxc', 'iceUsername', '', $iceUsername], - ['ojsxc', 'iceCredential', '', $iceCredential] - ]; - - $this->config->method('getAppValue')->will($this->returnValueMap($mapGetAppValue)); - } - - private function createUserMock($displayName) { - $user = $this->createMock(IUser::class); - - $user - ->method('getUID') - ->willReturn(preg_replace('/ /', '-', $displayName)); - - $user - ->method('getDisplayName') - ->willReturn($displayName); - - return $user; - } +class SettingsControllerTest extends TestCase +{ + private $request; + private $config; + private $userManager; + private $userSession; + private $settingsController; + + public function setUp() + { + parent::setUp(); + + $this->request = $this->createMock(IRequest::class); + $this->config = $this->createMock(IConfig::class); + $this->userManager = $this->createMock(IUserManager::class); + $this->userSession = $this->createMock(IUserSession::class); + + $this->settingsController = new SettingsController( + 'ojsxc', + $this->request, + $this->config, + $this->userManager, + $this->userSession + ); + } + + public function testIndexWithoutUser() + { + $return = $this->settingsController->index(); + + $this->assertEquals('noauth', $return['result']); + } + + public function testIndexDefaultServerType() + { + $this->expectsInternalServerSettings(null); + } + + public function testIndexServerTypeInternal() + { + $this->expectsInternalServerSettings('internal'); + } + + public function testIndexPreferPersonalEmail() + { + $mapGetAppValue = [ + ['ojsxc', 'serverType', null, 'external'], + ['ojsxc', 'xmppPreferMail', null, 'true'] + ]; + + $node = 'foobar'; + $domain = 'host'; + + $mapGetUserValue = [ + ['Foo', 'settings', 'email', '', $node.'@'.$domain] + ]; + + $this->setUpAuthenticatedIndex($mapGetAppValue, $mapGetUserValue); + + $return = $this->settingsController->index(); + + $this->assertEquals('success', $return['result']); + $this->assertEquals($node, $return['data']['xmpp']['username']); + $this->assertEquals($domain, $return['data']['xmpp']['domain']); + } + + public function testIndexTimeLimitedToken() + { + $mapGetAppValue = [ + ['ojsxc', 'serverType', null, 'external'], + ['ojsxc', 'timeLimitedToken', null, 'true'], + ['ojsxc', 'xmppDomain', null, 'localhost'] + ]; + + $this->setUpAuthenticatedIndex($mapGetAppValue); + + $return = $this->settingsController->index(); + + $this->assertEquals('success', $return['result']); + $this->assertNotEquals(null, $return['data']['xmpp']['password']); + } + + public function testGetIceServersNoData() + { + $this->setUpGetIceServers(); + + $return = $this->settingsController->getIceServers(); + + $this->assertEquals([], $return); + } + + public function testGetIceServersStoredDataWithPrefix() + { + $this->setUpGetIceServers('turn:localhost', '12345', 'foobar', 'password', 'secret'); + + $return = $this->settingsController->getIceServers(); + + $this->assertEquals('12345', $return['ttl']); + $this->assertEquals('turn:localhost', $return['iceServers'][0]['urls'][0]); + $this->assertEquals('foobar', $return['iceServers'][0]['username']); + $this->assertEquals('password', $return['iceServers'][0]['credential']); + } + + public function testGetIceServersGeneratedToken() + { + $ttl = 12345; + $this->setUpGetIceServers('turn:localhost', ''.$ttl, '', 'password', 'secret'); + + $this->userSession + ->expects($this->once()) + ->method('getUser') + ->willReturn($this->createUserMock('Foo')); + + $return = $this->settingsController->getIceServers(); + + $this->assertEquals('12345', $return['ttl']); + $this->assertEquals('turn:localhost', $return['iceServers'][0]['urls'][0]); + + $username = $return['iceServers'][0]['username']; + list($validUntil, $uid) = explode(':', $username); + + $this->assertGreaterThan(time(), intval($validUntil)); + $this->assertLessThanOrEqual(time() + $ttl, intval($validUntil)); + $this->assertEquals('Foo', $uid); + $this->assertNotEquals('password', $return['iceServers'][0]['credential']); + $this->assertFalse(empty($return['iceServers'][0]['credential'])); + } + + private function expectsInternalServerSettings($serverType) + { + $mapGetAppValue = [ + ['ojsxc', 'serverType', null, $serverType] + ]; + + $this->setUpAuthenticatedIndex($mapGetAppValue); + + $this->request + ->expects($this->once()) + ->method('getServerHost') + ->willReturn('localhost'); + + $return = $this->settingsController->index(); + + $this->assertEquals('success', $return['result']); + $this->assertEquals('internal', $return['data']['serverType']); + $this->assertEquals('localhost', $return['data']['adminSettings']['xmppDomain']); + } + + private function setUpAuthenticatedIndex($mapGetAppValue = [], $mapGetUserValue = []) + { + $mapGetParam = [ + ['username', null, 'foo'], + ['password', null, 'bar'] + ]; + + $this->request->method('getParam')->will($this->returnValueMap($mapGetParam)); + $this->config->method('getAppValue')->will($this->returnValueMap($mapGetAppValue)); + $this->config->method('getUserValue')->will($this->returnValueMap($mapGetUserValue)); + + $this->userManager + ->expects($this->once()) + ->method('checkPassword') + ->with('foo', 'bar') + ->willReturn($this->createUserMock('Foo')); + } + + private function setUpGetIceServers($iceUrl = '', $iceTtl = '', $iceUsername = '', $iceCredential = '', $iceSecret = '') + { + $mapGetAppValue = [ + ['ojsxc', 'iceSecret', null, $iceSecret], + ['ojsxc', 'iceTtl', 3600 * 24, $iceTtl], + ['ojsxc', 'iceUrl', null, $iceUrl], + ['ojsxc', 'iceUsername', '', $iceUsername], + ['ojsxc', 'iceCredential', '', $iceCredential] + ]; + + $this->config->method('getAppValue')->will($this->returnValueMap($mapGetAppValue)); + } + + private function createUserMock($displayName) + { + $user = $this->createMock(IUser::class); + + $user + ->method('getUID') + ->willReturn(preg_replace('/ /', '-', $displayName)); + + $user + ->method('getDisplayName') + ->willReturn($displayName); + + return $user; + } } diff --git a/tests/unit/http/XMPPResponseTest.php b/tests/unit/http/XMPPResponseTest.php index ffc3788..94cf1bc 100644 --- a/tests/unit/http/XMPPResponseTest.php +++ b/tests/unit/http/XMPPResponseTest.php @@ -1,7 +1,8 @@ <?php namespace OCA\OJSXC\Db { - function uniqid() { + function uniqid() + { return 4; // chosen by fair dice roll. // guaranteed to be unique. } @@ -13,10 +14,10 @@ namespace OCA\OJSXC\Http { use OCA\OJSXC\Db\Stanza; use PHPUnit_Framework_TestCase; - - class XMPPResponseTest extends PHPUnit_Framework_TestCase { - - public function writingProvider() { + class XMPPResponseTest extends PHPUnit_Framework_TestCase + { + public function writingProvider() + { $stanza1 = new Stanza(); $stanza1->setFrom('test@test.be'); $stanza1->setTo('test.be'); @@ -50,9 +51,10 @@ namespace OCA\OJSXC\Http { } /** - * @dataProvider writingProvider - */ - public function testWriting($stanzas, $expected) { + * @dataProvider writingProvider + */ + public function testWriting($stanzas, $expected) + { $stanzaLogger = $this->getMockBuilder('OCA\OJSXC\StanzaLogger')->disableOriginalConstructor()->getMock(); $response = new XMPPResponse($stanzaLogger); foreach ($stanzas as $stanza) { @@ -61,7 +63,6 @@ namespace OCA\OJSXC\Http { $result = $response->render(); $this->assertEquals($expected, $result); } - } -}
\ No newline at end of file +} diff --git a/tests/unit/stanzahandlers/IQTest.php b/tests/unit/stanzahandlers/IQTest.php index 9fddef2..8ab22be 100644 --- a/tests/unit/stanzahandlers/IQTest.php +++ b/tests/unit/stanzahandlers/IQTest.php @@ -6,8 +6,8 @@ use OCA\OJSXC\Db\IQRoster; use PHPUnit_Framework_MockObject_MockObject; use PHPUnit_Framework_TestCase; - -class IQTest extends PHPUnit_Framework_TestCase { +class IQTest extends PHPUnit_Framework_TestCase +{ /** * @var IQ $iq @@ -29,14 +29,16 @@ class IQTest extends PHPUnit_Framework_TestCase { */ private $host; - public function setUp() { + public function setUp() + { $this->host = 'localhost'; $this->userId = 'john'; $this->userManager = $this->getMockBuilder('OCP\IUserManager')->disableOriginalConstructor()->getMock(); $this->iq = new IQ($this->userId, $this->host, $this->userManager); } - public function iqRosterProvider() { + public function iqRosterProvider() + { $user1 = $this->getMockBuilder('OCP\IUser')->disableOriginalConstructor()->getMock(); $user1->expects($this->any()) ->method('getUID') @@ -140,7 +142,8 @@ class IQTest extends PHPUnit_Framework_TestCase { /** * @dataProvider iqRosterProvider */ - public function testIqRoster(array $stanza, array $users, $searchCount, $expected) { + public function testIqRoster(array $stanza, array $users, $searchCount, $expected) + { $this->userManager->expects($searchCount) ->method('search') ->with('') @@ -149,7 +152,6 @@ class IQTest extends PHPUnit_Framework_TestCase { $result = $this->iq->handle($stanza); if ($expected instanceof IQRoster) { - $this->assertEquals($expected->getFrom(), $result->getFrom()); $this->assertEquals($expected->getId(), $result->getId()); $this->assertEquals($expected->getItems(), $result->getItems()); @@ -161,5 +163,4 @@ class IQTest extends PHPUnit_Framework_TestCase { $this->assertEquals($expected, $result); } } - } diff --git a/tests/unit/stanzahandlers/MessageTest.php b/tests/unit/stanzahandlers/MessageTest.php index 1ac3577..01670d0 100644 --- a/tests/unit/stanzahandlers/MessageTest.php +++ b/tests/unit/stanzahandlers/MessageTest.php @@ -6,7 +6,8 @@ use OCA\OJSXC\Db\Message as MessageEntity; use PHPUnit_Framework_TestCase; use PHPUnit_Framework_MockObject_MockObject; -class MessageTest extends PHPUnit_Framework_TestCase { +class MessageTest extends PHPUnit_Framework_TestCase +{ /** * @var Message $message @@ -28,14 +29,16 @@ class MessageTest extends PHPUnit_Framework_TestCase { */ private $host; - public function setUp() { + public function setUp() + { $this->host = 'localhost'; $this->userId = 'john'; $this->messageMapper = $this->getMockBuilder('OCA\OJSXC\Db\MessageMapper')->disableOriginalConstructor()->getMock(); $this->message = new Message($this->userId, $this->host, $this->messageMapper); } - public function messageProvider(){ + public function messageProvider() + { $values = [ [ "name" => "body", @@ -78,13 +81,12 @@ class MessageTest extends PHPUnit_Framework_TestCase { /** * @dataProvider messageProvider */ - public function testMessage(array $stanza, $expected) { + public function testMessage(array $stanza, $expected) + { $this->messageMapper->expects($this->once()) ->method('insert') ->with($expected); $this->message->handle($stanza); - } - } diff --git a/tests/unit/stanzahandlers/PresenceTest.php b/tests/unit/stanzahandlers/PresenceTest.php index 1c4e6aa..1f24f35 100644 --- a/tests/unit/stanzahandlers/PresenceTest.php +++ b/tests/unit/stanzahandlers/PresenceTest.php @@ -7,9 +7,8 @@ use OCA\OJSXC\Db\Presence as PresenceEntity; use PHPUnit_Framework_MockObject_MockObject; use PHPUnit_Framework_TestCase; - -class PresenceTest extends PHPUnit_Framework_TestCase { - +class PresenceTest extends PHPUnit_Framework_TestCase +{ private $host; private $userId; @@ -29,17 +28,18 @@ class PresenceTest extends PHPUnit_Framework_TestCase { */ private $presence; - public function setUp() { + public function setUp() + { $this->host = 'localhost'; $this->userId = 'john'; $this->presenceMapper = $this->getMockBuilder('OCA\OJSXC\Db\PresenceMapper')->disableOriginalConstructor()->getMock(); $this->messageMapper = $this->getMockBuilder('OCA\OJSXC\Db\MessageMapper')->disableOriginalConstructor()->getMock(); - $this->presence = new Presence($this->userId, $this->host - , $this->presenceMapper, $this->messageMapper); + $this->presence = new Presence($this->userId, $this->host, $this->presenceMapper, $this->messageMapper); } - public function handleProvider() { + public function handleProvider() + { $presence = new PresenceEntity(); $presence->setPresence('online'); $presence->setUserid('john'); @@ -68,8 +68,8 @@ class PresenceTest extends PHPUnit_Framework_TestCase { /** * @dataProvider handleProvider */ - public function testHandle($presenceEntity, $connectedUsers, $presences, $insert) { - + public function testHandle($presenceEntity, $connectedUsers, $presences, $insert) + { $this->presenceMapper->expects($this->once()) ->method('setPresence') ->with($presenceEntity); @@ -97,7 +97,8 @@ class PresenceTest extends PHPUnit_Framework_TestCase { } - public function unavailableHandleProvider() { + public function unavailableHandleProvider() + { $presence = new PresenceEntity(); $presence->setPresence('unavailable'); $presence->setUserid('john'); @@ -127,8 +128,8 @@ class PresenceTest extends PHPUnit_Framework_TestCase { /** * @dataProvider UnavailableHandleProvider */ - public function testUnavailableHandle($presenceEntity, $connectedUsers, $presences, $insert) { - + public function testUnavailableHandle($presenceEntity, $connectedUsers, $presences, $insert) + { $this->presenceMapper->expects($this->once()) ->method('setPresence') ->with($presenceEntity); @@ -151,4 +152,4 @@ class PresenceTest extends PHPUnit_Framework_TestCase { $result = $this->presence->handle($presenceEntity); $this->assertEquals($presences, $result); } -}
\ No newline at end of file +} |