Completed
Pull Request — master (#4617)
by Julius
14:00
created
lib/private/Authentication/Token/DefaultTokenMapper.php 1 patch
Indentation   +107 added lines, -107 removed lines patch added patch discarded remove patch
@@ -30,123 +30,123 @@
 block discarded – undo
30 30
 
31 31
 class DefaultTokenMapper extends Mapper {
32 32
 
33
-	public function __construct(IDBConnection $db) {
34
-		parent::__construct($db, 'authtoken');
35
-	}
33
+    public function __construct(IDBConnection $db) {
34
+        parent::__construct($db, 'authtoken');
35
+    }
36 36
 
37
-	/**
38
-	 * Invalidate (delete) a given token
39
-	 *
40
-	 * @param string $token
41
-	 */
42
-	public function invalidate($token) {
43
-		/* @var $qb IQueryBuilder */
44
-		$qb = $this->db->getQueryBuilder();
45
-		$qb->delete('authtoken')
46
-			->where($qb->expr()->eq('token', $qb->createParameter('token')))
47
-			->setParameter('token', $token)
48
-			->execute();
49
-	}
37
+    /**
38
+     * Invalidate (delete) a given token
39
+     *
40
+     * @param string $token
41
+     */
42
+    public function invalidate($token) {
43
+        /* @var $qb IQueryBuilder */
44
+        $qb = $this->db->getQueryBuilder();
45
+        $qb->delete('authtoken')
46
+            ->where($qb->expr()->eq('token', $qb->createParameter('token')))
47
+            ->setParameter('token', $token)
48
+            ->execute();
49
+    }
50 50
 
51
-	/**
52
-	 * @param int $olderThan
53
-	 * @param int $remember
54
-	 */
55
-	public function invalidateOld($olderThan, $remember = IToken::DO_NOT_REMEMBER) {
56
-		/* @var $qb IQueryBuilder */
57
-		$qb = $this->db->getQueryBuilder();
58
-		$qb->delete('authtoken')
59
-			->where($qb->expr()->lt('last_activity', $qb->createNamedParameter($olderThan, IQueryBuilder::PARAM_INT)))
60
-			->andWhere($qb->expr()->eq('type', $qb->createNamedParameter(IToken::TEMPORARY_TOKEN, IQueryBuilder::PARAM_INT)))
61
-			->andWhere($qb->expr()->eq('remember', $qb->createNamedParameter($remember, IQueryBuilder::PARAM_INT)))
62
-			->execute();
63
-	}
51
+    /**
52
+     * @param int $olderThan
53
+     * @param int $remember
54
+     */
55
+    public function invalidateOld($olderThan, $remember = IToken::DO_NOT_REMEMBER) {
56
+        /* @var $qb IQueryBuilder */
57
+        $qb = $this->db->getQueryBuilder();
58
+        $qb->delete('authtoken')
59
+            ->where($qb->expr()->lt('last_activity', $qb->createNamedParameter($olderThan, IQueryBuilder::PARAM_INT)))
60
+            ->andWhere($qb->expr()->eq('type', $qb->createNamedParameter(IToken::TEMPORARY_TOKEN, IQueryBuilder::PARAM_INT)))
61
+            ->andWhere($qb->expr()->eq('remember', $qb->createNamedParameter($remember, IQueryBuilder::PARAM_INT)))
62
+            ->execute();
63
+    }
64 64
 
65
-	/**
66
-	 * Get the user UID for the given token
67
-	 *
68
-	 * @param string $token
69
-	 * @throws DoesNotExistException
70
-	 * @return DefaultToken
71
-	 */
72
-	public function getToken($token) {
73
-		/* @var $qb IQueryBuilder */
74
-		$qb = $this->db->getQueryBuilder();
75
-		$result = $qb->select('id', 'uid', 'login_name', 'password', 'name', 'type', 'remember', 'token', 'last_activity', 'last_check', 'scope')
76
-			->from('authtoken')
77
-			->where($qb->expr()->eq('token', $qb->createNamedParameter($token)))
78
-			->execute();
65
+    /**
66
+     * Get the user UID for the given token
67
+     *
68
+     * @param string $token
69
+     * @throws DoesNotExistException
70
+     * @return DefaultToken
71
+     */
72
+    public function getToken($token) {
73
+        /* @var $qb IQueryBuilder */
74
+        $qb = $this->db->getQueryBuilder();
75
+        $result = $qb->select('id', 'uid', 'login_name', 'password', 'name', 'type', 'remember', 'token', 'last_activity', 'last_check', 'scope')
76
+            ->from('authtoken')
77
+            ->where($qb->expr()->eq('token', $qb->createNamedParameter($token)))
78
+            ->execute();
79 79
 
80
-		$data = $result->fetch();
81
-		$result->closeCursor();
82
-		if ($data === false) {
83
-			throw new DoesNotExistException('token does not exist');
84
-		}
80
+        $data = $result->fetch();
81
+        $result->closeCursor();
82
+        if ($data === false) {
83
+            throw new DoesNotExistException('token does not exist');
84
+        }
85 85
 ;
86
-		return DefaultToken::fromRow($data);
87
-	}
86
+        return DefaultToken::fromRow($data);
87
+    }
88 88
 
89
-	/**
90
-	 * Get the token for $id
91
-	 *
92
-	 * @param string $id
93
-	 * @throws DoesNotExistException
94
-	 * @return DefaultToken
95
-	 */
96
-	public function getTokenById($id) {
97
-		/* @var $qb IQueryBuilder */
98
-		$qb = $this->db->getQueryBuilder();
99
-		$result = $qb->select('id', 'uid', 'login_name', 'password', 'name', 'type', 'token', 'last_activity', 'last_check', 'scope')
100
-			->from('authtoken')
101
-			->where($qb->expr()->eq('id', $qb->createNamedParameter($id)))
102
-			->execute();
89
+    /**
90
+     * Get the token for $id
91
+     *
92
+     * @param string $id
93
+     * @throws DoesNotExistException
94
+     * @return DefaultToken
95
+     */
96
+    public function getTokenById($id) {
97
+        /* @var $qb IQueryBuilder */
98
+        $qb = $this->db->getQueryBuilder();
99
+        $result = $qb->select('id', 'uid', 'login_name', 'password', 'name', 'type', 'token', 'last_activity', 'last_check', 'scope')
100
+            ->from('authtoken')
101
+            ->where($qb->expr()->eq('id', $qb->createNamedParameter($id)))
102
+            ->execute();
103 103
 
104
-		$data = $result->fetch();
105
-		$result->closeCursor();
106
-		if ($data === false) {
107
-			throw new DoesNotExistException('token does not exist');
108
-		};
109
-		return DefaultToken::fromRow($data);
110
-	}
104
+        $data = $result->fetch();
105
+        $result->closeCursor();
106
+        if ($data === false) {
107
+            throw new DoesNotExistException('token does not exist');
108
+        };
109
+        return DefaultToken::fromRow($data);
110
+    }
111 111
 
112
-	/**
113
-	 * Get all token of a user
114
-	 *
115
-	 * The provider may limit the number of result rows in case of an abuse
116
-	 * where a high number of (session) tokens is generated
117
-	 *
118
-	 * @param IUser $user
119
-	 * @return DefaultToken[]
120
-	 */
121
-	public function getTokenByUser(IUser $user) {
122
-		/* @var $qb IQueryBuilder */
123
-		$qb = $this->db->getQueryBuilder();
124
-		$qb->select('id', 'uid', 'login_name', 'password', 'name', 'type', 'remember', 'token', 'last_activity', 'last_check', 'scope')
125
-			->from('authtoken')
126
-			->where($qb->expr()->eq('uid', $qb->createNamedParameter($user->getUID())))
127
-			->setMaxResults(1000);
128
-		$result = $qb->execute();
129
-		$data = $result->fetchAll();
130
-		$result->closeCursor();
112
+    /**
113
+     * Get all token of a user
114
+     *
115
+     * The provider may limit the number of result rows in case of an abuse
116
+     * where a high number of (session) tokens is generated
117
+     *
118
+     * @param IUser $user
119
+     * @return DefaultToken[]
120
+     */
121
+    public function getTokenByUser(IUser $user) {
122
+        /* @var $qb IQueryBuilder */
123
+        $qb = $this->db->getQueryBuilder();
124
+        $qb->select('id', 'uid', 'login_name', 'password', 'name', 'type', 'remember', 'token', 'last_activity', 'last_check', 'scope')
125
+            ->from('authtoken')
126
+            ->where($qb->expr()->eq('uid', $qb->createNamedParameter($user->getUID())))
127
+            ->setMaxResults(1000);
128
+        $result = $qb->execute();
129
+        $data = $result->fetchAll();
130
+        $result->closeCursor();
131 131
 
132
-		$entities = array_map(function ($row) {
133
-			return DefaultToken::fromRow($row);
134
-		}, $data);
132
+        $entities = array_map(function ($row) {
133
+            return DefaultToken::fromRow($row);
134
+        }, $data);
135 135
 
136
-		return $entities;
137
-	}
136
+        return $entities;
137
+    }
138 138
 
139
-	/**
140
-	 * @param IUser $user
141
-	 * @param int $id
142
-	 */
143
-	public function deleteById(IUser $user, $id) {
144
-		/* @var $qb IQueryBuilder */
145
-		$qb = $this->db->getQueryBuilder();
146
-		$qb->delete('authtoken')
147
-			->where($qb->expr()->eq('id', $qb->createNamedParameter($id)))
148
-			->andWhere($qb->expr()->eq('uid', $qb->createNamedParameter($user->getUID())));
149
-		$qb->execute();
150
-	}
139
+    /**
140
+     * @param IUser $user
141
+     * @param int $id
142
+     */
143
+    public function deleteById(IUser $user, $id) {
144
+        /* @var $qb IQueryBuilder */
145
+        $qb = $this->db->getQueryBuilder();
146
+        $qb->delete('authtoken')
147
+            ->where($qb->expr()->eq('id', $qb->createNamedParameter($id)))
148
+            ->andWhere($qb->expr()->eq('uid', $qb->createNamedParameter($user->getUID())));
149
+        $qb->execute();
150
+    }
151 151
 
152 152
 }
Please login to merge, or discard this patch.
lib/private/Authentication/Token/DefaultTokenCleanupJob.php 1 patch
Indentation   +5 added lines, -5 removed lines patch added patch discarded remove patch
@@ -27,10 +27,10 @@
 block discarded – undo
27 27
 
28 28
 class DefaultTokenCleanupJob extends Job {
29 29
 
30
-	protected function run($argument) {
31
-		/* @var $provider IProvider */
32
-		$provider = OC::$server->query('OC\Authentication\Token\IProvider');
33
-		$provider->invalidateOldTokens();
34
-	}
30
+    protected function run($argument) {
31
+        /* @var $provider IProvider */
32
+        $provider = OC::$server->query('OC\Authentication\Token\IProvider');
33
+        $provider->invalidateOldTokens();
34
+    }
35 35
 
36 36
 }
Please login to merge, or discard this patch.
lib/private/Authentication/Token/DefaultToken.php 1 patch
Indentation   +131 added lines, -131 removed lines patch added patch discarded remove patch
@@ -42,135 +42,135 @@
 block discarded – undo
42 42
  */
43 43
 class DefaultToken extends Entity implements IToken {
44 44
 
45
-	/**
46
-	 * @var string user UID
47
-	 */
48
-	protected $uid;
49
-
50
-	/**
51
-	 * @var string login name used for generating the token
52
-	 */
53
-	protected $loginName;
54
-
55
-	/**
56
-	 * @var string encrypted user password
57
-	 */
58
-	protected $password;
59
-
60
-	/**
61
-	 * @var string token name (e.g. browser/OS)
62
-	 */
63
-	protected $name;
64
-
65
-	/**
66
-	 * @var string
67
-	 */
68
-	protected $token;
69
-
70
-	/**
71
-	 * @var int
72
-	 */
73
-	protected $type;
74
-
75
-	/**
76
-	 * @var int
77
-	 */
78
-	protected $remember;
79
-
80
-	/**
81
-	 * @var int
82
-	 */
83
-	protected $lastActivity;
84
-
85
-	/**
86
-	 * @var int
87
-	 */
88
-	protected $lastCheck;
89
-
90
-	/**
91
-	 * @var string
92
-	 */
93
-	protected $scope;
94
-
95
-	public function __construct() {
96
-		$this->addType('type', 'int');
97
-		$this->addType('lastActivity', 'int');
98
-		$this->addType('lastCheck', 'int');
99
-	}
100
-
101
-	public function getId() {
102
-		return $this->id;
103
-	}
104
-
105
-	public function getUID() {
106
-		return $this->uid;
107
-	}
108
-
109
-	/**
110
-	 * Get the login name used when generating the token
111
-	 *
112
-	 * @return string
113
-	 */
114
-	public function getLoginName() {
115
-		return parent::getLoginName();
116
-	}
117
-
118
-	/**
119
-	 * Get the (encrypted) login password
120
-	 *
121
-	 * @return string
122
-	 */
123
-	public function getPassword() {
124
-		return parent::getPassword();
125
-	}
126
-
127
-	public function jsonSerialize() {
128
-		return [
129
-			'id' => $this->id,
130
-			'name' => $this->name,
131
-			'lastActivity' => $this->lastActivity,
132
-			'type' => $this->type,
133
-			'scope' => $this->getScopeAsArray()
134
-		];
135
-	}
136
-
137
-	/**
138
-	 * Get the timestamp of the last password check
139
-	 *
140
-	 * @return int
141
-	 */
142
-	public function getLastCheck() {
143
-		return parent::getLastCheck();
144
-	}
145
-
146
-	/**
147
-	 * Get the timestamp of the last password check
148
-	 *
149
-	 * @param int $time
150
-	 */
151
-	public function setLastCheck($time) {
152
-		return parent::setLastCheck($time);
153
-	}
154
-
155
-	public function getScope() {
156
-		return parent::getScope();
157
-	}
158
-
159
-	public function getScopeAsArray() {
160
-		$scope = json_decode($this->getScope(), true);
161
-		if (!$scope) {
162
-			return [
163
-				'filesystem'=> true
164
-			];
165
-		}
166
-		return $scope;
167
-	}
168
-
169
-	public function setScope($scope) {
170
-		if (is_array($scope)) {
171
-			parent::setScope(json_encode($scope));
172
-		} else {
173
-			parent::setScope((string)$scope);
174
-		}
175
-	}
45
+    /**
46
+     * @var string user UID
47
+     */
48
+    protected $uid;
49
+
50
+    /**
51
+     * @var string login name used for generating the token
52
+     */
53
+    protected $loginName;
54
+
55
+    /**
56
+     * @var string encrypted user password
57
+     */
58
+    protected $password;
59
+
60
+    /**
61
+     * @var string token name (e.g. browser/OS)
62
+     */
63
+    protected $name;
64
+
65
+    /**
66
+     * @var string
67
+     */
68
+    protected $token;
69
+
70
+    /**
71
+     * @var int
72
+     */
73
+    protected $type;
74
+
75
+    /**
76
+     * @var int
77
+     */
78
+    protected $remember;
79
+
80
+    /**
81
+     * @var int
82
+     */
83
+    protected $lastActivity;
84
+
85
+    /**
86
+     * @var int
87
+     */
88
+    protected $lastCheck;
89
+
90
+    /**
91
+     * @var string
92
+     */
93
+    protected $scope;
94
+
95
+    public function __construct() {
96
+        $this->addType('type', 'int');
97
+        $this->addType('lastActivity', 'int');
98
+        $this->addType('lastCheck', 'int');
99
+    }
100
+
101
+    public function getId() {
102
+        return $this->id;
103
+    }
104
+
105
+    public function getUID() {
106
+        return $this->uid;
107
+    }
108
+
109
+    /**
110
+     * Get the login name used when generating the token
111
+     *
112
+     * @return string
113
+     */
114
+    public function getLoginName() {
115
+        return parent::getLoginName();
116
+    }
117
+
118
+    /**
119
+     * Get the (encrypted) login password
120
+     *
121
+     * @return string
122
+     */
123
+    public function getPassword() {
124
+        return parent::getPassword();
125
+    }
126
+
127
+    public function jsonSerialize() {
128
+        return [
129
+            'id' => $this->id,
130
+            'name' => $this->name,
131
+            'lastActivity' => $this->lastActivity,
132
+            'type' => $this->type,
133
+            'scope' => $this->getScopeAsArray()
134
+        ];
135
+    }
136
+
137
+    /**
138
+     * Get the timestamp of the last password check
139
+     *
140
+     * @return int
141
+     */
142
+    public function getLastCheck() {
143
+        return parent::getLastCheck();
144
+    }
145
+
146
+    /**
147
+     * Get the timestamp of the last password check
148
+     *
149
+     * @param int $time
150
+     */
151
+    public function setLastCheck($time) {
152
+        return parent::setLastCheck($time);
153
+    }
154
+
155
+    public function getScope() {
156
+        return parent::getScope();
157
+    }
158
+
159
+    public function getScopeAsArray() {
160
+        $scope = json_decode($this->getScope(), true);
161
+        if (!$scope) {
162
+            return [
163
+                'filesystem'=> true
164
+            ];
165
+        }
166
+        return $scope;
167
+    }
168
+
169
+    public function setScope($scope) {
170
+        if (is_array($scope)) {
171
+            parent::setScope(json_encode($scope));
172
+        } else {
173
+            parent::setScope((string)$scope);
174
+        }
175
+    }
176 176
 }
Please login to merge, or discard this patch.
lib/private/Authentication/Token/IProvider.php 1 patch
Indentation   +106 added lines, -106 removed lines patch added patch discarded remove patch
@@ -29,110 +29,110 @@
 block discarded – undo
29 29
 interface IProvider {
30 30
 
31 31
 
32
-	/**
33
-	 * Create and persist a new token
34
-	 *
35
-	 * @param string $token
36
-	 * @param string $uid
37
-	 * @param string $loginName
38
-	 * @param string|null $password
39
-	 * @param string $name
40
-	 * @param int $type token type
41
-	 * @param int $remember whether the session token should be used for remember-me
42
-	 * @return IToken
43
-	 */
44
-	public function generateToken($token, $uid, $loginName, $password, $name, $type = IToken::TEMPORARY_TOKEN, $remember = IToken::DO_NOT_REMEMBER);
45
-
46
-	/**
47
-	 * Get a token by token id
48
-	 *
49
-	 * @param string $tokenId
50
-	 * @throws InvalidTokenException
51
-	 * @return IToken
52
-	 */
53
-	public function getToken($tokenId);
54
-
55
-	/**
56
-	 * Get a token by token id
57
-	 *
58
-	 * @param string $tokenId
59
-	 * @throws InvalidTokenException
60
-	 * @return DefaultToken
61
-	 */
62
-	public function getTokenById($tokenId);
63
-
64
-	/**
65
-	 * Duplicate an existing session token
66
-	 *
67
-	 * @param string $oldSessionId
68
-	 * @param string $sessionId
69
-	 * @throws InvalidTokenException
70
-	 */
71
-	public function renewSessionToken($oldSessionId, $sessionId);
72
-
73
-	/**
74
-	 * Invalidate (delete) the given session token
75
-	 *
76
-	 * @param string $token
77
-	 */
78
-	public function invalidateToken($token);
79
-
80
-	/**
81
-	 * Invalidate (delete) the given token
82
-	 *
83
-	 * @param IUser $user
84
-	 * @param int $id
85
-	 */
86
-	public function invalidateTokenById(IUser $user, $id);
87
-
88
-	/**
89
-	 * Invalidate (delete) old session tokens
90
-	 */
91
-	public function invalidateOldTokens();
92
-
93
-	/**
94
-	 * Save the updated token
95
-	 *
96
-	 * @param IToken $token
97
-	 */
98
-	public function updateToken(IToken $token);
99
-
100
-	/**
101
-	 * Update token activity timestamp
102
-	 *
103
-	 * @param IToken $token
104
-	 */
105
-	public function updateTokenActivity(IToken $token);
106
-
107
-	/**
108
-	 * Get all token of a user
109
-	 *
110
-	 * The provider may limit the number of result rows in case of an abuse
111
-	 * where a high number of (session) tokens is generated
112
-	 *
113
-	 * @param IUser $user
114
-	 * @return IToken[]
115
-	 */
116
-	public function getTokenByUser(IUser $user);
117
-
118
-	/**
119
-	 * Get the (unencrypted) password of the given token
120
-	 *
121
-	 * @param IToken $token
122
-	 * @param string $tokenId
123
-	 * @throws InvalidTokenException
124
-	 * @throws PasswordlessTokenException
125
-	 * @return string
126
-	 */
127
-	public function getPassword(IToken $token, $tokenId);
128
-
129
-	/**
130
-	 * Encrypt and set the password of the given token
131
-	 *
132
-	 * @param IToken $token
133
-	 * @param string $tokenId
134
-	 * @param string $password
135
-	 * @throws InvalidTokenException
136
-	 */
137
-	public function setPassword(IToken $token, $tokenId, $password);
32
+    /**
33
+     * Create and persist a new token
34
+     *
35
+     * @param string $token
36
+     * @param string $uid
37
+     * @param string $loginName
38
+     * @param string|null $password
39
+     * @param string $name
40
+     * @param int $type token type
41
+     * @param int $remember whether the session token should be used for remember-me
42
+     * @return IToken
43
+     */
44
+    public function generateToken($token, $uid, $loginName, $password, $name, $type = IToken::TEMPORARY_TOKEN, $remember = IToken::DO_NOT_REMEMBER);
45
+
46
+    /**
47
+     * Get a token by token id
48
+     *
49
+     * @param string $tokenId
50
+     * @throws InvalidTokenException
51
+     * @return IToken
52
+     */
53
+    public function getToken($tokenId);
54
+
55
+    /**
56
+     * Get a token by token id
57
+     *
58
+     * @param string $tokenId
59
+     * @throws InvalidTokenException
60
+     * @return DefaultToken
61
+     */
62
+    public function getTokenById($tokenId);
63
+
64
+    /**
65
+     * Duplicate an existing session token
66
+     *
67
+     * @param string $oldSessionId
68
+     * @param string $sessionId
69
+     * @throws InvalidTokenException
70
+     */
71
+    public function renewSessionToken($oldSessionId, $sessionId);
72
+
73
+    /**
74
+     * Invalidate (delete) the given session token
75
+     *
76
+     * @param string $token
77
+     */
78
+    public function invalidateToken($token);
79
+
80
+    /**
81
+     * Invalidate (delete) the given token
82
+     *
83
+     * @param IUser $user
84
+     * @param int $id
85
+     */
86
+    public function invalidateTokenById(IUser $user, $id);
87
+
88
+    /**
89
+     * Invalidate (delete) old session tokens
90
+     */
91
+    public function invalidateOldTokens();
92
+
93
+    /**
94
+     * Save the updated token
95
+     *
96
+     * @param IToken $token
97
+     */
98
+    public function updateToken(IToken $token);
99
+
100
+    /**
101
+     * Update token activity timestamp
102
+     *
103
+     * @param IToken $token
104
+     */
105
+    public function updateTokenActivity(IToken $token);
106
+
107
+    /**
108
+     * Get all token of a user
109
+     *
110
+     * The provider may limit the number of result rows in case of an abuse
111
+     * where a high number of (session) tokens is generated
112
+     *
113
+     * @param IUser $user
114
+     * @return IToken[]
115
+     */
116
+    public function getTokenByUser(IUser $user);
117
+
118
+    /**
119
+     * Get the (unencrypted) password of the given token
120
+     *
121
+     * @param IToken $token
122
+     * @param string $tokenId
123
+     * @throws InvalidTokenException
124
+     * @throws PasswordlessTokenException
125
+     * @return string
126
+     */
127
+    public function getPassword(IToken $token, $tokenId);
128
+
129
+    /**
130
+     * Encrypt and set the password of the given token
131
+     *
132
+     * @param IToken $token
133
+     * @param string $tokenId
134
+     * @param string $password
135
+     * @throws InvalidTokenException
136
+     */
137
+    public function setPassword(IToken $token, $tokenId, $password);
138 138
 }
Please login to merge, or discard this patch.
lib/private/Authentication/Token/IToken.php 1 patch
Indentation   +58 added lines, -58 removed lines patch added patch discarded remove patch
@@ -26,71 +26,71 @@
 block discarded – undo
26 26
 
27 27
 interface IToken extends JsonSerializable {
28 28
 
29
-	const TEMPORARY_TOKEN = 0;
30
-	const PERMANENT_TOKEN = 1;
31
-	const DO_NOT_REMEMBER = 0;
32
-	const REMEMBER = 1;
29
+    const TEMPORARY_TOKEN = 0;
30
+    const PERMANENT_TOKEN = 1;
31
+    const DO_NOT_REMEMBER = 0;
32
+    const REMEMBER = 1;
33 33
 
34
-	/**
35
-	 * Get the token ID
36
-	 *
37
-	 * @return int
38
-	 */
39
-	public function getId();
34
+    /**
35
+     * Get the token ID
36
+     *
37
+     * @return int
38
+     */
39
+    public function getId();
40 40
 
41
-	/**
42
-	 * Get the user UID
43
-	 *
44
-	 * @return string
45
-	 */
46
-	public function getUID();
41
+    /**
42
+     * Get the user UID
43
+     *
44
+     * @return string
45
+     */
46
+    public function getUID();
47 47
 
48
-	/**
49
-	 * Get the login name used when generating the token
50
-	 *
51
-	 * @return string
52
-	 */
53
-	public function getLoginName();
48
+    /**
49
+     * Get the login name used when generating the token
50
+     *
51
+     * @return string
52
+     */
53
+    public function getLoginName();
54 54
 
55
-	/**
56
-	 * Get the (encrypted) login password
57
-	 *
58
-	 * @return string
59
-	 */
60
-	public function getPassword();
55
+    /**
56
+     * Get the (encrypted) login password
57
+     *
58
+     * @return string
59
+     */
60
+    public function getPassword();
61 61
 
62
-	/**
63
-	 * Get the timestamp of the last password check
64
-	 *
65
-	 * @return int
66
-	 */
67
-	public function getLastCheck();
62
+    /**
63
+     * Get the timestamp of the last password check
64
+     *
65
+     * @return int
66
+     */
67
+    public function getLastCheck();
68 68
 
69
-	/**
70
-	 * Set the timestamp of the last password check
71
-	 *
72
-	 * @param int $time
73
-	 */
74
-	public function setLastCheck($time);
69
+    /**
70
+     * Set the timestamp of the last password check
71
+     *
72
+     * @param int $time
73
+     */
74
+    public function setLastCheck($time);
75 75
 
76
-	/**
77
-	 * Get the authentication scope for this token
78
-	 *
79
-	 * @return string
80
-	 */
81
-	public function getScope();
76
+    /**
77
+     * Get the authentication scope for this token
78
+     *
79
+     * @return string
80
+     */
81
+    public function getScope();
82 82
 
83
-	/**
84
-	 * Get the authentication scope for this token
85
-	 *
86
-	 * @return array
87
-	 */
88
-	public function getScopeAsArray();
83
+    /**
84
+     * Get the authentication scope for this token
85
+     *
86
+     * @return array
87
+     */
88
+    public function getScopeAsArray();
89 89
 
90
-	/**
91
-	 * Set the authentication scope for this token
92
-	 *
93
-	 * @param array $scope
94
-	 */
95
-	public function setScope($scope);
90
+    /**
91
+     * Set the authentication scope for this token
92
+     *
93
+     * @param array $scope
94
+     */
95
+    public function setScope($scope);
96 96
 }
Please login to merge, or discard this patch.
lib/private/LargeFileHelper.php 1 patch
Indentation   +158 added lines, -158 removed lines patch added patch discarded remove patch
@@ -31,172 +31,172 @@
 block discarded – undo
31 31
  * Helper class for large files on 32-bit platforms.
32 32
  */
33 33
 class LargeFileHelper {
34
-	/**
35
-	* pow(2, 53) as a base-10 string.
36
-	* @var string
37
-	*/
38
-	const POW_2_53 = '9007199254740992';
34
+    /**
35
+     * pow(2, 53) as a base-10 string.
36
+     * @var string
37
+     */
38
+    const POW_2_53 = '9007199254740992';
39 39
 
40
-	/**
41
-	* pow(2, 53) - 1 as a base-10 string.
42
-	* @var string
43
-	*/
44
-	const POW_2_53_MINUS_1 = '9007199254740991';
40
+    /**
41
+     * pow(2, 53) - 1 as a base-10 string.
42
+     * @var string
43
+     */
44
+    const POW_2_53_MINUS_1 = '9007199254740991';
45 45
 
46
-	/**
47
-	* @brief Checks whether our assumptions hold on the PHP platform we are on.
48
-	*
49
-	* @throws \RunTimeException if our assumptions do not hold on the current
50
-	*                           PHP platform.
51
-	*/
52
-	public function __construct() {
53
-		$pow_2_53 = floatval(self::POW_2_53_MINUS_1) + 1.0;
54
-		if ($this->formatUnsignedInteger($pow_2_53) !== self::POW_2_53) {
55
-			throw new \RuntimeException(
56
-				'This class assumes floats to be double precision or "better".'
57
-			);
58
-		}
59
-	}
46
+    /**
47
+     * @brief Checks whether our assumptions hold on the PHP platform we are on.
48
+     *
49
+     * @throws \RunTimeException if our assumptions do not hold on the current
50
+     *                           PHP platform.
51
+     */
52
+    public function __construct() {
53
+        $pow_2_53 = floatval(self::POW_2_53_MINUS_1) + 1.0;
54
+        if ($this->formatUnsignedInteger($pow_2_53) !== self::POW_2_53) {
55
+            throw new \RuntimeException(
56
+                'This class assumes floats to be double precision or "better".'
57
+            );
58
+        }
59
+    }
60 60
 
61
-	/**
62
-	* @brief Formats a signed integer or float as an unsigned integer base-10
63
-	*        string. Passed strings will be checked for being base-10.
64
-	*
65
-	* @param int|float|string $number Number containing unsigned integer data
66
-	*
67
-	* @throws \UnexpectedValueException if $number is not a float, not an int
68
-	*                                   and not a base-10 string.
69
-	*
70
-	* @return string Unsigned integer base-10 string
71
-	*/
72
-	public function formatUnsignedInteger($number) {
73
-		if (is_float($number)) {
74
-			// Undo the effect of the php.ini setting 'precision'.
75
-			return number_format($number, 0, '', '');
76
-		} else if (is_string($number) && ctype_digit($number)) {
77
-			return $number;
78
-		} else if (is_int($number)) {
79
-			// Interpret signed integer as unsigned integer.
80
-			return sprintf('%u', $number);
81
-		} else {
82
-			throw new \UnexpectedValueException(
83
-				'Expected int, float or base-10 string'
84
-			);
85
-		}
86
-	}
61
+    /**
62
+     * @brief Formats a signed integer or float as an unsigned integer base-10
63
+     *        string. Passed strings will be checked for being base-10.
64
+     *
65
+     * @param int|float|string $number Number containing unsigned integer data
66
+     *
67
+     * @throws \UnexpectedValueException if $number is not a float, not an int
68
+     *                                   and not a base-10 string.
69
+     *
70
+     * @return string Unsigned integer base-10 string
71
+     */
72
+    public function formatUnsignedInteger($number) {
73
+        if (is_float($number)) {
74
+            // Undo the effect of the php.ini setting 'precision'.
75
+            return number_format($number, 0, '', '');
76
+        } else if (is_string($number) && ctype_digit($number)) {
77
+            return $number;
78
+        } else if (is_int($number)) {
79
+            // Interpret signed integer as unsigned integer.
80
+            return sprintf('%u', $number);
81
+        } else {
82
+            throw new \UnexpectedValueException(
83
+                'Expected int, float or base-10 string'
84
+            );
85
+        }
86
+    }
87 87
 
88
-	/**
89
-	* @brief Tries to get the size of a file via various workarounds that
90
-	*        even work for large files on 32-bit platforms.
91
-	*
92
-	* @param string $filename Path to the file.
93
-	*
94
-	* @return null|int|float Number of bytes as number (float or int) or
95
-	*                        null on failure.
96
-	*/
97
-	public function getFileSize($filename) {
98
-		$fileSize = $this->getFileSizeViaCurl($filename);
99
-		if (!is_null($fileSize)) {
100
-			return $fileSize;
101
-		}
102
-		$fileSize = $this->getFileSizeViaExec($filename);
103
-		if (!is_null($fileSize)) {
104
-			return $fileSize;
105
-		}
106
-		return $this->getFileSizeNative($filename);
107
-	}
88
+    /**
89
+     * @brief Tries to get the size of a file via various workarounds that
90
+     *        even work for large files on 32-bit platforms.
91
+     *
92
+     * @param string $filename Path to the file.
93
+     *
94
+     * @return null|int|float Number of bytes as number (float or int) or
95
+     *                        null on failure.
96
+     */
97
+    public function getFileSize($filename) {
98
+        $fileSize = $this->getFileSizeViaCurl($filename);
99
+        if (!is_null($fileSize)) {
100
+            return $fileSize;
101
+        }
102
+        $fileSize = $this->getFileSizeViaExec($filename);
103
+        if (!is_null($fileSize)) {
104
+            return $fileSize;
105
+        }
106
+        return $this->getFileSizeNative($filename);
107
+    }
108 108
 
109
-	/**
110
-	* @brief Tries to get the size of a file via a CURL HEAD request.
111
-	*
112
-	* @param string $fileName Path to the file.
113
-	*
114
-	* @return null|int|float Number of bytes as number (float or int) or
115
-	*                        null on failure.
116
-	*/
117
-	public function getFileSizeViaCurl($fileName) {
118
-		if (\OC::$server->getIniWrapper()->getString('open_basedir') === '') {
119
-			$encodedFileName = rawurlencode($fileName);
120
-			$ch = curl_init("file://$encodedFileName");
121
-			curl_setopt($ch, CURLOPT_NOBODY, true);
122
-			curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
123
-			curl_setopt($ch, CURLOPT_HEADER, true);
124
-			$data = curl_exec($ch);
125
-			curl_close($ch);
126
-			if ($data !== false) {
127
-				$matches = array();
128
-				preg_match('/Content-Length: (\d+)/', $data, $matches);
129
-				if (isset($matches[1])) {
130
-					return 0 + $matches[1];
131
-				}
132
-			}
133
-		}
134
-		return null;
135
-	}
109
+    /**
110
+     * @brief Tries to get the size of a file via a CURL HEAD request.
111
+     *
112
+     * @param string $fileName Path to the file.
113
+     *
114
+     * @return null|int|float Number of bytes as number (float or int) or
115
+     *                        null on failure.
116
+     */
117
+    public function getFileSizeViaCurl($fileName) {
118
+        if (\OC::$server->getIniWrapper()->getString('open_basedir') === '') {
119
+            $encodedFileName = rawurlencode($fileName);
120
+            $ch = curl_init("file://$encodedFileName");
121
+            curl_setopt($ch, CURLOPT_NOBODY, true);
122
+            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
123
+            curl_setopt($ch, CURLOPT_HEADER, true);
124
+            $data = curl_exec($ch);
125
+            curl_close($ch);
126
+            if ($data !== false) {
127
+                $matches = array();
128
+                preg_match('/Content-Length: (\d+)/', $data, $matches);
129
+                if (isset($matches[1])) {
130
+                    return 0 + $matches[1];
131
+                }
132
+            }
133
+        }
134
+        return null;
135
+    }
136 136
 
137
-	/**
138
-	* @brief Tries to get the size of a file via an exec() call.
139
-	*
140
-	* @param string $filename Path to the file.
141
-	*
142
-	* @return null|int|float Number of bytes as number (float or int) or
143
-	*                        null on failure.
144
-	*/
145
-	public function getFileSizeViaExec($filename) {
146
-		if (\OC_Helper::is_function_enabled('exec')) {
147
-			$os = strtolower(php_uname('s'));
148
-			$arg = escapeshellarg($filename);
149
-			$result = null;
150
-			if (strpos($os, 'linux') !== false) {
151
-				$result = $this->exec("stat -c %s $arg");
152
-			} else if (strpos($os, 'bsd') !== false || strpos($os, 'darwin') !== false) {
153
-				$result = $this->exec("stat -f %z $arg");
154
-			}
155
-			return $result;
156
-		}
157
-		return null;
158
-	}
137
+    /**
138
+     * @brief Tries to get the size of a file via an exec() call.
139
+     *
140
+     * @param string $filename Path to the file.
141
+     *
142
+     * @return null|int|float Number of bytes as number (float or int) or
143
+     *                        null on failure.
144
+     */
145
+    public function getFileSizeViaExec($filename) {
146
+        if (\OC_Helper::is_function_enabled('exec')) {
147
+            $os = strtolower(php_uname('s'));
148
+            $arg = escapeshellarg($filename);
149
+            $result = null;
150
+            if (strpos($os, 'linux') !== false) {
151
+                $result = $this->exec("stat -c %s $arg");
152
+            } else if (strpos($os, 'bsd') !== false || strpos($os, 'darwin') !== false) {
153
+                $result = $this->exec("stat -f %z $arg");
154
+            }
155
+            return $result;
156
+        }
157
+        return null;
158
+    }
159 159
 
160
-	/**
161
-	* @brief Gets the size of a file via a filesize() call and converts
162
-	*        negative signed int to positive float. As the result of filesize()
163
-	*        will wrap around after a file size of 2^32 bytes = 4 GiB, this
164
-	*        should only be used as a last resort.
165
-	*
166
-	* @param string $filename Path to the file.
167
-	*
168
-	* @return int|float Number of bytes as number (float or int).
169
-	*/
170
-	public function getFileSizeNative($filename) {
171
-		$result = filesize($filename);
172
-		if ($result < 0) {
173
-			// For file sizes between 2 GiB and 4 GiB, filesize() will return a
174
-			// negative int, as the PHP data type int is signed. Interpret the
175
-			// returned int as an unsigned integer and put it into a float.
176
-			return (float) sprintf('%u', $result);
177
-		}
178
-		return $result;
179
-	}
160
+    /**
161
+     * @brief Gets the size of a file via a filesize() call and converts
162
+     *        negative signed int to positive float. As the result of filesize()
163
+     *        will wrap around after a file size of 2^32 bytes = 4 GiB, this
164
+     *        should only be used as a last resort.
165
+     *
166
+     * @param string $filename Path to the file.
167
+     *
168
+     * @return int|float Number of bytes as number (float or int).
169
+     */
170
+    public function getFileSizeNative($filename) {
171
+        $result = filesize($filename);
172
+        if ($result < 0) {
173
+            // For file sizes between 2 GiB and 4 GiB, filesize() will return a
174
+            // negative int, as the PHP data type int is signed. Interpret the
175
+            // returned int as an unsigned integer and put it into a float.
176
+            return (float) sprintf('%u', $result);
177
+        }
178
+        return $result;
179
+    }
180 180
 
181
-	/**
182
-	 * Returns the current mtime for $fullPath
183
-	 *
184
-	 * @param string $fullPath
185
-	 * @return int
186
-	 */
187
-	public function getFileMtime($fullPath) {
188
-		if (\OC_Helper::is_function_enabled('exec')) {
189
-			$os = strtolower(php_uname('s'));
190
-			if (strpos($os, 'linux') !== false) {
191
-				return $this->exec('stat -c %Y ' . escapeshellarg($fullPath));
192
-			}
193
-		}
181
+    /**
182
+     * Returns the current mtime for $fullPath
183
+     *
184
+     * @param string $fullPath
185
+     * @return int
186
+     */
187
+    public function getFileMtime($fullPath) {
188
+        if (\OC_Helper::is_function_enabled('exec')) {
189
+            $os = strtolower(php_uname('s'));
190
+            if (strpos($os, 'linux') !== false) {
191
+                return $this->exec('stat -c %Y ' . escapeshellarg($fullPath));
192
+            }
193
+        }
194 194
 
195
-		return filemtime($fullPath);
196
-	}
195
+        return filemtime($fullPath);
196
+    }
197 197
 
198
-	protected function exec($cmd) {
199
-		$result = trim(exec($cmd));
200
-		return ctype_digit($result) ? 0 + $result : null;
201
-	}
198
+    protected function exec($cmd) {
199
+        $result = trim(exec($cmd));
200
+        return ctype_digit($result) ? 0 + $result : null;
201
+    }
202 202
 }
Please login to merge, or discard this patch.
lib/private/Console/TimestampFormatter.php 1 patch
Indentation   +67 added lines, -67 removed lines patch added patch discarded remove patch
@@ -28,81 +28,81 @@
 block discarded – undo
28 28
 use Symfony\Component\Console\Formatter\OutputFormatterStyleInterface;
29 29
 
30 30
 class TimestampFormatter implements OutputFormatterInterface {
31
-	/** @var IConfig */
32
-	protected $config;
31
+    /** @var IConfig */
32
+    protected $config;
33 33
 
34
-	/**
35
-	 * @param IConfig $config
36
-	 * @param OutputFormatterInterface $formatter
37
-	 */
38
-	public function __construct(IConfig $config, OutputFormatterInterface $formatter) {
39
-		$this->config = $config;
40
-		$this->formatter = $formatter;
41
-	}
34
+    /**
35
+     * @param IConfig $config
36
+     * @param OutputFormatterInterface $formatter
37
+     */
38
+    public function __construct(IConfig $config, OutputFormatterInterface $formatter) {
39
+        $this->config = $config;
40
+        $this->formatter = $formatter;
41
+    }
42 42
 
43
-	/**
44
-	 * Sets the decorated flag.
45
-	 *
46
-	 * @param bool $decorated Whether to decorate the messages or not
47
-	 */
48
-	public function setDecorated($decorated) {
49
-		$this->formatter->setDecorated($decorated);
50
-	}
43
+    /**
44
+     * Sets the decorated flag.
45
+     *
46
+     * @param bool $decorated Whether to decorate the messages or not
47
+     */
48
+    public function setDecorated($decorated) {
49
+        $this->formatter->setDecorated($decorated);
50
+    }
51 51
 
52
-	/**
53
-	 * Gets the decorated flag.
54
-	 *
55
-	 * @return bool true if the output will decorate messages, false otherwise
56
-	 */
57
-	public function isDecorated() {
58
-		return $this->formatter->isDecorated();
59
-	}
52
+    /**
53
+     * Gets the decorated flag.
54
+     *
55
+     * @return bool true if the output will decorate messages, false otherwise
56
+     */
57
+    public function isDecorated() {
58
+        return $this->formatter->isDecorated();
59
+    }
60 60
 
61
-	/**
62
-	 * Sets a new style.
63
-	 *
64
-	 * @param string $name The style name
65
-	 * @param OutputFormatterStyleInterface $style The style instance
66
-	 */
67
-	public function setStyle($name, OutputFormatterStyleInterface $style) {
68
-		$this->formatter->setStyle($name, $style);
69
-	}
61
+    /**
62
+     * Sets a new style.
63
+     *
64
+     * @param string $name The style name
65
+     * @param OutputFormatterStyleInterface $style The style instance
66
+     */
67
+    public function setStyle($name, OutputFormatterStyleInterface $style) {
68
+        $this->formatter->setStyle($name, $style);
69
+    }
70 70
 
71
-	/**
72
-	 * Checks if output formatter has style with specified name.
73
-	 *
74
-	 * @param string $name
75
-	 * @return bool
76
-	 */
77
-	public function hasStyle($name) {
78
-		$this->formatter->hasStyle($name);
79
-	}
71
+    /**
72
+     * Checks if output formatter has style with specified name.
73
+     *
74
+     * @param string $name
75
+     * @return bool
76
+     */
77
+    public function hasStyle($name) {
78
+        $this->formatter->hasStyle($name);
79
+    }
80 80
 
81
-	/**
82
-	 * Gets style options from style with specified name.
83
-	 *
84
-	 * @param string $name
85
-	 * @return OutputFormatterStyleInterface
86
-	 */
87
-	public function getStyle($name) {
88
-		return $this->formatter->getStyle($name);
89
-	}
81
+    /**
82
+     * Gets style options from style with specified name.
83
+     *
84
+     * @param string $name
85
+     * @return OutputFormatterStyleInterface
86
+     */
87
+    public function getStyle($name) {
88
+        return $this->formatter->getStyle($name);
89
+    }
90 90
 
91
-	/**
92
-	 * Formats a message according to the given styles.
93
-	 *
94
-	 * @param string $message The message to style
95
-	 * @return string The styled message, prepended with a timestamp using the
96
-	 * log timezone and dateformat, e.g. "2015-06-23T17:24:37+02:00"
97
-	 */
98
-	public function format($message) {
91
+    /**
92
+     * Formats a message according to the given styles.
93
+     *
94
+     * @param string $message The message to style
95
+     * @return string The styled message, prepended with a timestamp using the
96
+     * log timezone and dateformat, e.g. "2015-06-23T17:24:37+02:00"
97
+     */
98
+    public function format($message) {
99 99
 
100
-		$timeZone = $this->config->getSystemValue('logtimezone', 'UTC');
101
-		$timeZone = $timeZone !== null ? new \DateTimeZone($timeZone) : null;
100
+        $timeZone = $this->config->getSystemValue('logtimezone', 'UTC');
101
+        $timeZone = $timeZone !== null ? new \DateTimeZone($timeZone) : null;
102 102
 
103
-		$time = new \DateTime('now', $timeZone);
104
-		$timestampInfo = $time->format($this->config->getSystemValue('logdateformat', \DateTime::ATOM));
103
+        $time = new \DateTime('now', $timeZone);
104
+        $timestampInfo = $time->format($this->config->getSystemValue('logdateformat', \DateTime::ATOM));
105 105
 
106
-		return $timestampInfo . ' ' . $this->formatter->format($message);
107
-	}
106
+        return $timestampInfo . ' ' . $this->formatter->format($message);
107
+    }
108 108
 }
Please login to merge, or discard this patch.
lib/private/Tags.php 1 patch
Indentation   +757 added lines, -757 removed lines patch added patch discarded remove patch
@@ -48,761 +48,761 @@
 block discarded – undo
48 48
 
49 49
 class Tags implements \OCP\ITags {
50 50
 
51
-	/**
52
-	 * Tags
53
-	 *
54
-	 * @var array
55
-	 */
56
-	private $tags = array();
57
-
58
-	/**
59
-	 * Used for storing objectid/categoryname pairs while rescanning.
60
-	 *
61
-	 * @var array
62
-	 */
63
-	private static $relations = array();
64
-
65
-	/**
66
-	 * Type
67
-	 *
68
-	 * @var string
69
-	 */
70
-	private $type;
71
-
72
-	/**
73
-	 * User
74
-	 *
75
-	 * @var string
76
-	 */
77
-	private $user;
78
-
79
-	/**
80
-	 * Are we including tags for shared items?
81
-	 *
82
-	 * @var bool
83
-	 */
84
-	private $includeShared = false;
85
-
86
-	/**
87
-	 * The current user, plus any owners of the items shared with the current
88
-	 * user, if $this->includeShared === true.
89
-	 *
90
-	 * @var array
91
-	 */
92
-	private $owners = array();
93
-
94
-	/**
95
-	 * The Mapper we're using to communicate our Tag objects to the database.
96
-	 *
97
-	 * @var TagMapper
98
-	 */
99
-	private $mapper;
100
-
101
-	/**
102
-	 * The sharing backend for objects of $this->type. Required if
103
-	 * $this->includeShared === true to determine ownership of items.
104
-	 *
105
-	 * @var \OCP\Share_Backend
106
-	 */
107
-	private $backend;
108
-
109
-	const TAG_TABLE = '*PREFIX*vcategory';
110
-	const RELATION_TABLE = '*PREFIX*vcategory_to_object';
111
-
112
-	const TAG_FAVORITE = '_$!<Favorite>!$_';
113
-
114
-	/**
115
-	* Constructor.
116
-	*
117
-	* @param TagMapper $mapper Instance of the TagMapper abstraction layer.
118
-	* @param string $user The user whose data the object will operate on.
119
-	* @param string $type The type of items for which tags will be loaded.
120
-	* @param array $defaultTags Tags that should be created at construction.
121
-	* @param boolean $includeShared Whether to include tags for items shared with this user by others.
122
-	*/
123
-	public function __construct(TagMapper $mapper, $user, $type, $defaultTags = array(), $includeShared = false) {
124
-		$this->mapper = $mapper;
125
-		$this->user = $user;
126
-		$this->type = $type;
127
-		$this->includeShared = $includeShared;
128
-		$this->owners = array($this->user);
129
-		if ($this->includeShared) {
130
-			$this->owners = array_merge($this->owners, \OC\Share\Share::getSharedItemsOwners($this->user, $this->type, true));
131
-			$this->backend = \OC\Share\Share::getBackend($this->type);
132
-		}
133
-		$this->tags = $this->mapper->loadTags($this->owners, $this->type);
134
-
135
-		if(count($defaultTags) > 0 && count($this->tags) === 0) {
136
-			$this->addMultiple($defaultTags, true);
137
-		}
138
-	}
139
-
140
-	/**
141
-	* Check if any tags are saved for this type and user.
142
-	*
143
-	* @return boolean.
144
-	*/
145
-	public function isEmpty() {
146
-		return count($this->tags) === 0;
147
-	}
148
-
149
-	/**
150
-	* Returns an array mapping a given tag's properties to its values:
151
-	* ['id' => 0, 'name' = 'Tag', 'owner' = 'User', 'type' => 'tagtype']
152
-	*
153
-	* @param string $id The ID of the tag that is going to be mapped
154
-	* @return array|false
155
-	*/
156
-	public function getTag($id) {
157
-		$key = $this->getTagById($id);
158
-		if ($key !== false) {
159
-			return $this->tagMap($this->tags[$key]);
160
-		}
161
-		return false;
162
-	}
163
-
164
-	/**
165
-	* Get the tags for a specific user.
166
-	*
167
-	* This returns an array with maps containing each tag's properties:
168
-	* [
169
-	* 	['id' => 0, 'name' = 'First tag', 'owner' = 'User', 'type' => 'tagtype'],
170
-	* 	['id' => 1, 'name' = 'Shared tag', 'owner' = 'Other user', 'type' => 'tagtype'],
171
-	* ]
172
-	*
173
-	* @return array
174
-	*/
175
-	public function getTags() {
176
-		if(!count($this->tags)) {
177
-			return array();
178
-		}
179
-
180
-		usort($this->tags, function($a, $b) {
181
-			return strnatcasecmp($a->getName(), $b->getName());
182
-		});
183
-		$tagMap = array();
184
-
185
-		foreach($this->tags as $tag) {
186
-			if($tag->getName() !== self::TAG_FAVORITE) {
187
-				$tagMap[] = $this->tagMap($tag);
188
-			}
189
-		}
190
-		return $tagMap;
191
-
192
-	}
193
-
194
-	/**
195
-	* Return only the tags owned by the given user, omitting any tags shared
196
-	* by other users.
197
-	*
198
-	* @param string $user The user whose tags are to be checked.
199
-	* @return array An array of Tag objects.
200
-	*/
201
-	public function getTagsForUser($user) {
202
-		return array_filter($this->tags,
203
-			function($tag) use($user) {
204
-				return $tag->getOwner() === $user;
205
-			}
206
-		);
207
-	}
208
-
209
-	/**
210
-	 * Get the list of tags for the given ids.
211
-	 *
212
-	 * @param array $objIds array of object ids
213
-	 * @return array|boolean of tags id as key to array of tag names
214
-	 * or false if an error occurred
215
-	 */
216
-	public function getTagsForObjects(array $objIds) {
217
-		$entries = array();
218
-
219
-		try {
220
-			$conn = \OC::$server->getDatabaseConnection();
221
-			$chunks = array_chunk($objIds, 900, false);
222
-			foreach ($chunks as $chunk) {
223
-				$result = $conn->executeQuery(
224
-					'SELECT `category`, `categoryid`, `objid` ' .
225
-					'FROM `' . self::RELATION_TABLE . '` r, `' . self::TAG_TABLE . '` ' .
226
-					'WHERE `categoryid` = `id` AND `uid` = ? AND r.`type` = ? AND `objid` IN (?)',
227
-					array($this->user, $this->type, $chunk),
228
-					array(null, null, IQueryBuilder::PARAM_INT_ARRAY)
229
-				);
230
-				while ($row = $result->fetch()) {
231
-					$objId = (int)$row['objid'];
232
-					if (!isset($entries[$objId])) {
233
-						$entries[$objId] = array();
234
-					}
235
-					$entries[$objId][] = $row['category'];
236
-				}
237
-				if (\OCP\DB::isError($result)) {
238
-					\OCP\Util::writeLog('core', __METHOD__. 'DB error: ' . \OCP\DB::getErrorMessage(), \OCP\Util::ERROR);
239
-					return false;
240
-				}
241
-			}
242
-		} catch(\Exception $e) {
243
-			\OCP\Util::writeLog('core', __METHOD__.', exception: '.$e->getMessage(),
244
-				\OCP\Util::ERROR);
245
-			return false;
246
-		}
247
-
248
-		return $entries;
249
-	}
250
-
251
-	/**
252
-	* Get the a list if items tagged with $tag.
253
-	*
254
-	* Throws an exception if the tag could not be found.
255
-	*
256
-	* @param string $tag Tag id or name.
257
-	* @return array|false An array of object ids or false on error.
258
-	* @throws \Exception
259
-	*/
260
-	public function getIdsForTag($tag) {
261
-		$result = null;
262
-		$tagId = false;
263
-		if(is_numeric($tag)) {
264
-			$tagId = $tag;
265
-		} elseif(is_string($tag)) {
266
-			$tag = trim($tag);
267
-			if($tag === '') {
268
-				\OCP\Util::writeLog('core', __METHOD__.', Cannot use empty tag names', \OCP\Util::DEBUG);
269
-				return false;
270
-			}
271
-			$tagId = $this->getTagId($tag);
272
-		}
273
-
274
-		if($tagId === false) {
275
-			$l10n = \OC::$server->getL10N('core');
276
-			throw new \Exception(
277
-				$l10n->t('Could not find category "%s"', $tag)
278
-			);
279
-		}
280
-
281
-		$ids = array();
282
-		$sql = 'SELECT `objid` FROM `' . self::RELATION_TABLE
283
-			. '` WHERE `categoryid` = ?';
284
-
285
-		try {
286
-			$stmt = \OCP\DB::prepare($sql);
287
-			$result = $stmt->execute(array($tagId));
288
-			if (\OCP\DB::isError($result)) {
289
-				\OCP\Util::writeLog('core', __METHOD__. 'DB error: ' . \OCP\DB::getErrorMessage(), \OCP\Util::ERROR);
290
-				return false;
291
-			}
292
-		} catch(\Exception $e) {
293
-			\OCP\Util::writeLog('core', __METHOD__.', exception: '.$e->getMessage(),
294
-				\OCP\Util::ERROR);
295
-			return false;
296
-		}
297
-
298
-		if(!is_null($result)) {
299
-			while( $row = $result->fetchRow()) {
300
-				$id = (int)$row['objid'];
301
-
302
-				if ($this->includeShared) {
303
-					// We have to check if we are really allowed to access the
304
-					// items that are tagged with $tag. To that end, we ask the
305
-					// corresponding sharing backend if the item identified by $id
306
-					// is owned by any of $this->owners.
307
-					foreach ($this->owners as $owner) {
308
-						if ($this->backend->isValidSource($id, $owner)) {
309
-							$ids[] = $id;
310
-							break;
311
-						}
312
-					}
313
-				} else {
314
-					$ids[] = $id;
315
-				}
316
-			}
317
-		}
318
-
319
-		return $ids;
320
-	}
321
-
322
-	/**
323
-	* Checks whether a tag is saved for the given user,
324
-	* disregarding the ones shared with him or her.
325
-	*
326
-	* @param string $name The tag name to check for.
327
-	* @param string $user The user whose tags are to be checked.
328
-	* @return bool
329
-	*/
330
-	public function userHasTag($name, $user) {
331
-		$key = $this->array_searchi($name, $this->getTagsForUser($user));
332
-		return ($key !== false) ? $this->tags[$key]->getId() : false;
333
-	}
334
-
335
-	/**
336
-	* Checks whether a tag is saved for or shared with the current user.
337
-	*
338
-	* @param string $name The tag name to check for.
339
-	* @return bool
340
-	*/
341
-	public function hasTag($name) {
342
-		return $this->getTagId($name) !== false;
343
-	}
344
-
345
-	/**
346
-	* Add a new tag.
347
-	*
348
-	* @param string $name A string with a name of the tag
349
-	* @return false|int the id of the added tag or false on error.
350
-	*/
351
-	public function add($name) {
352
-		$name = trim($name);
353
-
354
-		if($name === '') {
355
-			\OCP\Util::writeLog('core', __METHOD__.', Cannot add an empty tag', \OCP\Util::DEBUG);
356
-			return false;
357
-		}
358
-		if($this->userHasTag($name, $this->user)) {
359
-			\OCP\Util::writeLog('core', __METHOD__.', name: ' . $name. ' exists already', \OCP\Util::DEBUG);
360
-			return false;
361
-		}
362
-		try {
363
-			$tag = new Tag($this->user, $this->type, $name);
364
-			$tag = $this->mapper->insert($tag);
365
-			$this->tags[] = $tag;
366
-		} catch(\Exception $e) {
367
-			\OCP\Util::writeLog('core', __METHOD__.', exception: '.$e->getMessage(),
368
-				\OCP\Util::ERROR);
369
-			return false;
370
-		}
371
-		\OCP\Util::writeLog('core', __METHOD__.', id: ' . $tag->getId(), \OCP\Util::DEBUG);
372
-		return $tag->getId();
373
-	}
374
-
375
-	/**
376
-	* Rename tag.
377
-	*
378
-	* @param string|integer $from The name or ID of the existing tag
379
-	* @param string $to The new name of the tag.
380
-	* @return bool
381
-	*/
382
-	public function rename($from, $to) {
383
-		$from = trim($from);
384
-		$to = trim($to);
385
-
386
-		if($to === '' || $from === '') {
387
-			\OCP\Util::writeLog('core', __METHOD__.', Cannot use empty tag names', \OCP\Util::DEBUG);
388
-			return false;
389
-		}
390
-
391
-		if (is_numeric($from)) {
392
-			$key = $this->getTagById($from);
393
-		} else {
394
-			$key = $this->getTagByName($from);
395
-		}
396
-		if($key === false) {
397
-			\OCP\Util::writeLog('core', __METHOD__.', tag: ' . $from. ' does not exist', \OCP\Util::DEBUG);
398
-			return false;
399
-		}
400
-		$tag = $this->tags[$key];
401
-
402
-		if($this->userHasTag($to, $tag->getOwner())) {
403
-			\OCP\Util::writeLog('core', __METHOD__.', A tag named ' . $to. ' already exists for user ' . $tag->getOwner() . '.', \OCP\Util::DEBUG);
404
-			return false;
405
-		}
406
-
407
-		try {
408
-			$tag->setName($to);
409
-			$this->tags[$key] = $this->mapper->update($tag);
410
-		} catch(\Exception $e) {
411
-			\OCP\Util::writeLog('core', __METHOD__.', exception: '.$e->getMessage(),
412
-				\OCP\Util::ERROR);
413
-			return false;
414
-		}
415
-		return true;
416
-	}
417
-
418
-	/**
419
-	* Add a list of new tags.
420
-	*
421
-	* @param string[] $names A string with a name or an array of strings containing
422
-	* the name(s) of the tag(s) to add.
423
-	* @param bool $sync When true, save the tags
424
-	* @param int|null $id int Optional object id to add to this|these tag(s)
425
-	* @return bool Returns false on error.
426
-	*/
427
-	public function addMultiple($names, $sync=false, $id = null) {
428
-		if(!is_array($names)) {
429
-			$names = array($names);
430
-		}
431
-		$names = array_map('trim', $names);
432
-		array_filter($names);
433
-
434
-		$newones = array();
435
-		foreach($names as $name) {
436
-			if(!$this->hasTag($name) && $name !== '') {
437
-				$newones[] = new Tag($this->user, $this->type, $name);
438
-			}
439
-			if(!is_null($id) ) {
440
-				// Insert $objectid, $categoryid  pairs if not exist.
441
-				self::$relations[] = array('objid' => $id, 'tag' => $name);
442
-			}
443
-		}
444
-		$this->tags = array_merge($this->tags, $newones);
445
-		if($sync === true) {
446
-			$this->save();
447
-		}
448
-
449
-		return true;
450
-	}
451
-
452
-	/**
453
-	 * Save the list of tags and their object relations
454
-	 */
455
-	protected function save() {
456
-		if(is_array($this->tags)) {
457
-			foreach($this->tags as $tag) {
458
-				try {
459
-					if (!$this->mapper->tagExists($tag)) {
460
-						$this->mapper->insert($tag);
461
-					}
462
-				} catch(\Exception $e) {
463
-					\OCP\Util::writeLog('core', __METHOD__.', exception: '.$e->getMessage(),
464
-						\OCP\Util::ERROR);
465
-				}
466
-			}
467
-
468
-			// reload tags to get the proper ids.
469
-			$this->tags = $this->mapper->loadTags($this->owners, $this->type);
470
-			\OCP\Util::writeLog('core', __METHOD__.', tags: ' . print_r($this->tags, true),
471
-				\OCP\Util::DEBUG);
472
-			// Loop through temporarily cached objectid/tagname pairs
473
-			// and save relations.
474
-			$tags = $this->tags;
475
-			// For some reason this is needed or array_search(i) will return 0..?
476
-			ksort($tags);
477
-			foreach(self::$relations as $relation) {
478
-				$tagId = $this->getTagId($relation['tag']);
479
-				\OCP\Util::writeLog('core', __METHOD__ . 'catid, ' . $relation['tag'] . ' ' . $tagId, \OCP\Util::DEBUG);
480
-				if($tagId) {
481
-					try {
482
-						\OCP\DB::insertIfNotExist(self::RELATION_TABLE,
483
-							array(
484
-								'objid' => $relation['objid'],
485
-								'categoryid' => $tagId,
486
-								'type' => $this->type,
487
-								));
488
-					} catch(\Exception $e) {
489
-						\OCP\Util::writeLog('core', __METHOD__.', exception: '.$e->getMessage(),
490
-							\OCP\Util::ERROR);
491
-					}
492
-				}
493
-			}
494
-			self::$relations = array(); // reset
495
-		} else {
496
-			\OCP\Util::writeLog('core', __METHOD__.', $this->tags is not an array! '
497
-				. print_r($this->tags, true), \OCP\Util::ERROR);
498
-		}
499
-	}
500
-
501
-	/**
502
-	* Delete tags and tag/object relations for a user.
503
-	*
504
-	* For hooking up on post_deleteUser
505
-	*
506
-	* @param array $arguments
507
-	*/
508
-	public static function post_deleteUser($arguments) {
509
-		// Find all objectid/tagId pairs.
510
-		$result = null;
511
-		try {
512
-			$stmt = \OCP\DB::prepare('SELECT `id` FROM `' . self::TAG_TABLE . '` '
513
-				. 'WHERE `uid` = ?');
514
-			$result = $stmt->execute(array($arguments['uid']));
515
-			if (\OCP\DB::isError($result)) {
516
-				\OCP\Util::writeLog('core', __METHOD__. 'DB error: ' . \OCP\DB::getErrorMessage(), \OCP\Util::ERROR);
517
-			}
518
-		} catch(\Exception $e) {
519
-			\OCP\Util::writeLog('core', __METHOD__.', exception: '.$e->getMessage(),
520
-				\OCP\Util::ERROR);
521
-		}
522
-
523
-		if(!is_null($result)) {
524
-			try {
525
-				$stmt = \OCP\DB::prepare('DELETE FROM `' . self::RELATION_TABLE . '` '
526
-					. 'WHERE `categoryid` = ?');
527
-				while( $row = $result->fetchRow()) {
528
-					try {
529
-						$stmt->execute(array($row['id']));
530
-					} catch(\Exception $e) {
531
-						\OCP\Util::writeLog('core', __METHOD__.', exception: '.$e->getMessage(),
532
-							\OCP\Util::ERROR);
533
-					}
534
-				}
535
-			} catch(\Exception $e) {
536
-				\OCP\Util::writeLog('core', __METHOD__.', exception: '.$e->getMessage(),
537
-					\OCP\Util::ERROR);
538
-			}
539
-		}
540
-		try {
541
-			$stmt = \OCP\DB::prepare('DELETE FROM `' . self::TAG_TABLE . '` '
542
-				. 'WHERE `uid` = ?');
543
-			$result = $stmt->execute(array($arguments['uid']));
544
-			if (\OCP\DB::isError($result)) {
545
-				\OCP\Util::writeLog('core', __METHOD__. ', DB error: ' . \OCP\DB::getErrorMessage(), \OCP\Util::ERROR);
546
-			}
547
-		} catch(\Exception $e) {
548
-			\OCP\Util::writeLog('core', __METHOD__ . ', exception: '
549
-				. $e->getMessage(), \OCP\Util::ERROR);
550
-		}
551
-	}
552
-
553
-	/**
554
-	* Delete tag/object relations from the db
555
-	*
556
-	* @param array $ids The ids of the objects
557
-	* @return boolean Returns false on error.
558
-	*/
559
-	public function purgeObjects(array $ids) {
560
-		if(count($ids) === 0) {
561
-			// job done ;)
562
-			return true;
563
-		}
564
-		$updates = $ids;
565
-		try {
566
-			$query = 'DELETE FROM `' . self::RELATION_TABLE . '` ';
567
-			$query .= 'WHERE `objid` IN (' . str_repeat('?,', count($ids)-1) . '?) ';
568
-			$query .= 'AND `type`= ?';
569
-			$updates[] = $this->type;
570
-			$stmt = \OCP\DB::prepare($query);
571
-			$result = $stmt->execute($updates);
572
-			if (\OCP\DB::isError($result)) {
573
-				\OCP\Util::writeLog('core', __METHOD__. 'DB error: ' . \OCP\DB::getErrorMessage(), \OCP\Util::ERROR);
574
-				return false;
575
-			}
576
-		} catch(\Exception $e) {
577
-			\OCP\Util::writeLog('core', __METHOD__.', exception: ' . $e->getMessage(),
578
-				\OCP\Util::ERROR);
579
-			return false;
580
-		}
581
-		return true;
582
-	}
583
-
584
-	/**
585
-	* Get favorites for an object type
586
-	*
587
-	* @return array|false An array of object ids.
588
-	*/
589
-	public function getFavorites() {
590
-		try {
591
-			return $this->getIdsForTag(self::TAG_FAVORITE);
592
-		} catch(\Exception $e) {
593
-			\OCP\Util::writeLog('core', __METHOD__.', exception: ' . $e->getMessage(),
594
-				\OCP\Util::DEBUG);
595
-			return array();
596
-		}
597
-	}
598
-
599
-	/**
600
-	* Add an object to favorites
601
-	*
602
-	* @param int $objid The id of the object
603
-	* @return boolean
604
-	*/
605
-	public function addToFavorites($objid) {
606
-		if(!$this->userHasTag(self::TAG_FAVORITE, $this->user)) {
607
-			$this->add(self::TAG_FAVORITE);
608
-		}
609
-		return $this->tagAs($objid, self::TAG_FAVORITE);
610
-	}
611
-
612
-	/**
613
-	* Remove an object from favorites
614
-	*
615
-	* @param int $objid The id of the object
616
-	* @return boolean
617
-	*/
618
-	public function removeFromFavorites($objid) {
619
-		return $this->unTag($objid, self::TAG_FAVORITE);
620
-	}
621
-
622
-	/**
623
-	* Creates a tag/object relation.
624
-	*
625
-	* @param int $objid The id of the object
626
-	* @param string $tag The id or name of the tag
627
-	* @return boolean Returns false on error.
628
-	*/
629
-	public function tagAs($objid, $tag) {
630
-		if(is_string($tag) && !is_numeric($tag)) {
631
-			$tag = trim($tag);
632
-			if($tag === '') {
633
-				\OCP\Util::writeLog('core', __METHOD__.', Cannot add an empty tag', \OCP\Util::DEBUG);
634
-				return false;
635
-			}
636
-			if(!$this->hasTag($tag)) {
637
-				$this->add($tag);
638
-			}
639
-			$tagId =  $this->getTagId($tag);
640
-		} else {
641
-			$tagId = $tag;
642
-		}
643
-		try {
644
-			\OCP\DB::insertIfNotExist(self::RELATION_TABLE,
645
-				array(
646
-					'objid' => $objid,
647
-					'categoryid' => $tagId,
648
-					'type' => $this->type,
649
-				));
650
-		} catch(\Exception $e) {
651
-			\OCP\Util::writeLog('core', __METHOD__.', exception: '.$e->getMessage(),
652
-				\OCP\Util::ERROR);
653
-			return false;
654
-		}
655
-		return true;
656
-	}
657
-
658
-	/**
659
-	* Delete single tag/object relation from the db
660
-	*
661
-	* @param int $objid The id of the object
662
-	* @param string $tag The id or name of the tag
663
-	* @return boolean
664
-	*/
665
-	public function unTag($objid, $tag) {
666
-		if(is_string($tag) && !is_numeric($tag)) {
667
-			$tag = trim($tag);
668
-			if($tag === '') {
669
-				\OCP\Util::writeLog('core', __METHOD__.', Tag name is empty', \OCP\Util::DEBUG);
670
-				return false;
671
-			}
672
-			$tagId =  $this->getTagId($tag);
673
-		} else {
674
-			$tagId = $tag;
675
-		}
676
-
677
-		try {
678
-			$sql = 'DELETE FROM `' . self::RELATION_TABLE . '` '
679
-					. 'WHERE `objid` = ? AND `categoryid` = ? AND `type` = ?';
680
-			$stmt = \OCP\DB::prepare($sql);
681
-			$stmt->execute(array($objid, $tagId, $this->type));
682
-		} catch(\Exception $e) {
683
-			\OCP\Util::writeLog('core', __METHOD__.', exception: '.$e->getMessage(),
684
-				\OCP\Util::ERROR);
685
-			return false;
686
-		}
687
-		return true;
688
-	}
689
-
690
-	/**
691
-	* Delete tags from the database.
692
-	*
693
-	* @param string[]|integer[] $names An array of tags (names or IDs) to delete
694
-	* @return bool Returns false on error
695
-	*/
696
-	public function delete($names) {
697
-		if(!is_array($names)) {
698
-			$names = array($names);
699
-		}
700
-
701
-		$names = array_map('trim', $names);
702
-		array_filter($names);
703
-
704
-		\OCP\Util::writeLog('core', __METHOD__ . ', before: '
705
-			. print_r($this->tags, true), \OCP\Util::DEBUG);
706
-		foreach($names as $name) {
707
-			$id = null;
708
-
709
-			if (is_numeric($name)) {
710
-				$key = $this->getTagById($name);
711
-			} else {
712
-				$key = $this->getTagByName($name);
713
-			}
714
-			if ($key !== false) {
715
-				$tag = $this->tags[$key];
716
-				$id = $tag->getId();
717
-				unset($this->tags[$key]);
718
-				$this->mapper->delete($tag);
719
-			} else {
720
-				\OCP\Util::writeLog('core', __METHOD__ . 'Cannot delete tag ' . $name
721
-					. ': not found.', \OCP\Util::ERROR);
722
-			}
723
-			if(!is_null($id) && $id !== false) {
724
-				try {
725
-					$sql = 'DELETE FROM `' . self::RELATION_TABLE . '` '
726
-							. 'WHERE `categoryid` = ?';
727
-					$stmt = \OCP\DB::prepare($sql);
728
-					$result = $stmt->execute(array($id));
729
-					if (\OCP\DB::isError($result)) {
730
-						\OCP\Util::writeLog('core',
731
-							__METHOD__. 'DB error: ' . \OCP\DB::getErrorMessage(),
732
-							\OCP\Util::ERROR);
733
-						return false;
734
-					}
735
-				} catch(\Exception $e) {
736
-					\OCP\Util::writeLog('core', __METHOD__.', exception: '.$e->getMessage(),
737
-						\OCP\Util::ERROR);
738
-					return false;
739
-				}
740
-			}
741
-		}
742
-		return true;
743
-	}
744
-
745
-	// case-insensitive array_search
746
-	protected function array_searchi($needle, $haystack, $mem='getName') {
747
-		if(!is_array($haystack)) {
748
-			return false;
749
-		}
750
-		return array_search(strtolower($needle), array_map(
751
-			function($tag) use($mem) {
752
-				return strtolower(call_user_func(array($tag, $mem)));
753
-			}, $haystack)
754
-		);
755
-	}
756
-
757
-	/**
758
-	* Get a tag's ID.
759
-	*
760
-	* @param string $name The tag name to look for.
761
-	* @return string|bool The tag's id or false if no matching tag is found.
762
-	*/
763
-	private function getTagId($name) {
764
-		$key = $this->array_searchi($name, $this->tags);
765
-		if ($key !== false) {
766
-			return $this->tags[$key]->getId();
767
-		}
768
-		return false;
769
-	}
770
-
771
-	/**
772
-	* Get a tag by its name.
773
-	*
774
-	* @param string $name The tag name.
775
-	* @return integer|bool The tag object's offset within the $this->tags
776
-	*                      array or false if it doesn't exist.
777
-	*/
778
-	private function getTagByName($name) {
779
-		return $this->array_searchi($name, $this->tags, 'getName');
780
-	}
781
-
782
-	/**
783
-	* Get a tag by its ID.
784
-	*
785
-	* @param string $id The tag ID to look for.
786
-	* @return integer|bool The tag object's offset within the $this->tags
787
-	*                      array or false if it doesn't exist.
788
-	*/
789
-	private function getTagById($id) {
790
-		return $this->array_searchi($id, $this->tags, 'getId');
791
-	}
792
-
793
-	/**
794
-	* Returns an array mapping a given tag's properties to its values:
795
-	* ['id' => 0, 'name' = 'Tag', 'owner' = 'User', 'type' => 'tagtype']
796
-	*
797
-	* @param Tag $tag The tag that is going to be mapped
798
-	* @return array
799
-	*/
800
-	private function tagMap(Tag $tag) {
801
-		return array(
802
-			'id'    => $tag->getId(),
803
-			'name'  => $tag->getName(),
804
-			'owner' => $tag->getOwner(),
805
-			'type'  => $tag->getType()
806
-		);
807
-	}
51
+    /**
52
+     * Tags
53
+     *
54
+     * @var array
55
+     */
56
+    private $tags = array();
57
+
58
+    /**
59
+     * Used for storing objectid/categoryname pairs while rescanning.
60
+     *
61
+     * @var array
62
+     */
63
+    private static $relations = array();
64
+
65
+    /**
66
+     * Type
67
+     *
68
+     * @var string
69
+     */
70
+    private $type;
71
+
72
+    /**
73
+     * User
74
+     *
75
+     * @var string
76
+     */
77
+    private $user;
78
+
79
+    /**
80
+     * Are we including tags for shared items?
81
+     *
82
+     * @var bool
83
+     */
84
+    private $includeShared = false;
85
+
86
+    /**
87
+     * The current user, plus any owners of the items shared with the current
88
+     * user, if $this->includeShared === true.
89
+     *
90
+     * @var array
91
+     */
92
+    private $owners = array();
93
+
94
+    /**
95
+     * The Mapper we're using to communicate our Tag objects to the database.
96
+     *
97
+     * @var TagMapper
98
+     */
99
+    private $mapper;
100
+
101
+    /**
102
+     * The sharing backend for objects of $this->type. Required if
103
+     * $this->includeShared === true to determine ownership of items.
104
+     *
105
+     * @var \OCP\Share_Backend
106
+     */
107
+    private $backend;
108
+
109
+    const TAG_TABLE = '*PREFIX*vcategory';
110
+    const RELATION_TABLE = '*PREFIX*vcategory_to_object';
111
+
112
+    const TAG_FAVORITE = '_$!<Favorite>!$_';
113
+
114
+    /**
115
+     * Constructor.
116
+     *
117
+     * @param TagMapper $mapper Instance of the TagMapper abstraction layer.
118
+     * @param string $user The user whose data the object will operate on.
119
+     * @param string $type The type of items for which tags will be loaded.
120
+     * @param array $defaultTags Tags that should be created at construction.
121
+     * @param boolean $includeShared Whether to include tags for items shared with this user by others.
122
+     */
123
+    public function __construct(TagMapper $mapper, $user, $type, $defaultTags = array(), $includeShared = false) {
124
+        $this->mapper = $mapper;
125
+        $this->user = $user;
126
+        $this->type = $type;
127
+        $this->includeShared = $includeShared;
128
+        $this->owners = array($this->user);
129
+        if ($this->includeShared) {
130
+            $this->owners = array_merge($this->owners, \OC\Share\Share::getSharedItemsOwners($this->user, $this->type, true));
131
+            $this->backend = \OC\Share\Share::getBackend($this->type);
132
+        }
133
+        $this->tags = $this->mapper->loadTags($this->owners, $this->type);
134
+
135
+        if(count($defaultTags) > 0 && count($this->tags) === 0) {
136
+            $this->addMultiple($defaultTags, true);
137
+        }
138
+    }
139
+
140
+    /**
141
+     * Check if any tags are saved for this type and user.
142
+     *
143
+     * @return boolean.
144
+     */
145
+    public function isEmpty() {
146
+        return count($this->tags) === 0;
147
+    }
148
+
149
+    /**
150
+     * Returns an array mapping a given tag's properties to its values:
151
+     * ['id' => 0, 'name' = 'Tag', 'owner' = 'User', 'type' => 'tagtype']
152
+     *
153
+     * @param string $id The ID of the tag that is going to be mapped
154
+     * @return array|false
155
+     */
156
+    public function getTag($id) {
157
+        $key = $this->getTagById($id);
158
+        if ($key !== false) {
159
+            return $this->tagMap($this->tags[$key]);
160
+        }
161
+        return false;
162
+    }
163
+
164
+    /**
165
+     * Get the tags for a specific user.
166
+     *
167
+     * This returns an array with maps containing each tag's properties:
168
+     * [
169
+     * 	['id' => 0, 'name' = 'First tag', 'owner' = 'User', 'type' => 'tagtype'],
170
+     * 	['id' => 1, 'name' = 'Shared tag', 'owner' = 'Other user', 'type' => 'tagtype'],
171
+     * ]
172
+     *
173
+     * @return array
174
+     */
175
+    public function getTags() {
176
+        if(!count($this->tags)) {
177
+            return array();
178
+        }
179
+
180
+        usort($this->tags, function($a, $b) {
181
+            return strnatcasecmp($a->getName(), $b->getName());
182
+        });
183
+        $tagMap = array();
184
+
185
+        foreach($this->tags as $tag) {
186
+            if($tag->getName() !== self::TAG_FAVORITE) {
187
+                $tagMap[] = $this->tagMap($tag);
188
+            }
189
+        }
190
+        return $tagMap;
191
+
192
+    }
193
+
194
+    /**
195
+     * Return only the tags owned by the given user, omitting any tags shared
196
+     * by other users.
197
+     *
198
+     * @param string $user The user whose tags are to be checked.
199
+     * @return array An array of Tag objects.
200
+     */
201
+    public function getTagsForUser($user) {
202
+        return array_filter($this->tags,
203
+            function($tag) use($user) {
204
+                return $tag->getOwner() === $user;
205
+            }
206
+        );
207
+    }
208
+
209
+    /**
210
+     * Get the list of tags for the given ids.
211
+     *
212
+     * @param array $objIds array of object ids
213
+     * @return array|boolean of tags id as key to array of tag names
214
+     * or false if an error occurred
215
+     */
216
+    public function getTagsForObjects(array $objIds) {
217
+        $entries = array();
218
+
219
+        try {
220
+            $conn = \OC::$server->getDatabaseConnection();
221
+            $chunks = array_chunk($objIds, 900, false);
222
+            foreach ($chunks as $chunk) {
223
+                $result = $conn->executeQuery(
224
+                    'SELECT `category`, `categoryid`, `objid` ' .
225
+                    'FROM `' . self::RELATION_TABLE . '` r, `' . self::TAG_TABLE . '` ' .
226
+                    'WHERE `categoryid` = `id` AND `uid` = ? AND r.`type` = ? AND `objid` IN (?)',
227
+                    array($this->user, $this->type, $chunk),
228
+                    array(null, null, IQueryBuilder::PARAM_INT_ARRAY)
229
+                );
230
+                while ($row = $result->fetch()) {
231
+                    $objId = (int)$row['objid'];
232
+                    if (!isset($entries[$objId])) {
233
+                        $entries[$objId] = array();
234
+                    }
235
+                    $entries[$objId][] = $row['category'];
236
+                }
237
+                if (\OCP\DB::isError($result)) {
238
+                    \OCP\Util::writeLog('core', __METHOD__. 'DB error: ' . \OCP\DB::getErrorMessage(), \OCP\Util::ERROR);
239
+                    return false;
240
+                }
241
+            }
242
+        } catch(\Exception $e) {
243
+            \OCP\Util::writeLog('core', __METHOD__.', exception: '.$e->getMessage(),
244
+                \OCP\Util::ERROR);
245
+            return false;
246
+        }
247
+
248
+        return $entries;
249
+    }
250
+
251
+    /**
252
+     * Get the a list if items tagged with $tag.
253
+     *
254
+     * Throws an exception if the tag could not be found.
255
+     *
256
+     * @param string $tag Tag id or name.
257
+     * @return array|false An array of object ids or false on error.
258
+     * @throws \Exception
259
+     */
260
+    public function getIdsForTag($tag) {
261
+        $result = null;
262
+        $tagId = false;
263
+        if(is_numeric($tag)) {
264
+            $tagId = $tag;
265
+        } elseif(is_string($tag)) {
266
+            $tag = trim($tag);
267
+            if($tag === '') {
268
+                \OCP\Util::writeLog('core', __METHOD__.', Cannot use empty tag names', \OCP\Util::DEBUG);
269
+                return false;
270
+            }
271
+            $tagId = $this->getTagId($tag);
272
+        }
273
+
274
+        if($tagId === false) {
275
+            $l10n = \OC::$server->getL10N('core');
276
+            throw new \Exception(
277
+                $l10n->t('Could not find category "%s"', $tag)
278
+            );
279
+        }
280
+
281
+        $ids = array();
282
+        $sql = 'SELECT `objid` FROM `' . self::RELATION_TABLE
283
+            . '` WHERE `categoryid` = ?';
284
+
285
+        try {
286
+            $stmt = \OCP\DB::prepare($sql);
287
+            $result = $stmt->execute(array($tagId));
288
+            if (\OCP\DB::isError($result)) {
289
+                \OCP\Util::writeLog('core', __METHOD__. 'DB error: ' . \OCP\DB::getErrorMessage(), \OCP\Util::ERROR);
290
+                return false;
291
+            }
292
+        } catch(\Exception $e) {
293
+            \OCP\Util::writeLog('core', __METHOD__.', exception: '.$e->getMessage(),
294
+                \OCP\Util::ERROR);
295
+            return false;
296
+        }
297
+
298
+        if(!is_null($result)) {
299
+            while( $row = $result->fetchRow()) {
300
+                $id = (int)$row['objid'];
301
+
302
+                if ($this->includeShared) {
303
+                    // We have to check if we are really allowed to access the
304
+                    // items that are tagged with $tag. To that end, we ask the
305
+                    // corresponding sharing backend if the item identified by $id
306
+                    // is owned by any of $this->owners.
307
+                    foreach ($this->owners as $owner) {
308
+                        if ($this->backend->isValidSource($id, $owner)) {
309
+                            $ids[] = $id;
310
+                            break;
311
+                        }
312
+                    }
313
+                } else {
314
+                    $ids[] = $id;
315
+                }
316
+            }
317
+        }
318
+
319
+        return $ids;
320
+    }
321
+
322
+    /**
323
+     * Checks whether a tag is saved for the given user,
324
+     * disregarding the ones shared with him or her.
325
+     *
326
+     * @param string $name The tag name to check for.
327
+     * @param string $user The user whose tags are to be checked.
328
+     * @return bool
329
+     */
330
+    public function userHasTag($name, $user) {
331
+        $key = $this->array_searchi($name, $this->getTagsForUser($user));
332
+        return ($key !== false) ? $this->tags[$key]->getId() : false;
333
+    }
334
+
335
+    /**
336
+     * Checks whether a tag is saved for or shared with the current user.
337
+     *
338
+     * @param string $name The tag name to check for.
339
+     * @return bool
340
+     */
341
+    public function hasTag($name) {
342
+        return $this->getTagId($name) !== false;
343
+    }
344
+
345
+    /**
346
+     * Add a new tag.
347
+     *
348
+     * @param string $name A string with a name of the tag
349
+     * @return false|int the id of the added tag or false on error.
350
+     */
351
+    public function add($name) {
352
+        $name = trim($name);
353
+
354
+        if($name === '') {
355
+            \OCP\Util::writeLog('core', __METHOD__.', Cannot add an empty tag', \OCP\Util::DEBUG);
356
+            return false;
357
+        }
358
+        if($this->userHasTag($name, $this->user)) {
359
+            \OCP\Util::writeLog('core', __METHOD__.', name: ' . $name. ' exists already', \OCP\Util::DEBUG);
360
+            return false;
361
+        }
362
+        try {
363
+            $tag = new Tag($this->user, $this->type, $name);
364
+            $tag = $this->mapper->insert($tag);
365
+            $this->tags[] = $tag;
366
+        } catch(\Exception $e) {
367
+            \OCP\Util::writeLog('core', __METHOD__.', exception: '.$e->getMessage(),
368
+                \OCP\Util::ERROR);
369
+            return false;
370
+        }
371
+        \OCP\Util::writeLog('core', __METHOD__.', id: ' . $tag->getId(), \OCP\Util::DEBUG);
372
+        return $tag->getId();
373
+    }
374
+
375
+    /**
376
+     * Rename tag.
377
+     *
378
+     * @param string|integer $from The name or ID of the existing tag
379
+     * @param string $to The new name of the tag.
380
+     * @return bool
381
+     */
382
+    public function rename($from, $to) {
383
+        $from = trim($from);
384
+        $to = trim($to);
385
+
386
+        if($to === '' || $from === '') {
387
+            \OCP\Util::writeLog('core', __METHOD__.', Cannot use empty tag names', \OCP\Util::DEBUG);
388
+            return false;
389
+        }
390
+
391
+        if (is_numeric($from)) {
392
+            $key = $this->getTagById($from);
393
+        } else {
394
+            $key = $this->getTagByName($from);
395
+        }
396
+        if($key === false) {
397
+            \OCP\Util::writeLog('core', __METHOD__.', tag: ' . $from. ' does not exist', \OCP\Util::DEBUG);
398
+            return false;
399
+        }
400
+        $tag = $this->tags[$key];
401
+
402
+        if($this->userHasTag($to, $tag->getOwner())) {
403
+            \OCP\Util::writeLog('core', __METHOD__.', A tag named ' . $to. ' already exists for user ' . $tag->getOwner() . '.', \OCP\Util::DEBUG);
404
+            return false;
405
+        }
406
+
407
+        try {
408
+            $tag->setName($to);
409
+            $this->tags[$key] = $this->mapper->update($tag);
410
+        } catch(\Exception $e) {
411
+            \OCP\Util::writeLog('core', __METHOD__.', exception: '.$e->getMessage(),
412
+                \OCP\Util::ERROR);
413
+            return false;
414
+        }
415
+        return true;
416
+    }
417
+
418
+    /**
419
+     * Add a list of new tags.
420
+     *
421
+     * @param string[] $names A string with a name or an array of strings containing
422
+     * the name(s) of the tag(s) to add.
423
+     * @param bool $sync When true, save the tags
424
+     * @param int|null $id int Optional object id to add to this|these tag(s)
425
+     * @return bool Returns false on error.
426
+     */
427
+    public function addMultiple($names, $sync=false, $id = null) {
428
+        if(!is_array($names)) {
429
+            $names = array($names);
430
+        }
431
+        $names = array_map('trim', $names);
432
+        array_filter($names);
433
+
434
+        $newones = array();
435
+        foreach($names as $name) {
436
+            if(!$this->hasTag($name) && $name !== '') {
437
+                $newones[] = new Tag($this->user, $this->type, $name);
438
+            }
439
+            if(!is_null($id) ) {
440
+                // Insert $objectid, $categoryid  pairs if not exist.
441
+                self::$relations[] = array('objid' => $id, 'tag' => $name);
442
+            }
443
+        }
444
+        $this->tags = array_merge($this->tags, $newones);
445
+        if($sync === true) {
446
+            $this->save();
447
+        }
448
+
449
+        return true;
450
+    }
451
+
452
+    /**
453
+     * Save the list of tags and their object relations
454
+     */
455
+    protected function save() {
456
+        if(is_array($this->tags)) {
457
+            foreach($this->tags as $tag) {
458
+                try {
459
+                    if (!$this->mapper->tagExists($tag)) {
460
+                        $this->mapper->insert($tag);
461
+                    }
462
+                } catch(\Exception $e) {
463
+                    \OCP\Util::writeLog('core', __METHOD__.', exception: '.$e->getMessage(),
464
+                        \OCP\Util::ERROR);
465
+                }
466
+            }
467
+
468
+            // reload tags to get the proper ids.
469
+            $this->tags = $this->mapper->loadTags($this->owners, $this->type);
470
+            \OCP\Util::writeLog('core', __METHOD__.', tags: ' . print_r($this->tags, true),
471
+                \OCP\Util::DEBUG);
472
+            // Loop through temporarily cached objectid/tagname pairs
473
+            // and save relations.
474
+            $tags = $this->tags;
475
+            // For some reason this is needed or array_search(i) will return 0..?
476
+            ksort($tags);
477
+            foreach(self::$relations as $relation) {
478
+                $tagId = $this->getTagId($relation['tag']);
479
+                \OCP\Util::writeLog('core', __METHOD__ . 'catid, ' . $relation['tag'] . ' ' . $tagId, \OCP\Util::DEBUG);
480
+                if($tagId) {
481
+                    try {
482
+                        \OCP\DB::insertIfNotExist(self::RELATION_TABLE,
483
+                            array(
484
+                                'objid' => $relation['objid'],
485
+                                'categoryid' => $tagId,
486
+                                'type' => $this->type,
487
+                                ));
488
+                    } catch(\Exception $e) {
489
+                        \OCP\Util::writeLog('core', __METHOD__.', exception: '.$e->getMessage(),
490
+                            \OCP\Util::ERROR);
491
+                    }
492
+                }
493
+            }
494
+            self::$relations = array(); // reset
495
+        } else {
496
+            \OCP\Util::writeLog('core', __METHOD__.', $this->tags is not an array! '
497
+                . print_r($this->tags, true), \OCP\Util::ERROR);
498
+        }
499
+    }
500
+
501
+    /**
502
+     * Delete tags and tag/object relations for a user.
503
+     *
504
+     * For hooking up on post_deleteUser
505
+     *
506
+     * @param array $arguments
507
+     */
508
+    public static function post_deleteUser($arguments) {
509
+        // Find all objectid/tagId pairs.
510
+        $result = null;
511
+        try {
512
+            $stmt = \OCP\DB::prepare('SELECT `id` FROM `' . self::TAG_TABLE . '` '
513
+                . 'WHERE `uid` = ?');
514
+            $result = $stmt->execute(array($arguments['uid']));
515
+            if (\OCP\DB::isError($result)) {
516
+                \OCP\Util::writeLog('core', __METHOD__. 'DB error: ' . \OCP\DB::getErrorMessage(), \OCP\Util::ERROR);
517
+            }
518
+        } catch(\Exception $e) {
519
+            \OCP\Util::writeLog('core', __METHOD__.', exception: '.$e->getMessage(),
520
+                \OCP\Util::ERROR);
521
+        }
522
+
523
+        if(!is_null($result)) {
524
+            try {
525
+                $stmt = \OCP\DB::prepare('DELETE FROM `' . self::RELATION_TABLE . '` '
526
+                    . 'WHERE `categoryid` = ?');
527
+                while( $row = $result->fetchRow()) {
528
+                    try {
529
+                        $stmt->execute(array($row['id']));
530
+                    } catch(\Exception $e) {
531
+                        \OCP\Util::writeLog('core', __METHOD__.', exception: '.$e->getMessage(),
532
+                            \OCP\Util::ERROR);
533
+                    }
534
+                }
535
+            } catch(\Exception $e) {
536
+                \OCP\Util::writeLog('core', __METHOD__.', exception: '.$e->getMessage(),
537
+                    \OCP\Util::ERROR);
538
+            }
539
+        }
540
+        try {
541
+            $stmt = \OCP\DB::prepare('DELETE FROM `' . self::TAG_TABLE . '` '
542
+                . 'WHERE `uid` = ?');
543
+            $result = $stmt->execute(array($arguments['uid']));
544
+            if (\OCP\DB::isError($result)) {
545
+                \OCP\Util::writeLog('core', __METHOD__. ', DB error: ' . \OCP\DB::getErrorMessage(), \OCP\Util::ERROR);
546
+            }
547
+        } catch(\Exception $e) {
548
+            \OCP\Util::writeLog('core', __METHOD__ . ', exception: '
549
+                . $e->getMessage(), \OCP\Util::ERROR);
550
+        }
551
+    }
552
+
553
+    /**
554
+     * Delete tag/object relations from the db
555
+     *
556
+     * @param array $ids The ids of the objects
557
+     * @return boolean Returns false on error.
558
+     */
559
+    public function purgeObjects(array $ids) {
560
+        if(count($ids) === 0) {
561
+            // job done ;)
562
+            return true;
563
+        }
564
+        $updates = $ids;
565
+        try {
566
+            $query = 'DELETE FROM `' . self::RELATION_TABLE . '` ';
567
+            $query .= 'WHERE `objid` IN (' . str_repeat('?,', count($ids)-1) . '?) ';
568
+            $query .= 'AND `type`= ?';
569
+            $updates[] = $this->type;
570
+            $stmt = \OCP\DB::prepare($query);
571
+            $result = $stmt->execute($updates);
572
+            if (\OCP\DB::isError($result)) {
573
+                \OCP\Util::writeLog('core', __METHOD__. 'DB error: ' . \OCP\DB::getErrorMessage(), \OCP\Util::ERROR);
574
+                return false;
575
+            }
576
+        } catch(\Exception $e) {
577
+            \OCP\Util::writeLog('core', __METHOD__.', exception: ' . $e->getMessage(),
578
+                \OCP\Util::ERROR);
579
+            return false;
580
+        }
581
+        return true;
582
+    }
583
+
584
+    /**
585
+     * Get favorites for an object type
586
+     *
587
+     * @return array|false An array of object ids.
588
+     */
589
+    public function getFavorites() {
590
+        try {
591
+            return $this->getIdsForTag(self::TAG_FAVORITE);
592
+        } catch(\Exception $e) {
593
+            \OCP\Util::writeLog('core', __METHOD__.', exception: ' . $e->getMessage(),
594
+                \OCP\Util::DEBUG);
595
+            return array();
596
+        }
597
+    }
598
+
599
+    /**
600
+     * Add an object to favorites
601
+     *
602
+     * @param int $objid The id of the object
603
+     * @return boolean
604
+     */
605
+    public function addToFavorites($objid) {
606
+        if(!$this->userHasTag(self::TAG_FAVORITE, $this->user)) {
607
+            $this->add(self::TAG_FAVORITE);
608
+        }
609
+        return $this->tagAs($objid, self::TAG_FAVORITE);
610
+    }
611
+
612
+    /**
613
+     * Remove an object from favorites
614
+     *
615
+     * @param int $objid The id of the object
616
+     * @return boolean
617
+     */
618
+    public function removeFromFavorites($objid) {
619
+        return $this->unTag($objid, self::TAG_FAVORITE);
620
+    }
621
+
622
+    /**
623
+     * Creates a tag/object relation.
624
+     *
625
+     * @param int $objid The id of the object
626
+     * @param string $tag The id or name of the tag
627
+     * @return boolean Returns false on error.
628
+     */
629
+    public function tagAs($objid, $tag) {
630
+        if(is_string($tag) && !is_numeric($tag)) {
631
+            $tag = trim($tag);
632
+            if($tag === '') {
633
+                \OCP\Util::writeLog('core', __METHOD__.', Cannot add an empty tag', \OCP\Util::DEBUG);
634
+                return false;
635
+            }
636
+            if(!$this->hasTag($tag)) {
637
+                $this->add($tag);
638
+            }
639
+            $tagId =  $this->getTagId($tag);
640
+        } else {
641
+            $tagId = $tag;
642
+        }
643
+        try {
644
+            \OCP\DB::insertIfNotExist(self::RELATION_TABLE,
645
+                array(
646
+                    'objid' => $objid,
647
+                    'categoryid' => $tagId,
648
+                    'type' => $this->type,
649
+                ));
650
+        } catch(\Exception $e) {
651
+            \OCP\Util::writeLog('core', __METHOD__.', exception: '.$e->getMessage(),
652
+                \OCP\Util::ERROR);
653
+            return false;
654
+        }
655
+        return true;
656
+    }
657
+
658
+    /**
659
+     * Delete single tag/object relation from the db
660
+     *
661
+     * @param int $objid The id of the object
662
+     * @param string $tag The id or name of the tag
663
+     * @return boolean
664
+     */
665
+    public function unTag($objid, $tag) {
666
+        if(is_string($tag) && !is_numeric($tag)) {
667
+            $tag = trim($tag);
668
+            if($tag === '') {
669
+                \OCP\Util::writeLog('core', __METHOD__.', Tag name is empty', \OCP\Util::DEBUG);
670
+                return false;
671
+            }
672
+            $tagId =  $this->getTagId($tag);
673
+        } else {
674
+            $tagId = $tag;
675
+        }
676
+
677
+        try {
678
+            $sql = 'DELETE FROM `' . self::RELATION_TABLE . '` '
679
+                    . 'WHERE `objid` = ? AND `categoryid` = ? AND `type` = ?';
680
+            $stmt = \OCP\DB::prepare($sql);
681
+            $stmt->execute(array($objid, $tagId, $this->type));
682
+        } catch(\Exception $e) {
683
+            \OCP\Util::writeLog('core', __METHOD__.', exception: '.$e->getMessage(),
684
+                \OCP\Util::ERROR);
685
+            return false;
686
+        }
687
+        return true;
688
+    }
689
+
690
+    /**
691
+     * Delete tags from the database.
692
+     *
693
+     * @param string[]|integer[] $names An array of tags (names or IDs) to delete
694
+     * @return bool Returns false on error
695
+     */
696
+    public function delete($names) {
697
+        if(!is_array($names)) {
698
+            $names = array($names);
699
+        }
700
+
701
+        $names = array_map('trim', $names);
702
+        array_filter($names);
703
+
704
+        \OCP\Util::writeLog('core', __METHOD__ . ', before: '
705
+            . print_r($this->tags, true), \OCP\Util::DEBUG);
706
+        foreach($names as $name) {
707
+            $id = null;
708
+
709
+            if (is_numeric($name)) {
710
+                $key = $this->getTagById($name);
711
+            } else {
712
+                $key = $this->getTagByName($name);
713
+            }
714
+            if ($key !== false) {
715
+                $tag = $this->tags[$key];
716
+                $id = $tag->getId();
717
+                unset($this->tags[$key]);
718
+                $this->mapper->delete($tag);
719
+            } else {
720
+                \OCP\Util::writeLog('core', __METHOD__ . 'Cannot delete tag ' . $name
721
+                    . ': not found.', \OCP\Util::ERROR);
722
+            }
723
+            if(!is_null($id) && $id !== false) {
724
+                try {
725
+                    $sql = 'DELETE FROM `' . self::RELATION_TABLE . '` '
726
+                            . 'WHERE `categoryid` = ?';
727
+                    $stmt = \OCP\DB::prepare($sql);
728
+                    $result = $stmt->execute(array($id));
729
+                    if (\OCP\DB::isError($result)) {
730
+                        \OCP\Util::writeLog('core',
731
+                            __METHOD__. 'DB error: ' . \OCP\DB::getErrorMessage(),
732
+                            \OCP\Util::ERROR);
733
+                        return false;
734
+                    }
735
+                } catch(\Exception $e) {
736
+                    \OCP\Util::writeLog('core', __METHOD__.', exception: '.$e->getMessage(),
737
+                        \OCP\Util::ERROR);
738
+                    return false;
739
+                }
740
+            }
741
+        }
742
+        return true;
743
+    }
744
+
745
+    // case-insensitive array_search
746
+    protected function array_searchi($needle, $haystack, $mem='getName') {
747
+        if(!is_array($haystack)) {
748
+            return false;
749
+        }
750
+        return array_search(strtolower($needle), array_map(
751
+            function($tag) use($mem) {
752
+                return strtolower(call_user_func(array($tag, $mem)));
753
+            }, $haystack)
754
+        );
755
+    }
756
+
757
+    /**
758
+     * Get a tag's ID.
759
+     *
760
+     * @param string $name The tag name to look for.
761
+     * @return string|bool The tag's id or false if no matching tag is found.
762
+     */
763
+    private function getTagId($name) {
764
+        $key = $this->array_searchi($name, $this->tags);
765
+        if ($key !== false) {
766
+            return $this->tags[$key]->getId();
767
+        }
768
+        return false;
769
+    }
770
+
771
+    /**
772
+     * Get a tag by its name.
773
+     *
774
+     * @param string $name The tag name.
775
+     * @return integer|bool The tag object's offset within the $this->tags
776
+     *                      array or false if it doesn't exist.
777
+     */
778
+    private function getTagByName($name) {
779
+        return $this->array_searchi($name, $this->tags, 'getName');
780
+    }
781
+
782
+    /**
783
+     * Get a tag by its ID.
784
+     *
785
+     * @param string $id The tag ID to look for.
786
+     * @return integer|bool The tag object's offset within the $this->tags
787
+     *                      array or false if it doesn't exist.
788
+     */
789
+    private function getTagById($id) {
790
+        return $this->array_searchi($id, $this->tags, 'getId');
791
+    }
792
+
793
+    /**
794
+     * Returns an array mapping a given tag's properties to its values:
795
+     * ['id' => 0, 'name' = 'Tag', 'owner' = 'User', 'type' => 'tagtype']
796
+     *
797
+     * @param Tag $tag The tag that is going to be mapped
798
+     * @return array
799
+     */
800
+    private function tagMap(Tag $tag) {
801
+        return array(
802
+            'id'    => $tag->getId(),
803
+            'name'  => $tag->getName(),
804
+            'owner' => $tag->getOwner(),
805
+            'type'  => $tag->getType()
806
+        );
807
+    }
808 808
 }
Please login to merge, or discard this patch.
lib/private/SubAdmin.php 1 patch
Indentation   +247 added lines, -247 removed lines patch added patch discarded remove patch
@@ -36,253 +36,253 @@
 block discarded – undo
36 36
 
37 37
 class SubAdmin extends PublicEmitter {
38 38
 
39
-	/** @var IUserManager */
40
-	private $userManager;
41
-
42
-	/** @var IGroupManager */
43
-	private $groupManager;
44
-
45
-	/** @var IDBConnection */
46
-	private $dbConn;
47
-
48
-	/**
49
-	 * @param IUserManager $userManager
50
-	 * @param IGroupManager $groupManager
51
-	 * @param IDBConnection $dbConn
52
-	 */
53
-	public function __construct(IUserManager $userManager,
54
-	                            IGroupManager $groupManager,
55
-								IDBConnection $dbConn) {
56
-		$this->userManager = $userManager;
57
-		$this->groupManager = $groupManager;
58
-		$this->dbConn = $dbConn;
59
-
60
-		$this->userManager->listen('\OC\User', 'postDelete', function($user) {
61
-			$this->post_deleteUser($user);
62
-		});
63
-		$this->groupManager->listen('\OC\Group', 'postDelete', function($group) {
64
-			$this->post_deleteGroup($group);	
65
-		});
66
-	}
67
-
68
-	/**
69
-	 * add a SubAdmin
70
-	 * @param IUser $user user to be SubAdmin
71
-	 * @param IGroup $group group $user becomes subadmin of
72
-	 * @return bool
73
-	 */
74
-	public function createSubAdmin(IUser $user, IGroup $group) {
75
-		$qb = $this->dbConn->getQueryBuilder();
76
-
77
-		$qb->insert('group_admin')
78
-			->values([
79
-				'gid' => $qb->createNamedParameter($group->getGID()),
80
-				'uid' => $qb->createNamedParameter($user->getUID())
81
-			])
82
-			->execute();
83
-
84
-		$this->emit('\OC\SubAdmin', 'postCreateSubAdmin', [$user, $group]);
85
-		\OC_Hook::emit("OC_SubAdmin", "post_createSubAdmin", ["gid" => $group->getGID()]);
86
-		return true;
87
-	}
88
-
89
-	/**
90
-	 * delete a SubAdmin
91
-	 * @param IUser $user the user that is the SubAdmin
92
-	 * @param IGroup $group the group
93
-	 * @return bool
94
-	 */
95
-	public function deleteSubAdmin(IUser $user, IGroup $group) {
96
-		$qb = $this->dbConn->getQueryBuilder();
97
-
98
-		$qb->delete('group_admin')
99
-			->where($qb->expr()->eq('gid', $qb->createNamedParameter($group->getGID())))
100
-			->andWhere($qb->expr()->eq('uid', $qb->createNamedParameter($user->getUID())))
101
-			->execute();
102
-
103
-		$this->emit('\OC\SubAdmin', 'postDeleteSubAdmin', [$user, $group]);
104
-		\OC_Hook::emit("OC_SubAdmin", "post_deleteSubAdmin", ["gid" => $group->getGID()]);
105
-		return true;
106
-	}
107
-
108
-	/**
109
-	 * get groups of a SubAdmin
110
-	 * @param IUser $user the SubAdmin
111
-	 * @return IGroup[]
112
-	 */
113
-	public function getSubAdminsGroups(IUser $user) {
114
-		$qb = $this->dbConn->getQueryBuilder();
115
-
116
-		$result = $qb->select('gid')
117
-			->from('group_admin')
118
-			->where($qb->expr()->eq('uid', $qb->createNamedParameter($user->getUID())))
119
-			->execute();
120
-
121
-		$groups = [];
122
-		while($row = $result->fetch()) {
123
-			$group = $this->groupManager->get($row['gid']);
124
-			if(!is_null($group)) {
125
-				$groups[] = $group;
126
-			}
127
-		}
128
-		$result->closeCursor();
129
-
130
-		return $groups;
131
-	}
132
-
133
-	/**
134
-	 * get SubAdmins of a group
135
-	 * @param IGroup $group the group
136
-	 * @return IUser[]
137
-	 */
138
-	public function getGroupsSubAdmins(IGroup $group) {
139
-		$qb = $this->dbConn->getQueryBuilder();
140
-
141
-		$result = $qb->select('uid')
142
-			->from('group_admin')
143
-			->where($qb->expr()->eq('gid', $qb->createNamedParameter($group->getGID())))
144
-			->execute();
145
-
146
-		$users = [];
147
-		while($row = $result->fetch()) {
148
-			$user = $this->userManager->get($row['uid']);
149
-			if(!is_null($user)) {
150
-				$users[] = $user;
151
-			}
152
-		}
153
-		$result->closeCursor();
154
-
155
-		return $users;
156
-	}
157
-
158
-	/**
159
-	 * get all SubAdmins
160
-	 * @return array
161
-	 */
162
-	public function getAllSubAdmins() {
163
-		$qb = $this->dbConn->getQueryBuilder();
164
-
165
-		$result = $qb->select('*')
166
-			->from('group_admin')
167
-			->execute();
168
-
169
-		$subadmins = [];
170
-		while($row = $result->fetch()) {
171
-			$user = $this->userManager->get($row['uid']);
172
-			$group = $this->groupManager->get($row['gid']);
173
-			if(!is_null($user) && !is_null($group)) {
174
-				$subadmins[] = [
175
-					'user'  => $user,
176
-					'group' => $group
177
-				];
178
-			}
179
-		}
180
-		$result->closeCursor();
181
-
182
-		return $subadmins;
183
-	}
184
-
185
-	/**
186
-	 * checks if a user is a SubAdmin of a group
187
-	 * @param IUser $user 
188
-	 * @param IGroup $group
189
-	 * @return bool
190
-	 */
191
-	public function isSubAdminOfGroup(IUser $user, IGroup $group) {
192
-		$qb = $this->dbConn->getQueryBuilder();
193
-
194
-		/*
39
+    /** @var IUserManager */
40
+    private $userManager;
41
+
42
+    /** @var IGroupManager */
43
+    private $groupManager;
44
+
45
+    /** @var IDBConnection */
46
+    private $dbConn;
47
+
48
+    /**
49
+     * @param IUserManager $userManager
50
+     * @param IGroupManager $groupManager
51
+     * @param IDBConnection $dbConn
52
+     */
53
+    public function __construct(IUserManager $userManager,
54
+                                IGroupManager $groupManager,
55
+                                IDBConnection $dbConn) {
56
+        $this->userManager = $userManager;
57
+        $this->groupManager = $groupManager;
58
+        $this->dbConn = $dbConn;
59
+
60
+        $this->userManager->listen('\OC\User', 'postDelete', function($user) {
61
+            $this->post_deleteUser($user);
62
+        });
63
+        $this->groupManager->listen('\OC\Group', 'postDelete', function($group) {
64
+            $this->post_deleteGroup($group);	
65
+        });
66
+    }
67
+
68
+    /**
69
+     * add a SubAdmin
70
+     * @param IUser $user user to be SubAdmin
71
+     * @param IGroup $group group $user becomes subadmin of
72
+     * @return bool
73
+     */
74
+    public function createSubAdmin(IUser $user, IGroup $group) {
75
+        $qb = $this->dbConn->getQueryBuilder();
76
+
77
+        $qb->insert('group_admin')
78
+            ->values([
79
+                'gid' => $qb->createNamedParameter($group->getGID()),
80
+                'uid' => $qb->createNamedParameter($user->getUID())
81
+            ])
82
+            ->execute();
83
+
84
+        $this->emit('\OC\SubAdmin', 'postCreateSubAdmin', [$user, $group]);
85
+        \OC_Hook::emit("OC_SubAdmin", "post_createSubAdmin", ["gid" => $group->getGID()]);
86
+        return true;
87
+    }
88
+
89
+    /**
90
+     * delete a SubAdmin
91
+     * @param IUser $user the user that is the SubAdmin
92
+     * @param IGroup $group the group
93
+     * @return bool
94
+     */
95
+    public function deleteSubAdmin(IUser $user, IGroup $group) {
96
+        $qb = $this->dbConn->getQueryBuilder();
97
+
98
+        $qb->delete('group_admin')
99
+            ->where($qb->expr()->eq('gid', $qb->createNamedParameter($group->getGID())))
100
+            ->andWhere($qb->expr()->eq('uid', $qb->createNamedParameter($user->getUID())))
101
+            ->execute();
102
+
103
+        $this->emit('\OC\SubAdmin', 'postDeleteSubAdmin', [$user, $group]);
104
+        \OC_Hook::emit("OC_SubAdmin", "post_deleteSubAdmin", ["gid" => $group->getGID()]);
105
+        return true;
106
+    }
107
+
108
+    /**
109
+     * get groups of a SubAdmin
110
+     * @param IUser $user the SubAdmin
111
+     * @return IGroup[]
112
+     */
113
+    public function getSubAdminsGroups(IUser $user) {
114
+        $qb = $this->dbConn->getQueryBuilder();
115
+
116
+        $result = $qb->select('gid')
117
+            ->from('group_admin')
118
+            ->where($qb->expr()->eq('uid', $qb->createNamedParameter($user->getUID())))
119
+            ->execute();
120
+
121
+        $groups = [];
122
+        while($row = $result->fetch()) {
123
+            $group = $this->groupManager->get($row['gid']);
124
+            if(!is_null($group)) {
125
+                $groups[] = $group;
126
+            }
127
+        }
128
+        $result->closeCursor();
129
+
130
+        return $groups;
131
+    }
132
+
133
+    /**
134
+     * get SubAdmins of a group
135
+     * @param IGroup $group the group
136
+     * @return IUser[]
137
+     */
138
+    public function getGroupsSubAdmins(IGroup $group) {
139
+        $qb = $this->dbConn->getQueryBuilder();
140
+
141
+        $result = $qb->select('uid')
142
+            ->from('group_admin')
143
+            ->where($qb->expr()->eq('gid', $qb->createNamedParameter($group->getGID())))
144
+            ->execute();
145
+
146
+        $users = [];
147
+        while($row = $result->fetch()) {
148
+            $user = $this->userManager->get($row['uid']);
149
+            if(!is_null($user)) {
150
+                $users[] = $user;
151
+            }
152
+        }
153
+        $result->closeCursor();
154
+
155
+        return $users;
156
+    }
157
+
158
+    /**
159
+     * get all SubAdmins
160
+     * @return array
161
+     */
162
+    public function getAllSubAdmins() {
163
+        $qb = $this->dbConn->getQueryBuilder();
164
+
165
+        $result = $qb->select('*')
166
+            ->from('group_admin')
167
+            ->execute();
168
+
169
+        $subadmins = [];
170
+        while($row = $result->fetch()) {
171
+            $user = $this->userManager->get($row['uid']);
172
+            $group = $this->groupManager->get($row['gid']);
173
+            if(!is_null($user) && !is_null($group)) {
174
+                $subadmins[] = [
175
+                    'user'  => $user,
176
+                    'group' => $group
177
+                ];
178
+            }
179
+        }
180
+        $result->closeCursor();
181
+
182
+        return $subadmins;
183
+    }
184
+
185
+    /**
186
+     * checks if a user is a SubAdmin of a group
187
+     * @param IUser $user 
188
+     * @param IGroup $group
189
+     * @return bool
190
+     */
191
+    public function isSubAdminOfGroup(IUser $user, IGroup $group) {
192
+        $qb = $this->dbConn->getQueryBuilder();
193
+
194
+        /*
195 195
 		 * Primary key is ('gid', 'uid') so max 1 result possible here
196 196
 		 */
197
-		$result = $qb->select('*')
198
-			->from('group_admin')
199
-			->where($qb->expr()->eq('gid', $qb->createNamedParameter($group->getGID())))
200
-			->andWhere($qb->expr()->eq('uid', $qb->createNamedParameter($user->getUID())))
201
-			->execute();
202
-
203
-		$fetch =  $result->fetch();
204
-		$result->closeCursor();
205
-		$result = !empty($fetch) ? true : false;
206
-
207
-		return $result;
208
-	}
209
-
210
-	/**
211
-	 * checks if a user is a SubAdmin
212
-	 * @param IUser $user 
213
-	 * @return bool
214
-	 */
215
-	public function isSubAdmin(IUser $user) {
216
-		// Check if the user is already an admin
217
-		if ($this->groupManager->isAdmin($user->getUID())) {
218
-			return true;
219
-		}
220
-
221
-		$qb = $this->dbConn->getQueryBuilder();
222
-
223
-		$result = $qb->select('gid')
224
-			->from('group_admin')
225
-			->andWhere($qb->expr()->eq('uid', $qb->createNamedParameter($user->getUID())))
226
-			->setMaxResults(1)
227
-			->execute();
228
-
229
-		$isSubAdmin = $result->fetch();
230
-		$result->closeCursor();
231
-
232
-		$result = $isSubAdmin === false ? false : true;
233
-
234
-		return $result;
235
-	}
236
-
237
-	/**
238
-	 * checks if a user is a accessible by a subadmin
239
-	 * @param IUser $subadmin
240
-	 * @param IUser $user
241
-	 * @return bool
242
-	 */
243
-	public function isUserAccessible($subadmin, $user) {
244
-		if(!$this->isSubAdmin($subadmin)) {
245
-			return false;
246
-		}
247
-		if($this->groupManager->isAdmin($user->getUID())) {
248
-			return false;
249
-		}
250
-		$accessibleGroups = $this->getSubAdminsGroups($subadmin);
251
-		foreach($accessibleGroups as $accessibleGroup) {
252
-			if($accessibleGroup->inGroup($user)) {
253
-				return true;
254
-			}
255
-		}
256
-		return false;
257
-	}
258
-
259
-	/**
260
-	 * delete all SubAdmins by $user
261
-	 * @param IUser $user
262
-	 * @return boolean
263
-	 */
264
-	private function post_deleteUser($user) {
265
-		$qb = $this->dbConn->getQueryBuilder();
266
-
267
-		$qb->delete('group_admin')
268
-			->where($qb->expr()->eq('uid', $qb->createNamedParameter($user->getUID())))
269
-			->execute();
270
-
271
-		return true;
272
-	}
273
-
274
-	/**
275
-	 * delete all SubAdmins by $group
276
-	 * @param IGroup $group
277
-	 * @return boolean
278
-	 */
279
-	private function post_deleteGroup($group) {
280
-		$qb = $this->dbConn->getQueryBuilder();
281
-
282
-		$qb->delete('group_admin')
283
-			->where($qb->expr()->eq('gid', $qb->createNamedParameter($group->getGID())))
284
-			->execute();
285
-
286
-		return true;
287
-	}
197
+        $result = $qb->select('*')
198
+            ->from('group_admin')
199
+            ->where($qb->expr()->eq('gid', $qb->createNamedParameter($group->getGID())))
200
+            ->andWhere($qb->expr()->eq('uid', $qb->createNamedParameter($user->getUID())))
201
+            ->execute();
202
+
203
+        $fetch =  $result->fetch();
204
+        $result->closeCursor();
205
+        $result = !empty($fetch) ? true : false;
206
+
207
+        return $result;
208
+    }
209
+
210
+    /**
211
+     * checks if a user is a SubAdmin
212
+     * @param IUser $user 
213
+     * @return bool
214
+     */
215
+    public function isSubAdmin(IUser $user) {
216
+        // Check if the user is already an admin
217
+        if ($this->groupManager->isAdmin($user->getUID())) {
218
+            return true;
219
+        }
220
+
221
+        $qb = $this->dbConn->getQueryBuilder();
222
+
223
+        $result = $qb->select('gid')
224
+            ->from('group_admin')
225
+            ->andWhere($qb->expr()->eq('uid', $qb->createNamedParameter($user->getUID())))
226
+            ->setMaxResults(1)
227
+            ->execute();
228
+
229
+        $isSubAdmin = $result->fetch();
230
+        $result->closeCursor();
231
+
232
+        $result = $isSubAdmin === false ? false : true;
233
+
234
+        return $result;
235
+    }
236
+
237
+    /**
238
+     * checks if a user is a accessible by a subadmin
239
+     * @param IUser $subadmin
240
+     * @param IUser $user
241
+     * @return bool
242
+     */
243
+    public function isUserAccessible($subadmin, $user) {
244
+        if(!$this->isSubAdmin($subadmin)) {
245
+            return false;
246
+        }
247
+        if($this->groupManager->isAdmin($user->getUID())) {
248
+            return false;
249
+        }
250
+        $accessibleGroups = $this->getSubAdminsGroups($subadmin);
251
+        foreach($accessibleGroups as $accessibleGroup) {
252
+            if($accessibleGroup->inGroup($user)) {
253
+                return true;
254
+            }
255
+        }
256
+        return false;
257
+    }
258
+
259
+    /**
260
+     * delete all SubAdmins by $user
261
+     * @param IUser $user
262
+     * @return boolean
263
+     */
264
+    private function post_deleteUser($user) {
265
+        $qb = $this->dbConn->getQueryBuilder();
266
+
267
+        $qb->delete('group_admin')
268
+            ->where($qb->expr()->eq('uid', $qb->createNamedParameter($user->getUID())))
269
+            ->execute();
270
+
271
+        return true;
272
+    }
273
+
274
+    /**
275
+     * delete all SubAdmins by $group
276
+     * @param IGroup $group
277
+     * @return boolean
278
+     */
279
+    private function post_deleteGroup($group) {
280
+        $qb = $this->dbConn->getQueryBuilder();
281
+
282
+        $qb->delete('group_admin')
283
+            ->where($qb->expr()->eq('gid', $qb->createNamedParameter($group->getGID())))
284
+            ->execute();
285
+
286
+        return true;
287
+    }
288 288
 }
Please login to merge, or discard this patch.