PageRenderTime 32ms CodeModel.GetById 0ms RepoModel.GetById 0ms app.codeStats 1ms

/libraries/joomla/user/helper.php

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