UserStorageMacOSX.php 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832
  1. <?php
  2. Lib::loadClass('UserStorageBase');
  3. Lib::loadClass('ObjectUserLdap');
  4. Lib::loadClass('ObjectGroupLdap');
  5. Lib::loadClass('UsersLdapHelper');
  6. Lib::loadClass('LDAP');
  7. /**
  8. * Test remove user:
  9. * $ dscl /Local/Default -list /Groups GroupMembership | grep test13
  10. * ... for all groups:
  11. * $ dscl -u diradmin -p /Local/Default -delete /Groups/workgroup GroupMembership test13
  12. * $ dscl /LDAPv3/127.0.0.1 -list /Groups GroupMembership | grep test13
  13. * ... for all groups:
  14. * $ dscl -u diradmin -p /LDAPv3/127.0.0.1 -delete /Groups/workgroup GroupMembership test13
  15. * $ dscl -u diradmin -p /Local/Default -delete /Users/test13
  16. */
  17. class UserStorageMacOSX extends UserStorageBase {
  18. private $_rootUser;
  19. private $_rootPass;
  20. private $_host;
  21. private $_ldapRoot;
  22. public function __construct($rootUser, $rootPass, $host) {
  23. $this->_rootUser = $rootUser;
  24. $this->_rootPass = $rootPass;
  25. $this->_host = $host;
  26. }
  27. /**
  28. * @return ObjectUserLdap
  29. */
  30. public function getUser($userName) {
  31. $usrLdap = UsersLdapHelper::getUser($userName, true);
  32. if (empty($usrLdap[0])) return null;
  33. DBG::_('DBG_SU', true, 'usrLdap', $usrLdap[0], __CLASS__, __FUNCTION__, __LINE__);
  34. $user = $this->_buildUserFromLdap($usrLdap[0]);
  35. return $user;
  36. }
  37. private function _buildUserFromLdap($usrLdap) {
  38. $user = new ObjectUserLdap($this);
  39. $user->primaryKey = V::get('uidNumber', '', $usrLdap);
  40. $user->login = V::get('uid', '', $usrLdap);
  41. $user->password = '';
  42. $user->name = V::get('cn', '', $usrLdap);
  43. $user->email = V::get('mail', '', $usrLdap);
  44. $user->phone = V::get('telephoneNumber', '', $usrLdap);
  45. $user->homeEmail = V::get('carLicense', '', $usrLdap);
  46. $user->homePhone = V::get('homePhone', '', $usrLdap);
  47. $user->employeeType = V::get('employeeType', '', $usrLdap);
  48. return $user;
  49. }
  50. /**
  51. * @return ObjectGroupLdap $group
  52. */
  53. public function getGroup($groupID) {
  54. return $this->_getGroup($groupID, $fetchNested = true);
  55. }
  56. private function _getGroup($groupID, $fetchNested = false) {
  57. if ($groupID <= 0) return false;
  58. $group = null;
  59. $groups = UsersLdapHelper::getGroupsByID($groupID);
  60. if (count($groups) == 1) {
  61. $group = reset($groups);
  62. if(V::get('DBG_SU', 0, $_GET, 'int') > 2){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">groupLdap (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($group);echo'</pre>';}
  63. $group = $this->_buildGroupFromLdap($group, $fetchNested);
  64. if(V::get('DBG_SU', 0, $_GET, 'int') > 2){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">group (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($group);echo'</pre>';}
  65. } else if (count($groups) > 1) {
  66. if(V::get('DBG_SU', 0, $_GET, 'int') > 0){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">'."Too much groups in ldap by ID {$groupID}".' (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($groups);echo'</pre>';}
  67. trigger_error("Too much groups in ldap by ID {$groupID}", E_USER_WARNING);
  68. }
  69. return $group;
  70. }
  71. public function getParentGroups(ObjectGroup $group) {
  72. $parentGroups = array();
  73. $parentGroupsLdap = UsersLdapHelper::getParentGroupsByAppleUID($group->getLdapUID());
  74. foreach ($parentGroupsLdap as $groupLdap) {
  75. $group = $this->_buildGroupFromLdap($groupLdap);
  76. if ($group->zasobID > 0) {
  77. $parentGroups[$group->zasobID] = $group;
  78. }
  79. }
  80. return $parentGroups;
  81. }
  82. /**
  83. * @return bool
  84. */
  85. public function isDisabled($usr) {
  86. if (!$usr) throw new Exception("Błąd podczas sprawdzania statusu blokady - nie podano użytkownika!");
  87. if (null === $usr->isDisabled) {
  88. $allGroups = $this->_fetchAllUserGroups($usr->login);
  89. $usr->isDisabled = in_array('com.apple.access_disabled', $allGroups);
  90. DBG::_('DBG_SU', '>1', "usr->isDisabled(" . (($usr->isDisabled)? 'true' : 'false') . ") ", null, __CLASS__, __FUNCTION__, __LINE__);
  91. }
  92. return $usr->isDisabled;
  93. }
  94. /**
  95. * @return bool
  96. */
  97. public function setDisabled($usrLogin, $isDisabled) {
  98. // pwpolicy -a diradmin -u t1 -disableuser
  99. // pwpolicy -a diradmin -u t1 -enableuser
  100. if (empty($usrLogin) || null === $isDisabled) {
  101. return false;
  102. }
  103. $cmdDisabled = ($isDisabled)? ' -disableuser' : ' -enableuser';
  104. $cmd = "pwpolicy -a {$this->_rootUser} -p {$this->_rootPass} -u {$usrLogin} {$cmdDisabled} 2>&1 ";
  105. $cmdOut = null; $cmdRet = null;
  106. exec($cmd, $cmdOut, $cmdRet);
  107. DBG::_('DBG_SU', '>1', "cmd(" . str_replace($this->_rootPass, '***', $cmd) . ") ret({$cmdRet}) ", $cmdOut, __CLASS__, __FUNCTION__, __LINE__);
  108. if ($cmdRet !== 0) {
  109. return false;
  110. }
  111. return true;
  112. }
  113. /**
  114. * @param $usr - user object @see UserStorageBase::getUser()
  115. * $usr->employeeType: Pracownik, Kandydat, Partner, Anonymous
  116. * Pracownik - all access
  117. * Kandydat - no access
  118. * Partner - access: smb/afp, TODO: calendar?, addressbook?
  119. * Anonymous - no access
  120. */
  121. public function createUser($usr) {
  122. DBG::_('DBG_SU', '>1', 'usr', $usr, __CLASS__, __FUNCTION__, __LINE__);
  123. $cmdDsclAuth = "dscl -u {$this->_rootUser} -P {$this->_rootPass} /LDAPv3/127.0.0.1 ";
  124. $login = $this->_cleanUid($usr->login);
  125. $name = $this->_cleanText($usr->name);
  126. $type = $usr->employeeType;
  127. $email = $usr->email;
  128. $pass = $usr->password;
  129. $uniqueID = 0;
  130. // test user login and pass by searching for $uniqueID for new user
  131. $cmd = "{$cmdDsclAuth} -list /Users > /dev/null && {$cmdDsclAuth} -list /Users UniqueID|awk '{print \$2}'|sort -n|tail -1 ";
  132. $cmdOut = null; $cmdRet = null;
  133. exec($cmd, $cmdOut, $cmdRet);
  134. if ($cmdRet == 0 && !empty($cmdOut[0])) {
  135. $uniqueID = intval($cmdOut[0]);
  136. if ($uniqueID > 0) {
  137. $uniqueID += 1;
  138. }
  139. }
  140. if ($uniqueID <= 0) {
  141. throw new Exception("Error: dscl auth - check login and password in ldap config");
  142. }
  143. if (empty($name)) {
  144. $name = $login;
  145. } else {
  146. // TODO: replace bad signs str_replace($_SESSION['CONFIG']['BAD_FILE_SIGNS_LETTERS'],$_SESSION['CONFIG']['OK_FILE_SIGNS_LETTERS'],$ADM_NAME)
  147. }
  148. if (empty($pass)) {
  149. $pass = $login;
  150. }
  151. $cmds = array();
  152. //$cmds[] = "{$cmdDsclAuth} -create /Users/{$login} HomeDirectory \"<home_dir><url>afp://{$this->_host}/Users</url><path>{$login}</path></home_dir>\" ";
  153. //$cmds[] = "{$cmdDsclAuth} -create /Users/{$login} NFSHomeDirectory /Network/Servers/{$this->_host}/Users/{$login} ";
  154. $cmds[] = "{$cmdDsclAuth} -create /Users/{$login} NFSHomeDirectory /Users/{$login} ";
  155. $cmds[] = "{$cmdDsclAuth} -create /Users/{$login} UserShell /bin/bash ";// TODO: bash?
  156. $cmds[] = "{$cmdDsclAuth} -create /Users/{$login} UniqueID {$uniqueID} ";
  157. $cmds[] = "{$cmdDsclAuth} -create /Users/{$login} PrimaryGroupID 20 ";// TODO: 20 maja domyslnie inne konta?
  158. $cmds[] = "{$cmdDsclAuth} -create /Users/{$login} RealName \"{$name}\" ";
  159. if (!empty($email)) $cmds[] = "{$cmdDsclAuth} -create /Users/{$login} EMailAddress {$email} ";
  160. $cmds[] = "{$cmdDsclAuth} -passwd /Users/{$login} \"{$pass}\" ";
  161. $cmds[] = "sudo /usr/sbin/createhomedir -c -u {$login} 2>&1 ";// TODO:INSTALATOR: add to sudoers _www ALL = NOPASSWD: /usr/sbin/createhomedir
  162. foreach ($cmds as $cmd) {
  163. $cmdOut = null; $cmdRet = null;
  164. exec($cmd, $cmdOut, $cmdRet);
  165. if ($cmdRet != 0) {
  166. DBG::_('DBG_SU', '>1', "cmd failed: " . str_replace($cmdDsclAuth, "dscl __auth__ ", $cmd), $cmdOut, __CLASS__, __FUNCTION__, __LINE__);
  167. throw new Exception("Wystąpił błąd podczas tworzenia użytwkonika '{$usrLogin}' w bazie Ldap");
  168. }
  169. }
  170. }
  171. private function _getAdminLdap() {
  172. if (!$this->_ldapRoot) {
  173. $this->_ldapRoot = LDAP::getInstance();
  174. if (!$this->_ldapRoot->bindDiradmin($errorMsg)) {
  175. // $errorMsg?
  176. $this->setError(1, "cant bind as diradmin", '(' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . ')');
  177. return null;
  178. }
  179. }
  180. return $this->_ldapRoot;
  181. }
  182. public function updateUser($userName, $updateData) {
  183. if (empty($updateData)) return true;
  184. foreach ($updateData as $fldName => $val) {
  185. $val = trim($val);
  186. switch ($fldName) {
  187. case 'email':
  188. $ldap = $this->_getAdminLdap();
  189. if ($ldap) {
  190. $attr = array();
  191. $attr['mail'] = $val;
  192. $ldap->mod_replace($userName, $attr);
  193. }
  194. break;
  195. case 'name':
  196. $ldap = $this->_getAdminLdap();
  197. if ($ldap) {
  198. $attr = array();
  199. $attr['cn'] = $val;
  200. $ldap->mod_replace($userName, $attr);
  201. }
  202. break;
  203. case 'phone':
  204. $ldap = $this->_getAdminLdap();
  205. if ($ldap) {
  206. $attr = array();
  207. $attr['telephoneNumber'] = $val;
  208. $ldap->mod_replace($userName, $attr);
  209. }
  210. break;
  211. case 'employeeType':
  212. $ldap = $this->_getAdminLdap();
  213. if ($ldap) {
  214. $attr = array();
  215. $attr['employeeType'] = $val;
  216. $ldap->mod_replace($userName, $attr);
  217. }
  218. break;
  219. case 'password':
  220. if (!empty($val) && !$this->changePassword($userName, $val)) {
  221. $this->setError(1, "Nie udało się zmienić hasła dla usera '{$userName}'", '(' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . ')');
  222. }
  223. break;
  224. case 'homeEmail':
  225. $ldap = $this->_getAdminLdap();
  226. if ($ldap) {
  227. $attr = array();
  228. $attr['carLicense'] = $val;
  229. if (!$ldap->mod_replace($userName, $attr)) {
  230. if (!$ldap->mod_add($userName, $attr)) {
  231. //$this->setError(1, "TODO: update homeEmail failed " . $ldap->error(), '(' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . ')');
  232. }
  233. }
  234. }
  235. break;
  236. default:
  237. $this->setError(1, "TODO: update user {$userName} field {$fldName} to value '{$val}'", '(' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . ')');
  238. }
  239. }
  240. if ($this->hasErrors()) {
  241. $this->setError(1, "Nie udało się zaktualizować danych usera '{$userName}'", '(' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . ')');
  242. return false;
  243. }
  244. return true;
  245. }
  246. public function updateGroup($group, $updateData) {
  247. if (!$group) return false;
  248. if (empty($updateData)) return true;
  249. foreach ($updateData as $fldName => $val) {
  250. switch ($fldName) {
  251. case 'realName':
  252. $ldap = $this->_getAdminLdap();
  253. if ($ldap) {
  254. $attr = array();
  255. $attr['apple-group-realname'] = $val;
  256. $ldap->groupAttrUpdate($group->primaryKey, $attr);
  257. }
  258. break;
  259. default:
  260. $this->setError(1, "Błąd podczas aktulizacji grupy '{$group->primaryKey}' - pole '{$fldName}' watość '{$val}'", '#L' . __LINE__);
  261. }
  262. }
  263. return true;
  264. }
  265. private function _getGroupIdFromUid($groupUid) {
  266. if (empty($groupUid)) return null;
  267. if (!is_numeric(substr($groupUid, 0, 1))) return null;
  268. $tmp = str_replace(array('-', '_'), '_', $groupUid);
  269. $tmp = explode('_', $tmp);
  270. $tmp = reset($tmp);
  271. if (!empty($tmp) && is_numeric($tmp)) {
  272. return $tmp;
  273. }
  274. return null;
  275. }
  276. /**
  277. * User group list by id.
  278. *
  279. * @param bool $fetchNested - contain all groups below connected groups and group PODMIOT from above.
  280. *
  281. * @return array with group objects @see getGroup
  282. */
  283. public function getUserGroups($usrLogin, $fetchNested = false) {
  284. $groups = array();
  285. $groupsNetwork = $this->_getUserGroupsNetwork($usrLogin);
  286. $groupsLocal = $this->_getUserGroupsLocal($usrLogin);
  287. foreach ($groupsLocal as $kGroupUid => $vGroup) {
  288. $groups[$kGroupUid] = $vGroup;
  289. }
  290. foreach ($groupsNetwork as $kGroupUid => $vGroupNetwork) {
  291. if ($vGroupNetwork->primaryKey == 'workgroup') {
  292. $groups[$vGroupNetwork->primaryKey] = $vGroupNetwork;
  293. }
  294. else if ($vGroupNetwork->zasobID > 0) {
  295. $groups[$vGroupNetwork->zasobID] = $vGroupNetwork;
  296. }
  297. }
  298. DBG::_('DBG_SU', '>2', "groupsNetwork", array_keys($groupsNetwork), __CLASS__, __FUNCTION__, __LINE__);
  299. DBG::_('DBG_SU', '>2', "groupsLocal", array_keys($groupsLocal), __CLASS__, __FUNCTION__, __LINE__);
  300. return $groups;
  301. }
  302. /**
  303. * Build network group object.
  304. *
  305. * @param object $groupDB {ID, DESC} @see _getUserGroupsAll
  306. * @return object $group @see getGroup
  307. *
  308. * Example: _buildGroupFromLdap($groupLdap) => {@see getGroup}
  309. */
  310. private function _buildGroupFromLdap($groupLdap, $fetchNested = false) {
  311. $group = new ObjectGroupLdap('MacOSX');
  312. $group->primaryKey = $groupLdap->cn;
  313. $group->realName = V::get('realName', '', $groupLdap);
  314. $group->zasobID = $this->_getGroupIdFromUid($groupLdap->cn);
  315. $group->type = 'unknown';// TODO: try to fetch from name or from ldap attribute
  316. if ($groupLdap->cn == 'workgroup') $group->type = 'network';
  317. if ($fetchNested && !empty($groupLdap->nestedGroups)) {
  318. $group->nestedGroups = $this->_fetchNestedGroupsByAppleUids($groupLdap->nestedGroups);
  319. }
  320. $group->setLdapUID($groupLdap->appleUID);
  321. return $group;
  322. }
  323. public function getGroupsByUserUid($usrLogin) {
  324. $groups = array();
  325. $rawUsrLdap = UsersLdapHelper::getUser($usrLogin, true);
  326. $rawUsrLdap = (!empty($rawUsrLdap))? $rawUsrLdap[0] : null;
  327. if (!$rawUsrLdap) return $groups;
  328. $usrAppleUid = V::get('apple-generateduid', '', $rawUsrLdap);
  329. DBG::_('DBG_SU', '>0', "CleanupAppleMemberUidTodoList user apple-generateduid({$usrAppleUid})", $rawUsrLdap, __CLASS__, __FUNCTION__, __LINE__);
  330. if (empty($usrAppleUid)) return $groups;
  331. $groupsLdap = UsersLdapHelper::getUserGroupsByAppleUid($usrAppleUid, 0);
  332. foreach ($groupsLdap as $groupLdap) {
  333. $group = $this->_buildGroupFromLdap($groupLdap);
  334. if ($group->zasobID > 0) {
  335. $groups[$group->zasobID] = $group;
  336. }
  337. }
  338. return $groups;
  339. }
  340. private function _fetchNestedGroupsByAppleUids($appleUids) {
  341. $groups = array();
  342. if (!is_array($appleUids)) $appleUids = array($appleUids);
  343. $groupsLdap = UsersLdapHelper::getGroupsByAppleUids($appleUids);
  344. foreach ($groupsLdap as $vGroupLdap) {
  345. $group = $this->_buildGroupFromLdap($vGroupLdap, $fetchNested = false);
  346. if ($group && $group->zasobID > 0) {
  347. $groups[$group->zasobID] = $group;
  348. }
  349. }
  350. return $groups;
  351. }
  352. /**
  353. * @param string $usrLogin - user login
  354. * @return array of group objects @see getGroup
  355. */
  356. private function _getUserGroupsNetwork($usrLogin) {
  357. $groups = array();
  358. $groupsNetwork = UsersLdapHelper::getUserGroups($usrLogin, 0);
  359. foreach ($groupsNetwork as $vGroupNetwork) {
  360. $groups[$vGroupNetwork->cn] = $this->_buildGroupFromLdap($vGroupNetwork);
  361. }
  362. return $groups;
  363. }
  364. /**
  365. * @param string $usrLogin - user login
  366. * @return array of group objects @see getGroup
  367. */
  368. private function _getUserGroupsLocal($usrLogin) {
  369. $groups = array();
  370. $allGroups = $this->_fetchAllUserGroups($usrLogin);
  371. foreach ($allGroups as $groupName) {
  372. if ($this->_isGroupLocal($groupName)) {
  373. $groups[$groupName] = $this->_buildGroupLocal($groupName);
  374. }
  375. }
  376. DBG::_('DBG_SU', '>1', "User '{$usrLogin}' GroupsLocal:", $groups, __CLASS__, __FUNCTION__, __LINE__);
  377. return $groups;
  378. }
  379. private function _fetchAllUserGroups($usrLogin) {
  380. $groups = array();
  381. $cmd = "groups {$usrLogin}";
  382. $cmdOut = null; $cmdRet = null;
  383. exec($cmd, $cmdOut, $cmdRet);
  384. if ($cmdRet == 0 && !empty($cmdOut[0])) {
  385. $groupsCmd = explode(' ', $cmdOut[0]);
  386. foreach ($groupsCmd as $groupName) {
  387. if (!empty($groupName)) {
  388. $groups[] = $groupName;
  389. }
  390. }
  391. }
  392. DBG::_('DBG_SU', '>1', "User '{$usrLogin}' all groups:", $groups, __CLASS__, __FUNCTION__, __LINE__);
  393. return $groups;
  394. }
  395. public function getUserGroupsWithNested($usrLogin) {// TODO: NOT USED
  396. $groups = array();
  397. $groupsAll = array();
  398. $cmd = "groups {$usrLogin}";
  399. $cmdOut = null; $cmdRet = null;
  400. exec($cmd, $cmdOut, $cmdRet);
  401. if ($cmdRet == 0 && !empty($cmdOut[0])) {
  402. $pominGrupy = array('staff','everyone','netaccounts');
  403. $groupsCmd = explode(' ', $cmdOut[0]);
  404. foreach ($groupsCmd as $group) {
  405. $groupsAll[] = $group;
  406. $groupID = $this->_getGroupIdFromUid($group);
  407. if (!empty($groupID)) {
  408. $groups[$groupID] = $group;
  409. }
  410. else if ('workgroup' == $group) {
  411. $groups[$group] = $group;
  412. }
  413. else if (substr($group, 0, strlen('com.apple.access_')) == 'com.apple.access_') {
  414. $groups[$group] = $group;
  415. }
  416. }
  417. }
  418. if (V::get('DBG_SU', 0, $_GET, 'int') > 1) {
  419. echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">groupsAll (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($groupsAll);echo'</pre>';
  420. echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">groups (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($groups);echo'</pre>';
  421. }
  422. return $groups;
  423. }
  424. private function _groupNameRemoveID($groupName) {
  425. if (substr($groupName, 0, 1) == '[' && strpos($groupName, ']')) {
  426. $groupName = substr($groupName, strpos($groupName, ']') + 1);
  427. $groupName = trim($groupName);
  428. }
  429. return $groupName;
  430. }
  431. private function _generateGroupName($id, $groupName) {
  432. $groupNameShort = $groupName;
  433. $groupNameShort = $this->_groupNameRemoveID($groupNameShort);
  434. // TODO: polish chars - replace to ascii?
  435. $groupNameShort = preg_replace('/[^a-zA-Z0-9_-]+/', '_', $groupNameShort);
  436. // TODO: skrócić nazwę bo nie widać w aplikacji Server, np.
  437. // RealName: [5] Typowe_stanowisko_obs_uguj_ce_Obieg_Dokument_w_do_implementacji_po_instalacji_systemu
  438. // w apliakcji Server pokauje tylko "[5] ", tak samo w edycji
  439. return "[{$id}] {$groupNameShort}";
  440. }
  441. private function _generateGroupUid($id, $groupName) {
  442. $groupNameShort = $groupName;
  443. $groupNameShort = $this->_groupNameRemoveID($groupNameShort);
  444. $groupNameShort = str_replace(' ', '_', $groupNameShort);
  445. $groupNameShort = preg_replace('/[^a-zA-Z0-9_-]+/', '_', $groupNameShort);
  446. if (strlen($groupNameShort) > 30) {
  447. $groupNameShort = substr($groupNameShort, 0, 30);
  448. }
  449. return "{$id}_{$groupNameShort}";
  450. }
  451. /**
  452. * Create group.
  453. *
  454. * @param object $group @see getGroup
  455. * @return bool
  456. *
  457. * @require $group->zasobID - Allowed only network group based on Zasob.
  458. */
  459. public function createGroup(ObjectGroup $group) {
  460. // TEST: $ dscl /LDAPv3/127.0.0.1 -list /Groups PrimaryGroupID
  461. if ($group->zasobID <= 0) {
  462. throw new Exception("Nie udało się utworzyć grupy sieciowej '{$group->primaryKey}' '{$group->realName}' - brak numery zasobu");
  463. }
  464. $groupName = $this->_generateGroupName($group->zasobID, $group->realName);
  465. $groupUidGenerated = $this->_generateGroupUid($group->zasobID, $group->realName);
  466. /*
  467. * dseditgroup -o create -n /LDAPv3/ldap.company.com -u {$this->_rootUser} -P {$this->_rootPass} -r "Extra Group" -c "a nice comment" -k "some keyword" extragroup
  468. * The group extragroup is created from the node /LDAPv3/ldap.company.com with the realname, comment,
  469. * timetolive (instead of default of 14400 = 4 hours), and keyword atttribute values given above if the user
  470. * myusername has supplied a correct password and has write access.
  471. *
  472. * -r realname
  473. * This is a simple text string.
  474. *
  475. * -t recordtype
  476. * The type of the record to be added to or deleted from the group specified by groupname. Valid values are user, computer, group, or computergroup.
  477. *
  478. */
  479. $cmd = "dseditgroup -o create -n /LDAPv3/127.0.0.1 -u {$this->_rootUser} -P {$this->_rootPass} -r \"{$groupName}\" {$groupUidGenerated}";
  480. $cmdOut = null; $cmdRet = null;
  481. exec($cmd, $cmdOut, $cmdRet);
  482. DBG::_('DBG_SU', '>1', "create group cmd(" . str_replace($this->_rootPass, '***', $cmd) . ") ret({$cmdRet})", $cmdOut, __CLASS__, __FUNCTION__, __LINE__);
  483. if ($cmdRet !== 0) {
  484. throw new Exception("Nie udało się utworzyć grupy sieciowej '{$group->primaryKey}' '{$group->realName}'");
  485. }
  486. //$command8 = "dscl -u {$user} -P {$pass} /LDAPv3/127.0.0.1 -append /Groups/{$groupUid} GroupMembership {$ACCOUNT} ";
  487. //$command8 = "dscl -u {$user} -P {$pass} /LDAPv3/127.0.0.1 -delete /Groups/{$groupUid} GroupMembership {$ACCOUNT} ";
  488. //$command1 = "dscl -u {$user} -P {$pass} /LDAPv3/127.0.0.1 -create /Groups/{$groupUid} PrimaryGroupID {$PrimaryGroupID} ";
  489. //$command2 = "dscl -u {$user} -P {$pass} /LDAPv3/127.0.0.1 -create /Groups/{$groupUid} RealName \"{$groupName}\" ";
  490. }
  491. private function _isGroupLocal($groupUid) {
  492. $localGroups = array();
  493. $localGroups[] = 'com.apple.access_mail';
  494. $localGroups[] = 'com.apple.access_addressbook';
  495. $localGroups[] = 'com.apple.access_calendar';
  496. $localGroups[] = 'com.apple.access_smb';
  497. $localGroups[] = 'com.apple.access_afp';
  498. $localGroups[] = 'com.apple.access_vpn';
  499. $localGroups[] = 'com.apple.access_chat';
  500. //$localGroups[] = 'workgroup'; - Network Group
  501. return in_array($groupUid, $localGroups);
  502. }
  503. /**
  504. * Add local group member.
  505. *
  506. * @param string $usrLogin - user login
  507. * @param object $group - @see getGroup
  508. * @return bool
  509. *
  510. * @require sudoers dla _www
  511. *
  512. * cat /etc/sudoers |grep "'.$ADMIN_USERNAME.' ALL = NOPASSWD: /usr/bin/su" || echo "'.$ADMIN_USERNAME.' ALL = NOPASSWD: /usr/bin/su " >> /etc/sudoers;
  513. * cat /etc/sudoers |grep "'.$ADMIN_USERNAME.' ALL = NOPASSWD: /usr/bin/su"
  514. * cat /etc/sudoers |grep "_www ALL = NOPASSWD: /Applications/Server.app/Contents/ServerRoot/usr/sbin/calendarserver_manage_principals" || echo "_www ALL = NOPASSWD: /Applications/Server.app/Contents/ServerRoot/usr/sbin/calendarserver_manage_principals " >> /etc/sudoers;
  515. * cat /etc/sudoers |grep "_www ALL = NOPASSWD: /Applications/Server.app/Contents/ServerRoot/usr/sbin/calendarserver_manage_principals"';
  516. * cat /etc/sudoers |grep "_www ALL = NOPASSWD: /usr/bin/dscl" || echo "_www ALL = NOPASSWD: /usr/bin/dscl " >> /etc/sudoers;
  517. * cat /etc/sudoers |grep "_www ALL = NOPASSWD: /usr/bin/dscl";
  518. * cat /etc/sudoers |grep "_www ALL = NOPASSWD: /usr/bin/pwpolicy" || echo "_www ALL = NOPASSWD: /usr/bin/pwpolicy" >> /etc/sudoers;
  519. * cat /etc/sudoers |grep "_www ALL = NOPASSWD: /usr/bin/pwpolicy";
  520. * cat /etc/sudoers |grep "_www ALL = NOPASSWD: /usr/sbin/createhomedir" || echo "_www ALL = NOPASSWD: /usr/sbin/createhomedir" >> /etc/sudoers;
  521. * cat /etc/sudoers |grep "_www ALL = NOPASSWD: /usr/sbin/createhomedir";
  522. *
  523. * cat /etc/sudoers |grep "_www ALL = NOPASSWD: /usr/sbin/dseditgroup" || echo "_www ALL = NOPASSWD: /usr/sbin/dseditgroup" >> /etc/sudoers;
  524. * cat /etc/sudoers |grep "_www ALL = NOPASSWD: /usr/sbin/dseditgroup";
  525. */
  526. private function _addUserGroupLocal($usrLogin, $group) {
  527. if (!$group || empty($group->primaryKey) || empty($usrLogin)) return false;
  528. $groupUid = $group->primaryKey;
  529. $cmd = "sudo dscl /Local/Default -append /Groups/{$groupUid} GroupMembership {$usrLogin} ";
  530. $cmdOut = null; $cmdRet = null;
  531. exec($cmd, $cmdOut, $cmdRet);
  532. if ($cmdRet != 0) {
  533. throw new Exception("Nie udało się dodać usera '{$usrLogin}' do grupy lokalnej '{$groupUid}'");
  534. }
  535. }
  536. /**
  537. * Remove local group member.
  538. *
  539. * @param string $usrLogin - user login
  540. * @param object $group - @see getGroup
  541. * @return bool
  542. */
  543. private function _removeUserGroupLocal($usrLogin, $group) {
  544. if (!$group || empty($group->primaryKey) || empty($usrLogin)) return false;
  545. $groupUid = $group->primaryKey;
  546. //$cmd = "sudo dscl /Local/Default -delete /Groups/{$groupUid} GroupMembership {$usrLogin} 2>&1 ";
  547. //$cmd = "dseditgroup -o edit -n /Local/Default -u diradmin -p ... -d username -t user {$groupUid} ";
  548. $cmd = "sudo dseditgroup -o edit -n /Local/Default -d {$usrLogin} -t user {$groupUid} 2>&1 ";
  549. // The group extragroup from the node /LDAPv3/ldap.company.com will have the username deleted if the correct
  550. // password is presented interactively for the user myusername which also need to have write access.
  551. // -t recordtype type of the record to add or delete
  552. // -d recordname name of the record to delete
  553. $cmdOut = null; $cmdRet = null;
  554. exec($cmd, $cmdOut, $cmdRet);
  555. DBG::_('DBG_SU', '>1', "cmd({$cmd}) ret({$cmdRet})", $cmdOut, __CLASS__, __FUNCTION__, __LINE__);
  556. if ($cmdRet != 0) {
  557. throw new Exception("Nie udało się dodać usera '{$usrLogin}' z grupy lokalnej '{$groupUid}'");
  558. }
  559. }
  560. public function findGroupUidDscl($groupUid) {// not used @see findGroupUid
  561. $groupRealUid = null;
  562. $cmd = "dscl /LDAPv3/127.0.0.1 -list /Groups | grep '^{$groupUid}' ";
  563. $cmdOut = null; $cmdRet = null;
  564. exec($cmd, $cmdOut, $cmdRet);
  565. if ($cmdRet != 0) {
  566. $this->setError(1, "cmd failed - search for group by uid", '(' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . ')');
  567. return false;
  568. }
  569. if (!empty($cmdOut)) {
  570. foreach ($cmdOut as $vGroupUid) {
  571. $vGroupID = $this->_getGroupIdFromUid($vGroupUid);
  572. if (!empty($vGroupID) && $vGroupID == $groupUid) {
  573. $groupRealUid = $vGroupUid;
  574. break;
  575. }
  576. }
  577. }
  578. return $groupRealUid;
  579. }
  580. public function findGroupUidLdap($groupUid) {
  581. $groupRealUid = null;
  582. $groups = UsersLdapHelper::getGroupsByID($groupUid);
  583. if (count($groups) == 1) {
  584. $groupRealUid = reset($groups)->cn;
  585. }
  586. return $groupRealUid;
  587. }
  588. public function findGroupUid($groupUid) {
  589. return $this->findGroupUidLdap($groupUid);
  590. }
  591. /**
  592. * Add network group member.
  593. *
  594. * @param string $usrLogin - user login
  595. * @param object $group - @see getGroup
  596. * @return bool
  597. */
  598. private function _addUserGroupNetwork($usrLogin, $group) {
  599. if (!$group || empty($group->primaryKey) || empty($usrLogin)) return false;
  600. $groupUid = $group->primaryKey;
  601. $groupName = $group->realName;
  602. $groupRealUid = '';
  603. if ($group->type == 'network') {
  604. $groupRealUid = $group->primaryKey;// workgroup
  605. }
  606. else if (is_numeric($groupUid)) {
  607. $groupRealUid = $this->findGroupUid($groupUid);
  608. }
  609. if (!$groupRealUid) {
  610. if ($group->type == 'network') {
  611. throw new Exception("Brak dostępu do utworzenia grupy sieciowej '{$group->primaryKey}'");
  612. } else if ($group->type == 'local') {
  613. throw new Exception("Brak dostępu do utworzenia grupy lokalnej '{$group->primaryKey}'");
  614. }
  615. $this->createGroup($group);
  616. }
  617. $cmdDsclAuth = "dscl -u {$this->_rootUser} -P {$this->_rootPass} /LDAPv3/127.0.0.1 ";
  618. $cmd = "{$cmdDsclAuth} -append /Groups/{$groupRealUid} GroupMembership {$usrLogin} ";
  619. $cmdOut = null; $cmdRet = null;
  620. exec($cmd, $cmdOut, $cmdRet);
  621. if ($cmdRet != 0) {// TODO: may return 62 - user already in this group
  622. throw new Exception("Nie udało się dodać usera '{$usrLogin}' do grupy sieciowej '{$groupUid}'");
  623. }
  624. }
  625. /**
  626. * Remove network group member.
  627. *
  628. * @param string $usrLogin - user login
  629. * @param object $group - @see getGroup
  630. * @return bool
  631. */
  632. private function _removeUserGroupNetwork($usrLogin, $group) {
  633. if (!$group || empty($group->primaryKey) || empty($usrLogin)) return false;
  634. $groupUid = $group->primaryKey;
  635. $cmdDsclAuth = "dscl -u {$this->_rootUser} -P {$this->_rootPass} /LDAPv3/127.0.0.1 ";
  636. $cmd = "{$cmdDsclAuth} -delete /Groups/{$groupUid} GroupMembership {$usrLogin} ";
  637. $cmdOut = null; $cmdRet = null;
  638. exec($cmd, $cmdOut, $cmdRet);
  639. DBG::_('DBG_SU', '>1', "cmd({$cmd}) ret({$cmdRet})", $cmdOut, __CLASS__, __FUNCTION__, __LINE__);
  640. if ($cmdRet != 0) {
  641. throw new Exception("Nie udało się dodać usera '{$usrLogin}' z grupy sieciowej '{$groupUid}'");
  642. }
  643. }
  644. private function _removeUserUidFromGroupNetwork($usrAppleUid, $group) {
  645. if (!$group || empty($group->primaryKey) || empty($usrAppleUid)) return false;
  646. $groupUid = $group->primaryKey;
  647. $cmdDsclAuth = "dscl -u {$this->_rootUser} -P {$this->_rootPass} /LDAPv3/127.0.0.1 ";
  648. $cmd = "{$cmdDsclAuth} -delete /Groups/{$groupUid} GroupMembers {$usrAppleUid} ";
  649. $cmdOut = null; $cmdRet = null;
  650. exec($cmd, $cmdOut, $cmdRet);
  651. DBG::_('DBG_SU', '>1', "cmd({$cmd}) ret({$cmdRet})", $cmdOut, __CLASS__, __FUNCTION__, __LINE__);
  652. if ($cmdRet != 0) {
  653. throw new Exception("Nie udało się usunąć uid '{$usrAppleUid}' z grupy sieciowej '{$groupUid}'");
  654. }
  655. }
  656. /**
  657. * Add group member.
  658. *
  659. * @param string $usrLogin - user login
  660. * @param object $group - @see getGroup
  661. * @return bool
  662. */
  663. public function addUserGroup($usrLogin, $group) {
  664. // $groupUid, $groupName
  665. if ($group->type == 'local') {
  666. return $this->_addUserGroupLocal($usrLogin, $group);
  667. } else {
  668. return $this->_addUserGroupNetwork($usrLogin, $group);
  669. }
  670. }
  671. /**
  672. * Remove group member.
  673. *
  674. * @param string $usrLogin - user login
  675. * @param object $group - @see getGroup
  676. * @return bool
  677. */
  678. public function removeUserGroup($usrLogin, $group) {
  679. if ($group->type == 'local') {
  680. return $this->_removeUserGroupLocal($usrLogin, $group);
  681. } else {
  682. return $this->_removeUserGroupNetwork($usrLogin, $group);
  683. }
  684. }
  685. public function removeUserUidFromGroup($usrLogin, $group) {
  686. $rawUsrLdap = UsersLdapHelper::getUser($usrLogin, true);
  687. $rawUsrLdap = (!empty($rawUsrLdap))? $rawUsrLdap[0] : null;
  688. if (!$rawUsrLdap) throw new Exception("Cannot find user '{$usrLogin}'");
  689. $usrAppleUid = V::get('apple-generateduid', '', $rawUsrLdap);
  690. if (empty($usrAppleUid)) throw new Exception("Cannot find uid for user '{$usrLogin}'");
  691. DBG::_('DBG_SU', '>0', "CleanupAppleMemberUidTodoList user apple-generateduid({$usrAppleUid})", $group, __CLASS__, __FUNCTION__, __LINE__);
  692. if ($group->type == 'local') {
  693. //return $this->_removeUserGroupLocal($usrLogin, $group);
  694. } else {
  695. return $this->_removeUserUidFromGroupNetwork($usrAppleUid, $group);
  696. }
  697. }
  698. public function addNestedGroup($groupID, $nestedGroupID) {
  699. if ($groupID <= 0) return false;
  700. if ($nestedGroupID <= 0) return false;
  701. $group = $this->_getGroup($groupID);
  702. $groupNested = $this->_getGroup($nestedGroupID);
  703. if (!$group || !$groupNested) {
  704. return false;
  705. }
  706. $groupToAdd = $groupNested->primaryKey;
  707. $groupName = $group->primaryKey;
  708. // put a group called {$groupToAdd} into the {$groupName} group
  709. $cmd = "dseditgroup -o edit -n /LDAPv3/127.0.0.1 -u {$this->_rootUser} -P {$this->_rootPass} -a {$groupToAdd} -t group {$groupName}";
  710. $cmdOut = null; $cmdRet = null;
  711. exec($cmd, $cmdOut, $cmdRet);
  712. if ($cmdRet != 0) {
  713. DBG::_('DBG_SU', '>1', "cmd(" . str_replace($this->_rootPass, '***', $cmd) . ") ret({$cmdRet})", $cmdOut, __CLASS__, __FUNCTION__, __LINE__);
  714. $this->setError(1, "Nie udało się dodać grupy nadrzędnej '{$groupToAdd}' do grupy '{$groupName}' ", '(' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . ')');
  715. return false;
  716. }
  717. return true;
  718. }
  719. public function removeNestedGroup($groupID, $nestedGroupID) {
  720. if ($groupID <= 0) return false;
  721. if ($nestedGroupID <= 0) return false;
  722. $group = $this->_getGroup($groupID);
  723. $groupNested = $this->_getGroup($nestedGroupID);
  724. if (!$group || !$groupNested) {
  725. return false;
  726. }
  727. $groupToRemove = $groupNested->primaryKey;
  728. $groupName = $group->primaryKey;
  729. // put a group called {$groupToAdd} into the {$groupName} group
  730. $cmd = "dseditgroup -o edit -n /LDAPv3/127.0.0.1 -u {$this->_rootUser} -P {$this->_rootPass} -d {$groupToRemove} -t group {$groupName}";
  731. $cmdOut = null; $cmdRet = null;
  732. exec($cmd, $cmdOut, $cmdRet);
  733. if ($cmdRet != 0) {
  734. DBG::_('DBG_SU', '>1', "cmd(" . str_replace($this->_rootPass, '***', $cmd) . ") ret({$cmdRet})", $cmdOut, __CLASS__, __FUNCTION__, __LINE__);
  735. $this->setError(1, "Nie udało się usunąć grupy podrzędnej '{$groupToRemove}' z grupy '{$groupName}' ", '(' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . ')');
  736. return false;
  737. }
  738. return true;
  739. }
  740. public function changePassword($usrLogin, $passwd) {
  741. $cmdDsclAuth = "dscl -u {$this->_rootUser} -P {$this->_rootPass} /LDAPv3/127.0.0.1 ";
  742. $cmd = "{$cmdDsclAuth} -passwd /Users/{$usrLogin} \"{$passwd}\" ";
  743. $cmdOut = null; $cmdRet = null;
  744. exec($cmd, $cmdOut, $cmdRet);
  745. if ($cmdRet != 0) {
  746. return false;
  747. }
  748. return true;
  749. }
  750. }