/libraries/joomla/user/helper.php

https://bitbucket.org/eternaware/joomus · PHP · 574 lines · 322 code · 65 blank · 187 comment · 35 complexity · b176e1d37739bd044f3dfcbd519e8ba2 MD5 · raw file

  1. <?php
  2. /**
  3. * @package Joomla.Platform
  4. * @subpackage User
  5. *
  6. * @copyright Copyright (C) 2005 - 2012 Open Source Matters, Inc. All rights reserved.
  7. * @license GNU General Public License version 2 or later; see LICENSE
  8. */
  9. defined('JPATH_PLATFORM') or die;
  10. /**
  11. * Authorisation helper class, provides static methods to perform various tasks relevant
  12. * to the Joomla user and authorisation classes
  13. *
  14. * This class has influences and some method logic from the Horde Auth package
  15. *
  16. * @package Joomla.Platform
  17. * @subpackage User
  18. * @since 11.1
  19. */
  20. abstract class JUserHelper
  21. {
  22. /**
  23. * Method to add a user to a group.
  24. *
  25. * @param integer $userId The id of the user.
  26. * @param integer $groupId The id of the group.
  27. *
  28. * @return boolean True on success
  29. *
  30. * @since 11.1
  31. * @throws RuntimeException
  32. */
  33. public static function addUserToGroup($userId, $groupId)
  34. {
  35. // Get the user object.
  36. $user = new JUser((int) $userId);
  37. // Add the user to the group if necessary.
  38. if (!in_array($groupId, $user->groups))
  39. {
  40. // Get the title of the group.
  41. $db = JFactory::getDbo();
  42. $query = $db->getQuery(true);
  43. $query->select($db->quoteName('title'));
  44. $query->from($db->quoteName('#__usergroups'));
  45. $query->where($db->quoteName('id') . ' = ' . (int) $groupId);
  46. $db->setQuery($query);
  47. $title = $db->loadResult();
  48. // If the group does not exist, return an exception.
  49. if (!$title)
  50. {
  51. throw new RuntimeException('Access Usergroup Invalid');
  52. }
  53. // Add the group data to the user object.
  54. $user->groups[$title] = $groupId;
  55. // Store the user object.
  56. $user->save();
  57. }
  58. // Set the group data for any preloaded user objects.
  59. $temp = JFactory::getUser((int) $userId);
  60. $temp->groups = $user->groups;
  61. // Set the group data for the user object in the session.
  62. $temp = JFactory::getUser();
  63. if ($temp->id == $userId)
  64. {
  65. $temp->groups = $user->groups;
  66. }
  67. return true;
  68. }
  69. /**
  70. * Method to get a list of groups a user is in.
  71. *
  72. * @param integer $userId The id of the user.
  73. *
  74. * @return array List of groups
  75. *
  76. * @since 11.1
  77. */
  78. public static function getUserGroups($userId)
  79. {
  80. // Get the user object.
  81. $user = JUser::getInstance((int) $userId);
  82. return isset($user->groups) ? $user->groups : array();
  83. }
  84. /**
  85. * Method to remove a user from a group.
  86. *
  87. * @param integer $userId The id of the user.
  88. * @param integer $groupId The id of the group.
  89. *
  90. * @return boolean True on success
  91. *
  92. * @since 11.1
  93. */
  94. public static function removeUserFromGroup($userId, $groupId)
  95. {
  96. // Get the user object.
  97. $user = JUser::getInstance((int) $userId);
  98. // Remove the user from the group if necessary.
  99. $key = array_search($groupId, $user->groups);
  100. if ($key !== false)
  101. {
  102. // Remove the user from the group.
  103. unset($user->groups[$key]);
  104. // Store the user object.
  105. $user->save();
  106. }
  107. // Set the group data for any preloaded user objects.
  108. $temp = JFactory::getUser((int) $userId);
  109. $temp->groups = $user->groups;
  110. // Set the group data for the user object in the session.
  111. $temp = JFactory::getUser();
  112. if ($temp->id == $userId)
  113. {
  114. $temp->groups = $user->groups;
  115. }
  116. return true;
  117. }
  118. /**
  119. * Method to set the groups for a user.
  120. *
  121. * @param integer $userId The id of the user.
  122. * @param array $groups An array of group ids to put the user in.
  123. *
  124. * @return boolean True on success
  125. *
  126. * @since 11.1
  127. */
  128. public static function setUserGroups($userId, $groups)
  129. {
  130. // Get the user object.
  131. $user = JUser::getInstance((int) $userId);
  132. // Set the group ids.
  133. JArrayHelper::toInteger($groups);
  134. $user->groups = $groups;
  135. // Get the titles for the user groups.
  136. $db = JFactory::getDbo();
  137. $query = $db->getQuery(true);
  138. $query->select($db->quoteName('id') . ', ' . $db->quoteName('title'));
  139. $query->from($db->quoteName('#__usergroups'));
  140. $query->where($db->quoteName('id') . ' = ' . implode(' OR ' . $db->quoteName('id') . ' = ', $user->groups));
  141. $db->setQuery($query);
  142. $results = $db->loadObjectList();
  143. // Set the titles for the user groups.
  144. for ($i = 0, $n = count($results); $i < $n; $i++)
  145. {
  146. $user->groups[$results[$i]->id] = $results[$i]->id;
  147. }
  148. // Store the user object.
  149. $user->save();
  150. // Set the group data for any preloaded user objects.
  151. $temp = JFactory::getUser((int) $userId);
  152. $temp->groups = $user->groups;
  153. // Set the group data for the user object in the session.
  154. $temp = JFactory::getUser();
  155. if ($temp->id == $userId)
  156. {
  157. $temp->groups = $user->groups;
  158. }
  159. return true;
  160. }
  161. /**
  162. * Gets the user profile information
  163. *
  164. * @param integer $userId The id of the user.
  165. *
  166. * @return object
  167. *
  168. * @since 11.1
  169. */
  170. public static function getProfile($userId = 0)
  171. {
  172. if ($userId == 0)
  173. {
  174. $user = JFactory::getUser();
  175. $userId = $user->id;
  176. }
  177. // Get the dispatcher and load the user's plugins.
  178. $dispatcher = JEventDispatcher::getInstance();
  179. JPluginHelper::importPlugin('user');
  180. $data = new JObject;
  181. $data->id = $userId;
  182. // Trigger the data preparation event.
  183. $dispatcher->trigger('onContentPrepareData', array('com_users.profile', &$data));
  184. return $data;
  185. }
  186. /**
  187. * Method to activate a user
  188. *
  189. * @param string $activation Activation string
  190. *
  191. * @return boolean True on success
  192. *
  193. * @since 11.1
  194. */
  195. public static function activateUser($activation)
  196. {
  197. // Initialize some variables.
  198. $db = JFactory::getDbo();
  199. $query = $db->getQuery(true);
  200. // Let's get the id of the user we want to activate
  201. $query->select($db->quoteName('id'));
  202. $query->from($db->quoteName('#__users'));
  203. $query->where($db->quoteName('activation') . ' = ' . $db->quote($activation));
  204. $query->where($db->quoteName('block') . ' = 1');
  205. $query->where($db->quoteName('lastvisitDate') . ' = ' . $db->quote('0000-00-00 00:00:00'));
  206. $db->setQuery($query);
  207. $id = (int) $db->loadResult();
  208. // Is it a valid user to activate?
  209. if ($id)
  210. {
  211. $user = JUser::getInstance((int) $id);
  212. $user->set('block', '0');
  213. $user->set('activation', '');
  214. // Time to take care of business.... store the user.
  215. if (!$user->save())
  216. {
  217. JLog::add($user->getError(), JLog::WARNING, 'jerror');
  218. return false;
  219. }
  220. }
  221. else
  222. {
  223. JLog::add(JText::_('JLIB_USER_ERROR_UNABLE_TO_FIND_USER'), JLog::WARNING, 'jerror');
  224. return false;
  225. }
  226. return true;
  227. }
  228. /**
  229. * Returns userid if a user exists
  230. *
  231. * @param string $username The username to search on.
  232. *
  233. * @return integer The user id or 0 if not found.
  234. *
  235. * @since 11.1
  236. */
  237. public static function getUserId($username)
  238. {
  239. // Initialise some variables
  240. $db = JFactory::getDbo();
  241. $query = $db->getQuery(true);
  242. $query->select($db->quoteName('id'));
  243. $query->from($db->quoteName('#__users'));
  244. $query->where($db->quoteName('username') . ' = ' . $db->quote($username));
  245. $db->setQuery($query, 0, 1);
  246. return $db->loadResult();
  247. }
  248. /**
  249. * Formats a password using the current encryption.
  250. *
  251. * @param string $plaintext The plaintext password to encrypt.
  252. * @param string $salt The salt to use to encrypt the password. []
  253. * If not present, a new salt will be
  254. * generated.
  255. * @param string $encryption The kind of password encryption to use.
  256. * Defaults to md5-hex.
  257. * @param boolean $show_encrypt Some password systems prepend the kind of
  258. * encryption to the crypted password ({SHA},
  259. * etc). Defaults to false.
  260. *
  261. * @return string The encrypted password.
  262. *
  263. * @since 11.1
  264. */
  265. public static function getCryptedPassword($plaintext, $salt = '', $encryption = 'md5-hex', $show_encrypt = false)
  266. {
  267. // Get the salt to use.
  268. $salt = self::getSalt($encryption, $salt, $plaintext);
  269. // Encrypt the password.
  270. switch ($encryption)
  271. {
  272. case 'plain':
  273. return $plaintext;
  274. case 'sha':
  275. $encrypted = base64_encode(mhash(MHASH_SHA1, $plaintext));
  276. return ($show_encrypt) ? '{SHA}' . $encrypted : $encrypted;
  277. case 'crypt':
  278. case 'crypt-des':
  279. case 'crypt-md5':
  280. case 'crypt-blowfish':
  281. return ($show_encrypt ? '{crypt}' : '') . crypt($plaintext, $salt);
  282. case 'md5-base64':
  283. $encrypted = base64_encode(mhash(MHASH_MD5, $plaintext));
  284. return ($show_encrypt) ? '{MD5}' . $encrypted : $encrypted;
  285. case 'ssha':
  286. $encrypted = base64_encode(mhash(MHASH_SHA1, $plaintext . $salt) . $salt);
  287. return ($show_encrypt) ? '{SSHA}' . $encrypted : $encrypted;
  288. case 'smd5':
  289. $encrypted = base64_encode(mhash(MHASH_MD5, $plaintext . $salt) . $salt);
  290. return ($show_encrypt) ? '{SMD5}' . $encrypted : $encrypted;
  291. case 'aprmd5':
  292. $length = strlen($plaintext);
  293. $context = $plaintext . '$apr1$' . $salt;
  294. $binary = self::_bin(md5($plaintext . $salt . $plaintext));
  295. for ($i = $length; $i > 0; $i -= 16)
  296. {
  297. $context .= substr($binary, 0, ($i > 16 ? 16 : $i));
  298. }
  299. for ($i = $length; $i > 0; $i >>= 1)
  300. {
  301. $context .= ($i & 1) ? chr(0) : $plaintext[0];
  302. }
  303. $binary = self::_bin(md5($context));
  304. for ($i = 0; $i < 1000; $i++)
  305. {
  306. $new = ($i & 1) ? $plaintext : substr($binary, 0, 16);
  307. if ($i % 3)
  308. {
  309. $new .= $salt;
  310. }
  311. if ($i % 7)
  312. {
  313. $new .= $plaintext;
  314. }
  315. $new .= ($i & 1) ? substr($binary, 0, 16) : $plaintext;
  316. $binary = self::_bin(md5($new));
  317. }
  318. $p = array();
  319. for ($i = 0; $i < 5; $i++)
  320. {
  321. $k = $i + 6;
  322. $j = $i + 12;
  323. if ($j == 16)
  324. {
  325. $j = 5;
  326. }
  327. $p[] = self::_toAPRMD5((ord($binary[$i]) << 16) | (ord($binary[$k]) << 8) | (ord($binary[$j])), 5);
  328. }
  329. return '$apr1$' . $salt . '$' . implode('', $p) . self::_toAPRMD5(ord($binary[11]), 3);
  330. case 'md5-hex':
  331. default:
  332. $encrypted = ($salt) ? md5($plaintext . $salt) : md5($plaintext);
  333. return ($show_encrypt) ? '{MD5}' . $encrypted : $encrypted;
  334. }
  335. }
  336. /**
  337. * Returns a salt for the appropriate kind of password encryption.
  338. * Optionally takes a seed and a plaintext password, to extract the seed
  339. * of an existing password, or for encryption types that use the plaintext
  340. * in the generation of the salt.
  341. *
  342. * @param string $encryption The kind of password encryption to use.
  343. * Defaults to md5-hex.
  344. * @param string $seed The seed to get the salt from (probably a
  345. * previously generated password). Defaults to
  346. * generating a new seed.
  347. * @param string $plaintext The plaintext password that we're generating
  348. * a salt for. Defaults to none.
  349. *
  350. * @return string The generated or extracted salt.
  351. *
  352. * @since 11.1
  353. */
  354. public static function getSalt($encryption = 'md5-hex', $seed = '', $plaintext = '')
  355. {
  356. // Encrypt the password.
  357. switch ($encryption)
  358. {
  359. case 'crypt':
  360. case 'crypt-des':
  361. if ($seed)
  362. {
  363. return substr(preg_replace('|^{crypt}|i', '', $seed), 0, 2);
  364. }
  365. else
  366. {
  367. return substr(md5(mt_rand()), 0, 2);
  368. }
  369. break;
  370. case 'crypt-md5':
  371. if ($seed)
  372. {
  373. return substr(preg_replace('|^{crypt}|i', '', $seed), 0, 12);
  374. }
  375. else
  376. {
  377. return '$1$' . substr(md5(mt_rand()), 0, 8) . '$';
  378. }
  379. break;
  380. case 'crypt-blowfish':
  381. if ($seed)
  382. {
  383. return substr(preg_replace('|^{crypt}|i', '', $seed), 0, 16);
  384. }
  385. else
  386. {
  387. return '$2$' . substr(md5(mt_rand()), 0, 12) . '$';
  388. }
  389. break;
  390. case 'ssha':
  391. if ($seed)
  392. {
  393. return substr(preg_replace('|^{SSHA}|', '', $seed), -20);
  394. }
  395. else
  396. {
  397. return mhash_keygen_s2k(MHASH_SHA1, $plaintext, substr(pack('h*', md5(mt_rand())), 0, 8), 4);
  398. }
  399. break;
  400. case 'smd5':
  401. if ($seed)
  402. {
  403. return substr(preg_replace('|^{SMD5}|', '', $seed), -16);
  404. }
  405. else
  406. {
  407. return mhash_keygen_s2k(MHASH_MD5, $plaintext, substr(pack('h*', md5(mt_rand())), 0, 8), 4);
  408. }
  409. break;
  410. case 'aprmd5': /* 64 characters that are valid for APRMD5 passwords. */
  411. $APRMD5 = './0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
  412. if ($seed)
  413. {
  414. return substr(preg_replace('/^\$apr1\$(.{8}).*/', '\\1', $seed), 0, 8);
  415. }
  416. else
  417. {
  418. $salt = '';
  419. for ($i = 0; $i < 8; $i++)
  420. {
  421. $salt .= $APRMD5{rand(0, 63)};
  422. }
  423. return $salt;
  424. }
  425. break;
  426. default:
  427. $salt = '';
  428. if ($seed)
  429. {
  430. $salt = $seed;
  431. }
  432. return $salt;
  433. break;
  434. }
  435. }
  436. /**
  437. * Generate a random password
  438. *
  439. * @param integer $length Length of the password to generate
  440. *
  441. * @return string Random Password
  442. *
  443. * @since 11.1
  444. */
  445. public static function genRandomPassword($length = 8)
  446. {
  447. $salt = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
  448. $base = strlen($salt);
  449. $makepass = '';
  450. /*
  451. * Start with a cryptographic strength random string, then convert it to
  452. * a string with the numeric base of the salt.
  453. * Shift the base conversion on each character so the character
  454. * distribution is even, and randomize the start shift so it's not
  455. * predictable.
  456. */
  457. $random = JCrypt::genRandomBytes($length + 1);
  458. $shift = ord($random[0]);
  459. for ($i = 1; $i <= $length; ++$i)
  460. {
  461. $makepass .= $salt[($shift + ord($random[$i])) % $base];
  462. $shift += ord($random[$i]);
  463. }
  464. return $makepass;
  465. }
  466. /**
  467. * Converts to allowed 64 characters for APRMD5 passwords.
  468. *
  469. * @param string $value The value to convert.
  470. * @param integer $count The number of characters to convert.
  471. *
  472. * @return string $value converted to the 64 MD5 characters.
  473. *
  474. * @since 11.1
  475. */
  476. protected static function _toAPRMD5($value, $count)
  477. {
  478. /* 64 characters that are valid for APRMD5 passwords. */
  479. $APRMD5 = './0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
  480. $aprmd5 = '';
  481. $count = abs($count);
  482. while (--$count)
  483. {
  484. $aprmd5 .= $APRMD5[$value & 0x3f];
  485. $value >>= 6;
  486. }
  487. return $aprmd5;
  488. }
  489. /**
  490. * Converts hexadecimal string to binary data.
  491. *
  492. * @param string $hex Hex data.
  493. *
  494. * @return string Binary data.
  495. *
  496. * @since 11.1
  497. */
  498. private static function _bin($hex)
  499. {
  500. $bin = '';
  501. $length = strlen($hex);
  502. for ($i = 0; $i < $length; $i += 2)
  503. {
  504. $tmp = sscanf(substr($hex, $i, 2), '%x');
  505. $bin .= chr(array_shift($tmp));
  506. }
  507. return $bin;
  508. }
  509. }