PageRenderTime 50ms CodeModel.GetById 21ms RepoModel.GetById 1ms app.codeStats 0ms

/libraries/joomla/user/helper.php

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