UserPrivilegesFile::populateSharingPrivileges()   D
last analyzed

Complexity

Conditions 20
Paths 44

Size

Total Lines 46
Code Lines 33

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 16
CRAP Score 65.3238

Importance

Changes 0
Metric Value
eloc 33
dl 0
loc 46
ccs 16
cts 31
cp 0.5161
rs 4.1666
c 0
b 0
f 0
cc 20
nc 44
nop 5
crap 65.3238

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
namespace App;
4
5
/**
6
 * Create user privileges file class.
7
 *
8
 * @package App
9
 *
10
 * @copyright YetiForce S.A.
11
 * @license   YetiForce Public License 6.5 (licenses/LicenseEN.txt or yetiforce.com)
12
 */
13
class UserPrivilegesFile
14
{
15
	/**
16
	 * Function to recalculate the Sharing Rules for all the vtiger_users
17 5
	 * This function will recalculate all the sharing rules for all the vtiger_users in the Organization and will write them in flat vtiger_files.
18
	 *
19 5
	 * @return int
20 5
	 */
21 5
	public static function recalculateAll(): int
22 5
	{
23
		$userIds = (new Db\Query())->select(['id'])->from('vtiger_users')->where(['deleted' => 0])->column();
24 5
		foreach ($userIds as $id) {
25
			static::createUserPrivilegesfile($id);
26
			static::createUserSharingPrivilegesfile($id);
27
		}
28
		return \count($userIds);
29
	}
30
31
	/**
32 5778
	 * Creates a file with all the user, user-role,user-profile, user-groups informations.
33
	 *
34 5778
	 * @param int $userid
35 5778
	 * @returns User_Privileges_Userid file under the User_Privileges Directory
36 5778
	 */
37 5778
	public static function createUserPrivilegesfile($userid)
38 5778
	{
39 5778
		$fileUserPrivileges = ROOT_DIRECTORY . \DIRECTORY_SEPARATOR . 'user_privileges/user_privileges_' . $userid . '.php';
40 5778
		$handle = fopen($fileUserPrivileges, 'w+');
41 5778
		if ($handle) {
0 ignored issues
show
introduced by
$handle is of type resource, thus it always evaluated to false.
Loading history...
42 5778
			$newBuf = '';
43 5778
			$newBuf .= "<?php\n";
44 5778
			$userFocus = \CRMEntity::getInstance('Users');
45 5778
			$userFocus->retrieveEntityInfo($userid, 'Users');
46 5778
			$userInfo = [];
47 5778
			$userFocus->column_fields['id'] = '';
48
			$userFocus->id = $userid;
49 5778
			foreach ($userFocus->column_fields as $field => $value) {
50
				if (isset($userFocus->{$field})) {
51
					if ('currency_symbol' === $field || $field === 'imagename'|| $field === 'othereventduration') {
52
						$userInfo[$field] = $userFocus->{$field};
53 5778
					} else {
54 5776
						$userInfo[$field] = is_numeric($userFocus->{$field}) ? $userFocus->{$field} : \App\Purifier::encodeHtml($userFocus->{$field});
55 5776
					}
56
				}
57 2
			}
58 2
			if ('on' == $userFocus->is_admin) {
59 2
				$newBuf .= "\$is_admin=true;\n";
60 2
				$newBuf .= '$user_info=' . Utils::varExport($userInfo) . ";\n";
61 2
			} else {
62 2
				$newBuf .= "\$is_admin=false;\n";
63 2
				$globalPermissionArr = PrivilegeUtil::getCombinedUserGlobalPermissions($userid);
64 2
				$tabsPermissionArr = PrivilegeUtil::getCombinedUserModulesPermissions($userid);
65 2
				$actionPermissionArr = PrivilegeUtil::getCombinedUserActionsPermissions($userid);
66 2
				$userRole = PrivilegeUtil::getRoleByUsers($userid);
67
				$userRoleParent = PrivilegeUtil::getRoleDetail($userRole)['parentrole'];
68 2
				$subRoles = PrivilegeUtil::getRoleSubordinates($userRole);
69 2
				$subRoleAndUsers = [];
70 2
				foreach ($subRoles as $subRoleId) {
71 2
					$subRoleAndUsers[$subRoleId] = \App\PrivilegeUtil::getUsersNameByRole($subRoleId);
72 2
				}
73 2
				$parentRoles = PrivilegeUtil::getParentRole($userRole);
74 2
				$newBuf .= "\$current_user_roles='" . $userRole . "';\n";
75 2
				$newBuf .= "\$current_user_parent_role_seq='" . $userRoleParent . "';\n";
76 2
				$newBuf .= '$current_user_profiles=' . Utils::varExport(PrivilegeUtil::getProfilesByRole($userRole)) . ";\n";
77 2
				$newBuf .= '$profileGlobalPermission=' . Utils::varExport($globalPermissionArr) . ";\n";
78 2
				$newBuf .= '$profileTabsPermission=' . Utils::varExport($tabsPermissionArr) . ";\n";
79 2
				$newBuf .= '$profileActionPermission=' . Utils::varExport($actionPermissionArr) . ";\n";
80
				$newBuf .= '$current_user_groups=' . Utils::varExport(PrivilegeUtil::getAllGroupsByUser($userid)) . ";\n";
81 5778
				$newBuf .= '$subordinate_roles=' . Utils::varExport($subRoles) . ";\n";
82 5778
				$newBuf .= '$parent_roles=' . Utils::varExport($parentRoles) . ";\n";
83 5778
				$newBuf .= '$subordinate_roles_users=' . Utils::varExport($subRoleAndUsers) . ";\n";
84 5778
				$newBuf .= '$user_info=' . Utils::varExport($userInfo) . ";\n";
85 5778
			}
86 5778
			fwrite($handle, $newBuf);
87
			fclose($handle);
88 5778
			PrivilegeFile::createUserPrivilegesFile($userid);
89
			\Users_Privileges_Model::clearCache($userid);
90
			User::clearCache($userid);
91
			\App\Cache::resetFileCache($fileUserPrivileges);
92
		}
93
	}
94
95
	/**
96
	 * Creates a file with all the organization default sharing permissions
97
	 * and custom sharing permissins specific for the specified user.
98 5778
	 * In this file the information of the other users whose data is shared with the specified user is stored.
99
	 *
100 5778
	 * @param int $userid
101 5778
	 * @returns sharing_privileges_userid file under the user_privileges directory
102 5778
	 */
103 5778
	public static function createUserSharingPrivilegesfile($userid)
104 5778
	{
105 5778
		\vtlib\Deprecated::checkFileAccessForInclusion('user_privileges/user_privileges_' . $userid . '.php');
106 5778
		require 'user_privileges/user_privileges_' . $userid . '.php';
107 5778
		$fileUserSharingPrivileges = ROOT_DIRECTORY . \DIRECTORY_SEPARATOR . 'user_privileges/sharing_privileges_' . $userid . '.php';
108 5778
		$handle = fopen($fileUserSharingPrivileges, 'w+');
109 5776
		if ($handle) {
0 ignored issues
show
introduced by
$handle is of type resource, thus it always evaluated to false.
Loading history...
110 5776
			$newBuf = "<?php\n";
111
			$userFocus = \CRMEntity::getInstance('Users');
112 2
			$userFocus->retrieveEntityInfo($userid, 'Users');
113
			if ('on' == $userFocus->is_admin) {
114 2
				fwrite($handle, $newBuf);
115 2
				fclose($handle);
116 2
			} else {
117 2
				$sharingPrivileges = [];
118 2
				//Constructig the Default Org Share Array
119 2
				$defOrgShare = PrivilegeUtil::getAllDefaultSharingAction();
120
				$newBuf .= '$defaultOrgSharingPermission=' . Utils::varExport($defOrgShare) . ";\n";
121 2
				$sharingPrivileges['defOrgShare'] = $defOrgShare;
122 2
				$relatedModuleShare = PrivilegeUtil::getDatashareRelatedModules();
123 2
				$newBuf .= '$related_module_share=' . Utils::varExport($relatedModuleShare) . ";\n";
124 2
				$sharingPrivileges['relatedModuleShare'] = $relatedModuleShare;
125 2
				//Constructing Account Sharing Rules
126 2
				$accountSharePerArray = PrivilegeUtil::getUserModuleSharingObjects('Accounts', $userid, $defOrgShare, $current_user_roles, $parent_roles, $current_user_groups);
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $current_user_groups seems to be never defined.
Loading history...
Comprehensibility Best Practice introduced by
The variable $current_user_roles seems to be never defined.
Loading history...
Comprehensibility Best Practice introduced by
The variable $parent_roles seems to be never defined.
Loading history...
127 2
				$accountShareReadPer = $accountSharePerArray['read'];
128
				$accountShareWritePer = $accountSharePerArray['write'];
129 2
				$accountSharingruleMembers = $accountSharePerArray['sharingrules'];
130 2
				$newBuf .= "\$Accounts_share_read_permission=array('ROLE'=>" . Utils::varExport($accountShareReadPer['ROLE']) . ",'GROUP'=>" . Utils::varExport($accountShareReadPer['GROUP']) . ");\n";
131 2
				$newBuf .= "\$Accounts_share_write_permission=array('ROLE'=>" . Utils::varExport($accountShareWritePer['ROLE']) . ",'GROUP'=>" . Utils::varExport($accountShareWritePer['GROUP']) . ");\n";
132
				$sharingPrivileges['permission']['Accounts'] = ['read' => $accountShareReadPer, 'write' => $accountShareWritePer];
133 2
				//Constructing Contact Sharing Rules
134 2
				$newBuf .= "\$Contacts_share_read_permission=array('ROLE'=>" . Utils::varExport($accountShareReadPer['ROLE']) . ",'GROUP'=>" . Utils::varExport($accountShareReadPer['GROUP']) . ");\n";
135 2
				$newBuf .= "\$Contacts_share_write_permission=array('ROLE'=>" . Utils::varExport($accountShareWritePer['ROLE']) . ",'GROUP'=>" . Utils::varExport($accountShareWritePer['GROUP']) . ");\n";
136 2
				$sharingPrivileges['permission']['Contacts'] = ['read' => $accountShareReadPer, 'write' => $accountShareWritePer];
137 2
				//Constructing the Account Ticket Related Module Sharing Array
138 2
				$acctRelatedTkt = static::getRelatedModuleSharingArray('Accounts', 'HelpDesk', $accountSharingruleMembers, $accountShareReadPer, $accountShareWritePer, $defOrgShare);
139 2
				$accTktShareReadPer = $acctRelatedTkt['read'];
140 2
				$accTktShareWriteer = $acctRelatedTkt['write'];
141 2
				$newBuf .= "\$Accounts_HelpDesk_share_read_permission=array('ROLE'=>" . Utils::varExport($accTktShareReadPer['ROLE']) . ",'GROUP'=>" . Utils::varExport($accTktShareReadPer['GROUP']) . ");\n";
142 2
				$newBuf .= "\$Accounts_HelpDesk_share_write_permission=array('ROLE'=>" . Utils::varExport($accTktShareWriteer['ROLE']) . ",'GROUP'=>" . Utils::varExport($accTktShareWriteer['GROUP']) . ");\n";
143 2
				$sharingPrivileges['permission']['Accounts_HelpDesk'] = ['read' => $accTktShareReadPer, 'write' => $accTktShareWriteer];
144 2
				$customModules = Module::getSharingModuleList(['Accounts', 'Contacts']);
145 2
				foreach ($customModules as $moduleName) {
146 2
					$modSharePermArray = PrivilegeUtil::getUserModuleSharingObjects($moduleName, $userid, $defOrgShare, $current_user_roles, $parent_roles, $current_user_groups);
147 2
					$modShareReadPerm = $modSharePermArray['read'];
148 2
					$modShareWritePerm = $modSharePermArray['write'];
149 2
					$newBuf .= '$' . $moduleName . "_share_read_permission=['ROLE'=>" .
150
						Utils::varExport($modShareReadPerm['ROLE']) . ",'GROUP'=>" .
151 2
						Utils::varExport($modShareReadPerm['GROUP']) . "];\n";
152
					$newBuf .= '$' . $moduleName . "_share_write_permission=['ROLE'=>" .
153 2
						Utils::varExport($modShareWritePerm['ROLE']) . ",'GROUP'=>" .
154
						Utils::varExport($modShareWritePerm['GROUP']) . "];\n";
155 2
156 2
					$sharingPrivileges['permission'][$moduleName] = ['read' => $modShareReadPerm, 'write' => $modShareWritePerm];
157
				}
158 2
				$newBuf .= 'return ' . Utils::varExport($sharingPrivileges) . ";\n";
159 2
				// END
160 2
				fwrite($handle, $newBuf);
161
				fclose($handle);
162
				//Populating Temp Tables
163 5778
				\App\Cache::resetFileCache($fileUserSharingPrivileges);
164
				static::populateSharingtmptables($userid);
165
				User::clearCache($userid);
166
			}
167
		}
168
	}
169
170
	/**
171
	 * Gives an array which contains the information for what all roles,
172
	 * groups and user's related module data that is to be shared  for the specified parent module and shared module.
173
	 *
174
	 * @param string $par_mod
175
	 * @param string $share_mod
176
	 * @param array  $mod_sharingrule_members
177
	 * @param array  $mod_share_read_per
178 2
	 * @param array  $mod_share_write_per
179
	 * @param array  $def_org_share
180 2
	 *
181 2
	 * @return array
182 2
	 */
183 2
	public static function getRelatedModuleSharingArray($par_mod, $share_mod, $mod_sharingrule_members, $mod_share_read_per, $mod_share_write_per, $def_org_share)
184 2
	{
185 2
		$relatedModSharingPermission = [];
186 2
		$modShareReadPermission = [];
187 2
		$modShareWritePermission = [];
188 2
		$modShareReadPermission['ROLE'] = [];
189 2
		$modShareWritePermission['ROLE'] = [];
190
		$modShareReadPermission['GROUP'] = [];
191
		$modShareWritePermission['GROUP'] = [];
192
		$parModId = Module::getModuleId($par_mod);
193
		$shareModId = Module::getModuleId($share_mod);
194
		if (3 == $def_org_share[$shareModId] || 0 == $def_org_share[$shareModId]) {
195
			$roleReadPer = [];
196
			$roleWritePer = [];
197
			$grpReadPer = [];
198
			$grpWritePer = [];
199
			foreach ($mod_sharingrule_members as $sharingid => $sharingInfoArr) {
200
				$sharePermission = (new Db\Query())->select(['vtiger_datashare_relatedmodule_permission.permission'])
201
					->from('vtiger_datashare_relatedmodule_permission')
202
					->innerJoin('vtiger_datashare_relatedmodules', 'vtiger_datashare_relatedmodules.datashare_relatedmodule_id = vtiger_datashare_relatedmodule_permission.datashare_relatedmodule_id')
203
					->where([
204
						'vtiger_datashare_relatedmodule_permission.shareid' => $sharingid,
205
						'vtiger_datashare_relatedmodules.tabid' => $parModId,
206
						'vtiger_datashare_relatedmodules.relatedto_tabid' => $shareModId,
207
					])->scalar();
208
				foreach ($sharingInfoArr as $shareType => $shareEntArr) {
209
					foreach ($shareEntArr as $shareEntId) {
210
						if ('ROLE' == $shareType) {
211
							if (1 == $sharePermission) {
212
								if (3 == $def_org_share[$shareModId] && !isset($roleReadPer[$shareEntId])) {
213
									if (isset($mod_share_read_per['ROLE'][$shareEntId])) {
214
										$shareRoleUsers = $mod_share_read_per['ROLE'][$shareEntId];
215
									} elseif (isset($mod_share_write_per['ROLE'][$shareEntId])) {
216
										$shareRoleUsers = $mod_share_write_per['ROLE'][$shareEntId];
217
									} else {
218
										$shareRoleUsers = PrivilegeUtil::getUsersByRole($shareEntId);
219
									}
220
									$roleReadPer[$shareEntId] = $shareRoleUsers;
221
								}
222
								if (!isset($roleWritePer[$shareEntId])) {
223
									if (isset($mod_share_read_per['ROLE'][$shareEntId])) {
224
										$shareRoleUsers = $mod_share_read_per['ROLE'][$shareEntId];
225
									} elseif (isset($mod_share_write_per['ROLE'][$shareEntId])) {
226
										$shareRoleUsers = $mod_share_write_per['ROLE'][$shareEntId];
227
									} else {
228
										$shareRoleUsers = PrivilegeUtil::getUsersByRole($shareEntId);
229
									}
230
									$roleWritePer[$shareEntId] = $shareRoleUsers;
231
								}
232
							} elseif (0 == $sharePermission && 3 == $def_org_share[$shareModId]) {
0 ignored issues
show
Bug Best Practice introduced by
It seems like you are loosely comparing $sharePermission of type false|null|string to 0; this is ambiguous as not only 0 == 0 is true, but null == 0 is true, too. Consider using a strict comparison ===.
Loading history...
233
								if (!isset($roleReadPer[$shareEntId])) {
234
									if (isset($mod_share_read_per['ROLE'][$shareEntId])) {
235
										$shareRoleUsers = $mod_share_read_per['ROLE'][$shareEntId];
236
									} elseif (isset($mod_share_write_per['ROLE'][$shareEntId])) {
237
										$shareRoleUsers = $mod_share_write_per['ROLE'][$shareEntId];
238
									} else {
239
										$shareRoleUsers = PrivilegeUtil::getUsersByRole($shareEntId);
240
									}
241
									$roleReadPer[$shareEntId] = $shareRoleUsers;
242
								}
243
							}
244
						} elseif ('GROUP' == $shareType) {
245
							if (1 == $sharePermission) {
246
								if (3 == $def_org_share[$shareModId] && !isset($grpReadPer[$shareEntId])) {
247
									if (isset($mod_share_read_per['GROUP'][$shareEntId])) {
248
										$shareGrpUsers = $mod_share_read_per['GROUP'][$shareEntId];
249
									} elseif (isset($mod_share_write_per['GROUP'][$shareEntId])) {
250
										$shareGrpUsers = $mod_share_write_per['GROUP'][$shareEntId];
251
									} else {
252
										$usersByGroup = PrivilegeUtil::getUsersByGroup($shareEntId, true);
253
										$shareGrpUsers = $usersByGroup['users'];
254
										foreach ($usersByGroup['subGroups'] as $subgrpid => $subgrpusers) {
255
											if (!isset($grpReadPer[$subgrpid])) {
256
												$grpReadPer[$subgrpid] = $subgrpusers;
257
											}
258
										}
259
									}
260
									$grpReadPer[$shareEntId] = $shareGrpUsers;
261
								}
262
								if (!isset($grpWritePer[$shareEntId])) {
263
									if (isset($mod_share_read_per['GROUP'][$shareEntId])) {
264
										$shareGrpUsers = $mod_share_read_per['GROUP'][$shareEntId];
265
									} elseif (isset($mod_share_write_per['GROUP'][$shareEntId])) {
266
										$shareGrpUsers = $mod_share_write_per['GROUP'][$shareEntId];
267
									} else {
268
										$usersByGroup = PrivilegeUtil::getUsersByGroup($shareEntId, true);
269
										$shareGrpUsers = $usersByGroup['users'];
270
										foreach ($usersByGroup['subGroups'] as $subgrpid => $subgrpusers) {
271
											if (!isset($grpWritePer[$subgrpid])) {
272
												$grpWritePer[$subgrpid] = $subgrpusers;
273
											}
274
										}
275
									}
276
									$grpWritePer[$shareEntId] = $shareGrpUsers;
277
								}
278
							} elseif (0 == $sharePermission && 3 == $def_org_share[$shareModId]) {
0 ignored issues
show
Bug Best Practice introduced by
It seems like you are loosely comparing $sharePermission of type false|null|string to 0; this is ambiguous as not only 0 == 0 is true, but null == 0 is true, too. Consider using a strict comparison ===.
Loading history...
279
								if (!isset($grpReadPer[$shareEntId])) {
280
									if (isset($mod_share_read_per['GROUP'][$shareEntId])) {
281
										$shareGrpUsers = $mod_share_read_per['GROUP'][$shareEntId];
282
									} elseif (isset($mod_share_write_per['GROUP'][$shareEntId])) {
283
										$shareGrpUsers = $mod_share_write_per['GROUP'][$shareEntId];
284
									} else {
285
										$usersByGroup = PrivilegeUtil::getUsersByGroup($shareEntId, true);
286
										$shareGrpUsers = $usersByGroup['users'];
287
										foreach ($usersByGroup['subGroups'] as $subgrpid => $subgrpusers) {
288
											if (!isset($grpReadPer[$subgrpid])) {
289
												$grpReadPer[$subgrpid] = $subgrpusers;
290
											}
291
										}
292
									}
293
									$grpReadPer[$shareEntId] = $shareGrpUsers;
294
								}
295
							}
296
						}
297
					}
298
				}
299
			}
300 2
			$modShareReadPermission['ROLE'] = $roleReadPer;
301 2
			$modShareWritePermission['ROLE'] = $roleWritePer;
302
			$modShareReadPermission['GROUP'] = $grpReadPer;
303 2
			$modShareWritePermission['GROUP'] = $grpWritePer;
304
		}
305
		$relatedModSharingPermission['read'] = $modShareReadPermission;
306
		$relatedModSharingPermission['write'] = $modShareWritePermission;
307
308
		return $relatedModSharingPermission;
309 2
	}
310
311 2
	/** Function to populate the read/wirte Sharing permissions data of user/groups for the specified user into the database.
312 2
	 * @param int $userid
313
	 */
314 2
	public static function populateSharingtmptables($userid)
315
	{
316 2
		$dbCommand = \App\Db::getInstance()->createCommand();
317 2
		\vtlib\Deprecated::checkFileAccessForInclusion('user_privileges/sharing_privileges_' . $userid . '.php');
318 2
319
		require 'user_privileges/sharing_privileges_' . $userid . '.php';
320
		//Deleting from the existing vtiger_tables
321 2
		$tableArr = ['vtiger_tmp_read_user_sharing_per', 'vtiger_tmp_write_user_sharing_per', 'vtiger_tmp_read_group_sharing_per', 'vtiger_tmp_write_group_sharing_per', 'vtiger_tmp_read_user_rel_sharing_per', 'vtiger_tmp_write_user_rel_sharing_per', 'vtiger_tmp_read_group_rel_sharing_per', 'vtiger_tmp_write_group_rel_sharing_per'];
322 2
		foreach ($tableArr as $tableName) {
323 2
			$dbCommand->delete($tableName, ['userid' => $userid])->execute();
324 2
		}
325 2
		// Look up for modules for which sharing access is enabled.
326 2
		$modules = \vtlib\Functions::getAllModules(true, true, 0, false, 0);
327 2
		$sharingArray = array_column($modules, 'name');
328 2
		foreach ($sharingArray as $module) {
329 2
			$moduleSharingReadPermvar = $module . '_share_read_permission';
330
			$moduleSharingWritePermvar = $module . '_share_write_permission';
331
			static::populateSharingPrivileges('USER', $userid, $module, 'read', ${$moduleSharingReadPermvar});
332 2
			static::populateSharingPrivileges('USER', $userid, $module, 'write', ${$moduleSharingWritePermvar});
333 2
			static::populateSharingPrivileges('GROUP', $userid, $module, 'read', ${$moduleSharingReadPermvar});
334 2
			static::populateSharingPrivileges('GROUP', $userid, $module, 'write', ${$moduleSharingWritePermvar});
335 2
		}
336 2
		//Populating Values into the temp related sharing tables
337 2
		foreach ($related_module_share as $relTabId => $tabIdArr) {
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $related_module_share seems to be never defined.
Loading history...
338 2
			$relTabName = Module::getModuleName($relTabId);
339 2
			if (!empty($relTabName)) {
340 2
				foreach ($tabIdArr as $tabId) {
341 2
					$tabName = Module::getModuleName($tabId);
342 2
					$relmoduleSharingReadPermvar = $tabName . '_' . $relTabName . '_share_read_permission';
343
					$relmoduleSharingWritePermvar = $tabName . '_' . $relTabName . '_share_write_permission';
344
					static::populateRelatedSharingPrivileges('USER', $userid, $tabName, $relTabName, 'read', ${$relmoduleSharingReadPermvar});
345
					static::populateRelatedSharingPrivileges('USER', $userid, $tabName, $relTabName, 'write', ${$relmoduleSharingWritePermvar});
346 2
					static::populateRelatedSharingPrivileges('GROUP', $userid, $tabName, $relTabName, 'read', ${$relmoduleSharingReadPermvar});
347
					static::populateRelatedSharingPrivileges('GROUP', $userid, $tabName, $relTabName, 'write', ${$relmoduleSharingWritePermvar});
348
				}
349
			}
350
		}
351
	}
352
353
	/**
354
	 * Function to populate the read/wirte Sharing permissions data for the specified user into the database.
355
	 *
356
	 * @param string $enttype
357 2
	 * @param int    $userId
358
	 * @param string $module
359 2
	 * @param string $pertype
360 2
	 * @param bool   $varArr
361 2
	 */
362
	public static function populateSharingPrivileges($enttype, $userId, $module, $pertype, $varArr = false)
363
	{
364 2
		$tabId = Module::getModuleId($module);
365 2
		$dbCommand = \App\Db::getInstance()->createCommand();
366 2
		if (empty($varArr)) {
367 2
			return;
368 2
		}
369
		if ('USER' === $enttype) {
370 2
			if ('read' === $pertype) {
371 2
				$tableName = 'vtiger_tmp_read_user_sharing_per';
372
			} elseif ('write' === $pertype) {
373
				$tableName = 'vtiger_tmp_write_user_sharing_per';
374
			}
375
			$useArrr = [];
376
			if (!empty($varArr['ROLE'])) {
377
				foreach ($varArr['ROLE'] as $roleUsers) {
378
					foreach ($roleUsers as $sharedUserId) {
379
						if (!\in_array($sharedUserId, $useArrr) && $userId != $sharedUserId) {
380
							$dbCommand->insert($tableName, ['userid' => $userId, 'tabid' => $tabId, 'shareduserid' => $sharedUserId])->execute();
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $tableName does not seem to be defined for all execution paths leading up to this point.
Loading history...
381 2
							$useArrr[] = $sharedUserId;
382
						}
383
					}
384
				}
385
			}
386
			if (!empty($varArr['GROUP'])) {
387
				foreach ($varArr['GROUP'] as $grpUsers) {
388
					foreach ($grpUsers as $sharedUserId) {
389
						if (!\in_array($sharedUserId, $useArrr)) {
390
							$dbCommand->insert($tableName, ['userid' => $userId, 'tabid' => $tabId, 'shareduserid' => $sharedUserId])->execute();
391 2
							$useArrr[] = $sharedUserId;
392 2
						}
393 2
					}
394 2
				}
395 2
			}
396
		} elseif ('GROUP' === $enttype) {
397 2
			if ('read' === $pertype) {
398 2
				$tableName = 'vtiger_tmp_read_group_sharing_per';
399
			} elseif ('write' === $pertype) {
400
				$tableName = 'vtiger_tmp_write_group_sharing_per';
401
			}
402
			$grpArr = [];
403
			if (!empty($varArr['GROUP'])) {
404
				foreach ($varArr['GROUP'] as $groupId => $grpusers) {
405
					if (!\in_array($groupId, $grpArr)) {
406
						$dbCommand->insert($tableName, ['userid' => $userId, 'tabid' => $tabId, 'sharedgroupid' => $groupId])->execute();
407 2
						$grpArr[] = $groupId;
408
					}
409
				}
410
			}
411
		}
412
	}
413
414
	/**
415
	 * Function to populate the read/wirte Sharing permissions related module data for the specified user into the database.
416
	 *
417
	 * @param string $enttype
418
	 * @param int    $userid
419
	 * @param string $module
420 2
	 * @param string $relmodule
421
	 * @param string $pertype
422 2
	 * @param bool   $varArr
423 2
	 * @param mixed  $userId
424 2
	 */
425 2
	public static function populateRelatedSharingPrivileges($enttype, $userId, $module, $relmodule, $pertype, $varArr = false)
426
	{
427
		$dbCommand = \App\Db::getInstance()->createCommand();
428 2
		$tabId = Module::getModuleId($module);
429 2
		$relTabId = Module::getModuleId($relmodule);
430 2
		if (empty($varArr)) {
431 2
			return;
432 2
		}
433
		if ('USER' === $enttype) {
434 2
			if ('read' === $pertype) {
435 2
				$tableName = 'vtiger_tmp_read_user_rel_sharing_per';
436
			} elseif ('write' === $pertype) {
437
				$tableName = 'vtiger_tmp_write_user_rel_sharing_per';
438
			}
439
			$userArr = [];
440
			if (!empty($varArr['ROLE'])) {
441
				foreach ($varArr['ROLE'] as $roleUsers) {
442
					foreach ($roleUsers as $sharedUserId) {
443
						if (!\in_array($sharedUserId, $userArr) && $userId != $sharedUserId) {
444
							$dbCommand->insert($tableName, ['userid' => $userId, 'tabid' => $tabId, 'relatedtabid' => $relTabId, 'shareduserid' => $sharedUserId])->execute();
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $tableName does not seem to be defined for all execution paths leading up to this point.
Loading history...
445 2
							$userArr[] = $sharedUserId;
446
						}
447
					}
448
				}
449
			}
450
			if (!empty($varArr['GROUP'])) {
451
				foreach ($varArr['GROUP'] as $grpUsers) {
452
					foreach ($grpUsers as $sharedUserId) {
453
						if (!\in_array($sharedUserId, $userArr)) {
454
							$dbCommand->insert($tableName, ['userid' => $userId, 'tabid' => $tabId, 'relatedtabid' => $relTabId, 'shareduserid' => $sharedUserId])->execute();
455 2
							$userArr[] = $sharedUserId;
456 2
						}
457 2
					}
458 2
				}
459 2
			}
460
		} elseif ('GROUP' === $enttype) {
461 2
			if ('read' === $pertype) {
462 2
				$tableName = 'vtiger_tmp_read_group_rel_sharing_per';
463
			} elseif ('write' === $pertype) {
464
				$tableName = 'vtiger_tmp_write_group_rel_sharing_per';
465
			}
466
			$grpArr = [];
467
			if (!empty($varArr['GROUP'])) {
468
				foreach ($varArr['GROUP'] as $groupId => $grpUsers) {
469
					if (!\in_array($groupId, $grpArr)) {
470
						$dbCommand->insert($tableName, ['userid' => $userId, 'tabid' => $tabId, 'relatedtabid' => $relTabId, 'sharedgroupid' => $groupId])->execute();
471 2
						$grpArr[] = $groupId;
472
					}
473
				}
474
			}
475
		}
476
	}
477
478
	/**
479
	 * Reload user privileges file by multi company id.
480
	 *
481
	 * @param int $companyId
482
	 */
483
	public static function reloadByMultiCompany(int $companyId)
484
	{
485
		foreach (MultiCompany::getUsersByCompany($companyId) as $userId) {
486
			static::createUserPrivilegesfile($userId);
487
		}
488
	}
489
}
490