-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathSaveUserBehavior.php
More file actions
426 lines (384 loc) · 13.4 KB
/
SaveUserBehavior.php
File metadata and controls
426 lines (384 loc) · 13.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
<?php
/**
* SaveUser Behavior
*
* @author Noriko Arai <arai@nii.ac.jp>
* @author Shohei Nakajima <nakajimashouhei@gmail.com>
* @link http://www.netcommons.org NetCommons Project
* @license http://www.netcommons.org/license.txt NetCommons License
* @copyright Copyright 2014, NetCommons Project
*/
App::uses('ModelBehavior', 'Model');
App::uses('Space', 'Rooms.Model');
/**
* SaveUser Behavior
*
* @author Shohei Nakajima <nakajimashouhei@gmail.com>
* @package NetCommons\Users\Model\Behavior
* @SuppressWarnings(PHPMD.ExcessiveClassComplexity)
*/
class SaveUserBehavior extends ModelBehavior {
/**
* beforeValidate is called before a model is validated, you can use this callback to
* add behavior validation rules into a models validate array. Returning false
* will allow you to make the validation fail.
*
* @param Model $model Model using this behavior
* @param array $options Options passed from Model::save().
* @return mixed False or null will abort the operation. Any other result will continue.
* @see Model::save()
*/
public function beforeValidate(Model $model, $options = array()) {
if (! Configure::read('NetCommons.installed')) {
return true;
}
$model->loadModels([
'UserAttribute' => 'UserAttributes.UserAttribute',
'UserAttributesRole' => 'UserRoles.UserAttributesRole',
'UsersLanguage' => 'Users.UsersLanguage',
]);
//UserAttributesRoleデータ取得
$userAttributesRoles = $model->UserAttributesRole->getUserAttributesRole(
Current::read('User.role_key')
);
//バリデーションルールのセット
foreach ($model->userAttributeData as $userAttribute) {
$userAttributeKey = $userAttribute['UserAttribute']['key'];
if ($userAttribute['UserAttributeSetting']['data_type_key'] === DataType::DATA_TYPE_LABEL) {
continue;
}
if (! isset($userAttribute['UserAttributesRole'])) {
$userAttributesRole = Hash::extract($userAttributesRoles,
'{n}.UserAttributesRole[user_attribute_key=' . $userAttributeKey . ']');
$userAttribute['UserAttributesRole'] = $userAttributesRole[0];
}
//強制エラーのセット
$this->__setInvalidates($model, $userAttribute);
//バリデーションセット
if ($userAttribute['UserAttribute']['key'] === 'password') {
//パスワードは、呼び出し元で行う
continue;
}
// 登録時はuserIdないため、ここスルーされる。
// 更新時は、チェックボックスなど会員追加項目は、$model->data[UsersLanguage]にセットされるため、そちらを見る
$userId = Hash::get($model->data, array($model->alias, 'id'));
if ($userId &&
! isset($model->data[$model->alias][$userAttributeKey]) &&
! isset($model->data[$model->UsersLanguage->alias][0][$userAttributeKey])) {
continue;
}
$this->__setValidates($model, $userAttribute);
}
//emailの重複チェック
$emails = $this->getEmailFields($model);
$model->validate = ValidateMerge::merge($model->validate, array(
'email' => array(
'notDuplicate' => array(
'rule' => array('notDuplicate', $emails),
'message' => sprintf(
__d('net_commons', '%s is already in use. Please choose another.'),
__d('users', 'E-mail')
),
'allowEmpty' => true,
'required' => false,
),
)
));
return true;
}
/**
* Emailのフィールド取得
*
* @param Model $model ビヘイビア呼び出し元モデル
* @return array
*/
public function getEmailFields(Model $model) {
$model->loadModels([
'DataType' => 'DataTypes.DataType',
'UserAttributeSetting' => 'UserAttributes.UserAttributeSetting',
]);
$result = $model->UserAttributeSetting->find('list', array(
'recursive' => -1,
'fields' => array('id', 'user_attribute_key'),
'conditions' => array(
'data_type_key' => DataType::DATA_TYPE_EMAIL
),
));
return array_values($result);
}
/**
* invalidatesのセット
*
* @param Model $model ビヘイビア呼び出し元モデル
* @param array $userAttribute UserAttributeデータ
* @return void
* @throws BadRequestException
* @SuppressWarnings(PHPMD.CyclomaticComplexity)
*/
private function __setInvalidates(Model $model, $userAttribute) {
$model->loadModels([
'UsersLanguage' => 'Users.UsersLanguage',
]);
$userAttributeKey = $userAttribute['UserAttribute']['key'];
if ($model->UsersLanguage->hasField($userAttributeKey)) {
$modelName = $model->UsersLanguage->alias;
$pathKey = $modelName . '.{n}.' . $userAttributeKey;
} else {
$modelName = $model->alias;
$pathKey = $modelName . '.' . $userAttributeKey;
}
//他人でother_editable=falseの場合、自分でself_editable=falseは、不正エラー
$userAttributesRole = $userAttribute['UserAttributesRole'];
$userId = Hash::get($model->data, array($model->alias, 'id'));
if ($userId !== Current::read('User.id') && ! $userAttributesRole['other_editable'] ||
$userId === Current::read('User.id') && !
$userAttributesRole['self_editable'] && Hash::extract($model->data, $pathKey)) {
throw new BadRequestException(__d('net_commons', 'Bad Request'));
}
//管理者しか許可しない項目のチェック⇒不正エラーとする
if ($userAttribute['UserAttributeSetting']['only_administrator_editable'] &&
! Current::allowSystemPlugin('user_manager') && Hash::extract($model->data, $pathKey)) {
throw new BadRequestException(__d('net_commons', 'Bad Request'));
}
}
/**
* validatesのセット
*
* @param Model $model ビヘイビア呼び出し元モデル
* @param array $userAttribute UserAttributeデータ
* @return void
*/
private function __setValidates(Model $model, $userAttribute) {
$userAttributeKey = $userAttribute['UserAttribute']['key'];
$userAttributeName = $userAttribute['UserAttribute']['name'];
$validates = array();
//必須チェック
if ($userAttribute['UserAttributeSetting']['required']) {
if ($userAttribute['UserAttributeSetting']['data_type_key'] === DataType::DATA_TYPE_CHECKBOX) {
//チェックボックスタイプ
$validates['multiple'] = array(
'rule' => array('multiple', array('min' => 1)),
'message' => sprintf(__d('net_commons', 'Please input %s.'), $userAttributeName),
'required' => false
);
} else {
//それ以外
$validates['notBlank'] = array(
'rule' => array('notBlank'),
'message' => sprintf(__d('net_commons', 'Please input %s.'), $userAttributeName),
'required' => false
);
}
}
//重複チェック
if (in_array($userAttributeKey, ['username', 'handlename', 'key'], true)) {
$validates['notDuplicate'] = array(
'rule' => array('notDuplicate', array($userAttributeKey)),
'message' => sprintf(
__d('net_commons', '%s is already in use. Please choose another.'),
$userAttributeName
),
'allowEmpty' => true,
'required' => false,
);
}
//メールアドレスチェック
if ($userAttribute['UserAttributeSetting']['data_type_key'] === DataType::DATA_TYPE_EMAIL) {
$validates['email'] = array(
'rule' => array('email'),
'message' => sprintf(
__d('net_commons', 'Unauthorized pattern for %s.'), $userAttributeName
),
'allowEmpty' => true,
'required' => false,
);
}
//選択肢チェック
if ($userAttribute['UserAttributeSetting']['data_type_key'] === DataType::DATA_TYPE_CHECKBOX) {
//チェックボックスタイプ
$valuePath = '{n}.code';
$inList = array_values(
Hash::combine($userAttribute['UserAttributeChoice'], '{n}.key', $valuePath)
);
$validates['inListByCheckbox'] = array(
'rule' => array('inListByCheckbox', $inList),
'message' => __d('net_commons', 'Invalid request.'),
'allowEmpty' => true,
'required' => false,
);
} elseif (isset($userAttribute['UserAttributeChoice'])) {
//それ以外
if ($userAttributeKey === 'role_key') {
$valuePath = '{n}.key';
} else {
$valuePath = '{n}.code';
}
$inList = array_values(
Hash::combine($userAttribute['UserAttributeChoice'], '{n}.key', $valuePath)
);
$validates['inList'] = array(
'rule' => array('inList', $inList),
'message' => __d('net_commons', 'Invalid request.'),
'allowEmpty' => true,
'required' => false,
);
}
if ($model->UsersLanguage->hasField($userAttributeKey)) {
$model->UsersLanguage->validate[$userAttributeKey] = $validates;
} else {
$model->validate[$userAttributeKey] = $validates;
}
}
/**
* beforeSave is called before a model is saved. Returning false from a beforeSave callback
* will abort the save operation.
*
* @param Model $model Model using this behavior
* @param array $options Options passed from Model::save().
* @return mixed False if the operation should abort. Any other result will continue.
* @see Model::save()
*/
public function beforeSave(Model $model, $options = array()) {
//インストール時は、言語のCurrentデータをセットする
if (! Configure::read('NetCommons.installed')) {
//@var $instance Current
$instance = Current::getInstance();
$instance->setCurrentLanguage();
}
return true;
}
/**
* afterSave is called after a model is saved.
*
* @param Model $model Model using this behavior
* @param bool $created True if this save created a new record
* @param array $options Options passed from Model::save().
* @return bool
* @see Model::save()
* @throws InternalErrorException
*/
public function afterSave(Model $model, $created, $options = array()) {
//UsersLanguage登録
$usersLanguages = Hash::get($model->data, 'UsersLanguage', array());
if ($created) {
$usersLanguages = Hash::insert(
$usersLanguages, '{n}.UsersLanguage.user_id', $model->data['User']['id']
);
}
foreach ($usersLanguages as $index => $usersLanguage) {
if (! $ret = $model->UsersLanguage->save($usersLanguage, false, false)) {
throw new InternalErrorException(__d('net_commons', 'Internal Server Error'));
}
$model->data['UsersLanguage'][$index] = Hash::extract($ret, 'UsersLanguage');
}
if ($created) {
//プライベートルーム等のユーザ登録時に登録するルーム
$model->loadModels([
'Space' => 'Rooms.Space',
]);
$spapces = $model->Space->getSpaces();
foreach ($spapces as $space) {
if ($space['Space']['after_user_save_model']) {
list(, $spaceModel) = pluginSplit($space['Space']['after_user_save_model']);
$model->loadModels([
$spaceModel => $space['Space']['after_user_save_model'],
]);
if ($model->{$spaceModel} instanceof Model &&
method_exists($model->{$spaceModel}, 'afterUserSave')) {
$model->{$spaceModel}->afterUserSave($model->data);
}
}
}
//参加ルームの登録
$this->__saveDefaultRolesRoomsUser($model);
}
return true;
}
/**
* 参加ルームの登録
*
* @param Model $model Model using this behavior
* @return bool
* @throws InternalErrorException
* @SuppressWarnings(PHPMD.CyclomaticComplexity)
*/
private function __saveDefaultRolesRoomsUser(Model $model) {
$model->loadModels([
'RolesRoomsUser' => 'Rooms.RolesRoomsUser',
'Room' => 'Rooms.Room',
]);
//参加ルームの登録
if (! isset($model->data['RolesRoomsUser'])) {
//新規登録やインポート時にデフォルト参加データを取得する
$model->data['RolesRoomsUser'] = $model->Room->getDefaultRolesRoomsUser();
}
foreach ($model->data['RolesRoomsUser'] as $i => $rolesRoomsUser) {
if (! $rolesRoomsUser['roles_room_id']) {
unset($model->data['RolesRoomsUser'][$i]);
continue;
}
$rolesRoomsUser['user_id'] = $model->data['User']['id'];
$model->data['RolesRoomsUser'][$i] = $rolesRoomsUser;
}
if ($model->data['RolesRoomsUser']) {
$result = $model->RolesRoomsUser->saveMany($model->data['RolesRoomsUser']);
if (! $result) {
throw new InternalErrorException(__d('net_commons', 'Internal Server Error'));
}
}
//会員管理から登録する際、コミュニティやプライベートスペースの参加データを登録する
$publicRoomId = Space::getRoomIdRoot(Space::PUBLIC_SPACE_ID);
foreach ($model->data['RolesRoomsUser'] as $rolesRoomsUser) {
if ($rolesRoomsUser['room_id'] == $publicRoomId) {
$publicRoom = $rolesRoomsUser;
break;
}
}
if ($publicRoom) {
$spaceRolesRoomIds = $model->RolesRoomsUser->getSpaceRolesRoomsUsers();
if (! $model->RolesRoomsUser->saveSpaceRoomForRooms($publicRoom, $spaceRolesRoomIds)) {
throw new InternalErrorException(__d('net_commons', 'Internal Server Error'));
}
}
return true;
}
/**
* UserのValidateチェック
*
* @param Model $model ビヘイビア呼び出し元モデル
* @param array $data data
* @return bool True:正常、False:不正
*/
public function validateUser(Model $model, $data) {
$model->prepare();
//バリデーション
$model->set($data);
return $model->validates();
}
/**
* ユーザの登録処理
*
* @param Model $model ビヘイビア呼び出し元モデル
* @param int $userId ユーザID
* @return mixed On success Model::$data, false on failure
* @throws InternalErrorException
*/
public function updateLoginTime(Model $model, $userId) {
//トランザクションBegin
$model->begin();
try {
$update = array(
'User.previous_login' => 'User.last_login',
'User.last_login' => '\'' . date('Y-m-d H:i:s') . '\''
);
$conditions = array('User.id' => (int)$userId);
if (! $model->updateAll($update, $conditions)) {
throw new InternalErrorException(__d('net_commons', 'Internal Server Error'));
}
$model->commit();
} catch (Exception $ex) {
$model->rollback($ex);
}
return true;
}
}