diff options
65 files changed, 596 insertions, 306 deletions
diff --git a/apps/files/appinfo/routes.php b/apps/files/appinfo/routes.php index b6506824a80..08c9041062d 100644 --- a/apps/files/appinfo/routes.php +++ b/apps/files/appinfo/routes.php @@ -85,4 +85,4 @@ $this->create('download', 'download{file}') ->actionInclude('files/download.php'); // Register with the capabilities API -\OC_API::register('get', '/cloud/capabilities', array('OCA\Files\Capabilities', 'getCapabilities'), 'files', \OC_API::USER_AUTH); +\OCP\API::register('get', '/cloud/capabilities', array('OCA\Files\Capabilities', 'getCapabilities'), 'files', \OCP\API::USER_AUTH); diff --git a/apps/files/l10n/fr.js b/apps/files/l10n/fr.js index 34d92155970..1c42ce7649c 100644 --- a/apps/files/l10n/fr.js +++ b/apps/files/l10n/fr.js @@ -89,7 +89,7 @@ OC.L10N.register( "Maximum upload size" : "Taille max. d'envoi", "max. possible: " : "Max. possible :", "Save" : "Sauvegarder", - "Can not be edited from here due to insufficient permissions." : "Ne peut être modifié ici à cause de permissions insufisantes.", + "Can not be edited from here due to insufficient permissions." : "Ne peut être modifié ici à cause de permissions insuffisantes.", "Settings" : "Paramètres", "WebDAV" : "WebDAV", "Use this address to <a href=\"%s\" target=\"_blank\">access your Files via WebDAV</a>" : "Utilisez cette adresse pour <a href=\"%s\" target=\"_blank\">accéder à vos fichiers par WebDAV</a>", diff --git a/apps/files/l10n/fr.json b/apps/files/l10n/fr.json index 66b527512d1..c04ba115e8b 100644 --- a/apps/files/l10n/fr.json +++ b/apps/files/l10n/fr.json @@ -87,7 +87,7 @@ "Maximum upload size" : "Taille max. d'envoi", "max. possible: " : "Max. possible :", "Save" : "Sauvegarder", - "Can not be edited from here due to insufficient permissions." : "Ne peut être modifié ici à cause de permissions insufisantes.", + "Can not be edited from here due to insufficient permissions." : "Ne peut être modifié ici à cause de permissions insuffisantes.", "Settings" : "Paramètres", "WebDAV" : "WebDAV", "Use this address to <a href=\"%s\" target=\"_blank\">access your Files via WebDAV</a>" : "Utilisez cette adresse pour <a href=\"%s\" target=\"_blank\">accéder à vos fichiers par WebDAV</a>", diff --git a/apps/files/l10n/ja.js b/apps/files/l10n/ja.js index fc90f8c2d97..80e1f478509 100644 --- a/apps/files/l10n/ja.js +++ b/apps/files/l10n/ja.js @@ -70,6 +70,7 @@ OC.L10N.register( "An error occurred while trying to update the tags" : "タグを更新する際にエラーが発生しました", "A new file or folder has been <strong>created</strong>" : "新しいファイルまたはフォルダーを<strong>作成</strong>したとき", "A file or folder has been <strong>changed</strong>" : "ファイルまたはフォルダーを<strong>変更</strong>したとき", + "Limit notifications about creation and changes to your <strong>favorite files</strong> <em>(Stream only)</em>" : "<strong>お気に入りファイル</strong>に対する作成と変更の通知は制限されています。<em>(表示のみ)</em>", "A file or folder has been <strong>deleted</strong>" : "ファイルまたはフォルダーを<strong>削除</strong>したとき", "A file or folder has been <strong>restored</strong>" : "ファイルまたはフォルダーを<strong>復元</strong>したとき", "You created %1$s" : "あなたは %1$s を作成しました", diff --git a/apps/files/l10n/ja.json b/apps/files/l10n/ja.json index c9c579ac189..f3868ed14cf 100644 --- a/apps/files/l10n/ja.json +++ b/apps/files/l10n/ja.json @@ -68,6 +68,7 @@ "An error occurred while trying to update the tags" : "タグを更新する際にエラーが発生しました", "A new file or folder has been <strong>created</strong>" : "新しいファイルまたはフォルダーを<strong>作成</strong>したとき", "A file or folder has been <strong>changed</strong>" : "ファイルまたはフォルダーを<strong>変更</strong>したとき", + "Limit notifications about creation and changes to your <strong>favorite files</strong> <em>(Stream only)</em>" : "<strong>お気に入りファイル</strong>に対する作成と変更の通知は制限されています。<em>(表示のみ)</em>", "A file or folder has been <strong>deleted</strong>" : "ファイルまたはフォルダーを<strong>削除</strong>したとき", "A file or folder has been <strong>restored</strong>" : "ファイルまたはフォルダーを<strong>復元</strong>したとき", "You created %1$s" : "あなたは %1$s を作成しました", diff --git a/apps/files_external/appinfo/routes.php b/apps/files_external/appinfo/routes.php index 31f82087786..8c6dff7a901 100644 --- a/apps/files_external/appinfo/routes.php +++ b/apps/files_external/appinfo/routes.php @@ -46,12 +46,6 @@ $application->registerRoutes( ) ); -// TODO: move these to app framework -$this->create('files_external_add_root_certificate', 'ajax/addRootCertificate.php') - ->actionInclude('files_external/ajax/addRootCertificate.php'); -$this->create('files_external_remove_root_certificate', 'ajax/removeRootCertificate.php') - ->actionInclude('files_external/ajax/removeRootCertificate.php'); - $this->create('files_external_dropbox', 'ajax/dropbox.php') ->actionInclude('files_external/ajax/dropbox.php'); $this->create('files_external_google', 'ajax/google.php') @@ -61,7 +55,7 @@ $this->create('files_external_google', 'ajax/google.php') $this->create('files_external_list_applicable', '/applicable') ->actionInclude('files_external/ajax/applicable.php'); -\OC_API::register('get', +\OCP\API::register('get', '/apps/files_external/api/v1/mounts', array('\OCA\Files\External\Api', 'getUserMounts'), 'files_external'); diff --git a/apps/files_external/l10n/ja.js b/apps/files_external/l10n/ja.js index 8b6a255db92..cd50ae8c530 100644 --- a/apps/files_external/l10n/ja.js +++ b/apps/files_external/l10n/ja.js @@ -44,7 +44,9 @@ OC.L10N.register( "URL" : "URL", "Secure https://" : "セキュア https://", "Public key" : "公開鍵", + "Storage with id \"%i\" not found" : "ストレージID \"%i\" が見つかりません", "Invalid mount point" : "無効なマウントポイント", + "Invalid storage backend \"%s\"" : "\"%s\" のストレージバックエンドが不正", "Access granted" : "アクセスは許可されました", "Error configuring Dropbox storage" : "Dropboxストレージの設定エラー", "Grant access" : "アクセスを許可", diff --git a/apps/files_external/l10n/ja.json b/apps/files_external/l10n/ja.json index dbdd911cb96..81da7f57397 100644 --- a/apps/files_external/l10n/ja.json +++ b/apps/files_external/l10n/ja.json @@ -42,7 +42,9 @@ "URL" : "URL", "Secure https://" : "セキュア https://", "Public key" : "公開鍵", + "Storage with id \"%i\" not found" : "ストレージID \"%i\" が見つかりません", "Invalid mount point" : "無効なマウントポイント", + "Invalid storage backend \"%s\"" : "\"%s\" のストレージバックエンドが不正", "Access granted" : "アクセスは許可されました", "Error configuring Dropbox storage" : "Dropboxストレージの設定エラー", "Grant access" : "アクセスを許可", diff --git a/apps/files_sharing/appinfo/routes.php b/apps/files_sharing/appinfo/routes.php index 16f8727a510..9ac3a1f731a 100644 --- a/apps/files_sharing/appinfo/routes.php +++ b/apps/files_sharing/appinfo/routes.php @@ -26,6 +26,7 @@ namespace OCA\Files_Sharing\AppInfo; use OCA\Files_Sharing\Application; +use OCP\API; $application = new Application(); $application->registerRoutes($this, [ @@ -55,33 +56,33 @@ $this->create('sharing_external_test_remote', '/testremote') //TODO: SET: mail notification, waiting for PR #4689 to be accepted -\OC_API::register('get', +API::register('get', '/apps/files_sharing/api/v1/shares', array('\OCA\Files_Sharing\API\Local', 'getAllShares'), 'files_sharing'); -\OC_API::register('post', +API::register('post', '/apps/files_sharing/api/v1/shares', array('\OCA\Files_Sharing\API\Local', 'createShare'), 'files_sharing'); -\OC_API::register('get', +API::register('get', '/apps/files_sharing/api/v1/shares/{id}', array('\OCA\Files_Sharing\API\Local', 'getShare'), 'files_sharing'); -\OC_API::register('put', +API::register('put', '/apps/files_sharing/api/v1/shares/{id}', array('\OCA\Files_Sharing\API\Local', 'updateShare'), 'files_sharing'); -\OC_API::register('delete', +API::register('delete', '/apps/files_sharing/api/v1/shares/{id}', array('\OCA\Files_Sharing\API\Local', 'deleteShare'), 'files_sharing'); // Register with the capabilities API -\OC_API::register('get', +API::register('get', '/cloud/capabilities', array('OCA\Files_Sharing\Capabilities', 'getCapabilities'), - 'files_sharing', \OC_API::USER_AUTH); + 'files_sharing', API::USER_AUTH); diff --git a/apps/files_trashbin/appinfo/routes.php b/apps/files_trashbin/appinfo/routes.php index 05b082002a5..526ad1d4e35 100644 --- a/apps/files_trashbin/appinfo/routes.php +++ b/apps/files_trashbin/appinfo/routes.php @@ -34,4 +34,4 @@ $this->create('files_trashbin_ajax_undelete', 'ajax/undelete.php') // Register with the capabilities API -\OC_API::register('get', '/cloud/capabilities', array('OCA\Files_Trashbin\Capabilities', 'getCapabilities'), 'files_trashbin', \OC_API::USER_AUTH); +\OCP\API::register('get', '/cloud/capabilities', array('OCA\Files_Trashbin\Capabilities', 'getCapabilities'), 'files_trashbin', \OCP\API::USER_AUTH); diff --git a/apps/files_versions/appinfo/routes.php b/apps/files_versions/appinfo/routes.php index 9a9bd5bd655..0ea37d3b1b1 100644 --- a/apps/files_versions/appinfo/routes.php +++ b/apps/files_versions/appinfo/routes.php @@ -38,4 +38,4 @@ $this->create('files_versions_ajax_rollbackVersion', 'ajax/rollbackVersion.php') ->actionInclude('files_versions/ajax/rollbackVersion.php'); // Register with the capabilities API -OC_API::register('get', '/cloud/capabilities', array('OCA\Files_Versions\Capabilities', 'getCapabilities'), 'files_versions', OC_API::USER_AUTH); +\OCP\API::register('get', '/cloud/capabilities', array('OCA\Files_Versions\Capabilities', 'getCapabilities'), 'files_versions', \OCP\API::USER_AUTH); diff --git a/apps/provisioning_api/appinfo/routes.php b/apps/provisioning_api/appinfo/routes.php index 756822bc7e1..87f073f82b0 100644 --- a/apps/provisioning_api/appinfo/routes.php +++ b/apps/provisioning_api/appinfo/routes.php @@ -21,27 +21,29 @@ */ // Users -OCP\API::register('get', '/cloud/users', array('OCA\Provisioning_API\Users', 'getUsers'), 'provisioning_api', OC_API::ADMIN_AUTH); -OCP\API::register('post', '/cloud/users', array('OCA\Provisioning_API\Users', 'addUser'), 'provisioning_api', OC_API::ADMIN_AUTH); -OCP\API::register('get', '/cloud/users/{userid}', array('OCA\Provisioning_API\Users', 'getUser'), 'provisioning_api', OC_API::USER_AUTH); -OCP\API::register('put', '/cloud/users/{userid}', array('OCA\Provisioning_API\Users', 'editUser'), 'provisioning_api', OC_API::USER_AUTH); -OCP\API::register('delete', '/cloud/users/{userid}', array('OCA\Provisioning_API\Users', 'deleteUser'), 'provisioning_api', OC_API::SUBADMIN_AUTH); -OCP\API::register('get', '/cloud/users/{userid}/groups', array('OCA\Provisioning_API\Users', 'getUsersGroups'), 'provisioning_api', OC_API::USER_AUTH); -OCP\API::register('post', '/cloud/users/{userid}/groups', array('OCA\Provisioning_API\Users', 'addToGroup'), 'provisioning_api', OC_API::SUBADMIN_AUTH); -OCP\API::register('delete', '/cloud/users/{userid}/groups', array('OCA\Provisioning_API\Users', 'removeFromGroup'), 'provisioning_api', OC_API::SUBADMIN_AUTH); -OCP\API::register('post', '/cloud/users/{userid}/subadmins', array('OCA\Provisioning_API\Users', 'addSubAdmin'), 'provisioning_api', OC_API::ADMIN_AUTH); -OCP\API::register('delete', '/cloud/users/{userid}/subadmins', array('OCA\Provisioning_API\Users', 'removeSubAdmin'), 'provisioning_api', OC_API::ADMIN_AUTH); -OCP\API::register('get', '/cloud/users/{userid}/subadmins', array('OCA\Provisioning_API\Users', 'getUserSubAdminGroups'), 'provisioning_api', OC_API::ADMIN_AUTH); +use OCP\API; + +API::register('get', '/cloud/users', array('OCA\Provisioning_API\Users', 'getUsers'), 'provisioning_api', API::ADMIN_AUTH); +API::register('post', '/cloud/users', array('OCA\Provisioning_API\Users', 'addUser'), 'provisioning_api', API::ADMIN_AUTH); +API::register('get', '/cloud/users/{userid}', array('OCA\Provisioning_API\Users', 'getUser'), 'provisioning_api', API::USER_AUTH); +API::register('put', '/cloud/users/{userid}', array('OCA\Provisioning_API\Users', 'editUser'), 'provisioning_api', API::USER_AUTH); +API::register('delete', '/cloud/users/{userid}', array('OCA\Provisioning_API\Users', 'deleteUser'), 'provisioning_api', API::SUBADMIN_AUTH); +API::register('get', '/cloud/users/{userid}/groups', array('OCA\Provisioning_API\Users', 'getUsersGroups'), 'provisioning_api', API::USER_AUTH); +API::register('post', '/cloud/users/{userid}/groups', array('OCA\Provisioning_API\Users', 'addToGroup'), 'provisioning_api', API::SUBADMIN_AUTH); +API::register('delete', '/cloud/users/{userid}/groups', array('OCA\Provisioning_API\Users', 'removeFromGroup'), 'provisioning_api', API::SUBADMIN_AUTH); +API::register('post', '/cloud/users/{userid}/subadmins', array('OCA\Provisioning_API\Users', 'addSubAdmin'), 'provisioning_api', API::ADMIN_AUTH); +API::register('delete', '/cloud/users/{userid}/subadmins', array('OCA\Provisioning_API\Users', 'removeSubAdmin'), 'provisioning_api', API::ADMIN_AUTH); +API::register('get', '/cloud/users/{userid}/subadmins', array('OCA\Provisioning_API\Users', 'getUserSubAdminGroups'), 'provisioning_api', API::ADMIN_AUTH); // Groups -OCP\API::register('get', '/cloud/groups', array('OCA\Provisioning_API\Groups', 'getGroups'), 'provisioning_api', OC_API::SUBADMIN_AUTH); -OCP\API::register('post', '/cloud/groups', array('OCA\Provisioning_API\Groups', 'addGroup'), 'provisioning_api', OC_API::SUBADMIN_AUTH); -OCP\API::register('get', '/cloud/groups/{groupid}', array('OCA\Provisioning_API\Groups', 'getGroup'), 'provisioning_api', OC_API::SUBADMIN_AUTH); -OCP\API::register('delete', '/cloud/groups/{groupid}', array('OCA\Provisioning_API\Groups', 'deleteGroup'), 'provisioning_api', OC_API::ADMIN_AUTH); -OCP\API::register('get', '/cloud/groups/{groupid}/subadmins', array('OCA\Provisioning_API\Groups', 'getSubAdminsOfGroup'), 'provisioning_api', OC_API::ADMIN_AUTH); +API::register('get', '/cloud/groups', array('OCA\Provisioning_API\Groups', 'getGroups'), 'provisioning_api', API::SUBADMIN_AUTH); +API::register('post', '/cloud/groups', array('OCA\Provisioning_API\Groups', 'addGroup'), 'provisioning_api', API::SUBADMIN_AUTH); +API::register('get', '/cloud/groups/{groupid}', array('OCA\Provisioning_API\Groups', 'getGroup'), 'provisioning_api', API::SUBADMIN_AUTH); +API::register('delete', '/cloud/groups/{groupid}', array('OCA\Provisioning_API\Groups', 'deleteGroup'), 'provisioning_api', API::ADMIN_AUTH); +API::register('get', '/cloud/groups/{groupid}/subadmins', array('OCA\Provisioning_API\Groups', 'getSubAdminsOfGroup'), 'provisioning_api', API::ADMIN_AUTH); // Apps -OCP\API::register('get', '/cloud/apps', array('OCA\Provisioning_API\Apps', 'getApps'), 'provisioning_api', OC_API::ADMIN_AUTH); -OCP\API::register('get', '/cloud/apps/{appid}', array('OCA\Provisioning_API\Apps', 'getAppInfo'), 'provisioning_api', OC_API::ADMIN_AUTH); -OCP\API::register('post', '/cloud/apps/{appid}', array('OCA\Provisioning_API\Apps', 'enable'), 'provisioning_api', OC_API::ADMIN_AUTH); -OCP\API::register('delete', '/cloud/apps/{appid}', array('OCA\Provisioning_API\Apps', 'disable'), 'provisioning_api', OC_API::ADMIN_AUTH); +API::register('get', '/cloud/apps', array('OCA\Provisioning_API\Apps', 'getApps'), 'provisioning_api', API::ADMIN_AUTH); +API::register('get', '/cloud/apps/{appid}', array('OCA\Provisioning_API\Apps', 'getAppInfo'), 'provisioning_api', API::ADMIN_AUTH); +API::register('post', '/cloud/apps/{appid}', array('OCA\Provisioning_API\Apps', 'enable'), 'provisioning_api', API::ADMIN_AUTH); +API::register('delete', '/cloud/apps/{appid}', array('OCA\Provisioning_API\Apps', 'disable'), 'provisioning_api', API::ADMIN_AUTH); diff --git a/apps/provisioning_api/lib/apps.php b/apps/provisioning_api/lib/apps.php index c1abb772e41..2bafd06a084 100644 --- a/apps/provisioning_api/lib/apps.php +++ b/apps/provisioning_api/lib/apps.php @@ -60,7 +60,7 @@ class Apps { if(!is_null($info)) { return new OC_OCS_Result(OC_App::getAppInfo($app)); } else { - return new OC_OCS_Result(null, \OC_API::RESPOND_NOT_FOUND, 'The request app was not found'); + return new OC_OCS_Result(null, \OCP\API::RESPOND_NOT_FOUND, 'The request app was not found'); } } diff --git a/apps/provisioning_api/lib/groups.php b/apps/provisioning_api/lib/groups.php index 4a5a69216c4..cd156110635 100644 --- a/apps/provisioning_api/lib/groups.php +++ b/apps/provisioning_api/lib/groups.php @@ -44,14 +44,14 @@ class Groups{ public static function getGroup($parameters){ // Check the group exists if(!OC_Group::groupExists($parameters['groupid'])){ - return new OC_OCS_Result(null, \OC_API::RESPOND_NOT_FOUND, 'The requested group could not be found'); + return new OC_OCS_Result(null, \OCP\API::RESPOND_NOT_FOUND, 'The requested group could not be found'); } // Check subadmin has access to this group if(\OC_User::isAdminUser(\OC_User::getUser()) || in_array($parameters['groupid'], \OC_SubAdmin::getSubAdminsGroups(\OC_User::getUser()))){ return new OC_OCS_Result(array('users' => OC_Group::usersInGroup($parameters['groupid']))); } else { - return new OC_OCS_Result(null, \OC_API::RESPOND_UNAUTHORISED, 'User does not have access to specified group'); + return new OC_OCS_Result(null, \OCP\API::RESPOND_UNAUTHORISED, 'User does not have access to specified group'); } } diff --git a/apps/provisioning_api/lib/users.php b/apps/provisioning_api/lib/users.php index 6169ea16f9c..505a141c032 100644 --- a/apps/provisioning_api/lib/users.php +++ b/apps/provisioning_api/lib/users.php @@ -67,7 +67,7 @@ class Users { if(OC_User::isAdminUser(OC_User::getUser()) || OC_SubAdmin::isUserAccessible(OC_User::getUser(), $userId)) { // Check they exist if(!OC_User::userExists($userId)) { - return new OC_OCS_Result(null, \OC_API::RESPOND_NOT_FOUND, 'The requested user could not be found'); + return new OC_OCS_Result(null, \OCP\API::RESPOND_NOT_FOUND, 'The requested user could not be found'); } // Show all $return = array( @@ -80,7 +80,7 @@ class Users { } else { // Check they are looking up themselves if(OC_User::getUser() != $userId) { - return new OC_OCS_Result(null, \OC_API::RESPOND_UNAUTHORISED); + return new OC_OCS_Result(null, \OCP\API::RESPOND_UNAUTHORISED); } // Return some additional information compared to the core route $return = array( @@ -226,7 +226,7 @@ class Users { // Check they're an admin if(!OC_Group::inGroup(OC_User::getUser(), 'admin')){ // This user doesn't have rights to add a user to this group - return new OC_OCS_Result(null, \OC_API::RESPOND_UNAUTHORISED); + return new OC_OCS_Result(null, \OCP\API::RESPOND_UNAUTHORISED); } // Check if the group exists if(!OC_Group::groupExists($group)){ diff --git a/apps/provisioning_api/tests/appstest.php b/apps/provisioning_api/tests/appstest.php index b2b5748ea27..140dd287a0e 100644 --- a/apps/provisioning_api/tests/appstest.php +++ b/apps/provisioning_api/tests/appstest.php @@ -36,7 +36,7 @@ class AppsTest extends TestCase { $result = \OCA\provisioning_API\Apps::getAppInfo(array('appid' => 'not_provisioning_api')); $this->assertInstanceOf('OC_OCS_Result', $result); $this->assertFalse($result->succeeded()); - $this->assertEquals(\OC_API::RESPOND_NOT_FOUND, $result->getStatusCode()); + $this->assertEquals(\OCP\API::RESPOND_NOT_FOUND, $result->getStatusCode()); } diff --git a/apps/provisioning_api/tests/groupstest.php b/apps/provisioning_api/tests/groupstest.php index 7c5343af46d..94bde52c392 100644 --- a/apps/provisioning_api/tests/groupstest.php +++ b/apps/provisioning_api/tests/groupstest.php @@ -39,7 +39,7 @@ class GroupsTest extends TestCase { $this->assertInstanceOf('OC_OCS_Result', $result); $this->assertFalse($result->succeeded()); - $this->assertEquals(\OC_API::RESPOND_UNAUTHORISED, $result->getStatusCode()); + $this->assertEquals(\OCP\API::RESPOND_UNAUTHORISED, $result->getStatusCode()); } @@ -92,7 +92,7 @@ class GroupsTest extends TestCase { $this->assertInstanceOf('OC_OCS_Result', $result); $this->assertFalse($result->succeeded()); - $this->assertEquals(\OC_API::RESPOND_UNAUTHORISED, $result->getStatusCode()); + $this->assertEquals(\OCP\API::RESPOND_UNAUTHORISED, $result->getStatusCode()); } diff --git a/apps/provisioning_api/tests/userstest.php b/apps/provisioning_api/tests/userstest.php index f06f853ee1f..b7e83a3c4fe 100644 --- a/apps/provisioning_api/tests/userstest.php +++ b/apps/provisioning_api/tests/userstest.php @@ -101,7 +101,7 @@ class UsersTest extends TestCase { $result = \OCA\provisioning_API\Users::getUser($params); $this->assertInstanceOf('OC_OCS_Result', $result); $this->assertFalse($result->succeeded()); - $this->assertEquals(\OC_API::RESPOND_NOT_FOUND, $result->getStatusCode()); + $this->assertEquals(\OCP\API::RESPOND_NOT_FOUND, $result->getStatusCode()); } diff --git a/apps/user_ldap/group_ldap.php b/apps/user_ldap/group_ldap.php index 7695ba06388..8f56e01bf3d 100644 --- a/apps/user_ldap/group_ldap.php +++ b/apps/user_ldap/group_ldap.php @@ -746,6 +746,6 @@ class GROUP_LDAP extends BackendUtility implements \OCP\GroupInterface { * compared with OC_USER_BACKEND_CREATE_USER etc. */ public function implementsActions($actions) { - return (bool)(OC_GROUP_BACKEND_COUNT_USERS & $actions); + return (bool)(\OC_Group_Backend::COUNT_USERS & $actions); } } diff --git a/apps/user_ldap/l10n/ja.js b/apps/user_ldap/l10n/ja.js index fd2ef9c9145..6dda509053a 100644 --- a/apps/user_ldap/l10n/ja.js +++ b/apps/user_ldap/l10n/ja.js @@ -30,8 +30,11 @@ OC.L10N.register( "Test Configuration" : "設定をテスト", "Help" : "ヘルプ", "Groups meeting these criteria are available in %s:" : "これらの基準を満たすグループが %s で利用可能:", + "LDAP Filter:" : "LDAP フィルタ:", "The filter specifies which LDAP groups shall have access to the %s instance." : "フィルターは、どの LDAP グループが %s にアクセスするかを指定します。", "Test Filter" : "フィルターをテスト", + "LDAP / AD Username:" : "LDAP / AD ユーザ名:", + "LDAP / AD Email Address:" : "LDAP / AD メールアドレス:", "Other Attributes:" : "その他の属性:", "Defines the filter to apply, when login is attempted. %%uid replaces the username in the login action. Example: \"uid=%%uid\"" : "ログイン実行時に適用するフィルターを定義します。%%uid にはログイン操作におけるユーザー名が入ります。例: \"uid=%%uid\"", "1. Server" : "1. Server", diff --git a/apps/user_ldap/l10n/ja.json b/apps/user_ldap/l10n/ja.json index 7117cb0ec17..d616a84e457 100644 --- a/apps/user_ldap/l10n/ja.json +++ b/apps/user_ldap/l10n/ja.json @@ -28,8 +28,11 @@ "Test Configuration" : "設定をテスト", "Help" : "ヘルプ", "Groups meeting these criteria are available in %s:" : "これらの基準を満たすグループが %s で利用可能:", + "LDAP Filter:" : "LDAP フィルタ:", "The filter specifies which LDAP groups shall have access to the %s instance." : "フィルターは、どの LDAP グループが %s にアクセスするかを指定します。", "Test Filter" : "フィルターをテスト", + "LDAP / AD Username:" : "LDAP / AD ユーザ名:", + "LDAP / AD Email Address:" : "LDAP / AD メールアドレス:", "Other Attributes:" : "その他の属性:", "Defines the filter to apply, when login is attempted. %%uid replaces the username in the login action. Example: \"uid=%%uid\"" : "ログイン実行時に適用するフィルターを定義します。%%uid にはログイン操作におけるユーザー名が入ります。例: \"uid=%%uid\"", "1. Server" : "1. Server", diff --git a/apps/user_ldap/l10n/nl.js b/apps/user_ldap/l10n/nl.js index 6c96d618f4d..43cf25d010a 100644 --- a/apps/user_ldap/l10n/nl.js +++ b/apps/user_ldap/l10n/nl.js @@ -23,9 +23,18 @@ OC.L10N.register( "{nthServer}. Server" : "{nthServer}. Server", "No object found in the given Base DN. Please revise." : "Geen object gevonden in de basis DN. Review instellingen.", "More then 1.000 directory entries available." : "Meer dan 1.000 directoryobjecten beschikbaar.", + " entries available within the provided Base DN" : "accounts beschikbaar binnen de provider Basis DN", + "An error occurred. Please check the Base DN, as well as connection settings and credentials." : "Er trad een fout op. Controleer de Basis DN en de verbindingsinstellingen en inloggegevens.", "Do you really want to delete the current Server Configuration?" : "Wilt u werkelijk de huidige Serverconfiguratie verwijderen?", "Confirm Deletion" : "Bevestig verwijderen", + "Mappings cleared successfully!" : "Mappings succesvol schoongemaakt!", + "Error while clearing the mappings." : "Fout bij opschonen mappings.", + "Saving failed. Please make sure the database is in Operation. Reload before continuing." : "Opslaan mislukt. Verifieer dat de database draait. Herlaad voordat u verder gaat.", + "Switching the mode will enable automatic LDAP queries. Depending on your LDAP size they may take a while. Do you still want to switch the mode?" : "Omschakelen van de modus schakelt automatische LDAP opvragingen in. Afhankelijk van uw LDAP omvang kan dat even duren. Wilt u nog steeds omschakelen?", + "Mode switch" : "Omschakelen modus", "Select attributes" : "Selecteer attributen", + "User not found. Please check your login attributes and username. Effective filter (to copy-and-paste for command line validation): <br/>" : "Gebruiker niet gevonden. Verifieer de inloggegevens en gebruikersnaam. Effectief filter (kopiëren en plakken voor commandoregel validatie): <br/>", + "User found and settings verified." : "Gebruiker gevonden en instellingen geverifieerd.", "_%s group found_::_%s groups found_" : ["%s groep gevonden","%s groepen gevonden"], "_%s user found_::_%s users found_" : ["%s gebruiker gevonden","%s gebruikers gevonden"], "Could not detect user display name attribute. Please specify it yourself in advanced ldap settings." : "Kon het weergavenaam attribuut van de gebruiker niet vinden. Geef het zelf op in de geavanceerde ldap instellingen.", diff --git a/apps/user_ldap/l10n/nl.json b/apps/user_ldap/l10n/nl.json index 6fa5f9ee391..d18c303cf04 100644 --- a/apps/user_ldap/l10n/nl.json +++ b/apps/user_ldap/l10n/nl.json @@ -21,9 +21,18 @@ "{nthServer}. Server" : "{nthServer}. Server", "No object found in the given Base DN. Please revise." : "Geen object gevonden in de basis DN. Review instellingen.", "More then 1.000 directory entries available." : "Meer dan 1.000 directoryobjecten beschikbaar.", + " entries available within the provided Base DN" : "accounts beschikbaar binnen de provider Basis DN", + "An error occurred. Please check the Base DN, as well as connection settings and credentials." : "Er trad een fout op. Controleer de Basis DN en de verbindingsinstellingen en inloggegevens.", "Do you really want to delete the current Server Configuration?" : "Wilt u werkelijk de huidige Serverconfiguratie verwijderen?", "Confirm Deletion" : "Bevestig verwijderen", + "Mappings cleared successfully!" : "Mappings succesvol schoongemaakt!", + "Error while clearing the mappings." : "Fout bij opschonen mappings.", + "Saving failed. Please make sure the database is in Operation. Reload before continuing." : "Opslaan mislukt. Verifieer dat de database draait. Herlaad voordat u verder gaat.", + "Switching the mode will enable automatic LDAP queries. Depending on your LDAP size they may take a while. Do you still want to switch the mode?" : "Omschakelen van de modus schakelt automatische LDAP opvragingen in. Afhankelijk van uw LDAP omvang kan dat even duren. Wilt u nog steeds omschakelen?", + "Mode switch" : "Omschakelen modus", "Select attributes" : "Selecteer attributen", + "User not found. Please check your login attributes and username. Effective filter (to copy-and-paste for command line validation): <br/>" : "Gebruiker niet gevonden. Verifieer de inloggegevens en gebruikersnaam. Effectief filter (kopiëren en plakken voor commandoregel validatie): <br/>", + "User found and settings verified." : "Gebruiker gevonden en instellingen geverifieerd.", "_%s group found_::_%s groups found_" : ["%s groep gevonden","%s groepen gevonden"], "_%s user found_::_%s users found_" : ["%s gebruiker gevonden","%s gebruikers gevonden"], "Could not detect user display name attribute. Please specify it yourself in advanced ldap settings." : "Kon het weergavenaam attribuut van de gebruiker niet vinden. Geef het zelf op in de geavanceerde ldap instellingen.", diff --git a/apps/user_ldap/l10n/ru.js b/apps/user_ldap/l10n/ru.js index 10fdef8150a..dcf2bcb8d86 100644 --- a/apps/user_ldap/l10n/ru.js +++ b/apps/user_ldap/l10n/ru.js @@ -19,7 +19,11 @@ OC.L10N.register( "Please check the credentials, they seem to be wrong." : "Пожалуйста проверьте учетный данные, возможно они не верны.", "Please specify the port, it could not be auto-detected." : "Пожалуйста укажите порт, он не может быть определен автоматически.", "Base DN could not be auto-detected, please revise credentials, host and port." : "База поиска не может быть определена автоматически, пожалуйста перепроверьте учетные данные, адрес и порт.", + "Could not detect Base DN, please enter it manually." : "Не возможно обнаружить Base DN, пожалуйста задайте в ручную.", "{nthServer}. Server" : "Сервер {nthServer}.", + "No object found in the given Base DN. Please revise." : "Не найдено объектов в Base DN. Пожалуйста перепроверьте.", + "More then 1.000 directory entries available." : "Доступно более 1.000 папок.", + " entries available within the provided Base DN" : "элементы доступные в Базе", "Do you really want to delete the current Server Configuration?" : "Вы действительно хотите удалить существующую конфигурацию сервера?", "Confirm Deletion" : "Подтверждение удаления", "Select attributes" : "Выберите атрибуты", @@ -34,8 +38,12 @@ OC.L10N.register( "Test Configuration" : "Проверить конфигурацию", "Help" : "Помощь", "Groups meeting these criteria are available in %s:" : "Группы, отвечающие этим критериям доступны в %s:", + "Search groups" : "Поиск групп", + "Available groups" : "Доступные группы", + "Selected groups" : "Выбранные группы", "The filter specifies which LDAP groups shall have access to the %s instance." : "Этот фильтр определяет какие LDAP группы должны иметь доступ к экземпляру %s.", "Test Filter" : "Проверить фильтр", + "LDAP / AD Username:" : "Имя пользователя LDAP/AD:", "Other Attributes:" : "Другие атрибуты:", "Defines the filter to apply, when login is attempted. %%uid replaces the username in the login action. Example: \"uid=%%uid\"" : "Определяет фильтр для применения при попытке входа. %%uid заменяет имя пользователя при входе в систему. Например: \"uid=%%uid\"", "1. Server" : "Сервер 1.", diff --git a/apps/user_ldap/l10n/ru.json b/apps/user_ldap/l10n/ru.json index 8ddc9ff25fd..b6a04af8177 100644 --- a/apps/user_ldap/l10n/ru.json +++ b/apps/user_ldap/l10n/ru.json @@ -17,7 +17,11 @@ "Please check the credentials, they seem to be wrong." : "Пожалуйста проверьте учетный данные, возможно они не верны.", "Please specify the port, it could not be auto-detected." : "Пожалуйста укажите порт, он не может быть определен автоматически.", "Base DN could not be auto-detected, please revise credentials, host and port." : "База поиска не может быть определена автоматически, пожалуйста перепроверьте учетные данные, адрес и порт.", + "Could not detect Base DN, please enter it manually." : "Не возможно обнаружить Base DN, пожалуйста задайте в ручную.", "{nthServer}. Server" : "Сервер {nthServer}.", + "No object found in the given Base DN. Please revise." : "Не найдено объектов в Base DN. Пожалуйста перепроверьте.", + "More then 1.000 directory entries available." : "Доступно более 1.000 папок.", + " entries available within the provided Base DN" : "элементы доступные в Базе", "Do you really want to delete the current Server Configuration?" : "Вы действительно хотите удалить существующую конфигурацию сервера?", "Confirm Deletion" : "Подтверждение удаления", "Select attributes" : "Выберите атрибуты", @@ -32,8 +36,12 @@ "Test Configuration" : "Проверить конфигурацию", "Help" : "Помощь", "Groups meeting these criteria are available in %s:" : "Группы, отвечающие этим критериям доступны в %s:", + "Search groups" : "Поиск групп", + "Available groups" : "Доступные группы", + "Selected groups" : "Выбранные группы", "The filter specifies which LDAP groups shall have access to the %s instance." : "Этот фильтр определяет какие LDAP группы должны иметь доступ к экземпляру %s.", "Test Filter" : "Проверить фильтр", + "LDAP / AD Username:" : "Имя пользователя LDAP/AD:", "Other Attributes:" : "Другие атрибуты:", "Defines the filter to apply, when login is attempted. %%uid replaces the username in the login action. Example: \"uid=%%uid\"" : "Определяет фильтр для применения при попытке входа. %%uid заменяет имя пользователя при входе в систему. Например: \"uid=%%uid\"", "1. Server" : "Сервер 1.", @@ -64,7 +64,7 @@ try { \OC::$server->getTempManager()->cleanOld(); // Exit if background jobs are disabled! - $appMode = OC_BackgroundJob::getExecutionType(); + $appMode = \OCP\BackgroundJob::getExecutionType(); if ($appMode == 'none') { if (OC::$CLI) { echo 'Background Jobs are disabled!' . PHP_EOL; @@ -107,7 +107,7 @@ try { // We call ownCloud from the CLI (aka cron) if ($appMode != 'cron') { - OC_BackgroundJob::setExecutionType('cron'); + \OCP\BackgroundJob::setExecutionType('cron'); } // open the file and try to lock if. If it is not locked, the background diff --git a/lib/l10n/ja.js b/lib/l10n/ja.js index e1121b6344b..f28db0d7204 100644 --- a/lib/l10n/ja.js +++ b/lib/l10n/ja.js @@ -84,6 +84,7 @@ OC.L10N.register( "Set an admin password." : "管理者のパスワードを設定。", "Can't create or write into the data directory %s" : "%s データディレクトリに作成、書き込みができません", "%s shared »%s« with you" : "%sが あなたと »%s«を共有しました", + "%s via %s" : "%s に %s から", "Sharing %s failed, because the backend does not allow shares from type %i" : "%s の共有に失敗しました。%i タイプからの共有は許可されていないからです。", "Sharing %s failed, because the file does not exist" : "%s の共有に失敗しました。そのようなファイルは存在しないからです。", "You are not allowed to share %s" : "%s を共有することを許可されていません。", @@ -116,6 +117,8 @@ OC.L10N.register( "A valid password must be provided" : "有効なパスワードを指定する必要があります", "The username is already being used" : "ユーザー名はすでに使われています", "No database drivers (sqlite, mysql, or postgresql) installed." : "データベースドライバー (sqlite, mysql, postgresql) がインストールされていません。", + "Microsoft Windows Platform is not supported" : "Microsoft Windows サーバーはサポートしていません。", + "Running ownCloud Server on the Microsoft Windows platform is not supported. We suggest you use a Linux server in a virtual machine if you have no option for migrating the server itself. Find Linux packages as well as easy to deploy virtual machine images on <a href=\"%s\">%s</a>. For migrating existing installations to Linux you can find some tips and a migration script in <a href=\"%s\">our documentation</a>." : "Microsoft Windowsサーバー上での ownCloud の動作は、サポートされていません。現在のサーバーOSを変更することができないのであれば、仮想マシン上で Linuxサーバーを動かすことをお勧めします。仮想マシンイメージを配置するのと同じぐらい簡単にLinuxパッケージを<a href=\"%s\">%s</a>で見つけられます。現在稼働中の設定をLinuxに移行する 移行スクリプトと注意点をこちらの<a href=\"%s\">ドキュメント</a>で確認してください。", "Cannot write into \"config\" directory" : "\"config\" ディレクトリに書き込みができません", "Cannot write into \"apps\" directory" : "\"apps\" ディレクトリに書き込みができません", "This can usually be fixed by %sgiving the webserver write access to the apps directory%s or disabling the appstore in the config file." : "多くの場合、これは %s Webサーバーにappsディレクトリ %s への書き込み権限を与えるか、設定ファイルでアプリストアを無効化することで解決できます。", @@ -141,6 +144,8 @@ OC.L10N.register( "Please make sure you have PostgreSQL >= 9 or check the logs for more information about the error" : "PostgreSQL >= 9 がインストールされているかどうか確認してください。もしくは、ログからエラーに関する詳細な情報を確認してください。", "Please change the permissions to 0770 so that the directory cannot be listed by other users." : "ディレクトリが他のユーザーから見えないように、パーミッションを 0770 に変更してください。", "Data directory (%s) is readable by other users" : "データディレクトリ (%s) は他のユーザーも閲覧することができます", + "Data directory (%s) must be an absolute path" : "データディレクトリ (%s) は、絶対パスである必要があります。", + "Check the value of \"datadirectory\" in your configuration" : "設定ファイル内の \"datadirectory\" の値を確認してください。", "Data directory (%s) is invalid" : "データディレクトリ (%s) は無効です", "Please check that the data directory contains a file \".ocdata\" in its root." : "データディレクトリに \".ocdata\" ファイルが含まれていることを確認してください。", "Could not obtain lock type %d on \"%s\"." : "\"%s\" で %d タイプのロックを取得できませんでした。" diff --git a/lib/l10n/ja.json b/lib/l10n/ja.json index 25bbc7b72fa..d096d48e3c2 100644 --- a/lib/l10n/ja.json +++ b/lib/l10n/ja.json @@ -82,6 +82,7 @@ "Set an admin password." : "管理者のパスワードを設定。", "Can't create or write into the data directory %s" : "%s データディレクトリに作成、書き込みができません", "%s shared »%s« with you" : "%sが あなたと »%s«を共有しました", + "%s via %s" : "%s に %s から", "Sharing %s failed, because the backend does not allow shares from type %i" : "%s の共有に失敗しました。%i タイプからの共有は許可されていないからです。", "Sharing %s failed, because the file does not exist" : "%s の共有に失敗しました。そのようなファイルは存在しないからです。", "You are not allowed to share %s" : "%s を共有することを許可されていません。", @@ -114,6 +115,8 @@ "A valid password must be provided" : "有効なパスワードを指定する必要があります", "The username is already being used" : "ユーザー名はすでに使われています", "No database drivers (sqlite, mysql, or postgresql) installed." : "データベースドライバー (sqlite, mysql, postgresql) がインストールされていません。", + "Microsoft Windows Platform is not supported" : "Microsoft Windows サーバーはサポートしていません。", + "Running ownCloud Server on the Microsoft Windows platform is not supported. We suggest you use a Linux server in a virtual machine if you have no option for migrating the server itself. Find Linux packages as well as easy to deploy virtual machine images on <a href=\"%s\">%s</a>. For migrating existing installations to Linux you can find some tips and a migration script in <a href=\"%s\">our documentation</a>." : "Microsoft Windowsサーバー上での ownCloud の動作は、サポートされていません。現在のサーバーOSを変更することができないのであれば、仮想マシン上で Linuxサーバーを動かすことをお勧めします。仮想マシンイメージを配置するのと同じぐらい簡単にLinuxパッケージを<a href=\"%s\">%s</a>で見つけられます。現在稼働中の設定をLinuxに移行する 移行スクリプトと注意点をこちらの<a href=\"%s\">ドキュメント</a>で確認してください。", "Cannot write into \"config\" directory" : "\"config\" ディレクトリに書き込みができません", "Cannot write into \"apps\" directory" : "\"apps\" ディレクトリに書き込みができません", "This can usually be fixed by %sgiving the webserver write access to the apps directory%s or disabling the appstore in the config file." : "多くの場合、これは %s Webサーバーにappsディレクトリ %s への書き込み権限を与えるか、設定ファイルでアプリストアを無効化することで解決できます。", @@ -139,6 +142,8 @@ "Please make sure you have PostgreSQL >= 9 or check the logs for more information about the error" : "PostgreSQL >= 9 がインストールされているかどうか確認してください。もしくは、ログからエラーに関する詳細な情報を確認してください。", "Please change the permissions to 0770 so that the directory cannot be listed by other users." : "ディレクトリが他のユーザーから見えないように、パーミッションを 0770 に変更してください。", "Data directory (%s) is readable by other users" : "データディレクトリ (%s) は他のユーザーも閲覧することができます", + "Data directory (%s) must be an absolute path" : "データディレクトリ (%s) は、絶対パスである必要があります。", + "Check the value of \"datadirectory\" in your configuration" : "設定ファイル内の \"datadirectory\" の値を確認してください。", "Data directory (%s) is invalid" : "データディレクトリ (%s) は無効です", "Please check that the data directory contains a file \".ocdata\" in its root." : "データディレクトリに \".ocdata\" ファイルが含まれていることを確認してください。", "Could not obtain lock type %d on \"%s\"." : "\"%s\" で %d タイプのロックを取得できませんでした。" diff --git a/lib/private/api.php b/lib/private/api.php index 119cdb7d1a3..dd50162f03e 100644 --- a/lib/private/api.php +++ b/lib/private/api.php @@ -34,17 +34,33 @@ class OC_API { /** * API authentication levels */ + + /** @deprecated Use \OCP\API::GUEST_AUTH instead */ const GUEST_AUTH = 0; + + /** @deprecated Use \OCP\API::USER_AUTH instead */ const USER_AUTH = 1; + + /** @deprecated Use \OCP\API::SUBADMIN_AUTH instead */ const SUBADMIN_AUTH = 2; + + /** @deprecated Use \OCP\API::ADMIN_AUTH instead */ const ADMIN_AUTH = 3; /** * API Response Codes */ + + /** @deprecated Use \OCP\API::RESPOND_UNAUTHORISED instead */ const RESPOND_UNAUTHORISED = 997; + + /** @deprecated Use \OCP\API::RESPOND_SERVER_ERROR instead */ const RESPOND_SERVER_ERROR = 996; + + /** @deprecated Use \OCP\API::RESPOND_NOT_FOUND instead */ const RESPOND_NOT_FOUND = 998; + + /** @deprecated Use \OCP\API::RESPOND_UNKNOWN_ERROR instead */ const RESPOND_UNKNOWN_ERROR = 999; /** @@ -65,7 +81,7 @@ class OC_API { * @param array $requirements */ public static function register($method, $url, $action, $app, - $authLevel = OC_API::USER_AUTH, + $authLevel = \OCP\API::USER_AUTH, $defaults = array(), $requirements = array()) { $name = strtolower($method).$url; @@ -106,7 +122,7 @@ class OC_API { if(!self::isAuthorised($action)) { $responses[] = array( 'app' => $action['app'], - 'response' => new OC_OCS_Result(null, OC_API::RESPOND_UNAUTHORISED, 'Unauthorised'), + 'response' => new OC_OCS_Result(null, \OCP\API::RESPOND_UNAUTHORISED, 'Unauthorised'), 'shipped' => OC_App::isShipped($action['app']), ); continue; @@ -114,7 +130,7 @@ class OC_API { if(!is_callable($action['action'])) { $responses[] = array( 'app' => $action['app'], - 'response' => new OC_OCS_Result(null, OC_API::RESPOND_NOT_FOUND, 'Api method not found'), + 'response' => new OC_OCS_Result(null, \OCP\API::RESPOND_NOT_FOUND, 'Api method not found'), 'shipped' => OC_App::isShipped($action['app']), ); continue; @@ -172,7 +188,7 @@ class OC_API { // Which shipped response do we use if they all failed? // They may have failed for different reasons (different status codes) // Which response code should we return? - // Maybe any that are not OC_API::RESPOND_SERVER_ERROR + // Maybe any that are not \OCP\API::RESPOND_SERVER_ERROR // Merge failed responses if more than one $data = array(); foreach($shipped['failed'] as $failure) { @@ -235,15 +251,15 @@ class OC_API { private static function isAuthorised($action) { $level = $action['authlevel']; switch($level) { - case OC_API::GUEST_AUTH: + case \OCP\API::GUEST_AUTH: // Anyone can access return true; break; - case OC_API::USER_AUTH: + case \OCP\API::USER_AUTH: // User required return self::loginUser(); break; - case OC_API::SUBADMIN_AUTH: + case \OCP\API::SUBADMIN_AUTH: // Check for subadmin $user = self::loginUser(); if(!$user) { @@ -258,7 +274,7 @@ class OC_API { } } break; - case OC_API::ADMIN_AUTH: + case \OCP\API::ADMIN_AUTH: // Check for admin $user = self::loginUser(); if(!$user) { @@ -325,7 +341,7 @@ class OC_API { */ public static function respond($result, $format='xml') { // Send 401 headers if unauthorised - if($result->getStatusCode() === self::RESPOND_UNAUTHORISED) { + if($result->getStatusCode() === \OCP\API::RESPOND_UNAUTHORISED) { header('WWW-Authenticate: Basic realm="Authorisation Required"'); header('HTTP/1.0 401 Unauthorized'); } @@ -384,7 +400,7 @@ class OC_API { * Based on the requested format the response content type is set */ public static function setContentType() { - $format = \OC_API::requestedFormat(); + $format = self::requestedFormat(); if ($format === 'xml') { header('Content-type: text/xml; charset=UTF-8'); return; diff --git a/lib/private/appframework/http/request.php b/lib/private/appframework/http/request.php index eb2a118a0f6..2455209cdf3 100644 --- a/lib/private/appframework/http/request.php +++ b/lib/private/appframework/http/request.php @@ -359,7 +359,7 @@ class Request implements \ArrayAccess, \Countable, IRequest { * @param string $key the key that will be taken from the $_COOKIE array * @return array the value in the $_COOKIE element */ - function getCookie($key) { + public function getCookie($key) { return isset($this->cookies[$key]) ? $this->cookies[$key] : null; } diff --git a/lib/private/appframework/utility/simplecontainer.php b/lib/private/appframework/utility/simplecontainer.php index 9e80f89e458..c7dff6f4571 100644 --- a/lib/private/appframework/utility/simplecontainer.php +++ b/lib/private/appframework/utility/simplecontainer.php @@ -106,7 +106,7 @@ class SimpleContainer extends \Pimple\Container implements \OCP\IContainer { * @param string $name * @param mixed $value */ - function registerParameter($name, $value) { + public function registerParameter($name, $value) { $this[$name] = $value; } @@ -119,7 +119,7 @@ class SimpleContainer extends \Pimple\Container implements \OCP\IContainer { * @param \Closure $closure the closure to be called on service creation * @param bool $shared */ - function registerService($name, \Closure $closure, $shared = true) { + public function registerService($name, \Closure $closure, $shared = true) { if (isset($this[$name])) { unset($this[$name]); } diff --git a/lib/private/avatarmanager.php b/lib/private/avatarmanager.php index 578ab05d49b..0ff4a3444e2 100644 --- a/lib/private/avatarmanager.php +++ b/lib/private/avatarmanager.php @@ -38,7 +38,7 @@ class AvatarManager implements IAvatarManager { * @param string $user the ownCloud user id * @return \OCP\IAvatar */ - function getAvatar($user) { + public function getAvatar($user) { return new Avatar($user); } } diff --git a/lib/private/backgroundjob.php b/lib/private/backgroundjob.php deleted file mode 100644 index 574109feee1..00000000000 --- a/lib/private/backgroundjob.php +++ /dev/null @@ -1,56 +0,0 @@ -<?php -/** - * @author Bart Visscher <bartv@thisnet.nl> - * @author Felix Moeller <mail@felixmoeller.de> - * @author Jakob Sack <mail@jakobsack.de> - * @author Jörn Friedrich Dreyer <jfd@butonic.de> - * @author Morris Jobke <hey@morrisjobke.de> - * @author Scrutinizer Auto-Fixer <auto-fixer@scrutinizer-ci.com> - * - * @copyright Copyright (c) 2015, ownCloud, Inc. - * @license AGPL-3.0 - * - * This code is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License, version 3, - * as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License, version 3, - * along with this program. If not, see <http://www.gnu.org/licenses/> - * - */ - -/** - * This class does the dirty work. - */ -class OC_BackgroundJob{ - /** - * get the execution type of background jobs - * @return string - * - * This method returns the type how background jobs are executed. If the user - * did not select something, the type is ajax. - */ - public static function getExecutionType() { - return OC_Appconfig::getValue( 'core', 'backgroundjobs_mode', 'ajax' ); - } - - /** - * sets the background jobs execution type - * @param string $type execution type - * @return false|null - * - * This method sets the execution type of the background jobs. Possible types - * are "none", "ajax", "webcron", "cron" - */ - public static function setExecutionType( $type ) { - if( !in_array( $type, array('none', 'ajax', 'webcron', 'cron'))) { - return false; - } - return OC_Appconfig::setValue( 'core', 'backgroundjobs_mode', $type ); - } -} diff --git a/lib/private/preview/txt.php b/lib/private/preview/txt.php index 80fd0c7ebb4..ea817388f86 100644 --- a/lib/private/preview/txt.php +++ b/lib/private/preview/txt.php @@ -55,7 +55,7 @@ class TXT extends Provider { $lines = preg_split("/\r\n|\n|\r/", $content); - $fontSize = 5; //5px + $fontSize = ($maxX) ? (int) ((5 / 36) * $maxX) : 5; //5px $lineSize = ceil($fontSize * 1.25); $image = imagecreate($maxX, $maxY); diff --git a/lib/private/response.php b/lib/private/response.php index 018c44d2367..5725af2b893 100644 --- a/lib/private/response.php +++ b/lib/private/response.php @@ -212,9 +212,10 @@ class OC_Response { } /** - * Send file as response, checking and setting caching headers - * @param string $filepath of file to send - */ + * Send file as response, checking and setting caching headers + * @param string $filepath of file to send + * @deprecated 8.1.0 - Use \OCP\AppFramework\Http\StreamResponse or another AppFramework controller instead + */ static public function sendFile($filepath) { $fp = fopen($filepath, 'rb'); if ($fp) { diff --git a/lib/private/route/route.php b/lib/private/route/route.php index cb864d3d73d..b33360f11ec 100644 --- a/lib/private/route/route.php +++ b/lib/private/route/route.php @@ -37,7 +37,7 @@ class Route extends SymfonyRoute implements IRoute { * @return \OC\Route\Route */ public function method($method) { - $this->setRequirement('_method', strtoupper($method)); + $this->setMethods($method); return $this; } @@ -109,7 +109,7 @@ class Route extends SymfonyRoute implements IRoute { * @return \OC\Route\Route */ public function requirements($requirements) { - $method = $this->getRequirement('_method'); + $method = $this->getMethods(); $this->setRequirements($requirements); if (isset($requirements['_method'])) { $method = $requirements['_method']; diff --git a/lib/private/security/certificate.php b/lib/private/security/certificate.php index 468427d0702..0d7fcc4148d 100644 --- a/lib/private/security/certificate.php +++ b/lib/private/security/certificate.php @@ -49,18 +49,18 @@ class Certificate implements ICertificate { */ public function __construct($data, $name) { $this->name = $name; - try { - $gmt = new \DateTimeZone('GMT'); - $info = openssl_x509_parse($data); - $this->commonName = isset($info['subject']['CN']) ? $info['subject']['CN'] : null; - $this->organization = isset($info['subject']['O']) ? $info['subject']['O'] : null; - $this->issueDate = new \DateTime('@' . $info['validFrom_time_t'], $gmt); - $this->expireDate = new \DateTime('@' . $info['validTo_time_t'], $gmt); - $this->issuerName = isset($info['issuer']['CN']) ? $info['issuer']['CN'] : null; - $this->issuerOrganization = isset($info['issuer']['O']) ? $info['issuer']['O'] : null; - } catch (\Exception $e) { + $gmt = new \DateTimeZone('GMT'); + $info = openssl_x509_parse($data); + if(!is_array($info)) { throw new \Exception('Certificate could not get parsed.'); } + + $this->commonName = isset($info['subject']['CN']) ? $info['subject']['CN'] : null; + $this->organization = isset($info['subject']['O']) ? $info['subject']['O'] : null; + $this->issueDate = new \DateTime('@' . $info['validFrom_time_t'], $gmt); + $this->expireDate = new \DateTime('@' . $info['validTo_time_t'], $gmt); + $this->issuerName = isset($info['issuer']['CN']) ? $info['issuer']['CN'] : null; + $this->issuerOrganization = isset($info['issuer']['O']) ? $info['issuer']['O'] : null; } /** diff --git a/lib/private/security/certificatemanager.php b/lib/private/security/certificatemanager.php index beeb87a8316..d61c7f29327 100644 --- a/lib/private/security/certificatemanager.php +++ b/lib/private/security/certificatemanager.php @@ -107,12 +107,12 @@ class CertificateManager implements ICertificateManager { * * @param string $certificate the certificate data * @param string $name the filename for the certificate - * @return \OCP\ICertificate|void|bool + * @return \OCP\ICertificate * @throws \Exception If the certificate could not get added */ public function addCertificate($certificate, $name) { if (!Filesystem::isValidPath($name) or Filesystem::isFileBlacklisted($name)) { - return false; + throw new \Exception('Filename is not valid'); } $dir = $this->getPathToCertificates() . 'uploads/'; diff --git a/lib/public/api.php b/lib/public/api.php index 7ef6902634c..6b920b6cf52 100644 --- a/lib/public/api.php +++ b/lib/public/api.php @@ -38,17 +38,35 @@ namespace OCP; class API { /** + * API authentication levels + * @since 8.1.0 + */ + const GUEST_AUTH = 0; + const USER_AUTH = 1; + const SUBADMIN_AUTH = 2; + const ADMIN_AUTH = 3; + + /** + * API Response Codes + * @since 8.1.0 + */ + const RESPOND_UNAUTHORISED = 997; + const RESPOND_SERVER_ERROR = 996; + const RESPOND_NOT_FOUND = 998; + const RESPOND_UNKNOWN_ERROR = 999; + + /** * registers an api call * @param string $method the http method * @param string $url the url to match * @param callable $action the function to run * @param string $app the id of the app registering the call - * @param int $authLevel the level of authentication required for the call (See OC_API constants) + * @param int $authLevel the level of authentication required for the call (See `self::*_AUTH` constants) * @param array $defaults * @param array $requirements * @since 5.0.0 */ - public static function register($method, $url, $action, $app, $authLevel = OC_API::USER_AUTH, + public static function register($method, $url, $action, $app, $authLevel = self::USER_AUTH, $defaults = array(), $requirements = array()){ \OC_API::register($method, $url, $action, $app, $authLevel, $defaults, $requirements); } diff --git a/lib/public/backgroundjob.php b/lib/public/backgroundjob.php index 3fd8ff92b2d..176c1d6e1ae 100644 --- a/lib/public/backgroundjob.php +++ b/lib/public/backgroundjob.php @@ -60,7 +60,7 @@ class BackgroundJob { * @since 5.0.0 */ public static function getExecutionType() { - return \OC_BackgroundJob::getExecutionType(); + return \OC::$server->getConfig()->getAppValue('core', 'backgroundjobs_mode', 'ajax'); } /** @@ -74,7 +74,10 @@ class BackgroundJob { * @since 5.0.0 */ public static function setExecutionType($type) { - return \OC_BackgroundJob::setExecutionType($type); + if( !in_array( $type, array('none', 'ajax', 'webcron', 'cron'))) { + return false; + } + \OC::$server->getConfig()->setAppValue('core', 'backgroundjobs_mode', $type); } /** diff --git a/lib/public/iavatar.php b/lib/public/iavatar.php index 6bf2ce1f19b..fc29212a599 100644 --- a/lib/public/iavatar.php +++ b/lib/public/iavatar.php @@ -37,7 +37,7 @@ interface IAvatar { * @return boolean|\OCP\IImage containing the avatar or false if there's no image * @since 6.0.0 */ - function get($size = 64); + public function get($size = 64); /** * Check if an avatar exists for the user @@ -56,12 +56,12 @@ interface IAvatar { * @return void * @since 6.0.0 */ - function set($data); + public function set($data); /** * remove the users avatar * @return void * @since 6.0.0 */ - function remove(); + public function remove(); } diff --git a/lib/public/iavatarmanager.php b/lib/public/iavatarmanager.php index 583b7f0afca..5ad5bf6a364 100644 --- a/lib/public/iavatarmanager.php +++ b/lib/public/iavatarmanager.php @@ -38,5 +38,5 @@ interface IAvatarManager { * @return \OCP\IAvatar * @since 6.0.0 */ - function getAvatar($user); + public function getAvatar($user); } diff --git a/lib/public/icertificatemanager.php b/lib/public/icertificatemanager.php index ec88f32e291..3014cd8f633 100644 --- a/lib/public/icertificatemanager.php +++ b/lib/public/icertificatemanager.php @@ -38,7 +38,8 @@ interface ICertificateManager { /** * @param string $certificate the certificate data * @param string $name the filename for the certificate - * @return bool | \OCP\ICertificate + * @return \OCP\ICertificate + * @throws \Exception If the certificate could not get added * @since 8.0.0 */ public function addCertificate($certificate, $name); diff --git a/lib/public/icontainer.php b/lib/public/icontainer.php index 27ca544ec67..35bf6a76ce8 100644 --- a/lib/public/icontainer.php +++ b/lib/public/icontainer.php @@ -47,7 +47,7 @@ interface IContainer { * @return mixed * @since 6.0.0 */ - function query($name); + public function query($name); /** * A value is stored in the container with it's corresponding name @@ -57,7 +57,7 @@ interface IContainer { * @return void * @since 6.0.0 */ - function registerParameter($name, $value); + public function registerParameter($name, $value); /** * A service is registered in the container where a closure is passed in which will actually @@ -72,5 +72,5 @@ interface IContainer { * @return void * @since 6.0.0 */ - function registerService($name, \Closure $closure, $shared = true); + public function registerService($name, \Closure $closure, $shared = true); } diff --git a/lib/public/ilogger.php b/lib/public/ilogger.php index c36d9ff285c..43b1ef70e5b 100644 --- a/lib/public/ilogger.php +++ b/lib/public/ilogger.php @@ -39,7 +39,7 @@ interface ILogger { * @return null * @since 7.0.0 */ - function emergency($message, array $context = array()); + public function emergency($message, array $context = array()); /** * Action must be taken immediately. @@ -49,7 +49,7 @@ interface ILogger { * @return null * @since 7.0.0 */ - function alert($message, array $context = array()); + public function alert($message, array $context = array()); /** * Critical conditions. @@ -59,7 +59,7 @@ interface ILogger { * @return null * @since 7.0.0 */ - function critical($message, array $context = array()); + public function critical($message, array $context = array()); /** * Runtime errors that do not require immediate action but should typically @@ -70,7 +70,7 @@ interface ILogger { * @return null * @since 7.0.0 */ - function error($message, array $context = array()); + public function error($message, array $context = array()); /** * Exceptional occurrences that are not errors. @@ -80,7 +80,7 @@ interface ILogger { * @return null * @since 7.0.0 */ - function warning($message, array $context = array()); + public function warning($message, array $context = array()); /** * Normal but significant events. @@ -90,7 +90,7 @@ interface ILogger { * @return null * @since 7.0.0 */ - function notice($message, array $context = array()); + public function notice($message, array $context = array()); /** * Interesting events. @@ -100,7 +100,7 @@ interface ILogger { * @return null * @since 7.0.0 */ - function info($message, array $context = array()); + public function info($message, array $context = array()); /** * Detailed debug information. @@ -110,7 +110,7 @@ interface ILogger { * @return null * @since 7.0.0 */ - function debug($message, array $context = array()); + public function debug($message, array $context = array()); /** * Logs with an arbitrary level. @@ -121,5 +121,5 @@ interface ILogger { * @return mixed * @since 7.0.0 */ - function log($level, $message, array $context = array()); + public function log($level, $message, array $context = array()); } diff --git a/lib/public/irequest.php b/lib/public/irequest.php index a236c5df9a0..20fa543dd69 100644 --- a/lib/public/irequest.php +++ b/lib/public/irequest.php @@ -68,7 +68,7 @@ interface IRequest { * @return string * @since 6.0.0 */ - function getHeader($name); + public function getHeader($name); /** * Lets you access post and get parameters by the index @@ -131,7 +131,7 @@ interface IRequest { * @return array the value in the $_COOKIE element * @since 6.0.0 */ - function getCookie($key); + public function getCookie($key); /** diff --git a/lib/public/response.php b/lib/public/response.php index 1942c1ec373..42220e4cf9c 100644 --- a/lib/public/response.php +++ b/lib/public/response.php @@ -37,6 +37,7 @@ namespace OCP; /** * This class provides convenient functions to send the correct http response headers * @since 4.0.0 + * @deprecated 8.1.0 - Use AppFramework controllers instead and modify the response object */ class Response { /** @@ -103,6 +104,7 @@ class Response { * Send file as response, checking and setting caching headers * @param string $filepath of file to send * @since 4.0.0 + * @deprecated 8.1.0 - Use \OCP\AppFramework\Http\StreamResponse or another AppFramework controller instead */ static public function sendFile( $filepath ) { \OC_Response::sendFile( $filepath ); diff --git a/ocs/routes.php b/ocs/routes.php index 2a8fe5dc2af..751a16d538e 100644 --- a/ocs/routes.php +++ b/ocs/routes.php @@ -23,109 +23,111 @@ * */ +use OCP\API; + // Config -OC_API::register( +API::register( 'get', '/config', array('OC_OCS_Config', 'apiConfig'), 'core', - OC_API::GUEST_AUTH + API::GUEST_AUTH ); // Person -OC_API::register( +API::register( 'post', '/person/check', array('OC_OCS_Person', 'check'), 'core', - OC_API::GUEST_AUTH + API::GUEST_AUTH ); // Privatedata -OC_API::register( +API::register( 'get', '/privatedata/getattribute', array('OC_OCS_Privatedata', 'get'), 'core', - OC_API::USER_AUTH, + API::USER_AUTH, array('app' => '', 'key' => '') ); -OC_API::register( +API::register( 'get', '/privatedata/getattribute/{app}', array('OC_OCS_Privatedata', 'get'), 'core', - OC_API::USER_AUTH, + API::USER_AUTH, array('key' => '') ); -OC_API::register( +API::register( 'get', '/privatedata/getattribute/{app}/{key}', array('OC_OCS_Privatedata', 'get'), 'core', - OC_API::USER_AUTH + API::USER_AUTH ); -OC_API::register( +API::register( 'post', '/privatedata/setattribute/{app}/{key}', array('OC_OCS_Privatedata', 'set'), 'core', - OC_API::USER_AUTH + API::USER_AUTH ); -OC_API::register( +API::register( 'post', '/privatedata/deleteattribute/{app}/{key}', array('OC_OCS_Privatedata', 'delete'), 'core', - OC_API::USER_AUTH + API::USER_AUTH ); // cloud -OC_API::register( +API::register( 'get', '/cloud/capabilities', array('OC_OCS_Cloud', 'getCapabilities'), 'core', - OC_API::USER_AUTH + API::USER_AUTH ); -OC_API::register( +API::register( 'get', '/cloud/users/{userid}', array('OC_OCS_Cloud', 'getUser'), 'core', - OC_API::USER_AUTH + API::USER_AUTH ); -OC_API::register( +API::register( 'get', '/cloud/user', array('OC_OCS_Cloud', 'getCurrentUser'), 'core', - OC_API::USER_AUTH + API::USER_AUTH ); // Server-to-Server Sharing $s2s = new \OCA\Files_Sharing\API\Server2Server(); -OC_API::register('post', +API::register('post', '/cloud/shares', array($s2s, 'createShare'), 'files_sharing', - OC_API::GUEST_AUTH + API::GUEST_AUTH ); -OC_API::register('post', +API::register('post', '/cloud/shares/{id}/accept', array($s2s, 'acceptShare'), 'files_sharing', - OC_API::GUEST_AUTH + API::GUEST_AUTH ); -OC_API::register('post', +API::register('post', '/cloud/shares/{id}/decline', array($s2s, 'declineShare'), 'files_sharing', - OC_API::GUEST_AUTH + API::GUEST_AUTH ); -OC_API::register('post', +API::register('post', '/cloud/shares/{id}/unshare', array($s2s, 'unshare'), 'files_sharing', - OC_API::GUEST_AUTH + API::GUEST_AUTH ); diff --git a/settings/ajax/addRootCertificate.php b/settings/ajax/addRootCertificate.php deleted file mode 100644 index 64a55eaede9..00000000000 --- a/settings/ajax/addRootCertificate.php +++ /dev/null @@ -1,52 +0,0 @@ -<?php -/** - * @author Lukas Reschke <lukas@owncloud.com> - * @author Robin Appelman <icewind@owncloud.com> - * - * @copyright Copyright (c) 2015, ownCloud, Inc. - * @license AGPL-3.0 - * - * This code is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License, version 3, - * as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License, version 3, - * along with this program. If not, see <http://www.gnu.org/licenses/> - * - */ -OCP\JSON::checkLoggedIn(); -OCP\JSON::callCheck(); - -$l = new OC_L10N('core'); - -if (!isset($_FILES['rootcert_import'])) { - OCP\JSON::error(array('error' => 'No certificate uploaded')); - exit; -} - -$data = file_get_contents($_FILES['rootcert_import']['tmp_name']); -$filename = basename($_FILES['rootcert_import']['name']); - -$certificateManager = \OC::$server->getCertificateManager(); - -try { - $cert = $certificateManager->addCertificate($data, $filename); - OCP\JSON::success(array( - 'name' => $cert->getName(), - 'commonName' => $cert->getCommonName(), - 'organization' => $cert->getOrganization(), - 'validFrom' => $cert->getIssueDate()->getTimestamp(), - 'validTill' => $cert->getExpireDate()->getTimestamp(), - 'validFromString' => $l->l('date', $cert->getIssueDate()), - 'validTillString' => $l->l('date', $cert->getExpireDate()), - 'issuer' => $cert->getIssuerName(), - 'issuerOrganization' => $cert->getIssuerOrganization() - )); -} catch(\Exception $e) { - OCP\JSON::error(array('error' => 'Couldn\'t import SSL root certificate, allowed formats: PEM and DER')); -} diff --git a/settings/ajax/removeRootCertificate.php b/settings/ajax/removeRootCertificate.php deleted file mode 100644 index 4ef5fe32aed..00000000000 --- a/settings/ajax/removeRootCertificate.php +++ /dev/null @@ -1,28 +0,0 @@ -<?php -/** - * @author Björn Schießle <schiessle@owncloud.com> - * @author Lukas Reschke <lukas@owncloud.com> - * @author Robin Appelman <icewind@owncloud.com> - * - * @copyright Copyright (c) 2015, ownCloud, Inc. - * @license AGPL-3.0 - * - * This code is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License, version 3, - * as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License, version 3, - * along with this program. If not, see <http://www.gnu.org/licenses/> - * - */ -OCP\JSON::checkLoggedIn(); -OCP\JSON::callCheck(); - -$name = (string)$_POST['cert']; -$certificateManager = \OC::$server->getCertificateManager(); -$certificateManager->removeCertificate($name); diff --git a/settings/application.php b/settings/application.php index 59fe9f6b65a..920d172c93d 100644 --- a/settings/application.php +++ b/settings/application.php @@ -25,6 +25,7 @@ namespace OC\Settings; use OC\Files\View; use OC\Settings\Controller\AppSettingsController; +use OC\Settings\Controller\CertificateController; use OC\Settings\Controller\CheckSetupController; use OC\Settings\Controller\EncryptionController; use OC\Settings\Controller\GroupsController; @@ -97,6 +98,14 @@ class Application extends App { $c->query('Config') ); }); + $container->registerService('CertificateController', function(IContainer $c) { + return new CertificateController( + $c->query('AppName'), + $c->query('Request'), + $c->query('CertificateManager'), + $c->query('L10N') + ); + }); $container->registerService('GroupsController', function(IContainer $c) { return new GroupsController( $c->query('AppName'), @@ -223,5 +232,8 @@ class Application extends App { $container->registerService('DatabaseConnection', function(IContainer $c) { return $c->query('ServerContainer')->getDatabaseConnection(); }); + $container->registerService('CertificateManager', function(IContainer $c){ + return $c->query('ServerContainer')->getCertificateManager(); + }); } } diff --git a/settings/controller/certificatecontroller.php b/settings/controller/certificatecontroller.php new file mode 100644 index 00000000000..d9026cd42af --- /dev/null +++ b/settings/controller/certificatecontroller.php @@ -0,0 +1,93 @@ +<?php +/** + * @author Lukas Reschke <lukas@owncloud.com> + * + * @copyright Copyright (c) 2015, ownCloud, Inc. + * @license AGPL-3.0 + * + * This code is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License, version 3, + * as published by the Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License, version 3, + * along with this program. If not, see <http://www.gnu.org/licenses/> + * + */ + +namespace OC\Settings\Controller; + +use OCP\AppFramework\Controller; +use OCP\AppFramework\Http; +use OCP\AppFramework\Http\DataResponse; +use OCP\ICertificateManager; +use OCP\IL10N; +use OCP\IRequest; + +/** + * @package OC\Settings\Controller + */ +class CertificateController extends Controller { + /** @var ICertificateManager */ + private $certificateManager; + /** @var IL10N */ + private $l10n; + + /** + * @param string $appName + * @param IRequest $request + * @param ICertificateManager $certificateManager + * @param IL10N $l10n + */ + public function __construct($appName, + IRequest $request, + ICertificateManager $certificateManager, + IL10N $l10n) { + parent::__construct($appName, $request); + $this->certificateManager = $certificateManager; + $this->l10n = $l10n; + } + + /** + * Add a new personal root certificate to the users' trust store + * @return array + */ + public function addPersonalRootCertificate() { + $file = $this->request->getUploadedFile('rootcert_import'); + if(empty($file)) { + return new DataResponse(['message' => 'No file uploaded'], Http::STATUS_UNPROCESSABLE_ENTITY); + } + + try { + $certificate = $this->certificateManager->addCertificate(file_get_contents($file['tmp_name']), $file['name']); + return new DataResponse([ + 'name' => $certificate->getName(), + 'commonName' => $certificate->getCommonName(), + 'organization' => $certificate->getOrganization(), + 'validFrom' => $certificate->getIssueDate()->getTimestamp(), + 'validTill' => $certificate->getExpireDate()->getTimestamp(), + 'validFromString' => $this->l10n->l('date', $certificate->getIssueDate()), + 'validTillString' => $this->l10n->l('date', $certificate->getExpireDate()), + 'issuer' => $certificate->getIssuerName(), + 'issuerOrganization' => $certificate->getIssuerOrganization(), + ]); + } catch (\Exception $e) { + return new DataResponse('An error occurred.', Http::STATUS_UNPROCESSABLE_ENTITY); + } + } + + /** + * Removes a personal root certificate from the users' trust store + * @param string $certificateIdentifier + * @return DataResponse + */ + public function removePersonalRootCertificate($certificateIdentifier) { + $this->certificateManager->removeCertificate($certificateIdentifier); + return new DataResponse(); + } + +} diff --git a/settings/js/personal.js b/settings/js/personal.js index 687b02399a7..165b55bcdae 100644 --- a/settings/js/personal.js +++ b/settings/js/personal.js @@ -297,8 +297,8 @@ $(document).ready(function () { $('#sslCertificate').on('click', 'td.remove > img', function () { var row = $(this).parent().parent(); - $.post(OC.generateUrl('settings/ajax/removeRootCertificate'), { - cert: row.data('name') + $.ajax(OC.generateUrl('settings/personal/certificate/{certificate}', {certificate: row.data('name')}), { + type: 'DELETE' }); row.remove(); return true; @@ -307,18 +307,19 @@ $(document).ready(function () { $('#sslCertificate tr > td').tipsy({gravity: 'n', live: true}); $('#rootcert_import').fileupload({ - done: function (e, data) { - var issueDate = new Date(data.result.validFrom * 1000); - var expireDate = new Date(data.result.validTill * 1000); + success: function (data) { + var issueDate = new Date(data.validFrom * 1000); + var expireDate = new Date(data.validTill * 1000); var now = new Date(); var isExpired = !(issueDate <= now && now <= expireDate); var row = $('<tr/>'); + row.data('name', data.name); row.addClass(isExpired? 'expired': 'valid'); - row.append($('<td/>').attr('title', data.result.organization).text(data.result.commonName)); - row.append($('<td/>').attr('title', t('core,', 'Valid until {date}', {date: data.result.validFromString})) - .text(data.result.validTillString)); - row.append($('<td/>').attr('title', data.result.issuerOrganization).text(data.result.issuer)); + row.append($('<td/>').attr('title', data.organization).text(data.commonName)); + row.append($('<td/>').attr('title', t('core,', 'Valid until {date}', {date: data.validTillString})) + .text(data.validTillString)); + row.append($('<td/>').attr('title', data.issuerOrganization).text(data.issuer)); row.append($('<td/>').addClass('remove').append( $('<img/>').attr({ alt: t('core', 'Delete'), @@ -328,6 +329,9 @@ $(document).ready(function () { )); $('#sslCertificate tbody').append(row); + }, + fail: function (e, data) { + OC.Notification.showTemporary(t('settings', 'An error occured. Please upload an ASCII-encoded PEM certificate.')); } }); diff --git a/settings/l10n/fr.js b/settings/l10n/fr.js index 3be50ae0ee2..4109a602df1 100644 --- a/settings/l10n/fr.js +++ b/settings/l10n/fr.js @@ -4,7 +4,9 @@ OC.L10N.register( "Security & setup warnings" : "Avertissements de sécurité ou de configuration", "Sharing" : "Partage", "External Storage" : "Stockage externe", + "Server-side encryption" : "Chiffrement côté serveur", "Cron" : "Cron", + "Email server" : "Serveur mail", "Log" : "Log", "Tips & tricks" : "Trucs et astuces", "Updates" : "Mises à jour", @@ -137,6 +139,7 @@ OC.L10N.register( "Execute one task with each page loaded" : "Exécute une tâche à chaque chargement de page", "cron.php is registered at a webcron service to call cron.php every 15 minutes over http." : "cron.php est enregistré auprès d'un service webcron qui l'exécutera toutes les 15 minutes via http.", "Use system's cron service to call the cron.php file every 15 minutes." : "Utilisez le service cron du système pour appeler le fichier cron.php toutes les 15 minutes.", + "Enable server-side encryption" : "Activer le chiffrement côté serveur", "Start migration" : "Démarrer la migration", "This is used for sending out notifications." : "Ceci est utilisé pour l'envoi des notifications.", "Send mode" : "Mode d'envoi", @@ -159,7 +162,7 @@ OC.L10N.register( "Less" : "Moins", "The logfile is bigger than 100 MB. Downloading it may take some time!" : "La taille du fichier journal excède 100 Mo. Le télécharger peut prendre un certain temps!", "SQLite is used as database. For larger installations we recommend to switch to a different database backend." : "SQLite est actuellement utilisé comme gestionnaire de base de données. Pour des installations plus volumineuses, nous vous conseillons d'utiliser un autre gestionnaire de base de données.", - "Especially when using the desktop client for file syncing the use of SQLite is discouraged." : "En particulier si vous utilisez le client de bureau pour synchroniser vos données : l'utilisation de SQLite est alors déconseillée.", + "Especially when using the desktop client for file syncing the use of SQLite is discouraged." : "L'utilisation de SQLite est particulièrement déconseillée si vous utilisez le client de bureau pour synchroniser vos données.", "To migrate to another database use the command line tool: 'occ db:convert-type', or see the <a target=\"_blank\" href=\"%s\">documentation ↗</a>." : "Pour migrer vers un autre type de base de données, utilisez la ligne de commande : 'occ db:convert-type' ou consultez la <a target=\"_blank\" href=\"%s\">documentation ↗</a>.", "How to do backups" : "Comment faire des sauvegardes", "Advanced monitoring" : "Surveillance avancée", diff --git a/settings/l10n/fr.json b/settings/l10n/fr.json index eac4dabeb00..0a3902925bc 100644 --- a/settings/l10n/fr.json +++ b/settings/l10n/fr.json @@ -2,7 +2,9 @@ "Security & setup warnings" : "Avertissements de sécurité ou de configuration", "Sharing" : "Partage", "External Storage" : "Stockage externe", + "Server-side encryption" : "Chiffrement côté serveur", "Cron" : "Cron", + "Email server" : "Serveur mail", "Log" : "Log", "Tips & tricks" : "Trucs et astuces", "Updates" : "Mises à jour", @@ -135,6 +137,7 @@ "Execute one task with each page loaded" : "Exécute une tâche à chaque chargement de page", "cron.php is registered at a webcron service to call cron.php every 15 minutes over http." : "cron.php est enregistré auprès d'un service webcron qui l'exécutera toutes les 15 minutes via http.", "Use system's cron service to call the cron.php file every 15 minutes." : "Utilisez le service cron du système pour appeler le fichier cron.php toutes les 15 minutes.", + "Enable server-side encryption" : "Activer le chiffrement côté serveur", "Start migration" : "Démarrer la migration", "This is used for sending out notifications." : "Ceci est utilisé pour l'envoi des notifications.", "Send mode" : "Mode d'envoi", @@ -157,7 +160,7 @@ "Less" : "Moins", "The logfile is bigger than 100 MB. Downloading it may take some time!" : "La taille du fichier journal excède 100 Mo. Le télécharger peut prendre un certain temps!", "SQLite is used as database. For larger installations we recommend to switch to a different database backend." : "SQLite est actuellement utilisé comme gestionnaire de base de données. Pour des installations plus volumineuses, nous vous conseillons d'utiliser un autre gestionnaire de base de données.", - "Especially when using the desktop client for file syncing the use of SQLite is discouraged." : "En particulier si vous utilisez le client de bureau pour synchroniser vos données : l'utilisation de SQLite est alors déconseillée.", + "Especially when using the desktop client for file syncing the use of SQLite is discouraged." : "L'utilisation de SQLite est particulièrement déconseillée si vous utilisez le client de bureau pour synchroniser vos données.", "To migrate to another database use the command line tool: 'occ db:convert-type', or see the <a target=\"_blank\" href=\"%s\">documentation ↗</a>." : "Pour migrer vers un autre type de base de données, utilisez la ligne de commande : 'occ db:convert-type' ou consultez la <a target=\"_blank\" href=\"%s\">documentation ↗</a>.", "How to do backups" : "Comment faire des sauvegardes", "Advanced monitoring" : "Surveillance avancée", diff --git a/settings/l10n/ru.js b/settings/l10n/ru.js index 7f7670c960e..e63bf95add1 100644 --- a/settings/l10n/ru.js +++ b/settings/l10n/ru.js @@ -4,7 +4,9 @@ OC.L10N.register( "Security & setup warnings" : "Предупреждения безопасности и установки", "Sharing" : "Общий доступ", "External Storage" : "Внешнее хранилище", + "Server-side encryption" : "Шифрование на стороне сервера", "Cron" : "Cron (планировщик задач)", + "Email server" : "Почтовый сервер", "Log" : "Журнал", "Tips & tricks" : "Советы и трюки", "Updates" : "Обновления", @@ -137,6 +139,7 @@ OC.L10N.register( "Execute one task with each page loaded" : "Выполнять одно задание с каждой загруженной страницей", "cron.php is registered at a webcron service to call cron.php every 15 minutes over http." : "cron.php зарегистрирован в webcron и будет вызываться каждые 15 минут по http.", "Use system's cron service to call the cron.php file every 15 minutes." : "Использовать системный cron для вызова cron.php каждые 15 минут.", + "Enable server-side encryption" : "Включить шифрование на стороне сервера", "Start migration" : "Запустить миграцию", "This is used for sending out notifications." : "Используется для отправки уведомлений.", "Send mode" : "Способ отправки", diff --git a/settings/l10n/ru.json b/settings/l10n/ru.json index 14a2b1144e3..51f468d4d07 100644 --- a/settings/l10n/ru.json +++ b/settings/l10n/ru.json @@ -2,7 +2,9 @@ "Security & setup warnings" : "Предупреждения безопасности и установки", "Sharing" : "Общий доступ", "External Storage" : "Внешнее хранилище", + "Server-side encryption" : "Шифрование на стороне сервера", "Cron" : "Cron (планировщик задач)", + "Email server" : "Почтовый сервер", "Log" : "Журнал", "Tips & tricks" : "Советы и трюки", "Updates" : "Обновления", @@ -135,6 +137,7 @@ "Execute one task with each page loaded" : "Выполнять одно задание с каждой загруженной страницей", "cron.php is registered at a webcron service to call cron.php every 15 minutes over http." : "cron.php зарегистрирован в webcron и будет вызываться каждые 15 минут по http.", "Use system's cron service to call the cron.php file every 15 minutes." : "Использовать системный cron для вызова cron.php каждые 15 минут.", + "Enable server-side encryption" : "Включить шифрование на стороне сервера", "Start migration" : "Запустить миграцию", "This is used for sending out notifications." : "Используется для отправки уведомлений.", "Send mode" : "Способ отправки", diff --git a/settings/l10n/sr.js b/settings/l10n/sr.js index c4eaa14084b..cc2ed54ea41 100644 --- a/settings/l10n/sr.js +++ b/settings/l10n/sr.js @@ -4,7 +4,9 @@ OC.L10N.register( "Security & setup warnings" : "Безбедносна и упозорења поставе", "Sharing" : "Дељење", "External Storage" : "Спољашње складиште", + "Server-side encryption" : "Шифровање на страни сервера", "Cron" : "Крон", + "Email server" : "Сервер е-поште", "Log" : "Бележење", "Tips & tricks" : "Савети и трикови", "Updates" : "Ажурирања", @@ -137,6 +139,7 @@ OC.L10N.register( "Execute one task with each page loaded" : "Изврши један задатак са сваком учитаном страницом", "cron.php is registered at a webcron service to call cron.php every 15 minutes over http." : "cron.php је регистрован код вебкрон сервиса за позивање cron.php сваких 15 минута преко протокола http.", "Use system's cron service to call the cron.php file every 15 minutes." : "Користите системски крон сервис за позивање cron.php фајла сваких 15 минута.", + "Enable server-side encryption" : "Укључи шифровање на страни сервера", "Start migration" : "Покрени пресељење", "This is used for sending out notifications." : "Ово се користи за слање обавештења.", "Send mode" : "Режим слања", diff --git a/settings/l10n/sr.json b/settings/l10n/sr.json index c613cae0d8a..f753ad2199f 100644 --- a/settings/l10n/sr.json +++ b/settings/l10n/sr.json @@ -2,7 +2,9 @@ "Security & setup warnings" : "Безбедносна и упозорења поставе", "Sharing" : "Дељење", "External Storage" : "Спољашње складиште", + "Server-side encryption" : "Шифровање на страни сервера", "Cron" : "Крон", + "Email server" : "Сервер е-поште", "Log" : "Бележење", "Tips & tricks" : "Савети и трикови", "Updates" : "Ажурирања", @@ -135,6 +137,7 @@ "Execute one task with each page loaded" : "Изврши један задатак са сваком учитаном страницом", "cron.php is registered at a webcron service to call cron.php every 15 minutes over http." : "cron.php је регистрован код вебкрон сервиса за позивање cron.php сваких 15 минута преко протокола http.", "Use system's cron service to call the cron.php file every 15 minutes." : "Користите системски крон сервис за позивање cron.php фајла сваких 15 минута.", + "Enable server-side encryption" : "Укључи шифровање на страни сервера", "Start migration" : "Покрени пресељење", "This is used for sending out notifications." : "Ово се користи за слање обавештења.", "Send mode" : "Режим слања", diff --git a/settings/personal.php b/settings/personal.php index 12b320ac001..7bf1110c03e 100644 --- a/settings/personal.php +++ b/settings/personal.php @@ -37,6 +37,7 @@ OC_Util::checkLoggedIn(); $defaults = new OC_Defaults(); // initialize themable default strings and urls $certificateManager = \OC::$server->getCertificateManager(); $config = \OC::$server->getConfig(); +$urlGenerator = \OC::$server->getURLGenerator(); // Highlight navigation entry OC_Util::addScript( 'settings', 'personal' ); @@ -118,6 +119,7 @@ $tmpl->assign('displayName', OC_User::getDisplayName()); $tmpl->assign('enableAvatars', $config->getSystemValue('enable_avatars', true)); $tmpl->assign('avatarChangeSupported', OC_User::canUserChangeAvatar(OC_User::getUser())); $tmpl->assign('certs', $certificateManager->listCertificates()); +$tmpl->assign('urlGenerator', $urlGenerator); // Get array of group ids for this user $groups = \OC::$server->getGroupManager()->getUserIdGroups(OC_User::getUser()); diff --git a/settings/routes.php b/settings/routes.php index 462b4ab543f..52b320cbdb5 100644 --- a/settings/routes.php +++ b/settings/routes.php @@ -53,6 +53,8 @@ $application->registerRoutes($this, [ ['name' => 'LogSettings#getEntries', 'url' => '/settings/admin/log/entries', 'verb' => 'GET'], ['name' => 'LogSettings#download', 'url' => '/settings/admin/log/download', 'verb' => 'GET'], ['name' => 'CheckSetup#check', 'url' => '/settings/ajax/checksetup', 'verb' => 'GET'], + ['name' => 'Certificate#addPersonalRootCertificate', 'url' => '/settings/personal/certificate', 'verb' => 'POST'], + ['name' => 'Certificate#removePersonalRootCertificate', 'url' => '/settings/personal/certificate/{certificateIdentifier}', 'verb' => 'DELETE'], ] ]); @@ -90,10 +92,6 @@ $this->create('settings_personal_changepassword', '/settings/personal/changepass ->action('OC\Settings\ChangePassword\Controller', 'changePersonalPassword'); $this->create('settings_ajax_setlanguage', '/settings/ajax/setlanguage.php') ->actionInclude('settings/ajax/setlanguage.php'); -$this->create('settings_cert_post', '/settings/ajax/addRootCertificate') - ->actionInclude('settings/ajax/addRootCertificate.php'); -$this->create('settings_cert_remove', '/settings/ajax/removeRootCertificate') - ->actionInclude('settings/ajax/removeRootCertificate.php'); // apps $this->create('settings_ajax_enableapp', '/settings/ajax/enableapp.php') ->actionInclude('settings/ajax/enableapp.php'); diff --git a/settings/templates/personal.php b/settings/templates/personal.php index dfdc6191805..02ee261cd1d 100644 --- a/settings/templates/personal.php +++ b/settings/templates/personal.php @@ -5,6 +5,7 @@ */ /** @var $_ array */ +/** @var $_['urlGenerator'] */ ?> <div id="app-navigation"> @@ -236,7 +237,7 @@ if($_['passwordChangeSupported']) { <?php endforeach; ?> </tbody> </table> - <form class="uploadButton" method="post" action="<?php p(\OC_Helper::linkToRoute('settings_cert_post')); ?>" target="certUploadFrame"> + <form class="uploadButton" method="post" action="<?php p($_['urlGenerator']->linkToRoute('settings.Certificate.addPersonalRootCertificate')); ?>" target="certUploadFrame"> <input type="file" id="rootcert_import" name="rootcert_import" class="hidden"> <input type="button" id="rootcert_import_button" value="<?php p($l->t('Import root certificate')); ?>"/> </form> diff --git a/tests/lib/security/certificate.php b/tests/lib/security/certificate.php index 361f2f8c38d..7fc8bbbdf25 100644 --- a/tests/lib/security/certificate.php +++ b/tests/lib/security/certificate.php @@ -1,9 +1,22 @@ <?php /** - * Copyright (c) 2014 Lukas Reschke <lukas@owncloud.com> - * This file is licensed under the Affero General Public License version 3 or - * later. - * See the COPYING-README file. + * @author Lukas Reschke <lukas@owncloud.com> + * + * @copyright Copyright (c) 2015, ownCloud, Inc. + * @license AGPL-3.0 + * + * This code is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License, version 3, + * as published by the Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License, version 3, + * along with this program. If not, see <http://www.gnu.org/licenses/> + * */ use \OC\Security\Certificate; @@ -32,33 +45,34 @@ class CertificateTest extends \Test\TestCase { * @expectedException \Exception * @expectedExceptionMessage Certificate could not get parsed. */ - function testBogusData() { - new Certificate('foo', 'bar'); + public function testBogusData() { + $certificate = new Certificate('foo', 'bar'); + $certificate->getIssueDate(); } - function testGetName() { + public function testGetName() { $this->assertSame('GoodCertificate', $this->goodCertificate->getName()); $this->assertSame('BadCertificate', $this->invalidCertificate->getName()); } - function testGetCommonName() { + public function testGetCommonName() { $this->assertSame('security.owncloud.com', $this->goodCertificate->getCommonName()); $this->assertSame(null, $this->invalidCertificate->getCommonName()); } - function testGetOrganization() { + public function testGetOrganization() { $this->assertSame('ownCloud Inc.', $this->goodCertificate->getOrganization()); $this->assertSame('Internet Widgits Pty Ltd', $this->invalidCertificate->getOrganization()); } - function testGetIssueDate() { + public function testGetIssueDate() { $expected = new DateTime('2014-08-27 08:45:52 GMT'); $this->assertEquals($expected->getTimestamp(), $this->goodCertificate->getIssueDate()->getTimestamp()); $expected = new DateTime('2014-08-27 08:48:51 GMT'); $this->assertEquals($expected->getTimestamp(), $this->invalidCertificate->getIssueDate()->getTimestamp()); } - function testGetExpireDate() { + public function testGetExpireDate() { $expected = new DateTime('2015-08-27 08:45:52 GMT'); $this->assertEquals($expected->getTimestamp(), $this->goodCertificate->getExpireDate()->getTimestamp()); $expected = new DateTime('2015-08-27 08:48:51 GMT'); @@ -70,19 +84,19 @@ class CertificateTest extends \Test\TestCase { /** * Obviously the following test case might fail after 2015-08-27, just create a new certificate with longer validity then */ - function testIsExpired() { + public function testIsExpired() { $this->assertSame(false, $this->goodCertificate->isExpired()); $this->assertSame(false, $this->invalidCertificate->isExpired()); $this->assertSame(true, $this->expiredCertificate->isExpired()); } - function testGetIssuerName() { + public function testGetIssuerName() { $this->assertSame('security.owncloud.com', $this->goodCertificate->getIssuerName()); $this->assertSame(null, $this->invalidCertificate->getIssuerName()); $this->assertSame(null, $this->expiredCertificate->getIssuerName()); } - function testGetIssuerOrganization() { + public function testGetIssuerOrganization() { $this->assertSame('ownCloud Inc.', $this->goodCertificate->getIssuerOrganization()); $this->assertSame('Internet Widgits Pty Ltd', $this->invalidCertificate->getIssuerOrganization()); $this->assertSame('Internet Widgits Pty Ltd', $this->expiredCertificate->getIssuerOrganization()); diff --git a/tests/lib/security/certificatemanager.php b/tests/lib/security/certificatemanager.php index 1167fe3d868..fab1c208443 100644 --- a/tests/lib/security/certificatemanager.php +++ b/tests/lib/security/certificatemanager.php @@ -14,8 +14,6 @@ class CertificateManagerTest extends \Test\TestCase { private $certificateManager; /** @var String */ private $username; - /** @var \OC\User\User */ - private $user; protected function setUp() { parent::setUp(); @@ -67,9 +65,25 @@ class CertificateManagerTest extends \Test\TestCase { $this->certificateManager->addCertificate('InvalidCertificate', 'invalidCertificate'); } - function testAddDangerousFile() { - $this->assertFalse($this->certificateManager->addCertificate(file_get_contents(__DIR__.'/../../data/certificates/expiredCertificate.crt'), '.htaccess')); - $this->assertFalse($this->certificateManager->addCertificate(file_get_contents(__DIR__.'/../../data/certificates/expiredCertificate.crt'), '../../foo.txt')); + /** + * @return array + */ + public function dangerousFileProvider() { + return [ + ['.htaccess'], + ['../../foo.txt'], + ['..\..\foo.txt'], + ]; + } + + /** + * @expectedException \Exception + * @expectedExceptionMessage Filename is not valid + * @dataProvider dangerousFileProvider + * @param string $filename + */ + function testAddDangerousFile($filename) { + $this->certificateManager->addCertificate(file_get_contents(__DIR__.'/../../data/certificates/expiredCertificate.crt'), $filename); } function testRemoveDangerousFile() { diff --git a/tests/settings/controller/CertificateControllerTest.php b/tests/settings/controller/CertificateControllerTest.php new file mode 100644 index 00000000000..b6981195034 --- /dev/null +++ b/tests/settings/controller/CertificateControllerTest.php @@ -0,0 +1,174 @@ +<?php +/** + * @author Lukas Reschke <lukas@owncloud.com> + * + * @copyright Copyright (c) 2015, ownCloud, Inc. + * @license AGPL-3.0 + * + * This code is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License, version 3, + * as published by the Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License, version 3, + * along with this program. If not, see <http://www.gnu.org/licenses/> + * + */ + +namespace OC\Settings\Controller; + +use OCP\AppFramework\Http; +use OCP\AppFramework\Http\DataResponse; +use OCP\IRequest; +use OCP\IL10N; +use OCP\ICertificateManager; + +/** + * Class CertificateControllerTest + * + * @package OC\Settings\Controller + */ +class CertificateControllerTest extends \Test\TestCase { + /** @var CertificateController */ + private $certificateController; + /** @var IRequest */ + private $request; + /** @var ICertificateManager */ + private $certificateManager; + /** @var IL10N */ + private $l10n; + + public function setUp() { + parent::setUp(); + + $this->request = $this->getMock('\OCP\IRequest'); + $this->certificateManager = $this->getMock('\OCP\ICertificateManager'); + $this->l10n = $this->getMock('\OCP\IL10N'); + + $this->certificateController = new CertificateController( + 'settings', + $this->request, + $this->certificateManager, + $this->l10n + ); + } + + public function testAddPersonalRootCertificateWithEmptyFile() { + $this->request + ->expects($this->once()) + ->method('getUploadedFile') + ->with('rootcert_import') + ->will($this->returnValue(null)); + + $expected = new DataResponse(['message' => 'No file uploaded'], Http::STATUS_UNPROCESSABLE_ENTITY); + $this->assertEquals($expected, $this->certificateController->addPersonalRootCertificate()); + } + + public function testAddPersonalRootCertificateValidCertificate() { + $uploadedFile = [ + 'tmp_name' => __DIR__ . '/../../data/certificates/goodCertificate.crt', + 'name' => 'goodCertificate.crt', + ]; + + $certificate = $this->getMock('\OCP\ICertificate'); + $certificate + ->expects($this->once()) + ->method('getName') + ->will($this->returnValue('Name')); + $certificate + ->expects($this->once()) + ->method('getCommonName') + ->will($this->returnValue('CommonName')); + $certificate + ->expects($this->once()) + ->method('getOrganization') + ->will($this->returnValue('Organization')); + $certificate + ->expects($this->exactly(2)) + ->method('getIssueDate') + ->will($this->returnValue(new \DateTime('@1429099555'))); + $certificate + ->expects($this->exactly(2)) + ->method('getExpireDate') + ->will($this->returnValue(new \DateTime('@1529099555'))); + $certificate + ->expects($this->once()) + ->method('getIssuerName') + ->will($this->returnValue('Issuer')); + $certificate + ->expects($this->once()) + ->method('getIssuerOrganization') + ->will($this->returnValue('IssuerOrganization')); + + $this->request + ->expects($this->once()) + ->method('getUploadedFile') + ->with('rootcert_import') + ->will($this->returnValue($uploadedFile)); + $this->certificateManager + ->expects($this->once()) + ->method('addCertificate') + ->with(file_get_contents($uploadedFile['tmp_name'], 'goodCertificate.crt')) + ->will($this->returnValue($certificate)); + + $this->l10n + ->expects($this->at(0)) + ->method('l') + ->with('date', new \DateTime('@1429099555')) + ->will($this->returnValue('Valid From as String')); + $this->l10n + ->expects($this->at(1)) + ->method('l') + ->with('date', new \DateTime('@1529099555')) + ->will($this->returnValue('Valid Till as String')); + + + $expected = new DataResponse([ + 'name' => 'Name', + 'commonName' => 'CommonName', + 'organization' => 'Organization', + 'validFrom' => 1429099555, + 'validTill' => 1529099555, + 'validFromString' => 'Valid From as String', + 'validTillString' => 'Valid Till as String', + 'issuer' => 'Issuer', + 'issuerOrganization' => 'IssuerOrganization', + ]); + $this->assertEquals($expected, $this->certificateController->addPersonalRootCertificate()); + } + + public function testAddPersonalRootCertificateInvalidCertificate() { + $uploadedFile = [ + 'tmp_name' => __DIR__ . '/../../data/certificates/badCertificate.crt', + 'name' => 'badCertificate.crt', + ]; + + $this->request + ->expects($this->once()) + ->method('getUploadedFile') + ->with('rootcert_import') + ->will($this->returnValue($uploadedFile)); + $this->certificateManager + ->expects($this->once()) + ->method('addCertificate') + ->with(file_get_contents($uploadedFile['tmp_name'], 'badCertificate.crt')) + ->will($this->throwException(new \Exception())); + + $expected = new DataResponse('An error occurred.', Http::STATUS_UNPROCESSABLE_ENTITY); + $this->assertEquals($expected, $this->certificateController->addPersonalRootCertificate()); + } + + public function testRemoveCertificate() { + $this->certificateManager + ->expects($this->once()) + ->method('removeCertificate') + ->with('CertificateToRemove'); + + $this->assertEquals(new DataResponse(), $this->certificateController->removePersonalRootCertificate('CertificateToRemove')); + } + +} |